tun

package module
v0.0.0-...-72376f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: GPL-2.0 Imports: 60 Imported by: 0

README

sing-tun

Simple transparent proxy library.

For Linux, Windows, macOS and iOS.

License

Copyright (C) 2022 by nekohasekai <contact-sagernet@sekai.icu>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Documentation

Index

Constants

View Source
const (
	DefaultAutoRedirectInputMark  = 0x2023
	DefaultAutoRedirectOutputMark = 0x2024
	DefaultAutoRedirectResetMark  = 0x2025
	DefaultAutoRedirectTProxyMark = 0x2026
	DefaultAutoRedirectNFQueue    = 100

	DefaultAutoRedirectInputMarkAndroid  = 0x400000
	DefaultAutoRedirectOutputMarkAndroid = 0x200000
	DefaultAutoRedirectResetMarkAndroid  = 0x600000
	DefaultAutoRedirectTProxyMarkAndroid = 0x800000
)
View Source
const (
	DefaultIPRoute2TableIndex                    = 2022
	DefaultIPRoute2RuleIndex                     = 9000
	DefaultIPRoute2AutoRedirectFallbackRuleIndex = 32768
)
View Source
const (
	DNSModeDisabled = "disabled"
	DNSModeNative   = "native"
	DNSModeHijack   = "hijack"
)
View Source
const FlagAndroidVPNUpdate = 1 << iota
View Source
const PacketOffset = 0
View Source
const WithGVisor = false

Variables

View Source
var ErrGVisorNotIncluded = E.New(`gVisor is not included in this build, rebuild with -tags with_gvisor`)
View Source
var ErrIncludeAllNetworks = E.New("`system` and `mixed` stack are not available when `includeAllNetworks` is enabled. See https://github.com/SagerNet/sing-tun/issues/25")
View Source
var ErrNetlinkBanned = E.New(
	"netlink socket in Android is banned by Google, " +
		"use the root or system (ADB) user to run sing-box, " +
		"or switch to the sing-box Android graphical interface client",
)
View Source
var ErrNoRoute = E.New("no route to internet")
View Source
var ErrTooManySegments = errors.New("too many segments")

ErrTooManySegments is returned by Device.Read() when segmentation overflows the length of supplied buffers. This error should not cause reads to cease.

Functions

func BroadcastAddr

func BroadcastAddr(inet4Address []netip.Prefix) netip.Addr

func BuildICMPError

func BuildICMPError(packet []byte, errorType ICMPError, source netip.Addr, mtu uint32, headroom int) ([]byte, bool)

func CalculateInterfaceName

func CalculateInterfaceName(name string) (tunName string)

func GSOSplit

func GSOSplit(in []byte, options GSOOptions, outBufs [][]byte, sizes []int, outOffset int) (int, error)

GSOSplit splits packets from 'in' into outBufs[<index>][outOffset:], writing the size of each element into sizes. It returns the number of buffers populated, and/or an error. Callers may pass an 'in' slice that overlaps with the first element of outBuffers, i.e. &in[0] may be equal to &outBufs[0][outOffset]. GSONone is a valid options.GSOType regardless of the value of options.NeedsCsum. Length of each outBufs element must be greater than or equal to the length of 'in', otherwise output may be silently truncated.

func HasNextAddress

func HasNextAddress(prefix netip.Prefix, count int) bool

func IPTransportProtocol

func IPTransportProtocol(packet []byte) (uint8, bool)

func IsRecoverableReadError

func IsRecoverableReadError(err error) bool

func PacketDestination

func PacketDestination(packet []byte) netip.Addr

func PacketFillHeader

func PacketFillHeader(packet []byte, ipVersion int)

func PacketIPVersion

func PacketIPVersion(packet []byte) int

Types

type AutoRedirect

type AutoRedirect interface {
	Start() error
	Close() error
	UpdateRouteAddressSet() error
}

func NewAutoRedirect

func NewAutoRedirect(options AutoRedirectOptions) (AutoRedirect, error)

type AutoRedirectHandler

type AutoRedirectHandler interface {
	JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) FlowVerdict
	N.TCPConnectionHandlerEx
}

type AutoRedirectOptions

type AutoRedirectOptions struct {
	TunOptions               *Options
	Context                  context.Context
	Handler                  AutoRedirectHandler
	Logger                   logger.Logger
	NetworkMonitor           NetworkUpdateMonitor
	InterfaceFinder          control.InterfaceFinder
	TableName                string
	DisableNFTables          bool
	CustomRedirectPort       func() int
	CustomRedirectListenerFD func() (int, error)
	RouteAddressSet          func() (include []netip.Prefix, exclude []netip.Prefix, err error)
	AndroidVPNService        bool
}

type DarwinTUN

