endpoint.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-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 twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
  16. from twisted.internet import defer, reactor
  17. from twisted.internet.error import ConnectError
  18. from twisted.names import client, dns
  19. from twisted.names.error import DNSNameError, DomainError
  20. import collections
  21. import logging
  22. import random
  23. import time
  24. logger = logging.getLogger(__name__)
  25. SERVER_CACHE = {}
  26. # our record of an individual server which can be tried to reach a destination.
  27. #
  28. # "host" is the hostname acquired from the SRV record. Except when there's
  29. # no SRV record, in which case it is the original hostname.
  30. _Server = collections.namedtuple(
  31. "_Server", "priority weight host port expires"
  32. )
  33. def matrix_federation_endpoint(reactor, destination, tls_client_options_factory=None,
  34. timeout=None):
  35. """Construct an endpoint for the given matrix destination.
  36. Args:
  37. reactor: Twisted reactor.
  38. destination (bytes): The name of the server to connect to.
  39. tls_client_options_factory
  40. (synapse.crypto.context_factory.ClientTLSOptionsFactory):
  41. Factory which generates TLS options for client connections.
  42. timeout (int): connection timeout in seconds
  43. """
  44. domain_port = destination.split(":")
  45. domain = domain_port[0]
  46. port = int(domain_port[1]) if domain_port[1:] else None
  47. endpoint_kw_args = {}
  48. if timeout is not None:
  49. endpoint_kw_args.update(timeout=timeout)
  50. if tls_client_options_factory is None:
  51. transport_endpoint = HostnameEndpoint
  52. default_port = 8008
  53. else:
  54. def transport_endpoint(reactor, host, port, timeout):
  55. return wrapClientTLS(
  56. tls_client_options_factory.get_options(host),
  57. HostnameEndpoint(reactor, host, port, timeout=timeout))
  58. default_port = 8448
  59. if port is None:
  60. return _WrappingEndpointFac(SRVClientEndpoint(
  61. reactor, "matrix", domain, protocol="tcp",
  62. default_port=default_port, endpoint=transport_endpoint,
  63. endpoint_kw_args=endpoint_kw_args
  64. ))
  65. else:
  66. return _WrappingEndpointFac(transport_endpoint(
  67. reactor, domain, port, **endpoint_kw_args
  68. ))
  69. class _WrappingEndpointFac(object):
  70. def __init__(self, endpoint_fac):
  71. self.endpoint_fac = endpoint_fac
  72. @defer.inlineCallbacks
  73. def connect(self, protocolFactory):
  74. conn = yield self.endpoint_fac.connect(protocolFactory)
  75. conn = _WrappedConnection(conn)
  76. defer.returnValue(conn)
  77. class _WrappedConnection(object):
  78. """Wraps a connection and calls abort on it if it hasn't seen any action
  79. for 2.5-3 minutes.
  80. """
  81. __slots__ = ["conn", "last_request"]
  82. def __init__(self, conn):
  83. object.__setattr__(self, "conn", conn)
  84. object.__setattr__(self, "last_request", time.time())
  85. def __getattr__(self, name):
  86. return getattr(self.conn, name)
  87. def __setattr__(self, name, value):
  88. setattr(self.conn, name, value)
  89. def _time_things_out_maybe(self):
  90. # We use a slightly shorter timeout here just in case the callLater is
  91. # triggered early. Paranoia ftw.
  92. # TODO: Cancel the previous callLater rather than comparing time.time()?
  93. if time.time() - self.last_request >= 2.5 * 60:
  94. self.abort()
  95. # Abort the underlying TLS connection. The abort() method calls
  96. # loseConnection() on the TLS connection which tries to
  97. # shutdown the connection cleanly. We call abortConnection()
  98. # since that will promptly close the TLS connection.
  99. #
  100. # In Twisted >18.4; the TLS connection will be None if it has closed
  101. # which will make abortConnection() throw. Check that the TLS connection
  102. # is not None before trying to close it.
  103. if self.transport.getHandle() is not None:
  104. self.transport.abortConnection()
  105. def request(self, request):
  106. self.last_request = time.time()
  107. # Time this connection out if we haven't send a request in the last
  108. # N minutes
  109. # TODO: Cancel the previous callLater?
  110. reactor.callLater(3 * 60, self._time_things_out_maybe)
  111. d = self.conn.request(request)
  112. def update_request_time(res):
  113. self.last_request = time.time()
  114. # TODO: Cancel the previous callLater?
  115. reactor.callLater(3 * 60, self._time_things_out_maybe)
  116. return res
  117. d.addCallback(update_request_time)
  118. return d
  119. class SpiderEndpoint(object):
  120. """An endpoint which refuses to connect to blacklisted IP addresses
  121. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  122. """
  123. def __init__(self, reactor, host, port, blacklist, whitelist,
  124. endpoint=HostnameEndpoint, endpoint_kw_args={}):
  125. self.reactor = reactor
  126. self.host = host
  127. self.port = port
  128. self.blacklist = blacklist
  129. self.whitelist = whitelist
  130. self.endpoint = endpoint
  131. self.endpoint_kw_args = endpoint_kw_args
  132. @defer.inlineCallbacks
  133. def connect(self, protocolFactory):
  134. address = yield self.reactor.resolve(self.host)
  135. from netaddr import IPAddress
  136. ip_address = IPAddress(address)
  137. if ip_address in self.blacklist:
  138. if self.whitelist is None or ip_address not in self.whitelist:
  139. raise ConnectError(
  140. "Refusing to spider blacklisted IP address %s" % address
  141. )
  142. logger.info("Connecting to %s:%s", address, self.port)
  143. endpoint = self.endpoint(
  144. self.reactor, address, self.port, **self.endpoint_kw_args
  145. )
  146. connection = yield endpoint.connect(protocolFactory)
  147. defer.returnValue(connection)
  148. class SRVClientEndpoint(object):
  149. """An endpoint which looks up SRV records for a service.
  150. Cycles through the list of servers starting with each call to connect
  151. picking the next server.
  152. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  153. """
  154. def __init__(self, reactor, service, domain, protocol="tcp",
  155. default_port=None, endpoint=HostnameEndpoint,
  156. endpoint_kw_args={}):
  157. self.reactor = reactor
  158. self.service_name = "_%s._%s.%s" % (service, protocol, domain)
  159. if default_port is not None:
  160. self.default_server = _Server(
  161. host=domain,
  162. port=default_port,
  163. priority=0,
  164. weight=0,
  165. expires=0,
  166. )
  167. else:
  168. self.default_server = None
  169. self.endpoint = endpoint
  170. self.endpoint_kw_args = endpoint_kw_args
  171. self.servers = None
  172. self.used_servers = None
  173. @defer.inlineCallbacks
  174. def fetch_servers(self):
  175. self.used_servers = []
  176. self.servers = yield resolve_service(self.service_name)
  177. def pick_server(self):
  178. if not self.servers:
  179. if self.used_servers:
  180. self.servers = self.used_servers
  181. self.used_servers = []
  182. self.servers.sort()
  183. elif self.default_server:
  184. return self.default_server
  185. else:
  186. raise ConnectError(
  187. "No server available for %s" % self.service_name
  188. )
  189. # look for all servers with the same priority
  190. min_priority = self.servers[0].priority
  191. weight_indexes = list(
  192. (index, server.weight + 1)
  193. for index, server in enumerate(self.servers)
  194. if server.priority == min_priority
  195. )
  196. total_weight = sum(weight for index, weight in weight_indexes)
  197. target_weight = random.randint(0, total_weight)
  198. for index, weight in weight_indexes:
  199. target_weight -= weight
  200. if target_weight <= 0:
  201. server = self.servers[index]
  202. # XXX: this looks totally dubious:
  203. #
  204. # (a) we never reuse a server until we have been through
  205. # all of the servers at the same priority, so if the
  206. # weights are A: 100, B:1, we always do ABABAB instead of
  207. # AAAA...AAAB (approximately).
  208. #
  209. # (b) After using all the servers at the lowest priority,
  210. # we move onto the next priority. We should only use the
  211. # second priority if servers at the top priority are
  212. # unreachable.
  213. #
  214. del self.servers[index]
  215. self.used_servers.append(server)
  216. return server
  217. @defer.inlineCallbacks
  218. def connect(self, protocolFactory):
  219. if self.servers is None:
  220. yield self.fetch_servers()
  221. server = self.pick_server()
  222. logger.info("Connecting to %s:%s", server.host, server.port)
  223. endpoint = self.endpoint(
  224. self.reactor, server.host, server.port, **self.endpoint_kw_args
  225. )
  226. connection = yield endpoint.connect(protocolFactory)
  227. defer.returnValue(connection)
  228. @defer.inlineCallbacks
  229. def resolve_service(service_name, dns_client=client, cache=SERVER_CACHE, clock=time):
  230. cache_entry = cache.get(service_name, None)
  231. if cache_entry:
  232. if all(s.expires > int(clock.time()) for s in cache_entry):
  233. servers = list(cache_entry)
  234. defer.returnValue(servers)
  235. servers = []
  236. try:
  237. try:
  238. answers, _, _ = yield dns_client.lookupService(service_name)
  239. except DNSNameError:
  240. defer.returnValue([])
  241. if (len(answers) == 1
  242. and answers[0].type == dns.SRV
  243. and answers[0].payload
  244. and answers[0].payload.target == dns.Name(b'.')):
  245. raise ConnectError("Service %s unavailable" % service_name)
  246. for answer in answers:
  247. if answer.type != dns.SRV or not answer.payload:
  248. continue
  249. payload = answer.payload
  250. servers.append(_Server(
  251. host=str(payload.target),
  252. port=int(payload.port),
  253. priority=int(payload.priority),
  254. weight=int(payload.weight),
  255. expires=int(clock.time()) + answer.ttl,
  256. ))
  257. servers.sort()
  258. cache[service_name] = list(servers)
  259. except DomainError as e:
  260. # We failed to resolve the name (other than a NameError)
  261. # Try something in the cache, else rereaise
  262. cache_entry = cache.get(service_name, None)
  263. if cache_entry:
  264. logger.warn(
  265. "Failed to resolve %r, falling back to cache. %r",
  266. service_name, e
  267. )
  268. servers = list(cache_entry)
  269. else:
  270. raise e
  271. defer.returnValue(servers)