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