connectproxyclient.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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. from zope.interface import implementer
  17. from twisted.internet import defer, protocol
  18. from twisted.internet.error import ConnectError
  19. from twisted.internet.interfaces import IStreamClientEndpoint
  20. from twisted.internet.protocol import connectionDone
  21. from twisted.web import http
  22. logger = logging.getLogger(__name__)
  23. class ProxyConnectError(ConnectError):
  24. pass
  25. @implementer(IStreamClientEndpoint)
  26. class HTTPConnectProxyEndpoint(object):
  27. """An Endpoint implementation which will send a CONNECT request to an http proxy
  28. Wraps an existing HostnameEndpoint for the proxy.
  29. When we get the connect() request from the connection pool (via the TLS wrapper),
  30. we'll first connect to the proxy endpoint with a ProtocolFactory which will make the
  31. CONNECT request. Once that completes, we invoke the protocolFactory which was passed
  32. in.
  33. Args:
  34. reactor: the Twisted reactor to use for the connection
  35. proxy_endpoint (IStreamClientEndpoint): the endpoint to use to connect to the
  36. proxy
  37. host (bytes): hostname that we want to CONNECT to
  38. port (int): port that we want to connect to
  39. """
  40. def __init__(self, reactor, proxy_endpoint, host, port):
  41. self._reactor = reactor
  42. self._proxy_endpoint = proxy_endpoint
  43. self._host = host
  44. self._port = port
  45. def __repr__(self):
  46. return "<HTTPConnectProxyEndpoint %s>" % (self._proxy_endpoint,)
  47. def connect(self, protocolFactory):
  48. f = HTTPProxiedClientFactory(self._host, self._port, protocolFactory)
  49. d = self._proxy_endpoint.connect(f)
  50. # once the tcp socket connects successfully, we need to wait for the
  51. # CONNECT to complete.
  52. d.addCallback(lambda conn: f.on_connection)
  53. return d
  54. class HTTPProxiedClientFactory(protocol.ClientFactory):
  55. """ClientFactory wrapper that triggers an HTTP proxy CONNECT on connect.
  56. Once the CONNECT completes, invokes the original ClientFactory to build the
  57. HTTP Protocol object and run the rest of the connection.
  58. Args:
  59. dst_host (bytes): hostname that we want to CONNECT to
  60. dst_port (int): port that we want to connect to
  61. wrapped_factory (protocol.ClientFactory): The original Factory
  62. """
  63. def __init__(self, dst_host, dst_port, wrapped_factory):
  64. self.dst_host = dst_host
  65. self.dst_port = dst_port
  66. self.wrapped_factory = wrapped_factory
  67. self.on_connection = defer.Deferred()
  68. def startedConnecting(self, connector):
  69. return self.wrapped_factory.startedConnecting(connector)
  70. def buildProtocol(self, addr):
  71. wrapped_protocol = self.wrapped_factory.buildProtocol(addr)
  72. return HTTPConnectProtocol(
  73. self.dst_host, self.dst_port, wrapped_protocol, self.on_connection
  74. )
  75. def clientConnectionFailed(self, connector, reason):
  76. logger.debug("Connection to proxy failed: %s", reason)
  77. if not self.on_connection.called:
  78. self.on_connection.errback(reason)
  79. return self.wrapped_factory.clientConnectionFailed(connector, reason)
  80. def clientConnectionLost(self, connector, reason):
  81. logger.debug("Connection to proxy lost: %s", reason)
  82. if not self.on_connection.called:
  83. self.on_connection.errback(reason)
  84. return self.wrapped_factory.clientConnectionLost(connector, reason)
  85. class HTTPConnectProtocol(protocol.Protocol):
  86. """Protocol that wraps an existing Protocol to do a CONNECT handshake at connect
  87. Args:
  88. host (bytes): The original HTTP(s) hostname or IPv4 or IPv6 address literal
  89. to put in the CONNECT request
  90. port (int): The original HTTP(s) port to put in the CONNECT request
  91. wrapped_protocol (interfaces.IProtocol): the original protocol (probably
  92. HTTPChannel or TLSMemoryBIOProtocol, but could be anything really)
  93. connected_deferred (Deferred): a Deferred which will be callbacked with
  94. wrapped_protocol when the CONNECT completes
  95. """
  96. def __init__(self, host, port, wrapped_protocol, connected_deferred):
  97. self.host = host
  98. self.port = port
  99. self.wrapped_protocol = wrapped_protocol
  100. self.connected_deferred = connected_deferred
  101. self.http_setup_client = HTTPConnectSetupClient(self.host, self.port)
  102. self.http_setup_client.on_connected.addCallback(self.proxyConnected)
  103. def connectionMade(self):
  104. self.http_setup_client.makeConnection(self.transport)
  105. def connectionLost(self, reason=connectionDone):
  106. if self.wrapped_protocol.connected:
  107. self.wrapped_protocol.connectionLost(reason)
  108. self.http_setup_client.connectionLost(reason)
  109. if not self.connected_deferred.called:
  110. self.connected_deferred.errback(reason)
  111. def proxyConnected(self, _):
  112. self.wrapped_protocol.makeConnection(self.transport)
  113. self.connected_deferred.callback(self.wrapped_protocol)
  114. # Get any pending data from the http buf and forward it to the original protocol
  115. buf = self.http_setup_client.clearLineBuffer()
  116. if buf:
  117. self.wrapped_protocol.dataReceived(buf)
  118. def dataReceived(self, data):
  119. # if we've set up the HTTP protocol, we can send the data there
  120. if self.wrapped_protocol.connected:
  121. return self.wrapped_protocol.dataReceived(data)
  122. # otherwise, we must still be setting up the connection: send the data to the
  123. # setup client
  124. return self.http_setup_client.dataReceived(data)
  125. class HTTPConnectSetupClient(http.HTTPClient):
  126. """HTTPClient protocol to send a CONNECT message for proxies and read the response.
  127. Args:
  128. host (bytes): The hostname to send in the CONNECT message
  129. port (int): The port to send in the CONNECT message
  130. """
  131. def __init__(self, host, port):
  132. self.host = host
  133. self.port = port
  134. self.on_connected = defer.Deferred()
  135. def connectionMade(self):
  136. logger.debug("Connected to proxy, sending CONNECT")
  137. self.sendCommand(b"CONNECT", b"%s:%d" % (self.host, self.port))
  138. self.endHeaders()
  139. def handleStatus(self, version, status, message):
  140. logger.debug("Got Status: %s %s %s", status, message, version)
  141. if status != b"200":
  142. raise ProxyConnectError("Unexpected status on CONNECT: %s" % status)
  143. def handleEndHeaders(self):
  144. logger.debug("End Headers")
  145. self.on_connected.callback(None)
  146. def handleResponse(self, body):
  147. pass