endpoint.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. import socket
  16. from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
  17. from twisted.internet import defer, reactor
  18. from twisted.internet.error import ConnectError
  19. from twisted.names import client, dns
  20. from twisted.names.error import DNSNameError, DomainError
  21. import collections
  22. import logging
  23. import random
  24. import time
  25. logger = logging.getLogger(__name__)
  26. SERVER_CACHE = {}
  27. # our record of an individual server which can be tried to reach a destination.
  28. #
  29. # "host" is actually a dotted-quad or ipv6 address string. Except when there's
  30. # no SRV record, in which case it is the original hostname.
  31. _Server = collections.namedtuple(
  32. "_Server", "priority weight host port expires"
  33. )
  34. def matrix_federation_endpoint(reactor, destination, ssl_context_factory=None,
  35. timeout=None):
  36. """Construct an endpoint for the given matrix destination.
  37. Args:
  38. reactor: Twisted reactor.
  39. destination (bytes): The name of the server to connect to.
  40. ssl_context_factory (twisted.internet.ssl.ContextFactory): Factory
  41. which generates SSL contexts to use for TLS.
  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 ssl_context_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. ssl_context_factory,
  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 underlying TLS connection which tries to
  97. # shutdown the connection cleanly. We call abortConnection()
  98. # since that will promptly close the underlying TCP connection.
  99. self.transport.abortConnection()
  100. def request(self, request):
  101. self.last_request = time.time()
  102. # Time this connection out if we haven't send a request in the last
  103. # N minutes
  104. # TODO: Cancel the previous callLater?
  105. reactor.callLater(3 * 60, self._time_things_out_maybe)
  106. d = self.conn.request(request)
  107. def update_request_time(res):
  108. self.last_request = time.time()
  109. # TODO: Cancel the previous callLater?
  110. reactor.callLater(3 * 60, self._time_things_out_maybe)
  111. return res
  112. d.addCallback(update_request_time)
  113. return d
  114. class SpiderEndpoint(object):
  115. """An endpoint which refuses to connect to blacklisted IP addresses
  116. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  117. """
  118. def __init__(self, reactor, host, port, blacklist, whitelist,
  119. endpoint=HostnameEndpoint, endpoint_kw_args={}):
  120. self.reactor = reactor
  121. self.host = host
  122. self.port = port
  123. self.blacklist = blacklist
  124. self.whitelist = whitelist
  125. self.endpoint = endpoint
  126. self.endpoint_kw_args = endpoint_kw_args
  127. @defer.inlineCallbacks
  128. def connect(self, protocolFactory):
  129. address = yield self.reactor.resolve(self.host)
  130. from netaddr import IPAddress
  131. ip_address = IPAddress(address)
  132. if ip_address in self.blacklist:
  133. if self.whitelist is None or ip_address not in self.whitelist:
  134. raise ConnectError(
  135. "Refusing to spider blacklisted IP address %s" % address
  136. )
  137. logger.info("Connecting to %s:%s", address, self.port)
  138. endpoint = self.endpoint(
  139. self.reactor, address, self.port, **self.endpoint_kw_args
  140. )
  141. connection = yield endpoint.connect(protocolFactory)
  142. defer.returnValue(connection)
  143. class SRVClientEndpoint(object):
  144. """An endpoint which looks up SRV records for a service.
  145. Cycles through the list of servers starting with each call to connect
  146. picking the next server.
  147. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  148. """
  149. def __init__(self, reactor, service, domain, protocol="tcp",
  150. default_port=None, endpoint=HostnameEndpoint,
  151. endpoint_kw_args={}):
  152. self.reactor = reactor
  153. self.service_name = "_%s._%s.%s" % (service, protocol, domain)
  154. if default_port is not None:
  155. self.default_server = _Server(
  156. host=domain,
  157. port=default_port,
  158. priority=0,
  159. weight=0,
  160. expires=0,
  161. )
  162. else:
  163. self.default_server = None
  164. self.endpoint = endpoint
  165. self.endpoint_kw_args = endpoint_kw_args
  166. self.servers = None
  167. self.used_servers = None
  168. @defer.inlineCallbacks
  169. def fetch_servers(self):
  170. self.used_servers = []
  171. self.servers = yield resolve_service(self.service_name)
  172. def pick_server(self):
  173. if not self.servers:
  174. if self.used_servers:
  175. self.servers = self.used_servers
  176. self.used_servers = []
  177. self.servers.sort()
  178. elif self.default_server:
  179. return self.default_server
  180. else:
  181. raise ConnectError(
  182. "No server available for %s" % self.service_name
  183. )
  184. # look for all servers with the same priority
  185. min_priority = self.servers[0].priority
  186. weight_indexes = list(
  187. (index, server.weight + 1)
  188. for index, server in enumerate(self.servers)
  189. if server.priority == min_priority
  190. )
  191. total_weight = sum(weight for index, weight in weight_indexes)
  192. target_weight = random.randint(0, total_weight)
  193. for index, weight in weight_indexes:
  194. target_weight -= weight
  195. if target_weight <= 0:
  196. server = self.servers[index]
  197. # XXX: this looks totally dubious:
  198. #
  199. # (a) we never reuse a server until we have been through
  200. # all of the servers at the same priority, so if the
  201. # weights are A: 100, B:1, we always do ABABAB instead of
  202. # AAAA...AAAB (approximately).
  203. #
  204. # (b) After using all the servers at the lowest priority,
  205. # we move onto the next priority. We should only use the
  206. # second priority if servers at the top priority are
  207. # unreachable.
  208. #
  209. del self.servers[index]
  210. self.used_servers.append(server)
  211. return server
  212. @defer.inlineCallbacks
  213. def connect(self, protocolFactory):
  214. if self.servers is None:
  215. yield self.fetch_servers()
  216. server = self.pick_server()
  217. logger.info("Connecting to %s:%s", server.host, server.port)
  218. endpoint = self.endpoint(
  219. self.reactor, server.host, server.port, **self.endpoint_kw_args
  220. )
  221. connection = yield endpoint.connect(protocolFactory)
  222. defer.returnValue(connection)
  223. @defer.inlineCallbacks
  224. def resolve_service(service_name, dns_client=client, cache=SERVER_CACHE, clock=time):
  225. cache_entry = cache.get(service_name, None)
  226. if cache_entry:
  227. if all(s.expires > int(clock.time()) for s in cache_entry):
  228. servers = list(cache_entry)
  229. defer.returnValue(servers)
  230. servers = []
  231. try:
  232. try:
  233. answers, _, _ = yield dns_client.lookupService(service_name)
  234. except DNSNameError:
  235. defer.returnValue([])
  236. if (len(answers) == 1
  237. and answers[0].type == dns.SRV
  238. and answers[0].payload
  239. and answers[0].payload.target == dns.Name('.')):
  240. raise ConnectError("Service %s unavailable" % service_name)
  241. for answer in answers:
  242. if answer.type != dns.SRV or not answer.payload:
  243. continue
  244. payload = answer.payload
  245. hosts = yield _get_hosts_for_srv_record(
  246. dns_client, str(payload.target)
  247. )
  248. for (ip, ttl) in hosts:
  249. host_ttl = min(answer.ttl, ttl)
  250. servers.append(_Server(
  251. host=ip,
  252. port=int(payload.port),
  253. priority=int(payload.priority),
  254. weight=int(payload.weight),
  255. expires=int(clock.time()) + host_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)
  272. @defer.inlineCallbacks
  273. def _get_hosts_for_srv_record(dns_client, host):
  274. """Look up each of the hosts in a SRV record
  275. Args:
  276. dns_client (twisted.names.dns.IResolver):
  277. host (basestring): host to look up
  278. Returns:
  279. Deferred[list[(str, int)]]: a list of (host, ttl) pairs
  280. """
  281. ip4_servers = []
  282. ip6_servers = []
  283. def cb(res):
  284. # lookupAddress and lookupIP6Address return a three-tuple
  285. # giving the answer, authority, and additional sections of the
  286. # response.
  287. #
  288. # we only care about the answers.
  289. return res[0]
  290. def eb(res, record_type):
  291. if res.check(DNSNameError):
  292. return []
  293. logger.warn("Error looking up %s for %s: %s", record_type, host, res)
  294. return res
  295. # no logcontexts here, so we can safely fire these off and gatherResults
  296. d1 = dns_client.lookupAddress(host).addCallbacks(
  297. cb, eb, errbackArgs=("A", ))
  298. d2 = dns_client.lookupIPV6Address(host).addCallbacks(
  299. cb, eb, errbackArgs=("AAAA", ))
  300. results = yield defer.DeferredList(
  301. [d1, d2], consumeErrors=True)
  302. # if all of the lookups failed, raise an exception rather than blowing out
  303. # the cache with an empty result.
  304. if results and all(s == defer.FAILURE for (s, _) in results):
  305. defer.returnValue(results[0][1])
  306. for (success, result) in results:
  307. if success == defer.FAILURE:
  308. continue
  309. for answer in result:
  310. if not answer.payload:
  311. continue
  312. try:
  313. if answer.type == dns.A:
  314. ip = answer.payload.dottedQuad()
  315. ip4_servers.append((ip, answer.ttl))
  316. elif answer.type == dns.AAAA:
  317. ip = socket.inet_ntop(
  318. socket.AF_INET6, answer.payload.address,
  319. )
  320. ip6_servers.append((ip, answer.ttl))
  321. else:
  322. # the most likely candidate here is a CNAME record.
  323. # rfc2782 says srvs may not point to aliases.
  324. logger.warn(
  325. "Ignoring unexpected DNS record type %s for %s",
  326. answer.type, host,
  327. )
  328. continue
  329. except Exception as e:
  330. logger.warn("Ignoring invalid DNS response for %s: %s",
  331. host, e)
  332. continue
  333. # keep the ipv4 results before the ipv6 results, mostly to match historical
  334. # behaviour.
  335. defer.returnValue(ip4_servers + ip6_servers)