snapshot: sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1

Содержимое пина, зафиксированного в go.mod sing-box-lx, одним коммитом
без истории. Полная история SagerNet/gvisor — 1.45 ГБ и клонируется в
каждой CI-джобе; наша дельта — одна вставка в одну функцию, история для
неё не нужна.

Module path github.com/sagernet/gvisor сохранён намеренно: на него
опирается replace-директива суперпроекта.

Патч поверх — отдельным коммитом, чтобы дельта читалась одним git show
и переносилась на новый пин копированием.

SPECS/TASKS/048-GVISOR_HANDSHAKE_NIL_CRASH
This commit is contained in:
Leadaxe 2026-08-04 15:50:08 +03:00
commit 2c4ae3b0a4
712 changed files with 185689 additions and 0 deletions

View file

@ -0,0 +1,375 @@
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package fragmentation contains the implementation of IP fragmentation.
// It is based on RFC 791, RFC 815 and RFC 8200.
package fragmentation
import (
"errors"
"fmt"
"time"
"github.com/sagernet/gvisor/pkg/buffer"
"github.com/sagernet/gvisor/pkg/log"
"github.com/sagernet/gvisor/pkg/sync"
"github.com/sagernet/gvisor/pkg/tcpip"
"github.com/sagernet/gvisor/pkg/tcpip/stack"
)
const (
// HighFragThreshold is the threshold at which we start trimming old
// fragmented packets. Linux uses a default value of 4 MB. See
// net.ipv4.ipfrag_high_thresh for more information.
HighFragThreshold = 4 << 20 // 4MB
// LowFragThreshold is the threshold we reach to when we start dropping
// older fragmented packets. It's important that we keep enough room for newer
// packets to be re-assembled. Hence, this needs to be lower than
// HighFragThreshold enough. Linux uses a default value of 3 MB. See
// net.ipv4.ipfrag_low_thresh for more information.
LowFragThreshold = 3 << 20 // 3MB
// minBlockSize is the minimum block size for fragments.
minBlockSize = 1
)
var (
// ErrInvalidArgs indicates to the caller that an invalid argument was
// provided.
ErrInvalidArgs = errors.New("invalid args")
// ErrFragmentOverlap indicates that, during reassembly, a fragment overlaps
// with another one.
ErrFragmentOverlap = errors.New("overlapping fragments")
// ErrFragmentConflict indicates that, during reassembly, some fragments are
// in conflict with one another.
ErrFragmentConflict = errors.New("conflicting fragments")
)
// FragmentID is the identifier for a fragment.
//
// +stateify savable
type FragmentID struct {
// Source is the source address of the fragment.
Source tcpip.Address
// Destination is the destination address of the fragment.
Destination tcpip.Address
// ID is the identification value of the fragment.
//
// This is a uint32 because IPv6 uses a 32-bit identification value.
ID uint32
// The protocol for the packet.
Protocol uint8
}
// Fragmentation is the main structure that other modules
// of the stack should use to implement IP Fragmentation.
//
// +stateify savable
type Fragmentation struct {
mu sync.Mutex `state:"nosave"`
highLimit int
lowLimit int
reassemblers map[FragmentID]*reassembler
rList reassemblerList
memSize int
timeout time.Duration
blockSize uint16
clock tcpip.Clock
releaseJob *tcpip.Job
timeoutHandler TimeoutHandler
}
// TimeoutHandler is consulted if a packet reassembly has timed out.
type TimeoutHandler interface {
// OnReassemblyTimeout will be called with the first fragment (or nil, if the
// first fragment has not been received) of a packet whose reassembly has
// timed out.
OnReassemblyTimeout(pkt *stack.PacketBuffer)
}
// NewFragmentation creates a new Fragmentation.
//
// blockSize specifies the fragment block size, in bytes.
//
// highMemoryLimit specifies the limit on the memory consumed
// by the fragments stored by Fragmentation (overhead of internal data-structures
// is not accounted). Fragments are dropped when the limit is reached.
//
// lowMemoryLimit specifies the limit on which we will reach by dropping
// fragments after reaching highMemoryLimit.
//
// reassemblingTimeout specifies the maximum time allowed to reassemble a packet.
// Fragments are lazily evicted only when a new a packet with an
// already existing fragmentation-id arrives after the timeout.
func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, reassemblingTimeout time.Duration, clock tcpip.Clock, timeoutHandler TimeoutHandler) *Fragmentation {
if lowMemoryLimit >= highMemoryLimit {
lowMemoryLimit = highMemoryLimit
}
if lowMemoryLimit < 0 {
lowMemoryLimit = 0
}
if blockSize < minBlockSize {
blockSize = minBlockSize
}
f := &Fragmentation{
reassemblers: make(map[FragmentID]*reassembler),
highLimit: highMemoryLimit,
lowLimit: lowMemoryLimit,
timeout: reassemblingTimeout,
blockSize: blockSize,
clock: clock,
timeoutHandler: timeoutHandler,
}
f.releaseJob = tcpip.NewJob(f.clock, &f.mu, f.releaseReassemblersLocked)
return f
}
// Process processes an incoming fragment belonging to an ID and returns a
// complete packet and its protocol number when all the packets belonging to
// that ID have been received.
//
// [first, last] is the range of the fragment bytes.
//
// first must be a multiple of the block size f is configured with. The size
// of the fragment data must be a multiple of the block size, unless there are
// no fragments following this fragment (more set to false).
//
// proto is the protocol number marked in the fragment being processed. It has
// to be given here outside of the FragmentID struct because IPv6 should not use
// the protocol to identify a fragment.
func (f *Fragmentation) Process(
id FragmentID, first, last uint16, more bool, proto uint8, pkt *stack.PacketBuffer) (
*stack.PacketBuffer, uint8, bool, error,
) {
if first > last {
return nil, 0, false, fmt.Errorf("first=%d is greater than last=%d: %w", first, last, ErrInvalidArgs)
}
if first%f.blockSize != 0 {
return nil, 0, false, fmt.Errorf("first=%d is not a multiple of block size=%d: %w", first, f.blockSize, ErrInvalidArgs)
}
fragmentSize := last - first + 1
if more && fragmentSize%f.blockSize != 0 {
return nil, 0, false, fmt.Errorf("fragment size=%d bytes is not a multiple of block size=%d on non-final fragment: %w", fragmentSize, f.blockSize, ErrInvalidArgs)
}
if l := pkt.Data().Size(); l != int(fragmentSize) {
return nil, 0, false, fmt.Errorf("got fragment size=%d bytes not equal to the expected fragment size=%d bytes (first=%d last=%d): %w", l, fragmentSize, first, last, ErrInvalidArgs)
}
f.mu.Lock()
if f.reassemblers == nil {
return nil, 0, false, fmt.Errorf("Release() called before fragmentation processing could finish")
}
r, ok := f.reassemblers[id]
if !ok {
r = newReassembler(id, f.clock)
f.reassemblers[id] = r
wasEmpty := f.rList.Empty()
f.rList.PushFront(r)
if wasEmpty {
// If we have just pushed a first reassembler into an empty list, we
// should kickstart the release job. The release job will keep
// rescheduling itself until the list becomes empty.
f.releaseReassemblersLocked()
}
}
f.mu.Unlock()
resPkt, firstFragmentProto, done, memConsumed, err := r.process(first, last, more, proto, pkt)
if err != nil {
// We probably got an invalid sequence of fragments. Just
// discard the reassembler and move on.
f.mu.Lock()
f.release(r, false /* timedOut */)
f.mu.Unlock()
return nil, 0, false, fmt.Errorf("fragmentation processing error: %w", err)
}
f.mu.Lock()
f.memSize += memConsumed
if done {
f.release(r, false /* timedOut */)
}
// Evict reassemblers if we are consuming more memory than highLimit until
// we reach lowLimit.
if f.memSize > f.highLimit {
for f.memSize > f.lowLimit {
tail := f.rList.Back()
if tail == nil {
break
}
f.release(tail, false /* timedOut */)
}
}
f.mu.Unlock()
return resPkt, firstFragmentProto, done, nil
}
// Release releases all underlying resources.
func (f *Fragmentation) Release() {
f.mu.Lock()
defer f.mu.Unlock()
for _, r := range f.reassemblers {
f.release(r, false /* timedOut */)
}
f.reassemblers = nil
}
func (f *Fragmentation) release(r *reassembler, timedOut bool) {
// Before releasing a fragment we need to check if r is already marked as done.
// Otherwise, we would delete it twice.
if r.checkDoneOrMark() {
return
}
delete(f.reassemblers, r.id)
f.rList.Remove(r)
f.memSize -= r.memSize
if f.memSize < 0 {
log.Warningf("memory counter < 0 (%d), this is an accounting bug that requires investigation", f.memSize)
f.memSize = 0
}
if h := f.timeoutHandler; timedOut && h != nil {
h.OnReassemblyTimeout(r.pkt)
}
if r.pkt != nil {
r.pkt.DecRef()
r.pkt = nil
}
for _, h := range r.holes {
if h.pkt != nil {
h.pkt.DecRef()
h.pkt = nil
}
}
r.holes = nil
}
// releaseReassemblersLocked releases already-expired reassemblers, then
// schedules the job to call back itself for the remaining reassemblers if
// any. This function must be called with f.mu locked.
func (f *Fragmentation) releaseReassemblersLocked() {
now := f.clock.NowMonotonic()
for {
// The reassembler at the end of the list is the oldest.
r := f.rList.Back()
if r == nil {
// The list is empty.
break
}
elapsed := now.Sub(r.createdAt)
if f.timeout > elapsed {
// If the oldest reassembler has not expired, schedule the release
// job so that this function is called back when it has expired.
f.releaseJob.Schedule(f.timeout - elapsed)
break
}
// If the oldest reassembler has already expired, release it.
f.release(r, true /* timedOut*/)
}
}
// PacketFragmenter is the book-keeping struct for packet fragmentation.
type PacketFragmenter struct {
transportHeader []byte
data buffer.Buffer
reserve int
fragmentPayloadLen int
fragmentCount int
currentFragment int
fragmentOffset int
}
// MakePacketFragmenter prepares the struct needed for packet fragmentation.
//
// pkt is the packet to be fragmented.
//
// fragmentPayloadLen is the maximum number of bytes of fragmentable data a fragment can
// have.
//
// reserve is the number of bytes that should be reserved for the headers in
// each generated fragment.
func MakePacketFragmenter(pkt *stack.PacketBuffer, fragmentPayloadLen uint32, reserve int) PacketFragmenter {
// As per RFC 8200 Section 4.5, some IPv6 extension headers should not be
// repeated in each fragment. However we do not currently support any header
// of that kind yet, so the following computation is valid for both IPv4 and
// IPv6.
// TODO(gvisor.dev/issue/3912): Once Authentication or ESP Headers are
// supported for outbound packets, the fragmentable data should not include
// these headers.
var fragmentableData buffer.Buffer
fragmentableData.Append(pkt.TransportHeader().View())
pktBuf := pkt.Data().ToBuffer()
fragmentableData.Merge(&pktBuf)
fragmentCount := (uint32(fragmentableData.Size()) + fragmentPayloadLen - 1) / fragmentPayloadLen
return PacketFragmenter{
data: fragmentableData,
reserve: reserve,
fragmentPayloadLen: int(fragmentPayloadLen),
fragmentCount: int(fragmentCount),
}
}
// BuildNextFragment returns a packet with the payload of the next fragment,
// along with the fragment's offset, the number of bytes copied and a boolean
// indicating if there are more fragments left or not. If this function is
// called again after it indicated that no more fragments were left, it will
// panic.
//
// Note that the returned packet will not have its network and link headers
// populated, but space for them will be reserved. The transport header will be
// stored in the packet's data.
func (pf *PacketFragmenter) BuildNextFragment() (*stack.PacketBuffer, int, int, bool) {
if pf.currentFragment >= pf.fragmentCount {
panic("BuildNextFragment should not be called again after the last fragment was returned")
}
fragPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
ReserveHeaderBytes: pf.reserve,
})
// Copy data for the fragment.
copied := fragPkt.Data().ReadFrom(&pf.data, pf.fragmentPayloadLen)
offset := pf.fragmentOffset
pf.fragmentOffset += copied
pf.currentFragment++
more := pf.currentFragment != pf.fragmentCount
return fragPkt, offset, copied, more
}
// RemainingFragmentCount returns the number of fragments left to be built.
func (pf *PacketFragmenter) RemainingFragmentCount() int {
return pf.fragmentCount - pf.currentFragment
}
// Release frees resources owned by the packet fragmenter.
func (pf *PacketFragmenter) Release() {
pf.data.Release()
}

