repository.py 13 KB

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