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