View file

@ -0,0 +1,246 @@
// automatically generated by stateify.
package fragmentation
import (
"context"
"github.com/sagernet/gvisor/pkg/state"
)
func (f *FragmentID) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.FragmentID"
}
func (f *FragmentID) StateFields() []string {
return []string{
"Source",
"Destination",
"ID",
"Protocol",
}
}
func (f *FragmentID) beforeSave() {}
// +checklocksignore
func (f *FragmentID) StateSave(stateSinkObject state.Sink) {
f.beforeSave()
stateSinkObject.Save(0, &f.Source)
stateSinkObject.Save(1, &f.Destination)
stateSinkObject.Save(2, &f.ID)
stateSinkObject.Save(3, &f.Protocol)
}
func (f *FragmentID) afterLoad(context.Context) {}
// +checklocksignore
func (f *FragmentID) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &f.Source)
stateSourceObject.Load(1, &f.Destination)
stateSourceObject.Load(2, &f.ID)
stateSourceObject.Load(3, &f.Protocol)
}
func (f *Fragmentation) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.Fragmentation"
}
func (f *Fragmentation) StateFields() []string {
return []string{
"highLimit",
"lowLimit",
"reassemblers",
"rList",
"memSize",
"timeout",
"blockSize",
"clock",
"releaseJob",
"timeoutHandler",
}
}
func (f *Fragmentation) beforeSave() {}
// +checklocksignore
func (f *Fragmentation) StateSave(stateSinkObject state.Sink) {
f.beforeSave()
stateSinkObject.Save(0, &f.highLimit)
stateSinkObject.Save(1, &f.lowLimit)
stateSinkObject.Save(2, &f.reassemblers)
stateSinkObject.Save(3, &f.rList)
stateSinkObject.Save(4, &f.memSize)
stateSinkObject.Save(5, &f.timeout)
stateSinkObject.Save(6, &f.blockSize)
stateSinkObject.Save(7, &f.clock)
stateSinkObject.Save(8, &f.releaseJob)
stateSinkObject.Save(9, &f.timeoutHandler)
}
func (f *Fragmentation) afterLoad(context.Context) {}
// +checklocksignore
func (f *Fragmentation) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &f.highLimit)
stateSourceObject.Load(1, &f.lowLimit)
stateSourceObject.Load(2, &f.reassemblers)
stateSourceObject.Load(3, &f.rList)
stateSourceObject.Load(4, &f.memSize)
stateSourceObject.Load(5, &f.timeout)
stateSourceObject.Load(6, &f.blockSize)
stateSourceObject.Load(7, &f.clock)
stateSourceObject.Load(8, &f.releaseJob)
stateSourceObject.Load(9, &f.timeoutHandler)
}
func (h *hole) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.hole"
}
func (h *hole) StateFields() []string {
return []string{
"first",
"last",
"filled",
"final",
"pkt",
}
}
func (h *hole) beforeSave() {}
// +checklocksignore
func (h *hole) StateSave(stateSinkObject state.Sink) {
h.beforeSave()
stateSinkObject.Save(0, &h.first)
stateSinkObject.Save(1, &h.last)
stateSinkObject.Save(2, &h.filled)
stateSinkObject.Save(3, &h.final)
stateSinkObject.Save(4, &h.pkt)
}
func (h *hole) afterLoad(context.Context) {}
// +checklocksignore
func (h *hole) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &h.first)
stateSourceObject.Load(1, &h.last)
stateSourceObject.Load(2, &h.filled)
stateSourceObject.Load(3, &h.final)
stateSourceObject.Load(4, &h.pkt)
}
func (r *reassembler) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.reassembler"
}
func (r *reassembler) StateFields() []string {
return []string{
"reassemblerEntry",
"id",
"memSize",
"proto",
"holes",
"filled",
"done",
"createdAt",
"pkt",
}
}
func (r *reassembler) beforeSave() {}
// +checklocksignore
func (r *reassembler) StateSave(stateSinkObject state.Sink) {
r.beforeSave()
stateSinkObject.Save(0, &r.reassemblerEntry)
stateSinkObject.Save(1, &r.id)
stateSinkObject.Save(2, &r.memSize)
stateSinkObject.Save(3, &r.proto)
stateSinkObject.Save(4, &r.holes)
stateSinkObject.Save(5, &r.filled)
stateSinkObject.Save(6, &r.done)
stateSinkObject.Save(7, &r.createdAt)
stateSinkObject.Save(8, &r.pkt)
}
func (r *reassembler) afterLoad(context.Context) {}
// +checklocksignore
func (r *reassembler) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &r.reassemblerEntry)
stateSourceObject.Load(1, &r.id)
stateSourceObject.Load(2, &r.memSize)
stateSourceObject.Load(3, &r.proto)
stateSourceObject.Load(4, &r.holes)
stateSourceObject.Load(5, &r.filled)
stateSourceObject.Load(6, &r.done)
stateSourceObject.Load(7, &r.createdAt)
stateSourceObject.Load(8, &r.pkt)
}
func (l *reassemblerList) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.reassemblerList"
}
func (l *reassemblerList) StateFields() []string {
return []string{
"head",
"tail",
}
}
func (l *reassemblerList) beforeSave() {}
// +checklocksignore
func (l *reassemblerList) StateSave(stateSinkObject state.Sink) {
l.beforeSave()
stateSinkObject.Save(0, &l.head)
stateSinkObject.Save(1, &l.tail)
}
func (l *reassemblerList) afterLoad(context.Context) {}
// +checklocksignore
func (l *reassemblerList) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &l.head)
stateSourceObject.Load(1, &l.tail)
}
func (e *reassemblerEntry) StateTypeName() string {
return "pkg/tcpip/network/internal/fragmentation.reassemblerEntry"
}
func (e *reassemblerEntry) StateFields() []string {
return []string{
"next",
"prev",
}
}
func (e *reassemblerEntry) beforeSave() {}
// +checklocksignore
func (e *reassemblerEntry) StateSave(stateSinkObject state.Sink) {
e.beforeSave()
stateSinkObject.Save(0, &e.next)
stateSinkObject.Save(1, &e.prev)
}
func (e *reassemblerEntry) afterLoad(context.Context) {}
// +checklocksignore
func (e *reassemblerEntry) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &e.next)
stateSourceObject.Load(1, &e.prev)
}
func init() {
state.Register((*FragmentID)(nil))
state.Register((*Fragmentation)(nil))
state.Register((*hole)(nil))
state.Register((*reassembler)(nil))
state.Register((*reassemblerList)(nil))
state.Register((*reassemblerEntry)(nil))
}

View file

