Fix the bounds checks in a peer frame loader

Review the AI's codeEasy10 minCisco style

Your task

An AI-written C++ loader copied a peer's name out of a packet into a 32-byte field, trusting the length byte from the wire. A fuzzer found a heap overflow. The fix decides, before any copy, whether the packet is safe to load.

An assistant wrote parse_peer_frame(packet, name_capacity). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • packet: the packet's bytes, as a list of integers. packet[0] is the name length, then come the name bytes, then 2 port bytes, big-endian.
  • name_capacity: the size of the destination name field in bytes. The name is stored as a C string, so it needs one extra byte for the terminating NUL.
  • Return [name_len, port] when the frame is safe to load, or [] to reject it.

Rules the tests check:

  • An empty packet is rejected.
  • The name plus its NUL terminator must fit the field: reject when name_len is greater than name_capacity - 1.
  • The packet must hold the length byte, the name and both port bytes: reject when it is shorter than 1 + name_len + 2. Extra bytes after the port are fine.
  • Otherwise the port is the first port byte times 256, plus the second.

Examples

parse_peer_frame(packet: list[int], name_capacity: int) -> list[int]
Example 1
Inputparse_peer_frame([3, 97, 98, 99, 1, 187], 32)
Output[3, 443]
Example 2
Inputparse_peer_frame([255, 65, 66], 32)
Output[]
Example 3
Inputparse_peer_frame([0, 1, 187], 32)
Output[0, 443]