endpoint.py 13 KB

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