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.

client.py 12KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. from __future__ import annotations
  2. import warnings
  3. from typing import Any, Generator, List, Optional, Sequence
  4. from .datastructures import Headers, MultipleValuesError
  5. from .exceptions import (
  6. InvalidHandshake,
  7. InvalidHeader,
  8. InvalidHeaderValue,
  9. InvalidStatus,
  10. InvalidUpgrade,
  11. NegotiationError,
  12. )
  13. from .extensions import ClientExtensionFactory, Extension
  14. from .headers import (
  15. build_authorization_basic,
  16. build_extension,
  17. build_host,
  18. build_subprotocol,
  19. parse_connection,
  20. parse_extension,
  21. parse_subprotocol,
  22. parse_upgrade,
  23. )
  24. from .http11 import Request, Response
  25. from .protocol import CLIENT, CONNECTING, OPEN, Protocol, State
  26. from .typing import (
  27. ConnectionOption,
  28. ExtensionHeader,
  29. LoggerLike,
  30. Origin,
  31. Subprotocol,
  32. UpgradeProtocol,
  33. )
  34. from .uri import WebSocketURI
  35. from .utils import accept_key, generate_key
  36. # See #940 for why lazy_import isn't used here for backwards compatibility.
  37. from .legacy.client import * # isort:skip # noqa: I001
  38. __all__ = ["ClientProtocol"]
  39. class ClientProtocol(Protocol):
  40. """
  41. Sans-I/O implementation of a WebSocket client connection.
  42. Args:
  43. wsuri: URI of the WebSocket server, parsed
  44. with :func:`~websockets.uri.parse_uri`.
  45. origin: value of the ``Origin`` header. This is useful when connecting
  46. to a server that validates the ``Origin`` header to defend against
  47. Cross-Site WebSocket 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. state: initial state of the WebSocket connection.
  53. max_size: maximum size of incoming messages in bytes;
  54. :obj:`None` disables the limit.
  55. logger: logger for this connection;
  56. defaults to ``logging.getLogger("websockets.client")``;
  57. see the :doc:`logging guide <../../topics/logging>` for details.
  58. """
  59. def __init__(
  60. self,
  61. wsuri: WebSocketURI,
  62. *,
  63. origin: Optional[Origin] = None,
  64. extensions: Optional[Sequence[ClientExtensionFactory]] = None,
  65. subprotocols: Optional[Sequence[Subprotocol]] = None,
  66. state: State = CONNECTING,
  67. max_size: Optional[int] = 2**20,
  68. logger: Optional[LoggerLike] = None,
  69. ):
  70. super().__init__(
  71. side=CLIENT,
  72. state=state,
  73. max_size=max_size,
  74. logger=logger,
  75. )
  76. self.wsuri = wsuri
  77. self.origin = origin
  78. self.available_extensions = extensions
  79. self.available_subprotocols = subprotocols
  80. self.key = generate_key()
  81. def connect(self) -> Request:
  82. """
  83. Create a handshake request to open a connection.
  84. You must send the handshake request with :meth:`send_request`.
  85. You can modify it before sending it, for example to add HTTP headers.
  86. Returns:
  87. Request: WebSocket handshake request event to send to the server.
  88. """
  89. headers = Headers()
  90. headers["Host"] = build_host(
  91. self.wsuri.host, self.wsuri.port, self.wsuri.secure
  92. )
  93. if self.wsuri.user_info:
  94. headers["Authorization"] = build_authorization_basic(*self.wsuri.user_info)
  95. if self.origin is not None:
  96. headers["Origin"] = self.origin
  97. headers["Upgrade"] = "websocket"
  98. headers["Connection"] = "Upgrade"
  99. headers["Sec-WebSocket-Key"] = self.key
  100. headers["Sec-WebSocket-Version"] = "13"
  101. if self.available_extensions is not None:
  102. extensions_header = build_extension(
  103. [
  104. (extension_factory.name, extension_factory.get_request_params())
  105. for extension_factory in self.available_extensions
  106. ]
  107. )
  108. headers["Sec-WebSocket-Extensions"] = extensions_header
  109. if self.available_subprotocols is not None:
  110. protocol_header = build_subprotocol(self.available_subprotocols)
  111. headers["Sec-WebSocket-Protocol"] = protocol_header
  112. return Request(self.wsuri.resource_name, headers)
  113. def process_response(self, response: Response) -> None:
  114. """
  115. Check a handshake response.
  116. Args:
  117. request: WebSocket handshake response received from the server.
  118. Raises:
  119. InvalidHandshake: if the handshake response is invalid.
  120. """
  121. if response.status_code != 101:
  122. raise InvalidStatus(response)
  123. headers = response.headers
  124. connection: List[ConnectionOption] = sum(
  125. [parse_connection(value) for value in headers.get_all("Connection")], []
  126. )
  127. if not any(value.lower() == "upgrade" for value in connection):
  128. raise InvalidUpgrade(
  129. "Connection", ", ".join(connection) if connection else None
  130. )
  131. upgrade: List[UpgradeProtocol] = sum(
  132. [parse_upgrade(value) for value in headers.get_all("Upgrade")], []
  133. )
  134. # For compatibility with non-strict implementations, ignore case when
  135. # checking the Upgrade header. It's supposed to be 'WebSocket'.
  136. if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
  137. raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None)
  138. try:
  139. s_w_accept = headers["Sec-WebSocket-Accept"]
  140. except KeyError as exc:
  141. raise InvalidHeader("Sec-WebSocket-Accept") from exc
  142. except MultipleValuesError as exc:
  143. raise InvalidHeader(
  144. "Sec-WebSocket-Accept",
  145. "more than one Sec-WebSocket-Accept header found",
  146. ) from exc
  147. if s_w_accept != accept_key(self.key):
  148. raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept)
  149. self.extensions = self.process_extensions(headers)
  150. self.subprotocol = self.process_subprotocol(headers)
  151. def process_extensions(self, headers: Headers) -> List[Extension]:
  152. """
  153. Handle the Sec-WebSocket-Extensions HTTP response header.
  154. Check that each extension is supported, as well as its parameters.
  155. :rfc:`6455` leaves the rules up to the specification of each
  156. extension.
  157. To provide this level of flexibility, for each extension accepted by
  158. the server, we check for a match with each extension available in the
  159. client configuration. If no match is found, an exception is raised.
  160. If several variants of the same extension are accepted by the server,
  161. it may be configured several times, which won't make sense in general.
  162. Extensions must implement their own requirements. For this purpose,
  163. the list of previously accepted extensions is provided.
  164. Other requirements, for example related to mandatory extensions or the
  165. order of extensions, may be implemented by overriding this method.
  166. Args:
  167. headers: WebSocket handshake response headers.
  168. Returns:
  169. List[Extension]: List of accepted extensions.
  170. Raises:
  171. InvalidHandshake: to abort the handshake.
  172. """
  173. accepted_extensions: List[Extension] = []
  174. extensions = headers.get_all("Sec-WebSocket-Extensions")
  175. if extensions:
  176. if self.available_extensions is None:
  177. raise InvalidHandshake("no extensions supported")
  178. parsed_extensions: List[ExtensionHeader] = sum(
  179. [parse_extension(header_value) for header_value in extensions], []
  180. )
  181. for name, response_params in parsed_extensions:
  182. for extension_factory in self.available_extensions:
  183. # Skip non-matching extensions based on their name.
  184. if extension_factory.name != name:
  185. continue
  186. # Skip non-matching extensions based on their params.
  187. try:
  188. extension = extension_factory.process_response_params(
  189. response_params, accepted_extensions
  190. )
  191. except NegotiationError:
  192. continue
  193. # Add matching extension to the final list.
  194. accepted_extensions.append(extension)
  195. # Break out of the loop once we have a match.
  196. break
  197. # If we didn't break from the loop, no extension in our list
  198. # matched what the server sent. Fail the connection.
  199. else:
  200. raise NegotiationError(
  201. f"Unsupported extension: "
  202. f"name = {name}, params = {response_params}"
  203. )
  204. return accepted_extensions
  205. def process_subprotocol(self, headers: Headers) -> Optional[Subprotocol]:
  206. """
  207. Handle the Sec-WebSocket-Protocol HTTP response header.
  208. If provided, check that it contains exactly one supported subprotocol.
  209. Args:
  210. headers: WebSocket handshake response headers.
  211. Returns:
  212. Optional[Subprotocol]: Subprotocol, if one was selected.
  213. """
  214. subprotocol: Optional[Subprotocol] = None
  215. subprotocols = headers.get_all("Sec-WebSocket-Protocol")
  216. if subprotocols:
  217. if self.available_subprotocols is None:
  218. raise InvalidHandshake("no subprotocols supported")
  219. parsed_subprotocols: Sequence[Subprotocol] = sum(
  220. [parse_subprotocol(header_value) for header_value in subprotocols], []
  221. )
  222. if len(parsed_subprotocols) > 1:
  223. subprotocols_display = ", ".join(parsed_subprotocols)
  224. raise InvalidHandshake(f"multiple subprotocols: {subprotocols_display}")
  225. subprotocol = parsed_subprotocols[0]
  226. if subprotocol not in self.available_subprotocols:
  227. raise NegotiationError(f"unsupported subprotocol: {subprotocol}")
  228. return subprotocol
  229. def send_request(self, request: Request) -> None:
  230. """
  231. Send a handshake request to the server.
  232. Args:
  233. request: WebSocket handshake request event.
  234. """
  235. if self.debug:
  236. self.logger.debug("> GET %s HTTP/1.1", request.path)
  237. for key, value in request.headers.raw_items():
  238. self.logger.debug("> %s: %s", key, value)
  239. self.writes.append(request.serialize())
  240. def parse(self) -> Generator[None, None, None]:
  241. if self.state is CONNECTING:
  242. try:
  243. response = yield from Response.parse(
  244. self.reader.read_line,
  245. self.reader.read_exact,
  246. self.reader.read_to_eof,
  247. )
  248. except Exception as exc:
  249. self.handshake_exc = exc
  250. self.parser = self.discard()
  251. next(self.parser) # start coroutine
  252. yield
  253. if self.debug:
  254. code, phrase = response.status_code, response.reason_phrase
  255. self.logger.debug("< HTTP/1.1 %d %s", code, phrase)
  256. for key, value in response.headers.raw_items():
  257. self.logger.debug("< %s: %s", key, value)
  258. if response.body is not None:
  259. self.logger.debug("< [body] (%d bytes)", len(response.body))
  260. try:
  261. self.process_response(response)
  262. except InvalidHandshake as exc:
  263. response._exception = exc
  264. self.events.append(response)
  265. self.handshake_exc = exc
  266. self.parser = self.discard()
  267. next(self.parser) # start coroutine
  268. yield
  269. assert self.state is CONNECTING
  270. self.state = OPEN
  271. self.events.append(response)
  272. yield from super().parse()
  273. class ClientConnection(ClientProtocol):
  274. def __init__(self, *args: Any, **kwargs: Any) -> None:
  275. warnings.warn(
  276. "ClientConnection was renamed to ClientProtocol",
  277. DeprecationWarning,
  278. )
  279. super().__init__(*args, **kwargs)