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.
 
 
 
 

1192 line
44 KiB

  1. from __future__ import annotations
  2. import asyncio
  3. import email.utils
  4. import functools
  5. import http
  6. import inspect
  7. import logging
  8. import socket
  9. import warnings
  10. from collections.abc import Awaitable, Generator, Iterable, Sequence
  11. from types import TracebackType
  12. from typing import Any, Callable, Union, cast
  13. from ..asyncio.compatibility import asyncio_timeout
  14. from ..datastructures import Headers, HeadersLike, MultipleValuesError
  15. from ..exceptions import (
  16. InvalidHandshake,
  17. InvalidHeader,
  18. InvalidMessage,
  19. InvalidOrigin,
  20. InvalidUpgrade,
  21. NegotiationError,
  22. )
  23. from ..extensions import Extension, ServerExtensionFactory
  24. from ..extensions.permessage_deflate import enable_server_permessage_deflate
  25. from ..headers import (
  26. build_extension,
  27. parse_extension,
  28. parse_subprotocol,
  29. validate_subprotocols,
  30. )
  31. from ..http11 import SERVER
  32. from ..protocol import State
  33. from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol
  34. from .exceptions import AbortHandshake
  35. from .handshake import build_response, check_request
  36. from .http import read_request
  37. from .protocol import WebSocketCommonProtocol, broadcast
  38. __all__ = [
  39. "broadcast",
  40. "serve",
  41. "unix_serve",
  42. "WebSocketServerProtocol",
  43. "WebSocketServer",
  44. ]
  45. # Change to HeadersLike | ... when dropping Python < 3.10.
  46. HeadersLikeOrCallable = Union[HeadersLike, Callable[[str, Headers], HeadersLike]]
  47. HTTPResponse = tuple[StatusLike, HeadersLike, bytes]
  48. class WebSocketServerProtocol(WebSocketCommonProtocol):
  49. """
  50. WebSocket server connection.
  51. :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send`
  52. coroutines for receiving and sending messages.
  53. It supports asynchronous iteration to receive messages::
  54. async for message in websocket:
  55. await process(message)
  56. The iterator exits normally when the connection is closed with close code
  57. 1000 (OK) or 1001 (going away) or without a close code. It raises
  58. a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
  59. is closed with any other code.
  60. You may customize the opening handshake in a subclass by
  61. overriding :meth:`process_request` or :meth:`select_subprotocol`.
  62. Args:
  63. ws_server: WebSocket server that created this connection.
  64. See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``,
  65. ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``.
  66. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  67. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  68. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  69. """
  70. is_client = False
  71. side = "server"
  72. def __init__(
  73. self,
  74. # The version that accepts the path in the second argument is deprecated.
  75. ws_handler: (
  76. Callable[[WebSocketServerProtocol], Awaitable[Any]]
  77. | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
  78. ),
  79. ws_server: WebSocketServer,
  80. *,
  81. logger: LoggerLike | None = None,
  82. origins: Sequence[Origin | None] | None = None,
  83. extensions: Sequence[ServerExtensionFactory] | None = None,
  84. subprotocols: Sequence[Subprotocol] | None = None,
  85. extra_headers: HeadersLikeOrCallable | None = None,
  86. server_header: str | None = SERVER,
  87. process_request: (
  88. Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None
  89. ) = None,
  90. select_subprotocol: (
  91. Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None
  92. ) = None,
  93. open_timeout: float | None = 10,
  94. **kwargs: Any,
  95. ) -> None:
  96. if logger is None:
  97. logger = logging.getLogger("websockets.server")
  98. super().__init__(logger=logger, **kwargs)
  99. # For backwards compatibility with 6.0 or earlier.
  100. if origins is not None and "" in origins:
  101. warnings.warn("use None instead of '' in origins", DeprecationWarning)
  102. origins = [None if origin == "" else origin for origin in origins]
  103. # For backwards compatibility with 10.0 or earlier. Done here in
  104. # addition to serve to trigger the deprecation warning on direct
  105. # use of WebSocketServerProtocol.
  106. self.ws_handler = remove_path_argument(ws_handler)
  107. self.ws_server = ws_server
  108. self.origins = origins
  109. self.available_extensions = extensions
  110. self.available_subprotocols = subprotocols
  111. self.extra_headers = extra_headers
  112. self.server_header = server_header
  113. self._process_request = process_request
  114. self._select_subprotocol = select_subprotocol
  115. self.open_timeout = open_timeout
  116. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  117. """
  118. Register connection and initialize a task to handle it.
  119. """
  120. super().connection_made(transport)
  121. # Register the connection with the server before creating the handler
  122. # task. Registering at the beginning of the handler coroutine would
  123. # create a race condition between the creation of the task, which
  124. # schedules its execution, and the moment the handler starts running.
  125. self.ws_server.register(self)
  126. self.handler_task = self.loop.create_task(self.handler())
  127. async def handler(self) -> None:
  128. """
  129. Handle the lifecycle of a WebSocket connection.
  130. Since this method doesn't have a caller able to handle exceptions, it
  131. attempts to log relevant ones and guarantees that the TCP connection is
  132. closed before exiting.
  133. """
  134. try:
  135. try:
  136. async with asyncio_timeout(self.open_timeout):
  137. await self.handshake(
  138. origins=self.origins,
  139. available_extensions=self.available_extensions,
  140. available_subprotocols=self.available_subprotocols,
  141. extra_headers=self.extra_headers,
  142. )
  143. except asyncio.TimeoutError: # pragma: no cover
  144. raise
  145. except ConnectionError:
  146. raise
  147. except Exception as exc:
  148. if isinstance(exc, AbortHandshake):
  149. status, headers, body = exc.status, exc.headers, exc.body
  150. elif isinstance(exc, InvalidOrigin):
  151. if self.debug:
  152. self.logger.debug("! invalid origin", exc_info=True)
  153. status, headers, body = (
  154. http.HTTPStatus.FORBIDDEN,
  155. Headers(),
  156. f"Failed to open a WebSocket connection: {exc}.\n".encode(),
  157. )
  158. elif isinstance(exc, InvalidUpgrade):
  159. if self.debug:
  160. self.logger.debug("! invalid upgrade", exc_info=True)
  161. status, headers, body = (
  162. http.HTTPStatus.UPGRADE_REQUIRED,
  163. Headers([("Upgrade", "websocket")]),
  164. (
  165. f"Failed to open a WebSocket connection: {exc}.\n"
  166. f"\n"
  167. f"You cannot access a WebSocket server directly "
  168. f"with a browser. You need a WebSocket client.\n"
  169. ).encode(),
  170. )
  171. elif isinstance(exc, InvalidHandshake):
  172. if self.debug:
  173. self.logger.debug("! invalid handshake", exc_info=True)
  174. exc_chain = cast(BaseException, exc)
  175. exc_str = f"{exc_chain}"
  176. while exc_chain.__cause__ is not None:
  177. exc_chain = exc_chain.__cause__
  178. exc_str += f"; {exc_chain}"
  179. status, headers, body = (
  180. http.HTTPStatus.BAD_REQUEST,
  181. Headers(),
  182. f"Failed to open a WebSocket connection: {exc_str}.\n".encode(),
  183. )
  184. else:
  185. self.logger.error("opening handshake failed", exc_info=True)
  186. status, headers, body = (
  187. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  188. Headers(),
  189. (
  190. b"Failed to open a WebSocket connection.\n"
  191. b"See server log for more information.\n"
  192. ),
  193. )
  194. headers.setdefault("Date", email.utils.formatdate(usegmt=True))
  195. if self.server_header:
  196. headers.setdefault("Server", self.server_header)
  197. headers.setdefault("Content-Length", str(len(body)))
  198. headers.setdefault("Content-Type", "text/plain")
  199. headers.setdefault("Connection", "close")
  200. self.write_http_response(status, headers, body)
  201. self.logger.info(
  202. "connection rejected (%d %s)", status.value, status.phrase
  203. )
  204. await self.close_transport()
  205. return
  206. try:
  207. await self.ws_handler(self)
  208. except Exception:
  209. self.logger.error("connection handler failed", exc_info=True)
  210. if not self.closed:
  211. self.fail_connection(1011)
  212. raise
  213. try:
  214. await self.close()
  215. except ConnectionError:
  216. raise
  217. except Exception:
  218. self.logger.error("closing handshake failed", exc_info=True)
  219. raise
  220. except Exception:
  221. # Last-ditch attempt to avoid leaking connections on errors.
  222. try:
  223. self.transport.close()
  224. except Exception: # pragma: no cover
  225. pass
  226. finally:
  227. # Unregister the connection with the server when the handler task
  228. # terminates. Registration is tied to the lifecycle of the handler
  229. # task because the server waits for tasks attached to registered
  230. # connections before terminating.
  231. self.ws_server.unregister(self)
  232. self.logger.info("connection closed")
  233. async def read_http_request(self) -> tuple[str, Headers]:
  234. """
  235. Read request line and headers from the HTTP request.
  236. If the request contains a body, it may be read from ``self.reader``
  237. after this coroutine returns.
  238. Raises:
  239. InvalidMessage: If the HTTP message is malformed or isn't an
  240. HTTP/1.1 GET request.
  241. """
  242. try:
  243. path, headers = await read_request(self.reader)
  244. except asyncio.CancelledError: # pragma: no cover
  245. raise
  246. except Exception as exc:
  247. raise InvalidMessage("did not receive a valid HTTP request") from exc
  248. if self.debug:
  249. self.logger.debug("< GET %s HTTP/1.1", path)
  250. for key, value in headers.raw_items():
  251. self.logger.debug("< %s: %s", key, value)
  252. self.path = path
  253. self.request_headers = headers
  254. return path, headers
  255. def write_http_response(
  256. self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None
  257. ) -> None:
  258. """
  259. Write status line and headers to the HTTP response.
  260. This coroutine is also able to write a response body.
  261. """
  262. self.response_headers = headers
  263. if self.debug:
  264. self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase)
  265. for key, value in headers.raw_items():
  266. self.logger.debug("> %s: %s", key, value)
  267. if body is not None:
  268. self.logger.debug("> [body] (%d bytes)", len(body))
  269. # Since the status line and headers only contain ASCII characters,
  270. # we can keep this simple.
  271. response = f"HTTP/1.1 {status.value} {status.phrase}\r\n"
  272. response += str(headers)
  273. self.transport.write(response.encode())
  274. if body is not None:
  275. self.transport.write(body)
  276. async def process_request(
  277. self, path: str, request_headers: Headers
  278. ) -> HTTPResponse | None:
  279. """
  280. Intercept the HTTP request and return an HTTP response if appropriate.
  281. You may override this method in a :class:`WebSocketServerProtocol`
  282. subclass, for example:
  283. * to return an HTTP 200 OK response on a given path; then a load
  284. balancer can use this path for a health check;
  285. * to authenticate the request and return an HTTP 401 Unauthorized or an
  286. HTTP 403 Forbidden when authentication fails.
  287. You may also override this method with the ``process_request``
  288. argument of :func:`serve` and :class:`WebSocketServerProtocol`. This
  289. is equivalent, except ``process_request`` won't have access to the
  290. protocol instance, so it can't store information for later use.
  291. :meth:`process_request` is expected to complete quickly. If it may run
  292. for a long time, then it should await :meth:`wait_closed` and exit if
  293. :meth:`wait_closed` completes, or else it could prevent the server
  294. from shutting down.
  295. Args:
  296. path: Request path, including optional query string.
  297. request_headers: Request headers.
  298. Returns:
  299. tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to
  300. continue the WebSocket handshake normally.
  301. An HTTP response, represented by a 3-uple of the response status,
  302. headers, and body, to abort the WebSocket handshake and return
  303. that HTTP response instead.
  304. """
  305. if self._process_request is not None:
  306. response = self._process_request(path, request_headers)
  307. if isinstance(response, Awaitable):
  308. return await response
  309. else:
  310. # For backwards compatibility with 7.0.
  311. warnings.warn(
  312. "declare process_request as a coroutine", DeprecationWarning
  313. )
  314. return response
  315. return None
  316. @staticmethod
  317. def process_origin(
  318. headers: Headers, origins: Sequence[Origin | None] | None = None
  319. ) -> Origin | None:
  320. """
  321. Handle the Origin HTTP request header.
  322. Args:
  323. headers: Request headers.
  324. origins: Optional list of acceptable origins.
  325. Raises:
  326. InvalidOrigin: If the origin isn't acceptable.
  327. """
  328. # "The user agent MUST NOT include more than one Origin header field"
  329. # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3.
  330. try:
  331. origin = headers.get("Origin")
  332. except MultipleValuesError as exc:
  333. raise InvalidHeader("Origin", "multiple values") from exc
  334. if origin is not None:
  335. origin = cast(Origin, origin)
  336. if origins is not None:
  337. if origin not in origins:
  338. raise InvalidOrigin(origin)
  339. return origin
  340. @staticmethod
  341. def process_extensions(
  342. headers: Headers,
  343. available_extensions: Sequence[ServerExtensionFactory] | None,
  344. ) -> tuple[str | None, list[Extension]]:
  345. """
  346. Handle the Sec-WebSocket-Extensions HTTP request header.
  347. Accept or reject each extension proposed in the client request.
  348. Negotiate parameters for accepted extensions.
  349. Return the Sec-WebSocket-Extensions HTTP response header and the list
  350. of accepted extensions.
  351. :rfc:`6455` leaves the rules up to the specification of each
  352. :extension.
  353. To provide this level of flexibility, for each extension proposed by
  354. the client, we check for a match with each extension available in the
  355. server configuration. If no match is found, the extension is ignored.
  356. If several variants of the same extension are proposed by the client,
  357. it may be accepted several times, which won't make sense in general.
  358. Extensions must implement their own requirements. For this purpose,
  359. the list of previously accepted extensions is provided.
  360. This process doesn't allow the server to reorder extensions. It can
  361. only select a subset of the extensions proposed by the client.
  362. Other requirements, for example related to mandatory extensions or the
  363. order of extensions, may be implemented by overriding this method.
  364. Args:
  365. headers: Request headers.
  366. extensions: Optional list of supported extensions.
  367. Raises:
  368. InvalidHandshake: To abort the handshake with an HTTP 400 error.
  369. """
  370. response_header_value: str | None = None
  371. extension_headers: list[ExtensionHeader] = []
  372. accepted_extensions: list[Extension] = []
  373. header_values = headers.get_all("Sec-WebSocket-Extensions")
  374. if header_values and available_extensions:
  375. parsed_header_values: list[ExtensionHeader] = sum(
  376. [parse_extension(header_value) for header_value in header_values], []
  377. )
  378. for name, request_params in parsed_header_values:
  379. for ext_factory in available_extensions:
  380. # Skip non-matching extensions based on their name.
  381. if ext_factory.name != name:
  382. continue
  383. # Skip non-matching extensions based on their params.
  384. try:
  385. response_params, extension = ext_factory.process_request_params(
  386. request_params, accepted_extensions
  387. )
  388. except NegotiationError:
  389. continue
  390. # Add matching extension to the final list.
  391. extension_headers.append((name, response_params))
  392. accepted_extensions.append(extension)
  393. # Break out of the loop once we have a match.
  394. break
  395. # If we didn't break from the loop, no extension in our list
  396. # matched what the client sent. The extension is declined.
  397. # Serialize extension header.
  398. if extension_headers:
  399. response_header_value = build_extension(extension_headers)
  400. return response_header_value, accepted_extensions
  401. # Not @staticmethod because it calls self.select_subprotocol()
  402. def process_subprotocol(
  403. self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None
  404. ) -> Subprotocol | None:
  405. """
  406. Handle the Sec-WebSocket-Protocol HTTP request header.
  407. Return Sec-WebSocket-Protocol HTTP response header, which is the same
  408. as the selected subprotocol.
  409. Args:
  410. headers: Request headers.
  411. available_subprotocols: Optional list of supported subprotocols.
  412. Raises:
  413. InvalidHandshake: To abort the handshake with an HTTP 400 error.
  414. """
  415. subprotocol: Subprotocol | None = None
  416. header_values = headers.get_all("Sec-WebSocket-Protocol")
  417. if header_values and available_subprotocols:
  418. parsed_header_values: list[Subprotocol] = sum(
  419. [parse_subprotocol(header_value) for header_value in header_values], []
  420. )
  421. subprotocol = self.select_subprotocol(
  422. parsed_header_values, available_subprotocols
  423. )
  424. return subprotocol
  425. def select_subprotocol(
  426. self,
  427. client_subprotocols: Sequence[Subprotocol],
  428. server_subprotocols: Sequence[Subprotocol],
  429. ) -> Subprotocol | None:
  430. """
  431. Pick a subprotocol among those supported by the client and the server.
  432. If several subprotocols are available, select the preferred subprotocol
  433. by giving equal weight to the preferences of the client and the server.
  434. If no subprotocol is available, proceed without a subprotocol.
  435. You may provide a ``select_subprotocol`` argument to :func:`serve` or
  436. :class:`WebSocketServerProtocol` to override this logic. For example,
  437. you could reject the handshake if the client doesn't support a
  438. particular subprotocol, rather than accept the handshake without that
  439. subprotocol.
  440. Args:
  441. client_subprotocols: List of subprotocols offered by the client.
  442. server_subprotocols: List of subprotocols available on the server.
  443. Returns:
  444. Selected subprotocol, if a common subprotocol was found.
  445. :obj:`None` to continue without a subprotocol.
  446. """
  447. if self._select_subprotocol is not None:
  448. return self._select_subprotocol(client_subprotocols, server_subprotocols)
  449. subprotocols = set(client_subprotocols) & set(server_subprotocols)
  450. if not subprotocols:
  451. return None
  452. return sorted(
  453. subprotocols,
  454. key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p),
  455. )[0]
  456. async def handshake(
  457. self,
  458. origins: Sequence[Origin | None] | None = None,
  459. available_extensions: Sequence[ServerExtensionFactory] | None = None,
  460. available_subprotocols: Sequence[Subprotocol] | None = None,
  461. extra_headers: HeadersLikeOrCallable | None = None,
  462. ) -> str:
  463. """
  464. Perform the server side of the opening handshake.
  465. Args:
  466. origins: List of acceptable values of the Origin HTTP header;
  467. include :obj:`None` if the lack of an origin is acceptable.
  468. extensions: List of supported extensions, in order in which they
  469. should be tried.
  470. subprotocols: List of supported subprotocols, in order of
  471. decreasing preference.
  472. extra_headers: Arbitrary HTTP headers to add to the response when
  473. the handshake succeeds.
  474. Returns:
  475. path of the URI of the request.
  476. Raises:
  477. InvalidHandshake: If the handshake fails.
  478. """
  479. path, request_headers = await self.read_http_request()
  480. # Hook for customizing request handling, for example checking
  481. # authentication or treating some paths as plain HTTP endpoints.
  482. early_response_awaitable = self.process_request(path, request_headers)
  483. if isinstance(early_response_awaitable, Awaitable):
  484. early_response = await early_response_awaitable
  485. else:
  486. # For backwards compatibility with 7.0.
  487. warnings.warn("declare process_request as a coroutine", DeprecationWarning)
  488. early_response = early_response_awaitable
  489. # The connection may drop while process_request is running.
  490. if self.state is State.CLOSED:
  491. # This subclass of ConnectionError is silently ignored in handler().
  492. raise BrokenPipeError("connection closed during opening handshake")
  493. # Change the response to a 503 error if the server is shutting down.
  494. if not self.ws_server.is_serving():
  495. early_response = (
  496. http.HTTPStatus.SERVICE_UNAVAILABLE,
  497. [],
  498. b"Server is shutting down.\n",
  499. )
  500. if early_response is not None:
  501. raise AbortHandshake(*early_response)
  502. key = check_request(request_headers)
  503. self.origin = self.process_origin(request_headers, origins)
  504. extensions_header, self.extensions = self.process_extensions(
  505. request_headers, available_extensions
  506. )
  507. protocol_header = self.subprotocol = self.process_subprotocol(
  508. request_headers, available_subprotocols
  509. )
  510. response_headers = Headers()
  511. build_response(response_headers, key)
  512. if extensions_header is not None:
  513. response_headers["Sec-WebSocket-Extensions"] = extensions_header
  514. if protocol_header is not None:
  515. response_headers["Sec-WebSocket-Protocol"] = protocol_header
  516. if callable(extra_headers):
  517. extra_headers = extra_headers(path, self.request_headers)
  518. if extra_headers is not None:
  519. response_headers.update(extra_headers)
  520. response_headers.setdefault("Date", email.utils.formatdate(usegmt=True))
  521. if self.server_header is not None:
  522. response_headers.setdefault("Server", self.server_header)
  523. self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers)
  524. self.logger.info("connection open")
  525. self.connection_open()
  526. return path
  527. class WebSocketServer:
  528. """
  529. WebSocket server returned by :func:`serve`.
  530. This class mirrors the API of :class:`~asyncio.Server`.
  531. It keeps track of WebSocket connections in order to close them properly
  532. when shutting down.
  533. Args:
  534. logger: Logger for this server.
  535. It defaults to ``logging.getLogger("websockets.server")``.
  536. See the :doc:`logging guide <../../topics/logging>` for details.
  537. """
  538. def __init__(self, logger: LoggerLike | None = None) -> None:
  539. if logger is None:
  540. logger = logging.getLogger("websockets.server")
  541. self.logger = logger
  542. # Keep track of active connections.
  543. self.websockets: set[WebSocketServerProtocol] = set()
  544. # Task responsible for closing the server and terminating connections.
  545. self.close_task: asyncio.Task[None] | None = None
  546. # Completed when the server is closed and connections are terminated.
  547. self.closed_waiter: asyncio.Future[None]
  548. def wrap(self, server: asyncio.base_events.Server) -> None:
  549. """
  550. Attach to a given :class:`~asyncio.Server`.
  551. Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
  552. custom ``Server`` class, the easiest solution that doesn't rely on
  553. private :mod:`asyncio` APIs is to:
  554. - instantiate a :class:`WebSocketServer`
  555. - give the protocol factory a reference to that instance
  556. - call :meth:`~asyncio.loop.create_server` with the factory
  557. - attach the resulting :class:`~asyncio.Server` with this method
  558. """
  559. self.server = server
  560. for sock in server.sockets:
  561. if sock.family == socket.AF_INET:
  562. name = "%s:%d" % sock.getsockname()
  563. elif sock.family == socket.AF_INET6:
  564. name = "[%s]:%d" % sock.getsockname()[:2]
  565. elif sock.family == socket.AF_UNIX:
  566. name = sock.getsockname()
  567. # In the unlikely event that someone runs websockets over a
  568. # protocol other than IP or Unix sockets, avoid crashing.
  569. else: # pragma: no cover
  570. name = str(sock.getsockname())
  571. self.logger.info("server listening on %s", name)
  572. # Initialized here because we need a reference to the event loop.
  573. # This should be moved back to __init__ when dropping Python < 3.10.
  574. self.closed_waiter = server.get_loop().create_future()
  575. def register(self, protocol: WebSocketServerProtocol) -> None:
  576. """
  577. Register a connection with this server.
  578. """
  579. self.websockets.add(protocol)
  580. def unregister(self, protocol: WebSocketServerProtocol) -> None:
  581. """
  582. Unregister a connection with this server.
  583. """
  584. self.websockets.remove(protocol)
  585. def close(self, close_connections: bool = True) -> None:
  586. """
  587. Close the server.
  588. * Close the underlying :class:`~asyncio.Server`.
  589. * When ``close_connections`` is :obj:`True`, which is the default,
  590. close existing connections. Specifically:
  591. * Reject opening WebSocket connections with an HTTP 503 (service
  592. unavailable) error. This happens when the server accepted the TCP
  593. connection but didn't complete the opening handshake before closing.
  594. * Close open WebSocket connections with close code 1001 (going away).
  595. * Wait until all connection handlers terminate.
  596. :meth:`close` is idempotent.
  597. """
  598. if self.close_task is None:
  599. self.close_task = self.get_loop().create_task(
  600. self._close(close_connections)
  601. )
  602. async def _close(self, close_connections: bool) -> None:
  603. """
  604. Implementation of :meth:`close`.
  605. This calls :meth:`~asyncio.Server.close` on the underlying
  606. :class:`~asyncio.Server` object to stop accepting new connections and
  607. then closes open connections with close code 1001.
  608. """
  609. self.logger.info("server closing")
  610. # Stop accepting new connections.
  611. self.server.close()
  612. # Wait until all accepted connections reach connection_made() and call
  613. # register(). See https://github.com/python/cpython/issues/79033 for
  614. # details. This workaround can be removed when dropping Python < 3.11.
  615. await asyncio.sleep(0)
  616. if close_connections:
  617. # Close OPEN connections with close code 1001. After server.close(),
  618. # handshake() closes OPENING connections with an HTTP 503 error.
  619. close_tasks = [
  620. asyncio.create_task(websocket.close(1001))
  621. for websocket in self.websockets
  622. if websocket.state is not State.CONNECTING
  623. ]
  624. # asyncio.wait doesn't accept an empty first argument.
  625. if close_tasks:
  626. await asyncio.wait(close_tasks)
  627. # Wait until all TCP connections are closed.
  628. await self.server.wait_closed()
  629. # Wait until all connection handlers terminate.
  630. # asyncio.wait doesn't accept an empty first argument.
  631. if self.websockets:
  632. await asyncio.wait(
  633. [websocket.handler_task for websocket in self.websockets]
  634. )
  635. # Tell wait_closed() to return.
  636. self.closed_waiter.set_result(None)
  637. self.logger.info("server closed")
  638. async def wait_closed(self) -> None:
  639. """
  640. Wait until the server is closed.
  641. When :meth:`wait_closed` returns, all TCP connections are closed and
  642. all connection handlers have returned.
  643. To ensure a fast shutdown, a connection handler should always be
  644. awaiting at least one of:
  645. * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed,
  646. it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
  647. * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is
  648. closed, it returns.
  649. Then the connection handler is immediately notified of the shutdown;
  650. it can clean up and exit.
  651. """
  652. await asyncio.shield(self.closed_waiter)
  653. def get_loop(self) -> asyncio.AbstractEventLoop:
  654. """
  655. See :meth:`asyncio.Server.get_loop`.
  656. """
  657. return self.server.get_loop()
  658. def is_serving(self) -> bool:
  659. """
  660. See :meth:`asyncio.Server.is_serving`.
  661. """
  662. return self.server.is_serving()
  663. async def start_serving(self) -> None: # pragma: no cover
  664. """
  665. See :meth:`asyncio.Server.start_serving`.
  666. Typical use::
  667. server = await serve(..., start_serving=False)
  668. # perform additional setup here...
  669. # ... then start the server
  670. await server.start_serving()
  671. """
  672. await self.server.start_serving()
  673. async def serve_forever(self) -> None: # pragma: no cover
  674. """
  675. See :meth:`asyncio.Server.serve_forever`.
  676. Typical use::
  677. server = await serve(...)
  678. # this coroutine doesn't return
  679. # canceling it stops the server
  680. await server.serve_forever()
  681. This is an alternative to using :func:`serve` as an asynchronous context
  682. manager. Shutdown is triggered by canceling :meth:`serve_forever`
  683. instead of exiting a :func:`serve` context.
  684. """
  685. await self.server.serve_forever()
  686. @property
  687. def sockets(self) -> Iterable[socket.socket]:
  688. """
  689. See :attr:`asyncio.Server.sockets`.
  690. """
  691. return self.server.sockets
  692. async def __aenter__(self) -> WebSocketServer: # pragma: no cover
  693. return self
  694. async def __aexit__(
  695. self,
  696. exc_type: type[BaseException] | None,
  697. exc_value: BaseException | None,
  698. traceback: TracebackType | None,
  699. ) -> None: # pragma: no cover
  700. self.close()
  701. await self.wait_closed()
  702. class Serve:
  703. """
  704. Start a WebSocket server listening on ``host`` and ``port``.
  705. Whenever a client connects, the server creates a
  706. :class:`WebSocketServerProtocol`, performs the opening handshake, and
  707. delegates to the connection handler, ``ws_handler``.
  708. The handler receives the :class:`WebSocketServerProtocol` and uses it to
  709. send and receive messages.
  710. Once the handler completes, either normally or with an exception, the
  711. server performs the closing handshake and closes the connection.
  712. Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object
  713. provides a :meth:`~WebSocketServer.close` method to shut down the server::
  714. # set this future to exit the server
  715. stop = asyncio.get_running_loop().create_future()
  716. server = await serve(...)
  717. await stop
  718. server.close()
  719. await server.wait_closed()
  720. :func:`serve` can be used as an asynchronous context manager. Then, the
  721. server is shut down automatically when exiting the context::
  722. # set this future to exit the server
  723. stop = asyncio.get_running_loop().create_future()
  724. async with serve(...):
  725. await stop
  726. Args:
  727. ws_handler: Connection handler. It receives the WebSocket connection,
  728. which is a :class:`WebSocketServerProtocol`, in argument.
  729. host: Network interfaces the server binds to.
  730. See :meth:`~asyncio.loop.create_server` for details.
  731. port: TCP port the server listens on.
  732. See :meth:`~asyncio.loop.create_server` for details.
  733. create_protocol: Factory for the :class:`asyncio.Protocol` managing
  734. the connection. It defaults to :class:`WebSocketServerProtocol`.
  735. Set it to a wrapper or a subclass to customize connection handling.
  736. logger: Logger for this server.
  737. It defaults to ``logging.getLogger("websockets.server")``.
  738. See the :doc:`logging guide <../../topics/logging>` for details.
  739. compression: The "permessage-deflate" extension is enabled by default.
  740. Set ``compression`` to :obj:`None` to disable it. See the
  741. :doc:`compression guide <../../topics/compression>` for details.
  742. origins: Acceptable values of the ``Origin`` header, for defending
  743. against Cross-Site WebSocket Hijacking attacks. Include :obj:`None`
  744. in the list if the lack of an origin is acceptable.
  745. extensions: List of supported extensions, in order in which they
  746. should be negotiated and run.
  747. subprotocols: List of supported subprotocols, in order of decreasing
  748. preference.
  749. extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]):
  750. Arbitrary HTTP headers to add to the response. This can be
  751. a :data:`~websockets.datastructures.HeadersLike` or a callable
  752. taking the request path and headers in arguments and returning
  753. a :data:`~websockets.datastructures.HeadersLike`.
  754. server_header: Value of the ``Server`` response header.
  755. It defaults to ``"Python/x.y.z websockets/X.Y"``.
  756. Setting it to :obj:`None` removes the header.
  757. process_request (Callable[[str, Headers], \
  758. Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None):
  759. Intercept HTTP request before the opening handshake.
  760. See :meth:`~WebSocketServerProtocol.process_request` for details.
  761. select_subprotocol: Select a subprotocol supported by the client.
  762. See :meth:`~WebSocketServerProtocol.select_subprotocol` for details.
  763. open_timeout: Timeout for opening connections in seconds.
  764. :obj:`None` disables the timeout.
  765. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
  766. documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
  767. ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
  768. Any other keyword arguments are passed the event loop's
  769. :meth:`~asyncio.loop.create_server` method.
  770. For example:
  771. * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.
  772. * You can set ``sock`` to a :obj:`~socket.socket` that you created
  773. outside of websockets.
  774. Returns:
  775. WebSocket server.
  776. """
  777. def __init__(
  778. self,
  779. # The version that accepts the path in the second argument is deprecated.
  780. ws_handler: (
  781. Callable[[WebSocketServerProtocol], Awaitable[Any]]
  782. | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
  783. ),
  784. host: str | Sequence[str] | None = None,
  785. port: int | None = None,
  786. *,
  787. create_protocol: Callable[..., WebSocketServerProtocol] | None = None,
  788. logger: LoggerLike | None = None,
  789. compression: str | None = "deflate",
  790. origins: Sequence[Origin | None] | None = None,
  791. extensions: Sequence[ServerExtensionFactory] | None = None,
  792. subprotocols: Sequence[Subprotocol] | None = None,
  793. extra_headers: HeadersLikeOrCallable | None = None,
  794. server_header: str | None = SERVER,
  795. process_request: (
  796. Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None
  797. ) = None,
  798. select_subprotocol: (
  799. Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None
  800. ) = None,
  801. open_timeout: float | None = 10,
  802. ping_interval: float | None = 20,
  803. ping_timeout: float | None = 20,
  804. close_timeout: float | None = None,
  805. max_size: int | None = 2**20,
  806. max_queue: int | None = 2**5,
  807. read_limit: int = 2**16,
  808. write_limit: int = 2**16,
  809. **kwargs: Any,
  810. ) -> None:
  811. # Backwards compatibility: close_timeout used to be called timeout.
  812. timeout: float | None = kwargs.pop("timeout", None)
  813. if timeout is None:
  814. timeout = 10
  815. else:
  816. warnings.warn("rename timeout to close_timeout", DeprecationWarning)
  817. # If both are specified, timeout is ignored.
  818. if close_timeout is None:
  819. close_timeout = timeout
  820. # Backwards compatibility: create_protocol used to be called klass.
  821. klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None)
  822. if klass is None:
  823. klass = WebSocketServerProtocol
  824. else:
  825. warnings.warn("rename klass to create_protocol", DeprecationWarning)
  826. # If both are specified, klass is ignored.
  827. if create_protocol is None:
  828. create_protocol = klass
  829. # Backwards compatibility: recv() used to return None on closed connections
  830. legacy_recv: bool = kwargs.pop("legacy_recv", False)
  831. # Backwards compatibility: the loop parameter used to be supported.
  832. _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None)
  833. if _loop is None:
  834. loop = asyncio.get_event_loop()
  835. else:
  836. loop = _loop
  837. warnings.warn("remove loop argument", DeprecationWarning)
  838. ws_server = WebSocketServer(logger=logger)
  839. secure = kwargs.get("ssl") is not None
  840. if compression == "deflate":
  841. extensions = enable_server_permessage_deflate(extensions)
  842. elif compression is not None:
  843. raise ValueError(f"unsupported compression: {compression}")
  844. if subprotocols is not None:
  845. validate_subprotocols(subprotocols)
  846. # Help mypy and avoid this error: "type[WebSocketServerProtocol] |
  847. # Callable[..., WebSocketServerProtocol]" not callable [misc]
  848. create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol)
  849. factory = functools.partial(
  850. create_protocol,
  851. # For backwards compatibility with 10.0 or earlier. Done here in
  852. # addition to WebSocketServerProtocol to trigger the deprecation
  853. # warning once per serve() call rather than once per connection.
  854. remove_path_argument(ws_handler),
  855. ws_server,
  856. host=host,
  857. port=port,
  858. secure=secure,
  859. open_timeout=open_timeout,
  860. ping_interval=ping_interval,
  861. ping_timeout=ping_timeout,
  862. close_timeout=close_timeout,
  863. max_size=max_size,
  864. max_queue=max_queue,
  865. read_limit=read_limit,
  866. write_limit=write_limit,
  867. loop=_loop,
  868. legacy_recv=legacy_recv,
  869. origins=origins,
  870. extensions=extensions,
  871. subprotocols=subprotocols,
  872. extra_headers=extra_headers,
  873. server_header=server_header,
  874. process_request=process_request,
  875. select_subprotocol=select_subprotocol,
  876. logger=logger,
  877. )
  878. if kwargs.pop("unix", False):
  879. path: str | None = kwargs.pop("path", None)
  880. # unix_serve(path) must not specify host and port parameters.
  881. assert host is None and port is None
  882. create_server = functools.partial(
  883. loop.create_unix_server, factory, path, **kwargs
  884. )
  885. else:
  886. create_server = functools.partial(
  887. loop.create_server, factory, host, port, **kwargs
  888. )
  889. # This is a coroutine function.
  890. self._create_server = create_server
  891. self.ws_server = ws_server
  892. # async with serve(...)
  893. async def __aenter__(self) -> WebSocketServer:
  894. return await self
  895. async def __aexit__(
  896. self,
  897. exc_type: type[BaseException] | None,
  898. exc_value: BaseException | None,
  899. traceback: TracebackType | None,
  900. ) -> None:
  901. self.ws_server.close()
  902. await self.ws_server.wait_closed()
  903. # await serve(...)
  904. def __await__(self) -> Generator[Any, None, WebSocketServer]:
  905. # Create a suitable iterator by calling __await__ on a coroutine.
  906. return self.__await_impl__().__await__()
  907. async def __await_impl__(self) -> WebSocketServer:
  908. server = await self._create_server()
  909. self.ws_server.wrap(server)
  910. return self.ws_server
  911. # yield from serve(...) - remove when dropping Python < 3.10
  912. __iter__ = __await__
  913. serve = Serve
  914. def unix_serve(
  915. # The version that accepts the path in the second argument is deprecated.
  916. ws_handler: (
  917. Callable[[WebSocketServerProtocol], Awaitable[Any]]
  918. | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
  919. ),
  920. path: str | None = None,
  921. **kwargs: Any,
  922. ) -> Serve:
  923. """
  924. Start a WebSocket server listening on a Unix socket.
  925. This function is identical to :func:`serve`, except the ``host`` and
  926. ``port`` arguments are replaced by ``path``. It is only available on Unix.
  927. Unrecognized keyword arguments are passed the event loop's
  928. :meth:`~asyncio.loop.create_unix_server` method.
  929. It's useful for deploying a server behind a reverse proxy such as nginx.
  930. Args:
  931. path: File system path to the Unix socket.
  932. """
  933. return serve(ws_handler, path=path, unix=True, **kwargs)
  934. def remove_path_argument(
  935. ws_handler: (
  936. Callable[[WebSocketServerProtocol], Awaitable[Any]]
  937. | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
  938. ),
  939. ) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]:
  940. try:
  941. inspect.signature(ws_handler).bind(None)
  942. except TypeError:
  943. try:
  944. inspect.signature(ws_handler).bind(None, "")
  945. except TypeError: # pragma: no cover
  946. # ws_handler accepts neither one nor two arguments; leave it alone.
  947. pass
  948. else:
  949. # ws_handler accepts two arguments; activate backwards compatibility.
  950. warnings.warn("remove second argument of ws_handler", DeprecationWarning)
  951. async def _ws_handler(websocket: WebSocketServerProtocol) -> Any:
  952. return await cast(
  953. Callable[[WebSocketServerProtocol, str], Awaitable[Any]],
  954. ws_handler,
  955. )(websocket, websocket.path)
  956. return _ws_handler
  957. return cast(
  958. Callable[[WebSocketServerProtocol], Awaitable[Any]],
  959. ws_handler,
  960. )