netutil.py 20 KB

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