You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

480 lines
15 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
  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 logging
  16. import os
  17. import urllib
  18. from abc import ABC, abstractmethod
  19. from types import TracebackType
  20. from typing import Awaitable, Dict, Generator, List, Optional, Tuple, Type
  21. import attr
  22. from twisted.internet.interfaces import IConsumer
  23. from twisted.protocols.basic import FileSender
  24. from twisted.web.server import Request
  25. from synapse.api.errors import Codes, SynapseError, cs_error
  26. from synapse.http.server import finish_request, respond_with_json
  27. from synapse.http.site import SynapseRequest
  28. from synapse.logging.context import make_deferred_yieldable
  29. from synapse.util.stringutils import is_ascii, parse_and_validate_server_name
  30. logger = logging.getLogger(__name__)
  31. # list all text content types that will have the charset default to UTF-8 when
  32. # none is given
  33. TEXT_CONTENT_TYPES = [
  34. "text/css",
  35. "text/csv",
  36. "text/html",
  37. "text/calendar",
  38. "text/plain",
  39. "text/javascript",
  40. "application/json",
  41. "application/ld+json",
  42. "application/rtf",
  43. "image/svg+xml",
  44. "text/xml",
  45. ]
  46. def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
  47. """Parses the server name, media ID and optional file name from the request URI
  48. Also performs some rough validation on the server name.
  49. Args:
  50. request: The `Request`.
  51. Returns:
  52. A tuple containing the parsed server name, media ID and optional file name.
  53. Raises:
  54. SynapseError(404): if parsing or validation fail for any reason
  55. """
  56. try:
  57. # The type on postpath seems incorrect in Twisted 21.2.0.
  58. postpath: List[bytes] = request.postpath # type: ignore
  59. assert postpath
  60. # This allows users to append e.g. /test.png to the URL. Useful for
  61. # clients that parse the URL to see content type.
  62. server_name_bytes, media_id_bytes = postpath[:2]
  63. server_name = server_name_bytes.decode("utf-8")
  64. media_id = media_id_bytes.decode("utf8")
  65. # Validate the server name, raising if invalid
  66. parse_and_validate_server_name(server_name)
  67. file_name = None
  68. if len(postpath) > 2:
  69. try:
  70. file_name = urllib.parse.unquote(postpath[-1].decode("utf-8"))
  71. except UnicodeDecodeError:
  72. pass
  73. return server_name, media_id, file_name
  74. except Exception:
  75. raise SynapseError(
  76. 404, "Invalid media id token %r" % (request.postpath,), Codes.UNKNOWN
  77. )
  78. def respond_404(request: SynapseRequest) -> None:
  79. respond_with_json(
  80. request,
  81. 404,
  82. cs_error("Not found %r" % (request.postpath,), code=Codes.NOT_FOUND),
  83. send_cors=True,
  84. )
  85. async def respond_with_file(
  86. request: SynapseRequest,
  87. media_type: str,
  88. file_path: str,
  89. file_size: Optional[int] = None,
  90. upload_name: Optional[str] = None,
  91. ) -> None:
  92. logger.debug("Responding with %r", file_path)
  93. if os.path.isfile(file_path):
  94. if file_size is None:
  95. stat = os.stat(file_path)
  96. file_size = stat.st_size
  97. add_file_headers(request, media_type, file_size, upload_name)
  98. with open(file_path, "rb") as f:
  99. await make_deferred_yieldable(FileSender().beginFileTransfer(f, request))
  100. finish_request(request)
  101. else:
  102. respond_404(request)
  103. def add_file_headers(
  104. request: Request,
  105. media_type: str,
  106. file_size: Optional[int],
  107. upload_name: Optional[str],
  108. ) -> None:
  109. """Adds the correct response headers in preparation for responding with the
  110. media.
  111. Args:
  112. request
  113. media_type: The media/content type.
  114. file_size: Size in bytes of the media, if known.
  115. upload_name: The name of the requested file, if any.
  116. """
  117. def _quote(x: str) -> str:
  118. return urllib.parse.quote(x.encode("utf-8"))
  119. # Default to a UTF-8 charset for text content types.
  120. # ex, uses UTF-8 for 'text/css' but not 'text/css; charset=UTF-16'
  121. if media_type.lower() in TEXT_CONTENT_TYPES:
  122. content_type = media_type + "; charset=UTF-8"
  123. else:
  124. content_type = media_type
  125. request.setHeader(b"Content-Type", content_type.encode("UTF-8"))
  126. if upload_name:
  127. # RFC6266 section 4.1 [1] defines both `filename` and `filename*`.
  128. #
  129. # `filename` is defined to be a `value`, which is defined by RFC2616
  130. # section 3.6 [2] to be a `token` or a `quoted-string`, where a `token`
  131. # is (essentially) a single US-ASCII word, and a `quoted-string` is a
  132. # US-ASCII string surrounded by double-quotes, using backslash as an
  133. # escape character. Note that %-encoding is *not* permitted.
  134. #
  135. # `filename*` is defined to be an `ext-value`, which is defined in
  136. # RFC5987 section 3.2.1 [3] to be `charset "'" [ language ] "'" value-chars`,
  137. # where `value-chars` is essentially a %-encoded string in the given charset.
  138. #
  139. # [1]: https://tools.ietf.org/html/rfc6266#section-4.1
  140. # [2]: https://tools.ietf.org/html/rfc2616#section-3.6
  141. # [3]: https://tools.ietf.org/html/rfc5987#section-3.2.1
  142. # We avoid the quoted-string version of `filename`, because (a) synapse didn't
  143. # correctly interpret those as of 0.99.2 and (b) they are a bit of a pain and we
  144. # may as well just do the filename* version.
  145. if _can_encode_filename_as_token(upload_name):
  146. disposition = "inline; filename=%s" % (upload_name,)
  147. else:
  148. disposition = "inline; filename*=utf-8''%s" % (_quote(upload_name),)
  149. request.setHeader(b"Content-Disposition", disposition.encode("ascii"))
  150. # cache for at least a day.
  151. # XXX: we might want to turn this off for data we don't want to
  152. # recommend caching as it's sensitive or private - or at least
  153. # select private. don't bother setting Expires as all our
  154. # clients are smart enough to be happy with Cache-Control
  155. request.setHeader(b"Cache-Control", b"public,max-age=86400,s-maxage=86400")
  156. if file_size is not None:
  157. request.setHeader(b"Content-Length", b"%d" % (file_size,))
  158. # Tell web crawlers to not index, archive, or follow links in media. This
  159. # should help to prevent things in the media repo from showing up in web
  160. # search results.
  161. request.setHeader(b"X-Robots-Tag", "noindex, nofollow, noarchive, noimageindex")
  162. # separators as defined in RFC2616. SP and HT are handled separately.
  163. # see _can_encode_filename_as_token.
  164. _FILENAME_SEPARATOR_CHARS = {
  165. "(",
  166. ")",
  167. "<",
  168. ">",
  169. "@",
  170. ",",
  171. ";",
  172. ":",
  173. "\\",
  174. '"',
  175. "/",
  176. "[",
  177. "]",
  178. "?",
  179. "=",
  180. "{",
  181. "}",
  182. }
  183. def _can_encode_filename_as_token(x: str) -> bool:
  184. for c in x:
  185. # from RFC2616:
  186. #
  187. # token = 1*<any CHAR except CTLs or separators>
  188. #
  189. # separators = "(" | ")" | "<" | ">" | "@"
  190. # | "," | ";" | ":" | "\" | <">
  191. # | "/" | "[" | "]" | "?" | "="
  192. # | "{" | "}" | SP | HT
  193. #
  194. # CHAR = <any US-ASCII character (octets 0 - 127)>
  195. #
  196. # CTL = <any US-ASCII control character
  197. # (octets 0 - 31) and DEL (127)>
  198. #
  199. if ord(c) >= 127 or ord(c) <= 32 or c in _FILENAME_SEPARATOR_CHARS:
  200. return False
  201. return True
  202. async def respond_with_responder(
  203. request: SynapseRequest,
  204. responder: "Optional[Responder]",
  205. media_type: str,
  206. file_size: Optional[int],
  207. upload_name: Optional[str] = None,
  208. ) -> None:
  209. """Responds to the request with given responder. If responder is None then
  210. returns 404.
  211. Args:
  212. request
  213. responder
  214. media_type: The media/content type.
  215. file_size: Size in bytes of the media. If not known it should be None
  216. upload_name: The name of the requested file, if any.
  217. """
  218. if not responder:
  219. respond_404(request)
  220. return
  221. # If we have a responder we *must* use it as a context manager.
  222. with responder:
  223. if request._disconnected:
  224. logger.warning(
  225. "Not sending response to request %s, already disconnected.", request
  226. )
  227. return
  228. logger.debug("Responding to media request with responder %s", responder)
  229. add_file_headers(request, media_type, file_size, upload_name)
  230. try:
  231. await responder.write_to_consumer(request)
  232. except Exception as e:
  233. # The majority of the time this will be due to the client having gone
  234. # away. Unfortunately, Twisted simply throws a generic exception at us
  235. # in that case.
  236. logger.warning("Failed to write to consumer: %s %s", type(e), e)
  237. # Unregister the producer, if it has one, so Twisted doesn't complain
  238. if request.producer:
  239. request.unregisterProducer()
  240. finish_request(request)
  241. class Responder(ABC):
  242. """Represents a response that can be streamed to the requester.
  243. Responder is a context manager which *must* be used, so that any resources
  244. held can be cleaned up.
  245. """
  246. @abstractmethod
  247. def write_to_consumer(self, consumer: IConsumer) -> Awaitable:
  248. """Stream response into consumer
  249. Args:
  250. consumer: The consumer to stream into.
  251. Returns:
  252. Resolves once the response has finished being written
  253. """
  254. raise NotImplementedError()
  255. def __enter__(self) -> None: # noqa: B027
  256. pass
  257. def __exit__( # noqa: B027
  258. self,
  259. exc_type: Optional[Type[BaseException]],
  260. exc_val: Optional[BaseException],
  261. exc_tb: Optional[TracebackType],
  262. ) -> None:
  263. pass
  264. @attr.s(slots=True, frozen=True, auto_attribs=True)
  265. class ThumbnailInfo:
  266. """Details about a generated thumbnail."""
  267. width: int
  268. height: int
  269. method: str
  270. # Content type of thumbnail, e.g. image/png
  271. type: str
  272. # The size of the media file, in bytes.
  273. length: Optional[int] = None
  274. @attr.s(slots=True, frozen=True, auto_attribs=True)
  275. class FileInfo:
  276. """Details about a requested/uploaded file."""
  277. # The server name where the media originated from, or None if local.
  278. server_name: Optional[str]
  279. # The local ID of the file. For local files this is the same as the media_id
  280. file_id: str
  281. # If the file is for the url preview cache
  282. url_cache: bool = False
  283. # Whether the file is a thumbnail or not.
  284. thumbnail: Optional[ThumbnailInfo] = None
  285. # The below properties exist to maintain compatibility with third-party modules.
  286. @property
  287. def thumbnail_width(self) -> Optional[int]:
  288. if not self.thumbnail:
  289. return None
  290. return self.thumbnail.width
  291. @property
  292. def thumbnail_height(self) -> Optional[int]:
  293. if not self.thumbnail:
  294. return None
  295. return self.thumbnail.height
  296. @property
  297. def thumbnail_method(self) -> Optional[str]:
  298. if not self.thumbnail:
  299. return None
  300. return self.thumbnail.method
  301. @property
  302. def thumbnail_type(self) -> Optional[str]:
  303. if not self.thumbnail:
  304. return None
  305. return self.thumbnail.type
  306. @property
  307. def thumbnail_length(self) -> Optional[int]:
  308. if not self.thumbnail:
  309. return None
  310. return self.thumbnail.length
  311. def get_filename_from_headers(headers: Dict[bytes, List[bytes]]) -> Optional[str]:
  312. """
  313. Get the filename of the downloaded file by inspecting the
  314. Content-Disposition HTTP header.
  315. Args:
  316. headers: The HTTP request headers.
  317. Returns:
  318. The filename, or None.
  319. """
  320. content_disposition = headers.get(b"Content-Disposition", [b""])
  321. # No header, bail out.
  322. if not content_disposition[0]:
  323. return None
  324. _, params = _parse_header(content_disposition[0])
  325. upload_name = None
  326. # First check if there is a valid UTF-8 filename
  327. upload_name_utf8 = params.get(b"filename*", None)
  328. if upload_name_utf8:
  329. if upload_name_utf8.lower().startswith(b"utf-8''"):
  330. upload_name_utf8 = upload_name_utf8[7:]
  331. # We have a filename*= section. This MUST be ASCII, and any UTF-8
  332. # bytes are %-quoted.
  333. try:
  334. # Once it is decoded, we can then unquote the %-encoded
  335. # parts strictly into a unicode string.
  336. upload_name = urllib.parse.unquote(
  337. upload_name_utf8.decode("ascii"), errors="strict"
  338. )
  339. except UnicodeDecodeError:
  340. # Incorrect UTF-8.
  341. pass
  342. # If there isn't check for an ascii name.
  343. if not upload_name:
  344. upload_name_ascii = params.get(b"filename", None)
  345. if upload_name_ascii and is_ascii(upload_name_ascii):
  346. upload_name = upload_name_ascii.decode("ascii")
  347. # This may be None here, indicating we did not find a matching name.
  348. return upload_name
  349. def _parse_header(line: bytes) -> Tuple[bytes, Dict[bytes, bytes]]:
  350. """Parse a Content-type like header.
  351. Cargo-culted from `cgi`, but works on bytes rather than strings.
  352. Args:
  353. line: header to be parsed
  354. Returns:
  355. The main content-type, followed by the parameter dictionary
  356. """
  357. parts = _parseparam(b";" + line)
  358. key = next(parts)
  359. pdict = {}
  360. for p in parts:
  361. i = p.find(b"=")
  362. if i >= 0:
  363. name = p[:i].strip().lower()
  364. value = p[i + 1 :].strip()
  365. # strip double-quotes
  366. if len(value) >= 2 and value[0:1] == value[-1:] == b'"':
  367. value = value[1:-1]
  368. value = value.replace(b"\\\\", b"\\").replace(b'\\"', b'"')
  369. pdict[name] = value
  370. return key, pdict
  371. def _parseparam(s: bytes) -> Generator[bytes, None, None]:
  372. """Generator which splits the input on ;, respecting double-quoted sequences
  373. Cargo-culted from `cgi`, but works on bytes rather than strings.
  374. Args:
  375. s: header to be parsed
  376. Returns:
  377. The split input
  378. """
  379. while s[:1] == b";":
  380. s = s[1:]
  381. # look for the next ;
  382. end = s.find(b";")
  383. # if there is an odd number of " marks between here and the next ;, skip to the
  384. # next ; instead
  385. while end > 0 and (s.count(b'"', 0, end) - s.count(b'\\"', 0, end)) % 2:
  386. end = s.find(b";", end + 1)
  387. if end < 0:
  388. end = len(s)
  389. f = s[:end]
  390. yield f.strip()
  391. s = s[end:]