@ -0,0 +1,185 @@
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fragmentation
import (
"math"
"sort"
"github.com/sagernet/gvisor/pkg/sync"
"github.com/sagernet/gvisor/pkg/tcpip"
"github.com/sagernet/gvisor/pkg/tcpip/stack"
)
// +stateify savable
type hole struct {
first uint16
last uint16
filled bool
final bool
// pkt is the fragment packet if hole is filled. We keep the whole pkt rather
// than the fragmented payload to prevent binding to specific buffer types.
pkt *stack.PacketBuffer
}
// +stateify savable
type reassembler struct {
reassemblerEntry
id FragmentID
memSize int
proto uint8
mu sync.Mutex `state:"nosave"`
holes []hole
filled int
done bool
createdAt tcpip.MonotonicTime
pkt *stack.PacketBuffer
}
func newReassembler(id FragmentID, clock tcpip.Clock) *reassembler {
r := &reassembler{
id: id,
createdAt: clock.NowMonotonic(),
}
r.holes = append(r.holes, hole{
first: 0,
last: math.MaxUint16,
filled: false,
final: true,
})
return r
}
func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *stack.PacketBuffer) (*stack.PacketBuffer, uint8, bool, int, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.done {
// A concurrent goroutine might have already reassembled
// the packet and emptied the heap while this goroutine
// was waiting on the mutex. We don't have to do anything in this case.
return nil, 0, false, 0, nil
}
var holeFound bool
var memConsumed int
for i := range r.holes {
currentHole := &r.holes[i]
if last < currentHole.first || currentHole.last < first {
continue
}
// For IPv6, overlaps with an existing fragment are explicitly forbidden by
// RFC 8200 section 4.5:
// If any of the fragments being reassembled overlap with any other
// fragments being reassembled for the same packet, reassembly of that
// packet must be abandoned and all the fragments that have been received
// for that packet must be discarded, and no ICMP error messages should be
// sent.
//
// It is not explicitly forbidden for IPv4, but to keep parity with Linux we
// disallow it as well:
// https://github.com/torvalds/linux/blob/38525c6/net/ipv4/inet_fragment.c#L349
if first < currentHole.first || currentHole.last < last {
// Incoming fragment only partially fits in the free hole.
return nil, 0, false, 0, ErrFragmentOverlap
}
if !more {
if !currentHole.final || currentHole.filled && currentHole.last != last {
// We have another final fragment, which does not perfectly overlap.
return nil, 0, false, 0, ErrFragmentConflict
}
}
holeFound = true
if currentHole.filled {
// Incoming fragment is a duplicate.
continue
}
// We are populating the current hole with the payload and creating a new
// hole for any unfilled ranges on either end.
if first > currentHole.first {
r.holes = append(r.holes, hole{
first: currentHole.first,
last: first - 1,
filled: false,
final: false,
})
}
if last < currentHole.last && more {
r.holes = append(r.holes, hole{
first: last + 1,
last: currentHole.last,
filled: false,
final: currentHole.final,
})
currentHole.final = false
}
memConsumed = pkt.MemSize()
r.memSize += memConsumed
// Update the current hole to precisely match the incoming fragment.
r.holes[i] = hole{
first: first,
last: last,
filled: true,
final: currentHole.final,
pkt: pkt.Clone(),
}
r.filled++
// For IPv6, it is possible to have different Protocol values between
// fragments of a packet (because, unlike IPv4, the Protocol is not used to
// identify a fragment). In this case, only the Protocol of the first
// fragment must be used as per RFC 8200 Section 4.5.
//
// TODO(gvisor.dev/issue/3648): During reassembly of an IPv6 packet, IP
// options received in the first fragment should be used - and they should
// override options from following fragments.
if first == 0 {
if r.pkt != nil {
r.pkt.DecRef()
}
r.pkt = pkt.Clone()
r.proto = proto
}
break
}
if !holeFound {
// Incoming fragment is beyond end.
return nil, 0, false, 0, ErrFragmentConflict
}
// Check if all the holes have been filled and we are ready to reassemble.
if r.filled < len(r.holes) {
return nil, 0, false, memConsumed, nil
}
sort.Slice(r.holes, func(i, j int) bool {
return r.holes[i].first < r.holes[j].first
})
resPkt := r.holes[0].pkt.Clone()
for i := 1; i < len(r.holes); i++ {
stack.MergeFragment(resPkt, r.holes[i].pkt)
}
return resPkt, r.proto, true /* done */, memConsumed, nil
}
func (r *reassembler) checkDoneOrMark() bool {
r.mu.Lock()
prev := r.done
r.done = true
r.mu.Unlock()
return prev
}

View file

@ -0,0 +1,239 @@
package fragmentation
// ElementMapper provides an identity mapping by default.
//
// This can be replaced to provide a struct that maps elements to linker
// objects, if they are not the same. An ElementMapper is not typically
// required if: Linker is left as is, Element is left as is, or Linker and
// Element are the same type.
type reassemblerElementMapper struct{}
// linkerFor maps an Element to a Linker.
//
// This default implementation should be inlined.
//
//go:nosplit
func (reassemblerElementMapper) linkerFor(elem *reassembler) *reassembler { return elem }
// List is an intrusive list. Entries can be added to or removed from the list
// in O(1) time and with no additional memory allocations.
//
// The zero value for List is an empty list ready to use.
//
// To iterate over a list (where l is a List):
//
// for e := l.Front(); e != nil; e = e.Next() {
// // do something with e.
// }
//
// +stateify savable
type reassemblerList struct {
head *reassembler
tail *reassembler
}
// Reset resets list l to the empty state.
func (l *reassemblerList) Reset() {
l.head = nil
l.tail = nil
}
// Empty returns true iff the list is empty.
//
//go:nosplit
func (l *reassemblerList) Empty() bool {
return l.head == nil
}
// Front returns the first element of list l or nil.
//
//go:nosplit
func (l *reassemblerList) Front() *reassembler {
return l.head
}
// Back returns the last element of list l or nil.
//
//go:nosplit
func (l *reassemblerList) Back() *reassembler {
return l.tail
}
// Len returns the number of elements in the list.
//
// NOTE: This is an O(n) operation.
//
//go:nosplit
func (l *reassemblerList) Len() (count int) {
for e := l.Front(); e != nil; e = (reassemblerElementMapper{}.linkerFor(e)).Next() {
count++
}
return count
}
// PushFront inserts the element e at the front of list l.
//
//go:nosplit
func (l *reassemblerList) PushFront(e *reassembler) {
linker := reassemblerElementMapper{}.linkerFor(e)
linker.SetNext(l.head)
linker.SetPrev(nil)
if l.head != nil {
reassemblerElementMapper{}.linkerFor(l.head).SetPrev(e)
} else {
l.tail = e
}
l.head = e
}
// PushFrontList inserts list m at the start of list l, emptying m.
//
//go:nosplit
func (l *reassemblerList) PushFrontList(m *reassemblerList) {
if l.head == nil {
l.head = m.head
l.tail = m.tail
} else if m.head != nil {
reassemblerElementMapper{}.linkerFor(l.head).SetPrev(m.tail)
reassemblerElementMapper{}.linkerFor(m.tail).SetNext(l.head)
l.head = m.head
}
m.head = nil
m.tail = nil
}
// PushBack inserts the element e at the back of list l.
//
//go:nosplit
func (l *reassemblerList) PushBack(e *reassembler) {
linker := reassemblerElementMapper{}.linkerFor(e)
linker.SetNext(nil)
linker.SetPrev(l.tail)
if l.tail != nil {
reassemblerElementMapper{}.linkerFor(l.tail).SetNext(e)
} else {
l.head = e
}
l.tail = e
}
// PushBackList inserts list m at the end of list l, emptying m.
//
//go:nosplit
func (l *reassemblerList) PushBackList(m *reassemblerList) {
if l.head == nil {
l.head = m.head
l.tail = m.tail
} else if m.head != nil {
reassemblerElementMapper{}.linkerFor(l.tail).SetNext(m.head)
reassemblerElementMapper{}.linkerFor(m.head).SetPrev(l.tail)
l.tail = m.tail
}
m.head = nil
m.tail = nil
}
// InsertAfter inserts e after b.
//
//go:nosplit
func (l *reassemblerList) InsertAfter(b, e *reassembler) {
bLinker := reassemblerElementMapper{}.linkerFor(b)
eLinker := reassemblerElementMapper{}.linkerFor(e)
a := bLinker.Next()
eLinker.SetNext(a)
eLinker.SetPrev(b)
bLinker.SetNext(e)
if a != nil {
reassemblerElementMapper{}.linkerFor(a).SetPrev(e)
} else {
l.tail = e
}
}
// InsertBefore inserts e before a.
//
//go:nosplit
func (l *reassemblerList) InsertBefore(a, e *reassembler) {
aLinker := reassemblerElementMapper{}.linkerFor(a)
eLinker := reassemblerElementMapper{}.linkerFor(e)
b := aLinker.Prev()
eLinker.SetNext(a)
eLinker.SetPrev(b)
aLinker.SetPrev(e)
if b != nil {
reassemblerElementMapper{}.linkerFor(b).SetNext(e)
} else {
l.head = e
}
}
// Remove removes e from l.
//
//go:nosplit
func (l *reassemblerList) Remove(e *reassembler) {
linker := reassemblerElementMapper{}.linkerFor(e)
prev := linker.Prev()
next := linker.Next()
if prev != nil {
reassemblerElementMapper{}.linkerFor(prev).SetNext(next)
} else if l.head == e {
l.head = next
}
if next != nil {
reassemblerElementMapper{}.linkerFor(next).SetPrev(prev)
} else if l.tail == e {
l.tail = prev
}
linker.SetNext(nil)
linker.SetPrev(nil)
}
// Entry is a default implementation of Linker. Users can add anonymous fields
// of this type to their structs to make them automatically implement the
// methods needed by List.
//
// +stateify savable
type reassemblerEntry struct {
next *reassembler
prev *reassembler
}
// Next returns the entry that follows e in the list.
//
//go:nosplit
func (e *reassemblerEntry) Next() *reassembler {
return e.next
}
// Prev returns the entry that precedes e in the list.
//
//go:nosplit
func (e *reassemblerEntry) Prev() *reassembler {
return e.prev
}
// SetNext assigns 'entry' as the entry that follows e in the list.
//
//go:nosplit
func (e *reassemblerEntry) SetNext(elem *reassembler) {
e.next = elem
}
// SetPrev assigns 'entry' as the entry that precedes e in the list.
//
//go:nosplit
func (e *reassemblerEntry) SetPrev(elem *reassembler) {
e.prev = elem
}

View file

