Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/tornado/netutil.py: 26%

226 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

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 

16"""Miscellaneous network utility code.""" 

17 

18import asyncio 

19import concurrent.futures 

20import errno 

21import os 

22import sys 

23import socket 

24import ssl 

25import stat 

26 

27from tornado.concurrent import dummy_executor, run_on_executor 

28from tornado.ioloop import IOLoop 

29from tornado.util import Configurable, errno_from_exception 

30 

31from typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional 

32 

33# Note that the naming of ssl.Purpose is confusing; the purpose 

34# of a context is to authenticate the opposite side of the connection. 

35_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) 

36_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) 

37if hasattr(ssl, "OP_NO_COMPRESSION"): 

38 # See netutil.ssl_options_to_context 

39 _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION 

40 _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION 

41 

42# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode, 

43# getaddrinfo attempts to import encodings.idna. If this is done at 

44# module-import time, the import lock is already held by the main thread, 

45# leading to deadlock. Avoid it by caching the idna encoder on the main 

46# thread now. 

47"foo".encode("idna") 

48 

49# For undiagnosed reasons, 'latin1' codec may also need to be preloaded. 

50"foo".encode("latin1") 

51 

52# Default backlog used when calling sock.listen() 

53_DEFAULT_BACKLOG = 128 

54 

55 

56def bind_sockets( 

57 port: int, 

58 address: Optional[str] = None, 

59 family: socket.AddressFamily = socket.AF_UNSPEC, 

60 backlog: int = _DEFAULT_BACKLOG, 

61 flags: Optional[int] = None, 

62 reuse_port: bool = False, 

63) -> List[socket.socket]: 

64 """Creates listening sockets bound to the given port and address. 

65 

66 Returns a list of socket objects (multiple sockets are returned if 

67 the given address maps to multiple IP addresses, which is most common 

68 for mixed IPv4 and IPv6 use). 

69 

70 Address may be either an IP address or hostname. If it's a hostname, 

71 the server will listen on all IP addresses associated with the 

72 name. Address may be an empty string or None to listen on all 

73 available interfaces. Family may be set to either `socket.AF_INET` 

74 or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise 

75 both will be used if available. 

76 

77 The ``backlog`` argument has the same meaning as for 

78 `socket.listen() <socket.socket.listen>`. 

79 

80 ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like 

81 ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. 

82 

83 ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket 

84 in the list. If your platform doesn't support this option ValueError will 

85 be raised. 

86 """ 

87 if reuse_port and not hasattr(socket, "SO_REUSEPORT"): 

88 raise ValueError("the platform doesn't support SO_REUSEPORT") 

89 

90 sockets = [] 

91 if address == "": 

92 address = None 

93 if not socket.has_ipv6 and family == socket.AF_UNSPEC: 

94 # Python can be compiled with --disable-ipv6, which causes 

95 # operations on AF_INET6 sockets to fail, but does not 

96 # automatically exclude those results from getaddrinfo 

97 # results. 

98 # http://bugs.python.org/issue16208 

99 family = socket.AF_INET 

100 if flags is None: 

101 flags = socket.AI_PASSIVE 

102 bound_port = None 

103 unique_addresses = set() # type: set 

104 for res in sorted( 

105 socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags), 

106 key=lambda x: x[0], 

107 ): 

108 if res in unique_addresses: 

109 continue 

110 

111 unique_addresses.add(res) 

112 

113 af, socktype, proto, canonname, sockaddr = res 

114 if ( 

115 sys.platform == "darwin" 

116 and address == "localhost" 

117 and af == socket.AF_INET6 

118 and sockaddr[3] != 0 # type: ignore 

119 ): 

120 # Mac OS X includes a link-local address fe80::1%lo0 in the 

121 # getaddrinfo results for 'localhost'. However, the firewall 

122 # doesn't understand that this is a local address and will 

123 # prompt for access (often repeatedly, due to an apparent 

124 # bug in its ability to remember granting access to an 

125 # application). Skip these addresses. 

126 continue 

127 try: 

128 sock = socket.socket(af, socktype, proto) 

129 except socket.error as e: 

130 if errno_from_exception(e) == errno.EAFNOSUPPORT: 

