exceptions.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. """
  2. :mod:`websockets.exceptions` defines the following hierarchy of exceptions.
  3. * :exc:`WebSocketException`
  4. * :exc:`ConnectionClosed`
  5. * :exc:`ConnectionClosedOK`
  6. * :exc:`ConnectionClosedError`
  7. * :exc:`InvalidURI`
  8. * :exc:`InvalidProxy`
  9. * :exc:`InvalidHandshake`
  10. * :exc:`SecurityError`
  11. * :exc:`RequestLineTooLong`
  12. * :exc:`StatusLineTooLong`
  13. * :exc:`HeaderLineTooLong`
  14. * :exc:`TooManyHeaders`
  15. * :exc:`ProxyError`
  16. * :exc:`InvalidProxyMessage`
  17. * :exc:`InvalidProxyStatus`
  18. * :exc:`InvalidMessage`
  19. * :exc:`InvalidMethod`
  20. * :exc:`InvalidProtocol`
  21. * :exc:`InvalidStatus`
  22. * :exc:`InvalidStatusCode` (legacy)
  23. * :exc:`InvalidHeader`
  24. * :exc:`InvalidHeaderFormat`
  25. * :exc:`InvalidHeaderValue`
  26. * :exc:`InvalidOrigin`
  27. * :exc:`InvalidUpgrade`
  28. * :exc:`NegotiationError`
  29. * :exc:`DuplicateParameter`
  30. * :exc:`InvalidParameterName`
  31. * :exc:`InvalidParameterValue`
  32. * :exc:`AbortHandshake` (legacy)
  33. * :exc:`RedirectHandshake` (legacy)
  34. * :exc:`ProtocolError` (Sans-I/O)
  35. * :exc:`PayloadTooBig` (Sans-I/O)
  36. * :exc:`InvalidState` (Sans-I/O)
  37. * :exc:`ConcurrencyError`
  38. """
  39. from __future__ import annotations
  40. import warnings
  41. from .imports import lazy_import
  42. __all__ = [
  43. "WebSocketException",
  44. "ConnectionClosed",
  45. "ConnectionClosedOK",
  46. "ConnectionClosedError",
  47. "InvalidURI",
  48. "InvalidProxy",
  49. "InvalidHandshake",
  50. "SecurityError",
  51. "RequestLineTooLong",
  52. "StatusLineTooLong",
  53. "HeaderLineTooLong",
  54. "TooManyHeaders",
  55. "ProxyError",
  56. "InvalidProxyMessage",
  57. "InvalidProxyStatus",
  58. "InvalidMessage",
  59. "InvalidMethod",
  60. "InvalidProtocol",
  61. "InvalidStatus",
  62. "InvalidHeader",
  63. "InvalidHeaderFormat",
  64. "InvalidHeaderValue",
  65. "InvalidOrigin",
  66. "InvalidUpgrade",
  67. "NegotiationError",
  68. "DuplicateParameter",
  69. "InvalidParameterName",
  70. "InvalidParameterValue",
  71. "ProtocolError",
  72. "PayloadTooBig",
  73. "InvalidState",
  74. "ConcurrencyError",
  75. ]
  76. class WebSocketException(Exception):
  77. """
  78. Base class for all exceptions defined by websockets.
  79. """
  80. class ConnectionClosed(WebSocketException):
  81. """
  82. Raised when trying to interact with a closed connection.
  83. Attributes:
  84. rcvd: If a close frame was received, its code and reason are available
  85. in ``rcvd.code`` and ``rcvd.reason``.
  86. sent: If a close frame was sent, its code and reason are available
  87. in ``sent.code`` and ``sent.reason``.
  88. rcvd_then_sent: If close frames were received and sent, this attribute
  89. tells in which order this happened, from the perspective of this
  90. side of the connection.
  91. """
  92. def __init__(
  93. self,
  94. rcvd: frames.Close | None,
  95. sent: frames.Close | None,
  96. rcvd_then_sent: bool | None = None,
  97. ) -> None:
  98. self.rcvd = rcvd
  99. self.sent = sent
  100. self.rcvd_then_sent = rcvd_then_sent
  101. assert (self.rcvd_then_sent is None) == (self.rcvd is None or self.sent is None)
  102. def __str__(self) -> str:
  103. if self.rcvd is None:
  104. if self.sent is None:
  105. return "no close frame received or sent"
  106. else:
  107. return f"sent {self.sent}; no close frame received"
  108. else:
  109. if self.sent is None:
  110. return f"received {self.rcvd}; no close frame sent"
  111. else:
  112. if self.rcvd_then_sent:
  113. return f"received {self.rcvd}; then sent {self.sent}"
  114. else:
  115. return f"sent {self.sent}; then received {self.rcvd}"
  116. # code and reason attributes are provided for backwards-compatibility
  117. @property
  118. def code(self) -> int:
  119. warnings.warn( # deprecated in 13.1 - 2024-09-21
  120. "ConnectionClosed.code is deprecated; "
  121. "use Protocol.close_code or ConnectionClosed.rcvd.code",
  122. DeprecationWarning,
  123. )
  124. if self.rcvd is None:
  125. return frames.CloseCode.ABNORMAL_CLOSURE
  126. return self.rcvd.code
  127. @property
  128. def reason(self) -> str:
  129. warnings.warn( # deprecated in 13.1 - 2024-09-21
  130. "ConnectionClosed.reason is deprecated; "
  131. "use Protocol.close_reason or ConnectionClosed.rcvd.reason",
  132. DeprecationWarning,
  133. )
  134. if self.rcvd is None:
  135. return ""
  136. return self.rcvd.reason
  137. class ConnectionClosedOK(ConnectionClosed):
  138. """
  139. Like :exc:`ConnectionClosed`, when the connection terminated properly.
  140. A close code with code 1000 (OK) or 1001 (going away) or without a code was
  141. received and sent.
  142. """
  143. class ConnectionClosedError(ConnectionClosed):
  144. """
  145. Like :exc:`ConnectionClosed`, when the connection terminated with an error.
  146. A close frame with a code other than 1000 (OK) or 1001 (going away) was
  147. received or sent, or the closing handshake didn't complete properly.
  148. """
  149. class InvalidURI(WebSocketException):
  150. """
  151. Raised when connecting to a URI that isn't a valid WebSocket URI.
  152. """
  153. def __init__(self, uri: str, msg: str) -> None:
  154. self.uri = uri
  155. self.msg = msg
  156. def __str__(self) -> str:
  157. return f"{self.uri} isn't a valid URI: {self.msg}"
  158. class InvalidProxy(WebSocketException):
  159. """
  160. Raised when connecting via a proxy that isn't valid.
  161. """
  162. def __init__(self, proxy: str, msg: str) -> None:
  163. self.proxy = proxy
  164. self.msg = msg
  165. def __str__(self) -> str:
  166. return f"{self.proxy} isn't a valid proxy: {self.msg}"
  167. class InvalidHandshake(WebSocketException):
  168. """
  169. Base class for exceptions raised when the opening handshake fails.
  170. """
  171. class SecurityError(InvalidHandshake):
  172. """
  173. Raised when a handshake request or response breaks a security rule.
  174. Security limits can be configured with :doc:`environment variables
  175. <../reference/variables>`.
  176. """
  177. class RequestLineTooLong(SecurityError):
  178. """
  179. Raised when the request line of a handshake request is too long.
  180. """
  181. class StatusLineTooLong(SecurityError):
  182. """
  183. Raised when the status line of a handshake response is too long.
  184. """
  185. class HeaderLineTooLong(SecurityError):
  186. """
  187. Raised when a header line of a handshake request or response is too long.
  188. """
  189. class TooManyHeaders(SecurityError):
  190. """
  191. Raised when a handshake request or response has too many headers.
  192. """
  193. class ProxyError(InvalidHandshake):
  194. """
  195. Raised when failing to connect to a proxy.
  196. """
  197. class InvalidProxyMessage(ProxyError):
  198. """
  199. Raised when an HTTP proxy response is malformed.
  200. """
  201. class InvalidProxyStatus(ProxyError):
  202. """
  203. Raised when an HTTP proxy rejects the connection.
  204. """
  205. def __init__(self, response: http11.Response) -> None:
  206. self.response = response
  207. def __str__(self) -> str:
  208. return f"proxy rejected connection: HTTP {self.response.status_code:d}"
  209. class InvalidMessage(InvalidHandshake):
  210. """
  211. Raised when a handshake request or response is malformed.
  212. """
  213. class InvalidMethod(InvalidHandshake):
  214. """
  215. Raised when a handshake request doesn't use HTTP GET.
  216. """
  217. def __init__(self, method: str) -> None:
  218. self.method = method
  219. def __str__(self) -> str:
  220. return f"unsupported HTTP method: {self.method}"
  221. class InvalidProtocol(InvalidHandshake):
  222. """
  223. Raised when a handshake request doesn't use HTTP/1.1.
  224. """
  225. def __init__(self, protocol: str) -> None:
  226. self.protocol = protocol
  227. def __str__(self) -> str:
  228. return f"unsupported HTTP version: {self.protocol}"
  229. class InvalidStatus(InvalidHandshake):
  230. """
  231. Raised when a handshake response rejects the WebSocket upgrade.
  232. """
  233. def __init__(self, response: http11.Response) -> None:
  234. self.response = response
  235. def __str__(self) -> str:
  236. return (
  237. f"server rejected WebSocket connection: HTTP {self.response.status_code:d}"
  238. )
  239. class InvalidHeader(InvalidHandshake):
  240. """
  241. Raised when an HTTP header doesn't have a valid format or value.
  242. """
  243. def __init__(self, name: str, value: str | None = None) -> None:
  244. self.name = name
  245. self.value = value
  246. def __str__(self) -> str:
  247. if self.value is None:
  248. return f"missing {self.name} header"
  249. elif self.value == "":
  250. return f"empty {self.name} header"
  251. else:
  252. return f"invalid {self.name} header: {self.value}"
  253. class InvalidHeaderFormat(InvalidHeader):
  254. """
  255. Raised when an HTTP header cannot be parsed.
  256. The format of the header doesn't match the grammar for that header.
  257. """
  258. def __init__(self, name: str, error: str, header: str, pos: int) -> None:
  259. super().__init__(name, f"{error} at {pos} in {header}")
  260. class InvalidHeaderValue(InvalidHeader):
  261. """
  262. Raised when an HTTP header has a wrong value.
  263. The format of the header is correct but the value isn't acceptable.
  264. """
  265. class InvalidOrigin(InvalidHeader):
  266. """
  267. Raised when the Origin header in a request isn't allowed.
  268. """
  269. def __init__(self, origin: str | None) -> None:
  270. super().__init__("Origin", origin)
  271. class InvalidUpgrade(InvalidHeader):
  272. """
  273. Raised when the Upgrade or Connection header isn't correct.
  274. """
  275. class NegotiationError(InvalidHandshake):
  276. """
  277. Raised when negotiating an extension or a subprotocol fails.
  278. """
  279. class DuplicateParameter(NegotiationError):
  280. """
  281. Raised when a parameter name is repeated in an extension header.
  282. """
  283. def __init__(self, name: str) -> None:
  284. self.name = name
  285. def __str__(self) -> str:
  286. return f"duplicate parameter: {self.name}"
  287. class InvalidParameterName(NegotiationError):
  288. """
  289. Raised when a parameter name in an extension header is invalid.
  290. """
  291. def __init__(self, name: str) -> None:
  292. self.name = name
  293. def __str__(self) -> str:
  294. return f"invalid parameter name: {self.name}"
  295. class InvalidParameterValue(NegotiationError):
  296. """
  297. Raised when a parameter value in an extension header is invalid.
  298. """
  299. def __init__(self, name: str, value: str | None) -> None:
  300. self.name = name
  301. self.value = value
  302. def __str__(self) -> str:
  303. if self.value is None:
  304. return f"missing value for parameter {self.name}"
  305. elif self.value == "":
  306. return f"empty value for parameter {self.name}"
  307. else:
  308. return f"invalid value for parameter {self.name}: {self.value}"
  309. class ProtocolError(WebSocketException):
  310. """
  311. Raised when receiving or sending a frame that breaks the protocol.
  312. The Sans-I/O implementation raises this exception when:
  313. * receiving or sending a frame that contains invalid data;
  314. * receiving or sending an invalid sequence of frames.
  315. """
  316. class PayloadTooBig(WebSocketException):
  317. """
  318. Raised when parsing a frame with a payload that exceeds the maximum size.
  319. The Sans-I/O layer uses this exception internally. It doesn't bubble up to
  320. the I/O layer.
  321. The :meth:`~websockets.extensions.Extension.decode` method of extensions
  322. must raise :exc:`PayloadTooBig` if decoding a frame would exceed the limit.
  323. """
  324. def __init__(
  325. self,
  326. size_or_message: int | None | str,
  327. max_size: int | None = None,
  328. current_size: int | None = None,
  329. ) -> None:
  330. if isinstance(size_or_message, str):
  331. assert max_size is None
  332. assert current_size is None
  333. warnings.warn( # deprecated in 14.0 - 2024-11-09
  334. "PayloadTooBig(message) is deprecated; "
  335. "change to PayloadTooBig(size, max_size)",
  336. DeprecationWarning,
  337. )
  338. self.message: str | None = size_or_message
  339. else:
  340. self.message = None
  341. self.size: int | None = size_or_message
  342. assert max_size is not None
  343. self.max_size: int = max_size
  344. self.current_size: int | None = None
  345. self.set_current_size(current_size)
  346. def __str__(self) -> str:
  347. if self.message is not None:
  348. return self.message
  349. else:
  350. message = "frame "
  351. if self.size is not None:
  352. message += f"with {self.size} bytes "
  353. if self.current_size is not None:
  354. message += f"after reading {self.current_size} bytes "
  355. message += f"exceeds limit of {self.max_size} bytes"
  356. return message
  357. def set_current_size(self, current_size: int | None) -> None:
  358. assert self.current_size is None
  359. if current_size is not None:
  360. self.max_size += current_size
  361. self.current_size = current_size
  362. class InvalidState(WebSocketException, AssertionError):
  363. """
  364. Raised when sending a frame is forbidden in the current state.
  365. Specifically, the Sans-I/O layer raises this exception when:
  366. * sending a data frame to a connection in a state other
  367. :attr:`~websockets.protocol.State.OPEN`;
  368. * sending a control frame to a connection in a state other than
  369. :attr:`~websockets.protocol.State.OPEN` or
  370. :attr:`~websockets.protocol.State.CLOSING`.
  371. """
  372. class ConcurrencyError(WebSocketException, RuntimeError):
  373. """
  374. Raised when receiving or sending messages concurrently.
  375. WebSocket is a connection-oriented protocol. Reads must be serialized; so
  376. must be writes. However, reading and writing concurrently is possible.
  377. """
  378. # At the bottom to break import cycles created by type annotations.
  379. from . import frames, http11 # noqa: E402
  380. lazy_import(
  381. globals(),
  382. deprecated_aliases={
  383. # deprecated in 14.0 - 2024-11-09
  384. "AbortHandshake": ".legacy.exceptions",
  385. "InvalidStatusCode": ".legacy.exceptions",
  386. "RedirectHandshake": ".legacy.exceptions",
  387. "WebSocketProtocolError": ".legacy.exceptions",
  388. },
  389. )