httpsclient.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 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. import logging
  16. import json
  17. from StringIO import StringIO
  18. from zope.interface import implementer
  19. import twisted.internet.reactor
  20. import twisted.internet.defer
  21. from twisted.internet.ssl import optionsForClientTLS
  22. from twisted.web.client import Agent, FileBodyProducer
  23. from twisted.web.iweb import IPolicyForHTTPS
  24. from twisted.web.http_headers import Headers
  25. logger = logging.getLogger(__name__)
  26. class ReplicationHttpsClient:
  27. """
  28. An HTTPS client specifically for talking replication to other Matrix Identity Servers
  29. (ie. presents our replication SSL certificate and validates peer SSL certificates as we would in the
  30. replication HTTPS server)
  31. """
  32. def __init__(self, sydent):
  33. self.sydent = sydent
  34. self.agent = None
  35. if self.sydent.sslComponents.myPrivateCertificate:
  36. # We will already have logged a warn if this is absent, so don't do it again
  37. #cert = self.sydent.sslComponents.myPrivateCertificate
  38. #self.certOptions = twisted.internet.ssl.CertificateOptions(privateKey=cert.privateKey.original,
  39. # certificate=cert.original,
  40. # trustRoot=self.sydent.sslComponents.trustRoot)
  41. self.agent = Agent(twisted.internet.reactor, SydentPolicyForHTTPS(self.sydent))
  42. def postJson(self, host, port, path, jsonObject):
  43. if not self.agent:
  44. logger.error("HTTPS post attempted but HTTPS is not configured")
  45. return
  46. headers = Headers({'Content-Type': ['application/json'], 'User-Agent': ['Sydent']})
  47. uri = "https://%s:%s%s" % (host, port, path)
  48. reqDeferred = self.agent.request('POST', uri.encode('utf8'), headers,
  49. FileBodyProducer(StringIO(json.dumps(jsonObject))))
  50. return reqDeferred
  51. @implementer(IPolicyForHTTPS)
  52. class SydentPolicyForHTTPS(object):
  53. def __init__(self, sydent):
  54. self.sydent = sydent
  55. def creatorForNetloc(self, hostname, port):
  56. return optionsForClientTLS(hostname.decode("ascii"),
  57. trustRoot=self.sydent.sslComponents.trustRoot,
  58. clientCertificate=self.sydent.sslComponents.myPrivateCertificate)