131 continue 

132 raise 

133 if os.name != "nt": 

134 try: 

135 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

136 except socket.error as e: 

137 if errno_from_exception(e) != errno.ENOPROTOOPT: 

138 # Hurd doesn't support SO_REUSEADDR. 

139 raise 

140 if reuse_port: 

141 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) 

142 if af == socket.AF_INET6: 

143 # On linux, ipv6 sockets accept ipv4 too by default, 

144 # but this makes it impossible to bind to both 

145 # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, 

146 # separate sockets *must* be used to listen for both ipv4 

147 # and ipv6. For consistency, always disable ipv4 on our 

148 # ipv6 sockets and use a separate ipv4 socket when needed. 

149 # 

150 # Python 2.x on windows doesn't have IPPROTO_IPV6. 

151 if hasattr(socket, "IPPROTO_IPV6"): 

152 sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) 

153 

154 # automatic port allocation with port=None 

155 # should bind on the same port on IPv4 and IPv6 

156 host, requested_port = sockaddr[:2] 

157 if requested_port == 0 and bound_port is not None: 

158 sockaddr = tuple([host, bound_port] + list(sockaddr[2:])) 

159 

160 sock.setblocking(False) 

161 try: 

162 sock.bind(sockaddr) 

163 except OSError as e: 

164 if ( 

165 errno_from_exception(e) == errno.EADDRNOTAVAIL 

166 and address == "localhost" 

167 and sockaddr[0] == "::1" 

168 ): 

169 # On some systems (most notably docker with default 

170 # configurations), ipv6 is partially disabled: 

171 # socket.has_ipv6 is true, we can create AF_INET6 

172 # sockets, and getaddrinfo("localhost", ..., 

173 # AF_PASSIVE) resolves to ::1, but we get an error 

174 # when binding. 

175 # 

176 # Swallow the error, but only for this specific case. 

177 # If EADDRNOTAVAIL occurs in other situations, it 

178 # might be a real problem like a typo in a 

179 # configuration. 

180 sock.close() 

181 continue 

182 else: 

183 raise 

184 bound_port = sock.getsockname()[1] 

185 sock.listen(backlog) 

186 sockets.append(sock) 

187 return sockets 

188 

189 

190if hasattr(socket, "AF_UNIX"): 

191 

192 def bind_unix_socket( 

193 file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG 

194 ) -> socket.socket: 

195 """Creates a listening unix socket. 

196 

197 If a socket with the given name already exists, it will be deleted. 

198 If any other file with that name exists, an exception will be 

199 raised. 

200 

201 Returns a socket object (not a list of socket objects like 

202 `bind_sockets`) 

203 """ 

204 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 

205 try: 

206 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

207 except socket.error as e: 

208 if errno_from_exception(e) != errno.ENOPROTOOPT: 

209 # Hurd doesn't support SO_REUSEADDR 

210 raise 

211 sock.setblocking(False) 

212 try: 

213 st = os.stat(file) 

214 except FileNotFoundError: 

215 pass 

216 else: 

217 if stat.S_ISSOCK(st.st_mode): 

218 os.remove(file) 

219 else: 

220 raise ValueError("File %s exists and is not a socket", file) 

221 sock.bind(file) 

222 os.chmod(file, mode) 

223 sock.listen(backlog) 

224 return sock 

225 

226 

227def add_accept_handler( 

228 sock: socket.socket, callback: Callable[[socket.socket, Any], None] 

229) -> Callable[[], None]: 

230 """Adds an `.IOLoop` event handler to accept new connections on ``sock``. 

231 

232 When a connection is accepted, ``callback(connection, address)`` will 

233 be run (``connection`` is a socket object, and ``address`` is the 

234 address of the other end of the connection). Note that this signature 

235 is different from the ``callback(fd, events)`` signature used for 

236 `.IOLoop` handlers. 

237 

238 A callable is returned which, when called, will remove the `.IOLoop` 

239 event handler and stop processing further incoming connections. 

240 

241 .. versionchanged:: 5.0 

242 The ``io_loop`` argument (deprecated since version 4.1) has been removed. 

243 

244 .. versionchanged:: 5.0 

245 A callable is returned (``None`` was returned before). 

246 """ 