type DarwinTUN interface {
	Tun
	BatchRead(frontHeadroom int, rearHeadroom int) ([]*buf.Buffer, error)
	BatchWrite(buffers []*buf.Buffer) error
}

type DefaultInterfaceMonitor

type DefaultInterfaceMonitor interface {
	Start() error
	Close() error
	DefaultInterface() *control.Interface
	OverrideAndroidVPN() bool
	AndroidVPNEnabled() bool
	RegisterCallback(callback DefaultInterfaceUpdateCallback) *list.Element[DefaultInterfaceUpdateCallback]
	UnregisterCallback(element *list.Element[DefaultInterfaceUpdateCallback])
	RegisterMyInterface(interfaceName string)
	MyInterfaces() []string
}

func NewDefaultInterfaceMonitor

func NewDefaultInterfaceMonitor(networkMonitor NetworkUpdateMonitor, logger logger.Logger, options DefaultInterfaceMonitorOptions) (DefaultInterfaceMonitor, error)

type DefaultInterfaceMonitorOptions

type DefaultInterfaceMonitorOptions struct {
	InterfaceFinder       control.InterfaceFinder
	OverrideAndroidVPN    bool
	UnderNetworkExtension bool
}

type DefaultInterfaceUpdateCallback

type DefaultInterfaceUpdateCallback = func(defaultInterface *control.Interface, flags int)

type FlowAction

type FlowAction uint8
const (
	ActionAccept FlowAction = iota
	ActionFlow
	ActionReject
	ActionDrop
	ActionBypass
	ActionHijackDNS
)

type FlowCloseReason

type FlowCloseReason uint8
const (
	FlowCloseReset FlowCloseReason = iota
	FlowCloseFinished
	FlowCloseTimeout
)

func (FlowCloseReason) String

func (r FlowCloseReason) String() string

type FlowHandle

type FlowHandle interface {
	CloseFlow()
}

type FlowTracker

type FlowTracker interface {
	AttachFlow(handle FlowHandle)
	CountForward(n int)
	CountReverse(n int)
	FlowEstablished()
	CloseFlow(reason FlowCloseReason)
}

type FlowVerdict

type FlowVerdict struct {
	Action      FlowAction
	Port        Port
	Destination netip.AddrPort
	UDPTimeout  time.Duration
	NewTracker  func() FlowTracker
}

type ForwardDispatcher

type ForwardDispatcher struct {
	// contains filtered or unexported fields
}

func NewForwardDispatcher

func NewForwardDispatcher(handler Handler, writeback ForwardWriteback, logger logger.Logger, udpTimeout time.Duration, icmpTimeout time.Duration) *ForwardDispatcher

func (*ForwardDispatcher) Close

func (d *ForwardDispatcher) Close()

func (*ForwardDispatcher) NewStage

func (d *ForwardDispatcher) NewStage(writeback ForwardWriteback) *ForwardStage

func (*ForwardDispatcher) ResetNetwork

func (d *ForwardDispatcher) ResetNetwork()

type ForwardFrameMeta

type ForwardFrameMeta struct {
	// contains filtered or unexported fields
}

type ForwardStage

type ForwardStage struct {
	// contains filtered or unexported fields
}

func (*ForwardStage) Dispatch

func (s *ForwardStage) Dispatch(packet []byte) bool

func (*ForwardStage) DispatchParsed

func (s *ForwardStage) DispatchParsed(packet []byte, meta ForwardFrameMeta, parsed *forwardPacket) bool

func (*ForwardStage) Flush

func (s *ForwardStage) Flush()

type ForwardWriteback

type ForwardWriteback interface {
	ReturnHeadroom() int
	WriteReturnPackets(packets [][]byte) error
}

type GSOOptions

type GSOOptions struct {
	// GSOType represents the type of segmentation offload.
	GSOType GSOType
	// HdrLen is the sum of the layer 3 and 4 header lengths. This field may be
	// zero when GSOType == GSONone.
	HdrLen uint16
	// CsumStart is the head byte index of the packet data to be checksummed,
	// i.e. the start of the TCP or UDP header.
	CsumStart uint16
	// CsumOffset is the offset from CsumStart where the 2-byte checksum value
	// should be placed.
	CsumOffset uint16
	// GSOSize is the size of each segment exclusive of HdrLen. The tail segment
	// may be smaller than this value.
	GSOSize uint16
	// NeedsCsum may be set where GSOType == GSONone. When set, the checksum
	// at CsumStart + CsumOffset must be a partial checksum, i.e. the
	// pseudo-header sum.
	NeedsCsum bool
}

GSOOptions is loosely modeled after struct virtio_net_hdr from the VIRTIO specification. It is a common representation of GSO metadata that can be applied to support packet GSO across tun.Device implementations.

