repository.py 15 KB

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