@ -0,0 +1,304 @@
// Copyright 2021 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package ip holds IPv4/IPv6 common utilities.
package ip
import (
"bytes"
"fmt"
"io"
"github.com/sagernet/gvisor/pkg/sync"
"github.com/sagernet/gvisor/pkg/tcpip"
"github.com/sagernet/gvisor/pkg/tcpip/stack"
)
type extendRequest int
const (
notRequested extendRequest = iota
requested
extended
)
// +stateify savable
type dadState struct {
nonce []byte
extendRequest extendRequest
done *bool
timer tcpip.Timer
completionHandlers []stack.DADCompletionHandler
}
// DADProtocol is a protocol whose core state machine can be represented by DAD.
type DADProtocol interface {
// SendDADMessage attempts to send a DAD probe message.
SendDADMessage(tcpip.Address, []byte) tcpip.Error
}
// DADOptions holds options for DAD.
//
// +stateify savable
type DADOptions struct {
Clock tcpip.Clock
// TODO(b/341946753): Restore when netstack is savable.
SecureRNG io.Reader `state:"nosave"`
NonceSize uint8
ExtendDADTransmits uint8
Protocol DADProtocol
NICID tcpip.NICID
}
// DAD performs duplicate address detection for addresses.
//
// +stateify savable
type DAD struct {
opts DADOptions
configs stack.DADConfigurations
protocolMU sync.Locker `state:"nosave"`
addresses map[tcpip.Address]dadState
}
// Init initializes the DAD state.
//
// Must only be called once for the lifetime of d; Init will panic if it is
// called twice.
//
// The lock will only be taken when timers fire.
func (d *DAD) Init(protocolMU sync.Locker, configs stack.DADConfigurations, opts DADOptions) {
if d.addresses != nil {
panic("attempted to initialize DAD state twice")
}
if opts.NonceSize != 0 && opts.ExtendDADTransmits == 0 {
panic(fmt.Sprintf("given a non-zero value for NonceSize (%d) but zero for ExtendDADTransmits", opts.NonceSize))
}
configs.Validate()
*d = DAD{
opts: opts,
configs: configs,
protocolMU: protocolMU,
addresses: make(map[tcpip.Address]dadState),
}
}
// CheckDuplicateAddressLocked performs DAD for an address, calling the
// completion handler once DAD resolves.
//
// If DAD is already performing for the provided address, h will be called when
// the currently running process completes.
//
// Precondition: d.protocolMU must be locked.
func (d *DAD) CheckDuplicateAddressLocked(addr tcpip.Address, h stack.DADCompletionHandler) stack.DADCheckAddressDisposition {
if d.configs.DupAddrDetectTransmits == 0 {
return stack.DADDisabled
}
ret := stack.DADAlreadyRunning
s, ok := d.addresses[addr]
if !ok {
ret = stack.DADStarting
remaining := d.configs.DupAddrDetectTransmits
// Protected by d.protocolMU.
done := false
s = dadState{
done: &done,
timer: d.opts.Clock.AfterFunc(0, func() {
dadDone := remaining == 0
nonce, earlyReturn := func() ([]byte, bool) {
d.protocolMU.Lock()
defer d.protocolMU.Unlock()
if done {
return nil, true
}
s, ok := d.addresses[addr]
if !ok {
panic(fmt.Sprintf("dad: timer fired but missing state for %s on NIC(%d)", addr, d.opts.NICID))
}
// As per RFC 7527 section 4
//
// If any probe is looped back within RetransTimer milliseconds
// after having sent DupAddrDetectTransmits NS(DAD) messages, the
// interface continues with another MAX_MULTICAST_SOLICIT number of
// NS(DAD) messages transmitted RetransTimer milliseconds apart.
if dadDone && s.extendRequest == requested {
dadDone = false
remaining = d.opts.ExtendDADTransmits
s.extendRequest = extended
}
if !dadDone && d.opts.NonceSize != 0 {
if s.nonce == nil {
s.nonce = make([]byte, d.opts.NonceSize)
}
if n, err := io.ReadFull(d.opts.SecureRNG, s.nonce); err != nil {
panic(fmt.Sprintf("SecureRNG.Read(...): %s", err))
} else if n != len(s.nonce) {
panic(fmt.Sprintf("expected to read %d bytes from secure RNG, only read %d bytes", len(s.nonce), n))
}
}
d.addresses[addr] = s
return s.nonce, false
}()
if earlyReturn {
return
}
var err tcpip.Error
if !dadDone {
err = d.opts.Protocol.SendDADMessage(addr, nonce)
}
d.protocolMU.Lock()
defer d.protocolMU.Unlock()
if done {
return
}
s, ok := d.addresses[addr]
if !ok {
panic(fmt.Sprintf("dad: timer fired but missing state for %s on NIC(%d)", addr, d.opts.NICID))
}
if !dadDone && err == nil {
remaining--
s.timer.Reset(d.configs.RetransmitTimer)
return
}
// At this point we know that either DAD has resolved or we hit an error
// sending the last DAD message. Either way, clear the DAD state.
done = false
s.timer.Stop()
delete(d.addresses, addr)
var res stack.DADResult = &stack.DADSucceeded{}
if err != nil {
res = &stack.DADError{Err: err}
}
for _, h := range s.completionHandlers {
h(res)
}
}),
}
}
s.completionHandlers = append(s.completionHandlers, h)
d.addresses[addr] = s
return ret
}
// ExtendIfNonceEqualLockedDisposition enumerates the possible results from
// ExtendIfNonceEqualLocked.
type ExtendIfNonceEqualLockedDisposition int
const (
// Extended indicates that the DAD process was extended.
Extended ExtendIfNonceEqualLockedDisposition = iota
// AlreadyExtended indicates that the DAD process was already extended.
AlreadyExtended
// NoDADStateFound indicates that DAD state was not found for the address.
NoDADStateFound
// NonceDisabled indicates that nonce values are not sent with DAD messages.
NonceDisabled
// NonceNotEqual indicates that the nonce value passed and the nonce in the
// last send DAD message are not equal.
NonceNotEqual
)
// ExtendIfNonceEqualLocked extends the DAD process if the provided nonce is the
// same as the nonce sent in the last DAD message.
//
// Precondition: d.protocolMU must be locked.
func (d *DAD) ExtendIfNonceEqualLocked(addr tcpip.Address, nonce []byte) ExtendIfNonceEqualLockedDisposition {
s, ok := d.addresses[addr]
if !ok {
return NoDADStateFound
}
if d.opts.NonceSize == 0 {
return NonceDisabled
}
if s.extendRequest != notRequested {
return AlreadyExtended
}
// As per RFC 7527 section 4
//
// If any probe is looped back within RetransTimer milliseconds after having
// sent DupAddrDetectTransmits NS(DAD) messages, the interface continues
// with another MAX_MULTICAST_SOLICIT number of NS(DAD) messages transmitted
// RetransTimer milliseconds apart.
//
// If a DAD message has already been sent and the nonce value we observed is
// the same as the nonce value we last sent, then we assume our probe was
// looped back and request an extension to the DAD process.
//
// Note, the first DAD message is sent asynchronously so we need to make sure
// that we sent a DAD message by checking if we have a nonce value set.
if s.nonce != nil && bytes.Equal(s.nonce, nonce) {
s.extendRequest = requested
d.addresses[addr] = s
return Extended
}
return NonceNotEqual
}
// StopLocked stops a currently running DAD process.
//
// Precondition: d.protocolMU must be locked.
func (d *DAD) StopLocked(addr tcpip.Address, reason stack.DADResult) {
s, ok := d.addresses[addr]
if !ok {
return
}
*s.done = true
s.timer.Stop()
delete(d.addresses, addr)
for _, h := range s.completionHandlers {
h(reason)
}
}
// SetConfigsLocked sets the DAD configurations.
//
// Precondition: d.protocolMU must be locked.
func (d *DAD) SetConfigsLocked(c stack.DADConfigurations) {
c.Validate()
d.configs = c
}

View file

