# tcptape File Format

## Overview

A tcptape file records bidirectional TCP traffic as a sequence of frames. Each frame consists of a 4-byte header followed by optional payload data.

The frames do not relate in any way to TCP/IP packets and only describe socket events.

## File Structure

### Magic Header

Every tcptape file begins with a NOOP frame containing the magic signature:

```
[NOOP Frame]
  Opcode: 0x00 (NOOP)
  Length: 0x000008 (8 bytes)
  Payload: "tcptape\x00"
```

This frame serves as a file format identifier and allows tools to recognize tcptape files.

The signature is not checked by the reader, just ignored like other NOOP frames. You can concatenate multiple tapes together; the header won't interfere.

### Frame Format

All frames follow this structure:

```
[4-byte header]
  Byte 0: Opcode (0x00-0x7F reserved, 0x80-0xFF for future extensions)
  Bytes 1-3: Length (big-endian, 24-bit unsigned integer, max 16,777,215 bytes)

[Variable-length payload] (optional, depends on opcode)
```

## Opcodes

### 0x00 - NOOP (No Operation)

Skip specified number of bytes.

### 0x01 - CLIENT_TO_SERVER

Data sent by the client to the server.

**Payload:** a byte buffer.

### 0x02 - SERVER_TO_CLIENT

Data sent by the server to the client.

**Payload:** a byte buffer.

### 0x03 - DELAY

Time delay between the previous event and the next event.

**Payload:** None (length field encodes the delay).

**Delay Duration:** The 24-bit length field represents milliseconds of elapsed time. Time spans longer than about 3 hours are capped to the largest representable value. Time spans shorter that 1 ms are ignores and won't emit this frame.

**Semantics:** Before sending a chunk to client (server), wait this many milliseconds before replying to client (server) being tested, if `-d` option is specified.

### 0x04 - CLIENT_TO_SERVER_EOF

The client closed its writing half of the connection (half-closed state).

**Payload:** None (length must be 0)

**Semantics:** In server replay mode, verify that a read attempt from client returns 0 (EOF). In client replay mode, shutdown the socket for writing at this point.

### 0x05 - SERVER_TO_CLIENT_EOF

A role-reversed `CLIENT_TO_SERVER_EOF`.

### 0x80-0xFF - Future Extensions

Any opcode with the high bit set (0x80 or above) is reserved for future backward-compatible extensions. Unrecognized frames are skipped like `NOOP`s.

**Processing:** Read and discard `length` bytes of payload, then continue processing the next frame.
