diff --git a/core/hint/conf/loader.go b/core/hint/conf/loader.go index 98babe0d..226f7a22 100644 --- a/core/hint/conf/loader.go +++ b/core/hint/conf/loader.go @@ -20,6 +20,7 @@ import ( hint_anytls "github.com/v2rayA/v2raya-core/hint/proxy/anytls" hint_juicity "github.com/v2rayA/v2raya-core/hint/proxy/juicity" hint_tuic "github.com/v2rayA/v2raya-core/hint/proxy/tuic" + hint_tunmips "github.com/v2rayA/v2raya-core/hint/proxy/tunmips" xray_commander "github.com/xtls/xray-core/app/commander" xray_proxyman "github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/common" @@ -86,6 +87,14 @@ type customOutboundJSON struct { StreamSettings json.RawMessage `json:"streamSettings"` } +// customInboundJSON is the raw JSON form of a tun-mips inbound. +type customInboundJSON struct { + Protocol string `json:"protocol"` + Tag string `json:"tag"` + Settings json.RawMessage `json:"settings"` + Sniffing *xray_conf.SniffingConfig `json:"sniffing"` +} + // customProtocols is the set of outbound protocols handled by hint/proxy. var customProtocols = map[string]bool{ "anytls": true, @@ -93,53 +102,122 @@ var customProtocols = map[string]bool{ "tuic": true, } -// stripCustomOutbounds parses raw JSON, removes custom-protocol outbound entries, -// and returns the modified JSON along with the stripped outbound descriptors. -// If the JSON is not valid or has no outbounds, raw is returned unchanged with -// nil custom list (safe to pass to xray unmodified). -func stripCustomOutbounds(raw []byte) ([]byte, []customOutboundJSON, error) { +// customInboundProtocols is the set of inbound protocols handled by +// hint/proxy. It is kept apart from customProtocols so that a protocol used +// in the wrong direction is rejected instead of being stripped and then +// silently dropped. +var customInboundProtocols = map[string]bool{ + "tun-mips": true, +} + +// customConfig is everything stripped from one JSON document before xray +// parses it. +type customConfig struct { + outbounds []customOutboundJSON + inbounds []customInboundJSON +} + +func (c *customConfig) empty() bool { + return c == nil || (len(c.outbounds) == 0 && len(c.inbounds) == 0) +} + +func (c *customConfig) merge(other *customConfig) { + if other == nil { + return + } + c.outbounds = append(c.outbounds, other.outbounds...) + c.inbounds = append(c.inbounds, other.inbounds...) +} + +// stripCustom removes hint/proxy outbounds and inbounds from raw JSON and +// returns the modified document with the stripped descriptors. Invalid JSON +// or a document without those arrays is returned unchanged, nothing +// stripped, for xray to report on. +func stripCustom(raw []byte) ([]byte, *customConfig, error) { var doc map[string]json.RawMessage if err := json.Unmarshal(raw, &doc); err != nil { return raw, nil, nil } - outboundsRaw, ok := doc["outbounds"] - if !ok { - return raw, nil, nil - } - var outbounds []json.RawMessage - if err := json.Unmarshal(outboundsRaw, &outbounds); err != nil { - return raw, nil, nil - } + custom := &customConfig{} + changed := false - var remaining []json.RawMessage - var custom []customOutboundJSON - for _, ob := range outbounds { - var probe struct { - Protocol string `json:"protocol"` - } - if err := json.Unmarshal(ob, &probe); err != nil { - remaining = append(remaining, ob) - continue - } - if customProtocols[probe.Protocol] { - var c customOutboundJSON - if err := json.Unmarshal(ob, &c); err == nil { - custom = append(custom, c) + if outboundsRaw, ok := doc["outbounds"]; ok { + var outbounds []json.RawMessage + if err := json.Unmarshal(outboundsRaw, &outbounds); err == nil { + var remaining []json.RawMessage + for _, ob := range outbounds { + var probe struct { + Protocol string `json:"protocol"` + Tag string `json:"tag"` + } + if err := json.Unmarshal(ob, &probe); err != nil { + remaining = append(remaining, ob) + continue + } + if customInboundProtocols[probe.Protocol] { + return raw, nil, errors.New("protocol ", probe.Protocol, " is an inbound, not valid as outbound (tag ", probe.Tag, ")") + } + if !customProtocols[probe.Protocol] { + remaining = append(remaining, ob) + continue + } + var c customOutboundJSON + if err := json.Unmarshal(ob, &c); err != nil { + return raw, nil, errors.New("invalid ", probe.Protocol, " outbound (tag ", probe.Tag, ")").Base(err) + } + custom.outbounds = append(custom.outbounds, c) + } + if len(custom.outbounds) > 0 { + newOutbounds, err := json.Marshal(remaining) + if err != nil { + return raw, nil, err + } + doc["outbounds"] = newOutbounds + changed = true } - } else { - remaining = append(remaining, ob) } } - if len(custom) == 0 { - return raw, nil, nil + if inboundsRaw, ok := doc["inbounds"]; ok { + var inbounds []json.RawMessage + if err := json.Unmarshal(inboundsRaw, &inbounds); err == nil { + var remaining []json.RawMessage + for _, ib := range inbounds { + var probe struct { + Protocol string `json:"protocol"` + Tag string `json:"tag"` + } + if err := json.Unmarshal(ib, &probe); err != nil { + remaining = append(remaining, ib) + continue + } + if customProtocols[probe.Protocol] { + return raw, nil, errors.New("protocol ", probe.Protocol, " is an outbound, not valid as inbound (tag ", probe.Tag, ")") + } + if !customInboundProtocols[probe.Protocol] { + remaining = append(remaining, ib) + continue + } + var c customInboundJSON + if err := json.Unmarshal(ib, &c); err != nil { + return raw, nil, errors.New("invalid ", probe.Protocol, " inbound (tag ", probe.Tag, ")").Base(err) + } + custom.inbounds = append(custom.inbounds, c) + } + if len(custom.inbounds) > 0 { + newInbounds, err := json.Marshal(remaining) + if err != nil { + return raw, nil, err + } + doc["inbounds"] = newInbounds + changed = true + } + } } - newOutbounds, err := json.Marshal(remaining) - if err != nil { - return raw, nil, err + if !changed { + return raw, nil, nil } - doc["outbounds"] = newOutbounds modified, err := json.Marshal(doc) if err != nil { return raw, nil, err @@ -147,6 +225,70 @@ func stripCustomOutbounds(raw []byte) ([]byte, []customOutboundJSON, error) { return modified, custom, nil } +// buildCustomInbounds converts stripped inbound descriptors into +// InboundHandlerConfig entries. The receiver settings carry the sniffing +// block so the proxyman builds the same sniffing context it would for a +// native inbound; there is no port because the device is the input. +func buildCustomInbounds(customs []customInboundJSON) ([]*xray_core.InboundHandlerConfig, error) { + result := make([]*xray_core.InboundHandlerConfig, 0, len(customs)) + for _, c := range customs { + receiver := &xray_proxyman.ReceiverConfig{} + if c.Sniffing != nil { + sniffing, err := c.Sniffing.Build() + if err != nil { + return nil, errors.New("invalid sniffing settings for tag ", c.Tag).Base(err) + } + receiver.SniffingSettings = sniffing + } + var proxySettings *serial.TypedMessage + switch c.Protocol { + case "tun-mips": + var raw hint_tunmips.ConfigJSON + if len(c.Settings) == 0 { + return nil, errors.New("tun-mips inbound (tag ", c.Tag, ") has no settings") + } + if err := json.Unmarshal(c.Settings, &raw); err != nil { + return nil, errors.New("invalid tun-mips settings for tag ", c.Tag).Base(err) + } + cfg, err := raw.Build() + if err != nil { + return nil, errors.New("invalid tun-mips settings for tag ", c.Tag).Base(err) + } + proxySettings = serial.ToTypedMessage(cfg) + default: + return nil, errors.New("unknown custom inbound protocol ", c.Protocol) + } + result = append(result, &xray_core.InboundHandlerConfig{ + Tag: c.Tag, + ReceiverSettings: serial.ToTypedMessage(receiver), + ProxySettings: proxySettings, + }) + } + return result, nil +} + +// appendCustom adds the stripped descriptors to a built core config. +func appendCustom(coreConfig *xray_core.Config, custom *customConfig) error { + if custom.empty() { + return nil + } + if len(custom.outbounds) > 0 { + customOutbounds, err := buildCustomOutbounds(custom.outbounds) + if err != nil { + return err + } + coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...) + } + if len(custom.inbounds) > 0 { + customInbounds, err := buildCustomInbounds(custom.inbounds) + if err != nil { + return err + } + coreConfig.Inbound = append(coreConfig.Inbound, customInbounds...) + } + return nil +} + // buildCustomOutbounds converts stripped custom outbound JSON descriptors into // xray OutboundHandlerConfig proto messages ready to append to coreConfig.Outbound. func buildCustomOutbounds(customs []customOutboundJSON) ([]*xray_core.OutboundHandlerConfig, error) { @@ -381,7 +523,7 @@ func injectCompatService(coreConfig *xray_core.Config) { // also extracts the extendedJSON fields (e.g. multiObservatory). // Custom-protocol outbounds (anytls, juicity) are stripped from the JSON // before xray processes it, and returned separately. -func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, []customOutboundJSON, error) { +func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, *customConfig, error) { r, err := confloader.LoadConfig(arg) if err != nil { return nil, nil, nil, errors.New("failed to read config: ", arg).Base(err) @@ -390,9 +532,9 @@ func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, []customOutbou if err != nil { return nil, nil, nil, errors.New("failed to read config bytes: ", arg).Base(err) } - modified, customs, err := stripCustomOutbounds(raw) + modified, customs, err := stripCustom(raw) if err != nil { - return nil, nil, nil, errors.New("failed to strip custom outbounds: ", arg).Base(err) + return nil, nil, nil, errors.New("failed to strip custom protocols: ", arg).Base(err) } c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified)) if err != nil { @@ -410,7 +552,7 @@ func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, []customOutbou func buildConfigFromFiles(files []*xray_core.ConfigSource) (*xray_core.Config, error) { cf := &xray_conf.Config{} var ext *extendedJSON - var allCustoms []customOutboundJSON + allCustoms := &customConfig{} for i, file := range files { errors.LogInfo(context.Background(), "v2raya-core: reading config: ", file) @@ -423,12 +565,12 @@ func buildConfigFromFiles(files []*xray_core.ConfigSource) (*xray_core.Config, e return nil, errors.New("failed to read config bytes: ", file).Base(err) } - // Strip custom outbounds before passing to xray. - modified, customs, err := stripCustomOutbounds(raw) + // Strip custom protocols before passing to xray. + modified, customs, err := stripCustom(raw) if err != nil { - return nil, errors.New("failed to strip custom outbounds: ", file).Base(err) + return nil, errors.New("failed to strip custom protocols: ", file).Base(err) } - allCustoms = append(allCustoms, customs...) + allCustoms.merge(customs) c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified)) if err != nil { @@ -458,12 +600,8 @@ func buildConfigFromFiles(files []*xray_core.ConfigSource) (*xray_core.Config, e } injectCompatService(coreConfig) reorderAppsForAPIReadiness(coreConfig) - if len(allCustoms) > 0 { - customOutbounds, err := buildCustomOutbounds(allCustoms) - if err != nil { - return nil, err - } - coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...) + if err := appendCustom(coreConfig, allCustoms); err != nil { + return nil, err } return coreConfig, nil } @@ -479,7 +617,7 @@ func init() { Extension: []string{"json"}, Loader: func(input interface{}) (*xray_core.Config, error) { var ext *extendedJSON - var allCustoms []customOutboundJSON + allCustoms := &customConfig{} switch v := input.(type) { case cmdarg.Arg: @@ -499,7 +637,7 @@ func init() { if e != nil && (e.MultiObservatory != nil || e.BurstObservatory != nil) { ext = e } - allCustoms = append(allCustoms, customs...) + allCustoms.merge(customs) } coreConfig, err := cf.Build() if err != nil { @@ -512,12 +650,8 @@ func init() { } injectCompatService(coreConfig) reorderAppsForAPIReadiness(coreConfig) - if len(allCustoms) > 0 { - customOutbounds, err := buildCustomOutbounds(allCustoms) - if err != nil { - return nil, err - } - coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...) + if err := appendCustom(coreConfig, allCustoms); err != nil { + return nil, err } return coreConfig, nil @@ -526,9 +660,9 @@ func init() { if err != nil { return nil, errors.New("failed to read config reader").Base(err) } - modified, customs, err := stripCustomOutbounds(raw) + modified, customs, err := stripCustom(raw) if err != nil { - return nil, errors.New("failed to strip custom outbounds").Base(err) + return nil, errors.New("failed to strip custom protocols").Base(err) } c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified)) if err != nil { @@ -547,12 +681,8 @@ func init() { } injectCompatService(coreConfig) reorderAppsForAPIReadiness(coreConfig) - if len(customs) > 0 { - customOutbounds, err := buildCustomOutbounds(customs) - if err != nil { - return nil, err - } - coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...) + if err := appendCustom(coreConfig, customs); err != nil { + return nil, err } return coreConfig, nil diff --git a/core/hint/conf/loader_test.go b/core/hint/conf/loader_test.go new file mode 100644 index 00000000..2eb58074 --- /dev/null +++ b/core/hint/conf/loader_test.go @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: MPL-2.0 +package conf + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + hint_tunmips "github.com/v2rayA/v2raya-core/hint/proxy/tunmips" + xray_proxyman "github.com/xtls/xray-core/app/proxyman" + xray_core "github.com/xtls/xray-core/core" + _ "github.com/xtls/xray-core/main/confloader/external" +) + +const tunMipsDoc = `{ + "inbounds": [ + {"port": 20170, "protocol": "socks", "listen": "127.0.0.1", "settings": {"udp": true}, "tag": "socks"}, + { + "protocol": "tun-mips", + "tag": "transparent", + "sniffing": {"enabled": true, "destOverride": ["http", "tls", "quic"], "routeOnly": false}, + "settings": { + "name": "tun0", + "mtu": 1500, + "address4": "10.0.85.2/30", + "address6": "%s", + "dnsTarget": "127.0.0.1:52353", + "excludeProcesses": ["curl", "v2raya"], + "selfPids": [4242] + } + } + ], + "outbounds": [ + {"protocol": "freedom", "tag": "direct"} + ] +}` + +func tunMipsJSON(address6 string) []byte { + return []byte(strings.Replace(tunMipsDoc, "%s", address6, 1)) +} + +// loadBothWays runs the document through the file builder and the reader +// loader, the two production entry points, and checks they agree. +func loadBothWays(t *testing.T, raw []byte) *xray_core.Config { + t.Helper() + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, raw, 0o600); err != nil { + t.Fatal(err) + } + fromFile, err := buildConfigFromFiles([]*xray_core.ConfigSource{{Name: path, Format: "json"}}) + if err != nil { + t.Fatalf("buildConfigFromFiles: %v", err) + } + fromReader, err := xray_core.LoadConfig("json", bytes.NewReader(raw)) + if err != nil { + t.Fatalf("LoadConfig(reader): %v", err) + } + if len(fromFile.Inbound) != len(fromReader.Inbound) || len(fromFile.Outbound) != len(fromReader.Outbound) { + t.Fatalf("file and reader paths disagree: %d/%d inbounds, %d/%d outbounds", + len(fromFile.Inbound), len(fromReader.Inbound), len(fromFile.Outbound), len(fromReader.Outbound)) + } + return fromFile +} + +func findInbound(t *testing.T, cfg *xray_core.Config, tag string) *xray_core.InboundHandlerConfig { + t.Helper() + for _, ib := range cfg.Inbound { + if ib.Tag == tag { + return ib + } + } + t.Fatalf("no inbound tagged %q among %d", tag, len(cfg.Inbound)) + return nil +} + +func TestTunMipsInboundIsBuilt(t *testing.T) { + for _, address6 := range []string{"fdfe:dcba:9876::2/126", ""} { + t.Run("address6="+address6, func(t *testing.T) { + cfg := loadBothWays(t, tunMipsJSON(address6)) + if len(cfg.Inbound) != 2 { + t.Fatalf("%d inbounds, want the socks one and tun-mips", len(cfg.Inbound)) + } + // The native inbound went through xray untouched. + findInbound(t, cfg, "socks") + + ib := findInbound(t, cfg, "transparent") + proxy, err := ib.ProxySettings.GetInstance() + if err != nil { + t.Fatal(err) + } + tc, ok := proxy.(*hint_tunmips.Config) + if !ok { + t.Fatalf("proxy settings are %T", proxy) + } + if tc.Name != "tun0" || tc.Mtu != 1500 || tc.Address4 != "10.0.85.2/30" || tc.Address6 != address6 || + tc.DnsTarget != "127.0.0.1:52353" || len(tc.ExcludeProcesses) != 2 || len(tc.SelfPids) != 1 || tc.SelfPids[0] != 4242 { + t.Fatalf("config %+v", tc) + } + + receiver, err := ib.ReceiverSettings.GetInstance() + if err != nil { + t.Fatal(err) + } + rc := receiver.(*xray_proxyman.ReceiverConfig) + if rc.SniffingSettings == nil || !rc.SniffingSettings.Enabled || len(rc.SniffingSettings.DestinationOverride) != 3 { + t.Fatalf("sniffing settings %+v", rc.SniffingSettings) + } + if rc.PortList != nil { + t.Fatalf("tun-mips inbound must not listen, got ports %+v", rc.PortList) + } + }) + } +} + +func TestWrongDirectionIsRejectedNotDropped(t *testing.T) { + for _, tc := range []struct{ name, doc, want string }{ + {"tun-mips as outbound", + `{"outbounds": [{"protocol": "freedom", "tag": "direct"}, {"protocol": "tun-mips", "tag": "oops", "settings": {}}]}`, + "not valid as outbound"}, + {"anytls as inbound", + `{"inbounds": [{"protocol": "anytls", "tag": "oops", "settings": {}}]}`, + "not valid as inbound"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, err := stripCustom([]byte(tc.doc)) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want %q", err, tc.want) + } + if _, err := xray_core.LoadConfig("json", strings.NewReader(tc.doc)); err == nil { + t.Fatal("LoadConfig accepted a protocol in the wrong direction") + } + }) + } +} + +func TestTunMipsMissingRequiredFieldFails(t *testing.T) { + doc := strings.Replace(string(tunMipsJSON("")), `"dnsTarget": "127.0.0.1:52353",`, "", 1) + _, err := xray_core.LoadConfig("json", strings.NewReader(doc)) + if err == nil || !strings.Contains(err.Error(), "dnsTarget") { + t.Fatalf("err = %v, want a dnsTarget complaint", err) + } +} + +// TestDocumentWithoutCustomProtocolsIsUntouched is the behaviour-neutrality +// check for configurations the service generates today. +func TestDocumentWithoutCustomProtocolsIsUntouched(t *testing.T) { + raw := []byte(`{"inbounds": [{"port": 20170, "protocol": "socks", "tag": "socks"}], "outbounds": [{"protocol": "freedom", "tag": "direct"}]}`) + modified, custom, err := stripCustom(raw) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(modified, raw) || !custom.empty() { + t.Fatalf("document was rewritten: %s", modified) + } +} diff --git a/core/hint/proxy/tunmips/config.pb.go b/core/hint/proxy/tunmips/config.pb.go new file mode 100644 index 00000000..5b6984a4 --- /dev/null +++ b/core/hint/proxy/tunmips/config.pb.go @@ -0,0 +1,208 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.34.2 +// source: config.proto + +package tunmips + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +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) +) + +// Config is the "tun-mips" inbound: a TUN device the core owns, driven by a +// user-space IP stack. The service side manages routes; the core creates +// the device and assigns its addresses. +type Config struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Interface name. On macOS "utun" lets the kernel pick the unit. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Mtu uint32 `protobuf:"varint,2,opt,name=mtu,proto3" json:"mtu,omitempty"` + // Operating-system side IPv4 address with prefix, e.g. "10.0.85.2/30". + Address4 string `protobuf:"bytes,3,opt,name=address4,proto3" json:"address4,omitempty"` + // Optional IPv6 address with prefix; empty disables IPv6 on the device. + Address6 string `protobuf:"bytes,4,opt,name=address6,proto3" json:"address6,omitempty"` + // host:port of the core's DNS module; port-53 flows to non-local + // resolvers are relayed there. + DnsTarget string `protobuf:"bytes,5,opt,name=dns_target,json=dnsTarget,proto3" json:"dns_target,omitempty"` + // Executable basenames whose flows bypass the proxy. + ExcludeProcesses []string `protobuf:"bytes,6,rep,name=exclude_processes,json=excludeProcesses,proto3" json:"exclude_processes,omitempty"` + // PIDs whose flows always bypass the proxy (v2rayA and the core itself). + SelfPids []uint32 `protobuf:"varint,7,rep,packed,name=self_pids,json=selfPids,proto3" json:"self_pids,omitempty"` + // Outbound tag used for excluded flows; "direct" when empty. + DirectTag string `protobuf:"bytes,8,opt,name=direct_tag,json=directTag,proto3" json:"direct_tag,omitempty"` + UserLevel uint32 `protobuf:"varint,9,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Config) Reset() { + *x = Config{} + mi := &file_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_config_proto_msgTypes[0] + if 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_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) GetAddress4() string { + if x != nil { + return x.Address4 + } + return "" +} + +func (x *Config) GetAddress6() string { + if x != nil { + return x.Address6 + } + return "" +} + +func (x *Config) GetDnsTarget() string { + if x != nil { + return x.DnsTarget + } + return "" +} + +func (x *Config) GetExcludeProcesses() []string { + if x != nil { + return x.ExcludeProcesses + } + return nil +} + +func (x *Config) GetSelfPids() []uint32 { + if x != nil { + return x.SelfPids + } + return nil +} + +func (x *Config) GetDirectTag() string { + if x != nil { + return x.DirectTag + } + return "" +} + +func (x *Config) GetUserLevel() uint32 { + if x != nil { + return x.UserLevel + } + return 0 +} + +var File_config_proto protoreflect.FileDescriptor + +const file_config_proto_rawDesc = "" + + "\n" + + "\fconfig.proto\x12\x14v2raya.proxy.tunmips\"\x8d\x02\n" + + "\x06Config\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" + + "\x03mtu\x18\x02 \x01(\rR\x03mtu\x12\x1a\n" + + "\baddress4\x18\x03 \x01(\tR\baddress4\x12\x1a\n" + + "\baddress6\x18\x04 \x01(\tR\baddress6\x12\x1d\n" + + "\n" + + "dns_target\x18\x05 \x01(\tR\tdnsTarget\x12+\n" + + "\x11exclude_processes\x18\x06 \x03(\tR\x10excludeProcesses\x12\x1b\n" + + "\tself_pids\x18\a \x03(\rR\bselfPids\x12\x1d\n" + + "\n" + + "direct_tag\x18\b \x01(\tR\tdirectTag\x12\x1d\n" + + "\n" + + "user_level\x18\t \x01(\rR\tuserLevelB2Z0github.com/v2rayA/v2raya-core/hint/proxy/tunmipsb\x06proto3" + +var ( + file_config_proto_rawDescOnce sync.Once + file_config_proto_rawDescData []byte +) + +func file_config_proto_rawDescGZIP() []byte { + file_config_proto_rawDescOnce.Do(func() { + file_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_config_proto_rawDesc), len(file_config_proto_rawDesc))) + }) + return file_config_proto_rawDescData +} + +var file_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_config_proto_goTypes = []any{ + (*Config)(nil), // 0: v2raya.proxy.tunmips.Config +} +var file_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_config_proto_init() } +func file_config_proto_init() { + if File_config_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_config_proto_rawDesc), len(file_config_proto_rawDesc)), + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_config_proto_goTypes, + DependencyIndexes: file_config_proto_depIdxs, + MessageInfos: file_config_proto_msgTypes, + }.Build() + File_config_proto = out.File + file_config_proto_goTypes = nil + file_config_proto_depIdxs = nil +} diff --git a/core/hint/proxy/tunmips/config.proto b/core/hint/proxy/tunmips/config.proto new file mode 100644 index 00000000..a448cb4f --- /dev/null +++ b/core/hint/proxy/tunmips/config.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package v2raya.proxy.tunmips; +option go_package = "github.com/v2rayA/v2raya-core/hint/proxy/tunmips"; + +// Config is the "tun-mips" inbound: a TUN device the core owns, driven by a +// user-space IP stack. The service side manages routes; the core creates +// the device and assigns its addresses. +message Config { + // Interface name. On macOS "utun" lets the kernel pick the unit. + string name = 1; + uint32 mtu = 2; + // Operating-system side IPv4 address with prefix, e.g. "10.0.85.2/30". + string address4 = 3; + // Optional IPv6 address with prefix; empty disables IPv6 on the device. + string address6 = 4; + // host:port of the core's DNS module; port-53 flows to non-local + // resolvers are relayed there. + string dns_target = 5; + // Executable basenames whose flows bypass the proxy. + repeated string exclude_processes = 6; + // PIDs whose flows always bypass the proxy (v2rayA and the core itself). + repeated uint32 self_pids = 7; + // Outbound tag used for excluded flows; "direct" when empty. + string direct_tag = 8; + uint32 user_level = 9; +} diff --git a/core/hint/proxy/tunmips/config_json.go b/core/hint/proxy/tunmips/config_json.go new file mode 100644 index 00000000..c0441673 --- /dev/null +++ b/core/hint/proxy/tunmips/config_json.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MPL-2.0 +package tunmips + +import ( + "errors" + "net/netip" +) + +// ConfigJSON is the "settings" object of a tun-mips inbound as the service +// writes it. Required fields are checked here so a missing one fails to +// load instead of silently becoming a zero value; the optional ones default +// to "no IPv6", "no exclusions" and "direct". +type ConfigJSON struct { + Name string `json:"name"` + MTU uint32 `json:"mtu"` + Address4 string `json:"address4"` + Address6 string `json:"address6"` + DnsTarget string `json:"dnsTarget"` + ExcludeProcesses []string `json:"excludeProcesses"` + SelfPids []uint32 `json:"selfPids"` + DirectTag string `json:"directTag"` + UserLevel uint32 `json:"userLevel"` +} + +// Build validates and converts to the proto Config. +func (c *ConfigJSON) Build() (*Config, error) { + if c.Name == "" { + return nil, errors.New("tun-mips: name is required") + } + if c.MTU == 0 { + return nil, errors.New("tun-mips: mtu is required") + } + if p, err := netip.ParsePrefix(c.Address4); err != nil || !p.Addr().Is4() { + return nil, errors.New("tun-mips: address4 must be an IPv4 prefix such as 10.0.85.2/30") + } + if c.Address6 != "" { + if p, err := netip.ParsePrefix(c.Address6); err != nil || !p.Addr().Is6() { + return nil, errors.New("tun-mips: address6 must be an IPv6 prefix or empty") + } + } + if _, err := netip.ParseAddrPort(c.DnsTarget); err != nil { + return nil, errors.New("tun-mips: dnsTarget must be host:port") + } + return &Config{ + Name: c.Name, + Mtu: c.MTU, + Address4: c.Address4, + Address6: c.Address6, + DnsTarget: c.DnsTarget, + ExcludeProcesses: c.ExcludeProcesses, + SelfPids: c.SelfPids, + DirectTag: c.DirectTag, + UserLevel: c.UserLevel, + }, nil +} diff --git a/core/hint/proxy/tunmips/inbound.go b/core/hint/proxy/tunmips/inbound.go new file mode 100644 index 00000000..5e72392b --- /dev/null +++ b/core/hint/proxy/tunmips/inbound.go @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MPL-2.0 +package tunmips + +import ( + "context" + "fmt" + "net/netip" + "os" + "sync" + + "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" + "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/session" + "github.com/xtls/xray-core/core" + "github.com/xtls/xray-core/features/policy" + "github.com/xtls/xray-core/features/routing" + "github.com/xtls/xray-core/features/stats" + "github.com/xtls/xray-core/transport/internet/stat" + "golang.zx2c4.com/wireguard/tun" +) + +// Handler is the "tun-mips" inbound. Like xray's tun inbound it listens on +// no port: its input is the device it opens in Start. +type Handler struct { + ctx context.Context + config *Config + tag string + sniff session.SniffingRequest + pm policy.Manager + dsp routing.Dispatcher + addr4 netip.Prefix + addr6 netip.Prefix + uplink stats.Counter + downlnk stats.Counter + + mu sync.Mutex + dev tun.Device + stack *mipsStack + fwd *forwarder +} + +func newHandler(ctx context.Context, config *Config) (*Handler, error) { + h := &Handler{ctx: ctx, config: config} + if config.Name == "" { + return nil, errors.New("tun-mips: name is required") + } + if config.Mtu == 0 { + return nil, errors.New("tun-mips: mtu is required") + } + var err error + if h.addr4, err = netip.ParsePrefix(config.Address4); err != nil || !h.addr4.Addr().Is4() { + return nil, errors.New("tun-mips: address4 must be an IPv4 prefix, got ", fmt.Sprintf("%q", config.Address4)) + } + if config.Address6 != "" { + if h.addr6, err = netip.ParsePrefix(config.Address6); err != nil || !h.addr6.Addr().Is6() { + return nil, errors.New("tun-mips: address6 must be an IPv6 prefix, got ", fmt.Sprintf("%q", config.Address6)) + } + } + if config.DnsTarget == "" { + return nil, errors.New("tun-mips: dnsTarget is required") + } + if _, err := netip.ParseAddrPort(config.DnsTarget); err != nil { + return nil, errors.New("tun-mips: dnsTarget must be host:port, got ", fmt.Sprintf("%q", config.DnsTarget)) + } + return h, nil +} + +// Init receives the tag and sniffing request the proxyman set in ctx. +func (h *Handler) Init(ctx context.Context, pm policy.Manager, dsp routing.Dispatcher) error { + if inbound := session.InboundFromContext(ctx); inbound != nil { + h.tag = inbound.Tag + } + if content := session.ContentFromContext(ctx); content != nil { + h.sniff = content.SniffingRequest + } + h.ctx = core.ToBackgroundDetachedContext(ctx) + h.pm, h.dsp = pm, dsp + if h.tag != "" { + if sm, ok := core.MustFromContext(ctx).GetFeature(stats.ManagerType()).(stats.Manager); ok { + if pm.ForSystem().Stats.InboundUplink { + h.uplink, _ = sm.GetOrRegisterCounter("inbound>>>" + h.tag + ">>>traffic>>>uplink") + } + if pm.ForSystem().Stats.InboundDownlink { + h.downlnk, _ = sm.GetOrRegisterCounter("inbound>>>" + h.tag + ">>>traffic>>>downlink") + } + } + } + return nil +} + +// Start opens the device, assigns its addresses and starts the stack. +func (h *Handler) Start() error { + h.mu.Lock() + defer h.mu.Unlock() + dev, err := openDevice(h.config.Name, h.config.Mtu, h.addr4, h.addr6) + if err != nil { + return err + } + name, _ := dev.Name() + + fwd := newForwarder(h.ctx, h.dsp) + fwd.tag = h.tag + fwd.sniffing = h.sniff + fwd.userLevel = h.config.UserLevel + fwd.uplink, fwd.downlink = h.uplink, h.downlnk + fwd.dns = newDNSHijack(h.config.DnsTarget) + selfPids := append([]uint32{uint32(os.Getpid())}, h.config.SelfPids...) + fwd.excl = newExclusion(h.config.ExcludeProcesses, selfPids) + fwd.directTag = h.config.DirectTag + if fwd.directTag == "" { + fwd.directTag = "direct" + } + + stack := newMipsStack(h.config.Mtu) + if err := stack.Start(dev, fwd.handlers()); err != nil { + dev.Close() + return errors.New("tun-mips: start stack on ", name).Base(err) + } + h.dev, h.stack, h.fwd = dev, stack, fwd + errors.LogInfo(h.ctx, "tun-mips: ", name, " up, ", h.addr4, " ", h.config.Address6) + go h.watch(name, stack, dev) + return nil +} + +// watch reports a pump failure and closes the device. The core keeps +// running, as with xray's tun inbound; the service's connectivity monitor +// sees the device disappear and pauses the transparent proxy. +func (h *Handler) watch(name string, stack *mipsStack, dev tun.Device) { + <-stack.done + if err := stack.Err(); err != nil { + errors.LogError(h.ctx, "tun-mips: ", name, " stopped: ", err) + } + dev.Close() +} + +func (h *Handler) Close() error { + h.mu.Lock() + defer h.mu.Unlock() + if h.fwd != nil && h.fwd.dns != nil { + h.fwd.dns.close() + } + if h.stack != nil { + h.stack.Close() + } + if h.dev != nil { + h.dev.Close() + } + h.dev, h.stack, h.fwd = nil, nil, nil + return nil +} + +// Network declares no listening network: the proxyman opens no port. +func (h *Handler) Network() []net.Network { return []net.Network{} } + +// Process is never called because nothing listens. +func (h *Handler) Process(context.Context, net.Network, stat.Connection, routing.Dispatcher) error { + return nil +} + +var _ common.Runnable = (*Handler)(nil) + +func init() { + common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { + h, err := newHandler(ctx, config.(*Config)) + if err != nil { + return nil, err + } + err = core.RequireFeatures(ctx, func(pm policy.Manager, dsp routing.Dispatcher) error { + return h.Init(ctx, pm, dsp) + }) + return h, err + })) +} diff --git a/core/main/distro/all/all.go b/core/main/distro/all/all.go index 301b642e..61f2a09a 100644 --- a/core/main/distro/all/all.go +++ b/core/main/distro/all/all.go @@ -89,9 +89,11 @@ import ( // (replaces github.com/xtls/xray-core/main/json) // - hint/proxy/anytls: native anytls outbound protocol handler // - hint/proxy/juicity: native juicity outbound protocol handler + // - hint/proxy/tunmips: in-core TUN inbound (tun-mips) _ "github.com/v2rayA/v2raya-core/hint/app/observatory/command" _ "github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory" _ "github.com/v2rayA/v2raya-core/hint/conf" _ "github.com/v2rayA/v2raya-core/hint/proxy/anytls" _ "github.com/v2rayA/v2raya-core/hint/proxy/juicity" + _ "github.com/v2rayA/v2raya-core/hint/proxy/tunmips" )