Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

server.py 20KB

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