| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import enum |
| 4 |
import logging |
| 5 |
import uuid |
| 6 |
from collections.abc import Generator |
| 7 |
|
| 8 |
from .exceptions import ( |
| 9 |
ConnectionClosed, |
| 10 |
ConnectionClosedError, |
| 11 |
ConnectionClosedOK, |
| 12 |
InvalidState, |
| 13 |
PayloadTooBig, |
| 14 |
ProtocolError, |
| 15 |
) |
| 16 |
from .extensions import Extension |
| 17 |
from .frames import ( |
| 18 |
BINARY, |
| 19 |
CLOSE, |
| 20 |
CONT, |
| 21 |
OK_CLOSE_CODES, |
| 22 |
PING, |
| 23 |
PONG, |
| 24 |
TEXT, |
| 25 |
Close, |
| 26 |
CloseCode, |
| 27 |
Frame, |
| 28 |
) |
| 29 |
from .http11 import Request, Response |
| 30 |
from .streams import StreamReader |
| 31 |
from .typing import BytesLike, LoggerLike, Origin, Subprotocol |
| 32 |
|
| 33 |
|
| 34 |
__all__ = [ |
| 35 |
"Protocol", |
| 36 |
"Side", |
| 37 |
"State", |
| 38 |
"SEND_EOF", |
| 39 |
] |
| 40 |
|
| 41 |
Event = Request | Response | Frame |
| 42 |
"""Events that :meth:`~Protocol.events_received` may return.""" |
| 43 |
|
| 44 |
|
| 45 |
class Side(enum.IntEnum): |
| 46 |
"""A WebSocket connection is either a server or a client.""" |
| 47 |
|
| 48 |
SERVER, CLIENT = range(2) |
| 49 |
|
| 50 |
|
| 51 |
SERVER = Side.SERVER |
| 52 |
CLIENT = Side.CLIENT |
| 53 |
|
| 54 |
|
| 55 |
class State(enum.IntEnum): |
| 56 |
"""A WebSocket connection is in one of these four states.""" |
| 57 |
|
| 58 |
CONNECTING, OPEN, CLOSING, CLOSED = range(4) |
| 59 |
|
| 60 |
|
| 61 |
CONNECTING = State.CONNECTING |
| 62 |
OPEN = State.OPEN |
| 63 |
CLOSING = State.CLOSING |
| 64 |
CLOSED = State.CLOSED |
| 65 |
|
| 66 |
|
| 67 |
SEND_EOF = b"" |
| 68 |
"""Sentinel signaling that the TCP connection must be half-closed.""" |
| 69 |
|
| 70 |
|
| 71 |
class Protocol: |
| 72 |
""" |
| 73 |
Sans-I/O implementation of a WebSocket connection. |
| 74 |
|
| 75 |
Args: |
| 76 |
side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`. |
| 77 |
state: Initial state of the WebSocket connection. |
| 78 |
max_size: Maximum size of incoming messages in bytes. |
| 79 |
:obj:`None` disables the limit. You may pass a ``(max_message_size, |
| 80 |
max_fragment_size)`` tuple to set different limits for messages and |
| 81 |
fragments when you expect long messages sent in short fragments. |
| 82 |
logger: Logger for this connection; depending on ``side``, |
| 83 |
defaults to ``logging.getLogger("websockets.client")`` |
| 84 |
or ``logging.getLogger("websockets.server")``; |
| 85 |
see the :doc:`logging guide <../../topics/logging>` for details. |
| 86 |
|
| 87 |
""" |
| 88 |
|
| 89 |
def __init__( |
| 90 |
self, |
| 91 |
side: Side, |
| 92 |
*, |
| 93 |
state: State = OPEN, |
| 94 |
max_size: tuple[int | None, int | None] | int | None = 2**20, |
| 95 |
logger: LoggerLike | None = None, |
| 96 |
) -> None: |
| 97 |
# Unique identifier. For logs. |
| 98 |
self.id: uuid.UUID = uuid.uuid4() |
| 99 |
"""Unique identifier of the connection. Useful in logs.""" |
| 100 |
|
| 101 |
# Logger or LoggerAdapter for this connection. |
| 102 |
if logger is None: |
| 103 |
logger = logging.getLogger(f"websockets.{side.name.lower()}") |
| 104 |
self.logger: LoggerLike = logger |
| 105 |
"""Logger for this connection.""" |
| 106 |
|
| 107 |
# Track if DEBUG is enabled. Shortcut logging calls if it isn't. |
| 108 |
self.debug = logger.isEnabledFor(logging.DEBUG) |
| 109 |
|
| 110 |
# Connection side. CLIENT or SERVER. |
| 111 |
self.side = side |
| 112 |
|
| 113 |
# Connection state. Initially OPEN because subclasses handle CONNECTING. |
| 114 |
self.state = state |
| 115 |
|
| 116 |
# Maximum size of incoming messages in bytes. |
| 117 |
if isinstance(max_size, int) or max_size is None: |
| 118 |
self.max_message_size, self.max_fragment_size = max_size, None |
| 119 |
else: |
| 120 |
self.max_message_size, self.max_fragment_size = max_size |
| 121 |
|
| 122 |
# Current size of incoming message in bytes. Only set while reading a |
| 123 |
# fragmented message i.e. a data frames with the FIN bit not set. |
| 124 |
self.current_size: int | None = None |
| 125 |
|
| 126 |
# True while sending a fragmented message i.e. a data frames with the |
| 127 |
# FIN bit not set. |
| 128 |
self.expect_continuation_frame = False |
| 129 |
|
| 130 |
# WebSocket protocol parameters. |
| 131 |
self.origin: Origin | None = None |
| 132 |
self.extensions: list[Extension] = [] |
| 133 |
self.subprotocol: Subprotocol | None = None |
| 134 |
|
| 135 |
# Close code and reason, set when a close frame is sent or received. |
| 136 |
self.close_rcvd: Close | None = None |
| 137 |
self.close_sent: Close | None = None |
| 138 |
self.close_rcvd_then_sent: bool | None = None |
| 139 |
|
| 140 |
# Track if an exception happened during the handshake. |
| 141 |
self.handshake_exc: Exception | None = None |
| 142 |
""" |
| 143 |
Exception to raise if the opening handshake failed. |
| 144 |
|
| 145 |
:obj:`None` if the opening handshake succeeded. |
| 146 |
|
| 147 |
""" |
| 148 |
|
| 149 |
# Track if send_eof() was called. |
| 150 |
self.eof_sent = False |
| 151 |
|
| 152 |
# Parser state. |
| 153 |
self.reader = StreamReader() |
| 154 |
self.events: list[Event] = [] |
| 155 |
self.writes: list[bytes] = [] |
| 156 |
self.parser = self.parse() |
| 157 |
next(self.parser) # start coroutine |
| 158 |
self.parser_exc: Exception | None = None |
| 159 |
|
| 160 |
@property |
| 161 |
def state(self) -> State: |
| 162 |
""" |
| 163 |
State of the WebSocket connection. |
| 164 |
|
| 165 |
Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`. |
| 166 |
|
| 167 |
.. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1 |
| 168 |
.. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2 |
| 169 |
.. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3 |
| 170 |
.. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 |
| 171 |
|
| 172 |
""" |
| 173 |
return self._state |
| 174 |
|
| 175 |
@state.setter |
| 176 |
def state(self, state: State) -> None: |
| 177 |
if self.debug: |
| 178 |
self.logger.debug("= connection is %s", state.name) |
| 179 |
self._state = state |
| 180 |
|
| 181 |
@property |
| 182 |
def close_code(self) -> int | None: |
| 183 |
""" |
| 184 |
WebSocket close code received from the remote endpoint. |
| 185 |
|
| 186 |
Defined in 7.1.5_ of :rfc:`6455`. |
| 187 |
|
| 188 |
.. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 |
| 189 |
|
| 190 |
:obj:`None` if the connection isn't closed yet. |
| 191 |
|
| 192 |
""" |
| 193 |
if self.state is not CLOSED: |
| 194 |
return None |
| 195 |
elif self.close_rcvd is None: |
| 196 |
return CloseCode.ABNORMAL_CLOSURE |
| 197 |
else: |
| 198 |
return self.close_rcvd.code |
| 199 |
|
| 200 |
@property |
| 201 |
def close_reason(self) -> str | None: |
| 202 |
""" |
| 203 |
WebSocket close reason received from the remote endpoint. |
| 204 |
|
| 205 |
Defined in 7.1.6_ of :rfc:`6455`. |
| 206 |
|
| 207 |
.. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 |
| 208 |
|
| 209 |
:obj:`None` if the connection isn't closed yet. |
| 210 |
|
| 211 |
""" |
| 212 |
if self.state is not CLOSED: |
| 213 |
return None |
| 214 |
elif self.close_rcvd is None: |
| 215 |
return "" |
| 216 |
else: |
| 217 |
return self.close_rcvd.reason |
| 218 |
|
| 219 |
@property |
| 220 |
def close_exc(self) -> ConnectionClosed: |
| 221 |
""" |
| 222 |
Exception to raise when trying to interact with a closed connection. |
| 223 |
|
| 224 |
Don't raise this exception while the connection :attr:`state` |
| 225 |
is :attr:`~websockets.protocol.State.CLOSING`; wait until |
| 226 |
it's :attr:`~websockets.protocol.State.CLOSED`. |
| 227 |
|
| 228 |
Indeed, the exception includes the close code and reason, which are |
| 229 |
known only once the connection is closed. |
| 230 |
|
| 231 |
Raises: |
| 232 |
AssertionError: If the connection isn't closed yet. |
| 233 |
|
| 234 |
""" |
| 235 |
assert self.state is CLOSED, "connection isn't closed yet" |
| 236 |
exc_type: type[ConnectionClosed] |
| 237 |
if ( |
| 238 |
self.close_rcvd is not None |
| 239 |
and self.close_sent is not None |
| 240 |
and self.close_rcvd.code in OK_CLOSE_CODES |
| 241 |
and self.close_sent.code in OK_CLOSE_CODES |
| 242 |
): |
| 243 |
exc_type = ConnectionClosedOK |
| 244 |
else: |
| 245 |
exc_type = ConnectionClosedError |
| 246 |
exc: ConnectionClosed = exc_type( |
| 247 |
self.close_rcvd, |
| 248 |
self.close_sent, |
| 249 |
self.close_rcvd_then_sent, |
| 250 |
) |
| 251 |
# Chain to the exception raised in the parser, if any. |
| 252 |
exc.__cause__ = self.parser_exc |
| 253 |
return exc |
| 254 |
|
| 255 |
# Public methods for receiving data. |
| 256 |
|
| 257 |
def receive_data(self, data: bytes | bytearray) -> None: |
| 258 |
""" |
| 259 |
Receive data from the network. |
| 260 |
|
| 261 |
After calling this method: |
| 262 |
|
| 263 |
- You must call :meth:`data_to_send` and send this data to the network. |
| 264 |
- You should call :meth:`events_received` and process resulting events. |
| 265 |
|
| 266 |
Raises: |
| 267 |
EOFError: If :meth:`receive_eof` was called earlier. |
| 268 |
|
| 269 |
""" |
| 270 |
self.reader.feed_data(data) |
| 271 |
next(self.parser) |
| 272 |
|
| 273 |
def receive_eof(self) -> None: |
| 274 |
""" |
| 275 |
Receive the end of the data stream from the network. |
| 276 |
|
| 277 |
After calling this method: |
| 278 |
|
| 279 |
- You must call :meth:`data_to_send` and send this data to the network; |
| 280 |
it will return ``[b""]``, signaling the end of the stream, or ``[]``. |
| 281 |
- You aren't expected to call :meth:`events_received`; it won't return |
| 282 |
any new events. |
| 283 |
|
| 284 |
:meth:`receive_eof` is idempotent. |
| 285 |
|
| 286 |
""" |
| 287 |
if self.reader.eof: |
| 288 |
return |
| 289 |
self.reader.feed_eof() |
| 290 |
next(self.parser) |
| 291 |
|
| 292 |
# Public methods for sending events. |
| 293 |
|
| 294 |
def send_continuation(self, data: BytesLike, fin: bool) -> None: |
| 295 |
""" |
| 296 |
Send a `Continuation frame`_. |
| 297 |
|
| 298 |
.. _Continuation frame: |
| 299 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 |
| 300 |
|
| 301 |
Parameters: |
| 302 |
data: payload containing the same kind of data |
| 303 |
as the initial frame. |
| 304 |
fin: FIN bit; set it to :obj:`True` if this is the last frame |
| 305 |
of a fragmented message and to :obj:`False` otherwise. |
| 306 |
|
| 307 |
Raises: |
| 308 |
ProtocolError: If a fragmented message isn't in progress. |
| 309 |
|
| 310 |
""" |
| 311 |
if not self.expect_continuation_frame: |
| 312 |
raise ProtocolError("unexpected continuation frame") |
| 313 |
if self._state is not OPEN: |
| 314 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 315 |
self.expect_continuation_frame = not fin |
| 316 |
self.send_frame(Frame(CONT, data, fin)) |
| 317 |
|
| 318 |
def send_text(self, data: BytesLike, fin: bool = True) -> None: |
| 319 |
""" |
| 320 |
Send a `Text frame`_. |
| 321 |
|
| 322 |
.. _Text frame: |
| 323 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 |
| 324 |
|
| 325 |
Parameters: |
| 326 |
data: payload containing text encoded with UTF-8. |
| 327 |
fin: FIN bit; set it to :obj:`False` if this is the first frame of |
| 328 |
a fragmented message. |
| 329 |
|
| 330 |
Raises: |
| 331 |
ProtocolError: If a fragmented message is in progress. |
| 332 |
|
| 333 |
""" |
| 334 |
if self.expect_continuation_frame: |
| 335 |
raise ProtocolError("expected a continuation frame") |
| 336 |
if self._state is not OPEN: |
| 337 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 338 |
self.expect_continuation_frame = not fin |
| 339 |
self.send_frame(Frame(TEXT, data, fin)) |
| 340 |
|
| 341 |
def send_binary(self, data: BytesLike, fin: bool = True) -> None: |
| 342 |
""" |
| 343 |
Send a `Binary frame`_. |
| 344 |
|
| 345 |
.. _Binary frame: |
| 346 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 |
| 347 |
|
| 348 |
Parameters: |
| 349 |
data: payload containing arbitrary binary data. |
| 350 |
fin: FIN bit; set it to :obj:`False` if this is the first frame of |
| 351 |
a fragmented message. |
| 352 |
|
| 353 |
Raises: |
| 354 |
ProtocolError: If a fragmented message is in progress. |
| 355 |
|
| 356 |
""" |
| 357 |
if self.expect_continuation_frame: |
| 358 |
raise ProtocolError("expected a continuation frame") |
| 359 |
if self._state is not OPEN: |
| 360 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 361 |
self.expect_continuation_frame = not fin |
| 362 |
self.send_frame(Frame(BINARY, data, fin)) |
| 363 |
|
| 364 |
def send_close(self, code: CloseCode | int | None = None, reason: str = "") -> None: |
| 365 |
""" |
| 366 |
Send a `Close frame`_. |
| 367 |
|
| 368 |
.. _Close frame: |
| 369 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1 |
| 370 |
|
| 371 |
Parameters: |
| 372 |
code: close code. |
| 373 |
reason: close reason. |
| 374 |
|
| 375 |
Raises: |
| 376 |
ProtocolError: If the code isn't valid or if a reason is provided |
| 377 |
without a code. |
| 378 |
|
| 379 |
""" |
| 380 |
# While RFC 6455 doesn't rule out sending more than one close Frame, |
| 381 |
# websockets is conservative in what it sends and doesn't allow that. |
| 382 |
if self._state is not OPEN: |
| 383 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 384 |
if code is None: |
| 385 |
if reason != "": |
| 386 |
raise ProtocolError("cannot send a reason without a code") |
| 387 |
close = Close(CloseCode.NO_STATUS_RCVD, "") |
| 388 |
data = b"" |
| 389 |
else: |
| 390 |
close = Close(code, reason) |
| 391 |
data = close.serialize() |
| 392 |
# 7.1.3. The WebSocket Closing Handshake is Started |
| 393 |
self.send_frame(Frame(CLOSE, data)) |
| 394 |
# Since the state is OPEN, no close frame was received yet. |
| 395 |
# As a consequence, self.close_rcvd_then_sent remains None. |
| 396 |
assert self.close_rcvd is None |
| 397 |
self.close_sent = close |
| 398 |
self.state = CLOSING |
| 399 |
|
| 400 |
def send_ping(self, data: BytesLike) -> None: |
| 401 |
""" |
| 402 |
Send a `Ping frame`_. |
| 403 |
|
| 404 |
.. _Ping frame: |
| 405 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 |
| 406 |
|
| 407 |
Parameters: |
| 408 |
data: payload containing arbitrary binary data. |
| 409 |
|
| 410 |
""" |
| 411 |
# RFC 6455 allows control frames after starting the closing handshake. |
| 412 |
if self._state is not OPEN and self._state is not CLOSING: |
| 413 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 414 |
self.send_frame(Frame(PING, data)) |
| 415 |
|
| 416 |
def send_pong(self, data: BytesLike) -> None: |
| 417 |
""" |
| 418 |
Send a `Pong frame`_. |
| 419 |
|
| 420 |
.. _Pong frame: |
| 421 |
https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 |
| 422 |
|
| 423 |
Parameters: |
| 424 |
data: payload containing arbitrary binary data. |
| 425 |
|
| 426 |
""" |
| 427 |
# RFC 6455 allows control frames after starting the closing handshake. |
| 428 |
if self._state is not OPEN and self._state is not CLOSING: |
| 429 |
raise InvalidState(f"connection is {self.state.name.lower()}") |
| 430 |
self.send_frame(Frame(PONG, data)) |
| 431 |
|
| 432 |
def fail(self, code: CloseCode | int, reason: str = "") -> None: |
| 433 |
""" |
| 434 |
`Fail the WebSocket connection`_. |
| 435 |
|
| 436 |
.. _Fail the WebSocket connection: |
| 437 |
https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7 |
| 438 |
|
| 439 |
Parameters: |
| 440 |
code: close code |
| 441 |
reason: close reason |
| 442 |
|
| 443 |
Raises: |
| 444 |
ProtocolError: If the code isn't valid. |
| 445 |
""" |
| 446 |
# 7.1.7. Fail the WebSocket Connection |
| 447 |
|
| 448 |
# Send a close frame when the state is OPEN (a close frame was already |
| 449 |
# sent if it's CLOSING), except when failing the connection because |
| 450 |
# of an error reading from or writing to the network. |
| 451 |
if self.state is OPEN: |
| 452 |
if code != CloseCode.ABNORMAL_CLOSURE: |
| 453 |
close = Close(code, reason) |
| 454 |
data = close.serialize() |
| 455 |
self.send_frame(Frame(CLOSE, data)) |
| 456 |
self.close_sent = close |
| 457 |
# If recv_messages() raised an exception upon receiving a close |
| 458 |
# frame but before echoing it, then close_rcvd is not None even |
| 459 |
# though the state is OPEN. This happens when the connection is |
| 460 |
# closed while receiving a fragmented message. |
| 461 |
if self.close_rcvd is not None: |
| 462 |
self.close_rcvd_then_sent = True |
| 463 |
self.state = CLOSING |
| 464 |
|
| 465 |
# When failing the connection, a server closes the TCP connection |
| 466 |
# without waiting for the client to complete the handshake, while a |
| 467 |
# client waits for the server to close the TCP connection, possibly |
| 468 |
# after sending a close frame that the client will ignore. |
| 469 |
if self.side is SERVER and not self.eof_sent: |
| 470 |
self.send_eof() |
| 471 |
|
| 472 |
# 7.1.7. Fail the WebSocket Connection "An endpoint MUST NOT continue |
| 473 |
# to attempt to process data(including a responding Close frame) from |
| 474 |
# the remote endpoint after being instructed to _Fail the WebSocket |
| 475 |
# Connection_." |
| 476 |
self.parser = self.discard() |
| 477 |
next(self.parser) # start coroutine |
| 478 |
|
| 479 |
# Public method for getting incoming events after receiving data. |
| 480 |
|
| 481 |
def events_received(self) -> list[Event]: |
| 482 |
""" |
| 483 |
Fetch events generated from data received from the network. |
| 484 |
|
| 485 |
Call this method immediately after any of the ``receive_*()`` methods. |
| 486 |
|
| 487 |
Process resulting events, likely by passing them to the application. |
| 488 |
|
| 489 |
Returns: |
| 490 |
Events read from the connection. |
| 491 |
""" |
| 492 |
events, self.events = self.events, [] |
| 493 |
return events |
| 494 |
|
| 495 |
# Public method for getting outgoing data after receiving data or sending events. |
| 496 |
|
| 497 |
def data_to_send(self) -> list[bytes]: |
| 498 |
""" |
| 499 |
Obtain data to send to the network. |
| 500 |
|
| 501 |
Call this method immediately after any of the ``receive_*()``, |
| 502 |
``send_*()``, or :meth:`fail` methods. |
| 503 |
|
| 504 |
Write resulting data to the connection. |
| 505 |
|
| 506 |
The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals |
| 507 |
the end of the data stream. When you receive it, half-close the TCP |
| 508 |
connection. |
| 509 |
|
| 510 |
Returns: |
| 511 |
Data to write to the connection. |
| 512 |
|
| 513 |
""" |
| 514 |
writes, self.writes = self.writes, [] |
| 515 |
return writes |
| 516 |
|
| 517 |
def close_expected(self) -> bool: |
| 518 |
""" |
| 519 |
Tell if the TCP connection is expected to close soon. |
| 520 |
|
| 521 |
Call this method immediately after any of the ``receive_*()``, |
| 522 |
``send_close()``, or :meth:`fail` methods. |
| 523 |
|
| 524 |
If it returns :obj:`True`, schedule closing the TCP connection after a |
| 525 |
short timeout if the other side hasn't already closed it. |
| 526 |
|
| 527 |
Returns: |
| 528 |
Whether the TCP connection is expected to close soon. |
| 529 |
|
| 530 |
""" |
| 531 |
# During the opening handshake, when our state is CONNECTING, we expect |
| 532 |
# a TCP close if and only if the hansdake fails. When it does, we start |
| 533 |
# the TCP closing handshake by sending EOF with send_eof(). |
| 534 |
|
| 535 |
# Once the opening handshake completes successfully, we expect a TCP |
| 536 |
# close if and only if we sent a close frame, meaning that our state |
| 537 |
# progressed to CLOSING: |
| 538 |
|
| 539 |
# * Normal closure: once we send a close frame, we expect a TCP close: |
| 540 |
# server waits for client to complete the TCP closing handshake; |
| 541 |
# client waits for server to initiate the TCP closing handshake. |
| 542 |
|
| 543 |
# * Abnormal closure: we always send a close frame and the same logic |
| 544 |
# applies, except on EOFError where we don't send a close frame |
| 545 |
# because we already received the TCP close, so we don't expect it. |
| 546 |
|
| 547 |
# If our state is CLOSED, we already received a TCP close so we don't |
| 548 |
# expect it anymore. |
| 549 |
|
| 550 |
# Micro-optimization: put the most common case first |
| 551 |
if self.state is OPEN: |
| 552 |
return False |
| 553 |
if self.state is CLOSING: |
| 554 |
return True |
| 555 |
if self.state is CLOSED: |
| 556 |
return False |
| 557 |
assert self.state is CONNECTING |
| 558 |
return self.eof_sent |
| 559 |
|
| 560 |
# Private methods for receiving data. |
| 561 |
|
| 562 |
def parse(self) -> Generator[None]: |
| 563 |
""" |
| 564 |
Parse incoming data into frames. |
| 565 |
|
| 566 |
:meth:`receive_data` and :meth:`receive_eof` run this generator |
| 567 |
coroutine until it needs more data or reaches EOF. |
| 568 |
|
| 569 |
:meth:`parse` never raises an exception. Instead, it sets the |
| 570 |
:attr:`parser_exc` and yields control. |
| 571 |
|
| 572 |
""" |
| 573 |
try: |
| 574 |
while True: |
| 575 |
if (yield from self.reader.at_eof()): |
| 576 |
if self.debug: |
| 577 |
self.logger.debug("< EOF") |
| 578 |
# If the WebSocket connection is closed cleanly, with a |
| 579 |
# closing handhshake, recv_frame() substitutes parse() |
| 580 |
# with discard(). This branch is reached only when the |
| 581 |
# connection isn't closed cleanly. |
| 582 |
raise EOFError("unexpected end of stream") |
| 583 |
|
| 584 |
max_size = None |
| 585 |
|
| 586 |
if self.max_message_size is not None: |
| 587 |
if self.current_size is None: |
| 588 |
max_size = self.max_message_size |
| 589 |
else: |
| 590 |
max_size = self.max_message_size - self.current_size |
| 591 |
|
| 592 |
if self.max_fragment_size is not None: |
| 593 |
if max_size is None: |
| 594 |
max_size = self.max_fragment_size |
| 595 |
else: |
| 596 |
max_size = min(max_size, self.max_fragment_size) |
| 597 |
|
| 598 |
# During a normal closure, execution ends here on the next |
| 599 |
# iteration of the loop after receiving a close frame. At |
| 600 |
# this point, recv_frame() replaced parse() by discard(). |
| 601 |
frame = yield from Frame.parse( |
| 602 |
self.reader.read_exact, |
| 603 |
mask=self.side is SERVER, |
| 604 |
max_size=max_size, |
| 605 |
extensions=self.extensions, |
| 606 |
) |
| 607 |
|
| 608 |
if self.debug: |
| 609 |
self.logger.debug("< %s", frame) |
| 610 |
|
| 611 |
self.recv_frame(frame) |
| 612 |
|
| 613 |
except ProtocolError as exc: |
| 614 |
self.fail(CloseCode.PROTOCOL_ERROR, str(exc)) |
| 615 |
self.parser_exc = exc |
| 616 |
|
| 617 |
except EOFError as exc: |
| 618 |
self.fail(CloseCode.ABNORMAL_CLOSURE, str(exc)) |
| 619 |
self.parser_exc = exc |
| 620 |
|
| 621 |
except UnicodeDecodeError as exc: |
| 622 |
self.fail(CloseCode.INVALID_DATA, f"{exc.reason} at position {exc.start}") |
| 623 |
self.parser_exc = exc |
| 624 |
|
| 625 |
except PayloadTooBig as exc: |
| 626 |
exc.set_current_size(self.current_size) |
| 627 |
self.fail(CloseCode.MESSAGE_TOO_BIG, str(exc)) |
| 628 |
self.parser_exc = exc |
| 629 |
|
| 630 |
except Exception as exc: |
| 631 |
self.logger.error("parser failed", exc_info=True) |
| 632 |
# Don't include exception details, which may be security-sensitive. |
| 633 |
self.fail(CloseCode.INTERNAL_ERROR) |
| 634 |
self.parser_exc = exc |
| 635 |
|
| 636 |
# During an abnormal closure, execution ends here after catching an |
| 637 |
# exception. At this point, fail() replaced parse() by discard(). |
| 638 |
yield |
| 639 |
raise AssertionError("parse() shouldn't step after error") |
| 640 |
|
| 641 |
def discard(self) -> Generator[None]: |
| 642 |
""" |
| 643 |
Discard incoming data. |
| 644 |
|
| 645 |
This coroutine replaces :meth:`parse`: |
| 646 |
|
| 647 |
- after receiving a close frame, during a normal closure (1.4); |
| 648 |
- after sending a close frame, during an abnormal closure (7.1.7). |
| 649 |
|
| 650 |
""" |
| 651 |
# After the opening handshake completes, the server closes the TCP |
| 652 |
# connection in the same circumstances where discard() replaces parse(). |
| 653 |
# The client closes it when it receives EOF from the server or times |
| 654 |
# out. (The latter case cannot be handled in this Sans-I/O layer.) |
| 655 |
assert (self.side is SERVER or self.state is CONNECTING) == (self.eof_sent) |
| 656 |
while not (yield from self.reader.at_eof()): |
| 657 |
self.reader.discard() |
| 658 |
# A server closes the TCP connection immediately, while a client |
| 659 |
# waits for the server to close the TCP connection. |
| 660 |
if self.side is CLIENT and self.state is not CONNECTING: |
| 661 |
self.send_eof() |
| 662 |
self.state = CLOSED |
| 663 |
if self.side is SERVER: |
| 664 |
self.logger.info("connection closed") |
| 665 |
# If discard() completes normally, execution ends here. |
| 666 |
yield |
| 667 |
# Once the reader reaches EOF, its feed_data/eof() methods raise an |
| 668 |
# error, so our receive_data/eof() methods don't step the generator. |
| 669 |
raise AssertionError("discard() shouldn't step after EOF") |
| 670 |
|
| 671 |
def recv_frame(self, frame: Frame) -> None: |
| 672 |
""" |
| 673 |
Process an incoming frame. |
| 674 |
|
| 675 |
""" |
| 676 |
if frame.opcode is TEXT or frame.opcode is BINARY: |
| 677 |
if self.current_size is not None: |
| 678 |
raise ProtocolError("expected a continuation frame") |
| 679 |
if not frame.fin: |
| 680 |
self.current_size = len(frame.data) |
| 681 |
|
| 682 |
elif frame.opcode is CONT: |
| 683 |
if self.current_size is None: |
| 684 |
raise ProtocolError("unexpected continuation frame") |
| 685 |
if frame.fin: |
| 686 |
self.current_size = None |
| 687 |
else: |
| 688 |
self.current_size += len(frame.data) |
| 689 |
|
| 690 |
elif frame.opcode is PING: |
| 691 |
# 5.5.2. Ping: "Upon receipt of a Ping frame, an endpoint MUST |
| 692 |
# send a Pong frame in response" |
| 693 |
pong_frame = Frame(PONG, frame.data) |
| 694 |
self.send_frame(pong_frame) |
| 695 |
|
| 696 |
elif frame.opcode is PONG: |
| 697 |
# 5.5.3 Pong: "A response to an unsolicited Pong frame is not |
| 698 |
# expected." |
| 699 |
pass |
| 700 |
|
| 701 |
elif frame.opcode is CLOSE: |
| 702 |
# 7.1.5. The WebSocket Connection Close Code |
| 703 |
# 7.1.6. The WebSocket Connection Close Reason |
| 704 |
self.close_rcvd = Close.parse(frame.data) |
| 705 |
if self.state is CLOSING: |
| 706 |
assert self.close_sent is not None |
| 707 |
self.close_rcvd_then_sent = False |
| 708 |
|
| 709 |
if self.current_size is not None: |
| 710 |
raise ProtocolError("incomplete fragmented message") |
| 711 |
|
| 712 |
# 5.5.1 Close: "If an endpoint receives a Close frame and did |
| 713 |
# not previously send a Close frame, the endpoint MUST send a |
| 714 |
# Close frame in response. (When sending a Close frame in |
| 715 |
# response, the endpoint typically echos the status code it |
| 716 |
# received.)" |
| 717 |
|
| 718 |
if self.state is OPEN: |
| 719 |
# Echo the original data instead of re-serializing it with |
| 720 |
# Close.serialize() because that fails when the close frame |
| 721 |
# is empty and Close.parse() synthesizes a 1005 close code. |
| 722 |
# The rest is identical to send_close(). |
| 723 |
self.send_frame(Frame(CLOSE, frame.data)) |
| 724 |
self.close_sent = self.close_rcvd |
| 725 |
self.close_rcvd_then_sent = True |
| 726 |
self.state = CLOSING |
| 727 |
|
| 728 |
# 7.1.2. Start the WebSocket Closing Handshake: "Once an |
| 729 |
# endpoint has both sent and received a Close control frame, |
| 730 |
# that endpoint SHOULD _Close the WebSocket Connection_" |
| 731 |
|
| 732 |
# A server closes the TCP connection immediately, while a client |
| 733 |
# waits for the server to close the TCP connection. |
| 734 |
if self.side is SERVER: |
| 735 |
self.send_eof() |
| 736 |
|
| 737 |
# 1.4. Closing Handshake: "after receiving a control frame |
| 738 |
# indicating the connection should be closed, a peer discards |
| 739 |
# any further data received." |
| 740 |
# RFC 6455 allows reading Ping and Pong frames after a Close frame. |
| 741 |
# However, that doesn't seem useful; websockets doesn't support it. |
| 742 |
self.parser = self.discard() |
| 743 |
next(self.parser) # start coroutine |
| 744 |
|
| 745 |
else: |
| 746 |
# This can't happen because Frame.parse() validates opcodes. |
| 747 |
raise AssertionError(f"unexpected opcode: {frame.opcode:02x}") |
| 748 |
|
| 749 |
self.events.append(frame) |
| 750 |
|
| 751 |
# Private methods for sending events. |
| 752 |
|
| 753 |
def send_frame(self, frame: Frame) -> None: |
| 754 |
if self.debug: |
| 755 |
self.logger.debug("> %s", frame) |
| 756 |
self.writes.append( |
| 757 |
frame.serialize( |
| 758 |
mask=self.side is CLIENT, |
| 759 |
extensions=self.extensions, |
| 760 |
) |
| 761 |
) |
| 762 |
|
| 763 |
def send_eof(self) -> None: |
| 764 |
assert not self.eof_sent |
| 765 |
self.eof_sent = True |
| 766 |
if self.debug: |
| 767 |
self.logger.debug("> EOF") |
| 768 |
self.writes.append(SEND_EOF) |