httpclient.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 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. from __future__ import absolute_import
  16. import json
  17. import logging
  18. from io import BytesIO
  19. from twisted.internet import defer
  20. from twisted.web.client import FileBodyProducer, Agent, readBody
  21. from twisted.web.http_headers import Headers
  22. from sydent.http.matrixfederationagent import MatrixFederationAgent
  23. from sydent.http.federation_tls_options import ClientTLSOptionsFactory
  24. from sydent.util import json_decoder
  25. logger = logging.getLogger(__name__)
  26. class HTTPClient(object):
  27. """A base HTTP class that contains methods for making GET and POST HTTP
  28. requests.
  29. """
  30. @defer.inlineCallbacks
  31. def get_json(self, uri):
  32. """Make a GET request to an endpoint returning JSON and parse result
  33. :param uri: The URI to make a GET request to.
  34. :type uri: unicode
  35. :return: A deferred containing JSON parsed into a Python object.
  36. :rtype: twisted.internet.defer.Deferred[dict[any, any]]
  37. """
  38. logger.debug("HTTP GET %s", uri)
  39. response = yield self.agent.request(
  40. b"GET",
  41. uri.encode("utf8"),
  42. )
  43. body = yield readBody(response)
  44. try:
  45. # json.loads doesn't allow bytes in Python 3.5
  46. json_body = json_decoder.decode(body.decode("UTF-8"))
  47. except Exception as e:
  48. logger.exception("Error parsing JSON from %s", uri)
  49. raise
  50. defer.returnValue(json_body)
  51. @defer.inlineCallbacks
  52. def post_json_get_nothing(self, uri, post_json, opts):
  53. """Make a POST request to an endpoint returning JSON and parse result
  54. :param uri: The URI to make a POST request to.
  55. :type uri: unicode
  56. :param post_json: A Python object that will be converted to a JSON
  57. string and POSTed to the given URI.
  58. :type post_json: dict[any, any]
  59. :param opts: A dictionary of request options. Currently only opts.headers
  60. is supported.
  61. :type opts: dict[str,any]
  62. :return: a response from the remote server.
  63. :rtype: twisted.internet.defer.Deferred[twisted.web.iweb.IResponse]
  64. """
  65. json_bytes = json.dumps(post_json).encode("utf8")
  66. headers = opts.get('headers', Headers({
  67. b"Content-Type": [b"application/json"],
  68. }))
  69. logger.debug("HTTP POST %s -> %s", json_bytes, uri)
  70. response = yield self.agent.request(
  71. b"POST",
  72. uri.encode("utf8"),
  73. headers,
  74. bodyProducer=FileBodyProducer(BytesIO(json_bytes))
  75. )
  76. # Ensure the body object is read otherwise we'll leak HTTP connections
  77. # as per
  78. # https://twistedmatrix.com/documents/current/web/howto/client.html
  79. yield readBody(response)
  80. defer.returnValue(response)
  81. class SimpleHttpClient(HTTPClient):
  82. """A simple, no-frills HTTP client based on the class of the same name
  83. from Synapse.
  84. """
  85. def __init__(self, sydent):
  86. self.sydent = sydent
  87. # The default endpoint factory in Twisted 14.0.0 (which we require) uses the
  88. # BrowserLikePolicyForHTTPS context factory which will do regular cert validation
  89. # 'like a browser'
  90. self.agent = Agent(
  91. self.sydent.reactor,
  92. connectTimeout=15,
  93. )
  94. class FederationHttpClient(HTTPClient):
  95. """HTTP client for federation requests to homeservers. Uses a
  96. MatrixFederationAgent.
  97. """
  98. def __init__(self, sydent):
  99. self.sydent = sydent
  100. self.agent = MatrixFederationAgent(
  101. self.sydent.reactor,
  102. ClientTLSOptionsFactory(sydent.cfg),
  103. )