type GSOType

type GSOType int

GSOType represents the type of segmentation offload.

const (
	GSONone GSOType = iota
	GSOTCPv4
	GSOTCPv6
	GSOUDPL4
)

func (GSOType) String

func (g GSOType) String() string

type Go

type Go struct {
	// contains filtered or unexported fields
}

func NewGo

func NewGo(options StackOptions) (*Go, error)

func (*Go) Close

func (s *Go) Close() error

func (*Go) DialTCP

func (s *Go) DialTCP(ctx context.Context, source netip.Addr, destination netip.AddrPort) (*GoConn, error)

func (*Go) DialUDP

func (s *Go) DialUDP(local netip.AddrPort, destination netip.AddrPort) (*GoUDPConn, error)

func (*Go) HasEndpoint

func (s *Go) HasEndpoint(protocol uint8, local, remote netip.AddrPort) bool

func (*Go) ListenTCP

func (s *Go) ListenTCP(local netip.AddrPort) (*GoListener, error)

func (*Go) ListenUDP

func (s *Go) ListenUDP(local netip.AddrPort) (*GoUDPConn, error)

func (*Go) ResetNetwork

func (s *Go) ResetNetwork()

func (*Go) Start

func (s *Go) Start() error

type GoConn

type GoConn struct {
	// contains filtered or unexported fields
}

func (*GoConn) Close

func (c *GoConn) Close() error

func (*GoConn) CloseRead

func (c *GoConn) CloseRead() error

func (*GoConn) CloseWrite

func (c *GoConn) CloseWrite() error

func (*GoConn) FrontHeadroom

func (c *GoConn) FrontHeadroom() int

func (*GoConn) HandshakeFailure

func (c *GoConn) HandshakeFailure(err error) error

func (*GoConn) HandshakeSuccess

func (c *GoConn) HandshakeSuccess() error

func (*GoConn) InitializeReadWaiter

func (c *GoConn) InitializeReadWaiter(options N.ReadWaitOptions) bool

func (*GoConn) LocalAddr

func (c *GoConn) LocalAddr() net.Addr

func (*GoConn) NeedHandshakeForRead

func (c *GoConn) NeedHandshakeForRead() bool

func (*GoConn) NeedHandshakeForWrite

func (c *GoConn) NeedHandshakeForWrite() bool

func (*GoConn) Read

func (c *GoConn) Read(p []byte) (int, error)

func (*GoConn) RemoteAddr

func (c *GoConn) RemoteAddr() net.Addr

func (*GoConn) SetDeadline

func (c *GoConn) SetDeadline(t time.Time) error

func (*GoConn) SetKeepAlive

func (c *GoConn) SetKeepAlive(keepalive bool) error

func (*GoConn) SetKeepAliveConfig

func (c *GoConn) SetKeepAliveConfig(config net.KeepAliveConfig) error

func (*GoConn) SetKeepAlivePeriod

func (c *GoConn) SetKeepAlivePeriod(d time.Duration) error

func (*GoConn) SetLinger

func (c *GoConn) SetLinger(sec int) error

func (*GoConn) SetNoDelay

func (c *GoConn) SetNoDelay(noDelay bool) error

func (*GoConn) SetReadBuffer

func (c *GoConn) SetReadBuffer(size int) error

func (*GoConn) SetReadDeadline

func (c *GoConn) SetReadDeadline(t time.Time) error

func (*GoConn) SetWriteBuffer

func (c *GoConn) SetWriteBuffer(size int) error

func (*GoConn) SetWriteDeadline

func (c *GoConn) SetWriteDeadline(t time.Time) error

func (*GoConn) Splice

func (c *GoConn) Splice(owner SpliceSocket, options SpliceOptions) bool

func (*GoConn) WaitReadBuffer

func (c *GoConn) WaitReadBuffer() (*buf.Buffer, error)

func (*GoConn) Write

func (c *GoConn) Write(p []byte) (int, error)

func (*GoConn) WriteBuffer

func (c *GoConn) WriteBuffer(buffer *buf.Buffer) error

func (*GoConn) WriterMTU

func (c *GoConn) WriterMTU() int

type GoListener

type GoListener struct {
	// contains filtered or unexported fields
}

func (*GoListener) Accept

func (l *GoListener) Accept() (net.Conn, error)

func (*GoListener) AcceptTCP

func (l *GoListener) AcceptTCP() (*GoConn, error)

func (*GoListener) Addr

func (l *GoListener) Addr() net.Addr

func (*GoListener) Close

func (l *GoListener) Close() error

func (*GoListener) SetDeadline

func (l *GoListener) SetDeadline(t time.Time) error

type GoPacketConn