247 io_loop = IOLoop.current() 

248 removed = [False] 

249 

250 def accept_handler(fd: socket.socket, events: int) -> None: 

251 # More connections may come in while we're handling callbacks; 

252 # to prevent starvation of other tasks we must limit the number 

253 # of connections we accept at a time. Ideally we would accept 

254 # up to the number of connections that were waiting when we 

255 # entered this method, but this information is not available 

256 # (and rearranging this method to call accept() as many times 

257 # as possible before running any callbacks would have adverse 

258 # effects on load balancing in multiprocess configurations). 

259 # Instead, we use the (default) listen backlog as a rough 

260 # heuristic for the number of connections we can reasonably 

261 # accept at once. 

262 for i in range(_DEFAULT_BACKLOG): 

263 if removed[0]: 

264 # The socket was probably closed 

265 return 

266 try: 

267 connection, address = sock.accept() 

268 except BlockingIOError: 

269 # EWOULDBLOCK indicates we have accepted every 

270 # connection that is available. 

271 return 

272 except ConnectionAbortedError: 

273 # ECONNABORTED indicates that there was a connection 

274 # but it was closed while still in the accept queue. 

275 # (observed on FreeBSD). 

276 continue 

277 callback(connection, address) 

278 

279 def remove_handler() -> None: 

280 io_loop.remove_handler(sock) 

281 removed[0] = True 

282 

283 io_loop.add_handler(sock, accept_handler, IOLoop.READ) 

284 return remove_handler 

285 

286 

287def is_valid_ip(ip: str) -> bool: 

288 """Returns ``True`` if the given string is a well-formed IP address. 

289 

290 Supports IPv4 and IPv6. 

291 """ 

292 if not ip or "\x00" in ip: 

293 # getaddrinfo resolves empty strings to localhost, and truncates 

294 # on zero bytes. 

295 return False 

296 try: 

297 res = socket.getaddrinfo( 

298 ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST 

299 ) 

300 return bool(res) 

301 except socket.gaierror as e: 

302 if e.args[0] == socket.EAI_NONAME: 

303 return False 

304 raise 

305 except UnicodeError: 

306 # `socket.getaddrinfo` will raise a UnicodeError from the 

307 # `idna` decoder if the input is longer than 63 characters, 

308 # even for socket.AI_NUMERICHOST. See 

309 # https://bugs.python.org/issue32958 for discussion 

310 return False 

311 return True 

312 

313 

314class Resolver(Configurable): 

315 """Configurable asynchronous DNS resolver interface. 

316 

317 By default, a blocking implementation is used (which simply calls 

318 `socket.getaddrinfo`). An alternative implementation can be 

319 chosen with the `Resolver.configure <.Configurable.configure>` 

320 class method:: 

321 

322 Resolver.configure('tornado.netutil.ThreadedResolver') 

323 

324 The implementations of this interface included with Tornado are 

325 

326 * `tornado.netutil.DefaultLoopResolver` 

327 * `tornado.netutil.DefaultExecutorResolver` (deprecated) 

328 * `tornado.netutil.BlockingResolver` (deprecated) 

329 * `tornado.netutil.ThreadedResolver` (deprecated) 

330 * `tornado.netutil.OverrideResolver` 

331 * `tornado.platform.twisted.TwistedResolver` (deprecated) 

332 * `tornado.platform.caresresolver.CaresResolver` (deprecated) 

333 

334 .. versionchanged:: 5.0 

335 The default implementation has changed from `BlockingResolver` to 

336 `DefaultExecutorResolver`. 

337 

338 .. versionchanged:: 6.2 

339 The default implementation has changed from `DefaultExecutorResolver` to 

340 `DefaultLoopResolver`. 

341 """ 

342 

343 @classmethod 

344 def configurable_base(cls) -> Type["Resolver"]: 

345 return Resolver 

346 

347 @classmethod 

348 def configurable_default(cls) -> Type["Resolver"]: 

349 return DefaultLoopResolver 

350 

351 def resolve( 

352 self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

353 ) -> Awaitable[List[Tuple[int, Any]]]: 

