github.com/vpnishe/netstack@v1.10.6/tcpip/stack/transport_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 stack_test
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/vpnishe/netstack/tcpip"
    21  	"github.com/vpnishe/netstack/tcpip/buffer"
    22  	"github.com/vpnishe/netstack/tcpip/iptables"
    23  	"github.com/vpnishe/netstack/tcpip/link/channel"
    24  	"github.com/vpnishe/netstack/tcpip/link/loopback"
    25  	"github.com/vpnishe/netstack/tcpip/stack"
    26  	"github.com/vpnishe/netstack/waiter"
    27  )
    28  
    29  const (
    30  	fakeTransNumber    tcpip.TransportProtocolNumber = 1
    31  	fakeTransHeaderLen                               = 3
    32  )
    33  
    34  // fakeTransportEndpoint is a transport-layer protocol endpoint. It counts
    35  // received packets; the counts of all endpoints are aggregated in the protocol
    36  // descriptor.
    37  //
    38  // Headers of this protocol are fakeTransHeaderLen bytes, but we currently don't
    39  // use it.
    40  type fakeTransportEndpoint struct {
    41  	stack.TransportEndpointInfo
    42  	stack    *stack.Stack
    43  	proto    *fakeTransportProtocol
    44  	peerAddr tcpip.Address
    45  	route    stack.Route
    46  	uniqueID uint64
    47  
    48  	// acceptQueue is non-nil iff bound.
    49  	acceptQueue []fakeTransportEndpoint
    50  }
    51  
    52  func (f *fakeTransportEndpoint) Info() tcpip.EndpointInfo {
    53  	return &f.TransportEndpointInfo
    54  }
    55  
    56  func (f *fakeTransportEndpoint) Stats() tcpip.EndpointStats {
    57  	return nil
    58  }
    59  
    60  func newFakeTransportEndpoint(s *stack.Stack, proto *fakeTransportProtocol, netProto tcpip.NetworkProtocolNumber, uniqueID uint64) tcpip.Endpoint {
    61  	return &fakeTransportEndpoint{stack: s, TransportEndpointInfo: stack.TransportEndpointInfo{NetProto: netProto}, proto: proto, uniqueID: uniqueID}
    62  }
    63  
    64  func (f *fakeTransportEndpoint) Close() {
    65  	f.route.Release()
    66  }
    67  
    68  func (*fakeTransportEndpoint) Readiness(mask waiter.EventMask) waiter.EventMask {
    69  	return mask
    70  }
    71  
    72  func (*fakeTransportEndpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages, *tcpip.Error) {
    73  	return buffer.View{}, tcpip.ControlMessages{}, nil
    74  }
    75  
    76  func (f *fakeTransportEndpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-chan struct{}, *tcpip.Error) {
    77  	if len(f.route.RemoteAddress) == 0 {
    78  		return 0, nil, tcpip.ErrNoRoute
    79  	}
    80  
    81  	hdr := buffer.NewPrependable(int(f.route.MaxHeaderLength()))
    82  	v, err := p.FullPayload()
    83  	if err != nil {
    84  		return 0, nil, err
    85  	}
    86  	if err := f.route.WritePacket(nil /* gso */, stack.NetworkHeaderParams{Protocol: fakeTransNumber, TTL: 123, TOS: stack.DefaultTOS}, tcpip.PacketBuffer{
    87  		Header: hdr,
    88  		Data:   buffer.View(v).ToVectorisedView(),
    89  	}); err != nil {
    90  		return 0, nil, err
    91  	}
    92  
    93  	return int64(len(v)), nil, nil
    94  }
    95  
    96  func (f *fakeTransportEndpoint) Peek([][]byte) (int64, tcpip.ControlMessages, *tcpip.Error) {
    97  	return 0, tcpip.ControlMessages{}, nil
    98  }
    99  
   100  // SetSockOpt sets a socket option. Currently not supported.
   101  func (*fakeTransportEndpoint) SetSockOpt(interface{}) *tcpip.Error {
   102  	return tcpip.ErrInvalidEndpointState
   103  }
   104  
   105  // SetSockOptInt sets a socket option. Currently not supported.
   106  func (*fakeTransportEndpoint) SetSockOptInt(tcpip.SockOpt, int) *tcpip.Error {
   107  	return tcpip.ErrInvalidEndpointState
   108  }
   109  
   110  // GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.
   111  func (*fakeTransportEndpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {
   112  	return -1, tcpip.ErrUnknownProtocolOption
   113  }
   114  
   115  // GetSockOpt implements tcpip.Endpoint.GetSockOpt.
   116  func (*fakeTransportEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {
   117  	switch opt.(type) {
   118  	case tcpip.ErrorOption:
   119  		return nil
   120  	}
   121  	return tcpip.ErrInvalidEndpointState
   122  }
   123  
   124  // Disconnect implements tcpip.Endpoint.Disconnect.
   125  func (*fakeTransportEndpoint) Disconnect() *tcpip.Error {
   126  	return tcpip.ErrNotSupported
   127  }
   128  
   129  func (f *fakeTransportEndpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {
   130  	f.peerAddr = addr.Addr
   131  
   132  	// Find the route.
   133  	r, err := f.stack.FindRoute(addr.NIC, "", addr.Addr, fakeNetNumber, false /* multicastLoop */)
   134  	if err != nil {
   135  		return tcpip.ErrNoRoute
   136  	}
   137  	defer r.Release()
   138  
   139  	// Try to register so that we can start receiving packets.
   140  	f.ID.RemoteAddress = addr.Addr
   141  	err = f.stack.RegisterTransportEndpoint(0, []tcpip.NetworkProtocolNumber{fakeNetNumber}, fakeTransNumber, f.ID, f, false /* reuse */, 0 /* bindToDevice */)
   142  	if err != nil {
   143  		return err
   144  	}
   145  
   146  	f.route = r.Clone()
   147  
   148  	return nil
   149  }
   150  
   151  func (f *fakeTransportEndpoint) UniqueID() uint64 {
   152  	return f.uniqueID
   153  }
   154  
   155  func (f *fakeTransportEndpoint) ConnectEndpoint(e tcpip.Endpoint) *tcpip.Error {
   156  	return nil
   157  }
   158  
   159  func (*fakeTransportEndpoint) Shutdown(tcpip.ShutdownFlags) *tcpip.Error {
   160  	return nil
   161  }
   162  
   163  func (*fakeTransportEndpoint) Reset() {
   164  }
   165  
   166  func (*fakeTransportEndpoint) Listen(int) *tcpip.Error {
   167  	return nil
   168  }
   169  
   170  func (f *fakeTransportEndpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {
   171  	if len(f.acceptQueue) == 0 {
   172  		return nil, nil, nil
   173  	}
   174  	a := f.acceptQueue[0]
   175  	f.acceptQueue = f.acceptQueue[1:]
   176  	return &a, nil, nil
   177  }
   178  
   179  func (f *fakeTransportEndpoint) Bind(a tcpip.FullAddress) *tcpip.Error {
   180  	if err := f.stack.RegisterTransportEndpoint(
   181  		a.NIC,
   182  		[]tcpip.NetworkProtocolNumber{fakeNetNumber},
   183  		fakeTransNumber,
   184  		stack.TransportEndpointID{LocalAddress: a.Addr},
   185  		f,
   186  		false, /* reuse */
   187  		0,     /* bindtoDevice */
   188  	); err != nil {
   189  		return err
   190  	}
   191  	f.acceptQueue = []fakeTransportEndpoint{}
   192  	return nil
   193  }
   194  
   195  func (*fakeTransportEndpoint) GetLocalAddress() (tcpip.FullAddress, *tcpip.Error) {
   196  	return tcpip.FullAddress{}, nil
   197  }
   198  
   199  func (*fakeTransportEndpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Error) {
   200  	return tcpip.FullAddress{}, nil
   201  }
   202  
   203  func (f *fakeTransportEndpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, _ tcpip.PacketBuffer) {
   204  	// Increment the number of received packets.
   205  	f.proto.packetCount++
   206  	if f.acceptQueue != nil {
   207  		f.acceptQueue = append(f.acceptQueue, fakeTransportEndpoint{
   208  			stack: f.stack,
   209  			TransportEndpointInfo: stack.TransportEndpointInfo{
   210  				ID:       f.ID,
   211  				NetProto: f.NetProto,
   212  			},
   213  			proto:    f.proto,
   214  			peerAddr: r.RemoteAddress,
   215  			route:    r.Clone(),
   216  		})
   217  	}
   218  }
   219  
   220  func (f *fakeTransportEndpoint) HandleControlPacket(stack.TransportEndpointID, stack.ControlType, uint32, tcpip.PacketBuffer) {
   221  	// Increment the number of received control packets.
   222  	f.proto.controlCount++
   223  }
   224  
   225  func (f *fakeTransportEndpoint) State() uint32 {
   226  	return 0
   227  }
   228  
   229  func (f *fakeTransportEndpoint) ModerateRecvBuf(copied int) {}
   230  
   231  func (f *fakeTransportEndpoint) IPTables() (iptables.IPTables, error) {
   232  	return iptables.IPTables{}, nil
   233  }
   234  
   235  func (f *fakeTransportEndpoint) Resume(*stack.Stack) {}
   236  
   237  func (f *fakeTransportEndpoint) Wait() {}
   238  
   239  type fakeTransportGoodOption bool
   240  
   241  type fakeTransportBadOption bool
   242  
   243  type fakeTransportInvalidValueOption int
   244  
   245  type fakeTransportProtocolOptions struct {
   246  	good bool
   247  }
   248  
   249  // fakeTransportProtocol is a transport-layer protocol descriptor. It
   250  // aggregates the number of packets received via endpoints of this protocol.
   251  type fakeTransportProtocol struct {
   252  	packetCount  int
   253  	controlCount int
   254  	opts         fakeTransportProtocolOptions
   255  }
   256  
   257  func (*fakeTransportProtocol) Number() tcpip.TransportProtocolNumber {
   258  	return fakeTransNumber
   259  }
   260  
   261  func (f *fakeTransportProtocol) NewEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, _ *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) {
   262  	return newFakeTransportEndpoint(stack, f, netProto, stack.UniqueID()), nil
   263  }
   264  
   265  func (f *fakeTransportProtocol) NewRawEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, _ *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) {
   266  	return nil, tcpip.ErrUnknownProtocol
   267  }
   268  
   269  func (*fakeTransportProtocol) MinimumPacketSize() int {
   270  	return fakeTransHeaderLen
   271  }
   272  
   273  func (*fakeTransportProtocol) ParsePorts(buffer.View) (src, dst uint16, err *tcpip.Error) {
   274  	return 0, 0, nil
   275  }
   276  
   277  func (*fakeTransportProtocol) HandleUnknownDestinationPacket(*stack.Route, stack.TransportEndpointID, tcpip.PacketBuffer) bool {
   278  	return true
   279  }
   280  
   281  func (f *fakeTransportProtocol) SetOption(option interface{}) *tcpip.Error {
   282  	switch v := option.(type) {
   283  	case fakeTransportGoodOption:
   284  		f.opts.good = bool(v)
   285  		return nil
   286  	case fakeTransportInvalidValueOption:
   287  		return tcpip.ErrInvalidOptionValue
   288  	default:
   289  		return tcpip.ErrUnknownProtocolOption
   290  	}
   291  }
   292  
   293  func (f *fakeTransportProtocol) Option(option interface{}) *tcpip.Error {
   294  	switch v := option.(type) {
   295  	case *fakeTransportGoodOption:
   296  		*v = fakeTransportGoodOption(f.opts.good)
   297  		return nil
   298  	default:
   299  		return tcpip.ErrUnknownProtocolOption
   300  	}
   301  }
   302  
   303  func fakeTransFactory() stack.TransportProtocol {
   304  	return &fakeTransportProtocol{}
   305  }
   306  
   307  func TestTransportReceive(t *testing.T) {
   308  	linkEP := channel.New(10, defaultMTU, "")
   309  	s := stack.New(stack.Options{
   310  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
   311  		TransportProtocols: []stack.TransportProtocol{fakeTransFactory()},
   312  	})
   313  	if err := s.CreateNIC(1, linkEP); err != nil {
   314  		t.Fatalf("CreateNIC failed: %v", err)
   315  	}
   316  
   317  	{
   318  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   319  		if err != nil {
   320  			t.Fatal(err)
   321  		}
   322  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   323  	}
   324  
   325  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   326  		t.Fatalf("AddAddress failed: %v", err)
   327  	}
   328  
   329  	// Create endpoint and connect to remote address.
   330  	wq := waiter.Queue{}
   331  	ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq)
   332  	if err != nil {
   333  		t.Fatalf("NewEndpoint failed: %v", err)
   334  	}
   335  
   336  	if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil {
   337  		t.Fatalf("Connect failed: %v", err)
   338  	}
   339  
   340  	fakeTrans := s.TransportProtocolInstance(fakeTransNumber).(*fakeTransportProtocol)
   341  
   342  	// Create buffer that will hold the packet.
   343  	buf := buffer.NewView(30)
   344  
   345  	// Make sure packet with wrong protocol is not delivered.
   346  	buf[0] = 1
   347  	buf[2] = 0
   348  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   349  		Data: buf.ToVectorisedView(),
   350  	})
   351  	if fakeTrans.packetCount != 0 {
   352  		t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 0)
   353  	}
   354  
   355  	// Make sure packet from the wrong source is not delivered.
   356  	buf[0] = 1
   357  	buf[1] = 3
   358  	buf[2] = byte(fakeTransNumber)
   359  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   360  		Data: buf.ToVectorisedView(),
   361  	})
   362  	if fakeTrans.packetCount != 0 {
   363  		t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 0)
   364  	}
   365  
   366  	// Make sure packet is delivered.
   367  	buf[0] = 1
   368  	buf[1] = 2
   369  	buf[2] = byte(fakeTransNumber)
   370  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   371  		Data: buf.ToVectorisedView(),
   372  	})
   373  	if fakeTrans.packetCount != 1 {
   374  		t.Errorf("packetCount = %d, want %d", fakeTrans.packetCount, 1)
   375  	}
   376  }
   377  
   378  func TestTransportControlReceive(t *testing.T) {
   379  	linkEP := channel.New(10, defaultMTU, "")
   380  	s := stack.New(stack.Options{
   381  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
   382  		TransportProtocols: []stack.TransportProtocol{fakeTransFactory()},
   383  	})
   384  	if err := s.CreateNIC(1, linkEP); err != nil {
   385  		t.Fatalf("CreateNIC failed: %v", err)
   386  	}
   387  
   388  	{
   389  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   390  		if err != nil {
   391  			t.Fatal(err)
   392  		}
   393  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   394  	}
   395  
   396  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   397  		t.Fatalf("AddAddress failed: %v", err)
   398  	}
   399  
   400  	// Create endpoint and connect to remote address.
   401  	wq := waiter.Queue{}
   402  	ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq)
   403  	if err != nil {
   404  		t.Fatalf("NewEndpoint failed: %v", err)
   405  	}
   406  
   407  	if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil {
   408  		t.Fatalf("Connect failed: %v", err)
   409  	}
   410  
   411  	fakeTrans := s.TransportProtocolInstance(fakeTransNumber).(*fakeTransportProtocol)
   412  
   413  	// Create buffer that will hold the control packet.
   414  	buf := buffer.NewView(2*fakeNetHeaderLen + 30)
   415  
   416  	// Outer packet contains the control protocol number.
   417  	buf[0] = 1
   418  	buf[1] = 0xfe
   419  	buf[2] = uint8(fakeControlProtocol)
   420  
   421  	// Make sure packet with wrong protocol is not delivered.
   422  	buf[fakeNetHeaderLen+0] = 0
   423  	buf[fakeNetHeaderLen+1] = 1
   424  	buf[fakeNetHeaderLen+2] = 0
   425  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   426  		Data: buf.ToVectorisedView(),
   427  	})
   428  	if fakeTrans.controlCount != 0 {
   429  		t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 0)
   430  	}
   431  
   432  	// Make sure packet from the wrong source is not delivered.
   433  	buf[fakeNetHeaderLen+0] = 3
   434  	buf[fakeNetHeaderLen+1] = 1
   435  	buf[fakeNetHeaderLen+2] = byte(fakeTransNumber)
   436  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   437  		Data: buf.ToVectorisedView(),
   438  	})
   439  	if fakeTrans.controlCount != 0 {
   440  		t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 0)
   441  	}
   442  
   443  	// Make sure packet is delivered.
   444  	buf[fakeNetHeaderLen+0] = 2
   445  	buf[fakeNetHeaderLen+1] = 1
   446  	buf[fakeNetHeaderLen+2] = byte(fakeTransNumber)
   447  	linkEP.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   448  		Data: buf.ToVectorisedView(),
   449  	})
   450  	if fakeTrans.controlCount != 1 {
   451  		t.Errorf("controlCount = %d, want %d", fakeTrans.controlCount, 1)
   452  	}
   453  }
   454  
   455  func TestTransportSend(t *testing.T) {
   456  	linkEP := channel.New(10, defaultMTU, "")
   457  	s := stack.New(stack.Options{
   458  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
   459  		TransportProtocols: []stack.TransportProtocol{fakeTransFactory()},
   460  	})
   461  	if err := s.CreateNIC(1, linkEP); err != nil {
   462  		t.Fatalf("CreateNIC failed: %v", err)
   463  	}
   464  
   465  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   466  		t.Fatalf("AddAddress failed: %v", err)
   467  	}
   468  
   469  	{
   470  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   471  		if err != nil {
   472  			t.Fatal(err)
   473  		}
   474  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   475  	}
   476  
   477  	// Create endpoint and bind it.
   478  	wq := waiter.Queue{}
   479  	ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq)
   480  	if err != nil {
   481  		t.Fatalf("NewEndpoint failed: %v", err)
   482  	}
   483  
   484  	if err := ep.Connect(tcpip.FullAddress{0, "\x02", 0}); err != nil {
   485  		t.Fatalf("Connect failed: %v", err)
   486  	}
   487  
   488  	// Create buffer that will hold the payload.
   489  	view := buffer.NewView(30)
   490  	_, _, err = ep.Write(tcpip.SlicePayload(view), tcpip.WriteOptions{})
   491  	if err != nil {
   492  		t.Fatalf("write failed: %v", err)
   493  	}
   494  
   495  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   496  
   497  	if fakeNet.sendPacketCount[2] != 1 {
   498  		t.Errorf("sendPacketCount = %d, want %d", fakeNet.sendPacketCount[2], 1)
   499  	}
   500  }
   501  
   502  func TestTransportOptions(t *testing.T) {
   503  	s := stack.New(stack.Options{
   504  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
   505  		TransportProtocols: []stack.TransportProtocol{fakeTransFactory()},
   506  	})
   507  
   508  	// Try an unsupported transport protocol.
   509  	if err := s.SetTransportProtocolOption(tcpip.TransportProtocolNumber(99999), fakeTransportGoodOption(false)); err != tcpip.ErrUnknownProtocol {
   510  		t.Fatalf("SetTransportProtocolOption(fakeTrans2, blah, false) = %v, want = tcpip.ErrUnknownProtocol", err)
   511  	}
   512  
   513  	testCases := []struct {
   514  		option   interface{}
   515  		wantErr  *tcpip.Error
   516  		verifier func(t *testing.T, p stack.TransportProtocol)
   517  	}{
   518  		{fakeTransportGoodOption(true), nil, func(t *testing.T, p stack.TransportProtocol) {
   519  			t.Helper()
   520  			fakeTrans := p.(*fakeTransportProtocol)
   521  			if fakeTrans.opts.good != true {
   522  				t.Fatalf("fakeTrans.opts.good = false, want = true")
   523  			}
   524  			var v fakeTransportGoodOption
   525  			if err := s.TransportProtocolOption(fakeTransNumber, &v); err != nil {
   526  				t.Fatalf("s.TransportProtocolOption(fakeTransNumber, &v) = %v, want = nil, where v is option %T", v, err)
   527  			}
   528  			if v != true {
   529  				t.Fatalf("s.TransportProtocolOption(fakeTransNumber, &v) returned v = %v, want = true", v)
   530  			}
   531  
   532  		}},
   533  		{fakeTransportBadOption(true), tcpip.ErrUnknownProtocolOption, nil},
   534  		{fakeTransportInvalidValueOption(1), tcpip.ErrInvalidOptionValue, nil},
   535  	}
   536  	for _, tc := range testCases {
   537  		if got := s.SetTransportProtocolOption(fakeTransNumber, tc.option); got != tc.wantErr {
   538  			t.Errorf("s.SetTransportProtocolOption(fakeTrans, %v) = %v, want = %v", tc.option, got, tc.wantErr)
   539  		}
   540  		if tc.verifier != nil {
   541  			tc.verifier(t, s.TransportProtocolInstance(fakeTransNumber))
   542  		}
   543  	}
   544  }
   545  
   546  func TestTransportForwarding(t *testing.T) {
   547  	s := stack.New(stack.Options{
   548  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
   549  		TransportProtocols: []stack.TransportProtocol{fakeTransFactory()},
   550  	})
   551  	s.SetForwarding(true)
   552  
   553  	// TODO(b/123449044): Change this to a channel NIC.
   554  	ep1 := loopback.New()
   555  	if err := s.CreateNIC(1, ep1); err != nil {
   556  		t.Fatalf("CreateNIC #1 failed: %v", err)
   557  	}
   558  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   559  		t.Fatalf("AddAddress #1 failed: %v", err)
   560  	}
   561  
   562  	ep2 := channel.New(10, defaultMTU, "")
   563  	if err := s.CreateNIC(2, ep2); err != nil {
   564  		t.Fatalf("CreateNIC #2 failed: %v", err)
   565  	}
   566  	if err := s.AddAddress(2, fakeNetNumber, "\x02"); err != nil {
   567  		t.Fatalf("AddAddress #2 failed: %v", err)
   568  	}
   569  
   570  	// Route all packets to address 3 to NIC 2 and all packets to address
   571  	// 1 to NIC 1.
   572  	{
   573  		subnet0, err := tcpip.NewSubnet("\x03", "\xff")
   574  		if err != nil {
   575  			t.Fatal(err)
   576  		}
   577  		subnet1, err := tcpip.NewSubnet("\x01", "\xff")
   578  		if err != nil {
   579  			t.Fatal(err)
   580  		}
   581  		s.SetRouteTable([]tcpip.Route{
   582  			{Destination: subnet0, Gateway: "\x00", NIC: 2},
   583  			{Destination: subnet1, Gateway: "\x00", NIC: 1},
   584  		})
   585  	}
   586  
   587  	wq := waiter.Queue{}
   588  	ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq)
   589  	if err != nil {
   590  		t.Fatalf("NewEndpoint failed: %v", err)
   591  	}
   592  
   593  	if err := ep.Bind(tcpip.FullAddress{Addr: "\x01", NIC: 1}); err != nil {
   594  		t.Fatalf("Bind failed: %v", err)
   595  	}
   596  
   597  	// Send a packet to address 1 from address 3.
   598  	req := buffer.NewView(30)
   599  	req[0] = 1
   600  	req[1] = 3
   601  	req[2] = byte(fakeTransNumber)
   602  	ep2.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{
   603  		Data: req.ToVectorisedView(),
   604  	})
   605  
   606  	aep, _, err := ep.Accept()
   607  	if err != nil || aep == nil {
   608  		t.Fatalf("Accept failed: %v, %v", aep, err)
   609  	}
   610  
   611  	resp := buffer.NewView(30)
   612  	if _, _, err := aep.Write(tcpip.SlicePayload(resp), tcpip.WriteOptions{}); err != nil {
   613  		t.Fatalf("Write failed: %v", err)
   614  	}
   615  
   616  	var p channel.PacketInfo
   617  	select {
   618  	case p = <-ep2.C:
   619  	default:
   620  		t.Fatal("Response packet not forwarded")
   621  	}
   622  
   623  	if dst := p.Pkt.Header.View()[0]; dst != 3 {
   624  		t.Errorf("Response packet has incorrect destination addresss: got = %d, want = 3", dst)
   625  	}
   626  	if src := p.Pkt.Header.View()[1]; src != 1 {
   627  		t.Errorf("Response packet has incorrect source addresss: got = %d, want = 3", src)
   628  	}
   629  }