1import os
2import ssl
3from dataclasses import dataclass
4
5import _ssl
6from typing import Optional
7
8_ssl_module_path = getattr(_ssl, '__file__', None)
9
10
11@dataclass(frozen=True)
12class OpenSSLDynLibs:
13 libssl: str
14 libcrypto: str
15
16 @property
17 def libssl_path(self) -> bytes:
18 return self.libssl.encode()
19
20 @property
21 def libcrypto_path(self) -> bytes:
22 return self.libcrypto.encode()
23
24
25if os.name == "nt":
26 from .utils_win import aiofn_get_openssl_library_paths
27elif os.name == "posix":
28 from .utils_posix import aiofn_get_openssl_library_paths
29else:
30 raise ImportError(f"unsupported platform {os.name}")
31
32
33def _find_openssl_library_paths() -> Optional[OpenSSLDynLibs]:
34 if _ssl_module_path is None:
35 return None
36
37 try:
38 openssl_library_paths = aiofn_get_openssl_library_paths(
39 _ssl_module_path)
40 except OSError as exc:
41 raise ImportError(
42 "aiofastnet could not identify the OpenSSL dynamic libraries "
43 "used by Python's _ssl module"
44 ) from exc
45
46 libssl_path, libcrypto_path = openssl_library_paths
47 return OpenSSLDynLibs(libssl_path, libcrypto_path)
48
49
50OPENSSL_DYN_LIBS = _find_openssl_library_paths()
51
52
53def create_transport_context(server_side, server_hostname):
54 sslcontext = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
55 if not server_hostname:
56 sslcontext.check_hostname = False
57 return sslcontext