354 """Resolves an address. 

355 

356 The ``host`` argument is a string which may be a hostname or a 

357 literal IP address. 

358 

359 Returns a `.Future` whose result is a list of (family, 

360 address) pairs, where address is a tuple suitable to pass to 

361 `socket.connect <socket.socket.connect>` (i.e. a ``(host, 

362 port)`` pair for IPv4; additional fields may be present for 

363 IPv6). If a ``callback`` is passed, it will be run with the 

364 result as an argument when it is complete. 

365 

366 :raises IOError: if the address cannot be resolved. 

367 

368 .. versionchanged:: 4.4 

369 Standardized all implementations to raise `IOError`. 

370 

371 .. versionchanged:: 6.0 The ``callback`` argument was removed. 

372 Use the returned awaitable object instead. 

373 

374 """ 

375 raise NotImplementedError() 

376 

377 def close(self) -> None: 

378 """Closes the `Resolver`, freeing any resources used. 

379 

380 .. versionadded:: 3.1 

381 

382 """ 

383 pass 

384 

385 

386def _resolve_addr( 

387 host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

388) -> List[Tuple[int, Any]]: 

389 # On Solaris, getaddrinfo fails if the given port is not found 

390 # in /etc/services and no socket type is given, so we must pass 

391 # one here. The socket type used here doesn't seem to actually 

392 # matter (we discard the one we get back in the results), 

393 # so the addresses we return should still be usable with SOCK_DGRAM. 

394 addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM) 

395 results = [] 

396 for fam, socktype, proto, canonname, address in addrinfo: 

397 results.append((fam, address)) 

398 return results # type: ignore 

399 

400 

401class DefaultExecutorResolver(Resolver): 

402 """Resolver implementation using `.IOLoop.run_in_executor`. 

403 

404 .. versionadded:: 5.0 

405 

406 .. deprecated:: 6.2 

407 

408 Use `DefaultLoopResolver` instead. 

409 """ 

410 

411 async def resolve( 

412 self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

413 ) -> List[Tuple[int, Any]]: 

414 result = await IOLoop.current().run_in_executor( 

415 None, _resolve_addr, host, port, family 

416 ) 

417 return result 

418 

419 

420class DefaultLoopResolver(Resolver): 

421 """Resolver implementation using `asyncio.loop.getaddrinfo`.""" 

422 

423 async def resolve( 

424 self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

425 ) -> List[Tuple[int, Any]]: 

426 # On Solaris, getaddrinfo fails if the given port is not found 

427 # in /etc/services and no socket type is given, so we must pass 

428 # one here. The socket type used here doesn't seem to actually 

429 # matter (we discard the one we get back in the results), 

430 # so the addresses we return should still be usable with SOCK_DGRAM. 

431 return [ 

432 (fam, address) 

433 for fam, _, _, _, address in await asyncio.get_running_loop().getaddrinfo( 

434 host, port, family=family, type=socket.SOCK_STREAM 

435 ) 

436 ] 

437 

438 

439class ExecutorResolver(Resolver): 

440 """Resolver implementation using a `concurrent.futures.Executor`. 

441 

442 Use this instead of `ThreadedResolver` when you require additional 

443 control over the executor being used. 

444 

445 The executor will be shut down when the resolver is closed unless 

446 ``close_resolver=False``; use this if you want to reuse the same 

447 executor elsewhere. 

448 

449 .. versionchanged:: 5.0 

450 The ``io_loop`` argument (deprecated since version 4.1) has been removed. 

451 

452 .. deprecated:: 5.0 

453 The default `Resolver` now uses `asyncio.loop.getaddrinfo`; 

454 use that instead of this class. 

455 """ 

456 

457 def initialize( 

458 self, 

459 executor: Optional[concurrent.futures.Executor] = None, 

460 close_executor: bool = True, 

461 ) -> None: 

462 if executor is not None: 

463 self.executor = executor 

464 self.close_executor = close_executor 

465 else: 

466 self.executor = dummy_executor 

467 self.close_executor = False 

468 

469 def close(self) -> None: 

470 if self.close_executor: 

471 self.executor.shutdown() 

472 self.executor = None # type: ignore 

