repository.py 11 KB

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