httpclient.py 4.1 KB

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