type GoPacketConn struct {
	// contains filtered or unexported fields
}

func (*GoPacketConn) Close

func (w *GoPacketConn) Close() error

func (*GoPacketConn) CloseFlow

func (w *GoPacketConn) CloseFlow()

func (*GoPacketConn) CreatePacketBatchWriter

func (w *GoPacketConn) CreatePacketBatchWriter() (N.PacketBatchWriter, bool)

func (*GoPacketConn) FrontHeadroom

func (w *GoPacketConn) FrontHeadroom() int

func (*GoPacketConn) HandshakeFailure

func (w *GoPacketConn) HandshakeFailure(err error) error

func (*GoPacketConn) HandshakeSuccess

func (w *GoPacketConn) HandshakeSuccess() error

func (*GoPacketConn) WritePacket

func (w *GoPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error

func (*GoPacketConn) WritePacketBatch

func (w *GoPacketConn) WritePacketBatch(buffers []*buf.Buffer, destinations []M.Socksaddr) error

type GoUDPConn

type GoUDPConn struct {
	// contains filtered or unexported fields
}

func (*GoUDPConn) Close

func (c *GoUDPConn) Close() error

func (*GoUDPConn) InitializeReadWaiter

func (c *GoUDPConn) InitializeReadWaiter(options N.ReadWaitOptions) bool

func (*GoUDPConn) LocalAddr

func (c *GoUDPConn) LocalAddr() net.Addr

func (*GoUDPConn) Read

func (c *GoUDPConn) Read(p []byte) (int, error)

func (*GoUDPConn) ReadFrom

func (c *GoUDPConn) ReadFrom(p []byte) (int, net.Addr, error)

func (*GoUDPConn) ReadFromUDPAddrPort

func (c *GoUDPConn) ReadFromUDPAddrPort(p []byte) (int, netip.AddrPort, error)

func (*GoUDPConn) ReadPacket

func (c *GoUDPConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error)

func (*GoUDPConn) RemoteAddr

func (c *GoUDPConn) RemoteAddr() net.Addr

func (*GoUDPConn) SetDeadline

func (c *GoUDPConn) SetDeadline(t time.Time) error

func (*GoUDPConn) SetReadBuffer

func (c *GoUDPConn) SetReadBuffer(size int) error

func (*GoUDPConn) SetReadDeadline

func (c *GoUDPConn) SetReadDeadline(t time.Time) error

func (*GoUDPConn) SetWriteBuffer

func (c *GoUDPConn) SetWriteBuffer(size int) error

func (*GoUDPConn) SetWriteDeadline

func (c *GoUDPConn) SetWriteDeadline(t time.Time) error

func (*GoUDPConn) WaitReadPacket

func (c *GoUDPConn) WaitReadPacket() (*buf.Buffer, M.Socksaddr, error)

func (*GoUDPConn) Write

func (c *GoUDPConn) Write(p []byte) (int, error)

func (*GoUDPConn) WritePacket

func (c *GoUDPConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error

func (*GoUDPConn) WriteTo

func (c *GoUDPConn) WriteTo(p []byte, addr net.Addr) (int, error)

func (*GoUDPConn) WriteToUDPAddrPort

func (c *GoUDPConn) WriteToUDPAddrPort(p []byte, addr netip.AddrPort) (int, error)

type Handler

type Handler interface {
	JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) FlowVerdict
	NewDNSPacket(payload []byte, source M.Socksaddr, destination M.Socksaddr, writer N.PacketWriter)
	N.TCPConnectionHandlerEx
	N.UDPConnectionHandlerEx
}

type ICMPError

type ICMPError uint8
const (
	ICMPErrorNoRoute ICMPError = iota
	ICMPErrorAddressUnreachable
	ICMPErrorPortUnreachable
	ICMPErrorSourcePolicy
	ICMPErrorHopLimitExceeded
	ICMPErrorPacketTooBig
)

type LinuxTUN

type LinuxTUN interface {
	Tun
	N.FrontHeadroom
	BatchSize() int
	BatchRead(buffers [][]byte, offset int, readN []int) (n int, err error)
	BatchWrite(buffers [][]byte, offset int) (n int, err error)
	TXChecksumOffload() bool
}

type MemoryPressure

type MemoryPressure uint8
const (
	MemoryPressureNone MemoryPressure = iota
	MemoryPressureWarning
	MemoryPressureCritical
)

type MemoryTun

type MemoryTun struct {
	// contains filtered or unexported fields
}

func NewMemoryTun

func NewMemoryTun(options MemoryTunOptions) *MemoryTun

func (*MemoryTun) Close

func (t *MemoryTun) Close() error

func (*MemoryTun) MTU

func (t *MemoryTun) MTU() int

func (*MemoryTun) Name

func (t *MemoryTun) Name() (string, error)

func (*MemoryTun) NewOutboundQueue

func (t *MemoryTun) NewOutboundQueue(handler func(packets []*buf.Buffer)) *OutboundQueue

func (*MemoryTun) Read

func (t *MemoryTun) Read(p []byte) (int, error)

func (*MemoryTun) Start

func (t *MemoryTun) Start() error

func (*MemoryTun) UpdateMTU

func (t *MemoryTun) UpdateMTU(mtu int)

func (*MemoryTun) UpdateRouteOptions

func (t *MemoryTun) UpdateRouteOptions(tunOptions Options) error

func (*MemoryTun) Write

func (t *MemoryTun) Write(p []byte) (int, error)

func (*MemoryTun) WritePackets

func (t *MemoryTun) WritePackets(packets [][]byte) (int, error)

type MemoryTunOptions

type MemoryTunOptions struct {
	MTU       int
	Headroom  int
	RearSpace int
	BatchSize int
	Outbound  func(packets []*buf.Buffer)
	Route     func(packet []byte) *OutboundQueue
}

type NATFiltering

type NATFiltering uint8
const (
	NATFilteringEndpointIndependent NATFiltering = iota
	NATFilteringAddressDependent
	NATFilteringAddressAndPortDependent
)

type NATMapping

type NATMapping uint8
const (
	NATMappingEndpointIndependent NATMapping = iota
	NATMappingAddressDependent
	NATMappingAddressAndPortDependent
)

type NativeTun

type NativeTun struct {
	// contains filtered or unexported fields
}

func (*NativeTun) BatchRead

func (t *NativeTun) BatchRead(buffers [][]byte, offset int, readN []int) (int, error)

func (*NativeTun) BatchSize

func (t *NativeTun) BatchSize() int

func (*NativeTun) BatchWrite

func (t *NativeTun) BatchWrite(buffers [][]byte, offset int) (int, error)

func (*NativeTun) Close

func (t *NativeTun) Close() error

func (*NativeTun) FrontHeadroom

func (t *NativeTun) FrontHeadroom() int

func (*NativeTun) Name

func (t *NativeTun) Name() (string, error)

func (*NativeTun) Read

func (t *NativeTun) Read(p []byte) (n int, err error)

func (*NativeTun) Start

func (t *NativeTun) Start() error

func (*NativeTun) TXChecksumOffload

func (t *NativeTun) TXChecksumOffload() bool

func (*NativeTun) UpdateRouteOptions

func (t *NativeTun) UpdateRouteOptions(tunOptions Options) error

func (*NativeTun) Write

func (t *NativeTun) Write(p []byte) (n int, err error)

type NetworkUpdateCallback

type NetworkUpdateCallback = func()

type NetworkUpdateMonitor

type NetworkUpdateMonitor interface {
	Start() error
	Close() error
	RegisterCallback(callback NetworkUpdateCallback) *list.Element[NetworkUpdateCallback]
	UnregisterCallback(element *list.Element[NetworkUpdateCallback])
}

func NewNetworkUpdateMonitor

func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error)

