tun

package module
v0.0.0-...-15dd90c Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: GPL-2.0 Imports: 45 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
)
View Source
const (
	DefaultIPRoute2TableIndex                    = 2022
	DefaultIPRoute2RuleIndex                     = 9000
	DefaultIPRoute2AutoRedirectFallbackRuleIndex = 32768
)
View Source
const FlagAndroidVPNUpdate = 1 << iota
View Source
const PacketOffset = 0
View Source
const ProtocolRedirect = "redirect"
View Source
const WithGVisor = false

Variables

View Source
var (
	ErrDrop  = E.New("drop by rule")
	ErrReset = E.New("reset by rule")
)
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 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 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()
}

func NewAutoRedirect

func NewAutoRedirect(options AutoRedirectOptions) (AutoRedirect, error)

type AutoRedirectOptions

type AutoRedirectOptions struct {
	TunOptions             *Options
	Context                context.Context
	Handler                Handler
	Logger                 logger.Logger
	NetworkMonitor         NetworkUpdateMonitor
	InterfaceFinder        control.InterfaceFinder
	TableName              string
	DisableNFTables        bool
	CustomRedirectPort     func() int
	RouteAddressSet        *[]*netipx.IPSet
	RouteExcludeAddressSet *[]*netipx.IPSet
}

type DarwinTUN

type DarwinTUN interface {
	Tun
	BatchSize() int
	BatchRead() ([]*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])
}

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 DirectRouteContext

type DirectRouteContext interface {
	WritePacket(packet []byte) error
}

type DirectRouteDestination

type DirectRouteDestination interface {
	WritePacket(packet *buf.Buffer) error
	Close() error
	IsClosed() bool
}

type DirectRouteMapping

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

func NewDirectRouteMapping

func NewDirectRouteMapping(timeout time.Duration) *DirectRouteMapping

func (*DirectRouteMapping) Lookup

func (m *DirectRouteMapping) Lookup(session DirectRouteSession, constructor func(timeout time.Duration) (DirectRouteDestination, error)) (DirectRouteDestination, error)

type DirectRouteSession

type DirectRouteSession struct {
	// IPVersion uint8
	// Network     uint8
	Source      netip.Addr
	Destination netip.Addr
}

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 Handler

type Handler interface {
	PrepareConnection(
		network string,
		source M.Socksaddr,
		destination M.Socksaddr,
		routeContext DirectRouteContext,
		timeout time.Duration,
	) (DirectRouteDestination, error)
	N.TCPConnectionHandler
	PacketHandler
	E.Handler
}

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 Mipstack

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

func (*Mipstack) Close

func (s *Mipstack) Close() error

Start and Close are called sequentially by the owner, like the other stacks.

func (*Mipstack) Start

func (s *Mipstack) Start() error

type NativeTun

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

func (*NativeTun) BatchRead

func (t *NativeTun) BatchRead(buffers [][]byte, offset int, readN []int) (n int, err 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) Read

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

func (*NativeTun) TXChecksumOffload

func (t *NativeTun) TXChecksumOffload() bool

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
	Inet4Address                          []netip.Prefix
	Inet6Address                          []netip.Prefix
	MTU                                   uint32
	GSO                                   bool
	AutoRoute                             bool
	Inet4Gateway                          netip.Addr
	Inet6Gateway                          netip.Addr
	DNSServers                            []netip.Addr
	IPRoute2TableIndex                    int
	IPRoute2RuleIndex                     int
	IPRoute2AutoRedirectFallbackRuleIndex int
	AutoRedirectMarkMode                  bool
	AutoRedirectInputMark                 uint32
	AutoRedirectOutputMark                uint32
	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
	IncludeUID                            []ranges.Range[uint32]
	ExcludeUID                            []ranges.Range[uint32]
	ExcludeSrcPort                        []ranges.Range[uint16]
	ExcludeDstPort                        []ranges.Range[uint16]
	IncludeAndroidUser                    []int
	IncludePackage                        []string
	ExcludePackage                        []string
	IncludeMACAddress                     []net.HardwareAddr
	ExcludeMACAddress                     []net.HardwareAddr
	InterfaceMonitor                      DefaultInterfaceMonitor
	FileDescriptor                        int
	Logger                                logger.Logger

	// For library usages.
	EXP_DisableDNSHijack bool

	// For darwin tun
	EXP_RecvMsgX bool
	EXP_SendMsgX bool

	// For gvisor
	EXP_ProcessorsPerChannel int
	// contains filtered or unexported fields
}

func (*Options) BuildAndroidRules

func (o *Options) BuildAndroidRules(packageManager PackageManager, errorHandler E.Handler)

func (*Options) BuildAutoRouteRanges

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

func (*Options) ExcludedRanges

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

func (*Options) Inet4GatewayAddr

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

func (*Options) Inet6GatewayAddr

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

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 PacketHandler

type PacketHandler interface {
	NewPacket(ctx context.Context, key netip.AddrPort, buffer *buf.Buffer, metadata M.Metadata, init func(natConn N.PacketConn) N.PacketWriter)
}

type PacketInterceptMatcher

type PacketInterceptMatcher interface {
	ShouldInterceptPacket(destination netip.Addr) bool
}

type PacketInterceptor

type PacketInterceptor interface {
	InterceptPacket(destination netip.Addr, packet []byte) bool
}

type Session

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

type Stack

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

func NewGVisor

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

func NewMipstack

func NewMipstack(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
	EndpointIndependentNat bool
	UDPTimeout             time.Duration
	ICMPTimeout            time.Duration
	Handler                Handler
	Logger                 logger.Logger
	ForwarderBindInterface bool
	IncludeAllNetworks     bool
	InterfaceFinder        control.InterfaceFinder
	EnforceBindInterface   bool
	PacketInterceptor      PacketInterceptor
	// TCPWindowBytes overrides the gVisor stack's fixed TCP receive/send
	// buffer size (default 20*1024, stack_gvisor.go's NewGVisorStackWithOptions).
	// 0 keeps that default. See docs/TUN_STACK_OPTIMIZATION.md step 3/4 in the
	// mihomo/Violet repo for the throughput-bound arithmetic (throughput ≈
	// window / RTT) behind why this exists: the fixed 20KB caps single-connection
	// throughput well below what a real network path allows once RTT grows past
	// a few milliseconds, and TCPModerateReceiveBufferOption's auto-tuning has
	// no room to grow past a ceiling that equals its own floor.
	TCPWindowBytes int
}

type System

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

func (*System) Close

func (s *System) Close() error

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, error)

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
	Close() error
}

func New

func New(options Options) (Tun, error)

type WinTun

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

Directories

Path Synopsis
internal
fdbased_darwin
Package fdbased provides the implementation of data-link layer endpoints backed by boundary-preserving file descriptors (e.g., TUN devices, seqpacket/datagram sockets).
Package fdbased provides the implementation of data-link layer endpoints backed by boundary-preserving file descriptors (e.g., TUN devices, seqpacket/datagram sockets).
gtcpip/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.
gtcpip/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.
gtcpip/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.

Jump to

Keyboard shortcuts

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