github.com/sagernet/sing-box@v1.2.7/transport/wireguard/device_system.go (about) 1 package wireguard 2 3 import ( 4 "context" 5 "net" 6 "net/netip" 7 "os" 8 9 "github.com/sagernet/sing-box/adapter" 10 "github.com/sagernet/sing-box/common/dialer" 11 "github.com/sagernet/sing-box/option" 12 "github.com/sagernet/sing-tun" 13 M "github.com/sagernet/sing/common/metadata" 14 N "github.com/sagernet/sing/common/network" 15 wgTun "github.com/sagernet/wireguard-go/tun" 16 ) 17 18 var _ Device = (*SystemDevice)(nil) 19 20 type SystemDevice struct { 21 dialer N.Dialer 22 device tun.Tun 23 name string 24 mtu int 25 events chan wgTun.Event 26 } 27 28 /*func (w *SystemDevice) NewEndpoint() (stack.LinkEndpoint, error) { 29 gTun, isGTun := w.device.(tun.GVisorTun) 30 if !isGTun { 31 return nil, tun.ErrGVisorUnsupported 32 } 33 return gTun.NewEndpoint() 34 }*/ 35 36 func NewSystemDevice(router adapter.Router, interfaceName string, localPrefixes []netip.Prefix, mtu uint32) (*SystemDevice, error) { 37 var inet4Addresses []netip.Prefix 38 var inet6Addresses []netip.Prefix 39 for _, prefixes := range localPrefixes { 40 if prefixes.Addr().Is4() { 41 inet4Addresses = append(inet4Addresses, prefixes) 42 } else { 43 inet6Addresses = append(inet6Addresses, prefixes) 44 } 45 } 46 if interfaceName == "" { 47 interfaceName = tun.CalculateInterfaceName("wg") 48 } 49 tunInterface, err := tun.New(tun.Options{ 50 Name: interfaceName, 51 Inet4Address: inet4Addresses, 52 Inet6Address: inet6Addresses, 53 MTU: mtu, 54 }) 55 if err != nil { 56 return nil, err 57 } 58 return &SystemDevice{ 59 dialer.NewDefault(router, option.DialerOptions{ 60 BindInterface: interfaceName, 61 }), 62 tunInterface, interfaceName, int(mtu), make(chan wgTun.Event), 63 }, nil 64 } 65 66 func (w *SystemDevice) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { 67 return w.dialer.DialContext(ctx, network, destination) 68 } 69 70 func (w *SystemDevice) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { 71 return w.dialer.ListenPacket(ctx, destination) 72 } 73 74 func (w *SystemDevice) Start() error { 75 w.events <- wgTun.EventUp 76 return nil 77 } 78 79 func (w *SystemDevice) File() *os.File { 80 return nil 81 } 82 83 func (w *SystemDevice) Read(bytes []byte, index int) (int, error) { 84 return w.device.Read(bytes[index-tun.PacketOffset:]) 85 } 86 87 func (w *SystemDevice) Write(bytes []byte, index int) (int, error) { 88 return w.device.Write(bytes[index:]) 89 } 90 91 func (w *SystemDevice) Flush() error { 92 return nil 93 } 94 95 func (w *SystemDevice) MTU() (int, error) { 96 return w.mtu, nil 97 } 98 99 func (w *SystemDevice) Name() (string, error) { 100 return w.name, nil 101 } 102 103 func (w *SystemDevice) Events() chan wgTun.Event { 104 return w.events 105 } 106 107 func (w *SystemDevice) Close() error { 108 return w.device.Close() 109 }