repository.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. from collections import namedtuple
  17. from typing import Dict, List
  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/gif", []).append(png_thumbnail)
  64. requirements.setdefault("image/png", []).append(png_thumbnail)
  65. return {
  66. media_type: tuple(thumbnails) for media_type, thumbnails in requirements.items()
  67. }
  68. class ContentRepositoryConfig(Config):
  69. section = "media"
  70. def read_config(self, config, **kwargs):
  71. # Only enable the media repo if either the media repo is enabled or the
  72. # current worker app is the media repo.
  73. if (
  74. self.enable_media_repo is False
  75. and config.get("worker_app") != "synapse.app.media_repository"
  76. ):
  77. self.can_load_media_repo = False
  78. return
  79. else:
  80. self.can_load_media_repo = True
  81. self.max_upload_size = self.parse_size(config.get("max_upload_size", "10M"))
  82. self.max_image_pixels = self.parse_size(config.get("max_image_pixels", "32M"))
  83. self.max_spider_size = self.parse_size(config.get("max_spider_size", "10M"))
  84. self.media_store_path = self.ensure_directory(
  85. config.get("media_store_path", "media_store")
  86. )
  87. backup_media_store_path = config.get("backup_media_store_path")
  88. synchronous_backup_media_store = config.get(
  89. "synchronous_backup_media_store", False
  90. )
  91. storage_providers = config.get("media_storage_providers", [])
  92. if backup_media_store_path:
  93. if storage_providers:
  94. raise ConfigError(
  95. "Cannot use both 'backup_media_store_path' and 'storage_providers'"
  96. )
  97. storage_providers = [
  98. {
  99. "module": "file_system",
  100. "store_local": True,
  101. "store_synchronous": synchronous_backup_media_store,
  102. "store_remote": True,
  103. "config": {"directory": backup_media_store_path},
  104. }
  105. ]
  106. # This is a list of config that can be used to create the storage
  107. # providers. The entries are tuples of (Class, class_config,
  108. # MediaStorageProviderConfig), where Class is the class of the provider,
  109. # the class_config the config to pass to it, and
  110. # MediaStorageProviderConfig are options for StorageProviderWrapper.
  111. #
  112. # We don't create the storage providers here as not all workers need
  113. # them to be started.
  114. self.media_storage_providers = [] # type: List[tuple]
  115. for provider_config in storage_providers:
  116. # We special case the module "file_system" so as not to need to
  117. # expose FileStorageProviderBackend
  118. if provider_config["module"] == "file_system":
  119. provider_config["module"] = (
  120. "synapse.rest.media.v1.storage_provider"
  121. ".FileStorageProviderBackend"
  122. )
  123. provider_class, parsed_config = load_module(provider_config)
  124. wrapper_config = MediaStorageProviderConfig(
  125. provider_config.get("store_local", False),
  126. provider_config.get("store_remote", False),
  127. provider_config.get("store_synchronous", False),
  128. )
  129. self.media_storage_providers.append(
  130. (provider_class, parsed_config, wrapper_config)
  131. )
  132. self.dynamic_thumbnails = config.get("dynamic_thumbnails", False)
  133. self.thumbnail_requirements = parse_thumbnail_requirements(
  134. config.get("thumbnail_sizes", DEFAULT_THUMBNAIL_SIZES)
  135. )
  136. self.url_preview_enabled = config.get("url_preview_enabled", False)
  137. if self.url_preview_enabled:
  138. try:
  139. check_requirements("url_preview")
  140. except DependencyException as e:
  141. raise ConfigError(e.message)
  142. if "url_preview_ip_range_blacklist" not in config:
  143. raise ConfigError(
  144. "For security, you must specify an explicit target IP address "
  145. "blacklist in url_preview_ip_range_blacklist for url previewing "
  146. "to work"
  147. )
  148. # netaddr is a dependency for url_preview
  149. from netaddr import IPSet
  150. self.url_preview_ip_range_blacklist = IPSet(
  151. config["url_preview_ip_range_blacklist"]
  152. )
  153. # we always blacklist '0.0.0.0' and '::', which are supposed to be
  154. # unroutable addresses.
  155. self.url_preview_ip_range_blacklist.update(["0.0.0.0", "::"])
  156. self.url_preview_ip_range_whitelist = IPSet(
  157. config.get("url_preview_ip_range_whitelist", ())
  158. )
  159. self.url_preview_url_blacklist = config.get("url_preview_url_blacklist", ())
  160. def generate_config_section(self, data_dir_path, **kwargs):
  161. media_store = os.path.join(data_dir_path, "media_store")
  162. uploads_path = os.path.join(data_dir_path, "uploads")
  163. formatted_thumbnail_sizes = "".join(
  164. THUMBNAIL_SIZE_YAML % s for s in DEFAULT_THUMBNAIL_SIZES
  165. )
  166. # strip final NL
  167. formatted_thumbnail_sizes = formatted_thumbnail_sizes[:-1]
  168. return (
  169. r"""
  170. ## Media Store ##
  171. # Enable the media store service in the Synapse master. Uncomment the
  172. # following if you are using a separate media store worker.
  173. #
  174. #enable_media_repo: false
  175. # Directory where uploaded images and attachments are stored.
  176. #
  177. media_store_path: "%(media_store)s"
  178. # Media storage providers allow media to be stored in different
  179. # locations.
  180. #
  181. #media_storage_providers:
  182. # - module: file_system
  183. # # Whether to write new local files.
  184. # store_local: false
  185. # # Whether to write new remote media
  186. # store_remote: false
  187. # # Whether to block upload requests waiting for write to this
  188. # # provider to complete
  189. # store_synchronous: false
  190. # config:
  191. # directory: /mnt/some/other/directory
  192. # The largest allowed upload size in bytes
  193. #
  194. #max_upload_size: 10M
  195. # Maximum number of pixels that will be thumbnailed
  196. #
  197. #max_image_pixels: 32M
  198. # Whether to generate new thumbnails on the fly to precisely match
  199. # the resolution requested by the client. If true then whenever
  200. # a new resolution is requested by the client the server will
  201. # generate a new thumbnail. If false the server will pick a thumbnail
  202. # from a precalculated list.
  203. #
  204. #dynamic_thumbnails: false
  205. # List of thumbnails to precalculate when an image is uploaded.
  206. #
  207. #thumbnail_sizes:
  208. %(formatted_thumbnail_sizes)s
  209. # Is the preview URL API enabled?
  210. #
  211. # 'false' by default: uncomment the following to enable it (and specify a
  212. # url_preview_ip_range_blacklist blacklist).
  213. #
  214. #url_preview_enabled: true
  215. # List of IP address CIDR ranges that the URL preview spider is denied
  216. # from accessing. There are no defaults: you must explicitly
  217. # specify a list for URL previewing to work. You should specify any
  218. # internal services in your network that you do not want synapse to try
  219. # to connect to, otherwise anyone in any Matrix room could cause your
  220. # synapse to issue arbitrary GET requests to your internal services,
  221. # causing serious security issues.
  222. #
  223. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  224. # listed here, since they correspond to unroutable addresses.)
  225. #
  226. # This must be specified if url_preview_enabled is set. It is recommended that
  227. # you uncomment the following list as a starting point.
  228. #
  229. #url_preview_ip_range_blacklist:
  230. # - '127.0.0.0/8'
  231. # - '10.0.0.0/8'
  232. # - '172.16.0.0/12'
  233. # - '192.168.0.0/16'
  234. # - '100.64.0.0/10'
  235. # - '169.254.0.0/16'
  236. # - '::1/128'
  237. # - 'fe80::/64'
  238. # - 'fc00::/7'
  239. # List of IP address CIDR ranges that the URL preview spider is allowed
  240. # to access even if they are specified in url_preview_ip_range_blacklist.
  241. # This is useful for specifying exceptions to wide-ranging blacklisted
  242. # target IP ranges - e.g. for enabling URL previews for a specific private
  243. # website only visible in your network.
  244. #
  245. #url_preview_ip_range_whitelist:
  246. # - '192.168.1.1'
  247. # Optional list of URL matches that the URL preview spider is
  248. # denied from accessing. You should use url_preview_ip_range_blacklist
  249. # in preference to this, otherwise someone could define a public DNS
  250. # entry that points to a private IP address and circumvent the blacklist.
  251. # This is more useful if you know there is an entire shape of URL that
  252. # you know that will never want synapse to try to spider.
  253. #
  254. # Each list entry is a dictionary of url component attributes as returned
  255. # by urlparse.urlsplit as applied to the absolute form of the URL. See
  256. # https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit
  257. # The values of the dictionary are treated as an filename match pattern
  258. # applied to that component of URLs, unless they start with a ^ in which
  259. # case they are treated as a regular expression match. If all the
  260. # specified component matches for a given list item succeed, the URL is
  261. # blacklisted.
  262. #
  263. #url_preview_url_blacklist:
  264. # # blacklist any URL with a username in its URI
  265. # - username: '*'
  266. #
  267. # # blacklist all *.google.com URLs
  268. # - netloc: 'google.com'
  269. # - netloc: '*.google.com'
  270. #
  271. # # blacklist all plain HTTP URLs
  272. # - scheme: 'http'
  273. #
  274. # # blacklist http(s)://www.acme.com/foo
  275. # - netloc: 'www.acme.com'
  276. # path: '/foo'
  277. #
  278. # # blacklist any URL with a literal IPv4 address
  279. # - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  280. # The largest allowed URL preview spidering size in bytes
  281. #
  282. #max_spider_size: 10M
  283. """
  284. % locals()
  285. )