473 

474 @run_on_executor 

475 def resolve( 

476 self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

477 ) -> List[Tuple[int, Any]]: 

478 return _resolve_addr(host, port, family) 

479 

480 

481class BlockingResolver(ExecutorResolver): 

482 """Default `Resolver` implementation, using `socket.getaddrinfo`. 

483 

484 The `.IOLoop` will be blocked during the resolution, although the 

485 callback will not be run until the next `.IOLoop` iteration. 

486 

487 .. deprecated:: 5.0 

488 The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead 

489 of this class. 

490 """ 

491 

492 def initialize(self) -> None: # type: ignore 

493 super().initialize() 

494 

495 

496class ThreadedResolver(ExecutorResolver): 

497 """Multithreaded non-blocking `Resolver` implementation. 

498 

499 Requires the `concurrent.futures` package to be installed 

500 (available in the standard library since Python 3.2, 

501 installable with ``pip install futures`` in older versions). 

502 

503 The thread pool size can be configured with:: 

504 

505 Resolver.configure('tornado.netutil.ThreadedResolver', 

506 num_threads=10) 

507 

508 .. versionchanged:: 3.1 

509 All ``ThreadedResolvers`` share a single thread pool, whose 

510 size is set by the first one to be created. 

511 

512 .. deprecated:: 5.0 

513 The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead 

514 of this class. 

515 """ 

516 

517 _threadpool = None # type: ignore 

518 _threadpool_pid = None # type: int 

519 

520 def initialize(self, num_threads: int = 10) -> None: # type: ignore 

521 threadpool = ThreadedResolver._create_threadpool(num_threads) 

522 super().initialize(executor=threadpool, close_executor=False) 

523 

524 @classmethod 

525 def _create_threadpool( 

526 cls, num_threads: int 

527 ) -> concurrent.futures.ThreadPoolExecutor: 

528 pid = os.getpid() 

529 if cls._threadpool_pid != pid: 

530 # Threads cannot survive after a fork, so if our pid isn't what it 

531 # was when we created the pool then delete it. 

532 cls._threadpool = None 

533 if cls._threadpool is None: 

534 cls._threadpool = concurrent.futures.ThreadPoolExecutor(num_threads) 

535 cls._threadpool_pid = pid 

536 return cls._threadpool 

537 

538 

539class OverrideResolver(Resolver): 

540 """Wraps a resolver with a mapping of overrides. 

541 

542 This can be used to make local DNS changes (e.g. for testing) 

543 without modifying system-wide settings. 

544 

545 The mapping can be in three formats:: 

546 

547 { 

548 # Hostname to host or ip 

549 "example.com": "127.0.1.1", 

550 

551 # Host+port to host+port 

552 ("login.example.com", 443): ("localhost", 1443), 

553 

554 # Host+port+address family to host+port 

555 ("login.example.com", 443, socket.AF_INET6): ("::1", 1443), 

556 } 

557 

558 .. versionchanged:: 5.0 

559 Added support for host-port-family triplets. 

560 """ 

561 

562 def initialize(self, resolver: Resolver, mapping: dict) -> None: 

563 self.resolver = resolver 

564 self.mapping = mapping 

565 

566 def close(self) -> None: 

567 self.resolver.close() 

568 

569 def resolve( 

570 self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC 

571 ) -> Awaitable[List[Tuple[int, Any]]]: 

572 if (host, port, family) in self.mapping: 

573 host, port = self.mapping[(host, port, family)] 

574 elif (host, port) in self.mapping: 

575 host, port = self.mapping[(host, port)] 

576 elif host in self.mapping: 

577 host = self.mapping[host] 

578 return self.resolver.resolve(host, port, family) 

579 

580 

581# These are the keyword arguments to ssl.wrap_socket that must be translated 

582# to their SSLContext equivalents (the other arguments are still passed 

583# to SSLContext.wrap_socket). 

584_SSL_CONTEXT_KEYWORDS = frozenset( 

585 ["ssl_version", "certfile", "keyfile", "cert_reqs", "ca_certs", "ciphers"] 

586) 

587 

588 

