Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

588 строки
21 KiB

  1. from __future__ import annotations
  2. import base64
  3. import binascii
  4. import email.utils
  5. import http
  6. import re
  7. import warnings
  8. from collections.abc import Generator, Sequence
  9. from typing import Any, Callable, cast
  10. from .datastructures import Headers, MultipleValuesError
  11. from .exceptions import (
  12. InvalidHandshake,
  13. InvalidHeader,
  14. InvalidHeaderValue,
  15. InvalidMessage,
  16. InvalidOrigin,
  17. InvalidUpgrade,
  18. NegotiationError,
  19. )
  20. from .extensions import Extension, ServerExtensionFactory
  21. from .headers import (
  22. build_extension,
  23. parse_connection,
  24. parse_extension,
  25. parse_subprotocol,
  26. parse_upgrade,
  27. )
  28. from .http11 import Request, Response
  29. from .imports import lazy_import
  30. from .protocol import CONNECTING, OPEN, SERVER, Protocol, State
  31. from .typing import (
  32. ConnectionOption,
  33. ExtensionHeader,
  34. LoggerLike,
  35. Origin,
  36. StatusLike,
  37. Subprotocol,
  38. UpgradeProtocol,
  39. )
  40. from .utils import accept_key
  41. __all__ = ["ServerProtocol"]
  42. class ServerProtocol(Protocol):
  43. """
  44. Sans-I/O implementation of a WebSocket server connection.
  45. Args:
  46. origins: Acceptable values of the ``Origin`` header. Values can be
  47. :class:`str` to test for an exact match or regular expressions
  48. compiled by :func:`re.compile` to test against a pattern. Include
  49. :obj:`None` in the list if the lack of an origin is acceptable.
  50. This is useful for defending against Cross-Site WebSocket
  51. Hijacking attacks.
  52. extensions: List of supported extensions, in order in which they
  53. should be tried.
  54. subprotocols: List of supported subprotocols, in order of decreasing
  55. preference.
  56. select_subprotocol: Callback for selecting a subprotocol among
  57. those supported by the client and the server. It has the same
  58. signature as the :meth:`select_subprotocol` method, including a
  59. :class:`ServerProtocol` instance as first argument.
  60. state: Initial state of the WebSocket connection.
  61. max_size: Maximum size of incoming messages in bytes;
  62. :obj:`None` disables the limit.
  63. logger: Logger for this connection;
  64. defaults to ``logging.getLogger("websockets.server")``;
  65. see the :doc:`logging guide <../../topics/logging>` for details.
  66. """
  67. def __init__(
  68. self,
  69. *,
  70. origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
  71. extensions: Sequence[ServerExtensionFactory] | None = None,
  72. subprotocols: Sequence[Subprotocol] | None = None,
  73. select_subprotocol: (
  74. Callable[
  75. [ServerProtocol, Sequence[Subprotocol]],
  76. Subprotocol | None,
  77. ]
  78. | None
  79. ) = None,
  80. state: State = CONNECTING,
  81. max_size: int | None = 2**20,
  82. logger: LoggerLike | None = None,
  83. ) -> None:
  84. super().__init__(
  85. side=SERVER,
  86. state=state,
  87. max_size=max_size,
  88. logger=logger,
  89. )
  90. self.origins = origins
  91. self.available_extensions = extensions
  92. self.available_subprotocols = subprotocols
  93. if select_subprotocol is not None:
  94. # Bind select_subprotocol then shadow self.select_subprotocol.
  95. # Use setattr to work around https://github.com/python/mypy/issues/2427.
  96. setattr(
  97. self,
  98. "select_subprotocol",
  99. select_subprotocol.__get__(self, self.__class__),
  100. )
  101. def accept(self, request: Request) -> Response:
  102. """
  103. Create a handshake response to accept the connection.
  104. If the handshake request is valid and the handshake successful,
  105. :meth:`accept` returns an HTTP response with status code 101.
  106. Else, it returns an HTTP response with another status code. This rejects
  107. the connection, like :meth:`reject` would.
  108. You must send the handshake response with :meth:`send_response`.
  109. You may modify the response before sending it, typically by adding HTTP
  110. headers.
  111. Args:
  112. request: WebSocket handshake request received from the client.
  113. Returns:
  114. WebSocket handshake response or HTTP response to send to the client.
  115. """
  116. try:
  117. (
  118. accept_header,
  119. extensions_header,
  120. protocol_header,
  121. ) = self.process_request(request)
  122. except InvalidOrigin as exc:
  123. request._exception = exc
  124. self.handshake_exc = exc
  125. if self.debug:
  126. self.logger.debug("! invalid origin", exc_info=True)
  127. return self.reject(
  128. http.HTTPStatus.FORBIDDEN,
  129. f"Failed to open a WebSocket connection: {exc}.\n",
  130. )
  131. except InvalidUpgrade as exc:
  132. request._exception = exc
  133. self.handshake_exc = exc
  134. if self.debug:
  135. self.logger.debug("! invalid upgrade", exc_info=True)
  136. response = self.reject(
  137. http.HTTPStatus.UPGRADE_REQUIRED,
  138. (
  139. f"Failed to open a WebSocket connection: {exc}.\n"
  140. f"\n"
  141. f"You cannot access a WebSocket server directly "
  142. f"with a browser. You need a WebSocket client.\n"
  143. ),
  144. )
  145. response.headers["Upgrade"] = "websocket"
  146. return response
  147. except InvalidHandshake as exc:
  148. request._exception = exc
  149. self.handshake_exc = exc
  150. if self.debug:
  151. self.logger.debug("! invalid handshake", exc_info=True)
  152. exc_chain = cast(BaseException, exc)
  153. exc_str = f"{exc_chain}"
  154. while exc_chain.__cause__ is not None:
  155. exc_chain = exc_chain.__cause__
  156. exc_str += f"; {exc_chain}"
  157. return self.reject(
  158. http.HTTPStatus.BAD_REQUEST,
  159. f"Failed to open a WebSocket connection: {exc_str}.\n",
  160. )
  161. except Exception as exc:
  162. # Handle exceptions raised by user-provided select_subprotocol and
  163. # unexpected errors.
  164. request._exception = exc
  165. self.handshake_exc = exc
  166. self.logger.error("opening handshake failed", exc_info=True)
  167. return self.reject(
  168. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  169. (
  170. "Failed to open a WebSocket connection.\n"
  171. "See server log for more information.\n"
  172. ),
  173. )
  174. headers = Headers()
  175. headers["Date"] = email.utils.formatdate(usegmt=True)
  176. headers["Upgrade"] = "websocket"
  177. headers["Connection"] = "Upgrade"
  178. headers["Sec-WebSocket-Accept"] = accept_header
  179. if extensions_header is not None:
  180. headers["Sec-WebSocket-Extensions"] = extensions_header
  181. if protocol_header is not None:
  182. headers["Sec-WebSocket-Protocol"] = protocol_header
  183. return Response(101, "Switching Protocols", headers)
  184. def process_request(
  185. self,
  186. request: Request,
  187. ) -> tuple[str, str | None, str | None]:
  188. """
  189. Check a handshake request and negotiate extensions and subprotocol.
  190. This function doesn't verify that the request is an HTTP/1.1 or higher
  191. GET request and doesn't check the ``Host`` header. These controls are
  192. usually performed earlier in the HTTP request handling code. They're
  193. the responsibility of the caller.
  194. Args:
  195. request: WebSocket handshake request received from the client.
  196. Returns:
  197. ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and
  198. ``Sec-WebSocket-Protocol`` headers for the handshake response.
  199. Raises:
  200. InvalidHandshake: If the handshake request is invalid;
  201. then the server must return 400 Bad Request error.
  202. """
  203. headers = request.headers
  204. connection: list[ConnectionOption] = sum(
  205. [parse_connection(value) for value in headers.get_all("Connection")], []
  206. )
  207. if not any(value.lower() == "upgrade" for value in connection):
  208. raise InvalidUpgrade(
  209. "Connection", ", ".join(connection) if connection else None
  210. )
  211. upgrade: list[UpgradeProtocol] = sum(
  212. [parse_upgrade(value) for value in headers.get_all("Upgrade")], []
  213. )
  214. # For compatibility with non-strict implementations, ignore case when
  215. # checking the Upgrade header. The RFC always uses "websocket", except
  216. # in section 11.2. (IANA registration) where it uses "WebSocket".
  217. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
  218. raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None)
  219. try:
  220. key = headers["Sec-WebSocket-Key"]
  221. except KeyError:
  222. raise InvalidHeader("Sec-WebSocket-Key") from None
  223. except MultipleValuesError:
  224. raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from None
  225. try:
  226. raw_key = base64.b64decode(key.encode(), validate=True)
  227. except binascii.Error as exc:
  228. raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc
  229. if len(raw_key) != 16:
  230. raise InvalidHeaderValue("Sec-WebSocket-Key", key)
  231. accept_header = accept_key(key)
  232. try:
  233. version = headers["Sec-WebSocket-Version"]
  234. except KeyError:
  235. raise InvalidHeader("Sec-WebSocket-Version") from None
  236. except MultipleValuesError:
  237. raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from None
  238. if version != "13":
  239. raise InvalidHeaderValue("Sec-WebSocket-Version", version)
  240. self.origin = self.process_origin(headers)
  241. extensions_header, self.extensions = self.process_extensions(headers)
  242. protocol_header = self.subprotocol = self.process_subprotocol(headers)
  243. return (accept_header, extensions_header, protocol_header)
  244. def process_origin(self, headers: Headers) -> Origin | None:
  245. """
  246. Handle the Origin HTTP request header.
  247. Args:
  248. headers: WebSocket handshake request headers.
  249. Returns:
  250. origin, if it is acceptable.
  251. Raises:
  252. InvalidHandshake: If the Origin header is invalid.
  253. InvalidOrigin: If the origin isn't acceptable.
  254. """
  255. # "The user agent MUST NOT include more than one Origin header field"
  256. # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3.
  257. try:
  258. origin = headers.get("Origin")
  259. except MultipleValuesError:
  260. raise InvalidHeader("Origin", "multiple values") from None
  261. if origin is not None:
  262. origin = cast(Origin, origin)
  263. if self.origins is not None:
  264. for origin_or_regex in self.origins:
  265. if origin_or_regex == origin or (
  266. isinstance(origin_or_regex, re.Pattern)
  267. and origin is not None
  268. and origin_or_regex.fullmatch(origin) is not None
  269. ):
  270. break
  271. else:
  272. raise InvalidOrigin(origin)
  273. return origin
  274. def process_extensions(
  275. self,
  276. headers: Headers,
  277. ) -> tuple[str | None, list[Extension]]:
  278. """
  279. Handle the Sec-WebSocket-Extensions HTTP request header.
  280. Accept or reject each extension proposed in the client request.
  281. Negotiate parameters for accepted extensions.
  282. Per :rfc:`6455`, negotiation rules are defined by the specification of
  283. each extension.
  284. To provide this level of flexibility, for each extension proposed by
  285. the client, we check for a match with each extension available in the
  286. server configuration. If no match is found, the extension is ignored.
  287. If several variants of the same extension are proposed by the client,
  288. it may be accepted several times, which won't make sense in general.
  289. Extensions must implement their own requirements. For this purpose,
  290. the list of previously accepted extensions is provided.
  291. This process doesn't allow the server to reorder extensions. It can
  292. only select a subset of the extensions proposed by the client.
  293. Other requirements, for example related to mandatory extensions or the
  294. order of extensions, may be implemented by overriding this method.
  295. Args:
  296. headers: WebSocket handshake request headers.
  297. Returns:
  298. ``Sec-WebSocket-Extensions`` HTTP response header and list of
  299. accepted extensions.
  300. Raises:
  301. InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid.
  302. """
  303. response_header_value: str | None = None
  304. extension_headers: list[ExtensionHeader] = []
  305. accepted_extensions: list[Extension] = []
  306. header_values = headers.get_all("Sec-WebSocket-Extensions")
  307. if header_values and self.available_extensions:
  308. parsed_header_values: list[ExtensionHeader] = sum(
  309. [parse_extension(header_value) for header_value in header_values], []
  310. )
  311. for name, request_params in parsed_header_values:
  312. for ext_factory in self.available_extensions:
  313. # Skip non-matching extensions based on their name.
  314. if ext_factory.name != name:
  315. continue
  316. # Skip non-matching extensions based on their params.
  317. try:
  318. response_params, extension = ext_factory.process_request_params(
  319. request_params, accepted_extensions
  320. )
  321. except NegotiationError:
  322. continue
  323. # Add matching extension to the final list.
  324. extension_headers.append((name, response_params))
  325. accepted_extensions.append(extension)
  326. # Break out of the loop once we have a match.
  327. break
  328. # If we didn't break from the loop, no extension in our list
  329. # matched what the client sent. The extension is declined.
  330. # Serialize extension header.
  331. if extension_headers:
  332. response_header_value = build_extension(extension_headers)
  333. return response_header_value, accepted_extensions
  334. def process_subprotocol(self, headers: Headers) -> Subprotocol | None:
  335. """
  336. Handle the Sec-WebSocket-Protocol HTTP request header.
  337. Args:
  338. headers: WebSocket handshake request headers.
  339. Returns:
  340. Subprotocol, if one was selected; this is also the value of the
  341. ``Sec-WebSocket-Protocol`` response header.
  342. Raises:
  343. InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid.
  344. """
  345. subprotocols: Sequence[Subprotocol] = sum(
  346. [
  347. parse_subprotocol(header_value)
  348. for header_value in headers.get_all("Sec-WebSocket-Protocol")
  349. ],
  350. [],
  351. )
  352. return self.select_subprotocol(subprotocols)
  353. def select_subprotocol(
  354. self,
  355. subprotocols: Sequence[Subprotocol],
  356. ) -> Subprotocol | None:
  357. """
  358. Pick a subprotocol among those offered by the client.
  359. If several subprotocols are supported by both the client and the server,
  360. pick the first one in the list declared the server.
  361. If the server doesn't support any subprotocols, continue without a
  362. subprotocol, regardless of what the client offers.
  363. If the server supports at least one subprotocol and the client doesn't
  364. offer any, abort the handshake with an HTTP 400 error.
  365. You provide a ``select_subprotocol`` argument to :class:`ServerProtocol`
  366. to override this logic. For example, you could accept the connection
  367. even if client doesn't offer a subprotocol, rather than reject it.
  368. Here's how to negotiate the ``chat`` subprotocol if the client supports
  369. it and continue without a subprotocol otherwise::
  370. def select_subprotocol(protocol, subprotocols):
  371. if "chat" in subprotocols:
  372. return "chat"
  373. Args:
  374. subprotocols: List of subprotocols offered by the client.
  375. Returns:
  376. Selected subprotocol, if a common subprotocol was found.
  377. :obj:`None` to continue without a subprotocol.
  378. Raises:
  379. NegotiationError: Custom implementations may raise this exception
  380. to abort the handshake with an HTTP 400 error.
  381. """
  382. # Server doesn't offer any subprotocols.
  383. if not self.available_subprotocols: # None or empty list
  384. return None
  385. # Server offers at least one subprotocol but client doesn't offer any.
  386. if not subprotocols:
  387. raise NegotiationError("missing subprotocol")
  388. # Server and client both offer subprotocols. Look for a shared one.
  389. proposed_subprotocols = set(subprotocols)
  390. for subprotocol in self.available_subprotocols:
  391. if subprotocol in proposed_subprotocols:
  392. return subprotocol
  393. # No common subprotocol was found.
  394. raise NegotiationError(
  395. "invalid subprotocol; expected one of "
  396. + ", ".join(self.available_subprotocols)
  397. )
  398. def reject(self, status: StatusLike, text: str) -> Response:
  399. """
  400. Create a handshake response to reject the connection.
  401. A short plain text response is the best fallback when failing to
  402. establish a WebSocket connection.
  403. You must send the handshake response with :meth:`send_response`.
  404. You may modify the response before sending it, for example by changing
  405. HTTP headers.
  406. Args:
  407. status: HTTP status code.
  408. text: HTTP response body; it will be encoded to UTF-8.
  409. Returns:
  410. HTTP response to send to the client.
  411. """
  412. # If status is an int instead of an HTTPStatus, fix it automatically.
  413. status = http.HTTPStatus(status)
  414. body = text.encode()
  415. headers = Headers(
  416. [
  417. ("Date", email.utils.formatdate(usegmt=True)),
  418. ("Connection", "close"),
  419. ("Content-Length", str(len(body))),
  420. ("Content-Type", "text/plain; charset=utf-8"),
  421. ]
  422. )
  423. return Response(status.value, status.phrase, headers, body)
  424. def send_response(self, response: Response) -> None:
  425. """
  426. Send a handshake response to the client.
  427. Args:
  428. response: WebSocket handshake response event to send.
  429. """
  430. if self.debug:
  431. code, phrase = response.status_code, response.reason_phrase
  432. self.logger.debug("> HTTP/1.1 %d %s", code, phrase)
  433. for key, value in response.headers.raw_items():
  434. self.logger.debug("> %s: %s", key, value)
  435. if response.body:
  436. self.logger.debug("> [body] (%d bytes)", len(response.body))
  437. self.writes.append(response.serialize())
  438. if response.status_code == 101:
  439. assert self.state is CONNECTING
  440. self.state = OPEN
  441. self.logger.info("connection open")
  442. else:
  443. self.logger.info(
  444. "connection rejected (%d %s)",
  445. response.status_code,
  446. response.reason_phrase,
  447. )
  448. self.send_eof()
  449. self.parser = self.discard()
  450. next(self.parser) # start coroutine
  451. def parse(self) -> Generator[None]:
  452. if self.state is CONNECTING:
  453. try:
  454. request = yield from Request.parse(
  455. self.reader.read_line,
  456. )
  457. except Exception as exc:
  458. self.handshake_exc = InvalidMessage(
  459. "did not receive a valid HTTP request"
  460. )
  461. self.handshake_exc.__cause__ = exc
  462. self.send_eof()
  463. self.parser = self.discard()
  464. next(self.parser) # start coroutine
  465. yield
  466. if self.debug:
  467. self.logger.debug("< GET %s HTTP/1.1", request.path)
  468. for key, value in request.headers.raw_items():
  469. self.logger.debug("< %s: %s", key, value)
  470. self.events.append(request)
  471. yield from super().parse()
  472. class ServerConnection(ServerProtocol):
  473. def __init__(self, *args: Any, **kwargs: Any) -> None:
  474. warnings.warn( # deprecated in 11.0 - 2023-04-02
  475. "ServerConnection was renamed to ServerProtocol",
  476. DeprecationWarning,
  477. )
  478. super().__init__(*args, **kwargs)
  479. lazy_import(
  480. globals(),
  481. deprecated_aliases={
  482. # deprecated in 14.0 - 2024-11-09
  483. "WebSocketServer": ".legacy.server",
  484. "WebSocketServerProtocol": ".legacy.server",
  485. "broadcast": ".legacy.server",
  486. "serve": ".legacy.server",
  487. "unix_serve": ".legacy.server",
  488. },
  489. )