endpoint.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 logging
  16. import random
  17. import re
  18. from twisted.internet import defer
  19. from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
  20. from twisted.internet.error import ConnectError
  21. from synapse.http.federation.srv_resolver import Server, resolve_service
  22. logger = logging.getLogger(__name__)
  23. def parse_server_name(server_name):
  24. """Split a server name into host/port parts.
  25. Args:
  26. server_name (str): server name to parse
  27. Returns:
  28. Tuple[str, int|None]: host/port parts.
  29. Raises:
  30. ValueError if the server name could not be parsed.
  31. """
  32. try:
  33. if server_name[-1] == ']':
  34. # ipv6 literal, hopefully
  35. return server_name, None
  36. domain_port = server_name.rsplit(":", 1)
  37. domain = domain_port[0]
  38. port = int(domain_port[1]) if domain_port[1:] else None
  39. return domain, port
  40. except Exception:
  41. raise ValueError("Invalid server name '%s'" % server_name)
  42. VALID_HOST_REGEX = re.compile(
  43. "\\A[0-9a-zA-Z.-]+\\Z",
  44. )
  45. def parse_and_validate_server_name(server_name):
  46. """Split a server name into host/port parts and do some basic validation.
  47. Args:
  48. server_name (str): server name to parse
  49. Returns:
  50. Tuple[str, int|None]: host/port parts.
  51. Raises:
  52. ValueError if the server name could not be parsed.
  53. """
  54. host, port = parse_server_name(server_name)
  55. # these tests don't need to be bulletproof as we'll find out soon enough
  56. # if somebody is giving us invalid data. What we *do* need is to be sure
  57. # that nobody is sneaking IP literals in that look like hostnames, etc.
  58. # look for ipv6 literals
  59. if host[0] == '[':
  60. if host[-1] != ']':
  61. raise ValueError("Mismatched [...] in server name '%s'" % (
  62. server_name,
  63. ))
  64. return host, port
  65. # otherwise it should only be alphanumerics.
  66. if not VALID_HOST_REGEX.match(host):
  67. raise ValueError("Server name '%s' contains invalid characters" % (
  68. server_name,
  69. ))
  70. return host, port
  71. def matrix_federation_endpoint(reactor, destination, tls_client_options_factory=None,
  72. timeout=None):
  73. """Construct an endpoint for the given matrix destination.
  74. Args:
  75. reactor: Twisted reactor.
  76. destination (unicode): The name of the server to connect to.
  77. tls_client_options_factory
  78. (synapse.crypto.context_factory.ClientTLSOptionsFactory):
  79. Factory which generates TLS options for client connections.
  80. timeout (int): connection timeout in seconds
  81. """
  82. domain, port = parse_server_name(destination)
  83. endpoint_kw_args = {}
  84. if timeout is not None:
  85. endpoint_kw_args.update(timeout=timeout)
  86. if tls_client_options_factory is None:
  87. transport_endpoint = HostnameEndpoint
  88. default_port = 8008
  89. else:
  90. # the SNI string should be the same as the Host header, minus the port.
  91. # as per https://github.com/matrix-org/synapse/issues/2525#issuecomment-336896777,
  92. # the Host header and SNI should therefore be the server_name of the remote
  93. # server.
  94. tls_options = tls_client_options_factory.get_options(domain)
  95. def transport_endpoint(reactor, host, port, timeout):
  96. return wrapClientTLS(
  97. tls_options,
  98. HostnameEndpoint(reactor, host, port, timeout=timeout),
  99. )
  100. default_port = 8448
  101. if port is None:
  102. return SRVClientEndpoint(
  103. reactor, "matrix", domain, protocol="tcp",
  104. default_port=default_port, endpoint=transport_endpoint,
  105. endpoint_kw_args=endpoint_kw_args
  106. )
  107. else:
  108. return transport_endpoint(
  109. reactor, domain, port, **endpoint_kw_args
  110. )
  111. class SRVClientEndpoint(object):
  112. """An endpoint which looks up SRV records for a service.
  113. Cycles through the list of servers starting with each call to connect
  114. picking the next server.
  115. Implements twisted.internet.interfaces.IStreamClientEndpoint.
  116. """
  117. def __init__(self, reactor, service, domain, protocol="tcp",
  118. default_port=None, endpoint=HostnameEndpoint,
  119. endpoint_kw_args={}):
  120. self.reactor = reactor
  121. self.service_name = "_%s._%s.%s" % (service, protocol, domain)
  122. if default_port is not None:
  123. self.default_server = Server(
  124. host=domain,
  125. port=default_port,
  126. )
  127. else:
  128. self.default_server = None
  129. self.endpoint = endpoint
  130. self.endpoint_kw_args = endpoint_kw_args
  131. self.servers = None
  132. self.used_servers = None
  133. @defer.inlineCallbacks
  134. def fetch_servers(self):
  135. self.used_servers = []
  136. self.servers = yield resolve_service(self.service_name)
  137. def pick_server(self):
  138. if not self.servers:
  139. if self.used_servers:
  140. self.servers = self.used_servers
  141. self.used_servers = []
  142. self.servers.sort()
  143. elif self.default_server:
  144. return self.default_server
  145. else:
  146. raise ConnectError(
  147. "No server available for %s" % self.service_name
  148. )
  149. # look for all servers with the same priority
  150. min_priority = self.servers[0].priority
  151. weight_indexes = list(
  152. (index, server.weight + 1)
  153. for index, server in enumerate(self.servers)
  154. if server.priority == min_priority
  155. )
  156. total_weight = sum(weight for index, weight in weight_indexes)
  157. target_weight = random.randint(0, total_weight)
  158. for index, weight in weight_indexes:
  159. target_weight -= weight
  160. if target_weight <= 0:
  161. server = self.servers[index]
  162. # XXX: this looks totally dubious:
  163. #
  164. # (a) we never reuse a server until we have been through
  165. # all of the servers at the same priority, so if the
  166. # weights are A: 100, B:1, we always do ABABAB instead of
  167. # AAAA...AAAB (approximately).
  168. #
  169. # (b) After using all the servers at the lowest priority,
  170. # we move onto the next priority. We should only use the
  171. # second priority if servers at the top priority are
  172. # unreachable.
  173. #
  174. del self.servers[index]
  175. self.used_servers.append(server)
  176. return server
  177. @defer.inlineCallbacks
  178. def connect(self, protocolFactory):
  179. if self.servers is None:
  180. yield self.fetch_servers()
  181. server = self.pick_server()
  182. logger.info("Connecting to %s:%s", server.host, server.port)
  183. endpoint = self.endpoint(
  184. self.reactor, server.host, server.port, **self.endpoint_kw_args
  185. )
  186. connection = yield endpoint.connect(protocolFactory)
  187. defer.returnValue(connection)