589def ssl_options_to_context( 

590 ssl_options: Union[Dict[str, Any], ssl.SSLContext], 

591 server_side: Optional[bool] = None, 

592) -> ssl.SSLContext: 

593 """Try to convert an ``ssl_options`` dictionary to an 

594 `~ssl.SSLContext` object. 

595 

596 The ``ssl_options`` dictionary contains keywords to be passed to 

597 `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can 

598 be used instead. This function converts the dict form to its 

599 `~ssl.SSLContext` equivalent, and may be used when a component which 

600 accepts both forms needs to upgrade to the `~ssl.SSLContext` version 

601 to use features like SNI or NPN. 

602 

603 .. versionchanged:: 6.2 

604 

605 Added server_side argument. Omitting this argument will 

606 result in a DeprecationWarning on Python 3.10. 

607 

608 """ 

609 if isinstance(ssl_options, ssl.SSLContext): 

610 return ssl_options 

611 assert isinstance(ssl_options, dict) 

612 assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options 

613 # TODO: Now that we have the server_side argument, can we switch to 

614 # create_default_context or would that change behavior? 

615 default_version = ssl.PROTOCOL_TLS 

616 if server_side: 

617 default_version = ssl.PROTOCOL_TLS_SERVER 

618 elif server_side is not None: 

619 default_version = ssl.PROTOCOL_TLS_CLIENT 

620 context = ssl.SSLContext(ssl_options.get("ssl_version", default_version)) 

621 if "certfile" in ssl_options: 

622 context.load_cert_chain( 

623 ssl_options["certfile"], ssl_options.get("keyfile", None) 

624 ) 

625 if "cert_reqs" in ssl_options: 

626 if ssl_options["cert_reqs"] == ssl.CERT_NONE: 

627 # This may have been set automatically by PROTOCOL_TLS_CLIENT but is 

628 # incompatible with CERT_NONE so we must manually clear it. 

629 context.check_hostname = False 

630 context.verify_mode = ssl_options["cert_reqs"] 

631 if "ca_certs" in ssl_options: 

632 context.load_verify_locations(ssl_options["ca_certs"]) 

633 if "ciphers" in ssl_options: 

634 context.set_ciphers(ssl_options["ciphers"]) 

635 if hasattr(ssl, "OP_NO_COMPRESSION"): 

636 # Disable TLS compression to avoid CRIME and related attacks. 

637 # This constant depends on openssl version 1.0. 

638 # TODO: Do we need to do this ourselves or can we trust 

639 # the defaults? 

640 context.options |= ssl.OP_NO_COMPRESSION 

641 return context 

642 

643 

644def ssl_wrap_socket( 

645 socket: socket.socket, 

646 ssl_options: Union[Dict[str, Any], ssl.SSLContext], 

647 server_hostname: Optional[str] = None, 

648 server_side: Optional[bool] = None, 

649 **kwargs: Any 

650) -> ssl.SSLSocket: 

651 """Returns an ``ssl.SSLSocket`` wrapping the given socket. 

652 

653 ``ssl_options`` may be either an `ssl.SSLContext` object or a 

654 dictionary (as accepted by `ssl_options_to_context`). Additional 

655 keyword arguments are passed to ``wrap_socket`` (either the 

656 `~ssl.SSLContext` method or the `ssl` module function as 

657 appropriate). 

658 

659 .. versionchanged:: 6.2 

660 

661 Added server_side argument. Omitting this argument will 

662 result in a DeprecationWarning on Python 3.10. 

663 """ 

664 context = ssl_options_to_context(ssl_options, server_side=server_side) 

665 if server_side is None: 

666 server_side = False 

667 if ssl.HAS_SNI: 

668 # In python 3.4, wrap_socket only accepts the server_hostname 

669 # argument if HAS_SNI is true. 

670 # TODO: add a unittest (python added server-side SNI support in 3.4) 

671 # In the meantime it can be manually tested with 

672 # python3 -m tornado.httpclient https://sni.velox.ch 

673 return context.wrap_socket( 

674 socket, server_hostname=server_hostname, server_side=server_side, **kwargs 

675 ) 

676 else: 

677 return context.wrap_socket(socket, server_side=server_side, **kwargs)