github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/packetimpact/tests/tcp_synrcvd_reset_test.go (about)

     1  // Copyright 2020 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tcp_syn_reset_test
    16  
    17  import (
    18  	"flag"
    19  	"testing"
    20  	"time"
    21  
    22  	"golang.org/x/sys/unix"
    23  	"github.com/SagerNet/gvisor/pkg/tcpip/header"
    24  	"github.com/SagerNet/gvisor/test/packetimpact/testbench"
    25  )
    26  
    27  func init() {
    28  	testbench.Initialize(flag.CommandLine)
    29  }
    30  
    31  // TestTCPSynRcvdReset tests transition from SYN-RCVD to CLOSED.
    32  func TestTCPSynRcvdReset(t *testing.T) {
    33  	dut := testbench.NewDUT(t)
    34  	listenFD, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)
    35  	defer dut.Close(t, listenFD)
    36  	conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})
    37  	defer conn.Close(t)
    38  
    39  	// Expect dut connection to have transitioned to SYN-RCVD state.
    40  	conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})
    41  	if _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, nil, time.Second); err != nil {
    42  		t.Fatalf("expected SYN-ACK %s", err)
    43  	}
    44  	conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst)})
    45  
    46  	// Expect the connection to have transitioned SYN-RCVD to CLOSED.
    47  	//
    48  	// Retransmit the ACK a few times to give time for the DUT to transition to
    49  	// CLOSED. We cannot use TCP_INFO to lookup the state as this is a passive
    50  	// DUT connection.
    51  	for i := 0; i < 5; i++ {
    52  		conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})
    53  		if _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst)}, nil, time.Second); err != nil {
    54  			t.Logf("retransmit%d ACK as we did not get the expected RST, %s", i, err)
    55  			continue
    56  		}
    57  		return
    58  	}
    59  	t.Fatal("did not receive a TCP RST")
    60  }