endpoint.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 (unicode): 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. # the SNI string should be the same as the Host header, minus the port.
  102. # as per https://github.com/matrix-org/synapse/issues/2525#issuecomment-336896777,
  103. # the Host header and SNI should therefore be the server_name of the remote
  104. # server.
  105. tls_options = tls_client_options_factory.get_options(domain)
  106. def transport_endpoint(reactor, host, port, timeout):
  107. return wrapClientTLS(
  108. tls_options,
  109. HostnameEndpoint(reactor, host, port, timeout=timeout),
  110. )
  111. default_port = 8448
  112. if port is None:
  113. return _WrappingEndpointFac(SRVClientEndpoint(
  114. reactor, "matrix", domain, protocol="tcp",
  115. default_port=default_port, endpoint=transport_endpoint,
  116. endpoint_kw_args=endpoint_kw_args
  117. ), reactor)
  118. else:
  119. return _WrappingEndpointFac(transport_endpoint(
  120. reactor, domain, port, **endpoint_kw_args
  121. ), reactor)
  122. class _WrappingEndpointFac(object):
  123. def __init__(self, endpoint_fac, reactor):
  124. self.endpoint_fac = endpoint_fac
  125. self.reactor = reactor
  126. @defer.inlineCallbacks
  127. def connect(self, protocolFactory):
  128. conn = yield self.endpoint_fac.connect(protocolFactory)
  129. conn = _WrappedConnection(conn, self.reactor)
  130. defer.returnValue(conn)
  131. class _WrappedConnection(object):
  132. """Wraps a connection and calls abort on it if it hasn't seen any action
  133. for 2.5-3 minutes.
  134. """
  135. __slots__ = ["conn", "last_request"]
  136. def __init__(self, conn, reactor):
  137. object.__setattr__(self, "conn", conn)
  138. object.__setattr__(self, "last_request", time.time())
  139. self._reactor = reactor
  140. def __getattr__(self, name):
  141. return getattr(self.conn, name)
  142. def __setattr__(self, name, value):
  143. setattr(self.conn, name, value)
  144. def _time_things_out_maybe(self):
  145. # We use a slightly shorter timeout here just in case the callLater is
  146. # triggered early. Paranoia ftw.
  147. # TODO: Cancel the previous callLater rather than comparing time.time()?
  148. if time.time() - self.last_request >= 2.5 * 60:
  149. self.abort()
  150. # Abort the underlying TLS connection. The abort() method calls
  151. # loseConnection() on the TLS connection which tries to
  152. # shutdown the connection cleanly. We call abortConnection()
  153. # since that will promptly close the TLS connection.
  154. #
  155. # In Twisted >18.4; the TLS connection will be None if it has closed
  156. # which will make abortConnection() throw. Check that the TLS connection
  157. # is not None before trying to close it.
  158. if self.transport.getHandle() is not None:
  159. self.transport.abortConnection()
  160. def request(self, request):
  161. self.last_request = time.time()
  162. # Time this connection out if we haven't send a request in the last
  163. # N minutes
  164. # TODO: Cancel the previous callLater?
  165. self._reactor.callLater(3 * 60, self._time_things_out_maybe)
  166. d = self.conn.request(request)
  167. def update_request_time(res):
  168. self.last_request = time.time()
  169. # TODO: Cancel the previous callLater?
  170. self._reactor.callLater(3 * 60, self._time_things_out_maybe)
  171. return res
  172. d.addCallback(update_request_time)
  173. return d
  174. class SRVClientEndpoint(object):
  175. """An endpoint which looks up SRV records for a service.
  176. Cycles through the list of servers starting with each call to connect
  177. picking the next server.
  178. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  179. """
  180. def __init__(self, reactor, service, domain, protocol="tcp",
  181. default_port=None, endpoint=HostnameEndpoint,
  182. endpoint_kw_args={}):
  183. self.reactor = reactor
  184. self.service_name = "_%s._%s.%s" % (service, protocol, domain)
  185. if default_port is not None:
  186. self.default_server = _Server(
  187. host=domain,
  188. port=default_port,
  189. priority=0,
  190. weight=0,
  191. expires=0,
  192. )
  193. else:
  194. self.default_server = None
  195. self.endpoint = endpoint
  196. self.endpoint_kw_args = endpoint_kw_args
  197. self.servers = None
  198. self.used_servers = None
  199. @defer.inlineCallbacks
  200. def fetch_servers(self):
  201. self.used_servers = []
  202. self.servers = yield resolve_service(self.service_name)
  203. def pick_server(self):
  204. if not self.servers:
  205. if self.used_servers:
  206. self.servers = self.used_servers
  207. self.used_servers = []
  208. self.servers.sort()
  209. elif self.default_server:
  210. return self.default_server
  211. else:
  212. raise ConnectError(
  213. "No server available for %s" % self.service_name
  214. )
  215. # look for all servers with the same priority
  216. min_priority = self.servers[0].priority
  217. weight_indexes = list(
  218. (index, server.weight + 1)
  219. for index, server in enumerate(self.servers)
  220. if server.priority == min_priority
  221. )
  222. total_weight = sum(weight for index, weight in weight_indexes)
  223. target_weight = random.randint(0, total_weight)
  224. for index, weight in weight_indexes:
  225. target_weight -= weight
  226. if target_weight <= 0:
  227. server = self.servers[index]
  228. # XXX: this looks totally dubious:
  229. #
  230. # (a) we never reuse a server until we have been through
  231. # all of the servers at the same priority, so if the
  232. # weights are A: 100, B:1, we always do ABABAB instead of
  233. # AAAA...AAAB (approximately).
  234. #
  235. # (b) After using all the servers at the lowest priority,
  236. # we move onto the next priority. We should only use the
  237. # second priority if servers at the top priority are
  238. # unreachable.
  239. #
  240. del self.servers[index]
  241. self.used_servers.append(server)
  242. return server
  243. @defer.inlineCallbacks
  244. def connect(self, protocolFactory):
  245. if self.servers is None:
  246. yield self.fetch_servers()
  247. server = self.pick_server()
  248. logger.info("Connecting to %s:%s", server.host, server.port)
  249. endpoint = self.endpoint(
  250. self.reactor, server.host, server.port, **self.endpoint_kw_args
  251. )
  252. connection = yield endpoint.connect(protocolFactory)
  253. defer.returnValue(connection)
  254. @defer.inlineCallbacks
  255. def resolve_service(service_name, dns_client=client, cache=SERVER_CACHE, clock=time):
  256. cache_entry = cache.get(service_name, None)
  257. if cache_entry:
  258. if all(s.expires > int(clock.time()) for s in cache_entry):
  259. servers = list(cache_entry)
  260. defer.returnValue(servers)
  261. servers = []
  262. try:
  263. try:
  264. answers, _, _ = yield dns_client.lookupService(service_name)
  265. except DNSNameError:
  266. defer.returnValue([])
  267. if (len(answers) == 1
  268. and answers[0].type == dns.SRV
  269. and answers[0].payload
  270. and answers[0].payload.target == dns.Name(b'.')):
  271. raise ConnectError("Service %s unavailable" % service_name)
  272. for answer in answers:
  273. if answer.type != dns.SRV or not answer.payload:
  274. continue
  275. payload = answer.payload
  276. servers.append(_Server(
  277. host=str(payload.target),
  278. port=int(payload.port),
  279. priority=int(payload.priority),
  280. weight=int(payload.weight),
  281. expires=int(clock.time()) + answer.ttl,
  282. ))
  283. servers.sort()
  284. cache[service_name] = list(servers)
  285. except DomainError as e:
  286. # We failed to resolve the name (other than a NameError)
  287. # Try something in the cache, else rereaise
  288. cache_entry = cache.get(service_name, None)
  289. if cache_entry:
  290. logger.warn(
  291. "Failed to resolve %r, falling back to cache. %r",
  292. service_name, e
  293. )
  294. servers = list(cache_entry)
  295. else:
  296. raise e
  297. defer.returnValue(servers)