type Options

type Options struct {
	Name                                  string
	NetNs                                 string
	Inet4Address                          []netip.Prefix
	Inet6Address                          []netip.Prefix
	MTU                                   uint32
	GSO                                   bool
	MultiQueue                            bool
	AutoRoute                             bool
	InterfaceScope                        bool
	Inet4Gateway                          netip.Addr
	Inet6Gateway                          netip.Addr
	DNSMode                               string
	DNSAddress                            []netip.Addr
	IPRoute2TableIndex                    int
	IPRoute2RuleIndex                     int
	IPRoute2AutoRedirectFallbackRuleIndex int
	AutoRedirectMarkMode                  bool
	AutoRedirectInputMark                 uint32
	AutoRedirectOutputMark                uint32
	AutoRedirectResetMark                 uint32
	AutoRedirectTProxyMark                uint32
	AutoRedirectNFQueue                   uint16
	ExcludeMPTCP                          bool
	Inet4LoopbackAddress                  []netip.Addr
	Inet6LoopbackAddress                  []netip.Addr
	StrictRoute                           bool
	Inet4RouteAddress                     []netip.Prefix
	Inet6RouteAddress                     []netip.Prefix
	Inet4RouteExcludeAddress              []netip.Prefix
	Inet6RouteExcludeAddress              []netip.Prefix
	IncludeInterface                      []string
	ExcludeInterface                      []string
	BridgeInterface                       []string
	IncludeUID                            []ranges.Range[uint32]
	ExcludeUID                            []ranges.Range[uint32]
	IncludeAndroidUser                    []int
	IncludePackage                        []string
	ExcludePackage                        []string
	IncludeMACAddress                     []net.HardwareAddr
	ExcludeMACAddress                     []net.HardwareAddr
	InterfaceFinder                       control.InterfaceFinder
	InterfaceMonitor                      DefaultInterfaceMonitor
	FileDescriptor                        int
	Logger                                logger.Logger

	// For library usages.
	EXP_DisableDNSHijack      bool
	EXP_ExternalConfiguration bool

	// Safe at every MTU: the darwin pending packet limit is derived from the utun control socket
	// receive buffer.
	EXP_MultiPendingPackets bool

	// Do not enable. In netif mode (every utun handed out by Network Extension) utun_pkt_input
	// returns ENOSPC without freeing the mbuf once 512 packets are queued
	// (net.utun.max_pending_input), leaking one mbuf per rejected write until reboot; sendmsg_x
	// pushes the write rate past the netif drain rate (about 500k to 700k packets per second on an
	// M4 Pro) and reproduces the device-wide network loss, writev stays below it by its own cost.
	EXP_SendMsgX bool
	// contains filtered or unexported fields
}

