server.py 34 KB

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