File size: 27,436 Bytes
9c6594c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 |
from __future__ import annotations
import hmac
import http
import logging
import os
import re
import selectors
import socket
import ssl as ssl_module
import sys
import threading
import warnings
from collections.abc import Iterable, Sequence
from types import TracebackType
from typing import Any, Callable, Mapping, cast
from ..exceptions import InvalidHeader
from ..extensions.base import ServerExtensionFactory
from ..extensions.permessage_deflate import enable_server_permessage_deflate
from ..frames import CloseCode
from ..headers import (
build_www_authenticate_basic,
parse_authorization_basic,
validate_subprotocols,
)
from ..http11 import SERVER, Request, Response
from ..protocol import CONNECTING, OPEN, Event
from ..server import ServerProtocol
from ..typing import LoggerLike, Origin, StatusLike, Subprotocol
from .connection import Connection
from .utils import Deadline
__all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"]
class ServerConnection(Connection):
"""
:mod:`threading` implementation of a WebSocket server connection.
:class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
receiving and sending messages.
It supports iteration to receive messages::
for message in websocket:
process(message)
The iterator exits normally when the connection is closed with close code
1000 (OK) or 1001 (going away) or without a close code. It raises a
:exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
closed with any other code.
The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
``max_queue`` arguments have the same meaning as in :func:`serve`.
Args:
socket: Socket connected to a WebSocket client.
protocol: Sans-I/O connection.
"""
def __init__(
self,
socket: socket.socket,
protocol: ServerProtocol,
*,
ping_interval: float | None = 20,
ping_timeout: float | None = 20,
close_timeout: float | None = 10,
max_queue: int | None | tuple[int | None, int | None] = 16,
) -> None:
self.protocol: ServerProtocol
self.request_rcvd = threading.Event()
super().__init__(
socket,
protocol,
ping_interval=ping_interval,
ping_timeout=ping_timeout,
close_timeout=close_timeout,
max_queue=max_queue,
)
self.username: str # see basic_auth()
self.handler: Callable[[ServerConnection], None] # see route()
self.handler_kwargs: Mapping[str, Any] # see route()
def respond(self, status: StatusLike, text: str) -> Response:
"""
Create a plain text HTTP response.
``process_request`` and ``process_response`` may call this method to
return an HTTP response instead of performing the WebSocket opening
handshake.
You can modify the response before returning it, for example by changing
HTTP headers.
Args:
status: HTTP status code.
text: HTTP response body; it will be encoded to UTF-8.
Returns:
HTTP response to send to the client.
"""
return self.protocol.reject(status, text)
def handshake(
self,
process_request: (
Callable[
[ServerConnection, Request],
Response | None,
]
| None
) = None,
process_response: (
Callable[
[ServerConnection, Request, Response],
Response | None,
]
| None
) = None,
server_header: str | None = SERVER,
timeout: float | None = None,
) -> None:
"""
Perform the opening handshake.
"""
if not self.request_rcvd.wait(timeout):
raise TimeoutError("timed out while waiting for handshake request")
if self.request is not None:
with self.send_context(expected_state=CONNECTING):
response = None
if process_request is not None:
try:
response = process_request(self, self.request)
except Exception as exc:
self.protocol.handshake_exc = exc
response = self.protocol.reject(
http.HTTPStatus.INTERNAL_SERVER_ERROR,
(
"Failed to open a WebSocket connection.\n"
"See server log for more information.\n"
),
)
if response is None:
self.response = self.protocol.accept(self.request)
else:
self.response = response
if server_header:
self.response.headers["Server"] = server_header
response = None
if process_response is not None:
try:
response = process_response(self, self.request, self.response)
except Exception as exc:
self.protocol.handshake_exc = exc
response = self.protocol.reject(
http.HTTPStatus.INTERNAL_SERVER_ERROR,
(
"Failed to open a WebSocket connection.\n"
"See server log for more information.\n"
),
)
if response is not None:
self.response = response
self.protocol.send_response(self.response)
# self.protocol.handshake_exc is set when the connection is lost before
# receiving a request, when the request cannot be parsed, or when the
# handshake fails, including when process_request or process_response
# raises an exception.
# It isn't set when process_request or process_response sends an HTTP
# response that rejects the handshake.
if self.protocol.handshake_exc is not None:
raise self.protocol.handshake_exc
def process_event(self, event: Event) -> None:
"""
Process one incoming event.
"""
# First event - handshake request.
if self.request is None:
assert isinstance(event, Request)
self.request = event
self.request_rcvd.set()
# Later events - frames.
else:
super().process_event(event)
def recv_events(self) -> None:
"""
Read incoming data from the socket and process events.
"""
try:
super().recv_events()
finally:
# If the connection is closed during the handshake, unblock it.
self.request_rcvd.set()
class Server:
"""
WebSocket server returned by :func:`serve`.
This class mirrors the API of :class:`~socketserver.BaseServer`, notably the
:meth:`~socketserver.BaseServer.serve_forever` and
:meth:`~socketserver.BaseServer.shutdown` methods, as well as the context
manager protocol.
Args:
socket: Server socket listening for new connections.
handler: Handler for one connection. Receives the socket and address
returned by :meth:`~socket.socket.accept`.
logger: Logger for this server.
It defaults to ``logging.getLogger("websockets.server")``.
See the :doc:`logging guide <../../topics/logging>` for details.
"""
def __init__(
self,
socket: socket.socket,
handler: Callable[[socket.socket, Any], None],
logger: LoggerLike | None = None,
) -> None:
self.socket = socket
self.handler = handler
if logger is None:
logger = logging.getLogger("websockets.server")
self.logger = logger
if sys.platform != "win32":
self.shutdown_watcher, self.shutdown_notifier = os.pipe()
def serve_forever(self) -> None:
"""
See :meth:`socketserver.BaseServer.serve_forever`.
This method doesn't return. Calling :meth:`shutdown` from another thread
stops the server.
Typical use::
with serve(...) as server:
server.serve_forever()
"""
poller = selectors.DefaultSelector()
try:
poller.register(self.socket, selectors.EVENT_READ)
except ValueError: # pragma: no cover
# If shutdown() is called before poller.register(),
# the socket is closed and poller.register() raises
# ValueError: Invalid file descriptor: -1
return
if sys.platform != "win32":
poller.register(self.shutdown_watcher, selectors.EVENT_READ)
while True:
poller.select()
try:
# If the socket is closed, this will raise an exception and exit
# the loop. So we don't need to check the return value of select().
sock, addr = self.socket.accept()
except OSError:
break
# Since there isn't a mechanism for tracking connections and waiting
# for them to terminate, we cannot use daemon threads, or else all
# connections would be terminate brutally when closing the server.
thread = threading.Thread(target=self.handler, args=(sock, addr))
thread.start()
def shutdown(self) -> None:
"""
See :meth:`socketserver.BaseServer.shutdown`.
"""
self.socket.close()
if sys.platform != "win32":
os.write(self.shutdown_notifier, b"x")
def fileno(self) -> int:
"""
See :meth:`socketserver.BaseServer.fileno`.
"""
return self.socket.fileno()
def __enter__(self) -> Server:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
self.shutdown()
def __getattr__(name: str) -> Any:
if name == "WebSocketServer":
warnings.warn( # deprecated in 13.0 - 2024-08-20
"WebSocketServer was renamed to Server",
DeprecationWarning,
)
return Server
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def serve(
handler: Callable[[ServerConnection], None],
host: str | None = None,
port: int | None = None,
*,
# TCP/TLS
sock: socket.socket | None = None,
ssl: ssl_module.SSLContext | None = None,
# WebSocket
origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
extensions: Sequence[ServerExtensionFactory] | None = None,
subprotocols: Sequence[Subprotocol] | None = None,
select_subprotocol: (
Callable[
[ServerConnection, Sequence[Subprotocol]],
Subprotocol | None,
]
| None
) = None,
compression: str | None = "deflate",
# HTTP
process_request: (
Callable[
[ServerConnection, Request],
Response | None,
]
| None
) = None,
process_response: (
Callable[
[ServerConnection, Request, Response],
Response | None,
]
| None
) = None,
server_header: str | None = SERVER,
# Timeouts
open_timeout: float | None = 10,
ping_interval: float | None = 20,
ping_timeout: float | None = 20,
close_timeout: float | None = 10,
# Limits
max_size: int | None = 2**20,
max_queue: int | None | tuple[int | None, int | None] = 16,
# Logging
logger: LoggerLike | None = None,
# Escape hatch for advanced customization
create_connection: type[ServerConnection] | None = None,
**kwargs: Any,
) -> Server:
"""
Create a WebSocket server listening on ``host`` and ``port``.
Whenever a client connects, the server creates a :class:`ServerConnection`,
performs the opening handshake, and delegates to the ``handler``.
The handler receives the :class:`ServerConnection` instance, which you can
use to send and receive messages.
Once the handler completes, either normally or with an exception, the server
performs the closing handshake and closes the connection.
This function returns a :class:`Server` whose API mirrors
:class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
that it will be closed and call :meth:`~Server.serve_forever` to serve
requests::
from websockets.sync.server import serve
def handler(websocket):
...
with serve(handler, ...) as server:
server.serve_forever()
Args:
handler: Connection handler. It receives the WebSocket connection,
which is a :class:`ServerConnection`, in argument.
host: Network interfaces the server binds to.
See :func:`~socket.create_server` for details.
port: TCP port the server listens on.
See :func:`~socket.create_server` for details.
sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
You may call :func:`socket.create_server` to create a suitable TCP
socket.
ssl: Configuration for enabling TLS on the connection.
origins: Acceptable values of the ``Origin`` header, for defending
against Cross-Site WebSocket Hijacking attacks. Values can be
:class:`str` to test for an exact match or regular expressions
compiled by :func:`re.compile` to test against a pattern. Include
:obj:`None` in the list if the lack of an origin is acceptable.
extensions: List of supported extensions, in order in which they
should be negotiated and run.
subprotocols: List of supported subprotocols, in order of decreasing
preference.
select_subprotocol: Callback for selecting a subprotocol among
those supported by the client and the server. It receives a
:class:`ServerConnection` (not a
:class:`~websockets.server.ServerProtocol`!) instance and a list of
subprotocols offered by the client. Other than the first argument,
it has the same behavior as the
:meth:`ServerProtocol.select_subprotocol
<websockets.server.ServerProtocol.select_subprotocol>` method.
compression: The "permessage-deflate" extension is enabled by default.
Set ``compression`` to :obj:`None` to disable it. See the
:doc:`compression guide <../../topics/compression>` for details.
process_request: Intercept the request during the opening handshake.
Return an HTTP response to force the response. Return :obj:`None` to
continue normally. When you force an HTTP 101 Continue response, the
handshake is successful. Else, the connection is aborted.
process_response: Intercept the response during the opening handshake.
Modify the response or return a new HTTP response to force the
response. Return :obj:`None` to continue normally. When you force an
HTTP 101 Continue response, the handshake is successful. Else, the
connection is aborted.
server_header: Value of the ``Server`` response header.
It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
:obj:`None` removes the header.
open_timeout: Timeout for opening connections in seconds.
:obj:`None` disables the timeout.
ping_interval: Interval between keepalive pings in seconds.
:obj:`None` disables keepalive.
ping_timeout: Timeout for keepalive pings in seconds.
:obj:`None` disables timeouts.
close_timeout: Timeout for closing connections in seconds.
:obj:`None` disables the timeout.
max_size: Maximum size of incoming messages in bytes.
:obj:`None` disables the limit.
max_queue: High-water mark of the buffer where frames are received.
It defaults to 16 frames. The low-water mark defaults to ``max_queue
// 4``. You may pass a ``(high, low)`` tuple to set the high-water
and low-water marks. If you want to disable flow control entirely,
you may set it to ``None``, although that's a bad idea.
logger: Logger for this server.
It defaults to ``logging.getLogger("websockets.server")``. See the
:doc:`logging guide <../../topics/logging>` for details.
create_connection: Factory for the :class:`ServerConnection` managing
the connection. Set it to a wrapper or a subclass to customize
connection handling.
Any other keyword arguments are passed to :func:`~socket.create_server`.
"""
# Process parameters
# Backwards compatibility: ssl used to be called ssl_context.
if ssl is None and "ssl_context" in kwargs:
ssl = kwargs.pop("ssl_context")
warnings.warn( # deprecated in 13.0 - 2024-08-20
"ssl_context was renamed to ssl",
DeprecationWarning,
)
if subprotocols is not None:
validate_subprotocols(subprotocols)
if compression == "deflate":
extensions = enable_server_permessage_deflate(extensions)
elif compression is not None:
raise ValueError(f"unsupported compression: {compression}")
if create_connection is None:
create_connection = ServerConnection
# Bind socket and listen
# Private APIs for unix_connect()
unix: bool = kwargs.pop("unix", False)
path: str | None = kwargs.pop("path", None)
if sock is None:
if unix:
if path is None:
raise ValueError("missing path argument")
kwargs.setdefault("family", socket.AF_UNIX)
sock = socket.create_server(path, **kwargs)
else:
sock = socket.create_server((host, port), **kwargs)
else:
if path is not None:
raise ValueError("path and sock arguments are incompatible")
# Initialize TLS wrapper
if ssl is not None:
sock = ssl.wrap_socket(
sock,
server_side=True,
# Delay TLS handshake until after we set a timeout on the socket.
do_handshake_on_connect=False,
)
# Define request handler
def conn_handler(sock: socket.socket, addr: Any) -> None:
# Calculate timeouts on the TLS and WebSocket handshakes.
# The TLS timeout must be set on the socket, then removed
# to avoid conflicting with the WebSocket timeout in handshake().
deadline = Deadline(open_timeout)
try:
# Disable Nagle algorithm
if not unix:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
# Perform TLS handshake
if ssl is not None:
sock.settimeout(deadline.timeout())
# mypy cannot figure this out
assert isinstance(sock, ssl_module.SSLSocket)
sock.do_handshake()
sock.settimeout(None)
# Create a closure to give select_subprotocol access to connection.
protocol_select_subprotocol: (
Callable[
[ServerProtocol, Sequence[Subprotocol]],
Subprotocol | None,
]
| None
) = None
if select_subprotocol is not None:
def protocol_select_subprotocol(
protocol: ServerProtocol,
subprotocols: Sequence[Subprotocol],
) -> Subprotocol | None:
# mypy doesn't know that select_subprotocol is immutable.
assert select_subprotocol is not None
# Ensure this function is only used in the intended context.
assert protocol is connection.protocol
return select_subprotocol(connection, subprotocols)
# Initialize WebSocket protocol
protocol = ServerProtocol(
origins=origins,
extensions=extensions,
subprotocols=subprotocols,
select_subprotocol=protocol_select_subprotocol,
max_size=max_size,
logger=logger,
)
# Initialize WebSocket connection
assert create_connection is not None # help mypy
connection = create_connection(
sock,
protocol,
ping_interval=ping_interval,
ping_timeout=ping_timeout,
close_timeout=close_timeout,
max_queue=max_queue,
)
except Exception:
sock.close()
return
try:
try:
connection.handshake(
process_request,
process_response,
server_header,
deadline.timeout(),
)
except TimeoutError:
connection.close_socket()
connection.recv_events_thread.join()
return
except Exception:
connection.logger.error("opening handshake failed", exc_info=True)
connection.close_socket()
connection.recv_events_thread.join()
return
assert connection.protocol.state is OPEN
try:
connection.start_keepalive()
handler(connection)
except Exception:
connection.logger.error("connection handler failed", exc_info=True)
connection.close(CloseCode.INTERNAL_ERROR)
else:
connection.close()
except Exception: # pragma: no cover
# Don't leak sockets on unexpected errors.
sock.close()
# Initialize server
return Server(sock, conn_handler, logger)
def unix_serve(
handler: Callable[[ServerConnection], None],
path: str | None = None,
**kwargs: Any,
) -> Server:
"""
Create a WebSocket server listening on a Unix socket.
This function accepts the same keyword arguments as :func:`serve`.
It's only available on Unix.
It's useful for deploying a server behind a reverse proxy such as nginx.
Args:
handler: Connection handler. It receives the WebSocket connection,
which is a :class:`ServerConnection`, in argument.
path: File system path to the Unix socket.
"""
return serve(handler, unix=True, path=path, **kwargs)
def is_credentials(credentials: Any) -> bool:
try:
username, password = credentials
except (TypeError, ValueError):
return False
else:
return isinstance(username, str) and isinstance(password, str)
def basic_auth(
realm: str = "",
credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None,
check_credentials: Callable[[str, str], bool] | None = None,
) -> Callable[[ServerConnection, Request], Response | None]:
"""
Factory for ``process_request`` to enforce HTTP Basic Authentication.
:func:`basic_auth` is designed to integrate with :func:`serve` as follows::
from websockets.sync.server import basic_auth, serve
with serve(
...,
process_request=basic_auth(
realm="my dev server",
credentials=("hello", "iloveyou"),
),
):
If authentication succeeds, the connection's ``username`` attribute is set.
If it fails, the server responds with an HTTP 401 Unauthorized status.
One of ``credentials`` or ``check_credentials`` must be provided; not both.
Args:
realm: Scope of protection. It should contain only ASCII characters
because the encoding of non-ASCII characters is undefined. Refer to
section 2.2 of :rfc:`7235` for details.
credentials: Hard coded authorized credentials. It can be a
``(username, password)`` pair or a list of such pairs.
check_credentials: Function that verifies credentials.
It receives ``username`` and ``password`` arguments and returns
whether they're valid.
Raises:
TypeError: If ``credentials`` or ``check_credentials`` is wrong.
ValueError: If ``credentials`` and ``check_credentials`` are both
provided or both not provided.
"""
if (credentials is None) == (check_credentials is None):
raise ValueError("provide either credentials or check_credentials")
if credentials is not None:
if is_credentials(credentials):
credentials_list = [cast(tuple[str, str], credentials)]
elif isinstance(credentials, Iterable):
credentials_list = list(cast(Iterable[tuple[str, str]], credentials))
if not all(is_credentials(item) for item in credentials_list):
raise TypeError(f"invalid credentials argument: {credentials}")
else:
raise TypeError(f"invalid credentials argument: {credentials}")
credentials_dict = dict(credentials_list)
def check_credentials(username: str, password: str) -> bool:
try:
expected_password = credentials_dict[username]
except KeyError:
return False
return hmac.compare_digest(expected_password, password)
assert check_credentials is not None # help mypy
def process_request(
connection: ServerConnection,
request: Request,
) -> Response | None:
"""
Perform HTTP Basic Authentication.
If it succeeds, set the connection's ``username`` attribute and return
:obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.
"""
try:
authorization = request.headers["Authorization"]
except KeyError:
response = connection.respond(
http.HTTPStatus.UNAUTHORIZED,
"Missing credentials\n",
)
response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
return response
try:
username, password = parse_authorization_basic(authorization)
except InvalidHeader:
response = connection.respond(
http.HTTPStatus.UNAUTHORIZED,
"Unsupported credentials\n",
)
response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
return response
if not check_credentials(username, password):
response = connection.respond(
http.HTTPStatus.UNAUTHORIZED,
"Invalid credentials\n",
)
response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
return response
connection.username = username
return None
return process_request
|