repository.py 14 KB

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