package bridge import ( "encoding/json" "errors" "fmt" "net/netip" "net/url" "os" "sort" "strings" ) // Only node fields may be imported. Route, DNS and TUN ownership remain managed. type Rule struct { Type string `json:"type"` Value string `json:"value"` Action string `json:"action"` } type MeshDNS struct { Suffix string `json:"suffix"` Server string `json:"server"` } type TunConfig struct { FD int `json:"fd"` Name string `json:"name"` Interface string `json:"physical_interface"` Index int `json:"physical_index"` } type RuleSet struct { Tag string `json:"tag"` Enabled bool `json:"enabled"` URL string `json:"url,omitempty"` Format string `json:"format,omitempty"` Rules []map[string]any `json:"rules,omitempty"` Action string `json:"action"` DownloadDetour string `json:"download_detour,omitempty"` UpdateHours int `json:"update_hours,omitempty"` } type Config struct { DNSProtection bool `json:"dns_protection,omitempty"` RuleSets []RuleSet `json:"rule_sets,omitempty"` DirectDNS string `json:"direct_dns_server,omitempty"` ListenPort uint16 `json:"listen_port"` MeshSOCKS string `json:"mesh_socks"` MeshCIDRs []string `json:"mesh_cidrs"` ProtectedCIDRs []string `json:"protected_cidrs,omitempty"` Feature string `json:"feature,omitempty"` Mode string `json:"mode,omitempty"` Proxy map[string]any `json:"proxy,omitempty"` Rules []Rule `json:"rules,omitempty"` DefaultAction string `json:"default_action,omitempty"` DNS string `json:"dns_server,omitempty"` ProxyDNS string `json:"proxy_dns_server,omitempty"` MeshDNS []MeshDNS `json:"mesh_dns,omitempty"` FakeIP bool `json:"fakeip,omitempty"` FakeIPExclude []string `json:"fakeip_exclude,omitempty"` DesktopTun bool `json:"desktop_tun,omitempty"` PhysicalInterface string `json:"physical_interface,omitempty"` Tun *TunConfig `json:"tun,omitempty"` } // Diagnostics are restricted to the privileged, mesh-only local fixture. They // cannot enable logging of a user's ordinary proxy nodes or network traffic. func (c Config) selfTestTrace() bool { if os.Getenv("MESHPORT_SELF_TEST_TRACE") != "1" || os.Geteuid() != 0 || !c.DesktopTun || c.Feature != "mesh" || c.Proxy != nil || len(c.MeshCIDRs) == 0 { return false } fixture := netip.MustParsePrefix("10.253.88.0/24") for _, value := range append(append([]string{}, c.MeshCIDRs...), c.ProtectedCIDRs...) { prefix, err := netip.ParsePrefix(value) if err != nil || prefix.Bits() < fixture.Bits() || !fixture.Contains(prefix.Addr()) { return false } } return true } func prefixes(values []string) ([]string, error) { if len(values) > 128 { return nil, errors.New("too many mesh prefixes") } set := map[string]bool{} for _, v := range values { p, e := netip.ParsePrefix(v) if e != nil || !p.Addr().Is4() || p.Bits() < 16 || !p.Addr().IsPrivate() { return nil, errors.New("invalid or unsupported mesh prefix") } set[p.Masked().String()] = true } result := make([]string, 0, len(set)) for p := range set { result = append(result, p) } sort.Strings(result) return result, nil } func domain(v string) bool { if len(v) > 253 || v == "" || strings.ContainsAny(v, " /:@*\r\n") { return false } for _, label := range strings.Split(v, ".") { if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { return false } for _, c := range label { if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') { return false } } } return true } func proxyNode(node map[string]any) (map[string]any, error) { kind, _ := node["type"].(string) fields := map[string]string{"socks": "version,username,password", "http": "username,password,tls", "shadowsocks": "method,password", "vmess": "uuid,security,alter_id,tls,transport", "vless": "uuid,flow,tls,transport", "trojan": "password,tls,transport"} extra, ok := fields[kind] if !ok { return nil, errors.New("unsupported proxy protocol") } allowed := ",type,server,server_port," + extra + "," result := map[string]any{"tag": "proxy"} for key, value := range node { if !strings.Contains(allowed, ","+key+",") { return nil, errors.New("unsupported proxy node field") } result[key] = value } host, ok := node["server"].(string) if !ok { return nil, errors.New("proxy server required") } if _, err := netip.ParseAddr(host); err != nil && !domain(host) { return nil, errors.New("invalid proxy server") } raw, _ := json.Marshal(node["server_port"]) var port uint16 if json.Unmarshal(raw, &port) != nil || port == 0 { return nil, errors.New("invalid proxy port") } // Nested transport/TLS options are validated by the fixed upstream registry; // they cannot supply route, DNS, dialer or arbitrary outbound configuration. if tls, ok := node["tls"].(map[string]any); ok { for k := range tls { if !strings.Contains(",enabled,server_name,alpn,reality,utls,", ","+k+",") { return nil, errors.New("unsupported TLS option") } } } if tr, ok := node["transport"].(map[string]any); ok { for k := range tr { if !strings.Contains(",type,path,headers,service_name,host,", ","+k+",") { return nil, errors.New("unsupported transport option") } } } return result, nil } func dnsAddress(value string) (string, uint16, error) { if ip, e := netip.ParseAddr(value); e == nil { return ip.String(), 53, nil } if addr, e := netip.ParseAddrPort(value); e == nil && addr.Port() > 0 { return addr.Addr().String(), addr.Port(), nil } return "", 0, errors.New("DNS server must be an IP with optional port") } // Encrypted resolver hostnames use the independent IP bootstrap resolver. func resolver(value, tag, detour string) (map[string]any, error) { result := map[string]any{"tag": tag} if !strings.Contains(value, "://") { host, port, err := dnsAddress(value) if err != nil { return nil, err } result["type"], result["server"], result["server_port"] = "udp", host, port } else { u, err := url.Parse(value) if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Scheme != "https" && u.Scheme != "tls") { return nil, errors.New("invalid encrypted DNS URL") } host := u.Hostname() if _, err := netip.ParseAddr(host); err != nil && !domain(host) { return nil, errors.New("invalid DNS host") } port := uint16(443) kind := "https" if u.Scheme == "tls" { port, kind = 853, "tls" if u.Path != "" && u.Path != "/" { return nil, errors.New("DoT does not accept a path") } } if u.Port() != "" { if _, err := fmt.Sscanf(u.Port(), "%d", &port); err != nil || port == 0 { return nil, errors.New("invalid DNS port") } } result["type"], result["server"], result["server_port"] = kind, host, port result["tls"] = map[string]any{"enabled": true, "server_name": host} if _, err := netip.ParseAddr(host); err != nil { result["domain_resolver"] = map[string]any{"server": "bootstrap"} } if kind == "https" { path := u.EscapedPath() if path == "" { path = "/dns-query" } result["path"] = path } } if detour != "" { result["detour"] = detour } return result, nil } func (c Config) managedJSON() ([]byte, error) { feature := c.Feature if feature == "" { feature = "mesh" } if feature != "mesh" && feature != "proxy" && feature != "combined" { return nil, errors.New("invalid feature") } mesh := feature != "proxy" internet := feature != "mesh" mode := c.Mode if mode == "" { mode = "rule" } if mode != "rule" && mode != "global" && mode != "direct" && mode != "bypass_cn" { return nil, errors.New("invalid proxy mode") } // A managed preset must not inherit custom rules that could override GeoIP. bypassCN := mode == "bypass_cn" if bypassCN { mode = "rule" c.DefaultAction = "proxy" c.Rules = nil c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true, URL: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs", Format: "binary", Action: "direct", DownloadDetour: "proxy", UpdateHours: 24}} } active, err := prefixes(c.MeshCIDRs) if err != nil { return nil, err } protected, err := prefixes(c.ProtectedCIDRs) if err != nil { return nil, err } if c.ListenPort == 0 { return nil, errors.New("listen port required") } outbounds := []any{} if mesh { endpoint, e := netip.ParseAddrPort(c.MeshSOCKS) if e != nil || !endpoint.Addr().Is4() || !endpoint.Addr().IsLoopback() || endpoint.Port() == 0 { return nil, errors.New("mesh SOCKS must be an IPv4 loopback endpoint with a port") } if len(active) == 0 && len(protected) == 0 { return nil, errors.New("effective mesh prefixes required") } meshOutbound := map[string]any{"type": "socks", "tag": "meshport", "server": endpoint.Addr().String(), "server_port": endpoint.Port(), "version": "5", "udp_over_tcp": false} // The Rust bridge is local. The internet default_interface must not // bind this loopback connection to a physical network adapter. if c.DesktopTun { meshOutbound["bind_interface"] = "lo0" } outbounds = append(outbounds, meshOutbound) } if internet { outbounds = append(outbounds, map[string]any{"type": "direct", "tag": "direct"}) if c.Proxy != nil { node, e := proxyNode(c.Proxy) if e != nil { return nil, e } // Only the proxy endpoint may bootstrap outside the proxy. node["domain_resolver"] = map[string]any{"server": "bootstrap"} outbounds = append(outbounds, node) } } action := c.DefaultAction if action == "" { action = "proxy" } if action != "proxy" && action != "direct" && action != "reject" { return nil, errors.New("invalid default action") } if internet && mode == "global" { action = "proxy" } if internet && mode == "direct" { action = "direct" } routeRules := []any{} dns := map[string]any{} defaultResolver := "bootstrap" if internet { server := c.DNS if server == "" { server = "1.1.1.1" } server, dnsPort, e := dnsAddress(server) if e != nil { return nil, e } dnsServers := []any{map[string]any{"type": "udp", "tag": "bootstrap", "server": server, "server_port": dnsPort}} dnsFinal := "bootstrap" if c.DirectDNS != "" { server, e := resolver(c.DirectDNS, "direct-dns", "") if e != nil { return nil, e } dnsServers = append(dnsServers, server) dnsFinal = "direct-dns" } if c.DNSProtection && mode != "direct" { if c.Proxy == nil { return nil, errors.New("DNS protection requires a selected proxy node; use direct mode for direct-only traffic") } if c.ProxyDNS == "" { return nil, errors.New("DNS protection requires an explicitly configured proxy DNS server") } } if c.ProxyDNS != "" && mode != "direct" { if c.Proxy == nil { return nil, errors.New("proxy DNS requires proxy node") } server, e := resolver(c.ProxyDNS, "proxy-dns", "proxy") if e != nil { return nil, e } dnsServers = append(dnsServers, server) if mode != "direct" { dnsFinal = "proxy-dns" } } dnsRules := []any{} for i, m := range c.MeshDNS { ip, e := netip.ParseAddr(m.Server) activeDNS, knownDNS := false, false for _, v := range active { if netip.MustParsePrefix(v).Contains(ip) { activeDNS = true } } for _, v := range protected { if netip.MustParsePrefix(v).Contains(ip) { knownDNS = true } } if !mesh || !domain(m.Suffix) || e != nil || !(activeDNS || knownDNS) { return nil, errors.New("mesh DNS requires a known mesh server and valid suffix") } if !activeDNS { dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "reject"}) continue } tag := "mesh-dns-" + strings.Repeat("x", i+1) dnsServers = append(dnsServers, map[string]any{"type": "udp", "tag": tag, "server": m.Server, "detour": "meshport"}) dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "route", "server": tag}) } if c.FakeIP { if len(c.FakeIPExclude) > 128 { return nil, errors.New("too many FakeIP exclusions") } excluded := []string{"localhost", "local", "lan"} for _, v := range c.FakeIPExclude { if !domain(v) { return nil, errors.New("invalid FakeIP exclusion") } excluded = append(excluded, v) } dnsRules = append(dnsRules, map[string]any{"domain_suffix": excluded, "action": "route", "server": dnsFinal}) dnsServers = append(dnsServers, map[string]any{"type": "fakeip", "tag": "fakeip", "inet4_range": "198.18.0.0/15", "inet6_range": "fc00::/18"}) dnsRules = append(dnsRules, map[string]any{"query_type": []string{"A", "AAAA"}, "action": "route", "server": "fakeip"}) } defaultResolver = dnsFinal dns = map[string]any{"servers": dnsServers, "rules": dnsRules, "final": dnsFinal, "strategy": "ipv4_only"} routeRules = append(routeRules, map[string]any{"port": 53, "action": "hijack-dns"}, map[string]any{"action": "resolve", "strategy": "ipv4_only"}) } else { routeRules = append(routeRules, map[string]any{"domain_regex": []string{".+"}, "action": "reject"}) } if mesh && internet { for _, rule := range c.MeshDNS { routeRules = append(routeRules, map[string]any{"domain_suffix": []string{rule.Suffix}, "action": "route", "outbound": "meshport"}) } } if mesh && len(active) > 0 { routeRules = append(routeRules, map[string]any{"ip_cidr": active, "action": "route", "outbound": "meshport"}) } if mesh && len(protected) > 0 { routeRules = append(routeRules, map[string]any{"ip_cidr": protected, "action": "reject"}) } if internet && bypassCN { routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"}) } usedProxy := internet && action == "proxy" if internet && mode == "rule" { if len(c.Rules) > 256 { return nil, errors.New("too many rules") } for _, r := range c.Rules { item := map[string]any{} switch r.Type { case "domain", "domain_suffix": if !domain(r.Value) { return nil, errors.New("invalid rule domain") } item[r.Type] = []string{r.Value} case "ip_cidr": p, e := netip.ParsePrefix(r.Value) if e != nil { return nil, errors.New("invalid rule CIDR") } item[r.Type] = []string{p.Masked().String()} default: return nil, errors.New("unsupported rule type") } switch r.Action { case "reject": item["action"] = "reject" case "direct", "proxy": item["action"] = "route" item["outbound"] = r.Action if r.Action == "proxy" { usedProxy = true } default: return nil, errors.New("invalid rule action") } routeRules = append(routeRules, item) } } ruleSets := []any{} if len(c.RuleSets) > 32 { return nil, errors.New("too many rule sets") } tags := map[string]bool{} for _, set := range c.RuleSets { if !set.Enabled || !internet || mode != "rule" { continue } if !domain(set.Tag) || tags[set.Tag] { return nil, errors.New("invalid or duplicate rule set tag") } tags[set.Tag] = true if set.Action != "proxy" && set.Action != "direct" && set.Action != "reject" { return nil, errors.New("invalid rule set action") } item := map[string]any{"tag": set.Tag} if set.URL != "" { u, err := url.Parse(set.URL) if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || len(set.Rules) != 0 { return nil, errors.New("invalid remote rule set URL") } if set.Format != "source" && set.Format != "binary" { return nil, errors.New("invalid rule set format") } hours := set.UpdateHours if hours == 0 { hours = 24 } if hours < 1 || hours > 168 { return nil, errors.New("invalid rule set interval") } detour := set.DownloadDetour if detour == "" { detour = "direct" } if detour != "proxy" && detour != "direct" { return nil, errors.New("invalid rule set download detour") } if detour == "proxy" && c.Proxy == nil { return nil, errors.New("rule set download requires proxy") } item["type"], item["format"], item["url"] = "remote", set.Format, set.URL item["update_interval"], item["download_detour"] = fmt.Sprintf("%dh", hours), detour } else { if len(set.Rules) == 0 || len(set.Rules) > 256 { return nil, errors.New("invalid inline rule set") } item["type"], item["rules"] = "inline", set.Rules } if internet && mode == "rule" { ruleSets = append(ruleSets, item) match := map[string]any{"rule_set": []string{set.Tag}, "action": "route", "outbound": set.Action} if set.Action == "reject" { delete(match, "outbound") match["action"] = "reject" } if set.Action == "proxy" { usedProxy = true } routeRules = append(routeRules, match) } } if usedProxy && c.Proxy == nil { return nil, errors.New("selected proxy node required") } final := "meshport" if internet && action != "reject" { final = action } else { routeRules = append(routeRules, map[string]any{"action": "reject"}) if internet { final = "direct" } } if c.FakeIP && !internet { return nil, errors.New("FakeIP requires ordinary proxy feature") } inbounds := []any{map[string]any{"type": "socks", "tag": "local", "listen": "127.0.0.1", "listen_port": c.ListenPort}} route := map[string]any{"rules": routeRules, "final": final} if len(ruleSets) > 0 { route["rule_set"] = ruleSets } if internet { route["default_domain_resolver"] = map[string]any{"server": defaultResolver} } if c.DesktopTun { if c.Tun != nil || c.PhysicalInterface == "" || strings.ContainsAny(c.PhysicalInterface, " /\\\t\r\n") { return nil, errors.New("desktop TUN requires physical interface") } route["default_interface"] = c.PhysicalInterface routes := []string{"0.0.0.0/1", "128.0.0.0/1", "::/1", "8000::/1"} if !internet { // Active prefixes also belong to the session's protection set. // Duplicate routes make Darwin delete the same entry twice on close, // which breaks subsequent announcement-driven engine restarts. captureSet := make(map[string]bool) for _, prefix := range append(append([]string{}, active...), protected...) { captureSet[prefix] = true } capture := make([]string, 0, len(captureSet)) for prefix := range captureSet { capture = append(capture, prefix) } routes, err = prefixes(capture) if err != nil { return nil, err } } dnsMode := "native" addresses := []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"} if !internet { dnsMode = "disabled" // No accepted IPv6 mesh prefixes exist yet. Giving Darwin an IPv6 // address with auto_route and no IPv6 route_address captures its // IPv6 default route, even in the subnet-only mode. addresses = []string{"172.19.0.1/30"} } inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "address": addresses, "mtu": 1280, "auto_route": true, "route_address": routes, "stack": "system", "dns_mode": dnsMode}) } if c.Tun != nil { if c.Tun.FD <= 0 || c.Tun.Name == "" || c.Tun.Interface == "" || c.Tun.Index <= 0 { return nil, errors.New("valid platform TUN and physical network required") } route["auto_detect_interface"] = true inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "interface_name": c.Tun.Name, "address": []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}, "mtu": 1280, "auto_route": false, "stack": "system", "dns_mode": "disabled"}) } result := map[string]any{"log": map[string]any{"disabled": !c.selfTestTrace(), "level": "debug"}, "inbounds": inbounds, "outbounds": outbounds, "route": route} if internet { result["dns"] = dns } return json.Marshal(result) }