endpoint.py 11 KB

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