(host: &str, port: u16)
| 306 | } |
| 307 | |
| 308 | fn websocket_client_script(host: &str, port: u16) -> String { |
| 309 | format!( |
| 310 | r#" |
| 311 | import base64 |
| 312 | import json |
| 313 | import os |
| 314 | import socket |
| 315 | import struct |
| 316 | import time |
| 317 | import urllib.parse |
| 318 | |
| 319 | HOST = {host:?} |
| 320 | PORT = {port} |
| 321 | TOKEN_ENV = {token_env:?} |
| 322 | |
| 323 | def recv_until(sock, marker): |
| 324 | data = b"" |
| 325 | while marker not in data: |
| 326 | chunk = sock.recv(4096) |
| 327 | if not chunk: |
| 328 | break |
| 329 | data += chunk |
| 330 | return data |
| 331 | |
| 332 | def read_exact(sock, size): |
| 333 | data = b"" |
| 334 | while len(data) < size: |
| 335 | chunk = sock.recv(size - len(data)) |
| 336 | if not chunk: |
| 337 | raise EOFError("unexpected end of websocket frame") |
| 338 | data += chunk |
| 339 | return data |
| 340 | |
| 341 | def masked_text_frame(payload): |
| 342 | data = payload.encode("utf-8") |
| 343 | mask = os.urandom(4) |
| 344 | if len(data) < 126: |
| 345 | header = bytes([0x81, 0x80 | len(data)]) |
| 346 | elif len(data) <= 0xFFFF: |
| 347 | header = bytes([0x81, 0x80 | 126]) + struct.pack("!H", len(data)) |
| 348 | else: |
| 349 | header = bytes([0x81, 0x80 | 127]) + struct.pack("!Q", len(data)) |
| 350 | masked = bytes(byte ^ mask[index % 4] for index, byte in enumerate(data)) |
| 351 | return header + mask + masked |
| 352 | |
| 353 | def read_frame(sock): |
| 354 | first, second = read_exact(sock, 2) |
| 355 | length = second & 0x7F |
| 356 | if length == 126: |
| 357 | length = struct.unpack("!H", read_exact(sock, 2))[0] |
| 358 | elif length == 127: |
| 359 | length = struct.unpack("!Q", read_exact(sock, 8))[0] |
| 360 | mask = read_exact(sock, 4) if second & 0x80 else b"" |
| 361 | payload = read_exact(sock, length) |
| 362 | if mask: |
| 363 | payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload)) |
| 364 | return first, payload |
| 365 |
no outgoing calls
no test coverage detected