|
| 1 | +# Copyright 2023 The Matrix.org Foundation C.I.C. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +from typing import Optional |
| 17 | + |
| 18 | +from zope.interface import implementer |
| 19 | + |
| 20 | +from twisted.internet import defer |
| 21 | +from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS |
| 22 | +from twisted.internet.interfaces import IStreamClientEndpoint |
| 23 | +from twisted.python.failure import Failure |
| 24 | +from twisted.web.client import URI, HTTPConnectionPool, _AgentBase |
| 25 | +from twisted.web.error import SchemeNotSupported |
| 26 | +from twisted.web.http_headers import Headers |
| 27 | +from twisted.web.iweb import ( |
| 28 | + IAgent, |
| 29 | + IAgentEndpointFactory, |
| 30 | + IBodyProducer, |
| 31 | + IPolicyForHTTPS, |
| 32 | + IResponse, |
| 33 | +) |
| 34 | + |
| 35 | +from synapse.types import ISynapseReactor |
| 36 | + |
| 37 | +logger = logging.getLogger(__name__) |
| 38 | + |
| 39 | + |
| 40 | +@implementer(IAgentEndpointFactory) |
| 41 | +class ReplicationEndpointFactory: |
| 42 | + """Connect to a given TCP socket""" |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + reactor: ISynapseReactor, |
| 47 | + context_factory: IPolicyForHTTPS, |
| 48 | + ) -> None: |
| 49 | + self.reactor = reactor |
| 50 | + self.context_factory = context_factory |
| 51 | + |
| 52 | + def endpointForURI(self, uri: URI) -> IStreamClientEndpoint: |
| 53 | + """ |
| 54 | + This part of the factory decides what kind of endpoint is being connected to. |
| 55 | +
|
| 56 | + Args: |
| 57 | + uri: The pre-parsed URI object containing all the uri data |
| 58 | +
|
| 59 | + Returns: The correct client endpoint object |
| 60 | + """ |
| 61 | + if uri.scheme in (b"http", b"https"): |
| 62 | + endpoint = HostnameEndpoint(self.reactor, uri.host, uri.port) |
| 63 | + if uri.scheme == b"https": |
| 64 | + endpoint = wrapClientTLS( |
| 65 | + self.context_factory.creatorForNetloc(uri.host, uri.port), endpoint |
| 66 | + ) |
| 67 | + return endpoint |
| 68 | + else: |
| 69 | + raise SchemeNotSupported(f"Unsupported scheme: {uri.scheme!r}") |
| 70 | + |
| 71 | + |
| 72 | +@implementer(IAgent) |
| 73 | +class ReplicationAgent(_AgentBase): |
| 74 | + """ |
| 75 | + Client for connecting to replication endpoints via HTTP and HTTPS. |
| 76 | +
|
| 77 | + Much of this code is copied from Twisted's twisted.web.client.Agent. |
| 78 | + """ |
| 79 | + |
| 80 | + def __init__( |
| 81 | + self, |
| 82 | + reactor: ISynapseReactor, |
| 83 | + contextFactory: IPolicyForHTTPS, |
| 84 | + connectTimeout: Optional[float] = None, |
| 85 | + bindAddress: Optional[bytes] = None, |
| 86 | + pool: Optional[HTTPConnectionPool] = None, |
| 87 | + ): |
| 88 | + """ |
| 89 | + Create a ReplicationAgent. |
| 90 | +
|
| 91 | + Args: |
| 92 | + reactor: A reactor for this Agent to place outgoing connections. |
| 93 | + contextFactory: A factory for TLS contexts, to control the |
| 94 | + verification parameters of OpenSSL. The default is to use a |
| 95 | + BrowserLikePolicyForHTTPS, so unless you have special |
| 96 | + requirements you can leave this as-is. |
| 97 | + connectTimeout: The amount of time that this Agent will wait |
| 98 | + for the peer to accept a connection. |
| 99 | + bindAddress: The local address for client sockets to bind to. |
| 100 | + pool: An HTTPConnectionPool instance, or None, in which |
| 101 | + case a non-persistent HTTPConnectionPool instance will be |
| 102 | + created. |
| 103 | + """ |
| 104 | + _AgentBase.__init__(self, reactor, pool) |
| 105 | + endpoint_factory = ReplicationEndpointFactory(reactor, contextFactory) |
| 106 | + self._endpointFactory = endpoint_factory |
| 107 | + |
| 108 | + def request( |
| 109 | + self, |
| 110 | + method: bytes, |
| 111 | + uri: bytes, |
| 112 | + headers: Optional[Headers] = None, |
| 113 | + bodyProducer: Optional[IBodyProducer] = None, |
| 114 | + ) -> "defer.Deferred[IResponse]": |
| 115 | + """ |
| 116 | + Issue a request to the server indicated by the given uri. |
| 117 | +
|
| 118 | + An existing connection from the connection pool may be used or a new |
| 119 | + one may be created. |
| 120 | +
|
| 121 | + Currently, HTTP and HTTPS schemes are supported in uri. |
| 122 | +
|
| 123 | + This is copied from twisted.web.client.Agent, except: |
| 124 | +
|
| 125 | + * It uses a different pool key (combining the host & port). |
| 126 | + * It does not call _ensureValidURI(...) since it breaks on some |
| 127 | + UNIX paths. |
| 128 | +
|
| 129 | + See: twisted.web.iweb.IAgent.request |
| 130 | + """ |
| 131 | + parsedURI = URI.fromBytes(uri) |
| 132 | + try: |
| 133 | + endpoint = self._endpointFactory.endpointForURI(parsedURI) |
| 134 | + except SchemeNotSupported: |
| 135 | + return defer.fail(Failure()) |
| 136 | + |
| 137 | + # This sets the Pool key to be: |
| 138 | + # (http(s), <host:ip>) |
| 139 | + key = (parsedURI.scheme, parsedURI.netloc) |
| 140 | + |
| 141 | + # _requestWithEndpoint comes from _AgentBase class |
| 142 | + return self._requestWithEndpoint( |
| 143 | + key, |
| 144 | + endpoint, |
| 145 | + method, |
| 146 | + parsedURI, |
| 147 | + headers, |
| 148 | + bodyProducer, |
| 149 | + parsedURI.originForm, |
| 150 | + ) |
0 commit comments