2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-06-04 23:42:44 +01:00
|
|
|
|
|
|
|
package packet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"math"
|
|
|
|
)
|
|
|
|
|
|
|
|
const tcpHeaderLength = 20
|
2021-03-20 04:05:51 +00:00
|
|
|
const sctpHeaderLength = 12
|
2020-06-04 23:42:44 +01:00
|
|
|
|
|
|
|
// maxPacketLength is the largest length that all headers support.
|
|
|
|
// IPv4 headers using uint16 for this forces an upper bound of 64KB.
|
|
|
|
const maxPacketLength = math.MaxUint16
|
|
|
|
|
|
|
|
var (
|
2020-11-11 05:12:46 +00:00
|
|
|
// errSmallBuffer is returned when Marshal receives a buffer
|
|
|
|
// too small to contain the header to marshal.
|
2020-06-04 23:42:44 +01:00
|
|
|
errSmallBuffer = errors.New("buffer too small")
|
2020-11-11 05:12:46 +00:00
|
|
|
// errLargePacket is returned when Marshal receives a payload
|
|
|
|
// larger than the maximum representable size in header
|
|
|
|
// fields.
|
2020-06-04 23:42:44 +01:00
|
|
|
errLargePacket = errors.New("packet too large")
|
|
|
|
)
|
|
|
|
|
2020-11-11 05:12:46 +00:00
|
|
|
// Header is a packet header capable of marshaling itself into a byte
|
|
|
|
// buffer.
|
2020-06-04 23:42:44 +01:00
|
|
|
type Header interface {
|
2020-11-11 05:12:46 +00:00
|
|
|
// Len returns the length of the marshaled packet.
|
2020-06-04 23:42:44 +01:00
|
|
|
Len() int
|
2020-11-11 05:12:46 +00:00
|
|
|
// Marshal serializes the header into buf, which must be at
|
|
|
|
// least Len() bytes long. Implementations of Marshal assume
|
|
|
|
// that bytes after the first Len() are payload bytes for the
|
|
|
|
// purpose of computing length and checksum fields. Marshal
|
|
|
|
// implementations must not allocate memory.
|
2020-06-04 23:42:44 +01:00
|
|
|
Marshal(buf []byte) error
|
|
|
|
}
|
|
|
|
|
2021-12-09 06:05:07 +00:00
|
|
|
// HeaderChecksummer is implemented by Header implementations that
|
2022-09-25 19:29:55 +01:00
|
|
|
// need to do a checksum over their payloads.
|
2021-12-09 06:05:07 +00:00
|
|
|
type HeaderChecksummer interface {
|
|
|
|
Header
|
|
|
|
|
|
|
|
// WriteCheck writes the correct checksum into buf, which should
|
|
|
|
// be be the already-marshalled header and payload.
|
|
|
|
WriteChecksum(buf []byte)
|
|
|
|
}
|
|
|
|
|
2020-11-11 05:12:46 +00:00
|
|
|
// Generate generates a new packet with the given Header and
|
|
|
|
// payload. This function allocates memory, see Header.Marshal for an
|
|
|
|
// allocation-free option.
|
2020-06-04 23:42:44 +01:00
|
|
|
func Generate(h Header, payload []byte) []byte {
|
|
|
|
hlen := h.Len()
|
|
|
|
buf := make([]byte, hlen+len(payload))
|
|
|
|
|
|
|
|
copy(buf[hlen:], payload)
|
|
|
|
h.Marshal(buf)
|
|
|
|
|
2021-12-09 06:05:07 +00:00
|
|
|
if hc, ok := h.(HeaderChecksummer); ok {
|
|
|
|
hc.WriteChecksum(buf)
|
|
|
|
}
|
|
|
|
|
2020-06-04 23:42:44 +01:00
|
|
|
return buf
|
|
|
|
}
|