server.py 34 KB

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