func (*Options) BuildAndroidRules

func (o *Options) BuildAndroidRules(packageManager PackageManager)

func (*Options) BuildAutoRouteRanges

func (o *Options) BuildAutoRouteRanges(underNetworkExtension bool) ([]netip.Prefix, error)

func (*Options) DNSModeOrDefault

func (o *Options) DNSModeOrDefault() string

func (*Options) DNSServerAddress

func (o *Options) DNSServerAddress() ([]netip.Addr, error)

func (*Options) ExcludedRanges

func (o *Options) ExcludedRanges() (uidRanges []ranges.Range[uint32])

func (*Options) Inet4DNSAddress

func (o *Options) Inet4DNSAddress() ([]netip.Addr, error)

func (*Options) Inet4GatewayAddr

func (o *Options) Inet4GatewayAddr() netip.Addr

func (*Options) Inet6DNSAddress

func (o *Options) Inet6DNSAddress() ([]netip.Addr, error)

func (*Options) Inet6GatewayAddr

func (o *Options) Inet6GatewayAddr() netip.Addr

type OutboundQueue

type OutboundQueue struct {
	// contains filtered or unexported fields
}

func (*OutboundQueue) Close

func (q *OutboundQueue) Close() error

func (*OutboundQueue) WriteBuffers

func (q *OutboundQueue) WriteBuffers(buffers []*buf.Buffer)

type PackageManager

type PackageManager interface {
	Start() error
	Close() error
	IDByPackage(packageName string) (uint32, bool)
	IDBySharedPackage(sharedPackage string) (uint32, bool)
	PackageByID(id uint32) (string, bool)
	PackagesByID(id uint32) ([]string, bool)
	SharedPackageByID(id uint32) (string, bool)
}

func NewPackageManager

func NewPackageManager(options PackageManagerOptions) (PackageManager, error)

type PackageManagerCallback

type PackageManagerCallback interface {
	OnPackagesUpdated(packages int, sharedUsers int)
}

type PackageManagerOptions

type PackageManagerOptions struct {
	Callback PackageManagerCallback

	// Logger is the logger to log errors
	// optional
	Logger logger.Logger
}

type PacketNAT

type PacketNAT struct {
	Origin         M.Socksaddr
	Destination    M.Socksaddr
	FakeIP         bool
	Unidirectional bool
}

type Port

type Port interface {
	PortAddresses() (v4 netip.Addr, v6 netip.Addr)
	PortMTU() uint32
	AttachReturn(returnPath Return) error
	DetachReturn(returnPath Return) error
	WritePackets(packets [][]byte) error
}

type PortWithSelectorRange

type PortWithSelectorRange interface {
	Port
	PortSelectorRange() (start uint16, count uint16)
}

type ReadRetry

type ReadRetry struct {
	// contains filtered or unexported fields
}

func (*ReadRetry) Reset

func (r *ReadRetry) Reset()

func (*ReadRetry) Wait

func (r *ReadRetry) Wait(err error)

type RedirectServer

type RedirectServer struct {
	// contains filtered or unexported fields
}

func NewRedirectServer

func NewRedirectServer(ctx context.Context, handler N.TCPConnectionHandlerEx, logger logger.Logger, listenAddress netip.Addr) *RedirectServer

func (*RedirectServer) Close

func (s *RedirectServer) Close() error

func (*RedirectServer) ListenerFileDescriptor

func (s *RedirectServer) ListenerFileDescriptor() (int, error)

func (*RedirectServer) Port

func (s *RedirectServer) Port() uint16

func (*RedirectServer) SetExternalTransparent

func (s *RedirectServer) SetExternalTransparent()

func (*RedirectServer) Start

