Debian Codegraph @

debian/vendor/hypercorn/config.py

raw
1 from __future__ import annotations
2
3 import importlib
4 import importlib.util
5 import logging
6 import os
7 import socket
8 import stat
9 import sys
10 import types
11 import warnings
12 from dataclasses import dataclass
13 from ssl import (
14 create_default_context,
15 OP_NO_COMPRESSION,
16 Purpose,
17 SSLContext,
18 TLSVersion,
19 VerifyFlags,
20 VerifyMode,
21 )
22 from time import time
23 from typing import Any, AnyStr, Dict, List, Mapping, Optional, Tuple, Type, Union
24 from wsgiref.handlers import format_date_time
25
26 if sys.version_info >= (3, 11):
27 import tomllib
28 else:
29 import tomli as tomllib
30
31 from .logging import Logger
32
33 BYTES = 1
34 OCTETS = 1
35 SECONDS = 1.0
36
37 FilePath = Union[AnyStr, os.PathLike]
38 SocketKind = Union[int, socket.SocketKind]
39
40
41 @dataclass
42 class Sockets:
43 secure_sockets: List[socket.socket]
44 insecure_sockets: List[socket.socket]
45 quic_sockets: List[socket.socket]
46
47
48 class SocketTypeError(Exception):
49 def __init__(self, expected: SocketKind, actual: SocketKind) -> None:
50 super().__init__(
51 f'Unexpected socket type, wanted "{socket.SocketKind(expected)}" got '
52 f'"{socket.SocketKind(actual)}"'
53 )
54
55
56 class Config:
57 _bind = ["127.0.0.1:8000"]
58 _insecure_bind: List[str] = []
59 _quic_bind: List[str] = []
60 _quic_addresses: List[Tuple] = []
61 _log: Optional[Logger] = None
62 _root_path: str = ""
63
64 access_log_format = '%(h)s %(l)s %(l)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
65 accesslog: Union[logging.Logger, str, None] = None
66 alpn_protocols = ["h2", "http/1.1"]
67 alt_svc_headers: List[str] = []
68 application_path: str
69 backlog = 100
70 ca_certs: Optional[str] = None
71 certfile: Optional[str] = None
72 ciphers: str = "ECDHE+AESGCM"
73 debug = False
74 dogstatsd_tags = ""
75 errorlog: Union[logging.Logger, str, None] = "-"
76 graceful_timeout: float = 3 * SECONDS
77 read_timeout: Optional[int] = None
78 group: Optional[int] = None
79 h11_max_incomplete_size = 16 * 1024 * BYTES
80 h11_pass_raw_headers = False
81 h2_max_concurrent_streams = 100
82 h2_max_header_list_size = 2**16
83 h2_max_inbound_frame_size = 2**14 * OCTETS
84 include_date_header = True
85 include_server_header = True
86 keep_alive_timeout = 5 * SECONDS
87 keyfile: Optional[str] = None
88 keyfile_password: Optional[str] = None
89 logconfig: Optional[str] = None
90 logconfig_dict: Optional[dict] = None
91 logger_class = Logger
92 loglevel: str = "INFO"
93 max_app_queue_size: int = 10
94 pid_path: Optional[str] = None
95 server_names: List[str] = []
96 shutdown_timeout = 60 * SECONDS
97 ssl_handshake_timeout = 60 * SECONDS
98 startup_timeout = 60 * SECONDS
99 statsd_host: Optional[str] = None
100 statsd_prefix = ""
101 umask: Optional[int] = None
102 use_reloader = False
103 user: Optional[int] = None
104 verify_flags: Optional[VerifyFlags] = None
105 verify_mode: Optional[VerifyMode] = None
106 websocket_max_message_size = 16 * 1024 * 1024 * BYTES
107 websocket_ping_interval: Optional[float] = None
108 worker_class = "asyncio"
109 workers = 1
110 wsgi_max_body_size = 16 * 1024 * 1024 * BYTES
111
112 def set_cert_reqs(self, value: int) -> None:
113 warnings.warn("Please use verify_mode instead", Warning)
114 self.verify_mode = VerifyMode(value)
115
116 cert_reqs = property(None, set_cert_reqs)
117
118 @property
119 def log(self) -> Logger:
120 if self._log is None:
121 self._log = self.logger_class(self)
122 return self._log
123
124 @property
125 def bind(self) -> List[str]:
126 return self._bind
127
128 @bind.setter
129 def bind(self, value: Union[List[str], str]) -> None:
130 if isinstance(value, str):
131 self._bind = [value]
132 else:
133 self._bind = value
134
135 @property
136 def insecure_bind(self) -> List[str]:
137 return self._insecure_bind
138
139 @insecure_bind.setter
140 def insecure_bind(self, value: Union[List[str], str]) -> None:
141 if isinstance(value, str):
142 self._insecure_bind = [value]
143 else:
144 self._insecure_bind = value
145
146 @property
147 def quic_bind(self) -> List[str]:
148 return self._quic_bind
149
150 @quic_bind.setter
151 def quic_bind(self, value: Union[List[str], str]) -> None:
152 if isinstance(value, str):
153 self._quic_bind = [value]
154 else:
155 self._quic_bind = value
156
157 @property
158 def root_path(self) -> str:
159 return self._root_path
160
161 @root_path.setter
162 def root_path(self, value: str) -> None:
163 self._root_path = value.rstrip("/")
164
165 def create_ssl_context(self) -> Optional[SSLContext]:
166 if not self.ssl_enabled:
167 return None
168
169 context = create_default_context(Purpose.CLIENT_AUTH)
170 context.set_ciphers(self.ciphers)
171 context.minimum_version = TLSVersion.TLSv1_2 # RFC 7540 Section 9.2: MUST be TLS >=1.2
172 context.options = OP_NO_COMPRESSION # RFC 7540 Section 9.2.1: MUST disable compression
173 context.set_alpn_protocols(self.alpn_protocols)
174
175 if self.certfile is not None and self.keyfile is not None:
176 context.load_cert_chain(
177 certfile=self.certfile,
178 keyfile=self.keyfile,
179 password=self.keyfile_password,
180 )
181
182 if self.ca_certs is not None:
183 context.load_verify_locations(self.ca_certs)
184 if self.verify_mode is not None:
185 context.verify_mode = self.verify_mode
186 if self.verify_flags is not None:
187 context.verify_flags = self.verify_flags
188
189 return context
190
191 @property
192 def ssl_enabled(self) -> bool:
193 return self.certfile is not None and self.keyfile is not None
194
195 def create_sockets(self) -> Sockets:
196 if self.ssl_enabled:
197 secure_sockets = self._create_sockets(self.bind)
198 insecure_sockets = self._create_sockets(self.insecure_bind)
199 quic_sockets = self._create_sockets(self.quic_bind, socket.SOCK_DGRAM)
200 self._set_quic_addresses(quic_sockets)
201 else:
202 secure_sockets = []
203 insecure_sockets = self._create_sockets(self.bind)
204 quic_sockets = []
205 return Sockets(secure_sockets, insecure_sockets, quic_sockets)
206
207 def _set_quic_addresses(self, sockets: List[socket.socket]) -> None:
208 self._quic_addresses = []
209 for sock in sockets:
210 name = sock.getsockname()
211 if type(name) is not str and len(name) >= 2:
212 self._quic_addresses.append(name)
213 else:
214 warnings.warn(
215 f'Cannot create a alt-svc header for the QUIC socket with address "{name}"',
216 Warning,
217 )
218
219 def _create_sockets(
220 self, binds: List[str], type_: int = socket.SOCK_STREAM
221 ) -> List[socket.socket]:
222 sockets: List[socket.socket] = []
223 for bind in binds:
224 binding: Any = None
225 if bind.startswith("unix:"):
226 sock = socket.socket(socket.AF_UNIX, type_)
227 binding = bind[5:]
228 try:
229 if stat.S_ISSOCK(os.stat(binding).st_mode):
230 os.remove(binding)
231 except FileNotFoundError:
232 pass
233 elif bind.startswith("fd://"):
234 sock = socket.socket(fileno=int(bind[5:]))
235 actual_type = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
236 if actual_type != type_:
237 raise SocketTypeError(type_, actual_type)
238 else:
239 bind = bind.replace("[", "").replace("]", "")
240 try:
241 value = bind.rsplit(":", 1)
242 host, port = value[0], int(value[1])
243 except (ValueError, IndexError):
244 host, port = bind, 8000
245 sock = socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET, type_)
246 if self.workers > 1:
247 try:
248 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
249 except AttributeError:
250 pass
251 binding = (host, port)
252
253 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
254
255 if bind.startswith("unix:"):
256 if self.umask is not None:
257 current_umask = os.umask(self.umask)
258 sock.bind(binding)
259 if self.user is not None and self.group is not None:
260 os.chown(binding, self.user, self.group)
261 if self.umask is not None:
262 os.umask(current_umask)
263 elif bind.startswith("fd://"):
264 pass
265 else:
266 sock.bind(binding)
267
268 sock.setblocking(False)
269 try:
270 sock.set_inheritable(True)
271 except AttributeError:
272 pass
273 sockets.append(sock)
274 return sockets
275
276 def response_headers(self, protocol: str) -> List[Tuple[bytes, bytes]]:
277 headers = []
278 if self.include_date_header:
279 headers.append((b"date", format_date_time(time()).encode("ascii")))
280 if self.include_server_header:
281 headers.append((b"server", f"hypercorn-{protocol}".encode("ascii")))
282
283 for alt_svc_header in self.alt_svc_headers:
284 headers.append((b"alt-svc", alt_svc_header.encode()))
285 if len(self.alt_svc_headers) == 0 and self._quic_addresses:
286 from aioquic.h3.connection import H3_ALPN
287
288 for version in H3_ALPN:
289 for addr in self._quic_addresses:
290 port = addr[1]
291 headers.append((b"alt-svc", b'%s=":%d"; ma=3600' % (version.encode(), port)))
292
293 return headers
294
295 def set_statsd_logger_class(self, statsd_logger: Type[Logger]) -> None:
296 if self.logger_class == Logger and self.statsd_host is not None:
297 self.logger_class = statsd_logger
298
299 @classmethod
300 def from_mapping(
301 cls: Type["Config"], mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any
302 ) -> "Config":
303 """Create a configuration from a mapping.
304
305 This allows either a mapping to be directly passed or as
306 keyword arguments, for example,
307
308 .. code-block:: python
309
310 config = {'keep_alive_timeout': 10}
311 Config.from_mapping(config)
312 Config.from_mapping(keep_alive_timeout=10)
313
314 Arguments:
315 mapping: Optionally a mapping object.
316 kwargs: Optionally a collection of keyword arguments to
317 form a mapping.
318 """
319 mappings: Dict[str, Any] = {}
320 if mapping is not None:
321 mappings.update(mapping)
322 mappings.update(kwargs)
323 config = cls()
324 for key, value in mappings.items():
325 try:
326 setattr(config, key, value)
327 except AttributeError:
328 pass
329
330 return config
331
332 @classmethod
333 def from_pyfile(cls: Type["Config"], filename: FilePath) -> "Config":
334 """Create a configuration from a Python file.
335
336 .. code-block:: python
337
338 Config.from_pyfile('hypercorn_config.py')
339
340 Arguments:
341 filename: The filename which gives the path to the file.
342 """
343 file_path = os.fspath(filename)
344 spec = importlib.util.spec_from_file_location("module.name", file_path)
345 module = importlib.util.module_from_spec(spec)
346 spec.loader.exec_module(module)
347 return cls.from_object(module)
348
349 @classmethod
350 def from_toml(cls: Type["Config"], filename: FilePath) -> "Config":
351 """Load the configuration values from a TOML formatted file.
352
353 This allows configuration to be loaded as so
354
355 .. code-block:: python
356
357 Config.from_toml('config.toml')
358
359 Arguments:
360 filename: The filename which gives the path to the file.
361 """
362 file_path = os.fspath(filename)
363 with open(file_path, "rb") as file_:
364 data = tomllib.load(file_)
365 return cls.from_mapping(data)
366
367 @classmethod
368 def from_object(cls: Type["Config"], instance: Union[object, str]) -> "Config":
369 """Create a configuration from a Python object.
370
371 This can be used to reference modules or objects within
372 modules for example,
373
374 .. code-block:: python
375
376 Config.from_object('module')
377 Config.from_object('module.instance')
378 from module import instance
379 Config.from_object(instance)
380
381 are valid.
382
383 Arguments:
384 instance: Either a str referencing a python object or the
385 object itself.
386
387 """
388 if isinstance(instance, str):
389 try:
390 instance = importlib.import_module(instance)
391 except ImportError:
392 path, config = instance.rsplit(".", 1)
393 module = importlib.import_module(path)
394 instance = getattr(module, config)
395
396 mapping = {
397 key: getattr(instance, key)
398 for key in dir(instance)
399 if not isinstance(getattr(instance, key), types.ModuleType) and not key.startswith("__")
400 }
401 return cls.from_mapping(mapping)