@ -0,0 +1,129 @@
// Copyright 2021 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ip
import (
"fmt"
"github.com/sagernet/gvisor/pkg/tcpip"
)
// ForwardingError represents an error that occurred while trying to forward
// a packet.
type ForwardingError interface {
isForwardingError()
fmt.Stringer
}
// ErrTTLExceeded indicates that the received packet's TTL has been exceeded.
type ErrTTLExceeded struct{}
func (*ErrTTLExceeded) isForwardingError() {}
func (*ErrTTLExceeded) String() string { return "ttl exceeded" }
// ErrOutgoingDeviceNoBufferSpace indicates that the outgoing device does not
// have enough space to hold a buffer.
type ErrOutgoingDeviceNoBufferSpace struct{}
func (*ErrOutgoingDeviceNoBufferSpace) isForwardingError() {}
func (*ErrOutgoingDeviceNoBufferSpace) String() string { return "no device buffer space" }
// ErrParameterProblem indicates the received packet had a problem with an IP
// parameter.
type ErrParameterProblem struct{}
func (*ErrParameterProblem) isForwardingError() {}
func (*ErrParameterProblem) String() string { return "parameter problem" }
// ErrInitializingSourceAddress indicates the received packet had a source
// address that may only be used on the local network as part of initialization
// work.
type ErrInitializingSourceAddress struct{}
func (*ErrInitializingSourceAddress) isForwardingError() {}
func (*ErrInitializingSourceAddress) String() string { return "initializing source address" }
// ErrLinkLocalSourceAddress indicates the received packet had a link-local
// source address.
type ErrLinkLocalSourceAddress struct{}
func (*ErrLinkLocalSourceAddress) isForwardingError() {}
func (*ErrLinkLocalSourceAddress) String() string { return "link local source address" }
// ErrLinkLocalDestinationAddress indicates the received packet had a link-local
// destination address.
type ErrLinkLocalDestinationAddress struct{}
func (*ErrLinkLocalDestinationAddress) isForwardingError() {}
func (*ErrLinkLocalDestinationAddress) String() string { return "link local destination address" }
// ErrHostUnreachable indicates that the destination host could not be reached.
type ErrHostUnreachable struct{}
func (*ErrHostUnreachable) isForwardingError() {}
func (*ErrHostUnreachable) String() string { return "no route to host" }
// ErrMessageTooLong indicates the packet was too big for the outgoing MTU.
//
// +stateify savable
type ErrMessageTooLong struct{}
func (*ErrMessageTooLong) isForwardingError() {}
func (*ErrMessageTooLong) String() string { return "message too long" }
// ErrNoMulticastPendingQueueBufferSpace indicates that a multicast packet
// could not be added to the pending packet queue due to insufficient buffer
// space.
//
// +stateify savable
type ErrNoMulticastPendingQueueBufferSpace struct{}
func (*ErrNoMulticastPendingQueueBufferSpace) isForwardingError() {}
func (*ErrNoMulticastPendingQueueBufferSpace) String() string { return "no buffer space" }
// ErrUnexpectedMulticastInputInterface indicates that the interface that the
// packet arrived on did not match the routes expected input interface.
type ErrUnexpectedMulticastInputInterface struct{}
func (*ErrUnexpectedMulticastInputInterface) isForwardingError() {}
func (*ErrUnexpectedMulticastInputInterface) String() string { return "unexpected input interface" }
// ErrUnknownOutputEndpoint indicates that the output endpoint associated with
// a route could not be found.
type ErrUnknownOutputEndpoint struct{}
func (*ErrUnknownOutputEndpoint) isForwardingError() {}
func (*ErrUnknownOutputEndpoint) String() string { return "unknown endpoint" }
// ErrOther indicates the packet coould not be forwarded for a reason
// captured by the contained error.
type ErrOther struct {
Err tcpip.Error
}
func (*ErrOther) isForwardingError() {}
func (e *ErrOther) String() string { return fmt.Sprintf("other tcpip error: %s", e.Err) }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,435 @@
// automatically generated by stateify.
package ip
import (
"context"
"github.com/sagernet/gvisor/pkg/state"
)
func (d *dadState) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.dadState"
}
func (d *dadState) StateFields() []string {
return []string{
"nonce",
"extendRequest",
"done",
"timer",
"completionHandlers",
}
}
func (d *dadState) beforeSave() {}
// +checklocksignore
func (d *dadState) StateSave(stateSinkObject state.Sink) {
d.beforeSave()
stateSinkObject.Save(0, &d.nonce)
stateSinkObject.Save(1, &d.extendRequest)
stateSinkObject.Save(2, &d.done)
stateSinkObject.Save(3, &d.timer)
stateSinkObject.Save(4, &d.completionHandlers)
}
func (d *dadState) afterLoad(context.Context) {}
// +checklocksignore
func (d *dadState) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &d.nonce)
stateSourceObject.Load(1, &d.extendRequest)
stateSourceObject.Load(2, &d.done)
stateSourceObject.Load(3, &d.timer)
stateSourceObject.Load(4, &d.completionHandlers)
}
func (d *DADOptions) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.DADOptions"
}
func (d *DADOptions) StateFields() []string {
return []string{
"Clock",
"NonceSize",
"ExtendDADTransmits",
"Protocol",
"NICID",
}
}
func (d *DADOptions) beforeSave() {}
// +checklocksignore
func (d *DADOptions) StateSave(stateSinkObject state.Sink) {
d.beforeSave()
stateSinkObject.Save(0, &d.Clock)
stateSinkObject.Save(1, &d.NonceSize)
stateSinkObject.Save(2, &d.ExtendDADTransmits)
stateSinkObject.Save(3, &d.Protocol)
stateSinkObject.Save(4, &d.NICID)
}
func (d *DADOptions) afterLoad(context.Context) {}
// +checklocksignore
func (d *DADOptions) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &d.Clock)
stateSourceObject.Load(1, &d.NonceSize)
stateSourceObject.Load(2, &d.ExtendDADTransmits)
stateSourceObject.Load(3, &d.Protocol)
stateSourceObject.Load(4, &d.NICID)
}
func (d *DAD) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.DAD"
}
func (d *DAD) StateFields() []string {
return []string{
"opts",
"configs",
"addresses",
}
}
func (d *DAD) beforeSave() {}
// +checklocksignore
func (d *DAD) StateSave(stateSinkObject state.Sink) {
d.beforeSave()
stateSinkObject.Save(0, &d.opts)
stateSinkObject.Save(1, &d.configs)
stateSinkObject.Save(2, &d.addresses)
}
func (d *DAD) afterLoad(context.Context) {}
// +checklocksignore
func (d *DAD) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &d.opts)
stateSourceObject.Load(1, &d.configs)
stateSourceObject.Load(2, &d.addresses)
}
func (e *ErrMessageTooLong) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.ErrMessageTooLong"
}
func (e *ErrMessageTooLong) StateFields() []string {
return []string{}
}
func (e *ErrMessageTooLong) beforeSave() {}
// +checklocksignore
func (e *ErrMessageTooLong) StateSave(stateSinkObject state.Sink) {
e.beforeSave()
}
func (e *ErrMessageTooLong) afterLoad(context.Context) {}
// +checklocksignore
func (e *ErrMessageTooLong) StateLoad(ctx context.Context, stateSourceObject state.Source) {
}
func (e *ErrNoMulticastPendingQueueBufferSpace) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.ErrNoMulticastPendingQueueBufferSpace"
}
func (e *ErrNoMulticastPendingQueueBufferSpace) StateFields() []string {
return []string{}
}
func (e *ErrNoMulticastPendingQueueBufferSpace) beforeSave() {}
// +checklocksignore
func (e *ErrNoMulticastPendingQueueBufferSpace) StateSave(stateSinkObject state.Sink) {
e.beforeSave()
}
func (e *ErrNoMulticastPendingQueueBufferSpace) afterLoad(context.Context) {}
// +checklocksignore
func (e *ErrNoMulticastPendingQueueBufferSpace) StateLoad(ctx context.Context, stateSourceObject state.Source) {
}
func (m *multicastGroupState) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.multicastGroupState"
}
func (m *multicastGroupState) StateFields() []string {
return []string{
"joins",
"transmissionLeft",
"lastToSendReport",
"delayedReportJob",
"queriedIncludeSources",
"deleteScheduled",
}
}
func (m *multicastGroupState) beforeSave() {}
// +checklocksignore
func (m *multicastGroupState) StateSave(stateSinkObject state.Sink) {
m.beforeSave()
stateSinkObject.Save(0, &m.joins)
stateSinkObject.Save(1, &m.transmissionLeft)
stateSinkObject.Save(2, &m.lastToSendReport)
stateSinkObject.Save(3, &m.delayedReportJob)
stateSinkObject.Save(4, &m.queriedIncludeSources)
stateSinkObject.Save(5, &m.deleteScheduled)
}
func (m *multicastGroupState) afterLoad(context.Context) {}
// +checklocksignore
func (m *multicastGroupState) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &m.joins)
stateSourceObject.Load(1, &m.transmissionLeft)
stateSourceObject.Load(2, &m.lastToSendReport)
stateSourceObject.Load(3, &m.delayedReportJob)
stateSourceObject.Load(4, &m.queriedIncludeSources)
stateSourceObject.Load(5, &m.deleteScheduled)
}
func (g *GenericMulticastProtocolOptions) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.GenericMulticastProtocolOptions"
}
func (g *GenericMulticastProtocolOptions) StateFields() []string {
return []string{
"Clock",
"Protocol",
"MaxUnsolicitedReportDelay",
}
}
func (g *GenericMulticastProtocolOptions) beforeSave() {}
// +checklocksignore
func (g *GenericMulticastProtocolOptions) StateSave(stateSinkObject state.Sink) {
g.beforeSave()
stateSinkObject.Save(0, &g.Clock)
stateSinkObject.Save(1, &g.Protocol)
stateSinkObject.Save(2, &g.MaxUnsolicitedReportDelay)
}
func (g *GenericMulticastProtocolOptions) afterLoad(context.Context) {}
// +checklocksignore
func (g *GenericMulticastProtocolOptions) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &g.Clock)
stateSourceObject.Load(1, &g.Protocol)
stateSourceObject.Load(2, &g.MaxUnsolicitedReportDelay)
}
func (g *GenericMulticastProtocolState) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.GenericMulticastProtocolState"
}
func (g *GenericMulticastProtocolState) StateFields() []string {
return []string{
"opts",
"memberships",
"robustnessVariable",
"queryInterval",
"mode",
"modeTimer",
"generalQueryV2Timer",
"stateChangedReportV2Timer",
"stateChangedReportV2TimerSet",
}
}
func (g *GenericMulticastProtocolState) beforeSave() {}
// +checklocksignore
func (g *GenericMulticastProtocolState) StateSave(stateSinkObject state.Sink) {
g.beforeSave()
stateSinkObject.Save(0, &g.opts)
stateSinkObject.Save(1, &g.memberships)
stateSinkObject.Save(2, &g.robustnessVariable)
stateSinkObject.Save(3, &g.queryInterval)
stateSinkObject.Save(4, &g.mode)
stateSinkObject.Save(5, &g.modeTimer)
stateSinkObject.Save(6, &g.generalQueryV2Timer)
stateSinkObject.Save(7, &g.stateChangedReportV2Timer)
stateSinkObject.Save(8, &g.stateChangedReportV2TimerSet)
}
func (g *GenericMulticastProtocolState) afterLoad(context.Context) {}
// +checklocksignore
func (g *GenericMulticastProtocolState) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &g.opts)
stateSourceObject.Load(1, &g.memberships)
stateSourceObject.Load(2, &g.robustnessVariable)
stateSourceObject.Load(3, &g.queryInterval)
stateSourceObject.Load(4, &g.mode)
stateSourceObject.Load(5, &g.modeTimer)
stateSourceObject.Load(6, &g.generalQueryV2Timer)
stateSourceObject.Load(7, &g.stateChangedReportV2Timer)
stateSourceObject.Load(8, &g.stateChangedReportV2TimerSet)
}
func (m *MultiCounterIPForwardingStats) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.MultiCounterIPForwardingStats"
}
func (m *MultiCounterIPForwardingStats) StateFields() []string {
return []string{
"Unrouteable",
"ExhaustedTTL",
"InitializingSource",
"LinkLocalSource",
"LinkLocalDestination",
"PacketTooBig",
"HostUnreachable",
"ExtensionHeaderProblem",
"UnexpectedMulticastInputInterface",
"UnknownOutputEndpoint",
"NoMulticastPendingQueueBufferSpace",
"OutgoingDeviceNoBufferSpace",
"Errors",
"OutgoingDeviceClosedForSend",
}
}
func (m *MultiCounterIPForwardingStats) beforeSave() {}
// +checklocksignore
func (m *MultiCounterIPForwardingStats) StateSave(stateSinkObject state.Sink) {
m.beforeSave()
stateSinkObject.Save(0, &m.Unrouteable)
stateSinkObject.Save(1, &m.ExhaustedTTL)
stateSinkObject.Save(2, &m.InitializingSource)
stateSinkObject.Save(3, &m.LinkLocalSource)
stateSinkObject.Save(4, &m.LinkLocalDestination)
stateSinkObject.Save(5, &m.PacketTooBig)
stateSinkObject.Save(6, &m.HostUnreachable)
stateSinkObject.Save(7, &m.ExtensionHeaderProblem)
stateSinkObject.Save(8, &m.UnexpectedMulticastInputInterface)
stateSinkObject.Save(9, &m.UnknownOutputEndpoint)
stateSinkObject.Save(10, &m.NoMulticastPendingQueueBufferSpace)
stateSinkObject.Save(11, &m.OutgoingDeviceNoBufferSpace)
stateSinkObject.Save(12, &m.Errors)
stateSinkObject.Save(13, &m.OutgoingDeviceClosedForSend)
}
func (m *MultiCounterIPForwardingStats) afterLoad(context.Context) {}
// +checklocksignore
func (m *MultiCounterIPForwardingStats) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &m.Unrouteable)
stateSourceObject.Load(1, &m.ExhaustedTTL)
stateSourceObject.Load(2, &m.InitializingSource)
stateSourceObject.Load(3, &m.LinkLocalSource)
stateSourceObject.Load(4, &m.LinkLocalDestination)
stateSourceObject.Load(5, &m.PacketTooBig)
stateSourceObject.Load(6, &m.HostUnreachable)
stateSourceObject.Load(7, &m.ExtensionHeaderProblem)
stateSourceObject.Load(8, &m.UnexpectedMulticastInputInterface)
stateSourceObject.Load(9, &m.UnknownOutputEndpoint)
stateSourceObject.Load(10, &m.NoMulticastPendingQueueBufferSpace)
stateSourceObject.Load(11, &m.OutgoingDeviceNoBufferSpace)
stateSourceObject.Load(12, &m.Errors)
stateSourceObject.Load(13, &m.OutgoingDeviceClosedForSend)
}
func (m *MultiCounterIPStats) StateTypeName() string {
return "pkg/tcpip/network/internal/ip.MultiCounterIPStats"
}
func (m *MultiCounterIPStats) StateFields() []string {
return []string{
"PacketsReceived",
"ValidPacketsReceived",
"DisabledPacketsReceived",
"InvalidDestinationAddressesReceived",
"InvalidSourceAddressesReceived",
"PacketsDelivered",
"PacketsSent",
"OutgoingPacketErrors",
"MalformedPacketsReceived",
"MalformedFragmentsReceived",
"IPTablesPreroutingDropped",
"IPTablesInputDropped",
"IPTablesForwardDropped",
"IPTablesOutputDropped",
"IPTablesPostroutingDropped",
"OptionTimestampReceived",
"OptionRecordRouteReceived",
"OptionRouterAlertReceived",
"OptionUnknownReceived",
"Forwarding",
}
}
func (m *MultiCounterIPStats) beforeSave() {}
// +checklocksignore
func (m *MultiCounterIPStats) StateSave(stateSinkObject state.Sink) {
m.beforeSave()
stateSinkObject.Save(0, &m.PacketsReceived)
stateSinkObject.Save(1, &m.ValidPacketsReceived)
stateSinkObject.Save(2, &m.DisabledPacketsReceived)
stateSinkObject.Save(3, &m.InvalidDestinationAddressesReceived)
stateSinkObject.Save(4, &m.InvalidSourceAddressesReceived)
stateSinkObject.Save(5, &m.PacketsDelivered)
stateSinkObject.Save(6, &m.PacketsSent)
stateSinkObject.Save(7, &m.OutgoingPacketErrors)
stateSinkObject.Save(8, &m.MalformedPacketsReceived)
stateSinkObject.Save(9, &m.MalformedFragmentsReceived)
stateSinkObject.Save(10, &m.IPTablesPreroutingDropped)
stateSinkObject.Save(11, &m.IPTablesInputDropped)
stateSinkObject.Save(12, &m.IPTablesForwardDropped)
stateSinkObject.Save(13, &m.IPTablesOutputDropped)
stateSinkObject.Save(14, &m.IPTablesPostroutingDropped)
stateSinkObject.Save(15, &m.OptionTimestampReceived)
stateSinkObject.Save(16, &m.OptionRecordRouteReceived)
stateSinkObject.Save(17, &m.OptionRouterAlertReceived)
stateSinkObject.Save(18, &m.OptionUnknownReceived)
stateSinkObject.Save(19, &m.Forwarding)
}
func (m *MultiCounterIPStats) afterLoad(context.Context) {}
// +checklocksignore
func (m *MultiCounterIPStats) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &m.PacketsReceived)
stateSourceObject.Load(1, &m.ValidPacketsReceived)
stateSourceObject.Load(2, &m.DisabledPacketsReceived)
stateSourceObject.Load(3, &m.InvalidDestinationAddressesReceived)
stateSourceObject.Load(4, &m.InvalidSourceAddressesReceived)
stateSourceObject.Load(5, &m.PacketsDelivered)
stateSourceObject.Load(6, &m.PacketsSent)
stateSourceObject.Load(7, &m.OutgoingPacketErrors)
stateSourceObject.Load(8, &m.MalformedPacketsReceived)
stateSourceObject.Load(9, &m.MalformedFragmentsReceived)
stateSourceObject.Load(10, &m.IPTablesPreroutingDropped)
stateSourceObject.Load(11, &m.IPTablesInputDropped)
stateSourceObject.Load(12, &m.IPTablesForwardDropped)
stateSourceObject.Load(13, &m.IPTablesOutputDropped)
stateSourceObject.Load(14, &m.IPTablesPostroutingDropped)
stateSourceObject.Load(15, &m.OptionTimestampReceived)
stateSourceObject.Load(16, &m.OptionRecordRouteReceived)
stateSourceObject.Load(17, &m.OptionRouterAlertReceived)
stateSourceObject.Load(18, &m.OptionUnknownReceived)
stateSourceObject.Load(19, &m.Forwarding)
}
func init() {
state.Register((*dadState)(nil))
state.Register((*DADOptions)(nil))
state.Register((*DAD)(nil))
state.Register((*ErrMessageTooLong)(nil))
state.Register((*ErrNoMulticastPendingQueueBufferSpace)(nil))
state.Register((*multicastGroupState)(nil))
state.Register((*GenericMulticastProtocolOptions)(nil))
state.Register((*GenericMulticastProtocolState)(nil))
state.Register((*MultiCounterIPForwardingStats)(nil))
state.Register((*MultiCounterIPStats)(nil))
}