func (s *RedirectServer) Start() error

type Return

type Return interface {
	ReturnHeadroom() int
	ReturnPackets(packets [][]byte) [][]byte
}

type Session

type Session struct {
	SourceAddress      netip.Addr
	DestinationAddress netip.Addr
	SourcePort         uint16
	DestinationPort    uint16
}

type SpliceOptions

type SpliceOptions struct {
	ReadCounters  []N.CountFunc
	WriteCounters []N.CountFunc
	OnClose       N.CloseHandlerFunc
}

type SplicePacketOptions

type SplicePacketOptions struct {
	SpliceOptions
	Timeout       time.Duration
	NAT           PacketNAT
	Cached        []*N.PacketBuffer
	Offload       N.PacketOffload
	FrontHeadroom int
	RearHeadroom  int
}

type SpliceSocket

type SpliceSocket interface {
	syscall.Conn
	io.Closer
	Attach(closer io.Closer) (io.Closer, bool)
	Detach()
}

type Stack

type Stack interface {
	Start() error
	ResetNetwork()
	Close() error
}

func NewGVisor

func NewGVisor(
	options StackOptions,
) (Stack, error)

func NewMixed

func NewMixed(
	options StackOptions,
) (Stack, error)

func NewStack

func NewStack(
	stack string,
	options StackOptions,
) (Stack, error)

func NewSystem

func NewSystem(options StackOptions) (Stack, error)

type StackOptions

type StackOptions struct {
	Context                context.Context
	Tun                    Tun
	TunOptions             Options
	UDPTimeout             time.Duration
	ICMPTimeout            time.Duration
	UDPMapping             NATMapping
	UDPFiltering           NATFiltering
	UDPNATMax              uint32
	Handler                Handler
	Logger                 logger.Logger
	ForwarderBindInterface bool
	IncludeAllNetworks     bool
	InterfaceFinder        control.InterfaceFinder
	MemoryPressure         func() MemoryPressure
	TCPCongestionControl   string
}

type System

type System struct {
	// contains filtered or unexported fields
}

func (*System) Close

func (s *System) Close() error

func (*System) ResetNetwork

func (s *System) ResetNetwork()

func (*System) Start

func (s *System) Start() error

type TCPNat

type TCPNat struct {
	// contains filtered or unexported fields
}

func NewNat

func NewNat(ctx context.Context, timeout time.Duration) *TCPNat

func (*TCPNat) Lookup

func (n *TCPNat) Lookup(source netip.AddrPort, destination netip.AddrPort) uint16

func (*TCPNat) LookupBack

func (n *TCPNat) LookupBack(port uint16) *TCPSession

type TCPSession

type TCPSession struct {
	sync.Mutex
	Source      netip.AddrPort
	Destination netip.AddrPort
	LastActive  time.Time
}

type Tun

type Tun interface {
	io.ReadWriter
	Name() (string, error)
	Start() error
	Close() error
	UpdateRouteOptions(tunOptions Options) error
}

func New

func New(options Options) (Tun, error)

type UDPEgressConn

type UDPEgressConn struct {
	// contains filtered or unexported fields
}

func NewUDPEgressConn

func NewUDPEgressConn(anchor *net.UDPConn, pool *UDPEgressPool) *UDPEgressConn

func (*UDPEgressConn) Close

func (c *UDPEgressConn) Close() error

func (*UDPEgressConn) LocalAddr

func (c *UDPEgressConn) LocalAddr() net.Addr

func (*UDPEgressConn) ReadFromUDPAddrPort

func (c *UDPEgressConn) ReadFromUDPAddrPort(buffer []byte) (int, netip.AddrPort, error)

func (*UDPEgressConn) SetDeadline

func (c *UDPEgressConn) SetDeadline(t time.Time) error

func (*UDPEgressConn) SetReadDeadline

func (c *UDPEgressConn) SetReadDeadline(t time.Time) error

func (*UDPEgressConn) SetWriteDeadline

func (c *UDPEgressConn) SetWriteDeadline(t time.Time) error

func (*UDPEgressConn) WriteToUDPAddrPort

func (c *UDPEgressConn) WriteToUDPAddrPort(buffer []byte, destination netip.AddrPort) (int, error)

type UDPEgressPool

type UDPEgressPool struct {
	// contains filtered or unexported fields
}

func NewUDPEgressPool

func NewUDPEgressPool(options UDPEgressPoolOptions) *UDPEgressPool

func (*UDPEgressPool) Close

func (p *UDPEgressPool) Close()

func (*UDPEgressPool) LookupEgress

func (p *UDPEgressPool) LookupEgress(destination netip.AddrPort) *net.UDPConn

func (*UDPEgressPool) ReceiveEgress

