github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/tun/stack.go (about) 1 package tun 2 3 import ( 4 "gvisor.dev/gvisor/pkg/tcpip" 5 "gvisor.dev/gvisor/pkg/tcpip/network/ipv4" 6 "gvisor.dev/gvisor/pkg/tcpip/network/ipv6" 7 "gvisor.dev/gvisor/pkg/tcpip/stack" 8 "gvisor.dev/gvisor/pkg/tcpip/transport/icmp" 9 "gvisor.dev/gvisor/pkg/tcpip/transport/tcp" 10 "gvisor.dev/gvisor/pkg/tcpip/transport/udp" 11 ) 12 13 type StackOption func(*stack.Stack) error 14 15 func (t *TUN) CreateStack(linkedEndpoint stack.LinkEndpoint) (*stack.Stack, error) { 16 s := stack.New(stack.Options{ 17 NetworkProtocols: []stack.NetworkProtocolFactory{ 18 ipv4.NewProtocol, 19 ipv6.NewProtocol, 20 }, 21 TransportProtocols: []stack.TransportProtocolFactory{ 22 tcp.NewProtocol, 23 udp.NewProtocol, 24 icmp.NewProtocol4, 25 icmp.NewProtocol6, 26 }, 27 }) 28 29 nicID := tcpip.NICID(s.UniqueID()) 30 31 opts := []StackOption{ 32 SetTCPHandler(t.ctx, t.dispatcher, t.policyManager, t.config), 33 SetUDPHandler(t.ctx, t.dispatcher, t.policyManager, t.config), 34 35 CreateNIC(nicID, linkedEndpoint), 36 AddProtocolAddress(nicID, t.config.Ips), 37 SetRouteTable(nicID, t.config.Routes), 38 SetPromiscuousMode(nicID, t.config.EnablePromiscuousMode), 39 SetSpoofing(nicID, t.config.EnableSpoofing), 40 } 41 42 if t.config.SocketSettings != nil { 43 if size := t.config.SocketSettings.TxBufSize; size != 0 { 44 opts = append(opts, SetTCPSendBufferSize(int(size))) 45 } 46 47 if size := t.config.SocketSettings.RxBufSize; size != 0 { 48 opts = append(opts, SetTCPReceiveBufferSize(int(size))) 49 } 50 } 51 52 for _, opt := range opts { 53 if err := opt(s); err != nil { 54 return nil, err 55 } 56 } 57 58 return s, nil 59 }