View file

@ -0,0 +1,219 @@
// Copyright 2020 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ip
import "github.com/sagernet/gvisor/pkg/tcpip"
// LINT.IfChange(MultiCounterIPForwardingStats)
// MultiCounterIPForwardingStats holds IP forwarding statistics. Each counter
// may have several versions.
//
// +stateify savable
type MultiCounterIPForwardingStats struct {
// Unrouteable is the number of IP packets received which were dropped
// because the netstack could not construct a route to their
// destination.
Unrouteable tcpip.MultiCounterStat
// ExhaustedTTL is the number of IP packets received which were dropped
// because their TTL was exhausted.
ExhaustedTTL tcpip.MultiCounterStat
// InitializingSource is the number of IP packets which were dropped
// because they contained a source address that may only be used on the local
// network as part of initialization work.
InitializingSource tcpip.MultiCounterStat
// LinkLocalSource is the number of IP packets which were dropped
// because they contained a link-local source address.
LinkLocalSource tcpip.MultiCounterStat
// LinkLocalDestination is the number of IP packets which were dropped
// because they contained a link-local destination address.
LinkLocalDestination tcpip.MultiCounterStat
// PacketTooBig is the number of IP packets which were dropped because they
// were too big for the outgoing MTU.
PacketTooBig tcpip.MultiCounterStat
// HostUnreachable is the number of IP packets received which could not be
// successfully forwarded due to an unresolvable next hop.
HostUnreachable tcpip.MultiCounterStat
// ExtensionHeaderProblem is the number of IP packets which were dropped
// because of a problem encountered when processing an IPv6 extension
// header.
ExtensionHeaderProblem tcpip.MultiCounterStat
// UnexpectedMulticastInputInterface is the number of multicast packets that
// were received on an interface that did not match the corresponding route's
// expected input interface.
UnexpectedMulticastInputInterface tcpip.MultiCounterStat
// UnknownOutputEndpoint is the number of packets that could not be forwarded
// because the output endpoint could not be found.
UnknownOutputEndpoint tcpip.MultiCounterStat
// NoMulticastPendingQueueBufferSpace is the number of multicast packets that
// were dropped due to insufficient buffer space in the pending packet queue.
NoMulticastPendingQueueBufferSpace tcpip.MultiCounterStat
// OutgoingDeviceNoBufferSpace is the number of packets that were dropped due
// to insufficient space in the outgoing device.
OutgoingDeviceNoBufferSpace tcpip.MultiCounterStat
// Errors is the number of IP packets received which could not be
// successfully forwarded.
Errors tcpip.MultiCounterStat
// OutgoingDeviceClosedForSend is the number of packets that were dropped due
// to the outgoing device being closed for send.
OutgoingDeviceClosedForSend tcpip.MultiCounterStat
}
// Init sets internal counters to track a and b counters.
func (m *MultiCounterIPForwardingStats) Init(a, b *tcpip.IPForwardingStats) {
m.Unrouteable.Init(a.Unrouteable, b.Unrouteable)
m.Errors.Init(a.Errors, b.Errors)
m.InitializingSource.Init(a.InitializingSource, b.InitializingSource)
m.LinkLocalSource.Init(a.LinkLocalSource, b.LinkLocalSource)
m.LinkLocalDestination.Init(a.LinkLocalDestination, b.LinkLocalDestination)
m.ExtensionHeaderProblem.Init(a.ExtensionHeaderProblem, b.ExtensionHeaderProblem)
m.PacketTooBig.Init(a.PacketTooBig, b.PacketTooBig)
m.ExhaustedTTL.Init(a.ExhaustedTTL, b.ExhaustedTTL)
m.HostUnreachable.Init(a.HostUnreachable, b.HostUnreachable)
m.UnexpectedMulticastInputInterface.Init(a.UnexpectedMulticastInputInterface, b.UnexpectedMulticastInputInterface)
m.UnknownOutputEndpoint.Init(a.UnknownOutputEndpoint, b.UnknownOutputEndpoint)
m.NoMulticastPendingQueueBufferSpace.Init(a.NoMulticastPendingQueueBufferSpace, b.NoMulticastPendingQueueBufferSpace)
m.OutgoingDeviceNoBufferSpace.Init(a.OutgoingDeviceNoBufferSpace, b.OutgoingDeviceNoBufferSpace)
m.OutgoingDeviceClosedForSend.Init(a.OutgoingDeviceClosedForSend, b.OutgoingDeviceClosedForSend)
}
// LINT.ThenChange(../../../tcpip.go:IPForwardingStats)
// LINT.IfChange(MultiCounterIPStats)
// MultiCounterIPStats holds IP statistics, each counter may have several
// versions.
//
// +stateify savable
type MultiCounterIPStats struct {
// PacketsReceived is the number of IP packets received from the link
// layer.
PacketsReceived tcpip.MultiCounterStat
// ValidPacketsReceived is the number of valid IP packets that reached the IP
// layer.
ValidPacketsReceived tcpip.MultiCounterStat
// DisabledPacketsReceived is the number of IP packets received from
// the link layer when the IP layer is disabled.
DisabledPacketsReceived tcpip.MultiCounterStat
// InvalidDestinationAddressesReceived is the number of IP packets
// received with an unknown or invalid destination address.
InvalidDestinationAddressesReceived tcpip.MultiCounterStat
// InvalidSourceAddressesReceived is the number of IP packets received
// with a source address that should never have been received on the
// wire.
InvalidSourceAddressesReceived tcpip.MultiCounterStat
// PacketsDelivered is the number of incoming IP packets successfully
// delivered to the transport layer.
PacketsDelivered tcpip.MultiCounterStat
// PacketsSent is the number of IP packets sent via WritePacket.
PacketsSent tcpip.MultiCounterStat
// OutgoingPacketErrors is the number of IP packets which failed to
// write to a link-layer endpoint.
OutgoingPacketErrors tcpip.MultiCounterStat
// MalformedPacketsReceived is the number of IP Packets that were
// dropped due to the IP packet header failing validation checks.
MalformedPacketsReceived tcpip.MultiCounterStat
// MalformedFragmentsReceived is the number of IP Fragments that were
// dropped due to the fragment failing validation checks.
MalformedFragmentsReceived tcpip.MultiCounterStat
// IPTablesPreroutingDropped is the number of IP packets dropped in the
// Prerouting chain.
IPTablesPreroutingDropped tcpip.MultiCounterStat
// IPTablesInputDropped is the number of IP packets dropped in the
// Input chain.
IPTablesInputDropped tcpip.MultiCounterStat
// IPTablesForwardDropped is the number of IP packets dropped in the
// Forward chain.
IPTablesForwardDropped tcpip.MultiCounterStat
// IPTablesOutputDropped is the number of IP packets dropped in the
// Output chain.
IPTablesOutputDropped tcpip.MultiCounterStat
// IPTablesPostroutingDropped is the number of IP packets dropped in
// the Postrouting chain.
IPTablesPostroutingDropped tcpip.MultiCounterStat
// TODO(https://gvisor.dev/issues/5529): Move the IPv4-only option
// stats out of IPStats.
// OptionTimestampReceived is the number of Timestamp options seen.
OptionTimestampReceived tcpip.MultiCounterStat
// OptionRecordRouteReceived is the number of Record Route options
// seen.
OptionRecordRouteReceived tcpip.MultiCounterStat
// OptionRouterAlertReceived is the number of Router Alert options
// seen.
OptionRouterAlertReceived tcpip.MultiCounterStat
// OptionUnknownReceived is the number of unknown IP options seen.
OptionUnknownReceived tcpip.MultiCounterStat
// Forwarding collects stats related to IP forwarding.
Forwarding MultiCounterIPForwardingStats
}
// Init sets internal counters to track a and b counters.
func (m *MultiCounterIPStats) Init(a, b *tcpip.IPStats) {
m.PacketsReceived.Init(a.PacketsReceived, b.PacketsReceived)
m.ValidPacketsReceived.Init(a.ValidPacketsReceived, b.ValidPacketsReceived)
m.DisabledPacketsReceived.Init(a.DisabledPacketsReceived, b.DisabledPacketsReceived)
m.InvalidDestinationAddressesReceived.Init(a.InvalidDestinationAddressesReceived, b.InvalidDestinationAddressesReceived)
m.InvalidSourceAddressesReceived.Init(a.InvalidSourceAddressesReceived, b.InvalidSourceAddressesReceived)
m.PacketsDelivered.Init(a.PacketsDelivered, b.PacketsDelivered)
m.PacketsSent.Init(a.PacketsSent, b.PacketsSent)
m.OutgoingPacketErrors.Init(a.OutgoingPacketErrors, b.OutgoingPacketErrors)
m.MalformedPacketsReceived.Init(a.MalformedPacketsReceived, b.MalformedPacketsReceived)
m.MalformedFragmentsReceived.Init(a.MalformedFragmentsReceived, b.MalformedFragmentsReceived)
m.IPTablesPreroutingDropped.Init(a.IPTablesPreroutingDropped, b.IPTablesPreroutingDropped)
m.IPTablesInputDropped.Init(a.IPTablesInputDropped, b.IPTablesInputDropped)
m.IPTablesForwardDropped.Init(a.IPTablesForwardDropped, b.IPTablesForwardDropped)
m.IPTablesOutputDropped.Init(a.IPTablesOutputDropped, b.IPTablesOutputDropped)
m.IPTablesPostroutingDropped.Init(a.IPTablesPostroutingDropped, b.IPTablesPostroutingDropped)
m.OptionTimestampReceived.Init(a.OptionTimestampReceived, b.OptionTimestampReceived)
m.OptionRecordRouteReceived.Init(a.OptionRecordRouteReceived, b.OptionRecordRouteReceived)
m.OptionRouterAlertReceived.Init(a.OptionRouterAlertReceived, b.OptionRouterAlertReceived)
m.OptionUnknownReceived.Init(a.OptionUnknownReceived, b.OptionUnknownReceived)
m.Forwarding.Init(&a.Forwarding, &b.Forwarding)
}
// LINT.ThenChange(../../../tcpip.go:IPStats)

