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.
 
 
 
 
 
 

101 line
3.2 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector 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 re
  16. from typing import Union
  17. from twisted.internet import address, task
  18. from twisted.web.client import FileBodyProducer
  19. from twisted.web.iweb import IRequest
  20. from synapse.api.errors import SynapseError
  21. class RequestTimedOutError(SynapseError):
  22. """Exception representing timeout of an outbound request"""
  23. def __init__(self, msg: str):
  24. super().__init__(504, msg)
  25. ACCESS_TOKEN_RE = re.compile(r"(\?.*access(_|%5[Ff])token=)[^&]*(.*)$")
  26. CLIENT_SECRET_RE = re.compile(r"(\?.*client(_|%5[Ff])secret=)[^&]*(.*)$")
  27. def redact_uri(uri: str) -> str:
  28. """Strips sensitive information from the uri replaces with <redacted>"""
  29. uri = ACCESS_TOKEN_RE.sub(r"\1<redacted>\3", uri)
  30. return CLIENT_SECRET_RE.sub(r"\1<redacted>\3", uri)
  31. class QuieterFileBodyProducer(FileBodyProducer):
  32. """Wrapper for FileBodyProducer that avoids CRITICAL errors when the connection drops.
  33. Workaround for https://github.com/matrix-org/synapse/issues/4003 /
  34. https://twistedmatrix.com/trac/ticket/6528
  35. """
  36. def stopProducing(self) -> None:
  37. try:
  38. FileBodyProducer.stopProducing(self)
  39. except task.TaskStopped:
  40. pass
  41. def get_request_uri(request: IRequest) -> bytes:
  42. """Return the full URI that was requested by the client"""
  43. return b"%s://%s%s" % (
  44. b"https" if request.isSecure() else b"http",
  45. _get_requested_host(request),
  46. # despite its name, "request.uri" is only the path and query-string.
  47. request.uri,
  48. )
  49. def _get_requested_host(request: IRequest) -> bytes:
  50. hostname = request.getHeader(b"host")
  51. if hostname:
  52. return hostname
  53. # no Host header, use the address/port that the request arrived on
  54. host: Union[address.IPv4Address, address.IPv6Address] = request.getHost()
  55. hostname = host.host.encode("ascii")
  56. if request.isSecure() and host.port == 443:
  57. # default port for https
  58. return hostname
  59. if not request.isSecure() and host.port == 80:
  60. # default port for http
  61. return hostname
  62. return b"%s:%i" % (
  63. hostname,
  64. host.port,
  65. )
  66. def get_request_user_agent(request: IRequest, default: str = "") -> str:
  67. """Return the last User-Agent header, or the given default."""
  68. # There could be raw utf-8 bytes in the User-Agent header.
  69. # N.B. if you don't do this, the logger explodes cryptically
  70. # with maximum recursion trying to log errors about
  71. # the charset problem.
  72. # c.f. https://github.com/matrix-org/synapse/issues/3471
  73. h = request.getHeader(b"User-Agent")
  74. return h.decode("ascii", "replace") if h else default