diff --git a/internal/backend/sagernet/backend.go b/internal/backend/sagernet/backend.go index b099842..96fc574 100644 --- a/internal/backend/sagernet/backend.go +++ b/internal/backend/sagernet/backend.go @@ -241,7 +241,10 @@ func (o *Outbound) Close() error { } // DirectSpec dials the destination directly. -type DirectSpec struct{} +type DirectSpec struct { + // DomainStrategy uses the sing-box domain_strategy values. + DomainStrategy string +} // ShadowsocksSpec is a Shadowsocks client. type ShadowsocksSpec struct { @@ -323,7 +326,14 @@ func (b *Backend) NewOutbound(tag string, spec any) (*Outbound, error) { out = newDropOutbound(tag) case DirectSpec: typ = "direct" - out, err = direct.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, option.DirectOutboundOptions{}) + var opts option.DirectOutboundOptions + if s.DomainStrategy != "" { + strategy, _ := json.Marshal(s.DomainStrategy) + if err = opts.DomainStrategy.UnmarshalJSON(strategy); err != nil { + break + } + } + out, err = direct.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, opts) case HTTPSpec: typ = "http" out, err = http.NewOutbound(b.ctx, b.router, b.componentLogger("outbound", typ, tag), tag, option.HTTPOutboundOptions{ diff --git a/internal/config/compile/compile.go b/internal/config/compile/compile.go index 20f227a..81a83f9 100644 --- a/internal/config/compile/compile.go +++ b/internal/config/compile/compile.go @@ -593,26 +593,33 @@ func (c *compiler) outbounds(eff *Effective) { } } for i := range eff.Outbounds { - identity := eff.Outbounds[i] - identity.Name = "" // display metadata must not rebuild a live outbound - if identity.Multiplex != nil { - m := *identity.Multiplex - m.Statistic = false - identity.Multiplex = &m - } - plugin, _ := json.Marshal(identity.Plugin) - params, _ := json.Marshal(identity.Protocol) - transport, _ := json.Marshal(identity.Transport) - headers, _ := json.Marshal(identity.Headers) - tlsSecrets := "" - if identity.TLS != nil { - carrier, _ := json.Marshal(identity.TLS.Carrier) - tlsSecrets = identity.TLS.Certificate + "\x00" + identity.TLS.PrivateKey + "\x00" + string(carrier) - } - eff.Outbounds[i].Fingerprint = fingerprint(identity, identity.Username, identity.Password, identity.UUID, identity.Encryption, string(plugin), string(params), string(transport), string(headers), tlsSecrets) + out := &eff.Outbounds[i] + if out.Dialer == nil || out.Dialer.Proxy == "" { + out.Fingerprint = outboundFingerprint(*out) + } } } +func outboundFingerprint(identity Outbound) string { + identity.Name = "" // display metadata must not rebuild a live outbound + identity.Fingerprint = "" + if identity.Multiplex != nil { + m := *identity.Multiplex + m.Statistic = false + identity.Multiplex = &m + } + plugin, _ := json.Marshal(identity.Plugin) + params, _ := json.Marshal(identity.Protocol) + transport, _ := json.Marshal(identity.Transport) + headers, _ := json.Marshal(identity.Headers) + tlsSecrets := "" + if identity.TLS != nil { + carrier, _ := json.Marshal(identity.TLS.Carrier) + tlsSecrets = identity.TLS.Certificate + "\x00" + identity.TLS.PrivateKey + "\x00" + string(carrier) + } + return fingerprint(identity, identity.Username, identity.Password, identity.UUID, identity.Encryption, string(plugin), string(params), string(transport), string(headers), tlsSecrets) +} + func (c *compiler) hasErrorAt(path string) bool { for _, d := range c.diags { if d.Path == path && d.Severity == model.SeverityError { diff --git a/internal/config/compile/detour.go b/internal/config/compile/detour.go index bf531eb..31bb884 100644 --- a/internal/config/compile/detour.go +++ b/internal/config/compile/detour.go @@ -1,6 +1,7 @@ package compile import ( + "fmt" "slices" "strings" @@ -8,36 +9,47 @@ import ( "github.com/MimoProxy/reka/internal/router" ) -// detours validates the combined outbound/group dependency graph and folds -// every possible parent transport into a child's replacement fingerprint. func (c *compiler) detours(e *Effective) { + for _, o := range e.Outbounds { + if d := o.Dialer; d != nil && d.Proxy != "" && (d.Interface != "" || d.RoutingMark != 0 || d.IPVersion != "" || d.TFO || d.MPTCP) { + c.warnf(model.DocProfile, "/outbounds/"+o.ID+"/dialer", "outbound.detour-options", "dialer proxy uses its parent's physical socket options; set interface, routing mark, IP version, TFO and MPTCP on the parent") + } + } + if !c.diags.HasErrors() { + for _, message := range e.fingerprintDetours() { + c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "%s", message) + } + } +} + +// fingerprintDetours validates the combined outbound/group dependency graph +// and folds every possible parent transport into a child's fingerprint. +func (e *Effective) fingerprintDetours() []string { hasDetour := false nodes := map[string]*Outbound{} - groups := map[string]router.Group{} for i := range e.Outbounds { o := &e.Outbounds[i] nodes[o.ID] = o hasDetour = hasDetour || o.Dialer != nil && o.Dialer.Proxy != "" - if d := o.Dialer; d != nil && d.Proxy != "" && (d.Interface != "" || d.RoutingMark != 0 || d.IPVersion != "" || d.TFO || d.MPTCP) { - c.warnf(model.DocProfile, "/outbounds/"+o.ID+"/dialer", "outbound.detour-options", "dialer proxy uses its parent's physical socket options; set interface, routing mark, IP version, TFO and MPTCP on the parent") - } } - if !hasDetour || c.diags.HasErrors() { - return + if !hasDetour { + return nil } + groups := map[string]router.Group{} for _, g := range e.Groups { groups[g.ID] = g } state := map[string]int{} hashes := map[string]string{} stack := []string{} + var problems []string var visit func(string) string visit = func(id string) string { if state[id] == 2 { return hashes[id] } if state[id] == 1 { - c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "cyclic dialer dependency: %s", strings.Join(append(stack, id), " -> ")) + problems = append(problems, "cyclic dialer dependency: "+strings.Join(append(stack, id), " -> ")) return "" } state[id] = 1 @@ -56,10 +68,10 @@ func (c *compiler) detours(e *Effective) { hashes[id] = o.Fingerprint if o.Dialer != nil && o.Dialer.Proxy != "" { parent := visit(o.Dialer.Proxy) - hashes[id] = fingerprint(o.Fingerprint, parent) + hashes[id] = fingerprint(outboundFingerprint(*o), parent) } } else { - c.errorf(model.DocProfile, "/outbounds", "outbound.detour", "dialer target %q is unavailable", id) + problems = append(problems, fmt.Sprintf("dialer target %q is unavailable", id)) } state[id] = 2 return hashes[id] @@ -69,14 +81,15 @@ func (c *compiler) detours(e *Effective) { visit(o.ID) } } - if c.diags.HasErrors() { - return + if len(problems) > 0 { + return problems } for _, o := range nodes { if o.Dialer != nil && o.Dialer.Proxy != "" { o.Fingerprint = hashes[o.ID] } } + return nil } // DetourLeaves returns the direct possible parents of one detour (all group diff --git a/internal/config/compile/dns.go b/internal/config/compile/dns.go index 02ec3cf..5671096 100644 --- a/internal/config/compile/dns.go +++ b/internal/config/compile/dns.go @@ -131,12 +131,16 @@ func (c *compiler) dns(eff *Effective) { } eff.DNS = cfg eff.DNSMatches = matchers + eff.DNSFingerprint = eff.dnsFingerprint() +} + +func (e *Effective) dnsFingerprint() string { hashes := map[string]string{} - for name, r := range matchers { + for name, r := range e.DNSMatches { hashes[name] = fingerprint(r.Rules().Rule(0)) } - eff.DNSFingerprint = fingerprint(struct { + return fingerprint(struct { Config *RD.Config Matches map[string]string - }{cfg, hashes}) + }{e.DNS, hashes}) } diff --git a/internal/config/compile/ip_version.go b/internal/config/compile/ip_version.go new file mode 100644 index 0000000..f05dc0d --- /dev/null +++ b/internal/config/compile/ip_version.go @@ -0,0 +1,58 @@ +package compile + +import ( + "errors" + "slices" + + "github.com/MimoProxy/reka/internal/config/model" +) + +// WithIPVersion returns a copy with the dialer IP policy and DNS IPv6 setting +// overridden. An empty policy keeps the compiled settings. +func (e *Effective) WithIPVersion(ipVersion string) (*Effective, error) { + eff := *e + switch ipVersion { + case "": + return &eff, nil + case "dual", "ipv4", "ipv6", "ipv4-prefer", "ipv6-prefer": + default: + return nil, errors.New("unknown IP version policy") + } + if e.DNS != nil { + cfg := *e.DNS + cfg.IPv6 = ipVersion != "ipv4" + eff.DNS = &cfg + if cfg.IPv6 != e.DNS.IPv6 { + eff.DNSFingerprint = eff.dnsFingerprint() + } + } + if ipVersion == "dual" { + ipVersion = "" + } + eff.Outbounds = slices.Clone(e.Outbounds) + changed := false + for i := range eff.Outbounds { + out := &eff.Outbounds[i] + switch out.Type { + case model.OutboundReject, "pass", "reject-drop": + continue + } + var dialer model.Dialer + if out.Dialer != nil { + dialer = *out.Dialer + } + if dialer.Proxy != "" || dialer.IPVersion == ipVersion { + continue + } + dialer.IPVersion = ipVersion + out.Dialer = &dialer + out.Fingerprint = outboundFingerprint(*out) + changed = true + } + if changed { + if problems := eff.fingerprintDetours(); len(problems) > 0 { + return nil, errors.New(problems[0]) + } + } + return &eff, nil +} diff --git a/internal/runtime/generation/engine.go b/internal/runtime/generation/engine.go index ec0f882..984fbf6 100644 --- a/internal/runtime/generation/engine.go +++ b/internal/runtime/generation/engine.go @@ -178,8 +178,9 @@ func NewEngine(opts EngineOptions) *Engine { e.opts.Resolver = e.backend.Resolver() } e.rt = runtime.NewValue[*sagernet.Outbound](nil, &generation{historyScope: history.Scope{ProfileID: opts.ProfileID}}, runtime.Options{ - DrainTimeout: opts.DrainTimeout, - MaxRetiring: opts.MaxRetiring, + DrainTimeout: opts.DrainTimeout, + MaxRetiring: opts.MaxRetiring, + AllowLargeReplacement: opts.HostPacketFlow, OnClosed: func(id string, gen uint64, forced int64, err error) { l := slog.Default() if opts.Backend.Logger != nil { @@ -273,10 +274,11 @@ func (e *Engine) plan(eff *compile.Effective) Plan { p.Draining++ } } - if cur := int(e.rt.Stats().Retiring); cur+p.Draining > e.opts.MaxRetiring { - p.Blocked = fmt.Sprintf("%d instances are draining and this change adds %d; the limit is %d", cur, p.Draining, e.opts.MaxRetiring) + retiring := int(e.rt.Stats().Retiring) + if limit := e.rt.RetiringLimit(p.Draining); retiring+p.Draining > limit { + p.Blocked = fmt.Sprintf("%d instances are draining and this change adds %d; the limit is %d", retiring, p.Draining, limit) } - p.Draining += int(e.rt.Stats().Retiring) + p.Draining += retiring for _, ch := range e.listenerChanges(eff.Listeners) { p.Listeners = append(p.Listeners, ch.ResourceChange) @@ -742,6 +744,9 @@ func usesUpstreamOutbound(o compile.Outbound) bool { } func specFor(o compile.Outbound) any { + if o.Builtin && o.Type == model.OutboundDirect { + return sagernet.DirectSpec{DomainStrategy: domainStrategy(o.Dialer)} + } tls := func() *sagernet.TLSSpec { if o.TLS == nil { return nil @@ -1289,12 +1294,23 @@ func (e *Engine) ListenerInstance(id string) any { return nil } +func domainStrategy(dialer *model.Dialer) string { + if dialer == nil { + return "" + } + return map[string]string{ + "ipv4": "ipv4_only", + "ipv6": "ipv6_only", + "ipv4-prefer": "prefer_ipv4", + "ipv6-prefer": "prefer_ipv6", + }[dialer.IPVersion] +} + func protocolOptions(o compile.Outbound) json.RawMessage { values := map[string]any{} if d := o.Dialer; d != nil { values["bind_interface"], values["routing_mark"], values["tcp_fast_open"], values["tcp_multi_path"] = d.Interface, d.RoutingMark, d.TFO, d.MPTCP - strategy := map[string]string{"ipv4": "ipv4_only", "ipv6": "ipv6_only", "ipv4-prefer": "prefer_ipv4", "ipv6-prefer": "prefer_ipv6"}[d.IPVersion] - if strategy != "" { + if strategy := domainStrategy(d); strategy != "" { values["domain_strategy"] = strategy } } diff --git a/internal/runtime/generation/ip_version_test.go b/internal/runtime/generation/ip_version_test.go new file mode 100644 index 0000000..c6ce054 --- /dev/null +++ b/internal/runtime/generation/ip_version_test.go @@ -0,0 +1,89 @@ +package generation + +import ( + "context" + "net" + "net/netip" + "slices" + "testing" + "time" + + "github.com/MimoProxy/reka/internal/backend/sagernet" + "github.com/MimoProxy/reka/internal/config/compile" +) + +func TestDirectOutboundIPVersion(t *testing.T) { + base, diagnostics := compile.Compile([]byte("schema-version: 1\n"), nil, compile.Options{}) + if diagnostics.HasErrors() { + t.Fatal(diagnostics) + } + engine := NewEngine(EngineOptions{}) + defer engine.Close() + + ipv4 := netip.MustParseAddr("127.0.0.1") + ipv6 := netip.IPv6Loopback() + v6Socket, err := net.ListenPacket("udp6", "[::1]:0") + if err == nil { + v6Socket.Close() + } + hasIPv6 := err == nil + for i, tc := range []struct { + policy, strategy string + results []netip.Addr + want netip.Addr + }{ + {"dual", "", []netip.Addr{ipv4}, ipv4}, + {"ipv4", "ipv4_only", []netip.Addr{ipv6}, netip.Addr{}}, + {"ipv6", "ipv6_only", []netip.Addr{ipv4}, netip.Addr{}}, + {"ipv4-prefer", "prefer_ipv4", []netip.Addr{ipv6, ipv4}, ipv4}, + {"ipv6-prefer", "prefer_ipv6", []netip.Addr{ipv4, ipv6}, ipv6}, + } { + t.Run(tc.policy, func(t *testing.T) { + updated, err := base.WithIPVersion(tc.policy) + if err != nil { + t.Fatal(err) + } + direct, _ := updated.Outbound("direct") + if got := specFor(direct); got != (sagernet.DirectSpec{DomainStrategy: tc.strategy}) { + t.Fatalf("direct spec = %+v, want strategy %q", got, tc.strategy) + } + previous := engine.OutboundInstance("direct") + prepared, err := engine.Prepare(updated) + if err != nil { + t.Fatal(err) + } + if _, err := engine.Activate(prepared, uint64(i+1)); err != nil { + t.Fatal(err) + } + outbound := engine.OutboundInstance("direct") + if outbound == nil || outbound == previous { + t.Fatal("direct outbound was not rebuilt") + } + if tc.want.Is6() && !hasIPv6 { + t.Skip("IPv6 loopback unavailable") + } + + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + ctx = sagernet.WithLookup(ctx, func(context.Context, string) ([]netip.Addr, error) { + return slices.Clone(tc.results), nil + }) + conn, err := outbound.Dial(ctx, "udp", "target.test:53") + if conn != nil { + defer conn.Close() + } + if !tc.want.IsValid() { + if err == nil || err.Error() != "no address for target.test" { + t.Fatalf("wrong-family DNS result was not filtered: %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + if got := conn.RemoteAddr().(*net.UDPAddr).AddrPort().Addr().Unmap(); got != tc.want { + t.Fatalf("dialed %s, want %s", got, tc.want) + } + }) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index c53b424..65b5613 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -41,6 +41,9 @@ type Options struct { // MaxRetiring rejects a commit that would leave more resources // draining than this. Zero means no limit. MaxRetiring int + // AllowLargeReplacement applies MaxRetiring to the existing backlog + // when a single replacement batch exceeds that limit. + AllowLargeReplacement bool // OnClosed, if set, is called after each retired resource is closed. // forced is the number of leases still held when it was closed. OnClosed func(id string, generation uint64, forced int64, err error) @@ -139,14 +142,23 @@ func (r *Runtime[R]) CommitValue(next map[string]R, value any) (uint64, error) { return r.commit(next, value, true) } +// RetiringLimit returns the limit for a batch that retires replacing resources. +func (r *Runtime[R]) RetiringLimit(replacing int) int { + limit := r.opts.MaxRetiring + if r.opts.AllowLargeReplacement && limit > 0 && replacing > limit { + limit += replacing + } + return limit +} + // WouldRetire reports how many resources committing next would retire, and -// whether that stays within MaxRetiring. It lets a caller refuse a commit +// whether that stays within the retirement limit. It lets a caller refuse a commit // before doing expensive preparation; Commit checks again. func (r *Runtime[R]) WouldRetire(next map[string]R) (int, bool) { r.commitMu.Lock() defer r.commitMu.Unlock() n := len(r.dropped(r.current.Load(), next)) - max := r.opts.MaxRetiring + max := r.RetiringLimit(n) return n, max <= 0 || int(r.retiring.Load())+n <= max } @@ -185,7 +197,7 @@ func (r *Runtime[R]) commit(next map[string]R, value any, setValue bool) (uint64 if !setValue { value = old.Value } - if max := r.opts.MaxRetiring; max > 0 && int(r.retiring.Load())+len(drop) > max { + if max := r.RetiringLimit(len(drop)); max > 0 && int(r.retiring.Load())+len(drop) > max { return old.Generation, ErrTooManyRetiring } diff --git a/mobile/packettunnel/profile.go b/mobile/packettunnel/profile.go index c174f56..e4a9265 100644 --- a/mobile/packettunnel/profile.go +++ b/mobile/packettunnel/profile.go @@ -22,18 +22,20 @@ import ( const ProfileAddress4 = "172.27.255.1/30" type profileSession struct { - mu sync.Mutex - engine *generation.Engine - base *compile.Effective - summary profile.Summary - rev uint64 - trace *routeTrace - sets map[string]*router.RuleSet + mu sync.Mutex + engine *generation.Engine + base *compile.Effective + summary profile.Summary + rev uint64 + ipVersion string + trace *routeTrace + sets map[string]*router.RuleSet } type ProfileStatus struct { Mode string `json:"mode"` BlockQUIC string `json:"blockQuic,omitempty"` + IPVersion string `json:"ipVersion,omitempty"` Groups []GroupStatus `json:"groups"` Routes []RouteHit `json:"routes,omitempty"` } @@ -185,6 +187,7 @@ func (p *profileSession) publish(base *compile.Effective, summary profile.Summar } p.rev++ p.base, p.summary = base, summary + p.ipVersion = controls.IPVersion return nil } @@ -246,7 +249,12 @@ func (s *Session) ProfileStatus() (*ProfileStatus, error) { return nil, err } eff, _ := p.engine.Effective() - status := &ProfileStatus{Mode: eff.Routing.Mode, BlockQUIC: eff.Routing.BlockQUIC, Groups: make([]GroupStatus, 0, len(eff.Groups))} + status := &ProfileStatus{ + Mode: eff.Routing.Mode, + BlockQUIC: eff.Routing.BlockQUIC, + IPVersion: p.ipVersion, + Groups: make([]GroupStatus, 0, len(eff.Groups)), + } observed := p.engine.GroupStatus() for _, group := range eff.Groups { row := GroupStatus{ID: group.ID, Selected: group.Selected} diff --git a/mobile/packettunnel/session_test.go b/mobile/packettunnel/session_test.go index 491e54a..4ffeffe 100644 --- a/mobile/packettunnel/session_test.go +++ b/mobile/packettunnel/session_test.go @@ -5,16 +5,20 @@ package packettunnel import ( "bytes" "context" + "encoding/json" + "fmt" "io" "net/netip" "os" "path/filepath" "strconv" + "strings" "testing" "time" "github.com/MimoProxy/reka/internal/packettunnellab" "github.com/MimoProxy/reka/internal/router" + "github.com/MimoProxy/reka/internal/runtime/generation" "github.com/MimoProxy/reka/mobile/profile" "github.com/miekg/dns" "github.com/sagernet/gvisor/pkg/buffer" @@ -62,6 +66,111 @@ func TestReplaceProfileKeepsPacketFlowAndRejectsInvalidUpdate(t *testing.T) { } } +func TestApplyIPVersionWhilePacketFlowIsActive(t *testing.T) { + snapshot := prepareSnapshot(t, ` +schema-version: 1 +outbounds: + - {id: node, type: shadowsocks, server: proxy.test, port: 443, method: aes-128-gcm, password: example} + - {id: detoured, type: direct, dialer: {proxy: hop}} +groups: [{id: hop, type: select, members: [node, direct]}] +rules: [{match: {all: true}, outbound: direct}] +dns: {ipv6: true, enhanced-mode: fake-ip, nameserver: [192.0.2.53]} +`) + session, err := StartProfile(snapshot, profile.Controls{}, false) + if err != nil { + t.Fatal(err) + } + defer session.Close() + link, engine := session.tunnel, session.profile.engine + query := new(dns.Msg).SetQuestion("target.test.", dns.TypeAAAA) + check := func(version string, answers int) { + t.Helper() + status, err := session.ProfileStatus() + if err != nil { + t.Fatal(err) + } + if status.IPVersion != version { + t.Fatalf("reported IP version %q, want %q", status.IPVersion, version) + } + data, err := json.Marshal(status) + if err != nil { + t.Fatal(err) + } + if version == "" { + if bytes.Contains(data, []byte(`"ipVersion"`)) { + t.Fatal("status included an empty IP version") + } + } else if !bytes.Contains(data, []byte(`"ipVersion":`+strconv.Quote(version))) { + t.Fatal("status JSON is missing the IP version") + } + response, err := engine.ExchangeDNS(t.Context(), query) + if err != nil { + t.Fatal(err) + } + if response.Rcode != dns.RcodeSuccess || len(response.Answer) != answers { + t.Fatalf("unexpected AAAA response: %v", response) + } + if session.tunnel != link || session.profile.engine != engine { + t.Fatal("controls rebuilt the packet tunnel") + } + } + check("", 1) + direct := engine.OutboundInstance("direct") + node := engine.OutboundInstance("node") + detoured := engine.OutboundInstance("detoured") + var controls profile.Controls + if err := json.Unmarshal([]byte(`{"ipVersion":"ipv4"}`), &controls); err != nil { + t.Fatal(err) + } + if err := session.ApplyControls(controls); err != nil { + t.Fatal(err) + } + check("ipv4", 0) + if direct == engine.OutboundInstance("direct") || node == engine.OutboundInstance("node") || detoured == engine.OutboundInstance("detoured") { + t.Fatal("IP version change did not replace all affected outbounds") + } + detoured = engine.OutboundInstance("detoured") + if err := session.ApplyControls(controls); err != nil { + t.Fatal(err) + } + if detoured != engine.OutboundInstance("detoured") { + t.Fatal("the same IP version did not reuse the detoured outbound") + } + if err := session.ApplyControls(profile.Controls{IPVersion: "invalid"}); err == nil { + t.Fatal("accepted an invalid IP version") + } + check("ipv4", 0) + if err := session.ApplyControls(profile.Controls{}); err != nil { + t.Fatal(err) + } + check("", 1) +} + +func TestApplyIPVersionReplacesLargeProfile(t *testing.T) { + session, err := StartProfile(prepareSnapshot(t, "schema-version: 1\n"), profile.Controls{}, false) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + var input strings.Builder + input.WriteString("schema-version: 1\noutbounds:\n") + for i := range generation.DefaultMaxRetiring { + fmt.Fprintf(&input, " - {id: route-%d, type: direct}\n", i) + } + input.WriteString("rules: [{match: {all: true}, outbound: direct}]\n") + if err := session.ReplaceProfile(prepareSnapshot(t, input.String()), profile.Controls{}); err != nil { + t.Fatal(err) + } + if err := session.ApplyControls(profile.Controls{IPVersion: "ipv4"}); err != nil { + t.Fatal(err) + } + status, err := session.ProfileStatus() + if err != nil || status.IPVersion != "ipv4" { + t.Fatalf("IP version update failed: %+v, %v", status, err) + } +} + func TestPacketFlowOverOneShadowsocksNode(t *testing.T) { peer, err := packettunnellab.Start(netip.MustParseAddr("127.0.0.1"), 0) if err != nil { diff --git a/mobile/profile/bundle.go b/mobile/profile/bundle.go index dd533d6..68bf173 100644 --- a/mobile/profile/bundle.go +++ b/mobile/profile/bundle.go @@ -66,7 +66,9 @@ type Controls struct { Selections map[string]string `json:"selections"` ProfileID string `json:"profileID,omitempty"` // BlockQUIC overrides the profile's routing.block-quic when set. - BlockQUIC string `json:"blockQuic,omitempty"` + BlockQUIC string `json:"blockQuic,omitempty"` + // IPVersion overrides the dialer IP policy and DNS IPv6 setting when set. + IPVersion string `json:"ipVersion,omitempty"` Secrets secret.Store `json:"-"` } @@ -181,10 +183,13 @@ func Describe(eff *compile.Effective) Summary { return summary } -// ApplyControls shares the already-compiled rule index and outbound specs -// across updates. Stable IDs are preferred; old iOS saves used display names. +// ApplyControls shares the compiled rule index across updates. Stable IDs are +// preferred, with display names supported for older iOS saves. func ApplyControls(base *compile.Effective, summary Summary, controls Controls) (*compile.Effective, error) { - eff := *base + eff, err := base.WithIPVersion(controls.IPVersion) + if err != nil { + return nil, err + } eff.Groups = slices.Clone(base.Groups) ids := make([]string, 0, len(base.Outbounds)) for _, outbound := range base.Outbounds { @@ -243,7 +248,6 @@ func ApplyControls(base *compile.Effective, summary Summary, controls Controls) } eff.Routing = model.Routing{Mode: mode, Global: global, BlockQUIC: blockQUIC} opts := router.Options{Outbounds: ids, Groups: eff.Groups, Final: base.Final} - var err error eff.Router, err = router.New(base.Router.Rules(), opts) if err != nil { return nil, err @@ -251,7 +255,7 @@ func ApplyControls(base *compile.Effective, summary Summary, controls Controls) eff.ActiveRouter = eff.Router switch mode { case "rule": - return &eff, nil + return eff, nil case "global": opts.Final = global case "direct": @@ -264,7 +268,7 @@ func ApplyControls(base *compile.Effective, summary Summary, controls Controls) return nil, err } eff.ActiveRouter, err = router.New(active, opts) - return &eff, err + return eff, err } func diagnosticError(prefix string, diagnostics model.Diagnostics) error { diff --git a/mobile/profile/bundle_test.go b/mobile/profile/bundle_test.go index 2884ee1..0a99ca2 100644 --- a/mobile/profile/bundle_test.go +++ b/mobile/profile/bundle_test.go @@ -2,9 +2,12 @@ package profile import ( "context" + "fmt" + "reflect" "testing" "github.com/MimoProxy/reka/internal/config/compile" + "github.com/MimoProxy/reka/internal/config/model" "github.com/MimoProxy/reka/internal/router" ) @@ -91,3 +94,100 @@ rules: t.Fatal("invalid QUIC blocking mode was accepted") } } + +func TestControlsIPVersion(t *testing.T) { + const input = ` +schema-version: 1 +outbounds: + - {id: configured, type: shadowsocks, server: proxy.test, port: 443, method: aes-128-gcm, password: example, dialer: {ip-version: ipv6-prefer, tfo: true}} + - {id: plain, type: shadowsocks, server: proxy.test, port: 443, method: aes-128-gcm, password: example} + - {id: detoured, type: direct, dialer: {proxy: plain}} +groups: [{id: main, type: select, members: [configured, plain, detoured], selected: configured}] +routing: {mode: rule, global: main} +rules: [{match: {all: true}, outbound: main}] +dns: {ipv6: %t, nameserver: [192.0.2.53]} +` + for _, baseIPv6 := range []bool{false, true} { + t.Run(fmt.Sprintf("profile IPv6 %t", baseIPv6), func(t *testing.T) { + bundle, err := prepare(t.Context(), []byte(fmt.Sprintf(input, baseIPv6)), nil) + if err != nil { + t.Fatal(err) + } + base, err := bundle.Compile() + if err != nil { + t.Fatal(err) + } + original, err := bundle.Compile() + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name, control, policy string + ipv6 bool + }{ + {"follow profile", "", "", baseIPv6}, + {"dual", "dual", "", true}, + {"ipv4", "ipv4", "ipv4", false}, + {"ipv6", "ipv6", "ipv6", true}, + {"ipv4-prefer", "ipv4-prefer", "ipv4-prefer", true}, + {"ipv6-prefer", "ipv6-prefer", "ipv6-prefer", true}, + } { + t.Run(tc.name, func(t *testing.T) { + updated, err := ApplyControls(base, bundle.Summary, Controls{IPVersion: tc.control}) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(base, original) { + t.Fatal("controls modified the base configuration") + } + if tc.control == "" { + if !reflect.DeepEqual(updated, base) { + t.Fatal("empty override changed the compiled settings") + } + return + } + if updated.DNS == nil || updated.DNS == base.DNS || updated.DNS.IPv6 != tc.ipv6 { + t.Fatalf("expected a copy of DNS config with IPv6 set to %t", tc.ipv6) + } + if (base.DNSFingerprint != updated.DNSFingerprint) != (baseIPv6 != tc.ipv6) { + t.Fatal("DNS fingerprint did not track the IPv6 setting") + } + want := map[string]*model.Dialer{ + "configured": {IPVersion: tc.policy, TFO: true}, + "detoured": {Proxy: "plain"}, + "direct": nil, + "plain": nil, + "reject": nil, + } + if tc.policy != "" { + want["direct"] = &model.Dialer{IPVersion: tc.policy} + want["plain"] = &model.Dialer{IPVersion: tc.policy} + } + for id, dialer := range want { + outbound, ok := updated.Outbound(id) + if !ok || !reflect.DeepEqual(outbound.Dialer, dialer) { + t.Errorf("outbound %q dialer = %+v, want %+v", id, outbound.Dialer, dialer) + } + } + }) + } + if _, err := ApplyControls(base, bundle.Summary, Controls{IPVersion: "invalid"}); err == nil || err.Error() != "unknown IP version policy" { + t.Fatalf("invalid IP version error = %v", err) + } + }) + } +} + +func TestControlsIPVersionWithoutDNS(t *testing.T) { + base, diagnostics := compile.Compile([]byte("schema-version: 1\n"), nil, compile.Options{}) + if diagnostics.HasErrors() { + t.Fatal(diagnostics) + } + updated, err := ApplyControls(base, Describe(base), Controls{IPVersion: "ipv4"}) + if err != nil { + t.Fatal(err) + } + if updated.DNS != nil || updated.DNSFingerprint != base.DNSFingerprint { + t.Fatal("override changed an absent DNS configuration") + } +}