github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/tcpip/header/ipv4.go (about)

     1  // Copyright 2021 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 header
    16  
    17  import (
    18  	"encoding/binary"
    19  	"fmt"
    20  	"time"
    21  
    22  	"github.com/MerlinKodo/gvisor/pkg/tcpip"
    23  	"github.com/MerlinKodo/gvisor/pkg/tcpip/checksum"
    24  )
    25  
    26  // RFC 971 defines the fields of the IPv4 header on page 11 using the following
    27  // diagram: ("Figure 4")
    28  //
    29  //	 0                   1                   2                   3
    30  //	 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    31  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    32  //	|Version|  IHL  |Type of Service|          Total Length         |
    33  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    34  //	|         Identification        |Flags|      Fragment Offset    |
    35  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    36  //	|  Time to Live |    Protocol   |         Header Checksum       |
    37  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    38  //	|                       Source Address                          |
    39  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    40  //	|                    Destination Address                        |
    41  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    42  //	|                    Options                    |    Padding    |
    43  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    44  const (
    45  	versIHL = 0
    46  	tos     = 1
    47  	// IPv4TotalLenOffset is the offset of the total length field in the
    48  	// IPv4 header.
    49  	IPv4TotalLenOffset = 2
    50  	id                 = 4
    51  	flagsFO            = 6
    52  	ttl                = 8
    53  	protocol           = 9
    54  	xsum               = 10
    55  	srcAddr            = 12
    56  	dstAddr            = 16
    57  	options            = 20
    58  )
    59  
    60  // IPv4Fields contains the fields of an IPv4 packet. It is used to describe the
    61  // fields of a packet that needs to be encoded. The IHL field is not here as
    62  // it is totally defined by the size of the options.
    63  type IPv4Fields struct {
    64  	// TOS is the "type of service" field of an IPv4 packet.
    65  	TOS uint8
    66  
    67  	// TotalLength is the "total length" field of an IPv4 packet.
    68  	TotalLength uint16
    69  
    70  	// ID is the "identification" field of an IPv4 packet.
    71  	ID uint16
    72  
    73  	// Flags is the "flags" field of an IPv4 packet.
    74  	Flags uint8
    75  
    76  	// FragmentOffset is the "fragment offset" field of an IPv4 packet.
    77  	FragmentOffset uint16
    78  
    79  	// TTL is the "time to live" field of an IPv4 packet.
    80  	TTL uint8
    81  
    82  	// Protocol is the "protocol" field of an IPv4 packet.
    83  	Protocol uint8
    84  
    85  	// Checksum is the "checksum" field of an IPv4 packet.
    86  	Checksum uint16
    87  
    88  	// SrcAddr is the "source ip address" of an IPv4 packet.
    89  	SrcAddr tcpip.Address
    90  
    91  	// DstAddr is the "destination ip address" of an IPv4 packet.
    92  	DstAddr tcpip.Address
    93  
    94  	// Options must be 40 bytes or less as they must fit along with the
    95  	// rest of the IPv4 header into the maximum size describable in the
    96  	// IHL field. RFC 791 section 3.1 says:
    97  	//    IHL:  4 bits
    98  	//
    99  	//    Internet Header Length is the length of the internet header in 32
   100  	//    bit words, and thus points to the beginning of the data.  Note that
   101  	//    the minimum value for a correct header is 5.
   102  	//
   103  	// That leaves ten 32 bit (4 byte) fields for options. An attempt to encode
   104  	// more will fail.
   105  	Options IPv4OptionsSerializer
   106  }
   107  
   108  // IPv4 is an IPv4 header.
   109  // Most of the methods of IPv4 access to the underlying slice without
   110  // checking the boundaries and could panic because of 'index out of range'.
   111  // Always call IsValid() to validate an instance of IPv4 before using other
   112  // methods.
   113  type IPv4 []byte
   114  
   115  const (
   116  	// IPv4MinimumSize is the minimum size of a valid IPv4 packet;
   117  	// i.e. a packet header with no options.
   118  	IPv4MinimumSize = 20
   119  
   120  	// IPv4MaximumHeaderSize is the maximum size of an IPv4 header. Given
   121  	// that there are only 4 bits (max 0xF (15)) to represent the header length
   122  	// in 32-bit (4 byte) units, the header cannot exceed 15*4 = 60 bytes.
   123  	IPv4MaximumHeaderSize = 60
   124  
   125  	// IPv4MaximumOptionsSize is the largest size the IPv4 options can be.
   126  	IPv4MaximumOptionsSize = IPv4MaximumHeaderSize - IPv4MinimumSize
   127  
   128  	// IPv4MaximumPayloadSize is the maximum size of a valid IPv4 payload.
   129  	//
   130  	// Linux limits this to 65,515 octets (the max IP datagram size - the IPv4
   131  	// header size). But RFC 791 section 3.2 discusses the design of the IPv4
   132  	// fragment "allows 2**13 = 8192 fragments of 8 octets each for a total of
   133  	// 65,536 octets. Note that this is consistent with the datagram total
   134  	// length field (of course, the header is counted in the total length and not
   135  	// in the fragments)."
   136  	IPv4MaximumPayloadSize = 65536
   137  
   138  	// MinIPFragmentPayloadSize is the minimum number of payload bytes that
   139  	// the first fragment must carry when an IPv4 packet is fragmented.
   140  	MinIPFragmentPayloadSize = 8
   141  
   142  	// IPv4AddressSize is the size, in bytes, of an IPv4 address.
   143  	IPv4AddressSize = 4
   144  
   145  	// IPv4AddressSizeBits is the size, in bits, of an IPv4 address.
   146  	IPv4AddressSizeBits = 32
   147  
   148  	// IPv4ProtocolNumber is IPv4's network protocol number.
   149  	IPv4ProtocolNumber tcpip.NetworkProtocolNumber = 0x0800
   150  
   151  	// IPv4Version is the version of the IPv4 protocol.
   152  	IPv4Version = 4
   153  
   154  	// IPv4MinimumProcessableDatagramSize is the minimum size of an IP
   155  	// packet that every IPv4 capable host must be able to
   156  	// process/reassemble.
   157  	IPv4MinimumProcessableDatagramSize = 576
   158  
   159  	// IPv4MinimumMTU is the minimum MTU required by IPv4, per RFC 791,
   160  	// section 3.2:
   161  	//   Every internet module must be able to forward a datagram of 68 octets
   162  	//   without further fragmentation.  This is because an internet header may be
   163  	//   up to 60 octets, and the minimum fragment is 8 octets.
   164  	IPv4MinimumMTU = 68
   165  )
   166  
   167  var (
   168  	// IPv4AllSystems is the all systems IPv4 multicast address as per
   169  	// IANA's IPv4 Multicast Address Space Registry. See
   170  	// https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml.
   171  	IPv4AllSystems = tcpip.AddrFrom4([4]byte{0xe0, 0x00, 0x00, 0x01})
   172  
   173  	// IPv4Broadcast is the broadcast address of the IPv4 procotol.
   174  	IPv4Broadcast = tcpip.AddrFrom4([4]byte{0xff, 0xff, 0xff, 0xff})
   175  
   176  	// IPv4Any is the non-routable IPv4 "any" meta address.
   177  	IPv4Any = tcpip.AddrFrom4([4]byte{0x00, 0x00, 0x00, 0x00})
   178  
   179  	// IPv4AllRoutersGroup is a multicast address for all routers.
   180  	IPv4AllRoutersGroup = tcpip.AddrFrom4([4]byte{0xe0, 0x00, 0x00, 0x02})
   181  )
   182  
   183  // Flags that may be set in an IPv4 packet.
   184  const (
   185  	IPv4FlagMoreFragments = 1 << iota
   186  	IPv4FlagDontFragment
   187  )
   188  
   189  // ipv4LinkLocalUnicastSubnet is the IPv4 link local unicast subnet as defined
   190  // by RFC 3927 section 1.
   191  var ipv4LinkLocalUnicastSubnet = func() tcpip.Subnet {
   192  	subnet, err := tcpip.NewSubnet(tcpip.AddrFrom4([4]byte{0xa9, 0xfe, 0x00, 0x00}), tcpip.MaskFrom("\xff\xff\x00\x00"))
   193  	if err != nil {
   194  		panic(err)
   195  	}
   196  	return subnet
   197  }()
   198  
   199  // ipv4LinkLocalMulticastSubnet is the IPv4 link local multicast subnet as
   200  // defined by RFC 5771 section 4.
   201  var ipv4LinkLocalMulticastSubnet = func() tcpip.Subnet {
   202  	subnet, err := tcpip.NewSubnet(tcpip.AddrFrom4([4]byte{0xe0, 0x00, 0x00, 0x00}), tcpip.MaskFrom("\xff\xff\xff\x00"))
   203  	if err != nil {
   204  		panic(err)
   205  	}
   206  	return subnet
   207  }()
   208  
   209  // IPv4EmptySubnet is the empty IPv4 subnet.
   210  var IPv4EmptySubnet = func() tcpip.Subnet {
   211  	subnet, err := tcpip.NewSubnet(IPv4Any, tcpip.MaskFrom("\x00\x00\x00\x00"))
   212  	if err != nil {
   213  		panic(err)
   214  	}
   215  	return subnet
   216  }()
   217  
   218  // IPv4CurrentNetworkSubnet is the subnet of addresses for the current network,
   219  // per RFC 6890 section 2.2.2,
   220  //
   221  //	+----------------------+----------------------------+
   222  //	| Attribute            | Value                      |
   223  //	+----------------------+----------------------------+
   224  //	| Address Block        | 0.0.0.0/8                  |
   225  //	| Name                 | "This host on this network"|
   226  //	| RFC                  | [RFC1122], Section 3.2.1.3 |
   227  //	| Allocation Date      | September 1981             |
   228  //	| Termination Date     | N/A                        |
   229  //	| Source               | True                       |
   230  //	| Destination          | False                      |
   231  //	| Forwardable          | False                      |
   232  //	| Global               | False                      |
   233  //	| Reserved-by-Protocol | True                       |
   234  //	+----------------------+----------------------------+
   235  var IPv4CurrentNetworkSubnet = func() tcpip.Subnet {
   236  	subnet, err := tcpip.NewSubnet(IPv4Any, tcpip.MaskFrom("\xff\x00\x00\x00"))
   237  	if err != nil {
   238  		panic(err)
   239  	}
   240  	return subnet
   241  }()
   242  
   243  // IPv4LoopbackSubnet is the loopback subnet for IPv4.
   244  var IPv4LoopbackSubnet = func() tcpip.Subnet {
   245  	subnet, err := tcpip.NewSubnet(tcpip.AddrFrom4([4]byte{0x7f, 0x00, 0x00, 0x00}), tcpip.MaskFrom("\xff\x00\x00\x00"))
   246  	if err != nil {
   247  		panic(err)
   248  	}
   249  	return subnet
   250  }()
   251  
   252  // IPVersion returns the version of IP used in the given packet. It returns -1
   253  // if the packet is not large enough to contain the version field.
   254  func IPVersion(b []byte) int {
   255  	// Length must be at least offset+length of version field.
   256  	if len(b) < versIHL+1 {
   257  		return -1
   258  	}
   259  	return int(b[versIHL] >> ipVersionShift)
   260  }
   261  
   262  // RFC 791 page 11 shows the header length (IHL) is in the lower 4 bits
   263  // of the first byte, and is counted in multiples of 4 bytes.
   264  //
   265  //	 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   266  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   267  //	|Version|  IHL  |Type of Service|          Total Length         |
   268  //	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   269  //	  (...)
   270  //	 Version:  4 bits
   271  //	   The Version field indicates the format of the internet header.  This
   272  //	   document describes version 4.
   273  //
   274  //	 IHL:  4 bits
   275  //	   Internet Header Length is the length of the internet header in 32
   276  //	   bit words, and thus points to the beginning of the data.  Note that
   277  //	   the minimum value for a correct header is 5.
   278  const (
   279  	ipVersionShift = 4
   280  	ipIHLMask      = 0x0f
   281  	IPv4IHLStride  = 4
   282  )
   283  
   284  // HeaderLength returns the value of the "header length" field of the IPv4
   285  // header. The length returned is in bytes.
   286  func (b IPv4) HeaderLength() uint8 {
   287  	return (b[versIHL] & ipIHLMask) * IPv4IHLStride
   288  }
   289  
   290  // SetHeaderLength sets the value of the "Internet Header Length" field.
   291  func (b IPv4) SetHeaderLength(hdrLen uint8) {
   292  	if hdrLen > IPv4MaximumHeaderSize {
   293  		panic(fmt.Sprintf("got IPv4 Header size = %d, want <= %d", hdrLen, IPv4MaximumHeaderSize))
   294  	}
   295  	b[versIHL] = (IPv4Version << ipVersionShift) | ((hdrLen / IPv4IHLStride) & ipIHLMask)
   296  }
   297  
   298  // ID returns the value of the identifier field of the IPv4 header.
   299  func (b IPv4) ID() uint16 {
   300  	return binary.BigEndian.Uint16(b[id:])
   301  }
   302  
   303  // Protocol returns the value of the protocol field of the IPv4 header.
   304  func (b IPv4) Protocol() uint8 {
   305  	return b[protocol]
   306  }
   307  
   308  // Flags returns the "flags" field of the IPv4 header.
   309  func (b IPv4) Flags() uint8 {
   310  	return uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13)
   311  }
   312  
   313  // More returns whether the more fragments flag is set.
   314  func (b IPv4) More() bool {
   315  	return b.Flags()&IPv4FlagMoreFragments != 0
   316  }
   317  
   318  // TTL returns the "TTL" field of the IPv4 header.
   319  func (b IPv4) TTL() uint8 {
   320  	return b[ttl]
   321  }
   322  
   323  // FragmentOffset returns the "fragment offset" field of the IPv4 header.
   324  func (b IPv4) FragmentOffset() uint16 {
   325  	return binary.BigEndian.Uint16(b[flagsFO:]) << 3
   326  }
   327  
   328  // TotalLength returns the "total length" field of the IPv4 header.
   329  func (b IPv4) TotalLength() uint16 {
   330  	return binary.BigEndian.Uint16(b[IPv4TotalLenOffset:])
   331  }
   332  
   333  // Checksum returns the checksum field of the IPv4 header.
   334  func (b IPv4) Checksum() uint16 {
   335  	return binary.BigEndian.Uint16(b[xsum:])
   336  }
   337  
   338  // SourceAddress returns the "source address" field of the IPv4 header.
   339  func (b IPv4) SourceAddress() tcpip.Address {
   340  	return tcpip.AddrFrom4Slice(b[srcAddr : srcAddr+IPv4AddressSize])
   341  }
   342  
   343  // DestinationAddress returns the "destination address" field of the IPv4
   344  // header.
   345  func (b IPv4) DestinationAddress() tcpip.Address {
   346  	return tcpip.AddrFrom4Slice(b[dstAddr : dstAddr+IPv4AddressSize])
   347  }
   348  
   349  // SetSourceAddressWithChecksumUpdate implements ChecksummableNetwork.
   350  func (b IPv4) SetSourceAddressWithChecksumUpdate(new tcpip.Address) {
   351  	b.SetChecksum(^checksumUpdate2ByteAlignedAddress(^b.Checksum(), b.SourceAddress(), new))
   352  	b.SetSourceAddress(new)
   353  }
   354  
   355  // SetDestinationAddressWithChecksumUpdate implements ChecksummableNetwork.
   356  func (b IPv4) SetDestinationAddressWithChecksumUpdate(new tcpip.Address) {
   357  	b.SetChecksum(^checksumUpdate2ByteAlignedAddress(^b.Checksum(), b.DestinationAddress(), new))
   358  	b.SetDestinationAddress(new)
   359  }
   360  
   361  // padIPv4OptionsLength returns the total length for IPv4 options of length l
   362  // after applying padding according to RFC 791:
   363  //
   364  //	The internet header padding is used to ensure that the internet
   365  //	header ends on a 32 bit boundary.
   366  func padIPv4OptionsLength(length uint8) uint8 {
   367  	return (length + IPv4IHLStride - 1) & ^uint8(IPv4IHLStride-1)
   368  }
   369  
   370  // IPv4Options is a buffer that holds all the raw IP options.
   371  type IPv4Options []byte
   372  
   373  // Options returns a buffer holding the options.
   374  func (b IPv4) Options() IPv4Options {
   375  	hdrLen := b.HeaderLength()
   376  	return IPv4Options(b[options:hdrLen:hdrLen])
   377  }
   378  
   379  // TransportProtocol implements Network.TransportProtocol.
   380  func (b IPv4) TransportProtocol() tcpip.TransportProtocolNumber {
   381  	return tcpip.TransportProtocolNumber(b.Protocol())
   382  }
   383  
   384  // Payload implements Network.Payload.
   385  func (b IPv4) Payload() []byte {
   386  	return b[b.HeaderLength():][:b.PayloadLength()]
   387  }
   388  
   389  // PayloadLength returns the length of the payload portion of the IPv4 packet.
   390  func (b IPv4) PayloadLength() uint16 {
   391  	return b.TotalLength() - uint16(b.HeaderLength())
   392  }
   393  
   394  // TOS returns the "type of service" field of the IPv4 header.
   395  func (b IPv4) TOS() (uint8, uint32) {
   396  	return b[tos], 0
   397  }
   398  
   399  // SetTOS sets the "type of service" field of the IPv4 header.
   400  func (b IPv4) SetTOS(v uint8, _ uint32) {
   401  	b[tos] = v
   402  }
   403  
   404  // SetTTL sets the "Time to Live" field of the IPv4 header.
   405  func (b IPv4) SetTTL(v byte) {
   406  	b[ttl] = v
   407  }
   408  
   409  // SetTotalLength sets the "total length" field of the IPv4 header.
   410  func (b IPv4) SetTotalLength(totalLength uint16) {
   411  	binary.BigEndian.PutUint16(b[IPv4TotalLenOffset:], totalLength)
   412  }
   413  
   414  // SetChecksum sets the checksum field of the IPv4 header.
   415  func (b IPv4) SetChecksum(v uint16) {
   416  	checksum.Put(b[xsum:], v)
   417  }
   418  
   419  // SetFlagsFragmentOffset sets the "flags" and "fragment offset" fields of the
   420  // IPv4 header.
   421  func (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) {
   422  	v := (uint16(flags) << 13) | (offset >> 3)
   423  	binary.BigEndian.PutUint16(b[flagsFO:], v)
   424  }
   425  
   426  // SetID sets the identification field.
   427  func (b IPv4) SetID(v uint16) {
   428  	binary.BigEndian.PutUint16(b[id:], v)
   429  }
   430  
   431  // SetSourceAddress sets the "source address" field of the IPv4 header.
   432  func (b IPv4) SetSourceAddress(addr tcpip.Address) {
   433  	copy(b[srcAddr:srcAddr+IPv4AddressSize], addr.AsSlice())
   434  }
   435  
   436  // SetDestinationAddress sets the "destination address" field of the IPv4
   437  // header.
   438  func (b IPv4) SetDestinationAddress(addr tcpip.Address) {
   439  	copy(b[dstAddr:dstAddr+IPv4AddressSize], addr.AsSlice())
   440  }
   441  
   442  // CalculateChecksum calculates the checksum of the IPv4 header.
   443  func (b IPv4) CalculateChecksum() uint16 {
   444  	return checksum.Checksum(b[:b.HeaderLength()], 0)
   445  }
   446  
   447  // Encode encodes all the fields of the IPv4 header.
   448  func (b IPv4) Encode(i *IPv4Fields) {
   449  	// The size of the options defines the size of the whole header and thus the
   450  	// IHL field. Options are rare and this is a heavily used function so it is
   451  	// worth a bit of optimisation here to keep the serializer out of the fast
   452  	// path.
   453  	hdrLen := uint8(IPv4MinimumSize)
   454  	if len(i.Options) != 0 {
   455  		hdrLen += i.Options.Serialize(b[options:])
   456  	}
   457  	if hdrLen > IPv4MaximumHeaderSize {
   458  		panic(fmt.Sprintf("%d is larger than maximum IPv4 header size of %d", hdrLen, IPv4MaximumHeaderSize))
   459  	}
   460  	b.SetHeaderLength(hdrLen)
   461  	b[tos] = i.TOS
   462  	b.SetTotalLength(i.TotalLength)
   463  	binary.BigEndian.PutUint16(b[id:], i.ID)
   464  	b.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset)
   465  	b[ttl] = i.TTL
   466  	b[protocol] = i.Protocol
   467  	b.SetChecksum(i.Checksum)
   468  	copy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr.AsSlice())
   469  	copy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr.AsSlice())
   470  }
   471  
   472  // EncodePartial updates the total length and checksum fields of IPv4 header,
   473  // taking in the partial checksum, which is the checksum of the header without
   474  // the total length and checksum fields. It is useful in cases when similar
   475  // packets are produced.
   476  func (b IPv4) EncodePartial(partialChecksum, totalLength uint16) {
   477  	b.SetTotalLength(totalLength)
   478  	xsum := checksum.Checksum(b[IPv4TotalLenOffset:IPv4TotalLenOffset+2], partialChecksum)
   479  	b.SetChecksum(^xsum)
   480  }
   481  
   482  // IsValid performs basic validation on the packet.
   483  func (b IPv4) IsValid(pktSize int) bool {
   484  	if len(b) < IPv4MinimumSize {
   485  		return false
   486  	}
   487  
   488  	hlen := int(b.HeaderLength())
   489  	tlen := int(b.TotalLength())
   490  	if hlen < IPv4MinimumSize || hlen > tlen || tlen > pktSize {
   491  		return false
   492  	}
   493  
   494  	if IPVersion(b) != IPv4Version {
   495  		return false
   496  	}
   497  
   498  	return true
   499  }
   500  
   501  // IsV4LinkLocalUnicastAddress determines if the provided address is an IPv4
   502  // link-local unicast address.
   503  func IsV4LinkLocalUnicastAddress(addr tcpip.Address) bool {
   504  	return ipv4LinkLocalUnicastSubnet.Contains(addr)
   505  }
   506  
   507  // IsV4LinkLocalMulticastAddress determines if the provided address is an IPv4
   508  // link-local multicast address.
   509  func IsV4LinkLocalMulticastAddress(addr tcpip.Address) bool {
   510  	return ipv4LinkLocalMulticastSubnet.Contains(addr)
   511  }
   512  
   513  // IsChecksumValid returns true iff the IPv4 header's checksum is valid.
   514  func (b IPv4) IsChecksumValid() bool {
   515  	// There has been some confusion regarding verifying checksums. We need
   516  	// just look for negative 0 (0xffff) as the checksum, as it's not possible to
   517  	// get positive 0 (0) for the checksum. Some bad implementations could get it
   518  	// when doing entry replacement in the early days of the Internet,
   519  	// however the lore that one needs to check for both persists.
   520  	//
   521  	// RFC 1624 section 1 describes the source of this confusion as:
   522  	//     [the partial recalculation method described in RFC 1071] computes a
   523  	//     result for certain cases that differs from the one obtained from
   524  	//     scratch (one's complement of one's complement sum of the original
   525  	//     fields).
   526  	//
   527  	// However RFC 1624 section 5 clarifies that if using the verification method
   528  	// "recommended by RFC 1071, it does not matter if an intermediate system
   529  	// generated a -0 instead of +0".
   530  	//
   531  	// RFC1071 page 1 specifies the verification method as:
   532  	//	  (3)  To check a checksum, the 1's complement sum is computed over the
   533  	//        same set of octets, including the checksum field.  If the result
   534  	//        is all 1 bits (-0 in 1's complement arithmetic), the check
   535  	//        succeeds.
   536  	return b.CalculateChecksum() == 0xffff
   537  }
   538  
   539  // IsV4MulticastAddress determines if the provided address is an IPv4 multicast
   540  // address (range 224.0.0.0 to 239.255.255.255). The four most significant bits
   541  // will be 1110 = 0xe0.
   542  func IsV4MulticastAddress(addr tcpip.Address) bool {
   543  	if addr.BitLen() != IPv4AddressSizeBits {
   544  		return false
   545  	}
   546  	addrBytes := addr.As4()
   547  	return (addrBytes[0] & 0xf0) == 0xe0
   548  }
   549  
   550  // IsV4LoopbackAddress determines if the provided address is an IPv4 loopback
   551  // address (belongs to 127.0.0.0/8 subnet). See RFC 1122 section 3.2.1.3.
   552  func IsV4LoopbackAddress(addr tcpip.Address) bool {
   553  	if addr.BitLen() != IPv4AddressSizeBits {
   554  		return false
   555  	}
   556  	addrBytes := addr.As4()
   557  	return addrBytes[0] == 0x7f
   558  }
   559  
   560  // ========================= Options ==========================
   561  
   562  // An IPv4OptionType can hold the valuse for the Type in an IPv4 option.
   563  type IPv4OptionType byte
   564  
   565  // These constants are needed to identify individual options in the option list.
   566  // While RFC 791 (page 31) says "Every internet module must be able to act on
   567  // every option." This has not generally been adhered to and some options have
   568  // very low rates of support. We do not support options other than those shown
   569  // below.
   570  
   571  const (
   572  	// IPv4OptionListEndType is the option type for the End Of Option List
   573  	// option. Anything following is ignored.
   574  	IPv4OptionListEndType IPv4OptionType = 0
   575  
   576  	// IPv4OptionNOPType is the No-Operation option. May appear between other
   577  	// options and may appear multiple times.
   578  	IPv4OptionNOPType IPv4OptionType = 1
   579  
   580  	// IPv4OptionRouterAlertType is the option type for the Router Alert option,
   581  	// defined in RFC 2113 Section 2.1.
   582  	IPv4OptionRouterAlertType IPv4OptionType = 20 | 0x80
   583  
   584  	// IPv4OptionRecordRouteType is used by each router on the path of the packet
   585  	// to record its path. It is carried over to an Echo Reply.
   586  	IPv4OptionRecordRouteType IPv4OptionType = 7
   587  
   588  	// IPv4OptionTimestampType is the option type for the Timestamp option.
   589  	IPv4OptionTimestampType IPv4OptionType = 68
   590  
   591  	// ipv4OptionTypeOffset is the offset in an option of its type field.
   592  	ipv4OptionTypeOffset = 0
   593  
   594  	// IPv4OptionLengthOffset is the offset in an option of its length field.
   595  	IPv4OptionLengthOffset = 1
   596  )
   597  
   598  // IPv4OptParameterProblem indicates that a Parameter Problem message
   599  // should be generated, and gives the offset in the current entity
   600  // that should be used in that packet.
   601  type IPv4OptParameterProblem struct {
   602  	Pointer  uint8
   603  	NeedICMP bool
   604  }
   605  
   606  // IPv4Option is an interface representing various option types.
   607  type IPv4Option interface {
   608  	// Type returns the type identifier of the option.
   609  	Type() IPv4OptionType
   610  
   611  	// Size returns the size of the option in bytes.
   612  	Size() uint8
   613  
   614  	// Contents returns a slice holding the contents of the option.
   615  	Contents() []byte
   616  }
   617  
   618  var _ IPv4Option = (*IPv4OptionGeneric)(nil)
   619  
   620  // IPv4OptionGeneric is an IPv4 Option of unknown type.
   621  type IPv4OptionGeneric []byte
   622  
   623  // Type implements IPv4Option.
   624  func (o *IPv4OptionGeneric) Type() IPv4OptionType {
   625  	return IPv4OptionType((*o)[ipv4OptionTypeOffset])
   626  }
   627  
   628  // Size implements IPv4Option.
   629  func (o *IPv4OptionGeneric) Size() uint8 { return uint8(len(*o)) }
   630  
   631  // Contents implements IPv4Option.
   632  func (o *IPv4OptionGeneric) Contents() []byte { return *o }
   633  
   634  // IPv4OptionIterator is an iterator pointing to a specific IP option
   635  // at any point of time. It also holds information as to a new options buffer
   636  // that we are building up to hand back to the caller.
   637  // TODO(https://gvisor.dev/issues/5513): Add unit tests for IPv4OptionIterator.
   638  type IPv4OptionIterator struct {
   639  	options IPv4Options
   640  	// ErrCursor is where we are while parsing options. It is exported as any
   641  	// resulting ICMP packet is supposed to have a pointer to the byte within
   642  	// the IP packet where the error was detected.
   643  	ErrCursor     uint8
   644  	nextErrCursor uint8
   645  	newOptions    [IPv4MaximumOptionsSize]byte
   646  	writePoint    int
   647  }
   648  
   649  // MakeIterator sets up and returns an iterator of options. It also sets up the
   650  // building of a new option set.
   651  func (o IPv4Options) MakeIterator() IPv4OptionIterator {
   652  	return IPv4OptionIterator{
   653  		options:       o,
   654  		nextErrCursor: IPv4MinimumSize,
   655  	}
   656  }
   657  
   658  // InitReplacement copies the option into the new option buffer.
   659  func (i *IPv4OptionIterator) InitReplacement(option IPv4Option) IPv4Options {
   660  	replacementOption := i.RemainingBuffer()[:option.Size()]
   661  	if copied := copy(replacementOption, option.Contents()); copied != len(replacementOption) {
   662  		panic(fmt.Sprintf("copied %d bytes in the replacement option buffer, expected %d bytes", copied, len(replacementOption)))
   663  	}
   664  	return replacementOption
   665  }
   666  
   667  // RemainingBuffer returns the remaining (unused) part of the new option buffer,
   668  // into which a new option may be written.
   669  func (i *IPv4OptionIterator) RemainingBuffer() IPv4Options {
   670  	return i.newOptions[i.writePoint:]
   671  }
   672  
   673  // ConsumeBuffer marks a portion of the new buffer as used.
   674  func (i *IPv4OptionIterator) ConsumeBuffer(size int) {
   675  	i.writePoint += size
   676  }
   677  
   678  // PushNOPOrEnd puts one of the single byte options onto the new options.
   679  // Only values 0 or 1 (ListEnd or NOP) are valid input.
   680  func (i *IPv4OptionIterator) PushNOPOrEnd(val IPv4OptionType) {
   681  	if val > IPv4OptionNOPType {
   682  		panic(fmt.Sprintf("invalid option type %d pushed onto option build buffer", val))
   683  	}
   684  	i.newOptions[i.writePoint] = byte(val)
   685  	i.writePoint++
   686  }
   687  
   688  // Finalize returns the completed replacement options buffer padded
   689  // as needed.
   690  func (i *IPv4OptionIterator) Finalize() IPv4Options {
   691  	// RFC 791 page 31 says:
   692  	//     The options might not end on a 32-bit boundary.  The internet header
   693  	//     must be filled out with octets of zeros.  The first of these would
   694  	//     be interpreted as the end-of-options option, and the remainder as
   695  	//     internet header padding.
   696  	// Since the buffer is already zero filled we just need to step the write
   697  	// pointer up to the next multiple of 4.
   698  	options := IPv4Options(i.newOptions[:(i.writePoint+0x3) & ^0x3])
   699  	// Poison the write pointer.
   700  	i.writePoint = len(i.newOptions)
   701  	return options
   702  }
   703  
   704  // Next returns the next IP option in the buffer/list of IP options.
   705  // It returns
   706  //   - A slice of bytes holding the next option or nil if there is error.
   707  //   - A boolean which is true if parsing of all the options is complete.
   708  //     Undefined in the case of error.
   709  //   - An error indication which is non-nil if an error condition was found.
   710  func (i *IPv4OptionIterator) Next() (IPv4Option, bool, *IPv4OptParameterProblem) {
   711  	// The opts slice gets shorter as we process the options. When we have no
   712  	// bytes left we are done.
   713  	if len(i.options) == 0 {
   714  		return nil, true, nil
   715  	}
   716  
   717  	i.ErrCursor = i.nextErrCursor
   718  
   719  	optType := IPv4OptionType(i.options[ipv4OptionTypeOffset])
   720  
   721  	if optType == IPv4OptionNOPType || optType == IPv4OptionListEndType {
   722  		optionBody := i.options[:1]
   723  		i.options = i.options[1:]
   724  		i.nextErrCursor = i.ErrCursor + 1
   725  		retval := IPv4OptionGeneric(optionBody)
   726  		return &retval, false, nil
   727  	}
   728  
   729  	// There are no more single byte options defined.  All the rest have a length
   730  	// field so we need to sanity check it.
   731  	if len(i.options) == 1 {
   732  		return nil, false, &IPv4OptParameterProblem{
   733  			Pointer:  i.ErrCursor,
   734  			NeedICMP: true,
   735  		}
   736  	}
   737  
   738  	optLen := i.options[IPv4OptionLengthOffset]
   739  
   740  	if optLen <= IPv4OptionLengthOffset || optLen > uint8(len(i.options)) {
   741  		// The actual error is in the length (2nd byte of the option) but we
   742  		// return the start of the option for compatibility with Linux.
   743  
   744  		return nil, false, &IPv4OptParameterProblem{
   745  			Pointer:  i.ErrCursor,
   746  			NeedICMP: true,
   747  		}
   748  	}
   749  
   750  	optionBody := i.options[:optLen]
   751  	i.nextErrCursor = i.ErrCursor + optLen
   752  	i.options = i.options[optLen:]
   753  
   754  	// Check the length of some option types that we know.
   755  	switch optType {
   756  	case IPv4OptionTimestampType:
   757  		if optLen < IPv4OptionTimestampHdrLength {
   758  			i.ErrCursor++
   759  			return nil, false, &IPv4OptParameterProblem{
   760  				Pointer:  i.ErrCursor,
   761  				NeedICMP: true,
   762  			}
   763  		}
   764  		retval := IPv4OptionTimestamp(optionBody)
   765  		return &retval, false, nil
   766  
   767  	case IPv4OptionRecordRouteType:
   768  		if optLen < IPv4OptionRecordRouteHdrLength {
   769  			i.ErrCursor++
   770  			return nil, false, &IPv4OptParameterProblem{
   771  				Pointer:  i.ErrCursor,
   772  				NeedICMP: true,
   773  			}
   774  		}
   775  		retval := IPv4OptionRecordRoute(optionBody)
   776  		return &retval, false, nil
   777  
   778  	case IPv4OptionRouterAlertType:
   779  		if optLen != IPv4OptionRouterAlertLength {
   780  			i.ErrCursor++
   781  			return nil, false, &IPv4OptParameterProblem{
   782  				Pointer:  i.ErrCursor,
   783  				NeedICMP: true,
   784  			}
   785  		}
   786  		retval := IPv4OptionRouterAlert(optionBody)
   787  		return &retval, false, nil
   788  	}
   789  	retval := IPv4OptionGeneric(optionBody)
   790  	return &retval, false, nil
   791  }
   792  
   793  //
   794  // IP Timestamp option - RFC 791 page 22.
   795  // +--------+--------+--------+--------+
   796  // |01000100| length | pointer|oflw|flg|
   797  // +--------+--------+--------+--------+
   798  // |         internet address          |
   799  // +--------+--------+--------+--------+
   800  // |             timestamp             |
   801  // +--------+--------+--------+--------+
   802  // |                ...                |
   803  //
   804  // Type = 68
   805  //
   806  // The Option Length is the number of octets in the option counting
   807  // the type, length, pointer, and overflow/flag octets (maximum
   808  // length 40).
   809  //
   810  // The Pointer is the number of octets from the beginning of this
   811  // option to the end of timestamps plus one (i.e., it points to the
   812  // octet beginning the space for next timestamp).  The smallest
   813  // legal value is 5.  The timestamp area is full when the pointer
   814  // is greater than the length.
   815  //
   816  // The Overflow (oflw) [4 bits] is the number of IP modules that
   817  // cannot register timestamps due to lack of space.
   818  //
   819  // The Flag (flg) [4 bits] values are
   820  //
   821  //   0 -- time stamps only, stored in consecutive 32-bit words,
   822  //
   823  //   1 -- each timestamp is preceded with internet address of the
   824  //        registering entity,
   825  //
   826  //   3 -- the internet address fields are prespecified.  An IP
   827  //        module only registers its timestamp if it matches its own
   828  //        address with the next specified internet address.
   829  //
   830  // Timestamps are defined in RFC 791 page 22 as milliseconds since midnight UTC.
   831  //
   832  //        The Timestamp is a right-justified, 32-bit timestamp in
   833  //        milliseconds since midnight UT.  If the time is not available in
   834  //        milliseconds or cannot be provided with respect to midnight UT
   835  //        then any time may be inserted as a timestamp provided the high
   836  //        order bit of the timestamp field is set to one to indicate the
   837  //        use of a non-standard value.
   838  
   839  // IPv4OptTSFlags sefines the values expected in the Timestamp
   840  // option Flags field.
   841  type IPv4OptTSFlags uint8
   842  
   843  // Timestamp option specific related constants.
   844  const (
   845  	// IPv4OptionTimestampHdrLength is the length of the timestamp option header.
   846  	IPv4OptionTimestampHdrLength = 4
   847  
   848  	// IPv4OptionTimestampSize is the size of an IP timestamp.
   849  	IPv4OptionTimestampSize = 4
   850  
   851  	// IPv4OptionTimestampWithAddrSize is the size of an IP timestamp + Address.
   852  	IPv4OptionTimestampWithAddrSize = IPv4AddressSize + IPv4OptionTimestampSize
   853  
   854  	// IPv4OptionTimestampMaxSize is limited by space for options
   855  	IPv4OptionTimestampMaxSize = IPv4MaximumOptionsSize
   856  
   857  	// IPv4OptionTimestampOnlyFlag is a flag indicating that only timestamp
   858  	// is present.
   859  	IPv4OptionTimestampOnlyFlag IPv4OptTSFlags = 0
   860  
   861  	// IPv4OptionTimestampWithIPFlag is a flag indicating that both timestamps and
   862  	// IP are present.
   863  	IPv4OptionTimestampWithIPFlag IPv4OptTSFlags = 1
   864  
   865  	// IPv4OptionTimestampWithPredefinedIPFlag is a flag indicating that
   866  	// predefined IP is present.
   867  	IPv4OptionTimestampWithPredefinedIPFlag IPv4OptTSFlags = 3
   868  )
   869  
   870  // ipv4TimestampTime provides the current time as specified in RFC 791.
   871  func ipv4TimestampTime(clock tcpip.Clock) uint32 {
   872  	// Per RFC 791 page 21:
   873  	//   The Timestamp is a right-justified, 32-bit timestamp in
   874  	//   milliseconds since midnight UT.
   875  	now := clock.Now().UTC()
   876  	midnight := now.Truncate(24 * time.Hour)
   877  	return uint32(now.Sub(midnight).Milliseconds())
   878  }
   879  
   880  // IP Timestamp option fields.
   881  const (
   882  	// IPv4OptTSPointerOffset is the offset of the Timestamp pointer field.
   883  	IPv4OptTSPointerOffset = 2
   884  
   885  	// IPv4OptTSPointerOffset is the offset of the combined Flag and Overflow
   886  	// fields, (each being 4 bits).
   887  	IPv4OptTSOFLWAndFLGOffset = 3
   888  	// These constants define the sub byte fields of the Flag and OverFlow field.
   889  	ipv4OptionTimestampOverflowshift      = 4
   890  	ipv4OptionTimestampFlagsMask     byte = 0x0f
   891  )
   892  
   893  var _ IPv4Option = (*IPv4OptionTimestamp)(nil)
   894  
   895  // IPv4OptionTimestamp is a Timestamp option from RFC 791.
   896  type IPv4OptionTimestamp []byte
   897  
   898  // Type implements IPv4Option.Type().
   899  func (ts *IPv4OptionTimestamp) Type() IPv4OptionType { return IPv4OptionTimestampType }
   900  
   901  // Size implements IPv4Option.
   902  func (ts *IPv4OptionTimestamp) Size() uint8 { return uint8(len(*ts)) }
   903  
   904  // Contents implements IPv4Option.
   905  func (ts *IPv4OptionTimestamp) Contents() []byte { return *ts }
   906  
   907  // Pointer returns the pointer field in the IP Timestamp option.
   908  func (ts *IPv4OptionTimestamp) Pointer() uint8 {
   909  	return (*ts)[IPv4OptTSPointerOffset]
   910  }
   911  
   912  // Flags returns the flags field in the IP Timestamp option.
   913  func (ts *IPv4OptionTimestamp) Flags() IPv4OptTSFlags {
   914  	return IPv4OptTSFlags((*ts)[IPv4OptTSOFLWAndFLGOffset] & ipv4OptionTimestampFlagsMask)
   915  }
   916  
   917  // Overflow returns the Overflow field in the IP Timestamp option.
   918  func (ts *IPv4OptionTimestamp) Overflow() uint8 {
   919  	return (*ts)[IPv4OptTSOFLWAndFLGOffset] >> ipv4OptionTimestampOverflowshift
   920  }
   921  
   922  // IncOverflow increments the Overflow field in the IP Timestamp option. It
   923  // returns the incremented value. If the return value is 0 then the field
   924  // overflowed.
   925  func (ts *IPv4OptionTimestamp) IncOverflow() uint8 {
   926  	(*ts)[IPv4OptTSOFLWAndFLGOffset] += 1 << ipv4OptionTimestampOverflowshift
   927  	return ts.Overflow()
   928  }
   929  
   930  // UpdateTimestamp updates the fields of the next free timestamp slot.
   931  func (ts *IPv4OptionTimestamp) UpdateTimestamp(addr tcpip.Address, clock tcpip.Clock) {
   932  	slot := (*ts)[ts.Pointer()-1:]
   933  
   934  	switch ts.Flags() {
   935  	case IPv4OptionTimestampOnlyFlag:
   936  		binary.BigEndian.PutUint32(slot, ipv4TimestampTime(clock))
   937  		(*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampSize
   938  	case IPv4OptionTimestampWithIPFlag:
   939  		if n := copy(slot, addr.AsSlice()); n != IPv4AddressSize {
   940  			panic(fmt.Sprintf("copied %d bytes, expected %d bytes", n, IPv4AddressSize))
   941  		}
   942  		binary.BigEndian.PutUint32(slot[IPv4AddressSize:], ipv4TimestampTime(clock))
   943  		(*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampWithAddrSize
   944  	case IPv4OptionTimestampWithPredefinedIPFlag:
   945  		if tcpip.AddrFrom4Slice(slot[:IPv4AddressSize]) == addr {
   946  			binary.BigEndian.PutUint32(slot[IPv4AddressSize:], ipv4TimestampTime(clock))
   947  			(*ts)[IPv4OptTSPointerOffset] += IPv4OptionTimestampWithAddrSize
   948  		}
   949  	}
   950  }
   951  
   952  // RecordRoute option specific related constants.
   953  //
   954  // from RFC 791 page 20:
   955  //
   956  //	Record Route
   957  //
   958  //	      +--------+--------+--------+---------//--------+
   959  //	      |00000111| length | pointer|     route data    |
   960  //	      +--------+--------+--------+---------//--------+
   961  //	        Type=7
   962  //
   963  //	      The record route option provides a means to record the route of
   964  //	      an internet datagram.
   965  //
   966  //	      The option begins with the option type code.  The second octet
   967  //	      is the option length which includes the option type code and the
   968  //	      length octet, the pointer octet, and length-3 octets of route
   969  //	      data.  The third octet is the pointer into the route data
   970  //	      indicating the octet which begins the next area to store a route
   971  //	      address.  The pointer is relative to this option, and the
   972  //	      smallest legal value for the pointer is 4.
   973  const (
   974  	// IPv4OptionRecordRouteHdrLength is the length of the Record Route option
   975  	// header.
   976  	IPv4OptionRecordRouteHdrLength = 3
   977  
   978  	// IPv4OptRRPointerOffset is the offset to the pointer field in an RR
   979  	// option, which points to the next free slot in the list of addresses.
   980  	IPv4OptRRPointerOffset = 2
   981  )
   982  
   983  var _ IPv4Option = (*IPv4OptionRecordRoute)(nil)
   984  
   985  // IPv4OptionRecordRoute is an IPv4 RecordRoute option defined by RFC 791.
   986  type IPv4OptionRecordRoute []byte
   987  
   988  // Pointer returns the pointer field in the IP RecordRoute option.
   989  func (rr *IPv4OptionRecordRoute) Pointer() uint8 {
   990  	return (*rr)[IPv4OptRRPointerOffset]
   991  }
   992  
   993  // StoreAddress stores the given IPv4 address into the next free slot.
   994  func (rr *IPv4OptionRecordRoute) StoreAddress(addr tcpip.Address) {
   995  	start := rr.Pointer() - 1 // A one based number.
   996  	// start and room checked by caller.
   997  	if n := copy((*rr)[start:], addr.AsSlice()); n != IPv4AddressSize {
   998  		panic(fmt.Sprintf("copied %d bytes, expected %d bytes", n, IPv4AddressSize))
   999  	}
  1000  	(*rr)[IPv4OptRRPointerOffset] += IPv4AddressSize
  1001  }
  1002  
  1003  // Type implements IPv4Option.
  1004  func (rr *IPv4OptionRecordRoute) Type() IPv4OptionType { return IPv4OptionRecordRouteType }
  1005  
  1006  // Size implements IPv4Option.
  1007  func (rr *IPv4OptionRecordRoute) Size() uint8 { return uint8(len(*rr)) }
  1008  
  1009  // Contents implements IPv4Option.
  1010  func (rr *IPv4OptionRecordRoute) Contents() []byte { return *rr }
  1011  
  1012  // Router Alert option specific related constants.
  1013  //
  1014  // from RFC 2113 section 2.1:
  1015  //
  1016  //	+--------+--------+--------+--------+
  1017  //	|10010100|00000100|  2 octet value  |
  1018  //	+--------+--------+--------+--------+
  1019  //
  1020  //	Type:
  1021  //	Copied flag:  1 (all fragments must carry the option)
  1022  //	Option class: 0 (control)
  1023  //	Option number: 20 (decimal)
  1024  //
  1025  //	Length: 4
  1026  //
  1027  //	Value:  A two octet code with the following values:
  1028  //	0 - Router shall examine packet
  1029  //	1-65535 - Reserved
  1030  const (
  1031  	// IPv4OptionRouterAlertLength is the length of a Router Alert option.
  1032  	IPv4OptionRouterAlertLength = 4
  1033  
  1034  	// IPv4OptionRouterAlertValue is the only permissible value of the 16 bit
  1035  	// payload of the router alert option.
  1036  	IPv4OptionRouterAlertValue = 0
  1037  
  1038  	// IPv4OptionRouterAlertValueOffset is the offset for the value of a
  1039  	// RouterAlert option.
  1040  	IPv4OptionRouterAlertValueOffset = 2
  1041  )
  1042  
  1043  var _ IPv4Option = (*IPv4OptionRouterAlert)(nil)
  1044  
  1045  // IPv4OptionRouterAlert is an IPv4 RouterAlert option defined by RFC 2113.
  1046  type IPv4OptionRouterAlert []byte
  1047  
  1048  // Type implements IPv4Option.
  1049  func (*IPv4OptionRouterAlert) Type() IPv4OptionType { return IPv4OptionRouterAlertType }
  1050  
  1051  // Size implements IPv4Option.
  1052  func (ra *IPv4OptionRouterAlert) Size() uint8 { return uint8(len(*ra)) }
  1053  
  1054  // Contents implements IPv4Option.
  1055  func (ra *IPv4OptionRouterAlert) Contents() []byte { return *ra }
  1056  
  1057  // Value returns the value of the IPv4OptionRouterAlert.
  1058  func (ra *IPv4OptionRouterAlert) Value() uint16 {
  1059  	return binary.BigEndian.Uint16(ra.Contents()[IPv4OptionRouterAlertValueOffset:])
  1060  }
  1061  
  1062  // IPv4SerializableOption is an interface to represent serializable IPv4 option
  1063  // types.
  1064  type IPv4SerializableOption interface {
  1065  	// optionType returns the type identifier of the option.
  1066  	optionType() IPv4OptionType
  1067  }
  1068  
  1069  // IPv4SerializableOptionPayload is an interface providing serialization of the
  1070  // payload of an IPv4 option.
  1071  type IPv4SerializableOptionPayload interface {
  1072  	// length returns the size of the payload.
  1073  	length() uint8
  1074  
  1075  	// serializeInto serializes the payload into the provided byte buffer.
  1076  	//
  1077  	// Note, the caller MUST provide a byte buffer with size of at least
  1078  	// Length. Implementers of this function may assume that the byte buffer
  1079  	// is of sufficient size. serializeInto MUST panic if the provided byte
  1080  	// buffer is not of sufficient size.
  1081  	//
  1082  	// serializeInto will return the number of bytes that was used to
  1083  	// serialize the receiver. Implementers must only use the number of
  1084  	// bytes required to serialize the receiver. Callers MAY provide a
  1085  	// larger buffer than required to serialize into.
  1086  	serializeInto(buffer []byte) uint8
  1087  }
  1088  
  1089  // IPv4OptionsSerializer is a serializer for IPv4 options.
  1090  type IPv4OptionsSerializer []IPv4SerializableOption
  1091  
  1092  // Length returns the total number of bytes required to serialize the options.
  1093  func (s IPv4OptionsSerializer) Length() uint8 {
  1094  	var total uint8
  1095  	for _, opt := range s {
  1096  		total++
  1097  		if withPayload, ok := opt.(IPv4SerializableOptionPayload); ok {
  1098  			// Add 1 to reported length to account for the length byte.
  1099  			total += 1 + withPayload.length()
  1100  		}
  1101  	}
  1102  	return padIPv4OptionsLength(total)
  1103  }
  1104  
  1105  // Serialize serializes the provided list of IPV4 options into b.
  1106  //
  1107  // Note, b must be of sufficient size to hold all the options in s. See
  1108  // IPv4OptionsSerializer.Length for details on the getting the total size
  1109  // of a serialized IPv4OptionsSerializer.
  1110  //
  1111  // Serialize panics if b is not of sufficient size to hold all the options in s.
  1112  func (s IPv4OptionsSerializer) Serialize(b []byte) uint8 {
  1113  	var total uint8
  1114  	for _, opt := range s {
  1115  		ty := opt.optionType()
  1116  		if withPayload, ok := opt.(IPv4SerializableOptionPayload); ok {
  1117  			// Serialize first to reduce bounds checks.
  1118  			l := 2 + withPayload.serializeInto(b[2:])
  1119  			b[0] = byte(ty)
  1120  			b[1] = l
  1121  			b = b[l:]
  1122  			total += l
  1123  			continue
  1124  		}
  1125  		// Options without payload consist only of the type field.
  1126  		//
  1127  		// NB: Repeating code from the branch above is intentional to minimize
  1128  		// bounds checks.
  1129  		b[0] = byte(ty)
  1130  		b = b[1:]
  1131  		total++
  1132  	}
  1133  
  1134  	// According to RFC 791:
  1135  	//
  1136  	//  The internet header padding is used to ensure that the internet
  1137  	//  header ends on a 32 bit boundary. The padding is zero.
  1138  	padded := padIPv4OptionsLength(total)
  1139  	b = b[:padded-total]
  1140  	for i := range b {
  1141  		b[i] = 0
  1142  	}
  1143  	return padded
  1144  }
  1145  
  1146  var _ IPv4SerializableOptionPayload = (*IPv4SerializableRouterAlertOption)(nil)
  1147  var _ IPv4SerializableOption = (*IPv4SerializableRouterAlertOption)(nil)
  1148  
  1149  // IPv4SerializableRouterAlertOption provides serialization of the Router Alert
  1150  // IPv4 option according to RFC 2113.
  1151  type IPv4SerializableRouterAlertOption struct{}
  1152  
  1153  // Type implements IPv4SerializableOption.
  1154  func (*IPv4SerializableRouterAlertOption) optionType() IPv4OptionType {
  1155  	return IPv4OptionRouterAlertType
  1156  }
  1157  
  1158  // Length implements IPv4SerializableOption.
  1159  func (*IPv4SerializableRouterAlertOption) length() uint8 {
  1160  	return IPv4OptionRouterAlertLength - IPv4OptionRouterAlertValueOffset
  1161  }
  1162  
  1163  // SerializeInto implements IPv4SerializableOption.
  1164  func (o *IPv4SerializableRouterAlertOption) serializeInto(buffer []byte) uint8 {
  1165  	binary.BigEndian.PutUint16(buffer, IPv4OptionRouterAlertValue)
  1166  	return o.length()
  1167  }
  1168  
  1169  var _ IPv4SerializableOption = (*IPv4SerializableNOPOption)(nil)
  1170  
  1171  // IPv4SerializableNOPOption provides serialization for the IPv4 no-op option.
  1172  type IPv4SerializableNOPOption struct{}
  1173  
  1174  // Type implements IPv4SerializableOption.
  1175  func (*IPv4SerializableNOPOption) optionType() IPv4OptionType {
  1176  	return IPv4OptionNOPType
  1177  }
  1178  
  1179  var _ IPv4SerializableOption = (*IPv4SerializableListEndOption)(nil)
  1180  
  1181  // IPv4SerializableListEndOption provides serialization for the IPv4 List End
  1182  // option.
  1183  type IPv4SerializableListEndOption struct{}
  1184  
  1185  // Type implements IPv4SerializableOption.
  1186  func (*IPv4SerializableListEndOption) optionType() IPv4OptionType {
  1187  	return IPv4OptionListEndType
  1188  }