पाठ 11 / 32

Frames, Opcodes and Masking

यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।

Decode a WebSocket frame header and explain FIN, opcodes, payload length and client masking.

लेखक: · 15 साल से वेब डेवलपर

Anatomy of a frame

After the handshake, data travels in frames. The first byte holds the FIN bit (is this the last fragment of a message?) and a 4-bit opcode: 0x1 text (UTF-8), 0x2 binary, 0x0 continuation, 0x8 close, 0x9 ping, 0xA pong. The second byte holds the MASK bit and a 7-bit length. Lengths up to 125 fit there directly; 126 means the next 2 bytes hold the length and 127 means the next 8 bytes do. So a small message costs only 2 bytes of header from the server, versus hundreds of bytes of headers for an HTTP request. Frames from client to server must be masked with a random 4-byte key XORed over the payload; server-to-client frames must not be. Masking is not encryption, since the key is sent in the frame. It exists to stop malicious pages from crafting bytes that confuse intermediary caches. A large message may be split into fragments: the first carries the opcode, the rest use continuation frames, and the last sets FIN.

Encoding a text frame by hand

The server frame for "Hi" is 4 bytes: 81 (FIN + text), 02 (unmasked, length 2), then H and i. The masked client frame adds a 4-byte key, and a 300-byte payload needs the 2-byte extended length.

import os

def encode_text_frame(text: str, mask: bool = True) -> bytes:
    payload = text.encode("utf-8")
    header = bytearray([0x80 | 0x1])          # FIN=1, opcode=1 (text)
    n = len(payload)
    mask_bit = 0x80 if mask else 0
    if n <= 125:
        header.append(mask_bit | n)
    elif n <= 0xFFFF:
        header.append(mask_bit | 126)
        header += n.to_bytes(2, "big")
    else:
        header.append(mask_bit | 127)
        header += n.to_bytes(8, "big")
    if not mask:
        return bytes(header) + payload
    key = os.urandom(4)
    masked = bytes(b ^ key[i % 4] for i, b in enumerate(payload))
    return bytes(header) + key + masked

server_frame = encode_text_frame("Hi", mask=False)
print(server_frame.hex(" "))
client_frame = encode_text_frame("Hi")
print(len(client_frame), "bytes, second byte =", hex(client_frame[1]))
print(len(encode_text_frame("x" * 300, mask=False)), "bytes for a 300-byte payload")

Output:

81 02 48 69
8 bytes, second byte = 0x82
304 bytes for a 300-byte payload

A railway parcel label

Each frame is a parcel with a small label: what kind of goods (opcode), how heavy (length), whether more parcels of the same consignment follow (FIN), and for parcels sent by the customer, a seal code (mask key). The label is tiny, so even small parcels are cheap to send.

Messages, not frames

Application code almost never sees frames. Browser and library APIs hand you whole messages, reassembled from fragments. Design your protocol around messages, and remember that TCP still guarantees order within one connection.

त्वरित जाँच: Which statement about masking is correct?

  • Server-to-client frames must be masked
  • Masking encrypts the payload so `ws://` is safe
  • Client-to-server frames must be masked with a 4-byte key
  • Masking is optional and off by default in browsers
Answer

Client-to-server frames must be masked with a 4-byte key — RFC 6455 requires clients to mask every frame they send and servers not to mask theirs. It protects intermediaries, not confidentiality.