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:
commit
2c4ae3b0a4
712 changed files with 185689 additions and 0 deletions
447
pkg/tcpip/link/tun/device.go
Normal file
447
pkg/tcpip/link/tun/device.go
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
// 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 tun
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/atomicbitops"
|
||||
"github.com/sagernet/gvisor/pkg/buffer"
|
||||
"github.com/sagernet/gvisor/pkg/context"
|
||||
"github.com/sagernet/gvisor/pkg/errors/linuxerr"
|
||||
"github.com/sagernet/gvisor/pkg/tcpip"
|
||||
"github.com/sagernet/gvisor/pkg/tcpip/header"
|
||||
"github.com/sagernet/gvisor/pkg/tcpip/link/channel"
|
||||
"github.com/sagernet/gvisor/pkg/tcpip/link/packetsocket"
|
||||
"github.com/sagernet/gvisor/pkg/tcpip/stack"
|
||||
"github.com/sagernet/gvisor/pkg/waiter"
|
||||
)
|
||||
|
||||
const (
|
||||
// drivers/net/tun.c:tun_net_init()
|
||||
defaultDevMtu = 1500
|
||||
|
||||
// Queue length for outbound packet, arriving at fd side for read. Overflow
|
||||
// causes packet drops. gVisor implementation-specific.
|
||||
defaultDevOutQueueLen = 1024
|
||||
)
|
||||
|
||||
var zeroMAC [6]byte
|
||||
|
||||
// Device is an opened /dev/net/tun device.
|
||||
//
|
||||
// +stateify savable
|
||||
type Device struct {
|
||||
waiter.Queue
|
||||
|
||||
mu deviceRWMutex `state:"nosave"`
|
||||
endpoint *tunEndpoint
|
||||
notifyHandle *channel.NotificationHandle
|
||||
flags Flags
|
||||
}
|
||||
|
||||
// Flags set properties of a Device
|
||||
//
|
||||
// +stateify savable
|
||||
type Flags struct {
|
||||
TUN bool
|
||||
TAP bool
|
||||
NoPacketInfo bool
|
||||
Exclusive bool
|
||||
}
|
||||
|
||||
// beforeSave is invoked by stateify.
|
||||
func (d *Device) beforeSave() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
// TODO(b/110961832): Restore the device to stack. At this moment, the stack
|
||||
// is not savable.
|
||||
if d.endpoint != nil {
|
||||
panic("/dev/net/tun does not support save/restore when a device is associated with it.")
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Device) SetPersistent(v bool) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.endpoint == nil {
|
||||
return linuxerr.EBADFD
|
||||
}
|
||||
|
||||
d.endpoint.setPersistent(v)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release implements fs.FileOperations.Release.
|
||||
func (d *Device) Release(ctx context.Context) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// Decrease refcount if there is an endpoint associated with this file.
|
||||
if d.endpoint != nil {
|
||||
d.endpoint.Drain()
|
||||
d.endpoint.RemoveNotify(d.notifyHandle)
|
||||
d.endpoint.DecRef(ctx)
|
||||
d.endpoint = nil
|
||||
}
|
||||
}
|
||||
|
||||
// SetIff services TUNSETIFF ioctl(2) request.
|
||||
func (d *Device) SetIff(ctx context.Context, s *stack.Stack, name string, flags Flags) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.endpoint != nil {
|
||||
return linuxerr.EINVAL
|
||||
}
|
||||
|
||||
// Input validation.
|
||||
if (flags.TAP && flags.TUN) || (!flags.TAP && !flags.TUN) {
|
||||
return linuxerr.EINVAL
|
||||
}
|
||||
|
||||
prefix := "tun"
|
||||
if flags.TAP {
|
||||
prefix = "tap"
|
||||
}
|
||||
|
||||
linkCaps := stack.CapabilityNone
|
||||
if flags.TAP {
|
||||
linkCaps |= stack.CapabilityResolutionRequired
|
||||
}
|
||||
|
||||
endpoint, err := attachOrCreateNIC(ctx, s, name, prefix, linkCaps, flags)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.endpoint = endpoint
|
||||
d.notifyHandle = d.endpoint.AddNotify(d)
|
||||
d.flags = flags
|
||||
return nil
|
||||
}
|
||||
|
||||
func attachOrCreateNIC(ctx context.Context, s *stack.Stack, name, prefix string, linkCaps stack.LinkEndpointCapabilities, flags Flags) (*tunEndpoint, error) {
|
||||
for {
|
||||
// 1. Try to attach to an existing NIC.
|
||||
if name != "" && !flags.Exclusive {
|
||||
if linkEP := s.GetLinkEndpointByName(name); linkEP != nil {
|
||||
packetEndpoint, ok := linkEP.(*packetsocket.Endpoint)
|
||||
if !ok {
|
||||
// Not a NIC created by tun device.
|
||||
return nil, linuxerr.EOPNOTSUPP
|
||||
}
|
||||
endpoint, ok := packetEndpoint.Child().(*tunEndpoint)
|
||||
if !ok {
|
||||
// Not a NIC created by tun device.
|
||||
return nil, linuxerr.EOPNOTSUPP
|
||||
}
|
||||
if !endpoint.TryIncRef() {
|
||||
// Race detected: NIC got deleted in between.
|
||||
continue
|
||||
}
|
||||
return endpoint, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Creating a new NIC.
|
||||
id := s.NextNICID()
|
||||
endpoint := &tunEndpoint{
|
||||
Endpoint: channel.New(defaultDevOutQueueLen, defaultDevMtu, ""),
|
||||
stack: s,
|
||||
nicID: id,
|
||||
name: name,
|
||||
isTap: prefix == "tap",
|
||||
}
|
||||
endpoint.InitRefs()
|
||||
endpoint.Endpoint.LinkEPCapabilities = linkCaps
|
||||
if endpoint.name == "" {
|
||||
endpoint.name = fmt.Sprintf("%s%d", prefix, id)
|
||||
}
|
||||
err := s.CreateNICWithOptions(endpoint.nicID, packetsocket.New(endpoint), stack.NICOptions{
|
||||
Name: endpoint.name,
|
||||
})
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
return endpoint, nil
|
||||
case *tcpip.ErrDuplicateNICID:
|
||||
endpoint.DecRef(ctx)
|
||||
if !flags.Exclusive {
|
||||
// Race detected: A NIC has been created in between.
|
||||
continue
|
||||
}
|
||||
return nil, linuxerr.EEXIST
|
||||
default:
|
||||
endpoint.DecRef(ctx)
|
||||
return nil, linuxerr.EINVAL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MTU returns the tun endpoint MTU (maximum transmission unit).
|
||||
func (d *Device) MTU() (uint32, error) {
|
||||
d.mu.RLock()
|
||||
endpoint := d.endpoint
|
||||
d.mu.RUnlock()
|
||||
if endpoint == nil {
|
||||
return 0, linuxerr.EBADFD
|
||||
}
|
||||
if !endpoint.IsAttached() {
|
||||
return 0, linuxerr.EIO
|
||||
}
|
||||
return endpoint.MTU(), nil
|
||||
}
|
||||
|
||||
// Write inject one inbound packet to the network interface.
|
||||
func (d *Device) Write(data *buffer.View) (int64, error) {
|
||||
d.mu.RLock()
|
||||
endpoint := d.endpoint
|
||||
d.mu.RUnlock()
|
||||
if endpoint == nil {
|
||||
return 0, linuxerr.EBADFD
|
||||
}
|
||||
if !endpoint.IsAttached() {
|
||||
return 0, linuxerr.EIO
|
||||
}
|
||||
|
||||
dataLen := int64(data.Size())
|
||||
|
||||
// Packet information.
|
||||
var pktInfoHdr PacketInfoHeader
|
||||
if !d.flags.NoPacketInfo {
|
||||
if dataLen < PacketInfoHeaderSize {
|
||||
// Ignore bad packet.
|
||||
return dataLen, nil
|
||||
}
|
||||
pktInfoHdrView := data.Clone()
|
||||
defer pktInfoHdrView.Release()
|
||||
pktInfoHdrView.CapLength(PacketInfoHeaderSize)
|
||||
pktInfoHdr = PacketInfoHeader(pktInfoHdrView.AsSlice())
|
||||
data.TrimFront(PacketInfoHeaderSize)
|
||||
}
|
||||
|
||||
// Ethernet header (TAP only).
|
||||
var ethHdr header.Ethernet
|
||||
if d.flags.TAP {
|
||||
if data.Size() < header.EthernetMinimumSize {
|
||||
// Ignore bad packet.
|
||||
return dataLen, nil
|
||||
}
|
||||
ethHdrView := data.Clone()
|
||||
defer ethHdrView.Release()
|
||||
ethHdrView.CapLength(header.EthernetMinimumSize)
|
||||
ethHdr = header.Ethernet(ethHdrView.AsSlice())
|
||||
data.TrimFront(header.EthernetMinimumSize)
|
||||
}
|
||||
|
||||
// Try to determine network protocol number, default zero.
|
||||
var protocol tcpip.NetworkProtocolNumber
|
||||
switch {
|
||||
case pktInfoHdr != nil:
|
||||
protocol = pktInfoHdr.Protocol()
|
||||
case ethHdr != nil:
|
||||
protocol = ethHdr.Type()
|
||||
case d.flags.TUN:
|
||||
// TUN interface with IFF_NO_PI enabled, thus
|
||||
// we need to determine protocol from version field
|
||||
version := data.AsSlice()[0] >> 4
|
||||
if version == 4 {
|
||||
protocol = header.IPv4ProtocolNumber
|
||||
} else if version == 6 {
|
||||
protocol = header.IPv6ProtocolNumber
|
||||
}
|
||||
}
|
||||
|
||||
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
ReserveHeaderBytes: len(ethHdr),
|
||||
Payload: buffer.MakeWithView(data.Clone()),
|
||||
})
|
||||
defer pkt.DecRef()
|
||||
copy(pkt.LinkHeader().Push(len(ethHdr)), ethHdr)
|
||||
endpoint.InjectInbound(protocol, pkt)
|
||||
return dataLen, nil
|
||||
}
|
||||
|
||||
// Read reads one outgoing packet from the network interface.
|
||||
func (d *Device) Read() (*buffer.View, error) {
|
||||
d.mu.RLock()
|
||||
endpoint := d.endpoint
|
||||
d.mu.RUnlock()
|
||||
if endpoint == nil {
|
||||
return nil, linuxerr.EBADFD
|
||||
}
|
||||
|
||||
pkt := endpoint.Read()
|
||||
if pkt == nil {
|
||||
return nil, linuxerr.ErrWouldBlock
|
||||
}
|
||||
v := d.encodePkt(pkt)
|
||||
pkt.DecRef()
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// encodePkt encodes packet for fd side.
|
||||
func (d *Device) encodePkt(pkt *stack.PacketBuffer) *buffer.View {
|
||||
var view *buffer.View
|
||||
|
||||
// Packet information.
|
||||
if !d.flags.NoPacketInfo {
|
||||
view = buffer.NewView(PacketInfoHeaderSize + pkt.Size())
|
||||
view.Grow(PacketInfoHeaderSize)
|
||||
hdr := PacketInfoHeader(view.AsSlice())
|
||||
hdr.Encode(&PacketInfoFields{
|
||||
Protocol: pkt.NetworkProtocolNumber,
|
||||
})
|
||||
pktView := pkt.ToView()
|
||||
view.Write(pktView.AsSlice())
|
||||
pktView.Release()
|
||||
} else {
|
||||
view = pkt.ToView()
|
||||
}
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
// Name returns the name of the attached network interface. Empty string if
|
||||
// unattached.
|
||||
func (d *Device) Name() string {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
if d.endpoint != nil {
|
||||
return d.endpoint.name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Flags returns the flags set for d. Zero value if unset.
|
||||
func (d *Device) Flags() Flags {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.flags
|
||||
}
|
||||
|
||||
// Readiness implements watier.Waitable.Readiness.
|
||||
func (d *Device) Readiness(mask waiter.EventMask) waiter.EventMask {
|
||||
if mask&waiter.ReadableEvents != 0 {
|
||||
d.mu.RLock()
|
||||
endpoint := d.endpoint
|
||||
d.mu.RUnlock()
|
||||
if endpoint != nil && endpoint.NumQueued() == 0 {
|
||||
mask &= ^waiter.ReadableEvents
|
||||
}
|
||||
}
|
||||
return mask & (waiter.ReadableEvents | waiter.WritableEvents)
|
||||
}
|
||||
|
||||
// WriteNotify implements channel.Notification.WriteNotify.
|
||||
func (d *Device) WriteNotify() {
|
||||
d.Notify(waiter.ReadableEvents)
|
||||
}
|
||||
|
||||
// tunEndpoint is the link endpoint for the NIC created by the tun device.
|
||||
//
|
||||
// It is ref-counted as multiple opening files can attach to the same NIC.
|
||||
// The last owner is responsible for deleting the NIC.
|
||||
//
|
||||
// +stateify savable
|
||||
type tunEndpoint struct {
|
||||
tunEndpointRefs
|
||||
*channel.Endpoint
|
||||
|
||||
stack *stack.Stack
|
||||
nicID tcpip.NICID
|
||||
name string
|
||||
isTap bool
|
||||
persistent atomicbitops.Bool
|
||||
closed atomicbitops.Bool
|
||||
|
||||
mu endpointMutex `state:"nosave"`
|
||||
onCloseAction func() `state:"nosave"`
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) setPersistent(v bool) {
|
||||
old := e.persistent.Swap(v)
|
||||
if old == v {
|
||||
return
|
||||
}
|
||||
if v {
|
||||
e.IncRef()
|
||||
} else {
|
||||
e.DecRef(context.Background())
|
||||
}
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) Close() {
|
||||
if e.closed.Swap(true) {
|
||||
return
|
||||
}
|
||||
|
||||
if e.persistent.Load() {
|
||||
e.DecRef(context.Background())
|
||||
}
|
||||
e.mu.Lock()
|
||||
action := e.onCloseAction
|
||||
e.onCloseAction = nil
|
||||
e.mu.Unlock()
|
||||
if action != nil {
|
||||
action()
|
||||
}
|
||||
e.Endpoint.Close()
|
||||
}
|
||||
|
||||
// SetOnCloseAction implements stack.LinkEndpoint.
|
||||
func (e *tunEndpoint) SetOnCloseAction(action func()) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.onCloseAction = action
|
||||
}
|
||||
|
||||
// DecRef decrements refcount of e, removing NIC if it reaches 0.
|
||||
func (e *tunEndpoint) DecRef(ctx context.Context) {
|
||||
e.tunEndpointRefs.DecRef(func() {
|
||||
e.Close()
|
||||
})
|
||||
}
|
||||
|
||||
// ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType.
|
||||
func (e *tunEndpoint) ARPHardwareType() header.ARPHardwareType {
|
||||
if e.isTap {
|
||||
return header.ARPHardwareEther
|
||||
}
|
||||
return header.ARPHardwareNone
|
||||
}
|
||||
|
||||
// AddHeader implements stack.LinkEndpoint.AddHeader.
|
||||
func (e *tunEndpoint) AddHeader(pkt *stack.PacketBuffer) {
|
||||
if !e.isTap {
|
||||
return
|
||||
}
|
||||
eth := header.Ethernet(pkt.LinkHeader().Push(header.EthernetMinimumSize))
|
||||
eth.Encode(&header.EthernetFields{
|
||||
SrcAddr: pkt.EgressRoute.LocalLinkAddress,
|
||||
DstAddr: pkt.EgressRoute.RemoteLinkAddress,
|
||||
Type: pkt.NetworkProtocolNumber,
|
||||
})
|
||||
}
|
||||
|
||||
// MaxHeaderLength returns the maximum size of the link layer header.
|
||||
func (e *tunEndpoint) MaxHeaderLength() uint16 {
|
||||
if e.isTap {
|
||||
return header.EthernetMinimumSize
|
||||
}
|
||||
return 0
|
||||
}
|
||||
96
pkg/tcpip/link/tun/device_mutex.go
Normal file
96
pkg/tcpip/link/tun/device_mutex.go
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
package tun
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/sync"
|
||||
"github.com/sagernet/gvisor/pkg/sync/locking"
|
||||
)
|
||||
|
||||
// RWMutex is sync.RWMutex with the correctness validator.
|
||||
type deviceRWMutex struct {
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// lockNames is a list of user-friendly lock names.
|
||||
// Populated in init.
|
||||
var devicelockNames []string
|
||||
|
||||
// lockNameIndex is used as an index passed to NestedLock and NestedUnlock,
|
||||
// referring to an index within lockNames.
|
||||
// Values are specified using the "consts" field of go_template_instance.
|
||||
type devicelockNameIndex int
|
||||
|
||||
// DO NOT REMOVE: The following function automatically replaced with lock index constants.
|
||||
// LOCK_NAME_INDEX_CONSTANTS
|
||||
const ()
|
||||
|
||||
// Lock locks m.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) Lock() {
|
||||
locking.AddGLock(deviceprefixIndex, -1)
|
||||
m.mu.Lock()
|
||||
}
|
||||
|
||||
// NestedLock locks m knowing that another lock of the same type is held.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) NestedLock(i devicelockNameIndex) {
|
||||
locking.AddGLock(deviceprefixIndex, int(i))
|
||||
m.mu.Lock()
|
||||
}
|
||||
|
||||
// Unlock unlocks m.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) Unlock() {
|
||||
m.mu.Unlock()
|
||||
locking.DelGLock(deviceprefixIndex, -1)
|
||||
}
|
||||
|
||||
// NestedUnlock unlocks m knowing that another lock of the same type is held.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) NestedUnlock(i devicelockNameIndex) {
|
||||
m.mu.Unlock()
|
||||
locking.DelGLock(deviceprefixIndex, int(i))
|
||||
}
|
||||
|
||||
// RLock locks m for reading.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) RLock() {
|
||||
locking.AddGLock(deviceprefixIndex, -1)
|
||||
m.mu.RLock()
|
||||
}
|
||||
|
||||
// RUnlock undoes a single RLock call.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) RUnlock() {
|
||||
m.mu.RUnlock()
|
||||
locking.DelGLock(deviceprefixIndex, -1)
|
||||
}
|
||||
|
||||
// RLockBypass locks m for reading without executing the validator.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) RLockBypass() {
|
||||
m.mu.RLock()
|
||||
}
|
||||
|
||||
// RUnlockBypass undoes a single RLockBypass call.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) RUnlockBypass() {
|
||||
m.mu.RUnlock()
|
||||
}
|
||||
|
||||
// DowngradeLock atomically unlocks rw for writing and locks it for reading.
|
||||
// +checklocksignore
|
||||
func (m *deviceRWMutex) DowngradeLock() {
|
||||
m.mu.DowngradeLock()
|
||||
}
|
||||
|
||||
var deviceprefixIndex *locking.MutexClass
|
||||
|
||||
// DO NOT REMOVE: The following function is automatically replaced.
|
||||
func deviceinitLockNames() {}
|
||||
|
||||
func init() {
|
||||
deviceinitLockNames()
|
||||
deviceprefixIndex = locking.NewMutexClass(reflect.TypeOf(deviceRWMutex{}), devicelockNames)
|
||||
}
|
||||
64
pkg/tcpip/link/tun/endpoint_mutex.go
Normal file
64
pkg/tcpip/link/tun/endpoint_mutex.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package tun
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/sync"
|
||||
"github.com/sagernet/gvisor/pkg/sync/locking"
|
||||
)
|
||||
|
||||
// Mutex is sync.Mutex with the correctness validator.
|
||||
type endpointMutex struct {
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var endpointprefixIndex *locking.MutexClass
|
||||
|
||||
// lockNames is a list of user-friendly lock names.
|
||||
// Populated in init.
|
||||
var endpointlockNames []string
|
||||
|
||||
// lockNameIndex is used as an index passed to NestedLock and NestedUnlock,
|
||||
// referring to an index within lockNames.
|
||||
// Values are specified using the "consts" field of go_template_instance.
|
||||
type endpointlockNameIndex int
|
||||
|
||||
// DO NOT REMOVE: The following function automatically replaced with lock index constants.
|
||||
// LOCK_NAME_INDEX_CONSTANTS
|
||||
const ()
|
||||
|
||||
// Lock locks m.
|
||||
// +checklocksignore
|
||||
func (m *endpointMutex) Lock() {
|
||||
locking.AddGLock(endpointprefixIndex, -1)
|
||||
m.mu.Lock()
|
||||
}
|
||||
|
||||
// NestedLock locks m knowing that another lock of the same type is held.
|
||||
// +checklocksignore
|
||||
func (m *endpointMutex) NestedLock(i endpointlockNameIndex) {
|
||||
locking.AddGLock(endpointprefixIndex, int(i))
|
||||
m.mu.Lock()
|
||||
}
|
||||
|
||||
// Unlock unlocks m.
|
||||
// +checklocksignore
|
||||
func (m *endpointMutex) Unlock() {
|
||||
locking.DelGLock(endpointprefixIndex, -1)
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// NestedUnlock unlocks m knowing that another lock of the same type is held.
|
||||
// +checklocksignore
|
||||
func (m *endpointMutex) NestedUnlock(i endpointlockNameIndex) {
|
||||
locking.DelGLock(endpointprefixIndex, int(i))
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// DO NOT REMOVE: The following function is automatically replaced.
|
||||
func endpointinitLockNames() {}
|
||||
|
||||
func init() {
|
||||
endpointinitLockNames()
|
||||
endpointprefixIndex = locking.NewMutexClass(reflect.TypeOf(endpointMutex{}), endpointlockNames)
|
||||
}
|
||||
56
pkg/tcpip/link/tun/protocol.go
Normal file
56
pkg/tcpip/link/tun/protocol.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// 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 tun
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/tcpip"
|
||||
)
|
||||
|
||||
const (
|
||||
// PacketInfoHeaderSize is the size of the packet information header.
|
||||
PacketInfoHeaderSize = 4
|
||||
|
||||
offsetFlags = 0
|
||||
offsetProtocol = 2
|
||||
)
|
||||
|
||||
// PacketInfoFields contains fields sent through the wire if IFF_NO_PI flag is
|
||||
// not set.
|
||||
type PacketInfoFields struct {
|
||||
Flags uint16
|
||||
Protocol tcpip.NetworkProtocolNumber
|
||||
}
|
||||
|
||||
// PacketInfoHeader is the wire representation of the packet information sent if
|
||||
// IFF_NO_PI flag is not set.
|
||||
type PacketInfoHeader []byte
|
||||
|
||||
// Encode encodes f into h.
|
||||
func (h PacketInfoHeader) Encode(f *PacketInfoFields) {
|
||||
binary.BigEndian.PutUint16(h[offsetFlags:][:2], f.Flags)
|
||||
binary.BigEndian.PutUint16(h[offsetProtocol:][:2], uint16(f.Protocol))
|
||||
}
|
||||
|
||||
// Flags returns the flag field in h.
|
||||
func (h PacketInfoHeader) Flags() uint16 {
|
||||
return binary.BigEndian.Uint16(h[offsetFlags:])
|
||||
}
|
||||
|
||||
// Protocol returns the protocol field in h.
|
||||
func (h PacketInfoHeader) Protocol() tcpip.NetworkProtocolNumber {
|
||||
return tcpip.NetworkProtocolNumber(binary.BigEndian.Uint16(h[offsetProtocol:]))
|
||||
}
|
||||
141
pkg/tcpip/link/tun/tun_endpoint_refs.go
Normal file
141
pkg/tcpip/link/tun/tun_endpoint_refs.go
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/atomicbitops"
|
||||
"github.com/sagernet/gvisor/pkg/refs"
|
||||
)
|
||||
|
||||
// enableLogging indicates whether reference-related events should be logged (with
|
||||
// stack traces). This is false by default and should only be set to true for
|
||||
// debugging purposes, as it can generate an extremely large amount of output
|
||||
// and drastically degrade performance.
|
||||
const tunEndpointenableLogging = false
|
||||
|
||||
// obj is used to customize logging. Note that we use a pointer to T so that
|
||||
// we do not copy the entire object when passed as a format parameter.
|
||||
var tunEndpointobj *tunEndpoint
|
||||
|
||||
// Refs implements refs.RefCounter. It keeps a reference count using atomic
|
||||
// operations and calls the destructor when the count reaches zero.
|
||||
//
|
||||
// NOTE: Do not introduce additional fields to the Refs struct. It is used by
|
||||
// many filesystem objects, and we want to keep it as small as possible (i.e.,
|
||||
// the same size as using an int64 directly) to avoid taking up extra cache
|
||||
// space. In general, this template should not be extended at the cost of
|
||||
// performance. If it does not offer enough flexibility for a particular object
|
||||
// (example: b/187877947), we should implement the RefCounter/CheckedObject
|
||||
// interfaces manually.
|
||||
//
|
||||
// +stateify savable
|
||||
type tunEndpointRefs struct {
|
||||
// refCount is composed of two fields:
|
||||
//
|
||||
// [32-bit speculative references]:[32-bit real references]
|
||||
//
|
||||
// Speculative references are used for TryIncRef, to avoid a CompareAndSwap
|
||||
// loop. See IncRef, DecRef and TryIncRef for details of how these fields are
|
||||
// used.
|
||||
refCount atomicbitops.Int64
|
||||
}
|
||||
|
||||
// InitRefs initializes r with one reference and, if enabled, activates leak
|
||||
// checking.
|
||||
func (r *tunEndpointRefs) InitRefs() {
|
||||
r.refCount.RacyStore(1)
|
||||
refs.Register(r)
|
||||
}
|
||||
|
||||
// RefType implements refs.CheckedObject.RefType.
|
||||
func (r *tunEndpointRefs) RefType() string {
|
||||
return fmt.Sprintf("%T", tunEndpointobj)[1:]
|
||||
}
|
||||
|
||||
// LeakMessage implements refs.CheckedObject.LeakMessage.
|
||||
func (r *tunEndpointRefs) LeakMessage() string {
|
||||
return fmt.Sprintf("[%s %p] reference count of %d instead of 0", r.RefType(), r, r.ReadRefs())
|
||||
}
|
||||
|
||||
// LogRefs implements refs.CheckedObject.LogRefs.
|
||||
func (r *tunEndpointRefs) LogRefs() bool {
|
||||
return tunEndpointenableLogging
|
||||
}
|
||||
|
||||
// ReadRefs returns the current number of references. The returned count is
|
||||
// inherently racy and is unsafe to use without external synchronization.
|
||||
func (r *tunEndpointRefs) ReadRefs() int64 {
|
||||
return r.refCount.Load()
|
||||
}
|
||||
|
||||
// IncRef implements refs.RefCounter.IncRef.
|
||||
//
|
||||
//go:nosplit
|
||||
func (r *tunEndpointRefs) IncRef() {
|
||||
v := r.refCount.Add(1)
|
||||
if tunEndpointenableLogging {
|
||||
refs.LogIncRef(r, v)
|
||||
}
|
||||
if v <= 1 {
|
||||
panic(fmt.Sprintf("Incrementing non-positive count %p on %s", r, r.RefType()))
|
||||
}
|
||||
}
|
||||
|
||||
// TryIncRef implements refs.TryRefCounter.TryIncRef.
|
||||
//
|
||||
// To do this safely without a loop, a speculative reference is first acquired
|
||||
// on the object. This allows multiple concurrent TryIncRef calls to distinguish
|
||||
// other TryIncRef calls from genuine references held.
|
||||
//
|
||||
//go:nosplit
|
||||
func (r *tunEndpointRefs) TryIncRef() bool {
|
||||
const speculativeRef = 1 << 32
|
||||
if v := r.refCount.Add(speculativeRef); int32(v) == 0 {
|
||||
|
||||
r.refCount.Add(-speculativeRef)
|
||||
return false
|
||||
}
|
||||
|
||||
v := r.refCount.Add(-speculativeRef + 1)
|
||||
if tunEndpointenableLogging {
|
||||
refs.LogTryIncRef(r, v)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// DecRef implements refs.RefCounter.DecRef.
|
||||
//
|
||||
// Note that speculative references are counted here. Since they were added
|
||||
// prior to real references reaching zero, they will successfully convert to
|
||||
// real references. In other words, we see speculative references only in the
|
||||
// following case:
|
||||
//
|
||||
// A: TryIncRef [speculative increase => sees non-negative references]
|
||||
// B: DecRef [real decrease]
|
||||
// A: TryIncRef [transform speculative to real]
|
||||
//
|
||||
//go:nosplit
|
||||
func (r *tunEndpointRefs) DecRef(destroy func()) {
|
||||
v := r.refCount.Add(-1)
|
||||
if tunEndpointenableLogging {
|
||||
refs.LogDecRef(r, v)
|
||||
}
|
||||
switch {
|
||||
case v < 0:
|
||||
panic(fmt.Sprintf("Decrementing non-positive ref count %p, owned by %s", r, r.RefType()))
|
||||
|
||||
case v == 0:
|
||||
refs.Unregister(r)
|
||||
|
||||
if destroy != nil {
|
||||
destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *tunEndpointRefs) afterLoad(context.Context) {
|
||||
if r.ReadRefs() > 0 {
|
||||
refs.Register(r)
|
||||
}
|
||||
}
|
||||
152
pkg/tcpip/link/tun/tun_state_autogen.go
Normal file
152
pkg/tcpip/link/tun/tun_state_autogen.go
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// automatically generated by stateify.
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/sagernet/gvisor/pkg/state"
|
||||
)
|
||||
|
||||
func (d *Device) StateTypeName() string {
|
||||
return "pkg/tcpip/link/tun.Device"
|
||||
}
|
||||
|
||||
func (d *Device) StateFields() []string {
|
||||
return []string{
|
||||
"Queue",
|
||||
"endpoint",
|
||||
"notifyHandle",
|
||||
"flags",
|
||||
}
|
||||
}
|
||||
|
||||
// +checklocksignore
|
||||
func (d *Device) StateSave(stateSinkObject state.Sink) {
|
||||
d.beforeSave()
|
||||
stateSinkObject.Save(0, &d.Queue)
|
||||
stateSinkObject.Save(1, &d.endpoint)
|
||||
stateSinkObject.Save(2, &d.notifyHandle)
|
||||
stateSinkObject.Save(3, &d.flags)
|
||||
}
|
||||
|
||||
func (d *Device) afterLoad(context.Context) {}
|
||||
|
||||
// +checklocksignore
|
||||
func (d *Device) StateLoad(ctx context.Context, stateSourceObject state.Source) {
|
||||
stateSourceObject.Load(0, &d.Queue)
|
||||
stateSourceObject.Load(1, &d.endpoint)
|
||||
stateSourceObject.Load(2, &d.notifyHandle)
|
||||
stateSourceObject.Load(3, &d.flags)
|
||||
}
|
||||
|
||||
func (f *Flags) StateTypeName() string {
|
||||
return "pkg/tcpip/link/tun.Flags"
|
||||
}
|
||||
|
||||
func (f *Flags) StateFields() []string {
|
||||
return []string{
|
||||
"TUN",
|
||||
"TAP",
|
||||
"NoPacketInfo",
|
||||
"Exclusive",
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Flags) beforeSave() {}
|
||||
|
||||
// +checklocksignore
|
||||
func (f *Flags) StateSave(stateSinkObject state.Sink) {
|
||||
f.beforeSave()
|
||||
stateSinkObject.Save(0, &f.TUN)
|
||||
stateSinkObject.Save(1, &f.TAP)
|
||||
stateSinkObject.Save(2, &f.NoPacketInfo)
|
||||
stateSinkObject.Save(3, &f.Exclusive)
|
||||
}
|
||||
|
||||
func (f *Flags) afterLoad(context.Context) {}
|
||||
|
||||
// +checklocksignore
|
||||
func (f *Flags) StateLoad(ctx context.Context, stateSourceObject state.Source) {
|
||||
stateSourceObject.Load(0, &f.TUN)
|
||||
stateSourceObject.Load(1, &f.TAP)
|
||||
stateSourceObject.Load(2, &f.NoPacketInfo)
|
||||
stateSourceObject.Load(3, &f.Exclusive)
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) StateTypeName() string {
|
||||
return "pkg/tcpip/link/tun.tunEndpoint"
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) StateFields() []string {
|
||||
return []string{
|
||||
"tunEndpointRefs",
|
||||
"Endpoint",
|
||||
"stack",
|
||||
"nicID",
|
||||
"name",
|
||||
"isTap",
|
||||
"persistent",
|
||||
"closed",
|
||||
}
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) beforeSave() {}
|
||||
|
||||
// +checklocksignore
|
||||
func (e *tunEndpoint) StateSave(stateSinkObject state.Sink) {
|
||||
e.beforeSave()
|
||||
stateSinkObject.Save(0, &e.tunEndpointRefs)
|
||||
stateSinkObject.Save(1, &e.Endpoint)
|
||||
stateSinkObject.Save(2, &e.stack)
|
||||
stateSinkObject.Save(3, &e.nicID)
|
||||
stateSinkObject.Save(4, &e.name)
|
||||
stateSinkObject.Save(5, &e.isTap)
|
||||
stateSinkObject.Save(6, &e.persistent)
|
||||
stateSinkObject.Save(7, &e.closed)
|
||||
}
|
||||
|
||||
func (e *tunEndpoint) afterLoad(context.Context) {}
|
||||
|
||||
// +checklocksignore
|
||||
func (e *tunEndpoint) StateLoad(ctx context.Context, stateSourceObject state.Source) {
|
||||
stateSourceObject.Load(0, &e.tunEndpointRefs)
|
||||
stateSourceObject.Load(1, &e.Endpoint)
|
||||
stateSourceObject.Load(2, &e.stack)
|
||||
stateSourceObject.Load(3, &e.nicID)
|
||||
stateSourceObject.Load(4, &e.name)
|
||||
stateSourceObject.Load(5, &e.isTap)
|
||||
stateSourceObject.Load(6, &e.persistent)
|
||||
stateSourceObject.Load(7, &e.closed)
|
||||
}
|
||||
|
||||
func (r *tunEndpointRefs) StateTypeName() string {
|
||||
return "pkg/tcpip/link/tun.tunEndpointRefs"
|
||||
}
|
||||
|
||||
func (r *tunEndpointRefs) StateFields() []string {
|
||||
return []string{
|
||||
"refCount",
|
||||
}
|
||||
}
|
||||
|
||||
func (r *tunEndpointRefs) beforeSave() {}
|
||||
|
||||
// +checklocksignore
|
||||
func (r *tunEndpointRefs) StateSave(stateSinkObject state.Sink) {
|
||||
r.beforeSave()
|
||||
stateSinkObject.Save(0, &r.refCount)
|
||||
}
|
||||
|
||||
// +checklocksignore
|
||||
func (r *tunEndpointRefs) StateLoad(ctx context.Context, stateSourceObject state.Source) {
|
||||
stateSourceObject.Load(0, &r.refCount)
|
||||
stateSourceObject.AfterLoad(func() { r.afterLoad(ctx) })
|
||||
}
|
||||
|
||||
func init() {
|
||||
state.Register((*Device)(nil))
|
||||
state.Register((*Flags)(nil))
|
||||
state.Register((*tunEndpoint)(nil))
|
||||
state.Register((*tunEndpointRefs)(nil))
|
||||
}
|
||||
65
pkg/tcpip/link/tun/tun_unsafe.go
Normal file
65
pkg/tcpip/link/tun/tun_unsafe.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// 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.
|
||||
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
// Package tun contains methods to open TAP and TUN devices.
|
||||
package tun
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// Open opens the specified TUN device, sets it to non-blocking mode, and
|
||||
// returns its file descriptor.
|
||||
func Open(name string) (int, error) {
|
||||
return open(name, unix.IFF_TUN|unix.IFF_NO_PI)
|
||||
}
|
||||
|
||||
// OpenTAP opens the specified TAP device, sets it to non-blocking mode, and
|
||||
// returns its file descriptor.
|
||||
func OpenTAP(name string) (int, error) {
|
||||
return open(name, unix.IFF_TAP|unix.IFF_NO_PI)
|
||||
}
|
||||
|
||||
func open(name string, flags uint16) (int, error) {
|
||||
fd, err := unix.Open("/dev/net/tun", unix.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
var ifr struct {
|
||||
name [16]byte
|
||||
flags uint16
|
||||
_ [22]byte
|
||||
}
|
||||
|
||||
copy(ifr.name[:], name)
|
||||
ifr.flags = flags
|
||||
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), unix.TUNSETIFF, uintptr(unsafe.Pointer(&ifr)))
|
||||
if errno != 0 {
|
||||
unix.Close(fd)
|
||||
return -1, errno
|
||||
}
|
||||
|
||||
if err = unix.SetNonblock(fd, true); err != nil {
|
||||
unix.Close(fd)
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return fd, nil
|
||||
}
|
||||
6
pkg/tcpip/link/tun/tun_unsafe_state_autogen.go
Normal file
6
pkg/tcpip/link/tun/tun_unsafe_state_autogen.go
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
// automatically generated by stateify.
|
||||
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package tun
|
||||
Loading…
Add table
Add a link
Reference in a new issue