netutil.py 22 KB

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