Browse Source

feat: add tun support for tcp

AkinoKaede 2 years ago
parent
commit
12567c62ea

+ 170 - 0
app/tun/config.pb.go

@@ -0,0 +1,170 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// 	protoc-gen-go v1.30.0
+// 	protoc        v3.21.12
+// source: app/tun/config.proto
+
+package tun
+
+import (
+	_ "github.com/v2fly/v2ray-core/v5/common/protoext"
+	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+	reflect "reflect"
+	sync "sync"
+)
+
+const (
+	// Verify that this generated code is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+	// Verify that runtime/protoimpl is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type Config struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Name      string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+	Mtu       uint32 `protobuf:"varint,2,opt,name=mtu,proto3" json:"mtu,omitempty"`
+	UserLevel uint32 `protobuf:"varint,3,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
+}
+
+func (x *Config) Reset() {
+	*x = Config{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_app_tun_config_proto_msgTypes[0]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *Config) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Config) ProtoMessage() {}
+
+func (x *Config) ProtoReflect() protoreflect.Message {
+	mi := &file_app_tun_config_proto_msgTypes[0]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use Config.ProtoReflect.Descriptor instead.
+func (*Config) Descriptor() ([]byte, []int) {
+	return file_app_tun_config_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *Config) GetName() string {
+	if x != nil {
+		return x.Name
+	}
+	return ""
+}
+
+func (x *Config) GetMtu() uint32 {
+	if x != nil {
+		return x.Mtu
+	}
+	return 0
+}
+
+func (x *Config) GetUserLevel() uint32 {
+	if x != nil {
+		return x.UserLevel
+	}
+	return 0
+}
+
+var File_app_tun_config_proto protoreflect.FileDescriptor
+
+var file_app_tun_config_proto_rawDesc = []byte{
+	0x0a, 0x14, 0x61, 0x70, 0x70, 0x2f, 0x74, 0x75, 0x6e, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67,
+	0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
+	0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x74, 0x75, 0x6e, 0x1a, 0x20, 0x63, 0x6f, 0x6d, 0x6d,
+	0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x74, 0x2f, 0x65, 0x78, 0x74, 0x65,
+	0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x61, 0x0a, 0x06,
+	0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01,
+	0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x74,
+	0x75, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x03, 0x6d, 0x74, 0x75, 0x12, 0x1d, 0x0a, 0x0a,
+	0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d,
+	0x52, 0x09, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x3a, 0x12, 0x82, 0xb5, 0x18,
+	0x0e, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x03, 0x74, 0x75, 0x6e, 0x42,
+	0x57, 0x0a, 0x16, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72,
+	0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x74, 0x75, 0x6e, 0x50, 0x01, 0x5a, 0x26, 0x67, 0x69, 0x74,
+	0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x66, 0x6c, 0x79, 0x2f, 0x76, 0x32,
+	0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x35, 0x2f, 0x61, 0x70, 0x70, 0x2f,
+	0x74, 0x75, 0x6e, 0xaa, 0x02, 0x12, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65,
+	0x2e, 0x41, 0x70, 0x70, 0x2e, 0x54, 0x75, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+	file_app_tun_config_proto_rawDescOnce sync.Once
+	file_app_tun_config_proto_rawDescData = file_app_tun_config_proto_rawDesc
+)
+
+func file_app_tun_config_proto_rawDescGZIP() []byte {
+	file_app_tun_config_proto_rawDescOnce.Do(func() {
+		file_app_tun_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_app_tun_config_proto_rawDescData)
+	})
+	return file_app_tun_config_proto_rawDescData
+}
+
+var file_app_tun_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
+var file_app_tun_config_proto_goTypes = []interface{}{
+	(*Config)(nil), // 0: v2ray.core.app.tun.Config
+}
+var file_app_tun_config_proto_depIdxs = []int32{
+	0, // [0:0] is the sub-list for method output_type
+	0, // [0:0] is the sub-list for method input_type
+	0, // [0:0] is the sub-list for extension type_name
+	0, // [0:0] is the sub-list for extension extendee
+	0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_app_tun_config_proto_init() }
+func file_app_tun_config_proto_init() {
+	if File_app_tun_config_proto != nil {
+		return
+	}
+	if !protoimpl.UnsafeEnabled {
+		file_app_tun_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*Config); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+	}
+	type x struct{}
+	out := protoimpl.TypeBuilder{
+		File: protoimpl.DescBuilder{
+			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+			RawDescriptor: file_app_tun_config_proto_rawDesc,
+			NumEnums:      0,
+			NumMessages:   1,
+			NumExtensions: 0,
+			NumServices:   0,
+		},
+		GoTypes:           file_app_tun_config_proto_goTypes,
+		DependencyIndexes: file_app_tun_config_proto_depIdxs,
+		MessageInfos:      file_app_tun_config_proto_msgTypes,
+	}.Build()
+	File_app_tun_config_proto = out.File
+	file_app_tun_config_proto_rawDesc = nil
+	file_app_tun_config_proto_goTypes = nil
+	file_app_tun_config_proto_depIdxs = nil
+}

+ 22 - 0
app/tun/config.proto

@@ -0,0 +1,22 @@
+syntax = "proto3";
+
+package v2ray.core.app.tun;
+option csharp_namespace = "V2Ray.Core.App.Tun";
+option go_package = "github.com/v2fly/v2ray-core/v5/app/tun";
+option java_package = "com.v2ray.core.app.tun";
+option java_multiple_files = true;
+
+
+// import "app/router/routercommon/common.proto";
+
+import "common/protoext/extensions.proto";
+
+message Config {
+    option (v2ray.core.common.protoext.message_opt).type = "service";
+    option (v2ray.core.common.protoext.message_opt).short_name = "tun";
+
+    
+    string name = 1;
+    uint32 mtu = 2;
+    uint32 user_level = 3;
+}

+ 19 - 0
app/tun/device/device.go

@@ -0,0 +1,19 @@
+package device
+
+import (
+	"github.com/v2fly/v2ray-core/v5/common"
+	"gvisor.dev/gvisor/pkg/tcpip/stack"
+)
+
+type Device interface {
+	stack.LinkEndpoint
+
+	common.Closable
+}
+
+type Options struct {
+	Name string
+	MTU  uint32
+}
+
+type NewTUNFunc func(Options) (Device, error)

+ 9 - 0
app/tun/device/tun/errors.generated.go

@@ -0,0 +1,9 @@
+package tun
+
+import "github.com/v2fly/v2ray-core/v5/common/errors"
+
+type errPathObjHolder struct{}
+
+func newError(values ...interface{}) *errors.Error {
+	return errors.New(values...).WithPathObj(errPathObjHolder{})
+}

+ 3 - 0
app/tun/device/tun/tun.go

@@ -0,0 +1,3 @@
+package tun
+
+//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen

+ 68 - 0
app/tun/device/tun/tun_gvisor.go

@@ -0,0 +1,68 @@
+//go:build linux && ((linux && amd64) || (linux && arm64))
+// +build linux
+// +build linux,amd64 linux,arm64
+
+package tun
+
+import (
+	"github.com/v2fly/v2ray-core/v5/app/tun/device"
+	"golang.org/x/sys/unix"
+	"gvisor.dev/gvisor/pkg/tcpip/stack"
+
+	"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
+	"gvisor.dev/gvisor/pkg/tcpip/link/rawfile"
+	"gvisor.dev/gvisor/pkg/tcpip/link/tun"
+)
+
+type TUN struct {
+	stack.LinkEndpoint
+
+	options device.Options
+
+	fd  int
+	mtu uint32 // real MTU
+}
+
+func New(options device.Options) (device.Device, error) {
+	t := &TUN{options: options}
+
+	if len(options.Name) > unix.IFNAMSIZ {
+		return nil, newError("name too long").AtError()
+	}
+
+	fd, err := tun.Open(options.Name)
+	if err != nil {
+		return nil, newError("failed to open tun device").Base(err).AtError()
+	}
+	t.fd = fd
+
+	// TODO: set MTU
+
+	mtu, err := rawfile.GetMTU(options.Name)
+	if err != nil {
+		return nil, newError("failed to get mtu").Base(err).AtError()
+	}
+	t.mtu = mtu
+
+	linkEndpoint, err := fdbased.New(&fdbased.Options{
+		FDs: []int{fd},
+		MTU: mtu,
+		// TUN is not need to process ethernet header.
+		EthernetHeader: false,
+		// Readv is the default dispatch mode and is the least performant of the
+		// dispatch options but the one that is supported by all underlying FD
+		// types.
+		PacketDispatchMode:    fdbased.Readv,
+		MaxSyscallHeaderBytes: 0x00,
+	})
+	if err != nil {
+		return nil, newError("failed to create link endpoint").Base(err).AtError()
+	}
+	t.LinkEndpoint = linkEndpoint
+
+	return t, nil
+}
+
+func (t *TUN) Close() error {
+	return unix.Close(t.fd)
+}

+ 9 - 0
app/tun/errors.generated.go

@@ -0,0 +1,9 @@
+package tun
+
+import "github.com/v2fly/v2ray-core/v5/common/errors"
+
+type errPathObjHolder struct{}
+
+func newError(values ...interface{}) *errors.Error {
+	return errors.New(values...).WithPathObj(errPathObjHolder{})
+}

+ 1 - 0
app/tun/handler.go

@@ -0,0 +1 @@
+package tun

+ 96 - 0
app/tun/handler_tcp.go

@@ -0,0 +1,96 @@
+package tun
+
+import (
+	"context"
+
+	"github.com/v2fly/v2ray-core/v5/common"
+	"github.com/v2fly/v2ray-core/v5/common/buf"
+	"github.com/v2fly/v2ray-core/v5/common/log"
+	"github.com/v2fly/v2ray-core/v5/common/net"
+	"github.com/v2fly/v2ray-core/v5/common/signal"
+	"github.com/v2fly/v2ray-core/v5/common/task"
+	"github.com/v2fly/v2ray-core/v5/features/policy"
+	"github.com/v2fly/v2ray-core/v5/features/routing"
+	"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
+	"gvisor.dev/gvisor/pkg/tcpip/stack"
+	"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
+	"gvisor.dev/gvisor/pkg/waiter"
+)
+
+type TCPHandler struct {
+	ctx           context.Context
+	dispatcher    routing.Dispatcher
+	policyManager policy.Manager
+	config        *Config
+
+	stack       *stack.Stack
+	rcvWnd      int
+	maxInFlight int
+}
+
+func (h *TCPHandler) SetHandler() {
+	tcpForwarder := tcp.NewForwarder(h.stack, h.rcvWnd, h.maxInFlight, func(r *tcp.ForwarderRequest) {
+		wg := new(waiter.Queue)
+		linkedEndpoint, err := r.CreateEndpoint(wg)
+		if err != nil {
+			r.Complete(true)
+			return
+		}
+		defer r.Complete(false)
+
+		// TODO: set sockopt
+
+		h.handle(gonet.NewTCPConn(wg, linkedEndpoint))
+
+	})
+	h.stack.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)
+}
+
+func (h *TCPHandler) handle(conn *gonet.TCPConn) error {
+	sessionPolicy := h.policyManager.ForLevel(h.config.UserLevel)
+
+	addr := conn.RemoteAddr()
+
+	dest := net.DestinationFromAddr(addr)
+	ctx := log.ContextWithAccessMessage(h.ctx, &log.AccessMessage{
+		From:   addr,
+		To:     dest,
+		Status: log.AccessAccepted,
+		Reason: "",
+	})
+	ctx, cancel := context.WithCancel(ctx)
+	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
+	link, err := h.dispatcher.Dispatch(ctx, dest)
+	if err != nil {
+		return newError("failed to dispatch").Base(err)
+	}
+
+	responseDone := func() error {
+		defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
+
+		if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil {
+			return newError("failed to transport all TCP response").Base(err)
+		}
+
+		return nil
+	}
+
+	requestDone := func() error {
+		defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
+
+		if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil {
+			return newError("failed to transport all TCP request").Base(err)
+		}
+
+		return nil
+	}
+
+	requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
+	if err := task.Run(h.ctx, requestDoneAndCloseWriter, responseDone); err != nil {
+		common.Interrupt(link.Reader)
+		common.Interrupt(link.Writer)
+		return newError("connection ends").Base(err)
+	}
+
+	return nil
+}

+ 29 - 0
app/tun/stack.go

@@ -0,0 +1,29 @@
+package tun
+
+import (
+	"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"
+)
+
+func CreateStack(_ stack.LinkEndpoint) (*stack.Stack, error) {
+	s := stack.New(stack.Options{
+		NetworkProtocols: []stack.NetworkProtocolFactory{
+			ipv4.NewProtocol,
+			ipv6.NewProtocol,
+		},
+		TransportProtocols: []stack.TransportProtocolFactory{
+			tcp.NewProtocol,
+			udp.NewProtocol,
+			icmp.NewProtocol4,
+			icmp.NewProtocol6,
+		},
+	})
+
+	// nicID := tcpip.NICID(s.UniqueID())
+
+	return s, nil
+}

+ 89 - 0
app/tun/tun.go

@@ -0,0 +1,89 @@
+//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 {
+	var newDeviceFunc device.NewTUNFunc
+	newDeviceFunc = tun.New
+	device, err := newDeviceFunc(device.Options{
+		Name: t.config.Name,
+		MTU:  t.config.Mtu,
+	})
+	if err != nil {
+		return newError("failed to create device").Base(err).AtError()
+	}
+
+	stack, err := CreateStack(device)
+	if err != nil {
+		return newError("failed to create stack").Base(err).AtError()
+	}
+	t.stack = stack
+
+	tcpHandler := &TCPHandler{
+		ctx:           t.ctx,
+		dispatcher:    t.dispatcher,
+		policyManager: t.policyManager,
+		config:        t.config,
+		stack:         stack,
+	}
+
+	tcpHandler.SetHandler()
+
+	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
+	}))
+}