View file

@ -0,0 +1,137 @@
// automatically generated by stateify.
package multicast
import (
"context"
"github.com/sagernet/gvisor/pkg/state"
)
func (r *RouteTable) StateTypeName() string {
return "pkg/tcpip/network/internal/multicast.RouteTable"
}
func (r *RouteTable) StateFields() []string {
return []string{
"installedRoutes",
"pendingRoutes",
"cleanupPendingRoutesTimer",
"isCleanupRoutineRunning",
"config",
}
}
func (r *RouteTable) beforeSave() {}
// +checklocksignore
func (r *RouteTable) StateSave(stateSinkObject state.Sink) {
r.beforeSave()
stateSinkObject.Save(0, &r.installedRoutes)
stateSinkObject.Save(1, &r.pendingRoutes)
stateSinkObject.Save(2, &r.cleanupPendingRoutesTimer)
stateSinkObject.Save(3, &r.isCleanupRoutineRunning)
stateSinkObject.Save(4, &r.config)
}
func (r *RouteTable) afterLoad(context.Context) {}
// +checklocksignore
func (r *RouteTable) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &r.installedRoutes)
stateSourceObject.Load(1, &r.pendingRoutes)
stateSourceObject.Load(2, &r.cleanupPendingRoutesTimer)
stateSourceObject.Load(3, &r.isCleanupRoutineRunning)
stateSourceObject.Load(4, &r.config)
}
func (r *InstalledRoute) StateTypeName() string {
return "pkg/tcpip/network/internal/multicast.InstalledRoute"
}
func (r *InstalledRoute) StateFields() []string {
return []string{
"MulticastRoute",
"lastUsedTimestamp",
}
}
func (r *InstalledRoute) beforeSave() {}
// +checklocksignore
func (r *InstalledRoute) StateSave(stateSinkObject state.Sink) {
r.beforeSave()
stateSinkObject.Save(0, &r.MulticastRoute)
stateSinkObject.Save(1, &r.lastUsedTimestamp)
}
func (r *InstalledRoute) afterLoad(context.Context) {}
// +checklocksignore
func (r *InstalledRoute) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &r.MulticastRoute)
stateSourceObject.Load(1, &r.lastUsedTimestamp)
}
func (p *PendingRoute) StateTypeName() string {
return "pkg/tcpip/network/internal/multicast.PendingRoute"
}
func (p *PendingRoute) StateFields() []string {
return []string{
"packets",
"expiration",
}
}
func (p *PendingRoute) beforeSave() {}
// +checklocksignore
func (p *PendingRoute) StateSave(stateSinkObject state.Sink) {
p.beforeSave()
stateSinkObject.Save(0, &p.packets)
stateSinkObject.Save(1, &p.expiration)
}
func (p *PendingRoute) afterLoad(context.Context) {}
// +checklocksignore
func (p *PendingRoute) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &p.packets)
stateSourceObject.Load(1, &p.expiration)
}
func (c *Config) StateTypeName() string {
return "pkg/tcpip/network/internal/multicast.Config"
}
func (c *Config) StateFields() []string {
return []string{
"MaxPendingQueueSize",
"Clock",
}
}
func (c *Config) beforeSave() {}
// +checklocksignore
func (c *Config) StateSave(stateSinkObject state.Sink) {
c.beforeSave()
stateSinkObject.Save(0, &c.MaxPendingQueueSize)
stateSinkObject.Save(1, &c.Clock)
}
func (c *Config) afterLoad(context.Context) {}
// +checklocksignore
func (c *Config) StateLoad(ctx context.Context, stateSourceObject state.Source) {
stateSourceObject.Load(0, &c.MaxPendingQueueSize)
stateSourceObject.Load(1, &c.Clock)
}
func init() {
state.Register((*RouteTable)(nil))
state.Register((*InstalledRoute)(nil))
state.Register((*PendingRoute)(nil))
state.Register((*Config)(nil))
}

View file

