Here is a quirk of the recvfrom system call that I haven’t found documented anyw...

@kasperd@westergaard.social

Here is a quirk of the recvfrom system call that I haven’t found documented anywhere.

If you combine the MSG_PEEK and MSG_WAITALL there will be a limit to how many bytes you can reliably inspect in a single call. This should be obvious to anyone who understands how it works. But what happens if you specify a too large number is less obvious.

On Linux the man page for recvfrom does not mention this particular scenario at all.

There are three behaviors I would consider reasonable:

  • If possible the kernel increases the size of the receive buffer to accommodate the request.
  • The system call returns a smaller number of bytes than requested.
  • The system call returns some error.

None of those three is what happens on Linux. Instead what happens is that the system call simply hangs until interrupted by a signal.

Even if the peer closes the TCP connection the receiving side can still be hanging. That’s because if enough bytes have already been produced by the sender to fill up the receive buffer and a bit of the send buffer, then the receiver will wait for those bytes. And the bytes in the send buffer cannot be delivered until bytes have been removed from the socket buffer, which MSG_PEEK won’t do.

The threshold for how many bytes you can peek ahead can vary over a sockets lifetime. At the start of the stream I observed 73180 bytes as the limit, but after having read some bytes it became possible to peek multiple megabytes ahead. The actual limit could depend on many other factors I haven’t identified.