github.com/sagernet/sing-tun@v0.3.0-beta.5/tun.go (about) 1 package tun 2 3 import ( 4 "io" 5 "net" 6 "net/netip" 7 "runtime" 8 "strconv" 9 "strings" 10 11 E "github.com/sagernet/sing/common/exceptions" 12 F "github.com/sagernet/sing/common/format" 13 "github.com/sagernet/sing/common/logger" 14 N "github.com/sagernet/sing/common/network" 15 "github.com/sagernet/sing/common/ranges" 16 ) 17 18 type Handler interface { 19 N.TCPConnectionHandler 20 N.UDPConnectionHandler 21 E.Handler 22 } 23 24 type Tun interface { 25 io.ReadWriter 26 N.VectorisedWriter 27 Close() error 28 } 29 30 type WinTun interface { 31 Tun 32 ReadPacket() ([]byte, func(), error) 33 } 34 35 type LinuxTUN interface { 36 Tun 37 N.FrontHeadroom 38 BatchSize() int 39 BatchRead(buffers [][]byte, offset int, readN []int) (n int, err error) 40 BatchWrite(buffers [][]byte, offset int) error 41 TXChecksumOffload() bool 42 } 43 44 type Options struct { 45 Name string 46 Inet4Address []netip.Prefix 47 Inet6Address []netip.Prefix 48 MTU uint32 49 GSO bool 50 AutoRoute bool 51 StrictRoute bool 52 Inet4RouteAddress []netip.Prefix 53 Inet6RouteAddress []netip.Prefix 54 Inet4RouteExcludeAddress []netip.Prefix 55 Inet6RouteExcludeAddress []netip.Prefix 56 IncludeInterface []string 57 ExcludeInterface []string 58 IncludeUID []ranges.Range[uint32] 59 ExcludeUID []ranges.Range[uint32] 60 IncludeAndroidUser []int 61 IncludePackage []string 62 ExcludePackage []string 63 InterfaceMonitor DefaultInterfaceMonitor 64 TableIndex int 65 FileDescriptor int 66 Logger logger.Logger 67 68 // No work for TCP, do not use. 69 _TXChecksumOffload bool 70 } 71 72 func CalculateInterfaceName(name string) (tunName string) { 73 if runtime.GOOS == "darwin" { 74 tunName = "utun" 75 } else if name != "" { 76 tunName = name 77 } else { 78 tunName = "tun" 79 } 80 interfaces, err := net.Interfaces() 81 if err != nil { 82 return 83 } 84 var tunIndex int 85 for _, netInterface := range interfaces { 86 if strings.HasPrefix(netInterface.Name, tunName) { 87 index, parseErr := strconv.ParseInt(netInterface.Name[len(tunName):], 10, 16) 88 if parseErr == nil && int(index) >= tunIndex { 89 tunIndex = int(index) + 1 90 } 91 } 92 } 93 tunName = F.ToString(tunName, tunIndex) 94 return 95 }