1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/app/tun/tun.go

79 lines
1.7 KiB
Go
Raw Normal View History

2023-05-28 00:18:58 -04:00
//go:build !confonly
// +build !confonly
package tun
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/tun/device"
"github.com/v2fly/v2ray-core/v5/app/tun/device/tun"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type TUN struct {
ctx context.Context
dispatcher routing.Dispatcher
policyManager policy.Manager
config *Config
stack *stack.Stack
}
func (t *TUN) Type() interface{} {
return (*TUN)(nil)
}
func (t *TUN) Start() error {
2023-05-28 02:17:40 -04:00
DeviceCreator := tun.New
device, err := DeviceCreator(device.Options{
2023-05-28 00:18:58 -04:00
Name: t.config.Name,
MTU: t.config.Mtu,
})
if err != nil {
return newError("failed to create device").Base(err).AtError()
}
2023-05-28 02:32:48 -04:00
stack, err := t.CreateStack(device)
2023-05-28 00:18:58 -04:00
if err != nil {
return newError("failed to create stack").Base(err).AtError()
}
t.stack = stack
return nil
}
func (t *TUN) Close() error {
if t.stack != nil {
t.stack.Close()
t.stack.Wait()
}
return nil
}
func NewTUN(ctx context.Context, config *Config, dispatcher routing.Dispatcher) *TUN {
v := core.MustFromContext(ctx)
return &TUN{
ctx: ctx,
dispatcher: dispatcher,
config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
tun := core.RequireFeatures(ctx, func(d routing.Dispatcher) *TUN {
return NewTUN(ctx, config.(*Config), d)
})
return tun, nil
}))
}