clash/listener/tun/tun_adapter.go

63 lines
1.7 KiB
Go
Raw Normal View History

2021-11-17 08:03:47 +00:00
package tun
import (
"errors"
"fmt"
"strings"
2021-12-09 14:52:11 +00:00
"time"
2021-11-17 08:03:47 +00:00
"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/config"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/listener/tun/dev"
"github.com/Dreamacro/clash/listener/tun/ipstack"
"github.com/Dreamacro/clash/listener/tun/ipstack/gvisor"
"github.com/Dreamacro/clash/listener/tun/ipstack/system"
"github.com/Dreamacro/clash/log"
)
// New create TunAdapter
func New(conf config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) (ipstack.TunAdapter, error) {
tunAddress := "198.18.0.1"
autoRoute := conf.AutoRoute
stack := conf.Stack
var tunAdapter ipstack.TunAdapter
device, err := dev.OpenTunDevice(tunAddress, autoRoute)
if err != nil {
2021-12-09 14:52:11 +00:00
for i := 1; i < 3; i++ {
time.Sleep(time.Second * 1)
device, err = dev.OpenTunDevice(tunAddress, autoRoute)
if err == nil {
break
}
}
if err != nil {
return nil, fmt.Errorf("can't open tun: %v", err)
}
2021-11-17 08:03:47 +00:00
}
mtu, err := device.MTU()
if err != nil {
_ = device.Close()
return nil, errors.New("unable to get device mtu")
}
2021-12-01 09:08:44 +00:00
if strings.EqualFold(stack, "system") {
2021-11-17 08:03:47 +00:00
tunAdapter, err = system.NewAdapter(device, conf, mtu, tunAddress, tunAddress, func() {}, tcpIn, udpIn)
} else if strings.EqualFold(stack, "gvisor") {
2021-12-26 19:16:48 +00:00
tunAdapter, err = gvisor.NewAdapter(device, conf, tcpIn, udpIn)
2021-11-17 08:03:47 +00:00
} else {
err = fmt.Errorf("can not support tun ip stack: %s, only support \"lwip\" \"system\" and \"gvisor\"", stack)
}
if err != nil {
_ = device.Close()
return nil, err
}
log.Infoln("Tun adapter listening at: %s(%s), mtu: %d, auto route: %v, ip stack: %s", device.Name(), tunAddress, mtu, autoRoute, stack)
return tunAdapter, nil
}