Debian Codegraph @

src/websockets/asyncio/server.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import hmac
5 import http
6 import logging
7 import re
8 import socket
9 from collections.abc import Awaitable, Coroutine, Generator, Iterable, Sequence
10 from types import TracebackType
11 from typing import Any, Callable, Mapping, Self, cast
12
13 from ..exceptions import InvalidHeader
14 from ..extensions.base import ServerExtensionFactory
15 from ..extensions.permessage_deflate import enable_server_permessage_deflate
16 from ..frames import CloseCode
17 from ..headers import (
18 build_www_authenticate_basic,
19 parse_authorization_basic,
20 validate_subprotocols,
21 )
22 from ..http11 import SERVER, Request, Response
23 from ..protocol import CONNECTING, OPEN, Event
24 from ..server import ServerProtocol
25 from ..typing import LoggerLike, Origin, PathLike, StatusLike, Subprotocol
26 from ..utils import get_socket_name
27 from .connection import Connection, broadcast
28
29
30 __all__ = [
31 "broadcast",
32 "serve",
33 "unix_serve",
34 "ServerConnection",
35 "Server",
36 "basic_auth",
37 ]
38
39
40 class ServerConnection(Connection):
41 """
42 :mod:`asyncio` implementation of a WebSocket server connection.
43
44 :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
45 receiving and sending messages.
46
47 It supports asynchronous iteration to receive messages::
48
49 async for message in websocket:
50 await process(message)
51
52 The iterator exits normally when the connection is closed with code
53 1000 (OK) or 1001 (going away) or without a close code. It raises a
54 :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
55 closed with any other code.
56
57 The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
58 and ``write_limit`` arguments have the same meaning as in :func:`serve`.
59
60 Args:
61 protocol: Sans-I/O connection.
62 server: Server that manages this connection.
63
64 """
65
66 def __init__(
67 self,
68 protocol: ServerProtocol,
69 server: Server,
70 *,
71 ping_interval: float | None = 20,
72 ping_timeout: float | None = 20,
73 close_timeout: float | None = 10,
74 max_queue: int | None | tuple[int | None, int | None] = 16,
75 write_limit: int | tuple[int, int | None] = 2**15,
76 ) -> None:
77 self.protocol: ServerProtocol
78 super().__init__(
79 protocol,
80 ping_interval=ping_interval,
81 ping_timeout=ping_timeout,
82 close_timeout=close_timeout,
83 max_queue=max_queue,
84 write_limit=write_limit,
85 )
86 self.server = server
87 self.request_rcvd: asyncio.Future[None] = self.loop.create_future()
88 self.username: str # see basic_auth()
89 self.handler: Callable[[ServerConnection], Awaitable[None]] # see route()
90 self.handler_kwargs: Mapping[str, Any] # see route()
91
92 def respond(self, status: StatusLike, text: str) -> Response:
93 """
94 Create a plain text HTTP response.
95
96 ``process_request`` and ``process_response`` may call this method to
97 return an HTTP response instead of performing the WebSocket opening
98 handshake.
99
100 You can modify the response before returning it, for example by changing
101 HTTP headers.
102
103 Args:
104 status: HTTP status code.
105 text: HTTP response body; it will be encoded to UTF-8.
106
107 Returns:
108 HTTP response to send to the client.
109
110 """
111 return self.protocol.reject(status, text)
112
113 async def handshake(
114 self,
115 process_request: (
116 Callable[
117 [ServerConnection, Request],
118 Awaitable[Response | None] | Response | None,
119 ]
120 | None
121 ) = None,
122 process_response: (
123 Callable[
124 [ServerConnection, Request, Response],
125 Awaitable[Response | None] | Response | None,
126 ]
127 | None
128 ) = None,
129 server_header: str | None = SERVER,
130 ) -> None:
131 """
132 Perform the opening handshake.
133
134 """
135 await asyncio.wait(
136 [self.request_rcvd, self.connection_lost_waiter],
137 return_when=asyncio.FIRST_COMPLETED,
138 )
139
140 if self.request is not None:
141 response = None
142
143 if process_request is not None:
144 try:
145 response = process_request(self, self.request)
146 if isinstance(response, Awaitable):
147 response = await response
148 except Exception as exc:
149 self.protocol.handshake_exc = exc
150 self.logger.error("process_request failed", exc_info=True)
151 response = self.protocol.reject(
152 http.HTTPStatus.INTERNAL_SERVER_ERROR,
153 (
154 "Failed to open a WebSocket connection.\n"
155 "See server log for more information.\n"
156 ),
157 )
158
159 if response is None:
160 self.response = self.protocol.accept(self.request)
161 else:
162 assert isinstance(response, Response) # help mypy
163 self.response = response
164
165 if server_header is not None:
166 self.response.headers["Server"] = server_header
167
168 response = None
169
170 if process_response is not None:
171 try:
172 response = process_response(self, self.request, self.response)
173 if isinstance(response, Awaitable):
174 response = await response
175 except Exception as exc:
176 self.protocol.handshake_exc = exc
177 self.logger.error("process_response failed", exc_info=True)
178 response = self.protocol.reject(
179 http.HTTPStatus.INTERNAL_SERVER_ERROR,
180 (
181 "Failed to open a WebSocket connection.\n"
182 "See server log for more information.\n"
183 ),
184 )
185
186 if response is not None:
187 assert isinstance(response, Response) # help mypy
188 self.response = response
189
190 # Reject the connection if the server started closing during the
191 # opening handshake. Don't yield before send_response() to avoid
192 # a race condition after checking if the server is closing.
193 if (
194 self.response.status_code == http.HTTPStatus.SWITCHING_PROTOCOLS
195 and not self.server.is_serving()
196 ):
197 self.response = self.protocol.reject(
198 http.HTTPStatus.SERVICE_UNAVAILABLE,
199 "Server is shutting down.\n",
200 )
201
202 # Don't respond if the connection was closed during the handshake.
203 if self.state is CONNECTING:
204 async with self.send_context(expected_state=CONNECTING):
205 self.protocol.send_response(self.response)
206
207 def process_event(self, event: Event) -> None:
208 """
209 Process one incoming event.
210
211 """
212 # First event - handshake request.
213 if self.request is None:
214 assert isinstance(event, Request)
215 self.request = event
216 self.request_rcvd.set_result(None)
217 # Later events - frames.
218 else:
219 super().process_event(event)
220
221 def connection_made(self, transport: asyncio.BaseTransport) -> None:
222 super().connection_made(transport)
223 # The handler task must be registered in self.handler_tasks now. If it
224 # was registered inside the task, a race condition could happen when
225 # closing the server after scheduling the task but before it executes.
226 handler_task = self.loop.create_task(self.server.handler(self))
227 self.server.handler_tasks.add(handler_task)
228
229
230 class Server:
231 """
232 WebSocket server returned by :func:`serve`.
233
234 This class mirrors most of the API of :class:`asyncio.Server`, with the
235 following differences:
236
237 * You can invoke :func:`serve` as ``async with serve(...) as server: ...``
238 in addition to ``server = await serve(...)`` to start the server.
239
240 * It doesn't provide ``close_clients`` or ``abort_clients``; by default,
241 :meth:`close` closes existing connections with code 1001 (going away).
242
243 Args:
244 handler: Handler for one connection. It receives an asyncio protocol.
245 logger: Logger for this server.
246 It defaults to ``logging.getLogger("websockets.server")``.
247 See the :doc:`logging guide <../../topics/logging>` for details.
248
249 """
250
251 def __init__(
252 self,
253 create_server: Callable[[], Coroutine[Any, Any, asyncio.Server]],
254 handler: Callable[[ServerConnection], Coroutine[Any, Any, None]],
255 logger: LoggerLike | None = None,
256 ) -> None:
257 self.create_server = create_server
258 self.handler = handler
259 if logger is None:
260 logger = logging.getLogger("websockets.server")
261 self.logger = logger
262
263 # Keep track of active connections and connection handler tasks.
264 self.all_connections: set[ServerConnection] = set()
265 self.handler_tasks: set[asyncio.Task[None]] = set()
266
267 # Task responsible for closing the server and terminating connections.
268 self.close_task: asyncio.Task[None] | None = None
269
270 # Completed when the server is closed and connections are terminated.
271 loop = asyncio.get_running_loop()
272 self.handlers_waiter: asyncio.Future[None] = loop.create_future()
273
274 @property
275 def connections(self) -> set[ServerConnection]:
276 """
277 Set of active connections.
278
279 This property contains all connections that completed the opening
280 handshake successfully and didn't start the closing handshake yet.
281 It can be useful in combination with :func:`~broadcast`.
282
283 """
284 return {
285 connection
286 for connection in self.all_connections
287 if connection.protocol.state is OPEN
288 }
289
290 def close(
291 self,
292 close_connections: bool = True,
293 code: CloseCode | int = CloseCode.GOING_AWAY,
294 reason: str = "",
295 ) -> None:
296 """
297 Close the server.
298
299 * Close the underlying :class:`asyncio.Server`.
300 * When ``close_connections`` is :obj:`True`, which is the default, close
301 existing connections. Specifically:
302
303 * Reject opening WebSocket connections with an HTTP 503 (service
304 unavailable) error. This happens when the server accepted the TCP
305 connection but didn't complete the opening handshake before closing.
306 * Close open WebSocket connections with code 1001 (going away).
307 ``code`` and ``reason`` can be customized, for example to use code
308 1012 (service restart).
309
310 * Wait until all connection handlers have returned.
311
312 :meth:`close` is idempotent.
313
314 """
315 if self.close_task is None:
316 self.close_task = self.get_loop().create_task(
317 self._close(close_connections, code, reason)
318 )
319
320 async def _close(
321 self,
322 close_connections: bool = True,
323 code: CloseCode | int = CloseCode.GOING_AWAY,
324 reason: str = "",
325 ) -> None:
326 """
327 Implementation of :meth:`close`.
328
329 This calls :meth:`~asyncio.Server.close` on the underlying
330 :class:`asyncio.Server` object to stop accepting new connections and
331 then closes open connections.
332
333 """
334 self.logger.info("server closing")
335
336 # Stop accepting new connections.
337 # Also reject OPENING connections with HTTP 503 — see handshake().
338 self.server.close()
339
340 # Close OPEN connections.
341 if close_connections:
342 close_tasks = [
343 asyncio.create_task(connection.close(code, reason))
344 for connection in self.all_connections
345 if connection.protocol.state is OPEN
346 ]
347 # asyncio.wait doesn't accept an empty first argument.
348 if close_tasks:
349 await asyncio.wait(close_tasks)
350
351 # Wait until all TCP connections are closed.
352 await self.server.wait_closed()
353
354 # Wait until all connection handlers have returned.
355 # asyncio.wait doesn't accept an empty first argument.
356 if self.handler_tasks:
357 await asyncio.wait(self.handler_tasks)
358
359 # Tell wait_closed() to return.
360 self.handlers_waiter.set_result(None)
361
362 self.logger.info("server closed")
363
364 def get_loop(self) -> asyncio.AbstractEventLoop:
365 """
366 See :meth:`asyncio.Server.get_loop`.
367
368 """
369 return self.server.get_loop()
370
371 async def start_serving(self) -> None:
372 """
373 See :meth:`asyncio.Server.start_serving`.
374
375 Typical use::
376
377 server = await serve(..., start_serving=False)
378 # perform additional setup here...
379 # ... then start the server
380 await server.start_serving()
381
382 """
383 await self.server.start_serving()
384
385 async def serve_forever(self) -> None:
386 """
387 See :meth:`asyncio.Server.serve_forever`.
388
389 Typical use::
390
391 server = await serve(...)
392 # this coroutine doesn't return
393 # canceling it stops the server
394 await server.serve_forever()
395
396 This is an alternative to using :func:`serve` as an asynchronous context
397 manager. Shutdown is triggered by canceling :meth:`serve_forever` or by
398 calling :meth:`~Server.close` from another task.
399
400 """
401 try:
402 if not self.is_serving():
403 await self.start_serving()
404 # If close() is called, wait_closed() will return, and we'll exit.
405 await self.wait_closed()
406 except asyncio.CancelledError:
407 try:
408 self.close()
409 await self.wait_closed()
410 finally:
411 raise
412
413 def is_serving(self) -> bool:
414 """
415 See :meth:`asyncio.Server.is_serving`.
416
417 """
418 return self.server.is_serving()
419
420 async def wait_closed(self) -> None:
421 """
422 Wait until the server is closed.
423
424 When :meth:`wait_closed` returns, all TCP connections are closed and
425 all connection handlers have returned.
426
427 To ensure a fast shutdown, a connection handler should always be
428 awaiting at least one of:
429
430 * :meth:`~ServerConnection.recv`: when the connection is closed,
431 it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
432 * :meth:`~ServerConnection.wait_closed`: when the connection is
433 closed, it returns.
434
435 Then the connection handler is immediately notified of the shutdown;
436 it can clean up and exit.
437
438 """
439 await asyncio.shield(self.handlers_waiter)
440
441 @property
442 def sockets(self) -> tuple[socket.socket, ...]:
443 """
444 See :attr:`asyncio.Server.sockets`.
445
446 """
447 return self.server.sockets
448
449 async def _await(self) -> Self:
450 if not hasattr(self, "server"):
451 self.server = await self.create_server()
452 if self.server.is_serving():
453 for sock in self.server.sockets:
454 self.logger.info("server listening on %s", get_socket_name(sock))
455 return self
456
457 def __await__(self) -> Generator[Any, None, Self]:
458 # Create a suitable iterator by calling __await__ on a coroutine.
459 return self._await().__await__()
460
461 async def __aenter__(self) -> Self:
462 return await self
463
464 async def __aexit__(
465 self,
466 exc_type: type[BaseException] | None,
467 exc_value: BaseException | None,
468 traceback: TracebackType | None,
469 ) -> None:
470 self.close()
471 await self.wait_closed()
472
473
474 # serve() is declared as a function rather than a coroutine in order to support
475 # async with serve(...) as server: ... in addition to server = await serve(...).
476
477
478 def serve(
479 handler: Callable[[ServerConnection], Awaitable[None]],
480 host: str | None = None,
481 port: int | None = None,
482 *,
483 # WebSocket
484 origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
485 extensions: Sequence[ServerExtensionFactory] | None = None,
486 subprotocols: Sequence[Subprotocol] | None = None,
487 select_subprotocol: (
488 Callable[
489 [ServerConnection, Sequence[Subprotocol]],
490 Subprotocol | None,
491 ]
492 | None
493 ) = None,
494 compression: str | None = "deflate",
495 # HTTP
496 process_request: (
497 Callable[
498 [ServerConnection, Request],
499 Awaitable[Response | None] | Response | None,
500 ]
501 | None
502 ) = None,
503 process_response: (
504 Callable[
505 [ServerConnection, Request, Response],
506 Awaitable[Response | None] | Response | None,
507 ]
508 | None
509 ) = None,
510 server_header: str | None = SERVER,
511 # Timeouts
512 open_timeout: float | None = 10,
513 ping_interval: float | None = 20,
514 ping_timeout: float | None = 20,
515 close_timeout: float | None = 10,
516 # Limits
517 max_size: int | None | tuple[int | None, int | None] = 2**20,
518 max_queue: int | None | tuple[int | None, int | None] = 16,
519 write_limit: int | tuple[int, int | None] = 2**15,
520 # Logging
521 logger: LoggerLike | None = None,
522 # Escape hatch for advanced customization
523 create_connection: type[ServerConnection] | None = None,
524 # Other keyword arguments are passed to loop.create_server
525 **kwargs: Any,
526 ) -> Server:
527 """
528 Create a WebSocket server listening on ``host`` and ``port``.
529
530 Whenever a client connects, the server creates a :class:`ServerConnection`,
531 performs the opening handshake, and delegates to the ``handler`` coroutine.
532
533 The handler receives the :class:`ServerConnection` instance, which you can
534 use to send and receive messages.
535
536 Once the handler completes, either normally or with an exception, the server
537 performs the closing handshake and closes the connection.
538
539 This function returns a :class:`Server` object whose API mirrors
540 :class:`asyncio.Server`. Treat it as an asynchronous context manager to
541 serve requests and ensure that the server will be closed gracefully::
542
543 from websockets.asyncio.server import serve
544
545 async def handler(websocket):
546 ...
547
548 # set this event to exit the server
549 stop = asyncio.Event()
550
551 async with serve(handler, host, port):
552 await stop.wait()
553
554 Alternatively, await it and call :meth:`~Server.serve_forever` to serve
555 requests, then cancel it or call :meth:`~Server.close` to stop the server::
556
557 server = await serve(handler, host, port)
558 await server.serve_forever()
559
560 The following pattern is functional but redundant: by the time the context
561 manager exits, :meth:`~Server.serve_forever` has already closed the server::
562
563 async with serve(handler, host, port) as server:
564 await server.serve_forever()
565
566 Args:
567 handler: Connection handler. It receives the WebSocket connection,
568 which is a :class:`ServerConnection`, in argument.
569 host: Network interfaces the server binds to.
570 See :meth:`~asyncio.loop.create_server` for details.
571 port: TCP port the server listens on.
572 See :meth:`~asyncio.loop.create_server` for details.
573 origins: Acceptable values of the ``Origin`` header, for defending
574 against Cross-Site WebSocket Hijacking attacks. Values can be
575 :class:`str` to test for an exact match or regular expressions
576 compiled by :func:`re.compile` to test against a pattern. Include
577 :obj:`None` in the list if the lack of an origin is acceptable.
578 extensions: List of supported extensions, in order in which they
579 should be negotiated and run.
580 subprotocols: List of supported subprotocols, in order of decreasing
581 preference.
582 select_subprotocol: Callback for selecting a subprotocol among
583 those supported by the client and the server. It receives a
584 :class:`ServerConnection` (not a
585 :class:`~websockets.server.ServerProtocol`!) instance and a list of
586 subprotocols offered by the client. Other than the first argument,
587 it has the same behavior as the
588 :meth:`ServerProtocol.select_subprotocol
589 <websockets.server.ServerProtocol.select_subprotocol>` method.
590 compression: The "permessage-deflate" extension is enabled by default.
591 Set ``compression`` to :obj:`None` to disable it. See the
592 :doc:`compression guide <../../topics/compression>` for details.
593 process_request: Intercept the request during the opening handshake.
594 Return an HTTP response to force the response or :obj:`None` to
595 continue normally. When you force an HTTP 101 Continue response, the
596 handshake is successful. Else, the connection is aborted.
597 ``process_request`` may be a function or a coroutine.
598 process_response: Intercept the response during the opening handshake.
599 Return an HTTP response to force the response or :obj:`None` to
600 continue normally. When you force an HTTP 101 Continue response, the
601 handshake is successful. Else, the connection is aborted.
602 ``process_response`` may be a function or a coroutine.
603 server_header: Value of the ``Server`` response header.
604 It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
605 :obj:`None` removes the header.
606 open_timeout: Timeout for opening connections in seconds.
607 :obj:`None` disables the timeout.
608 ping_interval: Interval between keepalive pings in seconds.
609 :obj:`None` disables keepalive.
610 ping_timeout: Timeout for keepalive pings in seconds.
611 :obj:`None` disables timeouts.
612 close_timeout: Timeout for closing connections in seconds.
613 :obj:`None` disables the timeout.
614 max_size: Maximum size of incoming messages in bytes.
615 :obj:`None` disables the limit. You may pass a ``(max_message_size,
616 max_fragment_size)`` tuple to set different limits for messages and
617 fragments when you expect long messages sent in short fragments.
618 max_queue: High-water mark of the buffer where frames are received.
619 It defaults to 16 frames. The low-water mark defaults to ``max_queue
620 // 4``. You may pass a ``(high, low)`` tuple to set the high-water
621 and low-water marks. If you want to disable flow control entirely,
622 you may set it to ``None``, although that's a bad idea.
623 write_limit: High-water mark of write buffer in bytes. It is passed to
624 :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
625 to 32 KiB. You may pass a ``(high, low)`` tuple to set the
626 high-water and low-water marks.
627 logger: Logger for this server.
628 It defaults to ``logging.getLogger("websockets.server")``.
629 See the :doc:`logging guide <../../topics/logging>` for details.
630 create_connection: Factory for the :class:`ServerConnection` managing
631 the connection. Set it to a wrapper or a subclass to customize
632 connection handling.
633
634 Any other keyword arguments are passed to the event loop's
635 :meth:`~asyncio.loop.create_server` method.
636
637 For example:
638
639 * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.
640
641 * You can set ``sock`` to provide a preexisting TCP socket. You may call
642 :func:`socket.create_server` (not to be confused with the event loop's
643 :meth:`~asyncio.loop.create_server` method) to create a suitable server
644 socket and customize it.
645
646 * You can set ``start_serving`` to ``False`` to start accepting connections
647 only after you call :meth:`~Server.start_serving()` or
648 :meth:`~Server.serve_forever()`.
649
650 """
651 if subprotocols is not None:
652 validate_subprotocols(subprotocols)
653
654 if compression == "deflate":
655 extensions = enable_server_permessage_deflate(extensions)
656 elif compression is not None:
657 raise ValueError(f"unsupported compression: {compression}")
658
659 if create_connection is None:
660 create_connection = ServerConnection
661
662 if kwargs.get("ssl") is not None:
663 kwargs.setdefault("ssl_handshake_timeout", open_timeout)
664 kwargs.setdefault("ssl_shutdown_timeout", close_timeout)
665
666 async def create_server() -> asyncio.Server:
667 loop = asyncio.get_running_loop()
668 if kwargs.pop("unix", False):
669 return await loop.create_unix_server(protocol_factory, **kwargs)
670 else:
671 # mypy cannot tell that kwargs must provide sock when port is None.
672 return await loop.create_server(protocol_factory, host, port, **kwargs) # type: ignore[arg-type]
673
674 def protocol_factory() -> ServerConnection:
675 """
676 Create an asyncio protocol for managing a WebSocket connection.
677
678 """
679 # Create a closure to give select_subprotocol access to connection.
680 protocol_select_subprotocol: (
681 Callable[
682 [ServerProtocol, Sequence[Subprotocol]],
683 Subprotocol | None,
684 ]
685 | None
686 ) = None
687 if select_subprotocol is not None:
688
689 def protocol_select_subprotocol(
690 protocol: ServerProtocol,
691 subprotocols: Sequence[Subprotocol],
692 ) -> Subprotocol | None:
693 # mypy doesn't know that select_subprotocol is immutable.
694 assert select_subprotocol is not None
695 # Ensure this function is only used in the intended context.
696 assert protocol is connection.protocol
697 return select_subprotocol(connection, subprotocols)
698
699 # This is a protocol in the Sans-I/O implementation of websockets.
700 protocol = ServerProtocol(
701 origins=origins,
702 extensions=extensions,
703 subprotocols=subprotocols,
704 select_subprotocol=protocol_select_subprotocol,
705 max_size=max_size,
706 logger=logger,
707 )
708 # This is a connection in websockets and a protocol in asyncio.
709 connection = create_connection(
710 protocol,
711 server,
712 ping_interval=ping_interval,
713 ping_timeout=ping_timeout,
714 close_timeout=close_timeout,
715 max_queue=max_queue,
716 write_limit=write_limit,
717 )
718 return connection
719
720 async def protocol_handler(connection: ServerConnection) -> None:
721 """
722 Handle the lifecycle of a WebSocket connection.
723
724 Since this coroutine doesn't have a caller that can handle
725 exceptions, it attempts to log relevant ones.
726
727 It guarantees that the TCP connection is closed before exiting.
728
729 """
730 try:
731 # Apply open_timeout to the WebSocket handshake.
732 # Use ssl_handshake_timeout for the TLS handshake.
733 async with asyncio.timeout(open_timeout):
734 await connection.handshake(
735 process_request,
736 process_response,
737 server_header,
738 )
739
740 if connection.protocol.state is not OPEN:
741 connection.transport.abort()
742 return
743
744 server.all_connections.add(connection)
745 connection.start_keepalive()
746 try:
747 await handler(connection)
748 except Exception:
749 connection.logger.error("connection handler failed", exc_info=True)
750 await connection.close(CloseCode.INTERNAL_ERROR)
751 else:
752 await connection.close()
753 finally:
754 server.all_connections.discard(connection)
755
756 except Exception:
757 # Don't leak connections when the opening handshake times out or
758 # an unexpected error occurs.
759 connection.transport.abort()
760
761 finally:
762 server.handler_tasks.discard(asyncio.current_task())
763
764 # The server variable is captured by the closure of conn_handler() and
765 # protocol_factory().
766 server = Server(create_server, protocol_handler, logger)
767 return server
768
769
770 def unix_serve(
771 handler: Callable[[ServerConnection], Awaitable[None]],
772 path: PathLike | None = None,
773 **kwargs: Any,
774 ) -> Server:
775 """
776 Create a WebSocket server listening on a Unix socket.
777
778 This function is identical to :func:`serve`, except the ``host`` and
779 ``port`` arguments are replaced by ``path``. It's only available on Unix.
780
781 It's useful for deploying a server behind a reverse proxy such as nginx.
782
783 Args:
784 handler: Connection handler. It receives the WebSocket connection,
785 which is a :class:`ServerConnection`, in argument.
786 path: File system path to the Unix socket.
787
788 """
789 return serve(handler, unix=True, path=path, **kwargs)
790
791
792 def is_credentials(credentials: Any) -> bool:
793 try:
794 username, password = credentials
795 except (TypeError, ValueError):
796 return False
797 else:
798 return isinstance(username, str) and isinstance(password, str)
799
800
801 def basic_auth(
802 realm: str = "",
803 credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None,
804 check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None,
805 ) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]:
806 """
807 Factory for ``process_request`` to enforce HTTP Basic Authentication.
808
809 :func:`basic_auth` is designed to integrate with :func:`serve` as follows::
810
811 from websockets.asyncio.server import basic_auth, serve
812
813 async with serve(
814 ...,
815 process_request=basic_auth(
816 realm="my dev server",
817 credentials=("hello", "iloveyou"),
818 ),
819 ):
820
821 If authentication succeeds, the connection's ``username`` attribute is set.
822 If it fails, the server responds with an HTTP 401 Unauthorized status.
823
824 One of ``credentials`` or ``check_credentials`` must be provided; not both.
825
826 Args:
827 realm: Scope of protection. It should contain only ASCII characters
828 because the encoding of non-ASCII characters is undefined. Refer to
829 section 2.2 of :rfc:`7235` for details.
830 credentials: Hard coded authorized credentials. It can be a
831 ``(username, password)`` pair or a list of such pairs.
832 check_credentials: Function or coroutine that verifies credentials.
833 It receives ``username`` and ``password`` arguments and returns
834 whether they're valid.
835 Raises:
836 TypeError: If ``credentials`` or ``check_credentials`` is wrong.
837 ValueError: If ``credentials`` and ``check_credentials`` are both
838 provided or both not provided.
839
840 """
841 if (credentials is None) == (check_credentials is None):
842 raise ValueError("provide either credentials or check_credentials")
843
844 if credentials is not None:
845 if is_credentials(credentials):
846 credentials_list = [cast(tuple[str, str], credentials)]
847 elif isinstance(credentials, Iterable):
848 credentials_list = list(cast(Iterable[tuple[str, str]], credentials))
849 if not all(is_credentials(item) for item in credentials_list):
850 raise TypeError(f"invalid credentials argument: {credentials}")
851 else:
852 raise TypeError(f"invalid credentials argument: {credentials}")
853
854 credentials_dict = dict(credentials_list)
855
856 def check_credentials(username: str, password: str) -> bool:
857 try:
858 expected_password = credentials_dict[username]
859 except KeyError:
860 return False
861 return hmac.compare_digest(expected_password, password)
862
863 assert check_credentials is not None # help mypy
864
865 async def process_request(
866 connection: ServerConnection,
867 request: Request,
868 ) -> Response | None:
869 """
870 Perform HTTP Basic Authentication.
871
872 If it succeeds, set the connection's ``username`` attribute and return
873 :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.
874
875 """
876 try:
877 authorization = request.headers["Authorization"]
878 except KeyError:
879 response = connection.respond(
880 http.HTTPStatus.UNAUTHORIZED,
881 "Missing credentials\n",
882 )
883 response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
884 return response
885
886 try:
887 username, password = parse_authorization_basic(authorization)
888 except InvalidHeader:
889 response = connection.respond(
890 http.HTTPStatus.UNAUTHORIZED,
891 "Unsupported credentials\n",
892 )
893 response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
894 return response
895
896 valid_credentials = check_credentials(username, password)
897 if isinstance(valid_credentials, Awaitable):
898 valid_credentials = await valid_credentials
899
900 if not valid_credentials:
901 response = connection.respond(
902 http.HTTPStatus.UNAUTHORIZED,
903 "Invalid credentials\n",
904 )
905 response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
906 return response
907
908 connection.username = username
909 return None
910
911 return process_request