background

TCP Fast Open (TFO for short) is used in the process of optimizing the first frame of live broadcast. Used to reduce connection time. In this article, the test demo is captured to explain the function of TFO.

The principle of interpretation

As the picture above shows:

  1. When the client sends data for the first time, it sends the data in the SYN packet. The server replies with a SYN+ACK with cookie, and the client replies with an ACK. The first connection is set up, and the data has been sent in the SYN packet.
  2. When the client sends data for the second time, it sends both data and cookies in the SYN packet. The server sends a SYN and AN ACK, and the client sends an ACK. The second connection is set up, and the data has been sent in the SYN packet.

Configuring the Test Environment

# echo 3 > /proc/sys/net/ipv4/tcp_fastopen
Copy the code

The test code

Tfo requires both client and server support. The server code needs to set the TCP_FASTOPEN socket option

int qlen=5;
setsockopt(serverSock, SOL_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen));
Copy the code

The flow of client code requires two points:

  1. Connect is no longer needed
  2. Use sendto to send data and the flags need to be set to MSG_FASTOPEN
sendto(clientSock, "Hello\n".6, MSG_FASTOPEN, (struct sockaddr *)&addr, sizeof(addr));
Copy the code

Detailed code, test methods and pCAP file links

Caught analysis

1. Tfo is enabled on both clients and servers

In the first SYN packet, TFO is enabled and cookie is carried. Some sources describe cookid as server-generated, but in this packet capture, it is client-generated.

In the figure, you can see that the TFO option has 10 bytes in total, with Kind occupying 1 byte, Length occupying 1 byte, and cookie occupying 8 bytes. Kind is 34, length is 10. You can also see that the SYN packet carries data.

By the way, I post kind values for TCP’s common extension options here.

As shown in the screenshot of the second SYN packet, you can see that the cookie values are identical.

The wireshark analysis diagram is as follows. There are 12 data packets in total.

2. Tfo is enabled on the client but not on the server

The first SYN packet is identical, with the same cookie, and carries data, but the server does not support TFO, so it is treated as a normal SYNC packet. The server accepts the data only when the third handshake is carried by the client in the ACK. The diagram below:

It is observed that there are 14 packets in total, and the two extra packets are the [PSH,ACK] packets of numbers 3 and 10. In this case, the data is also sent twice, wasting bandwidth.