You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

982 lines
36 KiB

  1. from __future__ import annotations
  2. import asyncio
  3. import hmac
  4. import http
  5. import logging
  6. import re
  7. import socket
  8. import sys
  9. from collections.abc import Awaitable, Generator, Iterable, Sequence
  10. from types import TracebackType
  11. from typing import Any, Callable, Mapping, cast
  12. from ..exceptions import InvalidHeader
  13. from ..extensions.base import ServerExtensionFactory
  14. from ..extensions.permessage_deflate import enable_server_permessage_deflate
  15. from ..frames import CloseCode
  16. from ..headers import (
  17. build_www_authenticate_basic,
  18. parse_authorization_basic,
  19. validate_subprotocols,
  20. )
  21. from ..http11 import SERVER, Request, Response
  22. from ..protocol import CONNECTING, OPEN, Event
  23. from ..server import ServerProtocol
  24. from ..typing import LoggerLike, Origin, StatusLike, Subprotocol
  25. from .compatibility import asyncio_timeout
  26. from .connection import Connection, broadcast
  27. __all__ = [
  28. "broadcast",
  29. "serve",
  30. "unix_serve",
  31. "ServerConnection",
  32. "Server",
  33. "basic_auth",
  34. ]
  35. class ServerConnection(Connection):
  36. """
  37. :mod:`asyncio` implementation of a WebSocket server connection.
  38. :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
  39. receiving and sending messages.
  40. It supports asynchronous iteration to receive messages::
  41. async for message in websocket:
  42. await process(message)
  43. The iterator exits normally when the connection is closed with close code
  44. 1000 (OK) or 1001 (going away) or without a close code. It raises a
  45. :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
  46. closed with any other code.
  47. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
  48. and ``write_limit`` arguments have the same meaning as in :func:`serve`.
  49. Args:
  50. protocol: Sans-I/O connection.
  51. server: Server that manages this connection.
  52. """
  53. def __init__(
  54. self,
  55. protocol: ServerProtocol,
  56. server: Server,
  57. *,
  58. ping_interval: float | None = 20,
  59. ping_timeout: float | None = 20,
  60. close_timeout: float | None = 10,
  61. max_queue: int | None | tuple[int | None, int | None] = 16,
  62. write_limit: int | tuple[int, int | None] = 2**15,
  63. ) -> None:
  64. self.protocol: ServerProtocol
  65. super().__init__(
  66. protocol,
  67. ping_interval=ping_interval,
  68. ping_timeout=ping_timeout,
  69. close_timeout=close_timeout,
  70. max_queue=max_queue,
  71. write_limit=write_limit,
  72. )
  73. self.server = server
  74. self.request_rcvd: asyncio.Future[None] = self.loop.create_future()
  75. self.username: str # see basic_auth()
  76. self.handler: Callable[[ServerConnection], Awaitable[None]] # see route()
  77. self.handler_kwargs: Mapping[str, Any] # see route()
  78. def respond(self, status: StatusLike, text: str) -> Response:
  79. """
  80. Create a plain text HTTP response.
  81. ``process_request`` and ``process_response`` may call this method to
  82. return an HTTP response instead of performing the WebSocket opening
  83. handshake.
  84. You can modify the response before returning it, for example by changing
  85. HTTP headers.
  86. Args:
  87. status: HTTP status code.
  88. text: HTTP response body; it will be encoded to UTF-8.
  89. Returns:
  90. HTTP response to send to the client.
  91. """
  92. return self.protocol.reject(status, text)
  93. async def handshake(
  94. self,
  95. process_request: (
  96. Callable[
  97. [ServerConnection, Request],
  98. Awaitable[Response | None] | Response | None,
  99. ]
  100. | None
  101. ) = None,
  102. process_response: (
  103. Callable[
  104. [ServerConnection, Request, Response],
  105. Awaitable[Response | None] | Response | None,
  106. ]
  107. | None
  108. ) = None,
  109. server_header: str | None = SERVER,
  110. ) -> None:
  111. """
  112. Perform the opening handshake.
  113. """
  114. await asyncio.wait(
  115. [self.request_rcvd, self.connection_lost_waiter],
  116. return_when=asyncio.FIRST_COMPLETED,
  117. )
  118. if self.request is not None:
  119. async with self.send_context(expected_state=CONNECTING):
  120. response = None
  121. if process_request is not None:
  122. try:
  123. response = process_request(self, self.request)
  124. if isinstance(response, Awaitable):
  125. response = await response
  126. except Exception as exc:
  127. self.protocol.handshake_exc = exc
  128. response = self.protocol.reject(
  129. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  130. (
  131. "Failed to open a WebSocket connection.\n"
  132. "See server log for more information.\n"
  133. ),
  134. )
  135. if response is None:
  136. if self.server.is_serving():
  137. self.response = self.protocol.accept(self.request)
  138. else:
  139. self.response = self.protocol.reject(
  140. http.HTTPStatus.SERVICE_UNAVAILABLE,
  141. "Server is shutting down.\n",
  142. )
  143. else:
  144. assert isinstance(response, Response) # help mypy
  145. self.response = response
  146. if server_header:
  147. self.response.headers["Server"] = server_header
  148. response = None
  149. if process_response is not None:
  150. try:
  151. response = process_response(self, self.request, self.response)
  152. if isinstance(response, Awaitable):
  153. response = await response
  154. except Exception as exc:
  155. self.protocol.handshake_exc = exc
  156. response = self.protocol.reject(
  157. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  158. (
  159. "Failed to open a WebSocket connection.\n"
  160. "See server log for more information.\n"
  161. ),
  162. )
  163. if response is not None:
  164. assert isinstance(response, Response) # help mypy
  165. self.response = response
  166. self.protocol.send_response(self.response)
  167. # self.protocol.handshake_exc is set when the connection is lost before
  168. # receiving a request, when the request cannot be parsed, or when the
  169. # handshake fails, including when process_request or process_response
  170. # raises an exception.
  171. # It isn't set when process_request or process_response sends an HTTP
  172. # response that rejects the handshake.
  173. if self.protocol.handshake_exc is not None:
  174. raise self.protocol.handshake_exc
  175. def process_event(self, event: Event) -> None:
  176. """
  177. Process one incoming event.
  178. """
  179. # First event - handshake request.
  180. if self.request is None:
  181. assert isinstance(event, Request)
  182. self.request = event
  183. self.request_rcvd.set_result(None)
  184. # Later events - frames.
  185. else:
  186. super().process_event(event)
  187. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  188. super().connection_made(transport)
  189. self.server.start_connection_handler(self)
  190. class Server:
  191. """
  192. WebSocket server returned by :func:`serve`.
  193. This class mirrors the API of :class:`asyncio.Server`.
  194. It keeps track of WebSocket connections in order to close them properly
  195. when shutting down.
  196. Args:
  197. handler: Connection handler. It receives the WebSocket connection,
  198. which is a :class:`ServerConnection`, in argument.
  199. process_request: Intercept the request during the opening handshake.
  200. Return an HTTP response to force the response. Return :obj:`None` to
  201. continue normally. When you force an HTTP 101 Continue response, the
  202. handshake is successful. Else, the connection is aborted.
  203. ``process_request`` may be a function or a coroutine.
  204. process_response: Intercept the response during the opening handshake.
  205. Modify the response or return a new HTTP response to force the
  206. response. Return :obj:`None` to continue normally. When you force an
  207. HTTP 101 Continue response, the handshake is successful. Else, the
  208. connection is aborted. ``process_response`` may be a function or a
  209. coroutine.
  210. server_header: Value of the ``Server`` response header.
  211. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
  212. :obj:`None` removes the header.
  213. open_timeout: Timeout for opening connections in seconds.
  214. :obj:`None` disables the timeout.
  215. logger: Logger for this server.
  216. It defaults to ``logging.getLogger("websockets.server")``.
  217. See the :doc:`logging guide <../../topics/logging>` for details.
  218. """
  219. def __init__(
  220. self,
  221. handler: Callable[[ServerConnection], Awaitable[None]],
  222. *,
  223. process_request: (
  224. Callable[
  225. [ServerConnection, Request],
  226. Awaitable[Response | None] | Response | None,
  227. ]
  228. | None
  229. ) = None,
  230. process_response: (
  231. Callable[
  232. [ServerConnection, Request, Response],
  233. Awaitable[Response | None] | Response | None,
  234. ]
  235. | None
  236. ) = None,
  237. server_header: str | None = SERVER,
  238. open_timeout: float | None = 10,
  239. logger: LoggerLike | None = None,
  240. ) -> None:
  241. self.loop = asyncio.get_running_loop()
  242. self.handler = handler
  243. self.process_request = process_request
  244. self.process_response = process_response
  245. self.server_header = server_header
  246. self.open_timeout = open_timeout
  247. if logger is None:
  248. logger = logging.getLogger("websockets.server")
  249. self.logger = logger
  250. # Keep track of active connections.
  251. self.handlers: dict[ServerConnection, asyncio.Task[None]] = {}
  252. # Task responsible for closing the server and terminating connections.
  253. self.close_task: asyncio.Task[None] | None = None
  254. # Completed when the server is closed and connections are terminated.
  255. self.closed_waiter: asyncio.Future[None] = self.loop.create_future()
  256. @property
  257. def connections(self) -> set[ServerConnection]:
  258. """
  259. Set of active connections.
  260. This property contains all connections that completed the opening
  261. handshake successfully and didn't start the closing handshake yet.
  262. It can be useful in combination with :func:`~broadcast`.
  263. """
  264. return {connection for connection in self.handlers if connection.state is OPEN}
  265. def wrap(self, server: asyncio.Server) -> None:
  266. """
  267. Attach to a given :class:`asyncio.Server`.
  268. Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
  269. custom ``Server`` class, the easiest solution that doesn't rely on
  270. private :mod:`asyncio` APIs is to:
  271. - instantiate a :class:`Server`
  272. - give the protocol factory a reference to that instance
  273. - call :meth:`~asyncio.loop.create_server` with the factory
  274. - attach the resulting :class:`asyncio.Server` with this method
  275. """
  276. self.server = server
  277. for sock in server.sockets:
  278. if sock.family == socket.AF_INET:
  279. name = "%s:%d" % sock.getsockname()
  280. elif sock.family == socket.AF_INET6:
  281. name = "[%s]:%d" % sock.getsockname()[:2]
  282. elif sock.family == socket.AF_UNIX:
  283. name = sock.getsockname()
  284. # In the unlikely event that someone runs websockets over a
  285. # protocol other than IP or Unix sockets, avoid crashing.
  286. else: # pragma: no cover
  287. name = str(sock.getsockname())
  288. self.logger.info("server listening on %s", name)
  289. async def conn_handler(self, connection: ServerConnection) -> None:
  290. """
  291. Handle the lifecycle of a WebSocket connection.
  292. Since this method doesn't have a caller that can handle exceptions,
  293. it attempts to log relevant ones.
  294. It guarantees that the TCP connection is closed before exiting.
  295. """
  296. try:
  297. async with asyncio_timeout(self.open_timeout):
  298. try:
  299. await connection.handshake(
  300. self.process_request,
  301. self.process_response,
  302. self.server_header,
  303. )
  304. except asyncio.CancelledError:
  305. connection.transport.abort()
  306. raise
  307. except Exception:
  308. connection.logger.error("opening handshake failed", exc_info=True)
  309. connection.transport.abort()
  310. return
  311. if connection.protocol.state is not OPEN:
  312. # process_request or process_response rejected the handshake.
  313. connection.transport.abort()
  314. return
  315. try:
  316. connection.start_keepalive()
  317. await self.handler(connection)
  318. except Exception:
  319. connection.logger.error("connection handler failed", exc_info=True)
  320. await connection.close(CloseCode.INTERNAL_ERROR)
  321. else:
  322. await connection.close()
  323. except TimeoutError:
  324. # When the opening handshake times out, there's nothing to log.
  325. pass
  326. except Exception: # pragma: no cover
  327. # Don't leak connections on unexpected errors.
  328. connection.transport.abort()
  329. finally:
  330. # Registration is tied to the lifecycle of conn_handler() because
  331. # the server waits for connection handlers to terminate, even if
  332. # all connections are already closed.
  333. del self.handlers[connection]
  334. def start_connection_handler(self, connection: ServerConnection) -> None:
  335. """
  336. Register a connection with this server.
  337. """
  338. # The connection must be registered in self.handlers immediately.
  339. # If it was registered in conn_handler(), a race condition could
  340. # happen when closing the server after scheduling conn_handler()
  341. # but before it starts executing.
  342. self.handlers[connection] = self.loop.create_task(self.conn_handler(connection))
  343. def close(self, close_connections: bool = True) -> None:
  344. """
  345. Close the server.
  346. * Close the underlying :class:`asyncio.Server`.
  347. * When ``close_connections`` is :obj:`True`, which is the default,
  348. close existing connections. Specifically:
  349. * Reject opening WebSocket connections with an HTTP 503 (service
  350. unavailable) error. This happens when the server accepted the TCP
  351. connection but didn't complete the opening handshake before closing.
  352. * Close open WebSocket connections with close code 1001 (going away).
  353. * Wait until all connection handlers terminate.
  354. :meth:`close` is idempotent.
  355. """
  356. if self.close_task is None:
  357. self.close_task = self.get_loop().create_task(
  358. self._close(close_connections)
  359. )
  360. async def _close(self, close_connections: bool) -> None:
  361. """
  362. Implementation of :meth:`close`.
  363. This calls :meth:`~asyncio.Server.close` on the underlying
  364. :class:`asyncio.Server` object to stop accepting new connections and
  365. then closes open connections with close code 1001.
  366. """
  367. self.logger.info("server closing")
  368. # Stop accepting new connections.
  369. self.server.close()
  370. # Wait until all accepted connections reach connection_made() and call
  371. # register(). See https://github.com/python/cpython/issues/79033 for
  372. # details. This workaround can be removed when dropping Python < 3.11.
  373. await asyncio.sleep(0)
  374. if close_connections:
  375. # Close OPEN connections with close code 1001. After server.close(),
  376. # handshake() closes OPENING connections with an HTTP 503 error.
  377. close_tasks = [
  378. asyncio.create_task(connection.close(1001))
  379. for connection in self.handlers
  380. if connection.protocol.state is not CONNECTING
  381. ]
  382. # asyncio.wait doesn't accept an empty first argument.
  383. if close_tasks:
  384. await asyncio.wait(close_tasks)
  385. # Wait until all TCP connections are closed.
  386. await self.server.wait_closed()
  387. # Wait until all connection handlers terminate.
  388. # asyncio.wait doesn't accept an empty first argument.
  389. if self.handlers:
  390. await asyncio.wait(self.handlers.values())
  391. # Tell wait_closed() to return.
  392. self.closed_waiter.set_result(None)
  393. self.logger.info("server closed")
  394. async def wait_closed(self) -> None:
  395. """
  396. Wait until the server is closed.
  397. When :meth:`wait_closed` returns, all TCP connections are closed and
  398. all connection handlers have returned.
  399. To ensure a fast shutdown, a connection handler should always be
  400. awaiting at least one of:
  401. * :meth:`~ServerConnection.recv`: when the connection is closed,
  402. it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
  403. * :meth:`~ServerConnection.wait_closed`: when the connection is
  404. closed, it returns.
  405. Then the connection handler is immediately notified of the shutdown;
  406. it can clean up and exit.
  407. """
  408. await asyncio.shield(self.closed_waiter)
  409. def get_loop(self) -> asyncio.AbstractEventLoop:
  410. """
  411. See :meth:`asyncio.Server.get_loop`.
  412. """
  413. return self.server.get_loop()
  414. def is_serving(self) -> bool: # pragma: no cover
  415. """
  416. See :meth:`asyncio.Server.is_serving`.
  417. """
  418. return self.server.is_serving()
  419. async def start_serving(self) -> None: # pragma: no cover
  420. """
  421. See :meth:`asyncio.Server.start_serving`.
  422. Typical use::
  423. server = await serve(..., start_serving=False)
  424. # perform additional setup here...
  425. # ... then start the server
  426. await server.start_serving()
  427. """
  428. await self.server.start_serving()
  429. async def serve_forever(self) -> None: # pragma: no cover
  430. """
  431. See :meth:`asyncio.Server.serve_forever`.
  432. Typical use::
  433. server = await serve(...)
  434. # this coroutine doesn't return
  435. # canceling it stops the server
  436. await server.serve_forever()
  437. This is an alternative to using :func:`serve` as an asynchronous context
  438. manager. Shutdown is triggered by canceling :meth:`serve_forever`
  439. instead of exiting a :func:`serve` context.
  440. """
  441. await self.server.serve_forever()
  442. @property
  443. def sockets(self) -> Iterable[socket.socket]:
  444. """
  445. See :attr:`asyncio.Server.sockets`.
  446. """
  447. return self.server.sockets
  448. async def __aenter__(self) -> Server: # pragma: no cover
  449. return self
  450. async def __aexit__(
  451. self,
  452. exc_type: type[BaseException] | None,
  453. exc_value: BaseException | None,
  454. traceback: TracebackType | None,
  455. ) -> None: # pragma: no cover
  456. self.close()
  457. await self.wait_closed()
  458. # This is spelled in lower case because it's exposed as a callable in the API.
  459. class serve:
  460. """
  461. Create a WebSocket server listening on ``host`` and ``port``.
  462. Whenever a client connects, the server creates a :class:`ServerConnection`,
  463. performs the opening handshake, and delegates to the ``handler`` coroutine.
  464. The handler receives the :class:`ServerConnection` instance, which you can
  465. use to send and receive messages.
  466. Once the handler completes, either normally or with an exception, the server
  467. performs the closing handshake and closes the connection.
  468. This coroutine returns a :class:`Server` whose API mirrors
  469. :class:`asyncio.Server`. Treat it as an asynchronous context manager to
  470. ensure that the server will be closed::
  471. from websockets.asyncio.server import serve
  472. def handler(websocket):
  473. ...
  474. # set this future to exit the server
  475. stop = asyncio.get_running_loop().create_future()
  476. async with serve(handler, host, port):
  477. await stop
  478. Alternatively, call :meth:`~Server.serve_forever` to serve requests and
  479. cancel it to stop the server::
  480. server = await serve(handler, host, port)
  481. await server.serve_forever()
  482. Args:
  483. handler: Connection handler. It receives the WebSocket connection,
  484. which is a :class:`ServerConnection`, in argument.
  485. host: Network interfaces the server binds to.
  486. See :meth:`~asyncio.loop.create_server` for details.
  487. port: TCP port the server listens on.
  488. See :meth:`~asyncio.loop.create_server` for details.
  489. origins: Acceptable values of the ``Origin`` header, for defending
  490. against Cross-Site WebSocket Hijacking attacks. Values can be
  491. :class:`str` to test for an exact match or regular expressions
  492. compiled by :func:`re.compile` to test against a pattern. Include
  493. :obj:`None` in the list if the lack of an origin is acceptable.
  494. extensions: List of supported extensions, in order in which they
  495. should be negotiated and run.
  496. subprotocols: List of supported subprotocols, in order of decreasing
  497. preference.
  498. select_subprotocol: Callback for selecting a subprotocol among
  499. those supported by the client and the server. It receives a
  500. :class:`ServerConnection` (not a
  501. :class:`~websockets.server.ServerProtocol`!) instance and a list of
  502. subprotocols offered by the client. Other than the first argument,
  503. it has the same behavior as the
  504. :meth:`ServerProtocol.select_subprotocol
  505. <websockets.server.ServerProtocol.select_subprotocol>` method.
  506. compression: The "permessage-deflate" extension is enabled by default.
  507. Set ``compression`` to :obj:`None` to disable it. See the
  508. :doc:`compression guide <../../topics/compression>` for details.
  509. process_request: Intercept the request during the opening handshake.
  510. Return an HTTP response to force the response or :obj:`None` to
  511. continue normally. When you force an HTTP 101 Continue response, the
  512. handshake is successful. Else, the connection is aborted.
  513. ``process_request`` may be a function or a coroutine.
  514. process_response: Intercept the response during the opening handshake.
  515. Return an HTTP response to force the response or :obj:`None` to
  516. continue normally. When you force an HTTP 101 Continue response, the
  517. handshake is successful. Else, the connection is aborted.
  518. ``process_response`` may be a function or a coroutine.
  519. server_header: Value of the ``Server`` response header.
  520. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
  521. :obj:`None` removes the header.
  522. open_timeout: Timeout for opening connections in seconds.
  523. :obj:`None` disables the timeout.
  524. ping_interval: Interval between keepalive pings in seconds.
  525. :obj:`None` disables keepalive.
  526. ping_timeout: Timeout for keepalive pings in seconds.
  527. :obj:`None` disables timeouts.
  528. close_timeout: Timeout for closing connections in seconds.
  529. :obj:`None` disables the timeout.
  530. max_size: Maximum size of incoming messages in bytes.
  531. :obj:`None` disables the limit.
  532. max_queue: High-water mark of the buffer where frames are received.
  533. It defaults to 16 frames. The low-water mark defaults to ``max_queue
  534. // 4``. You may pass a ``(high, low)`` tuple to set the high-water
  535. and low-water marks. If you want to disable flow control entirely,
  536. you may set it to ``None``, although that's a bad idea.
  537. write_limit: High-water mark of write buffer in bytes. It is passed to
  538. :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
  539. to 32 KiB. You may pass a ``(high, low)`` tuple to set the
  540. high-water and low-water marks.
  541. logger: Logger for this server.
  542. It defaults to ``logging.getLogger("websockets.server")``. See the
  543. :doc:`logging guide <../../topics/logging>` for details.
  544. create_connection: Factory for the :class:`ServerConnection` managing
  545. the connection. Set it to a wrapper or a subclass to customize
  546. connection handling.
  547. Any other keyword arguments are passed to the event loop's
  548. :meth:`~asyncio.loop.create_server` method.
  549. For example:
  550. * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.
  551. * You can set ``sock`` to provide a preexisting TCP socket. You may call
  552. :func:`socket.create_server` (not to be confused with the event loop's
  553. :meth:`~asyncio.loop.create_server` method) to create a suitable server
  554. socket and customize it.
  555. * You can set ``start_serving`` to ``False`` to start accepting connections
  556. only after you call :meth:`~Server.start_serving()` or
  557. :meth:`~Server.serve_forever()`.
  558. """
  559. def __init__(
  560. self,
  561. handler: Callable[[ServerConnection], Awaitable[None]],
  562. host: str | None = None,
  563. port: int | None = None,
  564. *,
  565. # WebSocket
  566. origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
  567. extensions: Sequence[ServerExtensionFactory] | None = None,
  568. subprotocols: Sequence[Subprotocol] | None = None,
  569. select_subprotocol: (
  570. Callable[
  571. [ServerConnection, Sequence[Subprotocol]],
  572. Subprotocol | None,
  573. ]
  574. | None
  575. ) = None,
  576. compression: str | None = "deflate",
  577. # HTTP
  578. process_request: (
  579. Callable[
  580. [ServerConnection, Request],
  581. Awaitable[Response | None] | Response | None,
  582. ]
  583. | None
  584. ) = None,
  585. process_response: (
  586. Callable[
  587. [ServerConnection, Request, Response],
  588. Awaitable[Response | None] | Response | None,
  589. ]
  590. | None
  591. ) = None,
  592. server_header: str | None = SERVER,
  593. # Timeouts
  594. open_timeout: float | None = 10,
  595. ping_interval: float | None = 20,
  596. ping_timeout: float | None = 20,
  597. close_timeout: float | None = 10,
  598. # Limits
  599. max_size: int | None = 2**20,
  600. max_queue: int | None | tuple[int | None, int | None] = 16,
  601. write_limit: int | tuple[int, int | None] = 2**15,
  602. # Logging
  603. logger: LoggerLike | None = None,
  604. # Escape hatch for advanced customization
  605. create_connection: type[ServerConnection] | None = None,
  606. # Other keyword arguments are passed to loop.create_server
  607. **kwargs: Any,
  608. ) -> None:
  609. if subprotocols is not None:
  610. validate_subprotocols(subprotocols)
  611. if compression == "deflate":
  612. extensions = enable_server_permessage_deflate(extensions)
  613. elif compression is not None:
  614. raise ValueError(f"unsupported compression: {compression}")
  615. if create_connection is None:
  616. create_connection = ServerConnection
  617. self.server = Server(
  618. handler,
  619. process_request=process_request,
  620. process_response=process_response,
  621. server_header=server_header,
  622. open_timeout=open_timeout,
  623. logger=logger,
  624. )
  625. if kwargs.get("ssl") is not None:
  626. kwargs.setdefault("ssl_handshake_timeout", open_timeout)
  627. if sys.version_info[:2] >= (3, 11): # pragma: no branch
  628. kwargs.setdefault("ssl_shutdown_timeout", close_timeout)
  629. def factory() -> ServerConnection:
  630. """
  631. Create an asyncio protocol for managing a WebSocket connection.
  632. """
  633. # Create a closure to give select_subprotocol access to connection.
  634. protocol_select_subprotocol: (
  635. Callable[
  636. [ServerProtocol, Sequence[Subprotocol]],
  637. Subprotocol | None,
  638. ]
  639. | None
  640. ) = None
  641. if select_subprotocol is not None:
  642. def protocol_select_subprotocol(
  643. protocol: ServerProtocol,
  644. subprotocols: Sequence[Subprotocol],
  645. ) -> Subprotocol | None:
  646. # mypy doesn't know that select_subprotocol is immutable.
  647. assert select_subprotocol is not None
  648. # Ensure this function is only used in the intended context.
  649. assert protocol is connection.protocol
  650. return select_subprotocol(connection, subprotocols)
  651. # This is a protocol in the Sans-I/O implementation of websockets.
  652. protocol = ServerProtocol(
  653. origins=origins,
  654. extensions=extensions,
  655. subprotocols=subprotocols,
  656. select_subprotocol=protocol_select_subprotocol,
  657. max_size=max_size,
  658. logger=logger,
  659. )
  660. # This is a connection in websockets and a protocol in asyncio.
  661. connection = create_connection(
  662. protocol,
  663. self.server,
  664. ping_interval=ping_interval,
  665. ping_timeout=ping_timeout,
  666. close_timeout=close_timeout,
  667. max_queue=max_queue,
  668. write_limit=write_limit,
  669. )
  670. return connection
  671. loop = asyncio.get_running_loop()
  672. if kwargs.pop("unix", False):
  673. self.create_server = loop.create_unix_server(factory, **kwargs)
  674. else:
  675. # mypy cannot tell that kwargs must provide sock when port is None.
  676. self.create_server = loop.create_server(factory, host, port, **kwargs) # type: ignore[arg-type]
  677. # async with serve(...) as ...: ...
  678. async def __aenter__(self) -> Server:
  679. return await self
  680. async def __aexit__(
  681. self,
  682. exc_type: type[BaseException] | None,
  683. exc_value: BaseException | None,
  684. traceback: TracebackType | None,
  685. ) -> None:
  686. self.server.close()
  687. await self.server.wait_closed()
  688. # ... = await serve(...)
  689. def __await__(self) -> Generator[Any, None, Server]:
  690. # Create a suitable iterator by calling __await__ on a coroutine.
  691. return self.__await_impl__().__await__()
  692. async def __await_impl__(self) -> Server:
  693. server = await self.create_server
  694. self.server.wrap(server)
  695. return self.server
  696. # ... = yield from serve(...) - remove when dropping Python < 3.10
  697. __iter__ = __await__
  698. def unix_serve(
  699. handler: Callable[[ServerConnection], Awaitable[None]],
  700. path: str | None = None,
  701. **kwargs: Any,
  702. ) -> Awaitable[Server]:
  703. """
  704. Create a WebSocket server listening on a Unix socket.
  705. This function is identical to :func:`serve`, except the ``host`` and
  706. ``port`` arguments are replaced by ``path``. It's only available on Unix.
  707. It's useful for deploying a server behind a reverse proxy such as nginx.
  708. Args:
  709. handler: Connection handler. It receives the WebSocket connection,
  710. which is a :class:`ServerConnection`, in argument.
  711. path: File system path to the Unix socket.
  712. """
  713. return serve(handler, unix=True, path=path, **kwargs)
  714. def is_credentials(credentials: Any) -> bool:
  715. try:
  716. username, password = credentials
  717. except (TypeError, ValueError):
  718. return False
  719. else:
  720. return isinstance(username, str) and isinstance(password, str)
  721. def basic_auth(
  722. realm: str = "",
  723. credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None,
  724. check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None,
  725. ) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]:
  726. """
  727. Factory for ``process_request`` to enforce HTTP Basic Authentication.
  728. :func:`basic_auth` is designed to integrate with :func:`serve` as follows::
  729. from websockets.asyncio.server import basic_auth, serve
  730. async with serve(
  731. ...,
  732. process_request=basic_auth(
  733. realm="my dev server",
  734. credentials=("hello", "iloveyou"),
  735. ),
  736. ):
  737. If authentication succeeds, the connection's ``username`` attribute is set.
  738. If it fails, the server responds with an HTTP 401 Unauthorized status.
  739. One of ``credentials`` or ``check_credentials`` must be provided; not both.
  740. Args:
  741. realm: Scope of protection. It should contain only ASCII characters
  742. because the encoding of non-ASCII characters is undefined. Refer to
  743. section 2.2 of :rfc:`7235` for details.
  744. credentials: Hard coded authorized credentials. It can be a
  745. ``(username, password)`` pair or a list of such pairs.
  746. check_credentials: Function or coroutine that verifies credentials.
  747. It receives ``username`` and ``password`` arguments and returns
  748. whether they're valid.
  749. Raises:
  750. TypeError: If ``credentials`` or ``check_credentials`` is wrong.
  751. ValueError: If ``credentials`` and ``check_credentials`` are both
  752. provided or both not provided.
  753. """
  754. if (credentials is None) == (check_credentials is None):
  755. raise ValueError("provide either credentials or check_credentials")
  756. if credentials is not None:
  757. if is_credentials(credentials):
  758. credentials_list = [cast(tuple[str, str], credentials)]
  759. elif isinstance(credentials, Iterable):
  760. credentials_list = list(cast(Iterable[tuple[str, str]], credentials))
  761. if not all(is_credentials(item) for item in credentials_list):
  762. raise TypeError(f"invalid credentials argument: {credentials}")
  763. else:
  764. raise TypeError(f"invalid credentials argument: {credentials}")
  765. credentials_dict = dict(credentials_list)
  766. def check_credentials(username: str, password: str) -> bool:
  767. try:
  768. expected_password = credentials_dict[username]
  769. except KeyError:
  770. return False
  771. return hmac.compare_digest(expected_password, password)
  772. assert check_credentials is not None # help mypy
  773. async def process_request(
  774. connection: ServerConnection,
  775. request: Request,
  776. ) -> Response | None:
  777. """
  778. Perform HTTP Basic Authentication.
  779. If it succeeds, set the connection's ``username`` attribute and return
  780. :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.
  781. """
  782. try:
  783. authorization = request.headers["Authorization"]
  784. except KeyError:
  785. response = connection.respond(
  786. http.HTTPStatus.UNAUTHORIZED,
  787. "Missing credentials\n",
  788. )
  789. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  790. return response
  791. try:
  792. username, password = parse_authorization_basic(authorization)
  793. except InvalidHeader:
  794. response = connection.respond(
  795. http.HTTPStatus.UNAUTHORIZED,
  796. "Unsupported credentials\n",
  797. )
  798. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  799. return response
  800. valid_credentials = check_credentials(username, password)
  801. if isinstance(valid_credentials, Awaitable):
  802. valid_credentials = await valid_credentials
  803. if not valid_credentials:
  804. response = connection.respond(
  805. http.HTTPStatus.UNAUTHORIZED,
  806. "Invalid credentials\n",
  807. )
  808. response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm)
  809. return response
  810. connection.username = username
  811. return None
  812. return process_request