@ -0,0 +1,446 @@
// Copyright 2022 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package multicast contains utilities for supporting multicast routing.
package multicast
import (
"errors"
"fmt"
"sync"
"time"
"github.com/sagernet/gvisor/pkg/tcpip"
"github.com/sagernet/gvisor/pkg/tcpip/stack"
)
// RouteTable represents a multicast routing table.
//
// +stateify savable
type RouteTable struct {
// Internally, installed and pending routes are stored and locked separately
// A couple of reasons for structuring the table this way:
//
// 1. We can avoid write locking installed routes when pending packets are
// being queued. In other words, the happy path of reading installed
// routes doesn't require an exclusive lock.
// 2. The cleanup process for expired routes only needs to operate on pending
// routes. Like above, a write lock on the installed routes can be
// avoided.
// 3. This structure is similar to the Linux implementation:
// https://github.com/torvalds/linux/blob/cffb2b72d3e/include/linux/mroute_base.h#L250
// The installedMu lock should typically be acquired before the pendingMu
// lock. This ensures that installed routes can continue to be read even when
// the pending routes are write locked.
installedMu sync.RWMutex `state:"nosave"`
// Maintaining pointers ensures that the installed routes are exclusively
// locked only when a route is being installed.
// +checklocks:installedMu
installedRoutes map[stack.UnicastSourceAndMulticastDestination]*InstalledRoute
pendingMu sync.RWMutex `state:"nosave"`
// +checklocks:pendingMu
pendingRoutes map[stack.UnicastSourceAndMulticastDestination]PendingRoute
// cleanupPendingRoutesTimer is a timer that triggers a routine to remove
// pending routes that are expired.
// +checklocks:pendingMu
cleanupPendingRoutesTimer tcpip.Timer
// +checklocks:pendingMu
isCleanupRoutineRunning bool
config Config
}
var (
// ErrNoBufferSpace indicates that no buffer space is available in the
// pending route packet queue.
ErrNoBufferSpace = errors.New("unable to queue packet, no buffer space available")
// ErrMissingClock indicates that a clock was not provided as part of the
// Config, but is required.
ErrMissingClock = errors.New("clock must not be nil")
// ErrAlreadyInitialized indicates that RouteTable.Init was already invoked.
ErrAlreadyInitialized = errors.New("table is already initialized")
)
// InstalledRoute represents a route that is in the installed state.
//
// If a route is in the installed state, then it may be used to forward
// multicast packets.
//
// +stateify savable
type InstalledRoute struct {
stack.MulticastRoute
lastUsedTimestampMu sync.RWMutex `state:"nosave"`
// +checklocks:lastUsedTimestampMu
lastUsedTimestamp tcpip.MonotonicTime
}
// LastUsedTimestamp returns a monotonic timestamp that corresponds to the last
// time the route was used or updated.
func (r *InstalledRoute) LastUsedTimestamp() tcpip.MonotonicTime {
r.lastUsedTimestampMu.RLock()
defer r.lastUsedTimestampMu.RUnlock()
return r.lastUsedTimestamp
}
// SetLastUsedTimestamp sets the time that the route was last used.
//
// The timestamp is only updated if it occurs after the currently set
// timestamp. Callers should invoke this anytime the route is used to forward a
// packet.
func (r *InstalledRoute) SetLastUsedTimestamp(monotonicTime tcpip.MonotonicTime) {
r.lastUsedTimestampMu.Lock()
defer r.lastUsedTimestampMu.Unlock()
if monotonicTime.After(r.lastUsedTimestamp) {
r.lastUsedTimestamp = monotonicTime
}
}
// PendingRoute represents a route that is in the "pending" state.
//
// A route is in the pending state if an installed route does not yet exist
// for the entry. For such routes, packets are added to an expiring queue until
// a route is installed.
//
// +stateify savable
type PendingRoute struct {
packets []*stack.PacketBuffer
// expiration is the timestamp at which the pending route should be expired.
//
// If this value is before the current time, then this pending route will
// be dropped.
expiration tcpip.MonotonicTime
}
func (p *PendingRoute) releasePackets() {
for _, pkt := range p.packets {
pkt.DecRef()
}
}
func (p *PendingRoute) isExpired(currentTime tcpip.MonotonicTime) bool {
return currentTime.After(p.expiration)
}
const (
// DefaultMaxPendingQueueSize corresponds to the number of elements that can
// be in the packet queue for a pending route.
//
// Matches the Linux default queue size:
// https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L1186
DefaultMaxPendingQueueSize uint8 = 3
// DefaultPendingRouteExpiration is the default maximum lifetime of a pending
// route.
//
// Matches the Linux default:
// https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L991
DefaultPendingRouteExpiration time.Duration = 10 * time.Second
// DefaultCleanupInterval is the default frequency of the routine that
// expires pending routes.
//
// Matches the Linux default:
// https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L793
DefaultCleanupInterval time.Duration = 10 * time.Second
)
// Config represents the options for configuring a RouteTable.
//
// +stateify savable
type Config struct {
// MaxPendingQueueSize corresponds to the maximum number of queued packets
// for a pending route.
//
// If the caller attempts to queue a packet and the queue already contains
// MaxPendingQueueSize elements, then the packet will be rejected and should
// not be forwarded.
MaxPendingQueueSize uint8
// Clock represents the clock that should be used to obtain the current time.
//
// This field is required and must have a non-nil value.
Clock tcpip.Clock
}
// DefaultConfig returns the default configuration for the table.
func DefaultConfig(clock tcpip.Clock) Config {
return Config{
MaxPendingQueueSize: DefaultMaxPendingQueueSize,
Clock: clock,
}
}
// Init initializes the RouteTable with the provided config.
//
// An error is returned if the config is not valid.
//
// Must be called before any other function on the table.
func (r *RouteTable) Init(config Config) error {
r.installedMu.Lock()
defer r.installedMu.Unlock()
r.pendingMu.Lock()
defer r.pendingMu.Unlock()
if r.installedRoutes != nil {
return ErrAlreadyInitialized
}
if config.Clock == nil {
return ErrMissingClock
}
r.config = config
r.installedRoutes = make(map[stack.UnicastSourceAndMulticastDestination]*InstalledRoute)
r.pendingRoutes = make(map[stack.UnicastSourceAndMulticastDestination]PendingRoute)
return nil
}
// Close cleans up resources held by the table.
//
// Calling this will stop the cleanup routine and release any packets owned by
// the table.
func (r *RouteTable) Close() {
r.pendingMu.Lock()
defer r.pendingMu.Unlock()
if r.cleanupPendingRoutesTimer != nil {
r.cleanupPendingRoutesTimer.Stop()
}
for key, route := range r.pendingRoutes {
delete(r.pendingRoutes, key)
route.releasePackets()
}
}
// maybeStopCleanupRoutine stops the pending routes cleanup routine if no
// pending routes exist.
//
// Returns true if the timer is not running. Otherwise, returns false.
//
// +checklocks:r.pendingMu
func (r *RouteTable) maybeStopCleanupRoutineLocked() bool {
if !r.isCleanupRoutineRunning {
return true
}
if len(r.pendingRoutes) == 0 {
r.cleanupPendingRoutesTimer.Stop()
r.isCleanupRoutineRunning = false
return true
}
return false
}
func (r *RouteTable) cleanupPendingRoutes() {
currentTime := r.config.Clock.NowMonotonic()
r.pendingMu.Lock()
defer r.pendingMu.Unlock()
for key, route := range r.pendingRoutes {
if route.isExpired(currentTime) {
delete(r.pendingRoutes, key)
route.releasePackets()
}
}
if stopped := r.maybeStopCleanupRoutineLocked(); !stopped {
r.cleanupPendingRoutesTimer.Reset(DefaultCleanupInterval)
}
}
func (r *RouteTable) newPendingRoute() PendingRoute {
return PendingRoute{
packets: make([]*stack.PacketBuffer, 0, r.config.MaxPendingQueueSize),
expiration: r.config.Clock.NowMonotonic().Add(DefaultPendingRouteExpiration),
}
}
// NewInstalledRoute instantiates an installed route for the table.
func (r *RouteTable) NewInstalledRoute(route stack.MulticastRoute) *InstalledRoute {
return &InstalledRoute{
MulticastRoute: route,
lastUsedTimestamp: r.config.Clock.NowMonotonic(),
}
}
// GetRouteResult represents the result of calling GetRouteOrInsertPending.
type GetRouteResult struct {
// GetRouteResultState signals the result of calling GetRouteOrInsertPending.
GetRouteResultState GetRouteResultState
// InstalledRoute represents the existing installed route. This field will
// only be populated if the GetRouteResultState is InstalledRouteFound.
InstalledRoute *InstalledRoute
}
// GetRouteResultState signals the result of calling GetRouteOrInsertPending.
type GetRouteResultState uint8
const (
// InstalledRouteFound indicates that an InstalledRoute was found.
InstalledRouteFound GetRouteResultState = iota
// PacketQueuedInPendingRoute indicates that the packet was queued in an
// existing pending route.
PacketQueuedInPendingRoute
// NoRouteFoundAndPendingInserted indicates that no route was found and that
// a pending route was newly inserted into the RouteTable.
NoRouteFoundAndPendingInserted
)
func (e GetRouteResultState) String() string {
switch e {
case InstalledRouteFound:
return "InstalledRouteFound"
case PacketQueuedInPendingRoute:
return "PacketQueuedInPendingRoute"
case NoRouteFoundAndPendingInserted:
return "NoRouteFoundAndPendingInserted"
default:
return fmt.Sprintf("%d", uint8(e))
}
}
// GetRouteOrInsertPending attempts to fetch the installed route that matches
// the provided key.
//
// If no matching installed route is found, then the pkt is cloned and queued
// in a pending route. The GetRouteResult.GetRouteResultState will indicate
// whether the pkt was queued in a new pending route or an existing one.
//
// If the relevant pending route queue is at max capacity, then returns false.
// Otherwise, returns true.
func (r *RouteTable) GetRouteOrInsertPending(key stack.UnicastSourceAndMulticastDestination, pkt *stack.PacketBuffer) (GetRouteResult, bool) {
r.installedMu.RLock()
defer r.installedMu.RUnlock()
if route, ok := r.installedRoutes[key]; ok {
return GetRouteResult{GetRouteResultState: InstalledRouteFound, InstalledRoute: route}, true
}
r.pendingMu.Lock()
defer r.pendingMu.Unlock()
pendingRoute, getRouteResultState := r.getOrCreatePendingRouteRLocked(key)
if len(pendingRoute.packets) >= int(r.config.MaxPendingQueueSize) {
// The incoming packet is rejected if the pending queue is already at max
// capacity. This behavior matches the Linux implementation:
// https://github.com/torvalds/linux/blob/ae085d7f936/net/ipv4/ipmr.c#L1147
return GetRouteResult{}, false
}
pendingRoute.packets = append(pendingRoute.packets, pkt.Clone())
r.pendingRoutes[key] = pendingRoute
if !r.isCleanupRoutineRunning {
// The cleanup routine isn't running, but should be. Start it.
if r.cleanupPendingRoutesTimer == nil {
r.cleanupPendingRoutesTimer = r.config.Clock.AfterFunc(DefaultCleanupInterval, r.cleanupPendingRoutes)
} else {
r.cleanupPendingRoutesTimer.Reset(DefaultCleanupInterval)
}
r.isCleanupRoutineRunning = true
}
return GetRouteResult{GetRouteResultState: getRouteResultState, InstalledRoute: nil}, true
}
// +checklocks:r.pendingMu
func (r *RouteTable) getOrCreatePendingRouteRLocked(key stack.UnicastSourceAndMulticastDestination) (PendingRoute, GetRouteResultState) {
if pendingRoute, ok := r.pendingRoutes[key]; ok {
return pendingRoute, PacketQueuedInPendingRoute
}
return r.newPendingRoute(), NoRouteFoundAndPendingInserted
}
// AddInstalledRoute adds the provided route to the table.
//
// Packets that were queued while the route was in the pending state are
// returned. The caller assumes ownership of these packets and is responsible
// for forwarding and releasing them. If an installed route already exists for
// the provided key, then it is overwritten.
func (r *RouteTable) AddInstalledRoute(key stack.UnicastSourceAndMulticastDestination, route *InstalledRoute) []*stack.PacketBuffer {
r.installedMu.Lock()
defer r.installedMu.Unlock()
r.installedRoutes[key] = route
r.pendingMu.Lock()
pendingRoute, ok := r.pendingRoutes[key]
delete(r.pendingRoutes, key)
// No need to reset the timer here. The cleanup routine is responsible for
// doing so.
_ = r.maybeStopCleanupRoutineLocked()
r.pendingMu.Unlock()
// Ignore the pending route if it is expired. It may be in this state since
// the cleanup process is only run periodically.
if !ok || pendingRoute.isExpired(r.config.Clock.NowMonotonic()) {
pendingRoute.releasePackets()
return nil
}
return pendingRoute.packets
}
// RemoveInstalledRoute deletes any installed route that matches the provided
// key.
//
// Returns true if a route was removed. Otherwise returns false.
func (r *RouteTable) RemoveInstalledRoute(key stack.UnicastSourceAndMulticastDestination) bool {
r.installedMu.Lock()
defer r.installedMu.Unlock()
if _, ok := r.installedRoutes[key]; ok {
delete(r.installedRoutes, key)
return true
}
return false
}
// RemoveAllInstalledRoutes removes all installed routes from the table.
func (r *RouteTable) RemoveAllInstalledRoutes() {
r.installedMu.Lock()
defer r.installedMu.Unlock()
for key := range r.installedRoutes {
delete(r.installedRoutes, key)
}
}
// GetLastUsedTimestamp returns a monotonic timestamp that represents the last
// time the route that matches the provided key was used or updated.
//
// Returns true if a matching route was found. Otherwise returns false.
func (r *RouteTable) GetLastUsedTimestamp(key stack.UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, bool) {
r.installedMu.RLock()
defer r.installedMu.RUnlock()
if route, ok := r.installedRoutes[key]; ok {
return route.LastUsedTimestamp(), true
}
return tcpip.MonotonicTime{}, false
}