Debian Codegraph @

src/websockets/server.py

raw
1 from __future__ import annotations
2
3 import base64
4 import binascii
5 import email.utils
6 import http
7 import re
8 import warnings
9 from collections.abc import Generator, Sequence
10 from typing import Any, Callable, cast
11
12 from .datastructures import Headers, MultipleValuesError
13 from .exceptions import (
14 HeaderLineTooLong,
15 InvalidHandshake,
16 InvalidHeader,
17 InvalidHeaderValue,
18 InvalidMessage,
19 InvalidMethod,
20 InvalidOrigin,
21 InvalidProtocol,
22 InvalidUpgrade,
23 NegotiationError,
24 RequestLineTooLong,
25 TooManyHeaders,
26 )
27 from .extensions import Extension, ServerExtensionFactory
28 from .headers import (
29 build_extension,
30 parse_connection,
31 parse_extension,
32 parse_subprotocol,
33 parse_upgrade,
34 )
35 from .http11 import Request, Response
36 from .imports import lazy_import
37 from .protocol import CONNECTING, OPEN, SERVER, Protocol, State
38 from .typing import (
39 ConnectionOption,
40 ExtensionHeader,
41 LoggerLike,
42 Origin,
43 StatusLike,
44 Subprotocol,
45 UpgradeProtocol,
46 )
47 from .utils import accept_key
48
49
50 __all__ = ["ServerProtocol"]
51
52
53 class ServerProtocol(Protocol):
54 """
55 Sans-I/O implementation of a WebSocket server connection.
56
57 Args:
58 origins: Acceptable values of the ``Origin`` header. Values can be
59 :class:`str` to test for an exact match or regular expressions
60 compiled by :func:`re.compile` to test against a pattern. Include
61 :obj:`None` in the list if the lack of an origin is acceptable.
62 This is useful for defending against Cross-Site WebSocket
63 Hijacking attacks.
64 extensions: List of supported extensions, in order in which they
65 should be tried.
66 subprotocols: List of supported subprotocols, in order of decreasing
67 preference.
68 select_subprotocol: Callback for selecting a subprotocol among
69 those supported by the client and the server. It has the same
70 signature as the :meth:`select_subprotocol` method, including a
71 :class:`ServerProtocol` instance as first argument.
72 state: Initial state of the WebSocket connection.
73 max_size: Maximum size of incoming messages in bytes.
74 :obj:`None` disables the limit. You may pass a ``(max_message_size,
75 max_fragment_size)`` tuple to set different limits for messages and
76 fragments when you expect long messages sent in short fragments.
77 logger: Logger for this connection;
78 defaults to ``logging.getLogger("websockets.server")``;
79 see the :doc:`logging guide <../../topics/logging>` for details.
80
81 """
82
83 def __init__(
84 self,
85 *,
86 origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
87 extensions: Sequence[ServerExtensionFactory] | None = None,
88 subprotocols: Sequence[Subprotocol] | None = None,
89 select_subprotocol: (
90 Callable[
91 [ServerProtocol, Sequence[Subprotocol]],
92 Subprotocol | None,
93 ]
94 | None
95 ) = None,
96 state: State = CONNECTING,
97 max_size: int | None | tuple[int | None, int | None] = 2**20,
98 logger: LoggerLike | None = None,
99 ) -> None:
100 super().__init__(
101 side=SERVER,
102 state=state,
103 max_size=max_size,
104 logger=logger,
105 )
106 self.origins = origins
107 self.available_extensions = extensions
108 self.available_subprotocols = subprotocols
109 if select_subprotocol is not None:
110 # Bind select_subprotocol then shadow self.select_subprotocol.
111 # Use setattr to work around https://github.com/python/mypy/issues/2427.
112 setattr(
113 self,
114 "select_subprotocol",
115 select_subprotocol.__get__(self, self.__class__),
116 )
117 # True when a WebSocket handshake was attempted via accept();
118 # False when a plain HTTP response sent by process_request().
119 self.accept_called = False
120
121 def accept(self, request: Request) -> Response:
122 """
123 Create a handshake response to accept the connection.
124
125 If the handshake request is valid and the handshake successful,
126 :meth:`accept` returns an HTTP response with status code 101.
127
128 Else, it returns an HTTP response with another status code. This rejects
129 the connection, like :meth:`reject` would.
130
131 You must send the handshake response with :meth:`send_response`.
132
133 You may modify the response before sending it, typically by adding HTTP
134 headers.
135
136 Args:
137 request: WebSocket handshake request received from the client.
138
139 Returns:
140 WebSocket handshake response or HTTP response to send to the client.
141
142 """
143 self.accept_called = True
144 try:
145 (
146 accept_header,
147 extensions_header,
148 protocol_header,
149 ) = self.process_request(request)
150 except InvalidOrigin as exc:
151 request._exception = exc
152 self.handshake_exc = exc
153 if self.debug:
154 self.logger.debug("! invalid origin", exc_info=True)
155 return self.reject(
156 http.HTTPStatus.FORBIDDEN,
157 f"Failed to open a WebSocket connection: {exc}.\n",
158 )
159 except InvalidMethod as exc:
160 request._exception = exc
161 self.handshake_exc = exc
162 if self.debug:
163 self.logger.debug("! invalid method", exc_info=True)
164 response = self.reject(
165 http.HTTPStatus.METHOD_NOT_ALLOWED,
166 f"Failed to open a WebSocket connection: {exc}.\n",
167 )
168 response.headers["Allow"] = "GET"
169 return response
170 except InvalidProtocol as exc:
171 request._exception = exc
172 self.handshake_exc = exc
173 if self.debug:
174 self.logger.debug("! invalid protocol", exc_info=True)
175 return self.reject(
176 http.HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
177 f"Failed to open a WebSocket connection: {exc}.\n",
178 )
179 except InvalidUpgrade as exc:
180 request._exception = exc
181 self.handshake_exc = exc
182 if self.debug:
183 self.logger.debug("! invalid upgrade", exc_info=True)
184 response = self.reject(
185 http.HTTPStatus.UPGRADE_REQUIRED,
186 (
187 f"Failed to open a WebSocket connection: {exc}.\n"
188 f"\n"
189 f"You cannot access a WebSocket server directly "
190 f"with a browser. You need a WebSocket client.\n"
191 ),
192 )
193 response.headers["Upgrade"] = "websocket"
194 return response
195 except InvalidHandshake as exc:
196 request._exception = exc
197 self.handshake_exc = exc
198 if self.debug:
199 self.logger.debug("! invalid handshake", exc_info=True)
200 exc_chain = cast(BaseException, exc)
201 exc_str = f"{exc_chain}"
202 while exc_chain.__cause__ is not None:
203 exc_chain = exc_chain.__cause__
204 exc_str += f"; {exc_chain}"
205 return self.reject(
206 http.HTTPStatus.BAD_REQUEST,
207 f"Failed to open a WebSocket connection: {exc_str}.\n",
208 )
209 except Exception as exc:
210 # Handle exceptions raised by user-provided select_subprotocol and
211 # unexpected errors.
212 request._exception = exc
213 self.handshake_exc = exc
214 self.logger.error("opening handshake failed", exc_info=True)
215 return self.reject(
216 http.HTTPStatus.INTERNAL_SERVER_ERROR,
217 (
218 "Failed to open a WebSocket connection.\n"
219 "See server log for more information.\n"
220 ),
221 )
222
223 headers = Headers()
224 headers["Date"] = email.utils.formatdate(usegmt=True)
225 headers["Upgrade"] = "websocket"
226 headers["Connection"] = "Upgrade"
227 headers["Sec-WebSocket-Accept"] = accept_header
228 if extensions_header is not None:
229 headers["Sec-WebSocket-Extensions"] = extensions_header
230 if protocol_header is not None:
231 headers["Sec-WebSocket-Protocol"] = protocol_header
232 return Response(101, "Switching Protocols", headers)
233
234 def process_request(
235 self,
236 request: Request,
237 ) -> tuple[str, str | None, str | None]:
238 """
239 Check a handshake request and negotiate extensions and subprotocol.
240
241 This function doesn't check the ``Host`` header. This control must be
242 performed by the HTTP stack earlier. It's the responsibility of the
243 caller.
244
245 Args:
246 request: WebSocket handshake request received from the client.
247
248 Returns:
249 ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and
250 ``Sec-WebSocket-Protocol`` headers for the handshake response.
251
252 Raises:
253 InvalidMethod: If the request method isn't GET; then the
254 server must return a 405 Method Not Allowed error.
255 InvalidProtocol: If the request protocol isn't HTTP/1.1; then
256 the server must return a 505 HTTP Version Not Supported
257 error.
258 InvalidHandshake: If the handshake request is invalid;
259 then the server must return a 400 Bad Request error.
260
261 """
262 if request.method != "GET":
263 raise InvalidMethod(request.method)
264
265 if request.protocol != "HTTP/1.1":
266 raise InvalidProtocol(request.protocol)
267
268 headers = request.headers
269
270 connection: list[ConnectionOption] = sum(
271 [parse_connection(value) for value in headers.get_all("Connection")], []
272 )
273 if not any(value.lower() == "upgrade" for value in connection):
274 raise InvalidUpgrade(
275 "Connection", ", ".join(connection) if connection else None
276 )
277
278 upgrade: list[UpgradeProtocol] = sum(
279 [parse_upgrade(value) for value in headers.get_all("Upgrade")], []
280 )
281 # For compatibility with non-strict implementations, ignore case when
282 # checking the Upgrade header. The RFC always uses "websocket", except
283 # in section 11.2. (IANA registration) where it uses "WebSocket".
284 if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
285 raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None)
286
287 try:
288 key = headers["Sec-WebSocket-Key"]
289 except KeyError:
290 raise InvalidHeader("Sec-WebSocket-Key") from None
291 except MultipleValuesError:
292 raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from None
293 try:
294 raw_key = base64.b64decode(key.encode(), validate=True)
295 except binascii.Error as exc:
296 raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc
297 if len(raw_key) != 16:
298 raise InvalidHeaderValue("Sec-WebSocket-Key", key)
299 accept_header = accept_key(key)
300
301 try:
302 version = headers["Sec-WebSocket-Version"]
303 except KeyError:
304 raise InvalidHeader("Sec-WebSocket-Version") from None
305 except MultipleValuesError:
306 raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from None
307 if version != "13":
308 raise InvalidHeaderValue("Sec-WebSocket-Version", version)
309
310 self.origin = self.process_origin(headers)
311 extensions_header, self.extensions = self.process_extensions(headers)
312 protocol_header = self.subprotocol = self.process_subprotocol(headers)
313
314 return (accept_header, extensions_header, protocol_header)
315
316 def process_origin(self, headers: Headers) -> Origin | None:
317 """
318 Handle the Origin HTTP request header.
319
320 Args:
321 headers: WebSocket handshake request headers.
322
323 Returns:
324 origin, if it is acceptable.
325
326 Raises:
327 InvalidHandshake: If the Origin header is invalid.
328 InvalidOrigin: If the origin isn't acceptable.
329
330 """
331 # "The user agent MUST NOT include more than one Origin header field"
332 # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3.
333 try:
334 origin = headers.get("Origin")
335 except MultipleValuesError:
336 raise InvalidHeader("Origin", "multiple values") from None
337 if origin is not None:
338 origin = cast(Origin, origin)
339 if self.origins is not None:
340 for origin_or_regex in self.origins:
341 if origin_or_regex == origin or (
342 isinstance(origin_or_regex, re.Pattern)
343 and origin is not None
344 and origin_or_regex.fullmatch(origin) is not None
345 ):
346 break
347 else:
348 raise InvalidOrigin(origin)
349 return origin
350
351 def process_extensions(
352 self,
353 headers: Headers,
354 ) -> tuple[str | None, list[Extension]]:
355 """
356 Handle the Sec-WebSocket-Extensions HTTP request header.
357
358 Accept or reject each extension proposed in the client request.
359 Negotiate parameters for accepted extensions.
360
361 Per :rfc:`6455`, negotiation rules are defined by the specification of
362 each extension.
363
364 To provide this level of flexibility, for each extension proposed by
365 the client, we check for a match with each extension available in the
366 server configuration. If no match is found, the extension is ignored.
367
368 If several variants of the same extension are proposed by the client,
369 it may be accepted several times, which won't make sense in general.
370 Extensions must implement their own requirements. For this purpose,
371 the list of previously accepted extensions is provided.
372
373 This process doesn't allow the server to reorder extensions. It can
374 only select a subset of the extensions proposed by the client.
375
376 Other requirements, for example related to mandatory extensions or the
377 order of extensions, may be implemented by overriding this method.
378
379 Args:
380 headers: WebSocket handshake request headers.
381
382 Returns:
383 ``Sec-WebSocket-Extensions`` HTTP response header and list of
384 accepted extensions.
385
386 Raises:
387 InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid.
388
389 """
390 response_header_value: str | None = None
391
392 extension_headers: list[ExtensionHeader] = []
393 accepted_extensions: list[Extension] = []
394
395 header_values = headers.get_all("Sec-WebSocket-Extensions")
396
397 if header_values and self.available_extensions:
398 parsed_header_values: list[ExtensionHeader] = sum(
399 [parse_extension(header_value) for header_value in header_values], []
400 )
401
402 for name, request_params in parsed_header_values:
403 for ext_factory in self.available_extensions:
404 # Skip non-matching extensions based on their name.
405 if ext_factory.name != name:
406 continue
407
408 # Skip non-matching extensions based on their params.
409 try:
410 response_params, extension = ext_factory.process_request_params(
411 request_params, accepted_extensions
412 )
413 except NegotiationError:
414 continue
415
416 # Add matching extension to the final list.
417 extension_headers.append((name, response_params))
418 accepted_extensions.append(extension)
419
420 # Break out of the loop once we have a match.
421 break
422
423 # If we didn't break from the loop, no extension in our list
424 # matched what the client sent. The extension is declined.
425
426 # Serialize extension header.
427 if extension_headers:
428 response_header_value = build_extension(extension_headers)
429
430 return response_header_value, accepted_extensions
431
432 def process_subprotocol(self, headers: Headers) -> Subprotocol | None:
433 """
434 Handle the Sec-WebSocket-Protocol HTTP request header.
435
436 Args:
437 headers: WebSocket handshake request headers.
438
439 Returns:
440 Subprotocol, if one was selected; this is also the value of the
441 ``Sec-WebSocket-Protocol`` response header.
442
443 Raises:
444 InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid.
445
446 """
447 subprotocols: Sequence[Subprotocol] = sum(
448 [
449 parse_subprotocol(header_value)
450 for header_value in headers.get_all("Sec-WebSocket-Protocol")
451 ],
452 [],
453 )
454 return self.select_subprotocol(subprotocols)
455
456 def select_subprotocol(
457 self,
458 subprotocols: Sequence[Subprotocol],
459 ) -> Subprotocol | None:
460 """
461 Pick a subprotocol among those offered by the client.
462
463 If several subprotocols are supported by both the client and the server,
464 pick the first one in the list declared the server.
465
466 If the server doesn't support any subprotocols, continue without a
467 subprotocol, regardless of what the client offers.
468
469 If the server supports at least one subprotocol and the client doesn't
470 offer any, abort the handshake with an HTTP 400 error.
471
472 You provide a ``select_subprotocol`` argument to :class:`ServerProtocol`
473 to override this logic. For example, you could accept the connection
474 even if client doesn't offer a subprotocol, rather than reject it.
475
476 Here's how to negotiate the ``chat`` subprotocol if the client supports
477 it and continue without a subprotocol otherwise::
478
479 def select_subprotocol(protocol, subprotocols):
480 if "chat" in subprotocols:
481 return "chat"
482
483 Args:
484 subprotocols: List of subprotocols offered by the client.
485
486 Returns:
487 Selected subprotocol, if a common subprotocol was found.
488
489 :obj:`None` to continue without a subprotocol.
490
491 Raises:
492 NegotiationError: Custom implementations may raise this exception
493 to abort the handshake with an HTTP 400 error.
494
495 """
496 # Server doesn't offer any subprotocols.
497 if not self.available_subprotocols: # None or empty list
498 return None
499
500 # Server offers at least one subprotocol but client doesn't offer any.
501 if not subprotocols:
502 raise NegotiationError("missing subprotocol")
503
504 # Server and client both offer subprotocols. Look for a shared one.
505 proposed_subprotocols = set(subprotocols)
506 for subprotocol in self.available_subprotocols:
507 if subprotocol in proposed_subprotocols:
508 return subprotocol
509
510 # No common subprotocol was found.
511 raise NegotiationError(
512 "invalid subprotocol; expected one of "
513 + ", ".join(self.available_subprotocols)
514 )
515
516 def reject(self, status: StatusLike, text: str) -> Response:
517 """
518 Create a handshake response to reject the connection.
519
520 A short plain text response is the best fallback when failing to
521 establish a WebSocket connection.
522
523 You must send the handshake response with :meth:`send_response`.
524
525 You may modify the response before sending it, for example by changing
526 HTTP headers.
527
528 Args:
529 status: HTTP status code.
530 text: HTTP response body; it will be encoded to UTF-8.
531
532 Returns:
533 HTTP response to send to the client.
534
535 """
536 # If status is an int instead of an HTTPStatus, fix it automatically.
537 status = http.HTTPStatus(status)
538 body = text.encode()
539 headers = Headers(
540 [
541 ("Date", email.utils.formatdate(usegmt=True)),
542 ("Connection", "close"),
543 ("Content-Length", str(len(body))),
544 ("Content-Type", "text/plain; charset=utf-8"),
545 ]
546 )
547 return Response(status.value, status.phrase, headers, body)
548
549 def send_response(self, response: Response) -> None:
550 """
551 Send a handshake response to the client.
552
553 Args:
554 response: WebSocket handshake response event to send.
555
556 """
557 if self.debug:
558 code, phrase = response.status_code, response.reason_phrase
559 self.logger.debug("> HTTP/1.1 %d %s", code, phrase)
560 for key, value in response.headers.raw_items():
561 self.logger.debug("> %s: %s", key, value)
562 if response.body:
563 self.logger.debug("> [body] (%d bytes)", len(response.body))
564
565 self.writes.append(response.serialize())
566
567 if response.status_code == 101:
568 assert self.state is CONNECTING
569 self.state = OPEN
570 self.logger.info("connection open")
571
572 else:
573 if self.accept_called:
574 log_message = "connection rejected (%d %s)"
575 else:
576 log_message = "HTTP response sent (%d %s)"
577 self.logger.info(
578 log_message,
579 response.status_code,
580 response.reason_phrase,
581 )
582
583 self.send_eof()
584 self.parser = self.discard()
585 next(self.parser) # start coroutine
586
587 def parse(self) -> Generator[None]:
588 if self.state is CONNECTING:
589 try:
590 request = yield from Request.parse(
591 self.reader.read_line,
592 )
593 except RequestLineTooLong as exc:
594 self.handshake_exc = exc
595 if self.debug:
596 self.logger.debug("! request line too long", exc_info=True)
597 response = self.reject(
598 # Change to http.HTTPStatus.URI_TOO_LONG when dropping Python < 3.13
599 http.HTTPStatus.REQUEST_URI_TOO_LONG,
600 f"Failed to open a WebSocket connection: {exc}.\n",
601 )
602 self.send_response(response)
603 yield
604 except (HeaderLineTooLong, TooManyHeaders) as exc:
605 self.handshake_exc = exc
606 if self.debug:
607 self.logger.debug("! header fields too large", exc_info=True)
608 response = self.reject(
609 http.HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
610 f"Failed to open a WebSocket connection: {exc}.\n",
611 )
612 self.send_response(response)
613 yield
614 except Exception as exc:
615 self.handshake_exc = InvalidMessage(
616 "did not receive a valid HTTP request"
617 )
618 if self.debug:
619 self.logger.debug("! no valid HTTP request", exc_info=True)
620 self.handshake_exc.__cause__ = exc
621 self.send_eof()
622 self.parser = self.discard()
623 next(self.parser) # start coroutine
624 yield
625
626 if self.debug:
627 self.logger.debug(
628 "< %s %s %s", request.method, request.path, request.protocol
629 )
630 for key, value in request.headers.raw_items():
631 self.logger.debug("< %s: %s", key, value)
632
633 self.events.append(request)
634
635 yield from super().parse()
636
637
638 class ServerConnection(ServerProtocol):
639 def __init__(self, *args: Any, **kwargs: Any) -> None:
640 warnings.warn( # deprecated in 11.0 - 2023-04-02
641 "ServerConnection was renamed to ServerProtocol",
642 DeprecationWarning,
643 )
644 super().__init__(*args, **kwargs)
645
646
647 lazy_import(
648 globals(),
649 deprecated_aliases={
650 # deprecated in 14.0 - 2024-11-09
651 "WebSocketServer": ".legacy.server",
652 "WebSocketServerProtocol": ".legacy.server",
653 "broadcast": ".legacy.server",
654 "serve": ".legacy.server",
655 "unix_serve": ".legacy.server",
656 },
657 )