__init__.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import re
  17. from twisted.internet import task
  18. from twisted.internet.defer import CancelledError
  19. from twisted.python import failure
  20. from twisted.web.client import FileBodyProducer
  21. from synapse.api.errors import SynapseError
  22. class RequestTimedOutError(SynapseError):
  23. """Exception representing timeout of an outbound request"""
  24. def __init__(self):
  25. super(RequestTimedOutError, self).__init__(504, "Timed out")
  26. def cancelled_to_request_timed_out_error(value, timeout):
  27. """Turns CancelledErrors into RequestTimedOutErrors.
  28. For use with async.add_timeout_to_deferred
  29. """
  30. if isinstance(value, failure.Failure):
  31. value.trap(CancelledError)
  32. raise RequestTimedOutError()
  33. return value
  34. ACCESS_TOKEN_RE = re.compile(r"(\?.*access(_|%5[Ff])token=)[^&]*(.*)$")
  35. CLIENT_SECRET_RE = re.compile(r"(\?.*client(_|%5[Ff])secret=)[^&]*(.*)$")
  36. def redact_uri(uri):
  37. """Strips sensitive information from the uri replaces with <redacted>"""
  38. uri = ACCESS_TOKEN_RE.sub(r"\1<redacted>\3", uri)
  39. return CLIENT_SECRET_RE.sub(r"\1<redacted>\3", uri)
  40. class QuieterFileBodyProducer(FileBodyProducer):
  41. """Wrapper for FileBodyProducer that avoids CRITICAL errors when the connection drops.
  42. Workaround for https://github.com/matrix-org/synapse/issues/4003 /
  43. https://twistedmatrix.com/trac/ticket/6528
  44. """
  45. def stopProducing(self):
  46. try:
  47. FileBodyProducer.stopProducing(self)
  48. except task.TaskStopped:
  49. pass