gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/tcpip/adapters/gonet/gonet_test.go (about)

     1  // Copyright 2018 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 gonet
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io"
    21  	"net"
    22  	"reflect"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"golang.org/x/net/nettest"
    28  	"gvisor.dev/gvisor/pkg/sync"
    29  	"gvisor.dev/gvisor/pkg/tcpip"
    30  	"gvisor.dev/gvisor/pkg/tcpip/header"
    31  	"gvisor.dev/gvisor/pkg/tcpip/link/loopback"
    32  	"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
    33  	"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
    34  	"gvisor.dev/gvisor/pkg/tcpip/stack"
    35  	"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
    36  	"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
    37  	"gvisor.dev/gvisor/pkg/waiter"
    38  )
    39  
    40  const (
    41  	NICID = 1
    42  )
    43  
    44  func TestTimeouts(t *testing.T) {
    45  	nc := NewTCPConn(nil, nil)
    46  	dlfs := []struct {
    47  		name string
    48  		f    func(time.Time) error
    49  	}{
    50  		{"SetDeadline", nc.SetDeadline},
    51  		{"SetReadDeadline", nc.SetReadDeadline},
    52  		{"SetWriteDeadline", nc.SetWriteDeadline},
    53  	}
    54  
    55  	for _, dlf := range dlfs {
    56  		if err := dlf.f(time.Time{}); err != nil {
    57  			t.Errorf("got %s(time.Time{}) = %v, want = %v", dlf.name, err, nil)
    58  		}
    59  	}
    60  }
    61  
    62  func newLoopbackStack() (*stack.Stack, tcpip.Error) {
    63  	// Create the stack and add a NIC.
    64  	s := stack.New(stack.Options{
    65  		NetworkProtocols:   []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
    66  		TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol},
    67  	})
    68  
    69  	if err := s.CreateNIC(NICID, loopback.New()); err != nil {
    70  		return nil, err
    71  	}
    72  
    73  	// Add default route.
    74  	s.SetRouteTable([]tcpip.Route{
    75  		// IPv4
    76  		{
    77  			Destination: header.IPv4EmptySubnet,
    78  			NIC:         NICID,
    79  		},
    80  
    81  		// IPv6
    82  		{
    83  			Destination: header.IPv6EmptySubnet,
    84  			NIC:         NICID,
    85  		},
    86  	})
    87  
    88  	return s, nil
    89  }
    90  
    91  type testConnection struct {
    92  	wq *waiter.Queue
    93  	e  *waiter.Entry
    94  	ch chan struct{}
    95  	ep tcpip.Endpoint
    96  }
    97  
    98  func connect(s *stack.Stack, addr tcpip.FullAddress) (*testConnection, tcpip.Error) {
    99  	wq := &waiter.Queue{}
   100  	ep, err := s.NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, wq)
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  
   105  	entry, ch := waiter.NewChannelEntry(waiter.WritableEvents)
   106  	wq.EventRegister(&entry)
   107  
   108  	err = ep.Connect(addr)
   109  	if _, ok := err.(*tcpip.ErrConnectStarted); ok {
   110  		<-ch
   111  		err = ep.LastError()
   112  	}
   113  	if err != nil {
   114  		return nil, err
   115  	}
   116  
   117  	wq.EventUnregister(&entry)
   118  	entry, ch = waiter.NewChannelEntry(waiter.ReadableEvents)
   119  	wq.EventRegister(&entry)
   120  
   121  	return &testConnection{wq, &entry, ch, ep}, nil
   122  }
   123  
   124  func (c *testConnection) close() {
   125  	c.wq.EventUnregister(c.e)
   126  	c.ep.Close()
   127  }
   128  
   129  // TestCloseReader tests that Conn.Close() causes Conn.Read() to unblock.
   130  func TestCloseReader(t *testing.T) {
   131  	s, err := newLoopbackStack()
   132  	if err != nil {
   133  		t.Fatalf("newLoopbackStack() = %v", err)
   134  	}
   135  	defer func() {
   136  		s.Close()
   137  		s.Wait()
   138  	}()
   139  
   140  	addr := tcpip.FullAddress{
   141  		NIC:  NICID,
   142  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   143  		Port: 11211,
   144  	}
   145  	protocolAddr := tcpip.ProtocolAddress{
   146  		Protocol:          ipv4.ProtocolNumber,
   147  		AddressWithPrefix: addr.Addr.WithPrefix(),
   148  	}
   149  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   150  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   151  	}
   152  
   153  	l, e := ListenTCP(s, addr, ipv4.ProtocolNumber)
   154  	if e != nil {
   155  		t.Fatalf("NewListener() = %v", e)
   156  	}
   157  	done := make(chan struct{})
   158  	go func() {
   159  		defer close(done)
   160  		c, err := l.Accept()
   161  		if err != nil {
   162  			t.Errorf("l.Accept() = %v", err)
   163  			// Cannot call Fatalf in goroutine. Just return from the goroutine.
   164  			return
   165  		}
   166  
   167  		// Give c.Read() a chance to block before closing the connection.
   168  		time.AfterFunc(time.Millisecond*50, func() {
   169  			c.Close()
   170  		})
   171  
   172  		buf := make([]byte, 256)
   173  		n, err := c.Read(buf)
   174  		if n != 0 || err != io.EOF {
   175  			t.Errorf("c.Read() = (%d, %v), want (0, EOF)", n, err)
   176  		}
   177  	}()
   178  	sender, err := connect(s, addr)
   179  	if err != nil {
   180  		t.Fatalf("connect() = %v", err)
   181  	}
   182  
   183  	select {
   184  	case <-done:
   185  	case <-time.After(5 * time.Second):
   186  		t.Errorf("c.Read() didn't unblock")
   187  	}
   188  	sender.close()
   189  }
   190  
   191  // TestCloseReaderWithForwarder tests that TCPConn.Close wakes TCPConn.Read when
   192  // using tcp.Forwarder.
   193  func TestCloseReaderWithForwarder(t *testing.T) {
   194  	s, err := newLoopbackStack()
   195  	if err != nil {
   196  		t.Fatalf("newLoopbackStack() = %v", err)
   197  	}
   198  	defer func() {
   199  		s.Close()
   200  		s.Wait()
   201  	}()
   202  
   203  	addr := tcpip.FullAddress{
   204  		NIC:  NICID,
   205  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   206  		Port: 11211,
   207  	}
   208  	protocolAddr := tcpip.ProtocolAddress{
   209  		Protocol:          ipv4.ProtocolNumber,
   210  		AddressWithPrefix: addr.Addr.WithPrefix(),
   211  	}
   212  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   213  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   214  	}
   215  
   216  	done := make(chan struct{})
   217  
   218  	fwd := tcp.NewForwarder(s, 30000, 10, func(r *tcp.ForwarderRequest) {
   219  		defer close(done)
   220  
   221  		var wq waiter.Queue
   222  		ep, err := r.CreateEndpoint(&wq)
   223  		if err != nil {
   224  			t.Fatalf("r.CreateEndpoint() = %v", err)
   225  		}
   226  		defer ep.Close()
   227  		r.Complete(false)
   228  
   229  		c := NewTCPConn(&wq, ep)
   230  
   231  		// Give c.Read() a chance to block before closing the connection.
   232  		time.AfterFunc(time.Millisecond*50, func() {
   233  			c.Close()
   234  		})
   235  
   236  		buf := make([]byte, 256)
   237  		n, e := c.Read(buf)
   238  		if n != 0 || e != io.EOF {
   239  			t.Errorf("c.Read() = (%d, %v), want (0, EOF)", n, e)
   240  		}
   241  	})
   242  	s.SetTransportProtocolHandler(tcp.ProtocolNumber, fwd.HandlePacket)
   243  
   244  	sender, err := connect(s, addr)
   245  	if err != nil {
   246  		t.Fatalf("connect() = %v", err)
   247  	}
   248  
   249  	select {
   250  	case <-done:
   251  	case <-time.After(5 * time.Second):
   252  		t.Errorf("c.Read() didn't unblock")
   253  	}
   254  	sender.close()
   255  }
   256  
   257  func TestCloseRead(t *testing.T) {
   258  	s, terr := newLoopbackStack()
   259  	if terr != nil {
   260  		t.Fatalf("newLoopbackStack() = %v", terr)
   261  	}
   262  	defer func() {
   263  		s.Close()
   264  		s.Wait()
   265  	}()
   266  
   267  	addr := tcpip.FullAddress{
   268  		NIC:  NICID,
   269  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   270  		Port: 11211,
   271  	}
   272  	protocolAddr := tcpip.ProtocolAddress{
   273  		Protocol:          ipv4.ProtocolNumber,
   274  		AddressWithPrefix: addr.Addr.WithPrefix(),
   275  	}
   276  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   277  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   278  	}
   279  
   280  	done := make(chan struct{})
   281  	fwd := tcp.NewForwarder(s, 30000, 10, func(r *tcp.ForwarderRequest) {
   282  		var wq waiter.Queue
   283  		_, err := r.CreateEndpoint(&wq)
   284  		if err != nil {
   285  			t.Fatalf("r.CreateEndpoint() = %v", err)
   286  		}
   287  		close(done)
   288  		// Endpoint will be closed in deferred s.Close (above).
   289  	})
   290  
   291  	s.SetTransportProtocolHandler(tcp.ProtocolNumber, fwd.HandlePacket)
   292  
   293  	tc, terr := connect(s, addr)
   294  	if terr != nil {
   295  		t.Fatalf("connect() = %v", terr)
   296  	}
   297  	c := NewTCPConn(tc.wq, tc.ep)
   298  
   299  	if err := c.CloseRead(); err != nil {
   300  		t.Errorf("c.CloseRead() = %v", err)
   301  	}
   302  
   303  	buf := make([]byte, 256)
   304  	if n, err := c.Read(buf); err != io.EOF {
   305  		t.Errorf("c.Read() = (%d, %v), want (0, io.EOF)", n, err)
   306  	}
   307  
   308  	if n, err := c.Write([]byte("abc123")); n != 6 || err != nil {
   309  		t.Errorf("c.Write() = (%d, %v), want (6, nil)", n, err)
   310  	}
   311  
   312  	select {
   313  	case <-done:
   314  	case <-time.After(1 * time.Second):
   315  		t.Fatalf("timed out waiting for r.CreateEndpoint(...) to complete")
   316  	}
   317  }
   318  
   319  func TestCloseWrite(t *testing.T) {
   320  	s, terr := newLoopbackStack()
   321  	if terr != nil {
   322  		t.Fatalf("newLoopbackStack() = %v", terr)
   323  	}
   324  	defer func() {
   325  		s.Close()
   326  		s.Wait()
   327  	}()
   328  
   329  	addr := tcpip.FullAddress{
   330  		NIC:  NICID,
   331  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   332  		Port: 11211,
   333  	}
   334  	protocolAddr := tcpip.ProtocolAddress{
   335  		Protocol:          ipv4.ProtocolNumber,
   336  		AddressWithPrefix: addr.Addr.WithPrefix(),
   337  	}
   338  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   339  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   340  	}
   341  
   342  	fwd := tcp.NewForwarder(s, 30000, 10, func(r *tcp.ForwarderRequest) {
   343  		var wq waiter.Queue
   344  		ep, err := r.CreateEndpoint(&wq)
   345  		if err != nil {
   346  			t.Fatalf("r.CreateEndpoint() = %v", err)
   347  		}
   348  		defer ep.Close()
   349  		r.Complete(false)
   350  
   351  		c := NewTCPConn(&wq, ep)
   352  
   353  		n, e := c.Read(make([]byte, 256))
   354  		if n != 0 || e != io.EOF {
   355  			t.Errorf("c.Read() = (%d, %v), want (0, io.EOF)", n, e)
   356  		}
   357  
   358  		if n, e = c.Write([]byte("abc123")); n != 6 || e != nil {
   359  			t.Errorf("c.Write() = (%d, %v), want (6, nil)", n, e)
   360  		}
   361  	})
   362  
   363  	s.SetTransportProtocolHandler(tcp.ProtocolNumber, fwd.HandlePacket)
   364  
   365  	tc, terr := connect(s, addr)
   366  	if terr != nil {
   367  		t.Fatalf("connect() = %v", terr)
   368  	}
   369  	c := NewTCPConn(tc.wq, tc.ep)
   370  
   371  	if err := c.CloseWrite(); err != nil {
   372  		t.Errorf("c.CloseWrite() = %v", err)
   373  	}
   374  
   375  	buf := make([]byte, 256)
   376  	n, err := c.Read(buf)
   377  	if err != nil || string(buf[:n]) != "abc123" {
   378  		t.Fatalf("c.Read() = (%d, %v), want (6, nil)", n, err)
   379  	}
   380  
   381  	n, err = c.Write([]byte("abc123"))
   382  	got, ok := err.(*net.OpError)
   383  	want := "endpoint is closed for send"
   384  	if n != 0 || !ok || got.Op != "write" || got.Err == nil || !strings.HasSuffix(got.Err.Error(), want) {
   385  		t.Errorf("c.Write() = (%d, %v), want (0, OpError(Op: write, Err: %s))", n, err, want)
   386  	}
   387  }
   388  
   389  // TestCloseStack tests that stack.Close wakes TCPConn.Read when
   390  // using tcp.Forwarder.
   391  func TestCloseStack(t *testing.T) {
   392  	s, err := newLoopbackStack()
   393  	if err != nil {
   394  		t.Fatalf("newLoopbackStack() = %v", err)
   395  	}
   396  
   397  	addr := tcpip.FullAddress{
   398  		NIC:  NICID,
   399  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   400  		Port: 11211,
   401  	}
   402  	protocolAddr := tcpip.ProtocolAddress{
   403  		Protocol:          ipv4.ProtocolNumber,
   404  		AddressWithPrefix: addr.Addr.WithPrefix(),
   405  	}
   406  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   407  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   408  	}
   409  
   410  	done := make(chan struct{})
   411  
   412  	fwd := tcp.NewForwarder(s, 30000, 10, func(r *tcp.ForwarderRequest) {
   413  		defer close(done)
   414  
   415  		var wq waiter.Queue
   416  		ep, err := r.CreateEndpoint(&wq)
   417  		if err != nil {
   418  			t.Fatalf("r.CreateEndpoint() = %v", err)
   419  		}
   420  		r.Complete(false)
   421  
   422  		c := NewTCPConn(&wq, ep)
   423  
   424  		// Give c.Read() a chance to block before closing the stack.
   425  		time.AfterFunc(50*time.Millisecond, func() {
   426  			s.Close()
   427  			s.Wait()
   428  		})
   429  
   430  		buf := make([]byte, 256)
   431  		n, e := c.Read(buf)
   432  		// Depending on the ordering of Close and Read, we should get
   433  		// one of two errors.
   434  		if n != 0 || (!strings.Contains(e.Error(), "operation aborted") && !strings.Contains(e.Error(), "connection reset by peer")) {
   435  			t.Errorf("c.Read() = (%d, %v), want (0, operation aborted) or (0, connection reset by peer)", n, e)
   436  		}
   437  	})
   438  	s.SetTransportProtocolHandler(tcp.ProtocolNumber, fwd.HandlePacket)
   439  
   440  	sender, err := connect(s, addr)
   441  	if err != nil {
   442  		t.Fatalf("connect() = %v", err)
   443  	}
   444  
   445  	select {
   446  	case <-done:
   447  	case <-time.After(5 * time.Second):
   448  		t.Errorf("c.Read() didn't unblock")
   449  	}
   450  	sender.close()
   451  }
   452  
   453  func TestUDPForwarder(t *testing.T) {
   454  	s, terr := newLoopbackStack()
   455  	if terr != nil {
   456  		t.Fatalf("newLoopbackStack() = %v", terr)
   457  	}
   458  	defer func() {
   459  		s.Close()
   460  		s.Wait()
   461  	}()
   462  
   463  	ip1 := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4())
   464  	addr1 := tcpip.FullAddress{NIC: NICID, Addr: ip1, Port: 11211}
   465  	protocolAddr1 := tcpip.ProtocolAddress{
   466  		Protocol:          ipv4.ProtocolNumber,
   467  		AddressWithPrefix: ip1.WithPrefix(),
   468  	}
   469  	if err := s.AddProtocolAddress(NICID, protocolAddr1, stack.AddressProperties{}); err != nil {
   470  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr1, err)
   471  	}
   472  	ip2 := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 2).To4())
   473  	addr2 := tcpip.FullAddress{NIC: NICID, Addr: ip2, Port: 11311}
   474  	protocolAddr2 := tcpip.ProtocolAddress{
   475  		Protocol:          ipv4.ProtocolNumber,
   476  		AddressWithPrefix: ip2.WithPrefix(),
   477  	}
   478  	if err := s.AddProtocolAddress(NICID, protocolAddr2, stack.AddressProperties{}); err != nil {
   479  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr2, err)
   480  	}
   481  
   482  	done := make(chan struct{})
   483  	fwd := udp.NewForwarder(s, func(r *udp.ForwarderRequest) {
   484  		defer close(done)
   485  
   486  		var wq waiter.Queue
   487  		ep, err := r.CreateEndpoint(&wq)
   488  		if err != nil {
   489  			t.Fatalf("r.CreateEndpoint() = %v", err)
   490  		}
   491  		defer ep.Close()
   492  
   493  		c := NewUDPConn(&wq, ep)
   494  
   495  		buf := make([]byte, 256)
   496  		n, e := c.Read(buf)
   497  		if e != nil {
   498  			t.Errorf("c.Read() = %v", e)
   499  		}
   500  
   501  		if _, e := c.Write(buf[:n]); e != nil {
   502  			t.Errorf("c.Write() = %v", e)
   503  		}
   504  	})
   505  	s.SetTransportProtocolHandler(udp.ProtocolNumber, fwd.HandlePacket)
   506  
   507  	c2, err := DialUDP(s, &addr2, nil, ipv4.ProtocolNumber)
   508  	if err != nil {
   509  		t.Fatal("DialUDP(bind port 5):", err)
   510  	}
   511  
   512  	sent := "abc123"
   513  	sendAddr := fullToUDPAddr(addr1)
   514  	if n, err := c2.WriteTo([]byte(sent), sendAddr); err != nil || n != len(sent) {
   515  		t.Errorf("c1.WriteTo(%q, %v) = %d, %v, want = %d, %v", sent, sendAddr, n, err, len(sent), nil)
   516  	}
   517  
   518  	buf := make([]byte, 256)
   519  	n, recvAddr, err := c2.ReadFrom(buf)
   520  	if err != nil || recvAddr.String() != sendAddr.String() {
   521  		t.Errorf("c1.ReadFrom() = %d, %v, %v, want = %d, %v, %v", n, recvAddr, err, len(sent), sendAddr, nil)
   522  	}
   523  }
   524  
   525  // TestDeadlineChange tests that changing the deadline affects currently blocked reads.
   526  func TestDeadlineChange(t *testing.T) {
   527  	s, err := newLoopbackStack()
   528  	if err != nil {
   529  		t.Fatalf("newLoopbackStack() = %v", err)
   530  	}
   531  	defer func() {
   532  		s.Close()
   533  		s.Wait()
   534  	}()
   535  
   536  	addr := tcpip.FullAddress{
   537  		NIC:  NICID,
   538  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   539  		Port: 11211,
   540  	}
   541  
   542  	protocolAddr := tcpip.ProtocolAddress{
   543  		Protocol:          ipv4.ProtocolNumber,
   544  		AddressWithPrefix: addr.Addr.WithPrefix(),
   545  	}
   546  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   547  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   548  	}
   549  
   550  	l, e := ListenTCP(s, addr, ipv4.ProtocolNumber)
   551  	if e != nil {
   552  		t.Fatalf("NewListener() = %v", e)
   553  	}
   554  	done := make(chan struct{})
   555  	go func() {
   556  		defer close(done)
   557  		c, err := l.Accept()
   558  		if err != nil {
   559  			t.Errorf("l.Accept() = %v", err)
   560  			// Cannot call Fatalf in goroutine. Just return from the goroutine.
   561  			return
   562  		}
   563  
   564  		c.SetDeadline(time.Now().Add(time.Minute))
   565  		// Give c.Read() a chance to block before closing the connection.
   566  		time.AfterFunc(time.Millisecond*50, func() {
   567  			c.SetDeadline(time.Now().Add(time.Millisecond * 10))
   568  		})
   569  
   570  		buf := make([]byte, 256)
   571  		n, err := c.Read(buf)
   572  		got, ok := err.(*net.OpError)
   573  		want := "i/o timeout"
   574  		if n != 0 || !ok || got.Err == nil || got.Err.Error() != want {
   575  			t.Errorf("c.Read() = (%d, %v), want (0, OpError(%s))", n, err, want)
   576  		}
   577  	}()
   578  	sender, err := connect(s, addr)
   579  	if err != nil {
   580  		t.Fatalf("connect() = %v", err)
   581  	}
   582  
   583  	select {
   584  	case <-done:
   585  	case <-time.After(time.Millisecond * 500):
   586  		t.Errorf("c.Read() didn't unblock")
   587  	}
   588  	sender.close()
   589  }
   590  
   591  func TestPacketConnTransfer(t *testing.T) {
   592  	s, e := newLoopbackStack()
   593  	if e != nil {
   594  		t.Fatalf("newLoopbackStack() = %v", e)
   595  	}
   596  	defer func() {
   597  		s.Close()
   598  		s.Wait()
   599  	}()
   600  
   601  	ip1 := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4())
   602  	addr1 := tcpip.FullAddress{NIC: NICID, Addr: ip1, Port: 11211}
   603  	protocolAddr1 := tcpip.ProtocolAddress{
   604  		Protocol:          ipv4.ProtocolNumber,
   605  		AddressWithPrefix: ip1.WithPrefix(),
   606  	}
   607  	if err := s.AddProtocolAddress(NICID, protocolAddr1, stack.AddressProperties{}); err != nil {
   608  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr1, err)
   609  	}
   610  	ip2 := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 2).To4())
   611  	addr2 := tcpip.FullAddress{NIC: NICID, Addr: ip2, Port: 11311}
   612  	protocolAddr2 := tcpip.ProtocolAddress{
   613  		Protocol:          ipv4.ProtocolNumber,
   614  		AddressWithPrefix: ip2.WithPrefix(),
   615  	}
   616  	if err := s.AddProtocolAddress(NICID, protocolAddr2, stack.AddressProperties{}); err != nil {
   617  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr2, err)
   618  	}
   619  
   620  	c1, err := DialUDP(s, &addr1, nil, ipv4.ProtocolNumber)
   621  	if err != nil {
   622  		t.Fatal("DialUDP(bind port 4):", err)
   623  	}
   624  	c2, err := DialUDP(s, &addr2, nil, ipv4.ProtocolNumber)
   625  	if err != nil {
   626  		t.Fatal("DialUDP(bind port 5):", err)
   627  	}
   628  
   629  	c1.SetDeadline(time.Now().Add(time.Second))
   630  	c2.SetDeadline(time.Now().Add(time.Second))
   631  
   632  	sent := "abc123"
   633  	sendAddr := fullToUDPAddr(addr2)
   634  	if n, err := c1.WriteTo([]byte(sent), sendAddr); err != nil || n != len(sent) {
   635  		t.Errorf("got c1.WriteTo(%q, %v) = %d, %v, want = %d, %v", sent, sendAddr, n, err, len(sent), nil)
   636  	}
   637  	recv := make([]byte, len(sent))
   638  	n, recvAddr, err := c2.ReadFrom(recv)
   639  	if err != nil || n != len(recv) {
   640  		t.Errorf("got c2.ReadFrom() = %d, %v, want = %d, %v", n, err, len(recv), nil)
   641  	}
   642  
   643  	if recv := string(recv); recv != sent {
   644  		t.Errorf("got recv = %q, want = %q", recv, sent)
   645  	}
   646  
   647  	if want := fullToUDPAddr(addr1); !reflect.DeepEqual(recvAddr, want) {
   648  		t.Errorf("got recvAddr = %v, want = %v", recvAddr, want)
   649  	}
   650  
   651  	if err := c1.Close(); err != nil {
   652  		t.Error("c1.Close():", err)
   653  	}
   654  	if err := c2.Close(); err != nil {
   655  		t.Error("c2.Close():", err)
   656  	}
   657  }
   658  
   659  func TestConnectedPacketConnTransfer(t *testing.T) {
   660  	s, e := newLoopbackStack()
   661  	if e != nil {
   662  		t.Fatalf("newLoopbackStack() = %v", e)
   663  	}
   664  	defer func() {
   665  		s.Close()
   666  		s.Wait()
   667  	}()
   668  
   669  	ip := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4())
   670  	addr := tcpip.FullAddress{NIC: NICID, Addr: ip, Port: 11211}
   671  	protocolAddr := tcpip.ProtocolAddress{
   672  		Protocol:          ipv4.ProtocolNumber,
   673  		AddressWithPrefix: ip.WithPrefix(),
   674  	}
   675  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   676  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   677  	}
   678  
   679  	c1, err := DialUDP(s, &addr, nil, ipv4.ProtocolNumber)
   680  	if err != nil {
   681  		t.Fatal("DialUDP(bind port 4):", err)
   682  	}
   683  	c2, err := DialUDP(s, nil, &addr, ipv4.ProtocolNumber)
   684  	if err != nil {
   685  		t.Fatal("DialUDP(bind port 5):", err)
   686  	}
   687  
   688  	c1.SetDeadline(time.Now().Add(time.Second))
   689  	c2.SetDeadline(time.Now().Add(time.Second))
   690  
   691  	sent := "abc123"
   692  	if n, err := c2.Write([]byte(sent)); err != nil || n != len(sent) {
   693  		t.Errorf("got c2.Write(%q) = %d, %v, want = %d, %v", sent, n, err, len(sent), nil)
   694  	}
   695  	recv := make([]byte, len(sent))
   696  	n, err := c1.Read(recv)
   697  	if err != nil || n != len(recv) {
   698  		t.Errorf("got c1.Read() = %d, %v, want = %d, %v", n, err, len(recv), nil)
   699  	}
   700  
   701  	if recv := string(recv); recv != sent {
   702  		t.Errorf("got recv = %q, want = %q", recv, sent)
   703  	}
   704  
   705  	if err := c1.Close(); err != nil {
   706  		t.Error("c1.Close():", err)
   707  	}
   708  	if err := c2.Close(); err != nil {
   709  		t.Error("c2.Close():", err)
   710  	}
   711  }
   712  
   713  func makePipe() (c1, c2 net.Conn, stop func(), err error) {
   714  	s, e := newLoopbackStack()
   715  	if e != nil {
   716  		return nil, nil, nil, fmt.Errorf("newLoopbackStack() = %v", e)
   717  	}
   718  
   719  	ip := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4())
   720  	addr := tcpip.FullAddress{NIC: NICID, Addr: ip, Port: 11211}
   721  	protocolAddr := tcpip.ProtocolAddress{
   722  		Protocol:          ipv4.ProtocolNumber,
   723  		AddressWithPrefix: ip.WithPrefix(),
   724  	}
   725  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   726  		return nil, nil, nil, fmt.Errorf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   727  	}
   728  
   729  	l, err := ListenTCP(s, addr, ipv4.ProtocolNumber)
   730  	if err != nil {
   731  		return nil, nil, nil, fmt.Errorf("NewListener: %w", err)
   732  	}
   733  
   734  	c1, err = DialTCP(s, addr, ipv4.ProtocolNumber)
   735  	if err != nil {
   736  		l.Close()
   737  		return nil, nil, nil, fmt.Errorf("DialTCP: %w", err)
   738  	}
   739  
   740  	c2, err = l.Accept()
   741  	if err != nil {
   742  		l.Close()
   743  		c1.Close()
   744  		return nil, nil, nil, fmt.Errorf("l.Accept: %w", err)
   745  	}
   746  
   747  	stop = func() {
   748  		c1.Close()
   749  		c2.Close()
   750  		s.Close()
   751  		s.Wait()
   752  	}
   753  
   754  	if err := l.Close(); err != nil {
   755  		stop()
   756  		return nil, nil, nil, fmt.Errorf("l.Close(): %w", err)
   757  	}
   758  
   759  	return c1, c2, stop, nil
   760  }
   761  
   762  func TestTCPConnTransfer(t *testing.T) {
   763  	c1, c2, _, err := makePipe()
   764  	if err != nil {
   765  		t.Fatal(err)
   766  	}
   767  	defer func() {
   768  		if err := c1.Close(); err != nil {
   769  			t.Error("c1.Close():", err)
   770  		}
   771  		if err := c2.Close(); err != nil {
   772  			t.Error("c2.Close():", err)
   773  		}
   774  	}()
   775  
   776  	c1.SetDeadline(time.Now().Add(time.Second))
   777  	c2.SetDeadline(time.Now().Add(time.Second))
   778  
   779  	const sent = "abc123"
   780  
   781  	tests := []struct {
   782  		name string
   783  		c1   net.Conn
   784  		c2   net.Conn
   785  	}{
   786  		{"connected to accepted", c1, c2},
   787  		{"accepted to connected", c2, c1},
   788  	}
   789  
   790  	for _, test := range tests {
   791  		if n, err := test.c1.Write([]byte(sent)); err != nil || n != len(sent) {
   792  			t.Errorf("%s: got test.c1.Write(%q) = %d, %v, want = %d, %v", test.name, sent, n, err, len(sent), nil)
   793  			continue
   794  		}
   795  
   796  		recv := make([]byte, len(sent))
   797  		n, err := test.c2.Read(recv)
   798  		if err != nil || n != len(recv) {
   799  			t.Errorf("%s: got test.c2.Read() = %d, %v, want = %d, %v", test.name, n, err, len(recv), nil)
   800  			continue
   801  		}
   802  
   803  		if recv := string(recv); recv != sent {
   804  			t.Errorf("%s: got recv = %q, want = %q", test.name, recv, sent)
   805  		}
   806  	}
   807  }
   808  
   809  func TestTCPDialError(t *testing.T) {
   810  	s, e := newLoopbackStack()
   811  	if e != nil {
   812  		t.Fatalf("newLoopbackStack() = %v", e)
   813  	}
   814  	defer func() {
   815  		s.Close()
   816  		s.Wait()
   817  	}()
   818  
   819  	ip := tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4())
   820  	addr := tcpip.FullAddress{NIC: NICID, Addr: ip, Port: 11211}
   821  
   822  	switch _, err := DialTCP(s, addr, ipv4.ProtocolNumber); err := err.(type) {
   823  	case *net.OpError:
   824  		if err.Err.Error() != (&tcpip.ErrHostUnreachable{}).String() {
   825  			t.Errorf("got DialTCP() = %s, want = %s", err, &tcpip.ErrHostUnreachable{})
   826  		}
   827  	default:
   828  		t.Errorf("got DialTCP(...) = %v, want %s", err, &tcpip.ErrHostUnreachable{})
   829  	}
   830  }
   831  
   832  func TestDialContextTCPCanceled(t *testing.T) {
   833  	s, err := newLoopbackStack()
   834  	if err != nil {
   835  		t.Fatalf("newLoopbackStack() = %v", err)
   836  	}
   837  	defer func() {
   838  		s.Close()
   839  		s.Wait()
   840  	}()
   841  
   842  	addr := tcpip.FullAddress{
   843  		NIC:  NICID,
   844  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   845  		Port: 11211,
   846  	}
   847  	protocolAddr := tcpip.ProtocolAddress{
   848  		Protocol:          ipv4.ProtocolNumber,
   849  		AddressWithPrefix: addr.Addr.WithPrefix(),
   850  	}
   851  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   852  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   853  	}
   854  
   855  	ctx := context.Background()
   856  	ctx, cancel := context.WithCancel(ctx)
   857  	cancel()
   858  
   859  	if _, err := DialContextTCP(ctx, s, addr, ipv4.ProtocolNumber); err != context.Canceled {
   860  		t.Errorf("got DialContextTCP(...) = %v, want = %v", err, context.Canceled)
   861  	}
   862  }
   863  
   864  func TestDialContextTCPTimeout(t *testing.T) {
   865  	s, err := newLoopbackStack()
   866  	if err != nil {
   867  		t.Fatalf("newLoopbackStack() = %v", err)
   868  	}
   869  	defer func() {
   870  		s.Close()
   871  		s.Wait()
   872  	}()
   873  
   874  	addr := tcpip.FullAddress{
   875  		NIC:  NICID,
   876  		Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   877  		Port: 11211,
   878  	}
   879  	protocolAddr := tcpip.ProtocolAddress{
   880  		Protocol:          ipv4.ProtocolNumber,
   881  		AddressWithPrefix: addr.Addr.WithPrefix(),
   882  	}
   883  	if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   884  		t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   885  	}
   886  
   887  	fwd := tcp.NewForwarder(s, 30000, 10, func(r *tcp.ForwarderRequest) {
   888  		time.Sleep(time.Second)
   889  		r.Complete(true)
   890  	})
   891  	s.SetTransportProtocolHandler(tcp.ProtocolNumber, fwd.HandlePacket)
   892  
   893  	ctx := context.Background()
   894  	ctx, cancel := context.WithDeadline(ctx, time.Now().Add(100*time.Millisecond))
   895  	defer cancel()
   896  
   897  	if _, err := DialContextTCP(ctx, s, addr, ipv4.ProtocolNumber); err != context.DeadlineExceeded {
   898  		t.Errorf("got DialContextTCP(...) = %v, want = %v", err, context.DeadlineExceeded)
   899  	}
   900  }
   901  
   902  // TestInterruptListender tests that (*TCPListener).Accept can be interrupted.
   903  func TestInterruptListender(t *testing.T) {
   904  	for _, test := range []struct {
   905  		name string
   906  		stop func(l *TCPListener) error
   907  	}{
   908  		{
   909  			"Close",
   910  			(*TCPListener).Close,
   911  		},
   912  		{
   913  			"Shutdown",
   914  			func(l *TCPListener) error {
   915  				l.Shutdown()
   916  				return nil
   917  			},
   918  		},
   919  		{
   920  			"Double Shutdown",
   921  			func(l *TCPListener) error {
   922  				l.Shutdown()
   923  				l.Shutdown()
   924  				return nil
   925  			},
   926  		},
   927  	} {
   928  		t.Run(test.name, func(t *testing.T) {
   929  			s, err := newLoopbackStack()
   930  			if err != nil {
   931  				t.Fatalf("newLoopbackStack() = %v", err)
   932  			}
   933  			defer func() {
   934  				s.Close()
   935  				s.Wait()
   936  			}()
   937  
   938  			addr := tcpip.FullAddress{
   939  				NIC:  NICID,
   940  				Addr: tcpip.AddrFromSlice(net.IPv4(169, 254, 10, 1).To4()),
   941  				Port: 11211,
   942  			}
   943  			protocolAddr := tcpip.ProtocolAddress{
   944  				Protocol:          ipv4.ProtocolNumber,
   945  				AddressWithPrefix: addr.Addr.WithPrefix(),
   946  			}
   947  			if err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {
   948  				t.Fatalf("AddProtocolAddress(%d, %+v, {}): %s", NICID, protocolAddr, err)
   949  			}
   950  
   951  			l, e := ListenTCP(s, addr, ipv4.ProtocolNumber)
   952  			if e != nil {
   953  				t.Fatalf("NewListener() = %v", e)
   954  			}
   955  			defer l.Close()
   956  			done := make(chan struct{})
   957  			go func() {
   958  				defer close(done)
   959  				c, err := l.Accept()
   960  				if err != nil {
   961  					// Accept is expected to return an error.
   962  					t.Log("Accept #1:", err)
   963  					return
   964  				}
   965  				t.Errorf("Accept #1 returned a connection: %v -> %v", c.LocalAddr(), c.RemoteAddr())
   966  				c.Close()
   967  			}()
   968  
   969  			// Give l.Accept a chance to block before stopping it.
   970  			time.Sleep(time.Millisecond * 50)
   971  
   972  			if err := test.stop(l); err != nil {
   973  				t.Error("stop:", err)
   974  			}
   975  
   976  			select {
   977  			case <-done:
   978  			case <-time.After(5 * time.Second):
   979  				t.Errorf("c.Accept didn't unblock")
   980  			}
   981  
   982  			done = make(chan struct{})
   983  			go func() {
   984  				defer close(done)
   985  				c, err := l.Accept()
   986  				if err != nil {
   987  					// Accept is expected to return an error.
   988  					t.Log("Accept #2:", err)
   989  					return
   990  				}
   991  				t.Errorf("Accept #2 returned a connection: %v -> %v", c.LocalAddr(), c.RemoteAddr())
   992  				c.Close()
   993  			}()
   994  
   995  			select {
   996  			case <-done:
   997  			case <-time.After(5 * time.Second):
   998  				t.Errorf("c.Accept didn't unblock a second time")
   999  			}
  1000  		})
  1001  	}
  1002  }
  1003  
  1004  func TestNetTest(t *testing.T) {
  1005  	nettest.TestConn(t, makePipe)
  1006  }
  1007  
  1008  // NOTE(gvisor.dev/issue/9885): Regression test.
  1009  func TestDeadlineTimerAfterZeroValue(t *testing.T) {
  1010  	timer := &deadlineTimer{}
  1011  	timer.init()
  1012  
  1013  	wg := sync.WaitGroup{}
  1014  	ch := timer.readCancel()
  1015  	wg.Add(1)
  1016  	go func() {
  1017  		defer wg.Done()
  1018  		select {
  1019  		case <-ch:
  1020  		case <-time.After(1 * time.Second):
  1021  			t.Fail()
  1022  		}
  1023  	}()
  1024  	timer.SetReadDeadline(time.Now().Add(10 * time.Second))
  1025  	timer.SetReadDeadline(time.Time{})
  1026  	timer.SetReadDeadline(time.Unix(1, 0))
  1027  	wg.Wait()
  1028  }