2023-05-28 00:18:58 -04:00
|
|
|
package tun
|
|
|
|
|
|
|
|
import (
|
2023-05-28 02:39:16 -04:00
|
|
|
"gvisor.dev/gvisor/pkg/tcpip"
|
2023-05-28 00:18:58 -04:00
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
|
|
|
)
|
|
|
|
|
2023-05-28 02:17:40 -04:00
|
|
|
type StackOption func(*stack.Stack) error
|
|
|
|
|
2023-05-28 02:39:16 -04:00
|
|
|
func (t *TUN) CreateStack(linkedEndpoint stack.LinkEndpoint) (*stack.Stack, error) {
|
2023-05-28 00:18:58 -04:00
|
|
|
s := stack.New(stack.Options{
|
|
|
|
NetworkProtocols: []stack.NetworkProtocolFactory{
|
|
|
|
ipv4.NewProtocol,
|
|
|
|
ipv6.NewProtocol,
|
|
|
|
},
|
|
|
|
TransportProtocols: []stack.TransportProtocolFactory{
|
|
|
|
tcp.NewProtocol,
|
|
|
|
udp.NewProtocol,
|
|
|
|
icmp.NewProtocol4,
|
|
|
|
icmp.NewProtocol6,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2023-05-28 02:39:16 -04:00
|
|
|
nicID := tcpip.NICID(s.UniqueID())
|
|
|
|
|
2023-05-28 02:32:48 -04:00
|
|
|
opts := []StackOption{
|
2023-05-28 09:08:36 -04:00
|
|
|
HandleTCP(handleTCP),
|
|
|
|
HandleUDP(handleUDP),
|
2023-05-28 02:39:16 -04:00
|
|
|
|
|
|
|
CreateNIC(nicID, linkedEndpoint),
|
2023-05-28 05:28:10 -04:00
|
|
|
AddProtocolAddress(nicID, t.config.Ips),
|
2023-05-28 06:00:23 -04:00
|
|
|
SetRouteTable(nicID, t.config.Routes),
|
2023-05-28 05:42:22 -04:00
|
|
|
SetPromiscuousMode(nicID, t.config.EnablePromiscuousMode),
|
|
|
|
SetSpoofing(nicID, t.config.EnableSpoofing),
|
2023-05-28 02:32:48 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
if err := opt(s); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-28 00:18:58 -04:00
|
|
|
return s, nil
|
|
|
|
}
|