netutil.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #
  2. # Copyright 2011 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # 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, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """Miscellaneous network utility code."""
  16. from __future__ import absolute_import, division, print_function
  17. import errno
  18. import os
  19. import sys
  20. import socket
  21. import stat
  22. from tornado.concurrent import dummy_executor, run_on_executor
  23. from tornado import gen
  24. from tornado.ioloop import IOLoop
  25. from tornado.platform.auto import set_close_exec
  26. from tornado.util import PY3, Configurable, errno_from_exception
  27. try:
  28. import ssl
  29. except ImportError:
  30. # ssl is not available on Google App Engine
  31. ssl = None
  32. if PY3:
  33. xrange = range
  34. if ssl is not None:
  35. # Note that the naming of ssl.Purpose is confusing; the purpose
  36. # of a context is to authentiate the opposite side of the connection.
  37. _client_ssl_defaults = ssl.create_default_context(
  38. ssl.Purpose.SERVER_AUTH)
  39. _server_ssl_defaults = ssl.create_default_context(
  40. ssl.Purpose.CLIENT_AUTH)
  41. if hasattr(ssl, 'OP_NO_COMPRESSION'):
  42. # See netutil.ssl_options_to_context
  43. _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
  44. _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
  45. else:
  46. # Google App Engine
  47. _client_ssl_defaults = dict(cert_reqs=None,
  48. ca_certs=None)
  49. _server_ssl_defaults = {}
  50. # ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,
  51. # getaddrinfo attempts to import encodings.idna. If this is done at
  52. # module-import time, the import lock is already held by the main thread,
  53. # leading to deadlock. Avoid it by caching the idna encoder on the main
  54. # thread now.
  55. u'foo'.encode('idna')
  56. # For undiagnosed reasons, 'latin1' codec may also need to be preloaded.
  57. u'foo'.encode('latin1')
  58. # These errnos indicate that a non-blocking operation must be retried
  59. # at a later time. On most platforms they're the same value, but on
  60. # some they differ.
  61. _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)
  62. if hasattr(errno, "WSAEWOULDBLOCK"):
  63. _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,) # type: ignore
  64. # Default backlog used when calling sock.listen()
  65. _DEFAULT_BACKLOG = 128
  66. def bind_sockets(port, address=None, family=socket.AF_UNSPEC,
  67. backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):
  68. """Creates listening sockets bound to the given port and address.
  69. Returns a list of socket objects (multiple sockets are returned if
  70. the given address maps to multiple IP addresses, which is most common
  71. for mixed IPv4 and IPv6 use).
  72. Address may be either an IP address or hostname. If it's a hostname,
  73. the server will listen on all IP addresses associated with the
  74. name. Address may be an empty string or None to listen on all
  75. available interfaces. Family may be set to either `socket.AF_INET`
  76. or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
  77. both will be used if available.
  78. The ``backlog`` argument has the same meaning as for
  79. `socket.listen() <socket.socket.listen>`.
  80. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
  81. ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
  82. ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
  83. in the list. If your platform doesn't support this option ValueError will
  84. be raised.
  85. """
  86. if reuse_port and not hasattr(socket, "SO_REUSEPORT"):
  87. raise ValueError("the platform doesn't support SO_REUSEPORT")
  88. sockets = []
  89. if address == "":
  90. address = None
  91. if not socket.has_ipv6 and family == socket.AF_UNSPEC:
  92. # Python can be compiled with --disable-ipv6, which causes
  93. # operations on AF_INET6 sockets to fail, but does not
  94. # automatically exclude those results from getaddrinfo
  95. # results.
  96. # http://bugs.python.org/issue16208
  97. family = socket.AF_INET
  98. if flags is None:
  99. flags = socket.AI_PASSIVE
  100. bound_port = None
  101. for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
  102. 0, flags)):
  103. af, socktype, proto, canonname, sockaddr = res
  104. if (sys.platform == 'darwin' and address == 'localhost' and
  105. af == socket.AF_INET6 and sockaddr[3] != 0):
  106. # Mac OS X includes a link-local address fe80::1%lo0 in the
  107. # getaddrinfo results for 'localhost'. However, the firewall
  108. # doesn't understand that this is a local address and will
  109. # prompt for access (often repeatedly, due to an apparent
  110. # bug in its ability to remember granting access to an
  111. # application). Skip these addresses.
  112. continue
  113. try:
  114. sock = socket.socket(af, socktype, proto)
  115. except socket.error as e:
  116. if errno_from_exception(e) == errno.EAFNOSUPPORT:
  117. continue
  118. raise
  119. set_close_exec(sock.fileno())
  120. if os.name != 'nt':
  121. try:
  122. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  123. except socket.error as e:
  124. if errno_from_exception(e) != errno.ENOPROTOOPT:
  125. # Hurd doesn't support SO_REUSEADDR.
  126. raise
  127. if reuse_port:
  128. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  129. if af == socket.AF_INET6:
  130. # On linux, ipv6 sockets accept ipv4 too by default,
  131. # but this makes it impossible to bind to both
  132. # 0.0.0.0 in ipv4 and :: in ipv6. On other systems,
  133. # separate sockets *must* be used to listen for both ipv4
  134. # and ipv6. For consistency, always disable ipv4 on our
  135. # ipv6 sockets and use a separate ipv4 socket when needed.
  136. #
  137. # Python 2.x on windows doesn't have IPPROTO_IPV6.
  138. if hasattr(socket, "IPPROTO_IPV6"):
  139. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  140. # automatic port allocation with port=None
  141. # should bind on the same port on IPv4 and IPv6
  142. host, requested_port = sockaddr[:2]
  143. if requested_port == 0 and bound_port is not None:
  144. sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))
  145. sock.setblocking(0)
  146. sock.bind(sockaddr)
  147. bound_port = sock.getsockname()[1]
  148. sock.listen(backlog)
  149. sockets.append(sock)
  150. return sockets
  151. if hasattr(socket, 'AF_UNIX'):
  152. def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):
  153. """Creates a listening unix socket.
  154. If a socket with the given name already exists, it will be deleted.
  155. If any other file with that name exists, an exception will be
  156. raised.
  157. Returns a socket object (not a list of socket objects like
  158. `bind_sockets`)
  159. """
  160. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  161. set_close_exec(sock.fileno())
  162. try:
  163. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  164. except socket.error as e:
  165. if errno_from_exception(e) != errno.ENOPROTOOPT:
  166. # Hurd doesn't support SO_REUSEADDR
  167. raise
  168. sock.setblocking(0)
  169. try:
  170. st = os.stat(file)
  171. except OSError as err:
  172. if errno_from_exception(err) != errno.ENOENT:
  173. raise
  174. else:
  175. if stat.S_ISSOCK(st.st_mode):
  176. os.remove(file)
  177. else:
  178. raise ValueError("File %s exists and is not a socket", file)
  179. sock.bind(file)
  180. os.chmod(file, mode)
  181. sock.listen(backlog)
  182. return sock
  183. def add_accept_handler(sock, callback):
  184. """Adds an `.IOLoop` event handler to accept new connections on ``sock``.
  185. When a connection is accepted, ``callback(connection, address)`` will
  186. be run (``connection`` is a socket object, and ``address`` is the
  187. address of the other end of the connection). Note that this signature
  188. is different from the ``callback(fd, events)`` signature used for
  189. `.IOLoop` handlers.
  190. A callable is returned which, when called, will remove the `.IOLoop`
  191. event handler and stop processing further incoming connections.
  192. .. versionchanged:: 5.0
  193. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  194. .. versionchanged:: 5.0
  195. A callable is returned (``None`` was returned before).
  196. """
  197. io_loop = IOLoop.current()
  198. removed = [False]
  199. def accept_handler(fd, events):
  200. # More connections may come in while we're handling callbacks;
  201. # to prevent starvation of other tasks we must limit the number
  202. # of connections we accept at a time. Ideally we would accept
  203. # up to the number of connections that were waiting when we
  204. # entered this method, but this information is not available
  205. # (and rearranging this method to call accept() as many times
  206. # as possible before running any callbacks would have adverse
  207. # effects on load balancing in multiprocess configurations).
  208. # Instead, we use the (default) listen backlog as a rough
  209. # heuristic for the number of connections we can reasonably
  210. # accept at once.
  211. for i in xrange(_DEFAULT_BACKLOG):
  212. if removed[0]:
  213. # The socket was probably closed
  214. return
  215. try:
  216. connection, address = sock.accept()
  217. except socket.error as e:
  218. # _ERRNO_WOULDBLOCK indicate we have accepted every
  219. # connection that is available.
  220. if errno_from_exception(e) in _ERRNO_WOULDBLOCK:
  221. return
  222. # ECONNABORTED indicates that there was a connection
  223. # but it was closed while still in the accept queue.
  224. # (observed on FreeBSD).
  225. if errno_from_exception(e) == errno.ECONNABORTED:
  226. continue
  227. raise
  228. set_close_exec(connection.fileno())
  229. callback(connection, address)
  230. def remove_handler():
  231. io_loop.remove_handler(sock)
  232. removed[0] = True
  233. io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  234. return remove_handler
  235. def is_valid_ip(ip):
  236. """Returns true if the given string is a well-formed IP address.
  237. Supports IPv4 and IPv6.
  238. """
  239. if not ip or '\x00' in ip:
  240. # getaddrinfo resolves empty strings to localhost, and truncates
  241. # on zero bytes.
  242. return False
  243. try:
  244. res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
  245. socket.SOCK_STREAM,
  246. 0, socket.AI_NUMERICHOST)
  247. return bool(res)
  248. except socket.gaierror as e:
  249. if e.args[0] == socket.EAI_NONAME:
  250. return False
  251. raise
  252. return True
  253. class Resolver(Configurable):
  254. """Configurable asynchronous DNS resolver interface.
  255. By default, a blocking implementation is used (which simply calls
  256. `socket.getaddrinfo`). An alternative implementation can be
  257. chosen with the `Resolver.configure <.Configurable.configure>`
  258. class method::
  259. Resolver.configure('tornado.netutil.ThreadedResolver')
  260. The implementations of this interface included with Tornado are
  261. * `tornado.netutil.DefaultExecutorResolver`
  262. * `tornado.netutil.BlockingResolver` (deprecated)
  263. * `tornado.netutil.ThreadedResolver` (deprecated)
  264. * `tornado.netutil.OverrideResolver`
  265. * `tornado.platform.twisted.TwistedResolver`
  266. * `tornado.platform.caresresolver.CaresResolver`
  267. .. versionchanged:: 5.0
  268. The default implementation has changed from `BlockingResolver` to
  269. `DefaultExecutorResolver`.
  270. """
  271. @classmethod
  272. def configurable_base(cls):
  273. return Resolver
  274. @classmethod
  275. def configurable_default(cls):
  276. return DefaultExecutorResolver
  277. def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
  278. """Resolves an address.
  279. The ``host`` argument is a string which may be a hostname or a
  280. literal IP address.
  281. Returns a `.Future` whose result is a list of (family,
  282. address) pairs, where address is a tuple suitable to pass to
  283. `socket.connect <socket.socket.connect>` (i.e. a ``(host,
  284. port)`` pair for IPv4; additional fields may be present for
  285. IPv6). If a ``callback`` is passed, it will be run with the
  286. result as an argument when it is complete.
  287. :raises IOError: if the address cannot be resolved.
  288. .. versionchanged:: 4.4
  289. Standardized all implementations to raise `IOError`.
  290. .. deprecated:: 5.1
  291. The ``callback`` argument is deprecated and will be removed in 6.0.
  292. Use the returned awaitable object instead.
  293. """
  294. raise NotImplementedError()
  295. def close(self):
  296. """Closes the `Resolver`, freeing any resources used.
  297. .. versionadded:: 3.1
  298. """
  299. pass
  300. def _resolve_addr(host, port, family=socket.AF_UNSPEC):
  301. # On Solaris, getaddrinfo fails if the given port is not found
  302. # in /etc/services and no socket type is given, so we must pass
  303. # one here. The socket type used here doesn't seem to actually
  304. # matter (we discard the one we get back in the results),
  305. # so the addresses we return should still be usable with SOCK_DGRAM.
  306. addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
  307. results = []
  308. for family, socktype, proto, canonname, address in addrinfo:
  309. results.append((family, address))
  310. return results
  311. class DefaultExecutorResolver(Resolver):
  312. """Resolver implementation using `.IOLoop.run_in_executor`.
  313. .. versionadded:: 5.0
  314. """
  315. @gen.coroutine
  316. def resolve(self, host, port, family=socket.AF_UNSPEC):
  317. result = yield IOLoop.current().run_in_executor(
  318. None, _resolve_addr, host, port, family)
  319. raise gen.Return(result)
  320. class ExecutorResolver(Resolver):
  321. """Resolver implementation using a `concurrent.futures.Executor`.
  322. Use this instead of `ThreadedResolver` when you require additional
  323. control over the executor being used.
  324. The executor will be shut down when the resolver is closed unless
  325. ``close_resolver=False``; use this if you want to reuse the same
  326. executor elsewhere.
  327. .. versionchanged:: 5.0
  328. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  329. .. deprecated:: 5.0
  330. The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
  331. of this class.
  332. """
  333. def initialize(self, executor=None, close_executor=True):
  334. self.io_loop = IOLoop.current()
  335. if executor is not None:
  336. self.executor = executor
  337. self.close_executor = close_executor
  338. else:
  339. self.executor = dummy_executor
  340. self.close_executor = False
  341. def close(self):
  342. if self.close_executor:
  343. self.executor.shutdown()
  344. self.executor = None
  345. @run_on_executor
  346. def resolve(self, host, port, family=socket.AF_UNSPEC):
  347. return _resolve_addr(host, port, family)
  348. class BlockingResolver(ExecutorResolver):
  349. """Default `Resolver` implementation, using `socket.getaddrinfo`.
  350. The `.IOLoop` will be blocked during the resolution, although the
  351. callback will not be run until the next `.IOLoop` iteration.
  352. .. deprecated:: 5.0
  353. The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
  354. of this class.
  355. """
  356. def initialize(self):
  357. super(BlockingResolver, self).initialize()
  358. class ThreadedResolver(ExecutorResolver):
  359. """Multithreaded non-blocking `Resolver` implementation.
  360. Requires the `concurrent.futures` package to be installed
  361. (available in the standard library since Python 3.2,
  362. installable with ``pip install futures`` in older versions).
  363. The thread pool size can be configured with::
  364. Resolver.configure('tornado.netutil.ThreadedResolver',
  365. num_threads=10)
  366. .. versionchanged:: 3.1
  367. All ``ThreadedResolvers`` share a single thread pool, whose
  368. size is set by the first one to be created.
  369. .. deprecated:: 5.0
  370. The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
  371. of this class.
  372. """
  373. _threadpool = None # type: ignore
  374. _threadpool_pid = None # type: int
  375. def initialize(self, num_threads=10):
  376. threadpool = ThreadedResolver._create_threadpool(num_threads)
  377. super(ThreadedResolver, self).initialize(
  378. executor=threadpool, close_executor=False)
  379. @classmethod
  380. def _create_threadpool(cls, num_threads):
  381. pid = os.getpid()
  382. if cls._threadpool_pid != pid:
  383. # Threads cannot survive after a fork, so if our pid isn't what it
  384. # was when we created the pool then delete it.
  385. cls._threadpool = None
  386. if cls._threadpool is None:
  387. from concurrent.futures import ThreadPoolExecutor
  388. cls._threadpool = ThreadPoolExecutor(num_threads)
  389. cls._threadpool_pid = pid
  390. return cls._threadpool
  391. class OverrideResolver(Resolver):
  392. """Wraps a resolver with a mapping of overrides.
  393. This can be used to make local DNS changes (e.g. for testing)
  394. without modifying system-wide settings.
  395. The mapping can be in three formats::
  396. {
  397. # Hostname to host or ip
  398. "example.com": "127.0.1.1",
  399. # Host+port to host+port
  400. ("login.example.com", 443): ("localhost", 1443),
  401. # Host+port+address family to host+port
  402. ("login.example.com", 443, socket.AF_INET6): ("::1", 1443),
  403. }
  404. .. versionchanged:: 5.0
  405. Added support for host-port-family triplets.
  406. """
  407. def initialize(self, resolver, mapping):
  408. self.resolver = resolver
  409. self.mapping = mapping
  410. def close(self):
  411. self.resolver.close()
  412. def resolve(self, host, port, family=socket.AF_UNSPEC, *args, **kwargs):
  413. if (host, port, family) in self.mapping:
  414. host, port = self.mapping[(host, port, family)]
  415. elif (host, port) in self.mapping:
  416. host, port = self.mapping[(host, port)]
  417. elif host in self.mapping:
  418. host = self.mapping[host]
  419. return self.resolver.resolve(host, port, family, *args, **kwargs)
  420. # These are the keyword arguments to ssl.wrap_socket that must be translated
  421. # to their SSLContext equivalents (the other arguments are still passed
  422. # to SSLContext.wrap_socket).
  423. _SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',
  424. 'cert_reqs', 'ca_certs', 'ciphers'])
  425. def ssl_options_to_context(ssl_options):
  426. """Try to convert an ``ssl_options`` dictionary to an
  427. `~ssl.SSLContext` object.
  428. The ``ssl_options`` dictionary contains keywords to be passed to
  429. `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can
  430. be used instead. This function converts the dict form to its
  431. `~ssl.SSLContext` equivalent, and may be used when a component which
  432. accepts both forms needs to upgrade to the `~ssl.SSLContext` version
  433. to use features like SNI or NPN.
  434. """
  435. if isinstance(ssl_options, ssl.SSLContext):
  436. return ssl_options
  437. assert isinstance(ssl_options, dict)
  438. assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
  439. # Can't use create_default_context since this interface doesn't
  440. # tell us client vs server.
  441. context = ssl.SSLContext(
  442. ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))
  443. if 'certfile' in ssl_options:
  444. context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))
  445. if 'cert_reqs' in ssl_options:
  446. context.verify_mode = ssl_options['cert_reqs']
  447. if 'ca_certs' in ssl_options:
  448. context.load_verify_locations(ssl_options['ca_certs'])
  449. if 'ciphers' in ssl_options:
  450. context.set_ciphers(ssl_options['ciphers'])
  451. if hasattr(ssl, 'OP_NO_COMPRESSION'):
  452. # Disable TLS compression to avoid CRIME and related attacks.
  453. # This constant depends on openssl version 1.0.
  454. # TODO: Do we need to do this ourselves or can we trust
  455. # the defaults?
  456. context.options |= ssl.OP_NO_COMPRESSION
  457. return context
  458. def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
  459. """Returns an ``ssl.SSLSocket`` wrapping the given socket.
  460. ``ssl_options`` may be either an `ssl.SSLContext` object or a
  461. dictionary (as accepted by `ssl_options_to_context`). Additional
  462. keyword arguments are passed to ``wrap_socket`` (either the
  463. `~ssl.SSLContext` method or the `ssl` module function as
  464. appropriate).
  465. """
  466. context = ssl_options_to_context(ssl_options)
  467. if ssl.HAS_SNI:
  468. # In python 3.4, wrap_socket only accepts the server_hostname
  469. # argument if HAS_SNI is true.
  470. # TODO: add a unittest (python added server-side SNI support in 3.4)
  471. # In the meantime it can be manually tested with
  472. # python3 -m tornado.httpclient https://sni.velox.ch
  473. return context.wrap_socket(socket, server_hostname=server_hostname,
  474. **kwargs)
  475. else:
  476. return context.wrap_socket(socket, **kwargs)