You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

367 lines
14 KiB

  1. # Copyright 2014, 2015 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from collections import namedtuple
  16. from typing import Dict, List
  17. from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST, generate_ip_set
  18. from synapse.python_dependencies import DependencyException, check_requirements
  19. from synapse.util.module_loader import load_module
  20. from ._base import Config, ConfigError
  21. DEFAULT_THUMBNAIL_SIZES = [
  22. {"width": 32, "height": 32, "method": "crop"},
  23. {"width": 96, "height": 96, "method": "crop"},
  24. {"width": 320, "height": 240, "method": "scale"},
  25. {"width": 640, "height": 480, "method": "scale"},
  26. {"width": 800, "height": 600, "method": "scale"},
  27. ]
  28. THUMBNAIL_SIZE_YAML = """\
  29. # - width: %(width)i
  30. # height: %(height)i
  31. # method: %(method)s
  32. """
  33. ThumbnailRequirement = namedtuple(
  34. "ThumbnailRequirement", ["width", "height", "method", "media_type"]
  35. )
  36. MediaStorageProviderConfig = namedtuple(
  37. "MediaStorageProviderConfig",
  38. (
  39. "store_local", # Whether to store newly uploaded local files
  40. "store_remote", # Whether to store newly downloaded remote files
  41. "store_synchronous", # Whether to wait for successful storage for local uploads
  42. ),
  43. )
  44. def parse_thumbnail_requirements(thumbnail_sizes):
  45. """Takes a list of dictionaries with "width", "height", and "method" keys
  46. and creates a map from image media types to the thumbnail size, thumbnailing
  47. method, and thumbnail media type to precalculate
  48. Args:
  49. thumbnail_sizes(list): List of dicts with "width", "height", and
  50. "method" keys
  51. Returns:
  52. Dictionary mapping from media type string to list of
  53. ThumbnailRequirement tuples.
  54. """
  55. requirements = {} # type: Dict[str, List]
  56. for size in thumbnail_sizes:
  57. width = size["width"]
  58. height = size["height"]
  59. method = size["method"]
  60. jpeg_thumbnail = ThumbnailRequirement(width, height, method, "image/jpeg")
  61. png_thumbnail = ThumbnailRequirement(width, height, method, "image/png")
  62. requirements.setdefault("image/jpeg", []).append(jpeg_thumbnail)
  63. requirements.setdefault("image/webp", []).append(jpeg_thumbnail)
  64. requirements.setdefault("image/gif", []).append(png_thumbnail)
  65. requirements.setdefault("image/png", []).append(png_thumbnail)
  66. return {
  67. media_type: tuple(thumbnails) for media_type, thumbnails in requirements.items()
  68. }
  69. class ContentRepositoryConfig(Config):
  70. section = "media"
  71. def read_config(self, config, **kwargs):
  72. # Only enable the media repo if either the media repo is enabled or the
  73. # current worker app is the media repo.
  74. if (
  75. self.enable_media_repo is False
  76. and config.get("worker_app") != "synapse.app.media_repository"
  77. ):
  78. self.can_load_media_repo = False
  79. return
  80. else:
  81. self.can_load_media_repo = True
  82. # Whether this instance should be the one to run the background jobs to
  83. # e.g clean up old URL previews.
  84. self.media_instance_running_background_jobs = config.get(
  85. "media_instance_running_background_jobs",
  86. )
  87. self.max_upload_size = self.parse_size(config.get("max_upload_size", "50M"))
  88. self.max_image_pixels = self.parse_size(config.get("max_image_pixels", "32M"))
  89. self.max_spider_size = self.parse_size(config.get("max_spider_size", "10M"))
  90. self.media_store_path = self.ensure_directory(
  91. config.get("media_store_path", "media_store")
  92. )
  93. backup_media_store_path = config.get("backup_media_store_path")
  94. synchronous_backup_media_store = config.get(
  95. "synchronous_backup_media_store", False
  96. )
  97. storage_providers = config.get("media_storage_providers", [])
  98. if backup_media_store_path:
  99. if storage_providers:
  100. raise ConfigError(
  101. "Cannot use both 'backup_media_store_path' and 'storage_providers'"
  102. )
  103. storage_providers = [
  104. {
  105. "module": "file_system",
  106. "store_local": True,
  107. "store_synchronous": synchronous_backup_media_store,
  108. "store_remote": True,
  109. "config": {"directory": backup_media_store_path},
  110. }
  111. ]
  112. # This is a list of config that can be used to create the storage
  113. # providers. The entries are tuples of (Class, class_config,
  114. # MediaStorageProviderConfig), where Class is the class of the provider,
  115. # the class_config the config to pass to it, and
  116. # MediaStorageProviderConfig are options for StorageProviderWrapper.
  117. #
  118. # We don't create the storage providers here as not all workers need
  119. # them to be started.
  120. self.media_storage_providers = [] # type: List[tuple]
  121. for i, provider_config in enumerate(storage_providers):
  122. # We special case the module "file_system" so as not to need to
  123. # expose FileStorageProviderBackend
  124. if provider_config["module"] == "file_system":
  125. provider_config["module"] = (
  126. "synapse.rest.media.v1.storage_provider"
  127. ".FileStorageProviderBackend"
  128. )
  129. provider_class, parsed_config = load_module(
  130. provider_config, ("media_storage_providers", "<item %i>" % i)
  131. )
  132. wrapper_config = MediaStorageProviderConfig(
  133. provider_config.get("store_local", False),
  134. provider_config.get("store_remote", False),
  135. provider_config.get("store_synchronous", False),
  136. )
  137. self.media_storage_providers.append(
  138. (provider_class, parsed_config, wrapper_config)
  139. )
  140. self.dynamic_thumbnails = config.get("dynamic_thumbnails", False)
  141. self.thumbnail_requirements = parse_thumbnail_requirements(
  142. config.get("thumbnail_sizes", DEFAULT_THUMBNAIL_SIZES)
  143. )
  144. self.url_preview_enabled = config.get("url_preview_enabled", False)
  145. if self.url_preview_enabled:
  146. try:
  147. check_requirements("url_preview")
  148. except DependencyException as e:
  149. raise ConfigError(
  150. e.message # noqa: B306, DependencyException.message is a property
  151. )
  152. if "url_preview_ip_range_blacklist" not in config:
  153. raise ConfigError(
  154. "For security, you must specify an explicit target IP address "
  155. "blacklist in url_preview_ip_range_blacklist for url previewing "
  156. "to work"
  157. )
  158. # we always blacklist '0.0.0.0' and '::', which are supposed to be
  159. # unroutable addresses.
  160. self.url_preview_ip_range_blacklist = generate_ip_set(
  161. config["url_preview_ip_range_blacklist"],
  162. ["0.0.0.0", "::"],
  163. config_path=("url_preview_ip_range_blacklist",),
  164. )
  165. self.url_preview_ip_range_whitelist = generate_ip_set(
  166. config.get("url_preview_ip_range_whitelist", ()),
  167. config_path=("url_preview_ip_range_whitelist",),
  168. )
  169. self.url_preview_url_blacklist = config.get("url_preview_url_blacklist", ())
  170. self.url_preview_accept_language = config.get(
  171. "url_preview_accept_language"
  172. ) or ["en"]
  173. def generate_config_section(self, data_dir_path, **kwargs):
  174. media_store = os.path.join(data_dir_path, "media_store")
  175. formatted_thumbnail_sizes = "".join(
  176. THUMBNAIL_SIZE_YAML % s for s in DEFAULT_THUMBNAIL_SIZES
  177. )
  178. # strip final NL
  179. formatted_thumbnail_sizes = formatted_thumbnail_sizes[:-1]
  180. ip_range_blacklist = "\n".join(
  181. " # - '%s'" % ip for ip in DEFAULT_IP_RANGE_BLACKLIST
  182. )
  183. return (
  184. r"""
  185. ## Media Store ##
  186. # Enable the media store service in the Synapse master. Uncomment the
  187. # following if you are using a separate media store worker.
  188. #
  189. #enable_media_repo: false
  190. # Directory where uploaded images and attachments are stored.
  191. #
  192. media_store_path: "%(media_store)s"
  193. # Media storage providers allow media to be stored in different
  194. # locations.
  195. #
  196. #media_storage_providers:
  197. # - module: file_system
  198. # # Whether to store newly uploaded local files
  199. # store_local: false
  200. # # Whether to store newly downloaded remote files
  201. # store_remote: false
  202. # # Whether to wait for successful storage for local uploads
  203. # store_synchronous: false
  204. # config:
  205. # directory: /mnt/some/other/directory
  206. # The largest allowed upload size in bytes
  207. #
  208. #max_upload_size: 50M
  209. # Maximum number of pixels that will be thumbnailed
  210. #
  211. #max_image_pixels: 32M
  212. # Whether to generate new thumbnails on the fly to precisely match
  213. # the resolution requested by the client. If true then whenever
  214. # a new resolution is requested by the client the server will
  215. # generate a new thumbnail. If false the server will pick a thumbnail
  216. # from a precalculated list.
  217. #
  218. #dynamic_thumbnails: false
  219. # List of thumbnails to precalculate when an image is uploaded.
  220. #
  221. #thumbnail_sizes:
  222. %(formatted_thumbnail_sizes)s
  223. # Is the preview URL API enabled?
  224. #
  225. # 'false' by default: uncomment the following to enable it (and specify a
  226. # url_preview_ip_range_blacklist blacklist).
  227. #
  228. #url_preview_enabled: true
  229. # List of IP address CIDR ranges that the URL preview spider is denied
  230. # from accessing. There are no defaults: you must explicitly
  231. # specify a list for URL previewing to work. You should specify any
  232. # internal services in your network that you do not want synapse to try
  233. # to connect to, otherwise anyone in any Matrix room could cause your
  234. # synapse to issue arbitrary GET requests to your internal services,
  235. # causing serious security issues.
  236. #
  237. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  238. # listed here, since they correspond to unroutable addresses.)
  239. #
  240. # This must be specified if url_preview_enabled is set. It is recommended that
  241. # you uncomment the following list as a starting point.
  242. #
  243. #url_preview_ip_range_blacklist:
  244. %(ip_range_blacklist)s
  245. # List of IP address CIDR ranges that the URL preview spider is allowed
  246. # to access even if they are specified in url_preview_ip_range_blacklist.
  247. # This is useful for specifying exceptions to wide-ranging blacklisted
  248. # target IP ranges - e.g. for enabling URL previews for a specific private
  249. # website only visible in your network.
  250. #
  251. #url_preview_ip_range_whitelist:
  252. # - '192.168.1.1'
  253. # Optional list of URL matches that the URL preview spider is
  254. # denied from accessing. You should use url_preview_ip_range_blacklist
  255. # in preference to this, otherwise someone could define a public DNS
  256. # entry that points to a private IP address and circumvent the blacklist.
  257. # This is more useful if you know there is an entire shape of URL that
  258. # you know that will never want synapse to try to spider.
  259. #
  260. # Each list entry is a dictionary of url component attributes as returned
  261. # by urlparse.urlsplit as applied to the absolute form of the URL. See
  262. # https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit
  263. # The values of the dictionary are treated as an filename match pattern
  264. # applied to that component of URLs, unless they start with a ^ in which
  265. # case they are treated as a regular expression match. If all the
  266. # specified component matches for a given list item succeed, the URL is
  267. # blacklisted.
  268. #
  269. #url_preview_url_blacklist:
  270. # # blacklist any URL with a username in its URI
  271. # - username: '*'
  272. #
  273. # # blacklist all *.google.com URLs
  274. # - netloc: 'google.com'
  275. # - netloc: '*.google.com'
  276. #
  277. # # blacklist all plain HTTP URLs
  278. # - scheme: 'http'
  279. #
  280. # # blacklist http(s)://www.acme.com/foo
  281. # - netloc: 'www.acme.com'
  282. # path: '/foo'
  283. #
  284. # # blacklist any URL with a literal IPv4 address
  285. # - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  286. # The largest allowed URL preview spidering size in bytes
  287. #
  288. #max_spider_size: 10M
  289. # A list of values for the Accept-Language HTTP header used when
  290. # downloading webpages during URL preview generation. This allows
  291. # Synapse to specify the preferred languages that URL previews should
  292. # be in when communicating with remote servers.
  293. #
  294. # Each value is a IETF language tag; a 2-3 letter identifier for a
  295. # language, optionally followed by subtags separated by '-', specifying
  296. # a country or region variant.
  297. #
  298. # Multiple values can be provided, and a weight can be added to each by
  299. # using quality value syntax (;q=). '*' translates to any language.
  300. #
  301. # Defaults to "en".
  302. #
  303. # Example:
  304. #
  305. # url_preview_accept_language:
  306. # - en-UK
  307. # - en-US;q=0.9
  308. # - fr;q=0.8
  309. # - *;q=0.7
  310. #
  311. url_preview_accept_language:
  312. # - en
  313. """
  314. % locals()
  315. )