func (p *UDPEgressPool) ReceiveEgress(buffer []byte) (int, netip.AddrPort, error)

func (*UDPEgressPool) SetEgressPort

func (p *UDPEgressPool) SetEgressPort(port uint16) bool

type UDPEgressPoolOptions

type UDPEgressPoolOptions struct {
	Logger           logger.Logger
	Network          string
	Control          control.Func
	InterfaceFinder  control.InterfaceFinder
	InterfaceMonitor DefaultInterfaceMonitor
	IsExempt         func() bool
}

type UDPNat

type UDPNat struct {
	// contains filtered or unexported fields
}

func NewUDPNat

func NewUDPNat(options UDPNatOptions) *UDPNat

func (*UDPNat) Close

func (s *UDPNat) Close() error

func (*UDPNat) NewPacket

func (s *UDPNat) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destination M.Socksaddr, userData any)

func (*UDPNat) NewPacketBatch

func (s *UDPNat) NewPacketBatch(buffers []*buf.Buffer, sources []M.Socksaddr, destination M.Socksaddr, userData any)

func (*UDPNat) Purge

func (s *UDPNat) Purge()

func (*UDPNat) PurgeExpired

func (s *UDPNat) PurgeExpired()

func (*UDPNat) Start

func (s *UDPNat) Start() error

type UDPNatConn

type UDPNatConn struct {
	// contains filtered or unexported fields
}

func (*UDPNatConn) Close

func (c *UDPNatConn) Close() error

func (*UDPNatConn) CreatePacketBatchReadWaiter

func (c *UDPNatConn) CreatePacketBatchReadWaiter() (N.PacketBatchReadWaiter, bool)

func (*UDPNatConn) CreatePacketBatchWriter

func (c *UDPNatConn) CreatePacketBatchWriter() (N.PacketBatchWriter, bool)

func (*UDPNatConn) InitializeReadWaiter

func (c *UDPNatConn) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool)

func (*UDPNatConn) LocalAddr

func (c *UDPNatConn) LocalAddr() net.Addr

func (*UDPNatConn) ReadPacket

func (c *UDPNatConn) ReadPacket(buffer *buf.Buffer) (addr M.Socksaddr, err error)

func (*UDPNatConn) RemoteAddr

func (c *UDPNatConn) RemoteAddr() net.Addr

func (*UDPNatConn) SetDeadline

func (c *UDPNatConn) SetDeadline(t time.Time) error

func (*UDPNatConn) SetReadDeadline

func (c *UDPNatConn) SetReadDeadline(t time.Time) error

func (*UDPNatConn) SetTimeout

func (c *UDPNatConn) SetTimeout(timeout time.Duration) bool

func (*UDPNatConn) SetWriteDeadline

func (c *UDPNatConn) SetWriteDeadline(t time.Time) error

func (*UDPNatConn) Splice

func (c *UDPNatConn) Splice(owner SpliceSocket, options SplicePacketOptions) bool

func (*UDPNatConn) Timeout

func (c *UDPNatConn) Timeout() time.Duration

func (*UDPNatConn) Upstream

func (c *UDPNatConn) Upstream() any

func (*UDPNatConn) WaitReadPacket

func (c *UDPNatConn) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error)

func (*UDPNatConn) WaitReadPackets

func (c *UDPNatConn) WaitReadPackets() (buffers []*buf.Buffer, destinations []M.Socksaddr, err error)

func (*UDPNatConn) WritePacket

func (c *UDPNatConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error

type UDPNatOptions

type UDPNatOptions struct {
	Handler   N.UDPConnectionHandlerEx
	Prepare   UDPNatPrepareFunc
	Timeout   time.Duration
	Shared    bool
	Mapping   NATMapping
	Filtering NATFiltering
	MaxSize   uint32

	InterfaceFinder control.InterfaceFinder
}

type UDPNatPrepareFunc

type UDPNatPrepareFunc func(source M.Socksaddr, destination M.Socksaddr, userData any) (bool, context.Context, N.PacketWriter, N.CloseHandlerFunc)

type WinTun

type WinTun interface {
	Tun
	ReadPacket() ([]byte, func(), error)
}

Directories

Path Synopsis
checksum
Package checksum provides the implementation of the encoding and decoding of network protocol headers.
Package checksum provides the implementation of the encoding and decoding of network protocol headers.
header
Package header provides the implementation of the encoding and decoding of network protocol headers.
Package header provides the implementation of the encoding and decoding of network protocol headers.
seqnum
Package seqnum defines the types and methods for TCP sequence numbers such that they fit in 32-bit words and work properly when overflows occur.
Package seqnum defines the types and methods for TCP sequence numbers such that they fit in 32-bit words and work properly when overflows occur.
internal
afd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL