github.com/FlowerWrong/netstack@v0.0.0-20191009141956-e5848263af28/tcpip/stack/stack_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 contains tests for the stack. It is in its own package so
    16  // that the tests can also validate that all definitions needed to implement
    17  // transport and network protocols are properly exported by the stack package.
    18  package stack_test
    19  
    20  import (
    21  	"bytes"
    22  	"fmt"
    23  	"math"
    24  	"sort"
    25  	"strings"
    26  	"testing"
    27  
    28  	"github.com/FlowerWrong/netstack/tcpip"
    29  	"github.com/FlowerWrong/netstack/tcpip/buffer"
    30  	"github.com/FlowerWrong/netstack/tcpip/header"
    31  	"github.com/FlowerWrong/netstack/tcpip/link/channel"
    32  	"github.com/FlowerWrong/netstack/tcpip/stack"
    33  )
    34  
    35  const (
    36  	fakeNetNumber        tcpip.NetworkProtocolNumber = math.MaxUint32
    37  	fakeNetHeaderLen                                 = 12
    38  	fakeDefaultPrefixLen                             = 8
    39  
    40  	// fakeControlProtocol is used for control packets that represent
    41  	// destination port unreachable.
    42  	fakeControlProtocol tcpip.TransportProtocolNumber = 2
    43  
    44  	// defaultMTU is the MTU, in bytes, used throughout the tests, except
    45  	// where another value is explicitly used. It is chosen to match the MTU
    46  	// of loopback interfaces on linux systems.
    47  	defaultMTU = 65536
    48  )
    49  
    50  // fakeNetworkEndpoint is a network-layer protocol endpoint. It counts sent and
    51  // received packets; the counts of all endpoints are aggregated in the protocol
    52  // descriptor.
    53  //
    54  // Headers of this protocol are fakeNetHeaderLen bytes, but we currently only
    55  // use the first three: destination address, source address, and transport
    56  // protocol. They're all one byte fields to simplify parsing.
    57  type fakeNetworkEndpoint struct {
    58  	nicid      tcpip.NICID
    59  	id         stack.NetworkEndpointID
    60  	prefixLen  int
    61  	proto      *fakeNetworkProtocol
    62  	dispatcher stack.TransportDispatcher
    63  	ep         stack.LinkEndpoint
    64  }
    65  
    66  func (f *fakeNetworkEndpoint) MTU() uint32 {
    67  	return f.ep.MTU() - uint32(f.MaxHeaderLength())
    68  }
    69  
    70  func (f *fakeNetworkEndpoint) NICID() tcpip.NICID {
    71  	return f.nicid
    72  }
    73  
    74  func (f *fakeNetworkEndpoint) PrefixLen() int {
    75  	return f.prefixLen
    76  }
    77  
    78  func (*fakeNetworkEndpoint) DefaultTTL() uint8 {
    79  	return 123
    80  }
    81  
    82  func (f *fakeNetworkEndpoint) ID() *stack.NetworkEndpointID {
    83  	return &f.id
    84  }
    85  
    86  func (f *fakeNetworkEndpoint) HandlePacket(r *stack.Route, vv buffer.VectorisedView) {
    87  	// Increment the received packet count in the protocol descriptor.
    88  	f.proto.packetCount[int(f.id.LocalAddress[0])%len(f.proto.packetCount)]++
    89  
    90  	// Consume the network header.
    91  	b := vv.First()
    92  	vv.TrimFront(fakeNetHeaderLen)
    93  
    94  	// Handle control packets.
    95  	if b[2] == uint8(fakeControlProtocol) {
    96  		nb := vv.First()
    97  		if len(nb) < fakeNetHeaderLen {
    98  			return
    99  		}
   100  
   101  		vv.TrimFront(fakeNetHeaderLen)
   102  		f.dispatcher.DeliverTransportControlPacket(tcpip.Address(nb[1:2]), tcpip.Address(nb[0:1]), fakeNetNumber, tcpip.TransportProtocolNumber(nb[2]), stack.ControlPortUnreachable, 0, vv)
   103  		return
   104  	}
   105  
   106  	// Dispatch the packet to the transport protocol.
   107  	f.dispatcher.DeliverTransportPacket(r, tcpip.TransportProtocolNumber(b[2]), buffer.View([]byte{}), vv)
   108  }
   109  
   110  func (f *fakeNetworkEndpoint) MaxHeaderLength() uint16 {
   111  	return f.ep.MaxHeaderLength() + fakeNetHeaderLen
   112  }
   113  
   114  func (f *fakeNetworkEndpoint) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, dstAddr tcpip.Address) uint16 {
   115  	return 0
   116  }
   117  
   118  func (f *fakeNetworkEndpoint) Capabilities() stack.LinkEndpointCapabilities {
   119  	return f.ep.Capabilities()
   120  }
   121  
   122  func (f *fakeNetworkEndpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, _ uint8, loop stack.PacketLooping) *tcpip.Error {
   123  	// Increment the sent packet count in the protocol descriptor.
   124  	f.proto.sendPacketCount[int(r.RemoteAddress[0])%len(f.proto.sendPacketCount)]++
   125  
   126  	// Add the protocol's header to the packet and send it to the link
   127  	// endpoint.
   128  	b := hdr.Prepend(fakeNetHeaderLen)
   129  	b[0] = r.RemoteAddress[0]
   130  	b[1] = f.id.LocalAddress[0]
   131  	b[2] = byte(protocol)
   132  
   133  	if loop&stack.PacketLoop != 0 {
   134  		views := make([]buffer.View, 1, 1+len(payload.Views()))
   135  		views[0] = hdr.View()
   136  		views = append(views, payload.Views()...)
   137  		vv := buffer.NewVectorisedView(len(views[0])+payload.Size(), views)
   138  		f.HandlePacket(r, vv)
   139  	}
   140  	if loop&stack.PacketOut == 0 {
   141  		return nil
   142  	}
   143  
   144  	return f.ep.WritePacket(r, gso, hdr, payload, fakeNetNumber)
   145  }
   146  
   147  func (*fakeNetworkEndpoint) WriteHeaderIncludedPacket(r *stack.Route, payload buffer.VectorisedView, loop stack.PacketLooping) *tcpip.Error {
   148  	return tcpip.ErrNotSupported
   149  }
   150  
   151  func (*fakeNetworkEndpoint) Close() {}
   152  
   153  type fakeNetGoodOption bool
   154  
   155  type fakeNetBadOption bool
   156  
   157  type fakeNetInvalidValueOption int
   158  
   159  type fakeNetOptions struct {
   160  	good bool
   161  }
   162  
   163  // fakeNetworkProtocol is a network-layer protocol descriptor. It aggregates the
   164  // number of packets sent and received via endpoints of this protocol. The index
   165  // where packets are added is given by the packet's destination address MOD 10.
   166  type fakeNetworkProtocol struct {
   167  	packetCount     [10]int
   168  	sendPacketCount [10]int
   169  	opts            fakeNetOptions
   170  }
   171  
   172  func (f *fakeNetworkProtocol) Number() tcpip.NetworkProtocolNumber {
   173  	return fakeNetNumber
   174  }
   175  
   176  func (f *fakeNetworkProtocol) MinimumPacketSize() int {
   177  	return fakeNetHeaderLen
   178  }
   179  
   180  func (f *fakeNetworkProtocol) DefaultPrefixLen() int {
   181  	return fakeDefaultPrefixLen
   182  }
   183  
   184  func (f *fakeNetworkProtocol) PacketCount(intfAddr byte) int {
   185  	return f.packetCount[int(intfAddr)%len(f.packetCount)]
   186  }
   187  
   188  func (*fakeNetworkProtocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) {
   189  	return tcpip.Address(v[1:2]), tcpip.Address(v[0:1])
   190  }
   191  
   192  func (f *fakeNetworkProtocol) NewEndpoint(nicid tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, ep stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {
   193  	return &fakeNetworkEndpoint{
   194  		nicid:      nicid,
   195  		id:         stack.NetworkEndpointID{LocalAddress: addrWithPrefix.Address},
   196  		prefixLen:  addrWithPrefix.PrefixLen,
   197  		proto:      f,
   198  		dispatcher: dispatcher,
   199  		ep:         ep,
   200  	}, nil
   201  }
   202  
   203  func (f *fakeNetworkProtocol) SetOption(option interface{}) *tcpip.Error {
   204  	switch v := option.(type) {
   205  	case fakeNetGoodOption:
   206  		f.opts.good = bool(v)
   207  		return nil
   208  	case fakeNetInvalidValueOption:
   209  		return tcpip.ErrInvalidOptionValue
   210  	default:
   211  		return tcpip.ErrUnknownProtocolOption
   212  	}
   213  }
   214  
   215  func (f *fakeNetworkProtocol) Option(option interface{}) *tcpip.Error {
   216  	switch v := option.(type) {
   217  	case *fakeNetGoodOption:
   218  		*v = fakeNetGoodOption(f.opts.good)
   219  		return nil
   220  	default:
   221  		return tcpip.ErrUnknownProtocolOption
   222  	}
   223  }
   224  
   225  func fakeNetFactory() stack.NetworkProtocol {
   226  	return &fakeNetworkProtocol{}
   227  }
   228  
   229  func TestNetworkReceive(t *testing.T) {
   230  	// Create a stack with the fake network protocol, one nic, and two
   231  	// addresses attached to it: 1 & 2.
   232  	ep := channel.New(10, defaultMTU, "")
   233  	s := stack.New(stack.Options{
   234  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   235  	})
   236  	if err := s.CreateNIC(1, ep); err != nil {
   237  		t.Fatal("CreateNIC failed:", err)
   238  	}
   239  
   240  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   241  		t.Fatal("AddAddress failed:", err)
   242  	}
   243  
   244  	if err := s.AddAddress(1, fakeNetNumber, "\x02"); err != nil {
   245  		t.Fatal("AddAddress failed:", err)
   246  	}
   247  
   248  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   249  
   250  	buf := buffer.NewView(30)
   251  
   252  	// Make sure packet with wrong address is not delivered.
   253  	buf[0] = 3
   254  	ep.Inject(fakeNetNumber, buf.ToVectorisedView())
   255  	if fakeNet.packetCount[1] != 0 {
   256  		t.Errorf("packetCount[1] = %d, want %d", fakeNet.packetCount[1], 0)
   257  	}
   258  	if fakeNet.packetCount[2] != 0 {
   259  		t.Errorf("packetCount[2] = %d, want %d", fakeNet.packetCount[2], 0)
   260  	}
   261  
   262  	// Make sure packet is delivered to first endpoint.
   263  	buf[0] = 1
   264  	ep.Inject(fakeNetNumber, buf.ToVectorisedView())
   265  	if fakeNet.packetCount[1] != 1 {
   266  		t.Errorf("packetCount[1] = %d, want %d", fakeNet.packetCount[1], 1)
   267  	}
   268  	if fakeNet.packetCount[2] != 0 {
   269  		t.Errorf("packetCount[2] = %d, want %d", fakeNet.packetCount[2], 0)
   270  	}
   271  
   272  	// Make sure packet is delivered to second endpoint.
   273  	buf[0] = 2
   274  	ep.Inject(fakeNetNumber, buf.ToVectorisedView())
   275  	if fakeNet.packetCount[1] != 1 {
   276  		t.Errorf("packetCount[1] = %d, want %d", fakeNet.packetCount[1], 1)
   277  	}
   278  	if fakeNet.packetCount[2] != 1 {
   279  		t.Errorf("packetCount[2] = %d, want %d", fakeNet.packetCount[2], 1)
   280  	}
   281  
   282  	// Make sure packet is not delivered if protocol number is wrong.
   283  	ep.Inject(fakeNetNumber-1, buf.ToVectorisedView())
   284  	if fakeNet.packetCount[1] != 1 {
   285  		t.Errorf("packetCount[1] = %d, want %d", fakeNet.packetCount[1], 1)
   286  	}
   287  	if fakeNet.packetCount[2] != 1 {
   288  		t.Errorf("packetCount[2] = %d, want %d", fakeNet.packetCount[2], 1)
   289  	}
   290  
   291  	// Make sure packet that is too small is dropped.
   292  	buf.CapLength(2)
   293  	ep.Inject(fakeNetNumber, buf.ToVectorisedView())
   294  	if fakeNet.packetCount[1] != 1 {
   295  		t.Errorf("packetCount[1] = %d, want %d", fakeNet.packetCount[1], 1)
   296  	}
   297  	if fakeNet.packetCount[2] != 1 {
   298  		t.Errorf("packetCount[2] = %d, want %d", fakeNet.packetCount[2], 1)
   299  	}
   300  }
   301  
   302  func sendTo(s *stack.Stack, addr tcpip.Address, payload buffer.View) *tcpip.Error {
   303  	r, err := s.FindRoute(0, "", addr, fakeNetNumber, false /* multicastLoop */)
   304  	if err != nil {
   305  		return err
   306  	}
   307  	defer r.Release()
   308  	return send(r, payload)
   309  }
   310  
   311  func send(r stack.Route, payload buffer.View) *tcpip.Error {
   312  	hdr := buffer.NewPrependable(int(r.MaxHeaderLength()))
   313  	return r.WritePacket(nil /* gso */, hdr, payload.ToVectorisedView(), fakeTransNumber, 123 /* ttl */, false /* useDefaultTTL */)
   314  }
   315  
   316  func testSendTo(t *testing.T, s *stack.Stack, addr tcpip.Address, ep *channel.Endpoint, payload buffer.View) {
   317  	t.Helper()
   318  	ep.Drain()
   319  	if err := sendTo(s, addr, payload); err != nil {
   320  		t.Error("sendTo failed:", err)
   321  	}
   322  	if got, want := ep.Drain(), 1; got != want {
   323  		t.Errorf("sendTo packet count: got = %d, want %d", got, want)
   324  	}
   325  }
   326  
   327  func testSend(t *testing.T, r stack.Route, ep *channel.Endpoint, payload buffer.View) {
   328  	t.Helper()
   329  	ep.Drain()
   330  	if err := send(r, payload); err != nil {
   331  		t.Error("send failed:", err)
   332  	}
   333  	if got, want := ep.Drain(), 1; got != want {
   334  		t.Errorf("send packet count: got = %d, want %d", got, want)
   335  	}
   336  }
   337  
   338  func testFailingSend(t *testing.T, r stack.Route, ep *channel.Endpoint, payload buffer.View, wantErr *tcpip.Error) {
   339  	t.Helper()
   340  	if gotErr := send(r, payload); gotErr != wantErr {
   341  		t.Errorf("send failed: got = %s, want = %s ", gotErr, wantErr)
   342  	}
   343  }
   344  
   345  func testFailingSendTo(t *testing.T, s *stack.Stack, addr tcpip.Address, ep *channel.Endpoint, payload buffer.View, wantErr *tcpip.Error) {
   346  	t.Helper()
   347  	if gotErr := sendTo(s, addr, payload); gotErr != wantErr {
   348  		t.Errorf("sendto failed: got = %s, want = %s ", gotErr, wantErr)
   349  	}
   350  }
   351  
   352  func testRecv(t *testing.T, fakeNet *fakeNetworkProtocol, localAddrByte byte, ep *channel.Endpoint, buf buffer.View) {
   353  	t.Helper()
   354  	// testRecvInternal injects one packet, and we expect to receive it.
   355  	want := fakeNet.PacketCount(localAddrByte) + 1
   356  	testRecvInternal(t, fakeNet, localAddrByte, ep, buf, want)
   357  }
   358  
   359  func testFailingRecv(t *testing.T, fakeNet *fakeNetworkProtocol, localAddrByte byte, ep *channel.Endpoint, buf buffer.View) {
   360  	t.Helper()
   361  	// testRecvInternal injects one packet, and we do NOT expect to receive it.
   362  	want := fakeNet.PacketCount(localAddrByte)
   363  	testRecvInternal(t, fakeNet, localAddrByte, ep, buf, want)
   364  }
   365  
   366  func testRecvInternal(t *testing.T, fakeNet *fakeNetworkProtocol, localAddrByte byte, ep *channel.Endpoint, buf buffer.View, want int) {
   367  	t.Helper()
   368  	ep.Inject(fakeNetNumber, buf.ToVectorisedView())
   369  	if got := fakeNet.PacketCount(localAddrByte); got != want {
   370  		t.Errorf("receive packet count: got = %d, want %d", got, want)
   371  	}
   372  }
   373  
   374  func TestNetworkSend(t *testing.T) {
   375  	// Create a stack with the fake network protocol, one nic, and one
   376  	// address: 1. The route table sends all packets through the only
   377  	// existing nic.
   378  	ep := channel.New(10, defaultMTU, "")
   379  	s := stack.New(stack.Options{
   380  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   381  	})
   382  	if err := s.CreateNIC(1, ep); err != nil {
   383  		t.Fatal("NewNIC failed:", err)
   384  	}
   385  
   386  	{
   387  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   388  		if err != nil {
   389  			t.Fatal(err)
   390  		}
   391  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   392  	}
   393  
   394  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   395  		t.Fatal("AddAddress failed:", err)
   396  	}
   397  
   398  	// Make sure that the link-layer endpoint received the outbound packet.
   399  	testSendTo(t, s, "\x03", ep, nil)
   400  }
   401  
   402  func TestNetworkSendMultiRoute(t *testing.T) {
   403  	// Create a stack with the fake network protocol, two nics, and two
   404  	// addresses per nic, the first nic has odd address, the second one has
   405  	// even addresses.
   406  	s := stack.New(stack.Options{
   407  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   408  	})
   409  
   410  	ep1 := channel.New(10, defaultMTU, "")
   411  	if err := s.CreateNIC(1, ep1); err != nil {
   412  		t.Fatal("CreateNIC failed:", err)
   413  	}
   414  
   415  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   416  		t.Fatal("AddAddress failed:", err)
   417  	}
   418  
   419  	if err := s.AddAddress(1, fakeNetNumber, "\x03"); err != nil {
   420  		t.Fatal("AddAddress failed:", err)
   421  	}
   422  
   423  	ep2 := channel.New(10, defaultMTU, "")
   424  	if err := s.CreateNIC(2, ep2); err != nil {
   425  		t.Fatal("CreateNIC failed:", err)
   426  	}
   427  
   428  	if err := s.AddAddress(2, fakeNetNumber, "\x02"); err != nil {
   429  		t.Fatal("AddAddress failed:", err)
   430  	}
   431  
   432  	if err := s.AddAddress(2, fakeNetNumber, "\x04"); err != nil {
   433  		t.Fatal("AddAddress failed:", err)
   434  	}
   435  
   436  	// Set a route table that sends all packets with odd destination
   437  	// addresses through the first NIC, and all even destination address
   438  	// through the second one.
   439  	{
   440  		subnet0, err := tcpip.NewSubnet("\x00", "\x01")
   441  		if err != nil {
   442  			t.Fatal(err)
   443  		}
   444  		subnet1, err := tcpip.NewSubnet("\x01", "\x01")
   445  		if err != nil {
   446  			t.Fatal(err)
   447  		}
   448  		s.SetRouteTable([]tcpip.Route{
   449  			{Destination: subnet1, Gateway: "\x00", NIC: 1},
   450  			{Destination: subnet0, Gateway: "\x00", NIC: 2},
   451  		})
   452  	}
   453  
   454  	// Send a packet to an odd destination.
   455  	testSendTo(t, s, "\x05", ep1, nil)
   456  
   457  	// Send a packet to an even destination.
   458  	testSendTo(t, s, "\x06", ep2, nil)
   459  }
   460  
   461  func testRoute(t *testing.T, s *stack.Stack, nic tcpip.NICID, srcAddr, dstAddr, expectedSrcAddr tcpip.Address) {
   462  	r, err := s.FindRoute(nic, srcAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
   463  	if err != nil {
   464  		t.Fatal("FindRoute failed:", err)
   465  	}
   466  
   467  	defer r.Release()
   468  
   469  	if r.LocalAddress != expectedSrcAddr {
   470  		t.Fatalf("Bad source address: expected %v, got %v", expectedSrcAddr, r.LocalAddress)
   471  	}
   472  
   473  	if r.RemoteAddress != dstAddr {
   474  		t.Fatalf("Bad destination address: expected %v, got %v", dstAddr, r.RemoteAddress)
   475  	}
   476  }
   477  
   478  func testNoRoute(t *testing.T, s *stack.Stack, nic tcpip.NICID, srcAddr, dstAddr tcpip.Address) {
   479  	_, err := s.FindRoute(nic, srcAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
   480  	if err != tcpip.ErrNoRoute {
   481  		t.Fatalf("FindRoute returned unexpected error, got = %v, want = %s", err, tcpip.ErrNoRoute)
   482  	}
   483  }
   484  
   485  func TestRoutes(t *testing.T) {
   486  	// Create a stack with the fake network protocol, two nics, and two
   487  	// addresses per nic, the first nic has odd address, the second one has
   488  	// even addresses.
   489  	s := stack.New(stack.Options{
   490  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   491  	})
   492  
   493  	ep1 := channel.New(10, defaultMTU, "")
   494  	if err := s.CreateNIC(1, ep1); err != nil {
   495  		t.Fatal("CreateNIC failed:", err)
   496  	}
   497  
   498  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
   499  		t.Fatal("AddAddress failed:", err)
   500  	}
   501  
   502  	if err := s.AddAddress(1, fakeNetNumber, "\x03"); err != nil {
   503  		t.Fatal("AddAddress failed:", err)
   504  	}
   505  
   506  	ep2 := channel.New(10, defaultMTU, "")
   507  	if err := s.CreateNIC(2, ep2); err != nil {
   508  		t.Fatal("CreateNIC failed:", err)
   509  	}
   510  
   511  	if err := s.AddAddress(2, fakeNetNumber, "\x02"); err != nil {
   512  		t.Fatal("AddAddress failed:", err)
   513  	}
   514  
   515  	if err := s.AddAddress(2, fakeNetNumber, "\x04"); err != nil {
   516  		t.Fatal("AddAddress failed:", err)
   517  	}
   518  
   519  	// Set a route table that sends all packets with odd destination
   520  	// addresses through the first NIC, and all even destination address
   521  	// through the second one.
   522  	{
   523  		subnet0, err := tcpip.NewSubnet("\x00", "\x01")
   524  		if err != nil {
   525  			t.Fatal(err)
   526  		}
   527  		subnet1, err := tcpip.NewSubnet("\x01", "\x01")
   528  		if err != nil {
   529  			t.Fatal(err)
   530  		}
   531  		s.SetRouteTable([]tcpip.Route{
   532  			{Destination: subnet1, Gateway: "\x00", NIC: 1},
   533  			{Destination: subnet0, Gateway: "\x00", NIC: 2},
   534  		})
   535  	}
   536  
   537  	// Test routes to odd address.
   538  	testRoute(t, s, 0, "", "\x05", "\x01")
   539  	testRoute(t, s, 0, "\x01", "\x05", "\x01")
   540  	testRoute(t, s, 1, "\x01", "\x05", "\x01")
   541  	testRoute(t, s, 0, "\x03", "\x05", "\x03")
   542  	testRoute(t, s, 1, "\x03", "\x05", "\x03")
   543  
   544  	// Test routes to even address.
   545  	testRoute(t, s, 0, "", "\x06", "\x02")
   546  	testRoute(t, s, 0, "\x02", "\x06", "\x02")
   547  	testRoute(t, s, 2, "\x02", "\x06", "\x02")
   548  	testRoute(t, s, 0, "\x04", "\x06", "\x04")
   549  	testRoute(t, s, 2, "\x04", "\x06", "\x04")
   550  
   551  	// Try to send to odd numbered address from even numbered ones, then
   552  	// vice-versa.
   553  	testNoRoute(t, s, 0, "\x02", "\x05")
   554  	testNoRoute(t, s, 2, "\x02", "\x05")
   555  	testNoRoute(t, s, 0, "\x04", "\x05")
   556  	testNoRoute(t, s, 2, "\x04", "\x05")
   557  
   558  	testNoRoute(t, s, 0, "\x01", "\x06")
   559  	testNoRoute(t, s, 1, "\x01", "\x06")
   560  	testNoRoute(t, s, 0, "\x03", "\x06")
   561  	testNoRoute(t, s, 1, "\x03", "\x06")
   562  }
   563  
   564  func TestAddressRemoval(t *testing.T) {
   565  	const localAddrByte byte = 0x01
   566  	localAddr := tcpip.Address([]byte{localAddrByte})
   567  	remoteAddr := tcpip.Address("\x02")
   568  
   569  	s := stack.New(stack.Options{
   570  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   571  	})
   572  
   573  	ep := channel.New(10, defaultMTU, "")
   574  	if err := s.CreateNIC(1, ep); err != nil {
   575  		t.Fatal("CreateNIC failed:", err)
   576  	}
   577  
   578  	if err := s.AddAddress(1, fakeNetNumber, localAddr); err != nil {
   579  		t.Fatal("AddAddress failed:", err)
   580  	}
   581  	{
   582  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   583  		if err != nil {
   584  			t.Fatal(err)
   585  		}
   586  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   587  	}
   588  
   589  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   590  
   591  	buf := buffer.NewView(30)
   592  
   593  	// Send and receive packets, and verify they are received.
   594  	buf[0] = localAddrByte
   595  	testRecv(t, fakeNet, localAddrByte, ep, buf)
   596  	testSendTo(t, s, remoteAddr, ep, nil)
   597  
   598  	// Remove the address, then check that send/receive doesn't work anymore.
   599  	if err := s.RemoveAddress(1, localAddr); err != nil {
   600  		t.Fatal("RemoveAddress failed:", err)
   601  	}
   602  	testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   603  	testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   604  
   605  	// Check that removing the same address fails.
   606  	if err := s.RemoveAddress(1, localAddr); err != tcpip.ErrBadLocalAddress {
   607  		t.Fatalf("RemoveAddress returned unexpected error, got = %v, want = %s", err, tcpip.ErrBadLocalAddress)
   608  	}
   609  }
   610  
   611  func TestAddressRemovalWithRouteHeld(t *testing.T) {
   612  	const localAddrByte byte = 0x01
   613  	localAddr := tcpip.Address([]byte{localAddrByte})
   614  	remoteAddr := tcpip.Address("\x02")
   615  
   616  	s := stack.New(stack.Options{
   617  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   618  	})
   619  
   620  	ep := channel.New(10, defaultMTU, "")
   621  	if err := s.CreateNIC(1, ep); err != nil {
   622  		t.Fatalf("CreateNIC failed: %v", err)
   623  	}
   624  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   625  	buf := buffer.NewView(30)
   626  
   627  	if err := s.AddAddress(1, fakeNetNumber, localAddr); err != nil {
   628  		t.Fatal("AddAddress failed:", err)
   629  	}
   630  	{
   631  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   632  		if err != nil {
   633  			t.Fatal(err)
   634  		}
   635  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   636  	}
   637  
   638  	r, err := s.FindRoute(0, "", remoteAddr, fakeNetNumber, false /* multicastLoop */)
   639  	if err != nil {
   640  		t.Fatal("FindRoute failed:", err)
   641  	}
   642  
   643  	// Send and receive packets, and verify they are received.
   644  	buf[0] = localAddrByte
   645  	testRecv(t, fakeNet, localAddrByte, ep, buf)
   646  	testSend(t, r, ep, nil)
   647  	testSendTo(t, s, remoteAddr, ep, nil)
   648  
   649  	// Remove the address, then check that send/receive doesn't work anymore.
   650  	if err := s.RemoveAddress(1, localAddr); err != nil {
   651  		t.Fatal("RemoveAddress failed:", err)
   652  	}
   653  	testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   654  	testFailingSend(t, r, ep, nil, tcpip.ErrInvalidEndpointState)
   655  	testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   656  
   657  	// Check that removing the same address fails.
   658  	if err := s.RemoveAddress(1, localAddr); err != tcpip.ErrBadLocalAddress {
   659  		t.Fatalf("RemoveAddress returned unexpected error, got = %v, want = %s", err, tcpip.ErrBadLocalAddress)
   660  	}
   661  }
   662  
   663  func verifyAddress(t *testing.T, s *stack.Stack, nicid tcpip.NICID, addr tcpip.Address) {
   664  	t.Helper()
   665  	info, ok := s.NICInfo()[nicid]
   666  	if !ok {
   667  		t.Fatalf("NICInfo() failed to find nicid=%d", nicid)
   668  	}
   669  	if len(addr) == 0 {
   670  		// No address given, verify that there is no address assigned to the NIC.
   671  		for _, a := range info.ProtocolAddresses {
   672  			if a.Protocol == fakeNetNumber && a.AddressWithPrefix != (tcpip.AddressWithPrefix{}) {
   673  				t.Errorf("verify no-address: got = %s, want = %s", a.AddressWithPrefix, (tcpip.AddressWithPrefix{}))
   674  			}
   675  		}
   676  		return
   677  	}
   678  	// Address given, verify the address is assigned to the NIC and no other
   679  	// address is.
   680  	found := false
   681  	for _, a := range info.ProtocolAddresses {
   682  		if a.Protocol == fakeNetNumber {
   683  			if a.AddressWithPrefix.Address == addr {
   684  				found = true
   685  			} else {
   686  				t.Errorf("verify address: got = %s, want = %s", a.AddressWithPrefix.Address, addr)
   687  			}
   688  		}
   689  	}
   690  	if !found {
   691  		t.Errorf("verify address: couldn't find %s on the NIC", addr)
   692  	}
   693  }
   694  
   695  func TestEndpointExpiration(t *testing.T) {
   696  	const (
   697  		localAddrByte byte          = 0x01
   698  		remoteAddr    tcpip.Address = "\x03"
   699  		noAddr        tcpip.Address = ""
   700  		nicid         tcpip.NICID   = 1
   701  	)
   702  	localAddr := tcpip.Address([]byte{localAddrByte})
   703  
   704  	for _, promiscuous := range []bool{true, false} {
   705  		for _, spoofing := range []bool{true, false} {
   706  			t.Run(fmt.Sprintf("promiscuous=%t spoofing=%t", promiscuous, spoofing), func(t *testing.T) {
   707  				s := stack.New(stack.Options{
   708  					NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   709  				})
   710  
   711  				ep := channel.New(10, defaultMTU, "")
   712  				if err := s.CreateNIC(nicid, ep); err != nil {
   713  					t.Fatal("CreateNIC failed:", err)
   714  				}
   715  
   716  				{
   717  					subnet, err := tcpip.NewSubnet("\x00", "\x00")
   718  					if err != nil {
   719  						t.Fatal(err)
   720  					}
   721  					s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   722  				}
   723  
   724  				fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   725  				buf := buffer.NewView(30)
   726  				buf[0] = localAddrByte
   727  
   728  				if promiscuous {
   729  					if err := s.SetPromiscuousMode(nicid, true); err != nil {
   730  						t.Fatal("SetPromiscuousMode failed:", err)
   731  					}
   732  				}
   733  
   734  				if spoofing {
   735  					if err := s.SetSpoofing(nicid, true); err != nil {
   736  						t.Fatal("SetSpoofing failed:", err)
   737  					}
   738  				}
   739  
   740  				// 1. No Address yet, send should only work for spoofing, receive for
   741  				// promiscuous mode.
   742  				//-----------------------
   743  				verifyAddress(t, s, nicid, noAddr)
   744  				if promiscuous {
   745  					testRecv(t, fakeNet, localAddrByte, ep, buf)
   746  				} else {
   747  					testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   748  				}
   749  				if spoofing {
   750  					// FIXME(b/139841518):Spoofing doesn't work if there is no primary address.
   751  					// testSendTo(t, s, remoteAddr, ep, nil)
   752  				} else {
   753  					testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   754  				}
   755  
   756  				// 2. Add Address, everything should work.
   757  				//-----------------------
   758  				if err := s.AddAddress(nicid, fakeNetNumber, localAddr); err != nil {
   759  					t.Fatal("AddAddress failed:", err)
   760  				}
   761  				verifyAddress(t, s, nicid, localAddr)
   762  				testRecv(t, fakeNet, localAddrByte, ep, buf)
   763  				testSendTo(t, s, remoteAddr, ep, nil)
   764  
   765  				// 3. Remove the address, send should only work for spoofing, receive
   766  				// for promiscuous mode.
   767  				//-----------------------
   768  				if err := s.RemoveAddress(nicid, localAddr); err != nil {
   769  					t.Fatal("RemoveAddress failed:", err)
   770  				}
   771  				verifyAddress(t, s, nicid, noAddr)
   772  				if promiscuous {
   773  					testRecv(t, fakeNet, localAddrByte, ep, buf)
   774  				} else {
   775  					testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   776  				}
   777  				if spoofing {
   778  					// FIXME(b/139841518):Spoofing doesn't work if there is no primary address.
   779  					// testSendTo(t, s, remoteAddr, ep, nil)
   780  				} else {
   781  					testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   782  				}
   783  
   784  				// 4. Add Address back, everything should work again.
   785  				//-----------------------
   786  				if err := s.AddAddress(nicid, fakeNetNumber, localAddr); err != nil {
   787  					t.Fatal("AddAddress failed:", err)
   788  				}
   789  				verifyAddress(t, s, nicid, localAddr)
   790  				testRecv(t, fakeNet, localAddrByte, ep, buf)
   791  				testSendTo(t, s, remoteAddr, ep, nil)
   792  
   793  				// 5. Take a reference to the endpoint by getting a route. Verify that
   794  				// we can still send/receive, including sending using the route.
   795  				//-----------------------
   796  				r, err := s.FindRoute(0, "", remoteAddr, fakeNetNumber, false /* multicastLoop */)
   797  				if err != nil {
   798  					t.Fatal("FindRoute failed:", err)
   799  				}
   800  				testRecv(t, fakeNet, localAddrByte, ep, buf)
   801  				testSendTo(t, s, remoteAddr, ep, nil)
   802  				testSend(t, r, ep, nil)
   803  
   804  				// 6. Remove the address. Send should only work for spoofing, receive
   805  				// for promiscuous mode.
   806  				//-----------------------
   807  				if err := s.RemoveAddress(nicid, localAddr); err != nil {
   808  					t.Fatal("RemoveAddress failed:", err)
   809  				}
   810  				verifyAddress(t, s, nicid, noAddr)
   811  				if promiscuous {
   812  					testRecv(t, fakeNet, localAddrByte, ep, buf)
   813  				} else {
   814  					testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   815  				}
   816  				if spoofing {
   817  					testSend(t, r, ep, nil)
   818  					testSendTo(t, s, remoteAddr, ep, nil)
   819  				} else {
   820  					testFailingSend(t, r, ep, nil, tcpip.ErrInvalidEndpointState)
   821  					testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   822  				}
   823  
   824  				// 7. Add Address back, everything should work again.
   825  				//-----------------------
   826  				if err := s.AddAddress(nicid, fakeNetNumber, localAddr); err != nil {
   827  					t.Fatal("AddAddress failed:", err)
   828  				}
   829  				verifyAddress(t, s, nicid, localAddr)
   830  				testRecv(t, fakeNet, localAddrByte, ep, buf)
   831  				testSendTo(t, s, remoteAddr, ep, nil)
   832  				testSend(t, r, ep, nil)
   833  
   834  				// 8. Remove the route, sendTo/recv should still work.
   835  				//-----------------------
   836  				r.Release()
   837  				verifyAddress(t, s, nicid, localAddr)
   838  				testRecv(t, fakeNet, localAddrByte, ep, buf)
   839  				testSendTo(t, s, remoteAddr, ep, nil)
   840  
   841  				// 9. Remove the address. Send should only work for spoofing, receive
   842  				// for promiscuous mode.
   843  				//-----------------------
   844  				if err := s.RemoveAddress(nicid, localAddr); err != nil {
   845  					t.Fatal("RemoveAddress failed:", err)
   846  				}
   847  				verifyAddress(t, s, nicid, noAddr)
   848  				if promiscuous {
   849  					testRecv(t, fakeNet, localAddrByte, ep, buf)
   850  				} else {
   851  					testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   852  				}
   853  				if spoofing {
   854  					// FIXME(b/139841518):Spoofing doesn't work if there is no primary address.
   855  					// testSendTo(t, s, remoteAddr, ep, nil)
   856  				} else {
   857  					testFailingSendTo(t, s, remoteAddr, ep, nil, tcpip.ErrNoRoute)
   858  				}
   859  			})
   860  		}
   861  	}
   862  }
   863  
   864  func TestPromiscuousMode(t *testing.T) {
   865  	s := stack.New(stack.Options{
   866  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   867  	})
   868  
   869  	ep := channel.New(10, defaultMTU, "")
   870  	if err := s.CreateNIC(1, ep); err != nil {
   871  		t.Fatal("CreateNIC failed:", err)
   872  	}
   873  
   874  	{
   875  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   876  		if err != nil {
   877  			t.Fatal(err)
   878  		}
   879  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   880  	}
   881  
   882  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
   883  
   884  	buf := buffer.NewView(30)
   885  
   886  	// Write a packet, and check that it doesn't get delivered as we don't
   887  	// have a matching endpoint.
   888  	const localAddrByte byte = 0x01
   889  	buf[0] = localAddrByte
   890  	testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   891  
   892  	// Set promiscuous mode, then check that packet is delivered.
   893  	if err := s.SetPromiscuousMode(1, true); err != nil {
   894  		t.Fatal("SetPromiscuousMode failed:", err)
   895  	}
   896  	testRecv(t, fakeNet, localAddrByte, ep, buf)
   897  
   898  	// Check that we can't get a route as there is no local address.
   899  	_, err := s.FindRoute(0, "", "\x02", fakeNetNumber, false /* multicastLoop */)
   900  	if err != tcpip.ErrNoRoute {
   901  		t.Fatalf("FindRoute returned unexpected error: got = %v, want = %s", err, tcpip.ErrNoRoute)
   902  	}
   903  
   904  	// Set promiscuous mode to false, then check that packet can't be
   905  	// delivered anymore.
   906  	if err := s.SetPromiscuousMode(1, false); err != nil {
   907  		t.Fatal("SetPromiscuousMode failed:", err)
   908  	}
   909  	testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
   910  }
   911  
   912  func TestSpoofingWithAddress(t *testing.T) {
   913  	localAddr := tcpip.Address("\x01")
   914  	nonExistentLocalAddr := tcpip.Address("\x02")
   915  	dstAddr := tcpip.Address("\x03")
   916  
   917  	s := stack.New(stack.Options{
   918  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   919  	})
   920  
   921  	ep := channel.New(10, defaultMTU, "")
   922  	if err := s.CreateNIC(1, ep); err != nil {
   923  		t.Fatal("CreateNIC failed:", err)
   924  	}
   925  
   926  	if err := s.AddAddress(1, fakeNetNumber, localAddr); err != nil {
   927  		t.Fatal("AddAddress failed:", err)
   928  	}
   929  
   930  	{
   931  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   932  		if err != nil {
   933  			t.Fatal(err)
   934  		}
   935  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   936  	}
   937  
   938  	// With address spoofing disabled, FindRoute does not permit an address
   939  	// that was not added to the NIC to be used as the source.
   940  	r, err := s.FindRoute(0, nonExistentLocalAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
   941  	if err == nil {
   942  		t.Errorf("FindRoute succeeded with route %+v when it should have failed", r)
   943  	}
   944  
   945  	// With address spoofing enabled, FindRoute permits any address to be used
   946  	// as the source.
   947  	if err := s.SetSpoofing(1, true); err != nil {
   948  		t.Fatal("SetSpoofing failed:", err)
   949  	}
   950  	r, err = s.FindRoute(0, nonExistentLocalAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
   951  	if err != nil {
   952  		t.Fatal("FindRoute failed:", err)
   953  	}
   954  	if r.LocalAddress != nonExistentLocalAddr {
   955  		t.Errorf("got Route.LocalAddress = %s, want = %s", r.LocalAddress, nonExistentLocalAddr)
   956  	}
   957  	if r.RemoteAddress != dstAddr {
   958  		t.Errorf("got Route.RemoteAddress = %s, want = %s", r.RemoteAddress, dstAddr)
   959  	}
   960  	// Sending a packet works.
   961  	testSendTo(t, s, dstAddr, ep, nil)
   962  	testSend(t, r, ep, nil)
   963  
   964  	// FindRoute should also work with a local address that exists on the NIC.
   965  	r, err = s.FindRoute(0, localAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
   966  	if err != nil {
   967  		t.Fatal("FindRoute failed:", err)
   968  	}
   969  	if r.LocalAddress != localAddr {
   970  		t.Errorf("got Route.LocalAddress = %s, want = %s", r.LocalAddress, nonExistentLocalAddr)
   971  	}
   972  	if r.RemoteAddress != dstAddr {
   973  		t.Errorf("got Route.RemoteAddress = %s, want = %s", r.RemoteAddress, dstAddr)
   974  	}
   975  	// Sending a packet using the route works.
   976  	testSend(t, r, ep, nil)
   977  }
   978  
   979  func TestSpoofingNoAddress(t *testing.T) {
   980  	nonExistentLocalAddr := tcpip.Address("\x01")
   981  	dstAddr := tcpip.Address("\x02")
   982  
   983  	s := stack.New(stack.Options{
   984  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
   985  	})
   986  
   987  	ep := channel.New(10, defaultMTU, "")
   988  	if err := s.CreateNIC(1, ep); err != nil {
   989  		t.Fatal("CreateNIC failed:", err)
   990  	}
   991  
   992  	{
   993  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
   994  		if err != nil {
   995  			t.Fatal(err)
   996  		}
   997  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
   998  	}
   999  
  1000  	// With address spoofing disabled, FindRoute does not permit an address
  1001  	// that was not added to the NIC to be used as the source.
  1002  	r, err := s.FindRoute(0, nonExistentLocalAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
  1003  	if err == nil {
  1004  		t.Errorf("FindRoute succeeded with route %+v when it should have failed", r)
  1005  	}
  1006  	// Sending a packet fails.
  1007  	testFailingSendTo(t, s, dstAddr, ep, nil, tcpip.ErrNoRoute)
  1008  
  1009  	// With address spoofing enabled, FindRoute permits any address to be used
  1010  	// as the source.
  1011  	if err := s.SetSpoofing(1, true); err != nil {
  1012  		t.Fatal("SetSpoofing failed:", err)
  1013  	}
  1014  	r, err = s.FindRoute(0, nonExistentLocalAddr, dstAddr, fakeNetNumber, false /* multicastLoop */)
  1015  	if err != nil {
  1016  		t.Fatal("FindRoute failed:", err)
  1017  	}
  1018  	if r.LocalAddress != nonExistentLocalAddr {
  1019  		t.Errorf("got Route.LocalAddress = %s, want = %s", r.LocalAddress, nonExistentLocalAddr)
  1020  	}
  1021  	if r.RemoteAddress != dstAddr {
  1022  		t.Errorf("got Route.RemoteAddress = %s, want = %s", r.RemoteAddress, dstAddr)
  1023  	}
  1024  	// Sending a packet works.
  1025  	// FIXME(b/139841518):Spoofing doesn't work if there is no primary address.
  1026  	// testSendTo(t, s, remoteAddr, ep, nil)
  1027  }
  1028  
  1029  func verifyRoute(gotRoute, wantRoute stack.Route) error {
  1030  	if gotRoute.LocalAddress != wantRoute.LocalAddress {
  1031  		return fmt.Errorf("bad local address: got %s, want = %s", gotRoute.LocalAddress, wantRoute.LocalAddress)
  1032  	}
  1033  	if gotRoute.RemoteAddress != wantRoute.RemoteAddress {
  1034  		return fmt.Errorf("bad remote address: got %s, want = %s", gotRoute.RemoteAddress, wantRoute.RemoteAddress)
  1035  	}
  1036  	if gotRoute.RemoteLinkAddress != wantRoute.RemoteLinkAddress {
  1037  		return fmt.Errorf("bad remote link address: got %s, want = %s", gotRoute.RemoteLinkAddress, wantRoute.RemoteLinkAddress)
  1038  	}
  1039  	if gotRoute.NextHop != wantRoute.NextHop {
  1040  		return fmt.Errorf("bad next-hop address: got %s, want = %s", gotRoute.NextHop, wantRoute.NextHop)
  1041  	}
  1042  	return nil
  1043  }
  1044  
  1045  func TestOutgoingBroadcastWithEmptyRouteTable(t *testing.T) {
  1046  	s := stack.New(stack.Options{
  1047  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1048  	})
  1049  
  1050  	ep := channel.New(10, defaultMTU, "")
  1051  	if err := s.CreateNIC(1, ep); err != nil {
  1052  		t.Fatal("CreateNIC failed:", err)
  1053  	}
  1054  	s.SetRouteTable([]tcpip.Route{})
  1055  
  1056  	// If there is no endpoint, it won't work.
  1057  	if _, err := s.FindRoute(1, header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */); err != tcpip.ErrNetworkUnreachable {
  1058  		t.Fatalf("got FindRoute(1, %s, %s, %d) = %s, want = %s", header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, err, tcpip.ErrNetworkUnreachable)
  1059  	}
  1060  
  1061  	protoAddr := tcpip.ProtocolAddress{Protocol: fakeNetNumber, AddressWithPrefix: tcpip.AddressWithPrefix{header.IPv4Any, 0}}
  1062  	if err := s.AddProtocolAddress(1, protoAddr); err != nil {
  1063  		t.Fatalf("AddProtocolAddress(1, %s) failed: %s", protoAddr, err)
  1064  	}
  1065  	r, err := s.FindRoute(1, header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */)
  1066  	if err != nil {
  1067  		t.Fatalf("FindRoute(1, %s, %s, %d) failed: %s", header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, err)
  1068  	}
  1069  	if err := verifyRoute(r, stack.Route{LocalAddress: header.IPv4Any, RemoteAddress: header.IPv4Broadcast}); err != nil {
  1070  		t.Errorf("FindRoute(1, %s, %s, %d) returned unexpected Route: %s)", header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, err)
  1071  	}
  1072  
  1073  	// If the NIC doesn't exist, it won't work.
  1074  	if _, err := s.FindRoute(2, header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */); err != tcpip.ErrNetworkUnreachable {
  1075  		t.Fatalf("got FindRoute(2, %s, %s, %d) = %s want = %s", header.IPv4Any, header.IPv4Broadcast, fakeNetNumber, err, tcpip.ErrNetworkUnreachable)
  1076  	}
  1077  }
  1078  
  1079  func TestOutgoingBroadcastWithRouteTable(t *testing.T) {
  1080  	defaultAddr := tcpip.AddressWithPrefix{header.IPv4Any, 0}
  1081  	// Local subnet on NIC1: 192.168.1.58/24, gateway 192.168.1.1.
  1082  	nic1Addr := tcpip.AddressWithPrefix{"\xc0\xa8\x01\x3a", 24}
  1083  	nic1Gateway := tcpip.Address("\xc0\xa8\x01\x01")
  1084  	// Local subnet on NIC2: 10.10.10.5/24, gateway 10.10.10.1.
  1085  	nic2Addr := tcpip.AddressWithPrefix{"\x0a\x0a\x0a\x05", 24}
  1086  	nic2Gateway := tcpip.Address("\x0a\x0a\x0a\x01")
  1087  
  1088  	// Create a new stack with two NICs.
  1089  	s := stack.New(stack.Options{
  1090  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1091  	})
  1092  	ep := channel.New(10, defaultMTU, "")
  1093  	if err := s.CreateNIC(1, ep); err != nil {
  1094  		t.Fatalf("CreateNIC failed: %s", err)
  1095  	}
  1096  	if err := s.CreateNIC(2, ep); err != nil {
  1097  		t.Fatalf("CreateNIC failed: %s", err)
  1098  	}
  1099  	nic1ProtoAddr := tcpip.ProtocolAddress{fakeNetNumber, nic1Addr}
  1100  	if err := s.AddProtocolAddress(1, nic1ProtoAddr); err != nil {
  1101  		t.Fatalf("AddProtocolAddress(1, %s) failed: %s", nic1ProtoAddr, err)
  1102  	}
  1103  
  1104  	nic2ProtoAddr := tcpip.ProtocolAddress{fakeNetNumber, nic2Addr}
  1105  	if err := s.AddProtocolAddress(2, nic2ProtoAddr); err != nil {
  1106  		t.Fatalf("AddAddress(2, %s) failed: %s", nic2ProtoAddr, err)
  1107  	}
  1108  
  1109  	// Set the initial route table.
  1110  	rt := []tcpip.Route{
  1111  		{Destination: nic1Addr.Subnet(), NIC: 1},
  1112  		{Destination: nic2Addr.Subnet(), NIC: 2},
  1113  		{Destination: defaultAddr.Subnet(), Gateway: nic2Gateway, NIC: 2},
  1114  		{Destination: defaultAddr.Subnet(), Gateway: nic1Gateway, NIC: 1},
  1115  	}
  1116  	s.SetRouteTable(rt)
  1117  
  1118  	// When an interface is given, the route for a broadcast goes through it.
  1119  	r, err := s.FindRoute(1, nic1Addr.Address, header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */)
  1120  	if err != nil {
  1121  		t.Fatalf("FindRoute(1, %s, %s, %d) failed: %s", nic1Addr.Address, header.IPv4Broadcast, fakeNetNumber, err)
  1122  	}
  1123  	if err := verifyRoute(r, stack.Route{LocalAddress: nic1Addr.Address, RemoteAddress: header.IPv4Broadcast}); err != nil {
  1124  		t.Errorf("FindRoute(1, %s, %s, %d) returned unexpected Route: %s)", nic1Addr.Address, header.IPv4Broadcast, fakeNetNumber, err)
  1125  	}
  1126  
  1127  	// When an interface is not given, it consults the route table.
  1128  	// 1. Case: Using the default route.
  1129  	r, err = s.FindRoute(0, "", header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */)
  1130  	if err != nil {
  1131  		t.Fatalf("FindRoute(0, \"\", %s, %d) failed: %s", header.IPv4Broadcast, fakeNetNumber, err)
  1132  	}
  1133  	if err := verifyRoute(r, stack.Route{LocalAddress: nic2Addr.Address, RemoteAddress: header.IPv4Broadcast}); err != nil {
  1134  		t.Errorf("FindRoute(0, \"\", %s, %d) returned unexpected Route: %s)", header.IPv4Broadcast, fakeNetNumber, err)
  1135  	}
  1136  
  1137  	// 2. Case: Having an explicit route for broadcast will select that one.
  1138  	rt = append(
  1139  		[]tcpip.Route{
  1140  			{Destination: tcpip.AddressWithPrefix{header.IPv4Broadcast, 8 * header.IPv4AddressSize}.Subnet(), NIC: 1},
  1141  		},
  1142  		rt...,
  1143  	)
  1144  	s.SetRouteTable(rt)
  1145  	r, err = s.FindRoute(0, "", header.IPv4Broadcast, fakeNetNumber, false /* multicastLoop */)
  1146  	if err != nil {
  1147  		t.Fatalf("FindRoute(0, \"\", %s, %d) failed: %s", header.IPv4Broadcast, fakeNetNumber, err)
  1148  	}
  1149  	if err := verifyRoute(r, stack.Route{LocalAddress: nic1Addr.Address, RemoteAddress: header.IPv4Broadcast}); err != nil {
  1150  		t.Errorf("FindRoute(0, \"\", %s, %d) returned unexpected Route: %s)", header.IPv4Broadcast, fakeNetNumber, err)
  1151  	}
  1152  }
  1153  
  1154  func TestMulticastOrIPv6LinkLocalNeedsNoRoute(t *testing.T) {
  1155  	for _, tc := range []struct {
  1156  		name        string
  1157  		routeNeeded bool
  1158  		address     tcpip.Address
  1159  	}{
  1160  		// IPv4 multicast address range: 224.0.0.0 - 239.255.255.255
  1161  		//                <=>  0xe0.0x00.0x00.0x00 - 0xef.0xff.0xff.0xff
  1162  		{"IPv4 Multicast 1", false, "\xe0\x00\x00\x00"},
  1163  		{"IPv4 Multicast 2", false, "\xef\xff\xff\xff"},
  1164  		{"IPv4 Unicast 1", true, "\xdf\xff\xff\xff"},
  1165  		{"IPv4 Unicast 2", true, "\xf0\x00\x00\x00"},
  1166  		{"IPv4 Unicast 3", true, "\x00\x00\x00\x00"},
  1167  
  1168  		// IPv6 multicast address is 0xff[8] + flags[4] + scope[4] + groupId[112]
  1169  		{"IPv6 Multicast 1", false, "\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1170  		{"IPv6 Multicast 2", false, "\xff\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1171  		{"IPv6 Multicast 3", false, "\xff\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"},
  1172  
  1173  		// IPv6 link-local address starts with fe80::/10.
  1174  		{"IPv6 Unicast Link-Local 1", false, "\xfe\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1175  		{"IPv6 Unicast Link-Local 2", false, "\xfe\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"},
  1176  		{"IPv6 Unicast Link-Local 3", false, "\xfe\x80\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff"},
  1177  		{"IPv6 Unicast Link-Local 4", false, "\xfe\xbf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1178  		{"IPv6 Unicast Link-Local 5", false, "\xfe\xbf\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"},
  1179  
  1180  		// IPv6 addresses that are neither multicast nor link-local.
  1181  		{"IPv6 Unicast Not Link-Local 1", true, "\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1182  		{"IPv6 Unicast Not Link-Local 2", true, "\xf0\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"},
  1183  		{"IPv6 Unicast Not Link-local 3", true, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1184  		{"IPv6 Unicast Not Link-Local 4", true, "\xfe\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1185  		{"IPv6 Unicast Not Link-Local 5", true, "\xfe\xdf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1186  		{"IPv6 Unicast Not Link-Local 6", true, "\xfd\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1187  		{"IPv6 Unicast Not Link-Local 7", true, "\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
  1188  	} {
  1189  		t.Run(tc.name, func(t *testing.T) {
  1190  			s := stack.New(stack.Options{
  1191  				NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1192  			})
  1193  
  1194  			ep := channel.New(10, defaultMTU, "")
  1195  			if err := s.CreateNIC(1, ep); err != nil {
  1196  				t.Fatal("CreateNIC failed:", err)
  1197  			}
  1198  
  1199  			s.SetRouteTable([]tcpip.Route{})
  1200  
  1201  			var anyAddr tcpip.Address
  1202  			if len(tc.address) == header.IPv4AddressSize {
  1203  				anyAddr = header.IPv4Any
  1204  			} else {
  1205  				anyAddr = header.IPv6Any
  1206  			}
  1207  
  1208  			want := tcpip.ErrNetworkUnreachable
  1209  			if tc.routeNeeded {
  1210  				want = tcpip.ErrNoRoute
  1211  			}
  1212  
  1213  			// If there is no endpoint, it won't work.
  1214  			if _, err := s.FindRoute(1, anyAddr, tc.address, fakeNetNumber, false /* multicastLoop */); err != want {
  1215  				t.Fatalf("got FindRoute(1, %v, %v, %v) = %v, want = %v", anyAddr, tc.address, fakeNetNumber, err, want)
  1216  			}
  1217  
  1218  			if err := s.AddAddress(1, fakeNetNumber, anyAddr); err != nil {
  1219  				t.Fatalf("AddAddress(%v, %v) failed: %v", fakeNetNumber, anyAddr, err)
  1220  			}
  1221  
  1222  			if r, err := s.FindRoute(1, anyAddr, tc.address, fakeNetNumber, false /* multicastLoop */); tc.routeNeeded {
  1223  				// Route table is empty but we need a route, this should cause an error.
  1224  				if err != tcpip.ErrNoRoute {
  1225  					t.Fatalf("got FindRoute(1, %v, %v, %v) = %v, want = %v", anyAddr, tc.address, fakeNetNumber, err, tcpip.ErrNoRoute)
  1226  				}
  1227  			} else {
  1228  				if err != nil {
  1229  					t.Fatalf("FindRoute(1, %v, %v, %v) failed: %v", anyAddr, tc.address, fakeNetNumber, err)
  1230  				}
  1231  				if r.LocalAddress != anyAddr {
  1232  					t.Errorf("Bad local address: got %v, want = %v", r.LocalAddress, anyAddr)
  1233  				}
  1234  				if r.RemoteAddress != tc.address {
  1235  					t.Errorf("Bad remote address: got %v, want = %v", r.RemoteAddress, tc.address)
  1236  				}
  1237  			}
  1238  			// If the NIC doesn't exist, it won't work.
  1239  			if _, err := s.FindRoute(2, anyAddr, tc.address, fakeNetNumber, false /* multicastLoop */); err != want {
  1240  				t.Fatalf("got FindRoute(2, %v, %v, %v) = %v want = %v", anyAddr, tc.address, fakeNetNumber, err, want)
  1241  			}
  1242  		})
  1243  	}
  1244  }
  1245  
  1246  // Add a range of addresses, then check that a packet is delivered.
  1247  func TestAddressRangeAcceptsMatchingPacket(t *testing.T) {
  1248  	s := stack.New(stack.Options{
  1249  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1250  	})
  1251  
  1252  	ep := channel.New(10, defaultMTU, "")
  1253  	if err := s.CreateNIC(1, ep); err != nil {
  1254  		t.Fatal("CreateNIC failed:", err)
  1255  	}
  1256  
  1257  	{
  1258  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
  1259  		if err != nil {
  1260  			t.Fatal(err)
  1261  		}
  1262  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
  1263  	}
  1264  
  1265  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
  1266  
  1267  	buf := buffer.NewView(30)
  1268  
  1269  	const localAddrByte byte = 0x01
  1270  	buf[0] = localAddrByte
  1271  	subnet, err := tcpip.NewSubnet(tcpip.Address("\x00"), tcpip.AddressMask("\xF0"))
  1272  	if err != nil {
  1273  		t.Fatal("NewSubnet failed:", err)
  1274  	}
  1275  	if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {
  1276  		t.Fatal("AddAddressRange failed:", err)
  1277  	}
  1278  
  1279  	testRecv(t, fakeNet, localAddrByte, ep, buf)
  1280  }
  1281  
  1282  func testNicForAddressRange(t *testing.T, nicID tcpip.NICID, s *stack.Stack, subnet tcpip.Subnet, rangeExists bool) {
  1283  	t.Helper()
  1284  
  1285  	// Loop over all addresses and check them.
  1286  	numOfAddresses := 1 << uint(8-subnet.Prefix())
  1287  	if numOfAddresses < 1 || numOfAddresses > 255 {
  1288  		t.Fatalf("got numOfAddresses = %d, want = [1 .. 255] (subnet=%s)", numOfAddresses, subnet)
  1289  	}
  1290  
  1291  	addrBytes := []byte(subnet.ID())
  1292  	for i := 0; i < numOfAddresses; i++ {
  1293  		addr := tcpip.Address(addrBytes)
  1294  		wantNicID := nicID
  1295  		// The subnet and broadcast addresses are skipped.
  1296  		if !rangeExists || addr == subnet.ID() || addr == subnet.Broadcast() {
  1297  			wantNicID = 0
  1298  		}
  1299  		if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, addr); gotNicID != wantNicID {
  1300  			t.Errorf("got CheckLocalAddress(0, %d, %s) = %d, want = %d", fakeNetNumber, addr, gotNicID, wantNicID)
  1301  		}
  1302  		addrBytes[0]++
  1303  	}
  1304  
  1305  	// Trying the next address should always fail since it is outside the range.
  1306  	if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addrBytes)); gotNicID != 0 {
  1307  		t.Errorf("got CheckLocalAddress(0, %d, %s) = %d, want = %d", fakeNetNumber, tcpip.Address(addrBytes), gotNicID, 0)
  1308  	}
  1309  }
  1310  
  1311  // Set a range of addresses, then remove it again, and check at each step that
  1312  // CheckLocalAddress returns the correct NIC for each address or zero if not
  1313  // existent.
  1314  func TestCheckLocalAddressForSubnet(t *testing.T) {
  1315  	const nicID tcpip.NICID = 1
  1316  	s := stack.New(stack.Options{
  1317  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1318  	})
  1319  
  1320  	ep := channel.New(10, defaultMTU, "")
  1321  	if err := s.CreateNIC(nicID, ep); err != nil {
  1322  		t.Fatal("CreateNIC failed:", err)
  1323  	}
  1324  
  1325  	{
  1326  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
  1327  		if err != nil {
  1328  			t.Fatal(err)
  1329  		}
  1330  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: nicID}})
  1331  	}
  1332  
  1333  	subnet, err := tcpip.NewSubnet(tcpip.Address("\xa0"), tcpip.AddressMask("\xf0"))
  1334  	if err != nil {
  1335  		t.Fatal("NewSubnet failed:", err)
  1336  	}
  1337  
  1338  	testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)
  1339  
  1340  	if err := s.AddAddressRange(nicID, fakeNetNumber, subnet); err != nil {
  1341  		t.Fatal("AddAddressRange failed:", err)
  1342  	}
  1343  
  1344  	testNicForAddressRange(t, nicID, s, subnet, true /* rangeExists */)
  1345  
  1346  	if err := s.RemoveAddressRange(nicID, subnet); err != nil {
  1347  		t.Fatal("RemoveAddressRange failed:", err)
  1348  	}
  1349  
  1350  	testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)
  1351  }
  1352  
  1353  // Set a range of addresses, then send a packet to a destination outside the
  1354  // range and then check it doesn't get delivered.
  1355  func TestAddressRangeRejectsNonmatchingPacket(t *testing.T) {
  1356  	s := stack.New(stack.Options{
  1357  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1358  	})
  1359  
  1360  	ep := channel.New(10, defaultMTU, "")
  1361  	if err := s.CreateNIC(1, ep); err != nil {
  1362  		t.Fatal("CreateNIC failed:", err)
  1363  	}
  1364  
  1365  	{
  1366  		subnet, err := tcpip.NewSubnet("\x00", "\x00")
  1367  		if err != nil {
  1368  			t.Fatal(err)
  1369  		}
  1370  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
  1371  	}
  1372  
  1373  	fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)
  1374  
  1375  	buf := buffer.NewView(30)
  1376  
  1377  	const localAddrByte byte = 0x01
  1378  	buf[0] = localAddrByte
  1379  	subnet, err := tcpip.NewSubnet(tcpip.Address("\x10"), tcpip.AddressMask("\xF0"))
  1380  	if err != nil {
  1381  		t.Fatal("NewSubnet failed:", err)
  1382  	}
  1383  	if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {
  1384  		t.Fatal("AddAddressRange failed:", err)
  1385  	}
  1386  	testFailingRecv(t, fakeNet, localAddrByte, ep, buf)
  1387  }
  1388  
  1389  func TestNetworkOptions(t *testing.T) {
  1390  	s := stack.New(stack.Options{
  1391  		NetworkProtocols:   []stack.NetworkProtocol{fakeNetFactory()},
  1392  		TransportProtocols: []stack.TransportProtocol{},
  1393  	})
  1394  
  1395  	// Try an unsupported network protocol.
  1396  	if err := s.SetNetworkProtocolOption(tcpip.NetworkProtocolNumber(99999), fakeNetGoodOption(false)); err != tcpip.ErrUnknownProtocol {
  1397  		t.Fatalf("SetNetworkProtocolOption(fakeNet2, blah, false) = %v, want = tcpip.ErrUnknownProtocol", err)
  1398  	}
  1399  
  1400  	testCases := []struct {
  1401  		option   interface{}
  1402  		wantErr  *tcpip.Error
  1403  		verifier func(t *testing.T, p stack.NetworkProtocol)
  1404  	}{
  1405  		{fakeNetGoodOption(true), nil, func(t *testing.T, p stack.NetworkProtocol) {
  1406  			t.Helper()
  1407  			fakeNet := p.(*fakeNetworkProtocol)
  1408  			if fakeNet.opts.good != true {
  1409  				t.Fatalf("fakeNet.opts.good = false, want = true")
  1410  			}
  1411  			var v fakeNetGoodOption
  1412  			if err := s.NetworkProtocolOption(fakeNetNumber, &v); err != nil {
  1413  				t.Fatalf("s.NetworkProtocolOption(fakeNetNumber, &v) = %v, want = nil, where v is option %T", v, err)
  1414  			}
  1415  			if v != true {
  1416  				t.Fatalf("s.NetworkProtocolOption(fakeNetNumber, &v) returned v = %v, want = true", v)
  1417  			}
  1418  		}},
  1419  		{fakeNetBadOption(true), tcpip.ErrUnknownProtocolOption, nil},
  1420  		{fakeNetInvalidValueOption(1), tcpip.ErrInvalidOptionValue, nil},
  1421  	}
  1422  	for _, tc := range testCases {
  1423  		if got := s.SetNetworkProtocolOption(fakeNetNumber, tc.option); got != tc.wantErr {
  1424  			t.Errorf("s.SetNetworkProtocolOption(fakeNet, %v) = %v, want = %v", tc.option, got, tc.wantErr)
  1425  		}
  1426  		if tc.verifier != nil {
  1427  			tc.verifier(t, s.NetworkProtocolInstance(fakeNetNumber))
  1428  		}
  1429  	}
  1430  }
  1431  
  1432  func stackContainsAddressRange(s *stack.Stack, id tcpip.NICID, addrRange tcpip.Subnet) bool {
  1433  	ranges, ok := s.NICAddressRanges()[id]
  1434  	if !ok {
  1435  		return false
  1436  	}
  1437  	for _, r := range ranges {
  1438  		if r == addrRange {
  1439  			return true
  1440  		}
  1441  	}
  1442  	return false
  1443  }
  1444  
  1445  func TestAddresRangeAddRemove(t *testing.T) {
  1446  	s := stack.New(stack.Options{
  1447  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1448  	})
  1449  	ep := channel.New(10, defaultMTU, "")
  1450  	if err := s.CreateNIC(1, ep); err != nil {
  1451  		t.Fatal("CreateNIC failed:", err)
  1452  	}
  1453  
  1454  	addr := tcpip.Address("\x01\x01\x01\x01")
  1455  	mask := tcpip.AddressMask(strings.Repeat("\xff", len(addr)))
  1456  	addrRange, err := tcpip.NewSubnet(addr, mask)
  1457  	if err != nil {
  1458  		t.Fatal("NewSubnet failed:", err)
  1459  	}
  1460  
  1461  	if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {
  1462  		t.Fatalf("got stackContainsAddressRange(...) = %t, want = %t", got, want)
  1463  	}
  1464  
  1465  	if err := s.AddAddressRange(1, fakeNetNumber, addrRange); err != nil {
  1466  		t.Fatal("AddAddressRange failed:", err)
  1467  	}
  1468  
  1469  	if got, want := stackContainsAddressRange(s, 1, addrRange), true; got != want {
  1470  		t.Fatalf("got stackContainsAddressRange(...) = %t, want = %t", got, want)
  1471  	}
  1472  
  1473  	if err := s.RemoveAddressRange(1, addrRange); err != nil {
  1474  		t.Fatal("RemoveAddressRange failed:", err)
  1475  	}
  1476  
  1477  	if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {
  1478  		t.Fatalf("got stackContainsAddressRange(...) = %t, want = %t", got, want)
  1479  	}
  1480  }
  1481  
  1482  func TestGetMainNICAddressAddPrimaryNonPrimary(t *testing.T) {
  1483  	for _, addrLen := range []int{4, 16} {
  1484  		t.Run(fmt.Sprintf("addrLen=%d", addrLen), func(t *testing.T) {
  1485  			for canBe := 0; canBe < 3; canBe++ {
  1486  				t.Run(fmt.Sprintf("canBe=%d", canBe), func(t *testing.T) {
  1487  					for never := 0; never < 3; never++ {
  1488  						t.Run(fmt.Sprintf("never=%d", never), func(t *testing.T) {
  1489  							s := stack.New(stack.Options{
  1490  								NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1491  							})
  1492  							ep := channel.New(10, defaultMTU, "")
  1493  							if err := s.CreateNIC(1, ep); err != nil {
  1494  								t.Fatal("CreateNIC failed:", err)
  1495  							}
  1496  							// Insert <canBe> primary and <never> never-primary addresses.
  1497  							// Each one will add a network endpoint to the NIC.
  1498  							primaryAddrAdded := make(map[tcpip.AddressWithPrefix]struct{})
  1499  							for i := 0; i < canBe+never; i++ {
  1500  								var behavior stack.PrimaryEndpointBehavior
  1501  								if i < canBe {
  1502  									behavior = stack.CanBePrimaryEndpoint
  1503  								} else {
  1504  									behavior = stack.NeverPrimaryEndpoint
  1505  								}
  1506  								// Add an address and in case of a primary one include a
  1507  								// prefixLen.
  1508  								address := tcpip.Address(bytes.Repeat([]byte{byte(i)}, addrLen))
  1509  								if behavior == stack.CanBePrimaryEndpoint {
  1510  									protocolAddress := tcpip.ProtocolAddress{
  1511  										Protocol: fakeNetNumber,
  1512  										AddressWithPrefix: tcpip.AddressWithPrefix{
  1513  											Address:   address,
  1514  											PrefixLen: addrLen * 8,
  1515  										},
  1516  									}
  1517  									if err := s.AddProtocolAddressWithOptions(1, protocolAddress, behavior); err != nil {
  1518  										t.Fatal("AddProtocolAddressWithOptions failed:", err)
  1519  									}
  1520  									// Remember the address/prefix.
  1521  									primaryAddrAdded[protocolAddress.AddressWithPrefix] = struct{}{}
  1522  								} else {
  1523  									if err := s.AddAddressWithOptions(1, fakeNetNumber, address, behavior); err != nil {
  1524  										t.Fatal("AddAddressWithOptions failed:", err)
  1525  									}
  1526  								}
  1527  							}
  1528  							// Check that GetMainNICAddress returns an address if at least
  1529  							// one primary address was added. In that case make sure the
  1530  							// address/prefixLen matches what we added.
  1531  							gotAddr, err := s.GetMainNICAddress(1, fakeNetNumber)
  1532  							if err != nil {
  1533  								t.Fatal("GetMainNICAddress failed:", err)
  1534  							}
  1535  							if len(primaryAddrAdded) == 0 {
  1536  								// No primary addresses present.
  1537  								if wantAddr := (tcpip.AddressWithPrefix{}); gotAddr != wantAddr {
  1538  									t.Fatalf("GetMainNICAddress: got addr = %s, want = %s", gotAddr, wantAddr)
  1539  								}
  1540  							} else {
  1541  								// At least one primary address was added, verify the returned
  1542  								// address is in the list of primary addresses we added.
  1543  								if _, ok := primaryAddrAdded[gotAddr]; !ok {
  1544  									t.Fatalf("GetMainNICAddress: got = %s, want any in {%v}", gotAddr, primaryAddrAdded)
  1545  								}
  1546  							}
  1547  						})
  1548  					}
  1549  				})
  1550  			}
  1551  		})
  1552  	}
  1553  }
  1554  
  1555  func TestGetMainNICAddressAddRemove(t *testing.T) {
  1556  	s := stack.New(stack.Options{
  1557  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1558  	})
  1559  	ep := channel.New(10, defaultMTU, "")
  1560  	if err := s.CreateNIC(1, ep); err != nil {
  1561  		t.Fatal("CreateNIC failed:", err)
  1562  	}
  1563  
  1564  	for _, tc := range []struct {
  1565  		name      string
  1566  		address   tcpip.Address
  1567  		prefixLen int
  1568  	}{
  1569  		{"IPv4", "\x01\x01\x01\x01", 24},
  1570  		{"IPv6", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 116},
  1571  	} {
  1572  		t.Run(tc.name, func(t *testing.T) {
  1573  			protocolAddress := tcpip.ProtocolAddress{
  1574  				Protocol: fakeNetNumber,
  1575  				AddressWithPrefix: tcpip.AddressWithPrefix{
  1576  					Address:   tc.address,
  1577  					PrefixLen: tc.prefixLen,
  1578  				},
  1579  			}
  1580  			if err := s.AddProtocolAddress(1, protocolAddress); err != nil {
  1581  				t.Fatal("AddProtocolAddress failed:", err)
  1582  			}
  1583  
  1584  			// Check that we get the right initial address and prefix length.
  1585  			gotAddr, err := s.GetMainNICAddress(1, fakeNetNumber)
  1586  			if err != nil {
  1587  				t.Fatal("GetMainNICAddress failed:", err)
  1588  			}
  1589  			if wantAddr := protocolAddress.AddressWithPrefix; gotAddr != wantAddr {
  1590  				t.Fatalf("got s.GetMainNICAddress(...) = %s, want = %s", gotAddr, wantAddr)
  1591  			}
  1592  
  1593  			if err := s.RemoveAddress(1, protocolAddress.AddressWithPrefix.Address); err != nil {
  1594  				t.Fatal("RemoveAddress failed:", err)
  1595  			}
  1596  
  1597  			// Check that we get no address after removal.
  1598  			gotAddr, err = s.GetMainNICAddress(1, fakeNetNumber)
  1599  			if err != nil {
  1600  				t.Fatal("GetMainNICAddress failed:", err)
  1601  			}
  1602  			if wantAddr := (tcpip.AddressWithPrefix{}); gotAddr != wantAddr {
  1603  				t.Fatalf("got GetMainNICAddress(...) = %s, want = %s", gotAddr, wantAddr)
  1604  			}
  1605  		})
  1606  	}
  1607  }
  1608  
  1609  // Simple network address generator. Good for 255 addresses.
  1610  type addressGenerator struct{ cnt byte }
  1611  
  1612  func (g *addressGenerator) next(addrLen int) tcpip.Address {
  1613  	g.cnt++
  1614  	return tcpip.Address(bytes.Repeat([]byte{g.cnt}, addrLen))
  1615  }
  1616  
  1617  func verifyAddresses(t *testing.T, expectedAddresses, gotAddresses []tcpip.ProtocolAddress) {
  1618  	t.Helper()
  1619  
  1620  	if len(gotAddresses) != len(expectedAddresses) {
  1621  		t.Fatalf("got len(addresses) = %d, want = %d", len(gotAddresses), len(expectedAddresses))
  1622  	}
  1623  
  1624  	sort.Slice(gotAddresses, func(i, j int) bool {
  1625  		return gotAddresses[i].AddressWithPrefix.Address < gotAddresses[j].AddressWithPrefix.Address
  1626  	})
  1627  	sort.Slice(expectedAddresses, func(i, j int) bool {
  1628  		return expectedAddresses[i].AddressWithPrefix.Address < expectedAddresses[j].AddressWithPrefix.Address
  1629  	})
  1630  
  1631  	for i, gotAddr := range gotAddresses {
  1632  		expectedAddr := expectedAddresses[i]
  1633  		if gotAddr != expectedAddr {
  1634  			t.Errorf("got address = %+v, wanted = %+v", gotAddr, expectedAddr)
  1635  		}
  1636  	}
  1637  }
  1638  
  1639  func TestAddAddress(t *testing.T) {
  1640  	const nicid = 1
  1641  	s := stack.New(stack.Options{
  1642  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1643  	})
  1644  	ep := channel.New(10, defaultMTU, "")
  1645  	if err := s.CreateNIC(nicid, ep); err != nil {
  1646  		t.Fatal("CreateNIC failed:", err)
  1647  	}
  1648  
  1649  	var addrGen addressGenerator
  1650  	expectedAddresses := make([]tcpip.ProtocolAddress, 0, 2)
  1651  	for _, addrLen := range []int{4, 16} {
  1652  		address := addrGen.next(addrLen)
  1653  		if err := s.AddAddress(nicid, fakeNetNumber, address); err != nil {
  1654  			t.Fatalf("AddAddress(address=%s) failed: %s", address, err)
  1655  		}
  1656  		expectedAddresses = append(expectedAddresses, tcpip.ProtocolAddress{
  1657  			Protocol:          fakeNetNumber,
  1658  			AddressWithPrefix: tcpip.AddressWithPrefix{address, fakeDefaultPrefixLen},
  1659  		})
  1660  	}
  1661  
  1662  	gotAddresses := s.AllAddresses()[nicid]
  1663  	verifyAddresses(t, expectedAddresses, gotAddresses)
  1664  }
  1665  
  1666  func TestAddProtocolAddress(t *testing.T) {
  1667  	const nicid = 1
  1668  	s := stack.New(stack.Options{
  1669  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1670  	})
  1671  	ep := channel.New(10, defaultMTU, "")
  1672  	if err := s.CreateNIC(nicid, ep); err != nil {
  1673  		t.Fatal("CreateNIC failed:", err)
  1674  	}
  1675  
  1676  	var addrGen addressGenerator
  1677  	addrLenRange := []int{4, 16}
  1678  	prefixLenRange := []int{8, 13, 20, 32}
  1679  	expectedAddresses := make([]tcpip.ProtocolAddress, 0, len(addrLenRange)*len(prefixLenRange))
  1680  	for _, addrLen := range addrLenRange {
  1681  		for _, prefixLen := range prefixLenRange {
  1682  			protocolAddress := tcpip.ProtocolAddress{
  1683  				Protocol: fakeNetNumber,
  1684  				AddressWithPrefix: tcpip.AddressWithPrefix{
  1685  					Address:   addrGen.next(addrLen),
  1686  					PrefixLen: prefixLen,
  1687  				},
  1688  			}
  1689  			if err := s.AddProtocolAddress(nicid, protocolAddress); err != nil {
  1690  				t.Errorf("AddProtocolAddress(%+v) failed: %s", protocolAddress, err)
  1691  			}
  1692  			expectedAddresses = append(expectedAddresses, protocolAddress)
  1693  		}
  1694  	}
  1695  
  1696  	gotAddresses := s.AllAddresses()[nicid]
  1697  	verifyAddresses(t, expectedAddresses, gotAddresses)
  1698  }
  1699  
  1700  func TestAddAddressWithOptions(t *testing.T) {
  1701  	const nicid = 1
  1702  	s := stack.New(stack.Options{
  1703  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1704  	})
  1705  	ep := channel.New(10, defaultMTU, "")
  1706  	if err := s.CreateNIC(nicid, ep); err != nil {
  1707  		t.Fatal("CreateNIC failed:", err)
  1708  	}
  1709  
  1710  	addrLenRange := []int{4, 16}
  1711  	behaviorRange := []stack.PrimaryEndpointBehavior{stack.CanBePrimaryEndpoint, stack.FirstPrimaryEndpoint, stack.NeverPrimaryEndpoint}
  1712  	expectedAddresses := make([]tcpip.ProtocolAddress, 0, len(addrLenRange)*len(behaviorRange))
  1713  	var addrGen addressGenerator
  1714  	for _, addrLen := range addrLenRange {
  1715  		for _, behavior := range behaviorRange {
  1716  			address := addrGen.next(addrLen)
  1717  			if err := s.AddAddressWithOptions(nicid, fakeNetNumber, address, behavior); err != nil {
  1718  				t.Fatalf("AddAddressWithOptions(address=%s, behavior=%d) failed: %s", address, behavior, err)
  1719  			}
  1720  			expectedAddresses = append(expectedAddresses, tcpip.ProtocolAddress{
  1721  				Protocol:          fakeNetNumber,
  1722  				AddressWithPrefix: tcpip.AddressWithPrefix{address, fakeDefaultPrefixLen},
  1723  			})
  1724  		}
  1725  	}
  1726  
  1727  	gotAddresses := s.AllAddresses()[nicid]
  1728  	verifyAddresses(t, expectedAddresses, gotAddresses)
  1729  }
  1730  
  1731  func TestAddProtocolAddressWithOptions(t *testing.T) {
  1732  	const nicid = 1
  1733  	s := stack.New(stack.Options{
  1734  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1735  	})
  1736  	ep := channel.New(10, defaultMTU, "")
  1737  	if err := s.CreateNIC(nicid, ep); err != nil {
  1738  		t.Fatal("CreateNIC failed:", err)
  1739  	}
  1740  
  1741  	addrLenRange := []int{4, 16}
  1742  	prefixLenRange := []int{8, 13, 20, 32}
  1743  	behaviorRange := []stack.PrimaryEndpointBehavior{stack.CanBePrimaryEndpoint, stack.FirstPrimaryEndpoint, stack.NeverPrimaryEndpoint}
  1744  	expectedAddresses := make([]tcpip.ProtocolAddress, 0, len(addrLenRange)*len(prefixLenRange)*len(behaviorRange))
  1745  	var addrGen addressGenerator
  1746  	for _, addrLen := range addrLenRange {
  1747  		for _, prefixLen := range prefixLenRange {
  1748  			for _, behavior := range behaviorRange {
  1749  				protocolAddress := tcpip.ProtocolAddress{
  1750  					Protocol: fakeNetNumber,
  1751  					AddressWithPrefix: tcpip.AddressWithPrefix{
  1752  						Address:   addrGen.next(addrLen),
  1753  						PrefixLen: prefixLen,
  1754  					},
  1755  				}
  1756  				if err := s.AddProtocolAddressWithOptions(nicid, protocolAddress, behavior); err != nil {
  1757  					t.Fatalf("AddProtocolAddressWithOptions(%+v, %d) failed: %s", protocolAddress, behavior, err)
  1758  				}
  1759  				expectedAddresses = append(expectedAddresses, protocolAddress)
  1760  			}
  1761  		}
  1762  	}
  1763  
  1764  	gotAddresses := s.AllAddresses()[nicid]
  1765  	verifyAddresses(t, expectedAddresses, gotAddresses)
  1766  }
  1767  
  1768  func TestNICStats(t *testing.T) {
  1769  	s := stack.New(stack.Options{
  1770  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1771  	})
  1772  	ep1 := channel.New(10, defaultMTU, "")
  1773  	if err := s.CreateNIC(1, ep1); err != nil {
  1774  		t.Fatal("CreateNIC failed: ", err)
  1775  	}
  1776  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
  1777  		t.Fatal("AddAddress failed:", err)
  1778  	}
  1779  	// Route all packets for address \x01 to NIC 1.
  1780  	{
  1781  		subnet, err := tcpip.NewSubnet("\x01", "\xff")
  1782  		if err != nil {
  1783  			t.Fatal(err)
  1784  		}
  1785  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 1}})
  1786  	}
  1787  
  1788  	// Send a packet to address 1.
  1789  	buf := buffer.NewView(30)
  1790  	ep1.Inject(fakeNetNumber, buf.ToVectorisedView())
  1791  	if got, want := s.NICInfo()[1].Stats.Rx.Packets.Value(), uint64(1); got != want {
  1792  		t.Errorf("got Rx.Packets.Value() = %d, want = %d", got, want)
  1793  	}
  1794  
  1795  	if got, want := s.NICInfo()[1].Stats.Rx.Bytes.Value(), uint64(len(buf)); got != want {
  1796  		t.Errorf("got Rx.Bytes.Value() = %d, want = %d", got, want)
  1797  	}
  1798  
  1799  	payload := buffer.NewView(10)
  1800  	// Write a packet out via the address for NIC 1
  1801  	if err := sendTo(s, "\x01", payload); err != nil {
  1802  		t.Fatal("sendTo failed: ", err)
  1803  	}
  1804  	want := uint64(ep1.Drain())
  1805  	if got := s.NICInfo()[1].Stats.Tx.Packets.Value(); got != want {
  1806  		t.Errorf("got Tx.Packets.Value() = %d, ep1.Drain() = %d", got, want)
  1807  	}
  1808  
  1809  	if got, want := s.NICInfo()[1].Stats.Tx.Bytes.Value(), uint64(len(payload)); got != want {
  1810  		t.Errorf("got Tx.Bytes.Value() = %d, want = %d", got, want)
  1811  	}
  1812  }
  1813  
  1814  func TestNICForwarding(t *testing.T) {
  1815  	// Create a stack with the fake network protocol, two NICs, each with
  1816  	// an address.
  1817  	s := stack.New(stack.Options{
  1818  		NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},
  1819  	})
  1820  	s.SetForwarding(true)
  1821  
  1822  	ep1 := channel.New(10, defaultMTU, "")
  1823  	if err := s.CreateNIC(1, ep1); err != nil {
  1824  		t.Fatal("CreateNIC #1 failed:", err)
  1825  	}
  1826  	if err := s.AddAddress(1, fakeNetNumber, "\x01"); err != nil {
  1827  		t.Fatal("AddAddress #1 failed:", err)
  1828  	}
  1829  
  1830  	ep2 := channel.New(10, defaultMTU, "")
  1831  	if err := s.CreateNIC(2, ep2); err != nil {
  1832  		t.Fatal("CreateNIC #2 failed:", err)
  1833  	}
  1834  	if err := s.AddAddress(2, fakeNetNumber, "\x02"); err != nil {
  1835  		t.Fatal("AddAddress #2 failed:", err)
  1836  	}
  1837  
  1838  	// Route all packets to address 3 to NIC 2.
  1839  	{
  1840  		subnet, err := tcpip.NewSubnet("\x03", "\xff")
  1841  		if err != nil {
  1842  			t.Fatal(err)
  1843  		}
  1844  		s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: "\x00", NIC: 2}})
  1845  	}
  1846  
  1847  	// Send a packet to address 3.
  1848  	buf := buffer.NewView(30)
  1849  	buf[0] = 3
  1850  	ep1.Inject(fakeNetNumber, buf.ToVectorisedView())
  1851  
  1852  	select {
  1853  	case <-ep2.C:
  1854  	default:
  1855  		t.Fatal("Packet not forwarded")
  1856  	}
  1857  
  1858  	// Test that forwarding increments Tx stats correctly.
  1859  	if got, want := s.NICInfo()[2].Stats.Tx.Packets.Value(), uint64(1); got != want {
  1860  		t.Errorf("got Tx.Packets.Value() = %d, want = %d", got, want)
  1861  	}
  1862  
  1863  	if got, want := s.NICInfo()[2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {
  1864  		t.Errorf("got Tx.Bytes.Value() = %d, want = %d", got, want)
  1865  	}
  1866  }