From d1650fa13e7d54baad194e6a64eece21e2aa3712 Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:47:24 +0300 Subject: [PATCH 1/2] Auto: a path with an IPv6 address is left alone on a device without IPv6, and the probes follow the address family Co-Authored-By: Claude Fable 5.2 --- core/cmd/mistgate-clientd/main.go | 2 + core/internal/diag/diag_test.go | 18 ++++++ core/internal/diag/network_other.go | 2 +- core/internal/diag/network_windows.go | 19 +++--- core/internal/diag/probes.go | 2 +- core/internal/diag/runner.go | 11 +++- core/internal/engine/gvisor_bridge_windows.go | 29 ++++++++- .../engine/ipv6_paths_windows_test.go | 63 +++++++++++++++++++ core/internal/engine/real_other.go | 3 + core/internal/engine/real_windows.go | 40 +++++++++++- core/internal/profile/profile.go | 28 +++++++-- core/internal/profile/profile_test.go | 55 +++++++++++++++- core/internal/session/manager.go | 2 +- core/internal/session/manager_memory_test.go | 23 +++++++ core/internal/subs/store.go | 29 +++++++++ core/internal/subs/store_test.go | 31 +++++++++ docs/ipc.md | 10 ++- 17 files changed, 346 insertions(+), 21 deletions(-) create mode 100644 core/internal/engine/ipv6_paths_windows_test.go diff --git a/core/cmd/mistgate-clientd/main.go b/core/cmd/mistgate-clientd/main.go index 396193b..bee063c 100644 --- a/core/cmd/mistgate-clientd/main.go +++ b/core/cmd/mistgate-clientd/main.go @@ -344,6 +344,8 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents status, err := manager.Status(ctx) return err == nil && (status.State == "off" || status.State == "error") } + // a path whose address is IPv6 is marked for the window when the device has none + store.IPv6 = engine.HasIPv6 // the panel's ASN is the network's: note which network the device was in when the sync brought it store.ASNSeen = func(sub string) { key, _ := diag.NetworkKey(memory.Salt()) diff --git a/core/internal/diag/diag_test.go b/core/internal/diag/diag_test.go index dbc4610..9a4ff5b 100644 --- a/core/internal/diag/diag_test.go +++ b/core/internal/diag/diag_test.go @@ -252,3 +252,21 @@ func TestServerAddressesAreKeptForAWhile(t *testing.T) { t.Fatalf("after the time ran out: asked %d times, err %v; want a fresh lookup", asked, err) } } + +// The probes of a server dial in its own family: an IPv6 path is not tried over IPv4 and lost for it. +func TestProbesFollowTheAddressFamily(t *testing.T) { + for host, want := range map[string]string{"192.0.2.1": "tcp4", "2001:db8::1": "tcp6"} { + var network string + dial := func(_ context.Context, n, _ string) (net.Conn, error) { + network = n + return nil, errors.New("down") + } + hostAlive(context.Background(), dial, host, []uint16{443}, 50*time.Millisecond) + if network != want { + t.Errorf("hostAlive(%s) dialed %q, want %q", host, network, want) + } + } + if got := networkFor(netip.MustParseAddr("2001:db8::1"), "udp"); got != "udp6" { + t.Errorf("networkFor(IPv6, udp) = %q", got) + } +} diff --git a/core/internal/diag/network_other.go b/core/internal/diag/network_other.go index 30fe989..e6c44e7 100644 --- a/core/internal/diag/network_other.go +++ b/core/internal/diag/network_other.go @@ -26,7 +26,7 @@ func NetworkKey([]byte) (key, kind string) { return "", "" } func interfaceFor(_ netip.Addr, fallback interfaceInfo) interfaceInfo { return fallback } -func listenPacketBound(context.Context, interfaceInfo) (net.PacketConn, error) { +func listenPacketBound(context.Context, interfaceInfo, string) (net.PacketConn, error) { return nil, errors.New("physical interface binding is unavailable") } diff --git a/core/internal/diag/network_windows.go b/core/internal/diag/network_windows.go index 818328a..b1ae9fe 100644 --- a/core/internal/diag/network_windows.go +++ b/core/internal/diag/network_windows.go @@ -118,10 +118,10 @@ func interfaceFor(destination netip.Addr, fallback interfaceInfo) interfaceInfo return fallback } -func listenPacketBound(ctx context.Context, physical interfaceInfo) (net.PacketConn, error) { +func listenPacketBound(ctx context.Context, physical interfaceInfo, network string) (net.PacketConn, error) { var config net.ListenConfig config.Control = netcfg.SocketControl(physical.Index) - return config.ListenPacket(ctx, "udp4", ":0") + return config.ListenPacket(ctx, network, ":0") } func boundDialer(physical interfaceInfo) *net.Dialer { @@ -160,7 +160,7 @@ func dnsExchange(ctx context.Context, server netip.Addr, query []byte, physical if !server.Is4() { return nil, errors.New("physical resolver is not IPv4") } - conn, err := listenPacketBound(ctx, physical) + conn, err := listenPacketBound(ctx, physical, "udp4") // the resolvers are IPv4 if err != nil { return nil, err } @@ -235,6 +235,7 @@ func attemptProfile(ctx context.Context, p profile.Profile, endpoint netip.AddrP type hy2BoundFactory struct { ctx context.Context physical interfaceInfo + network string // udp4 or udp6, by the server's address kind string password []byte mu sync.Mutex @@ -246,7 +247,7 @@ type hy2BoundFactory struct { } func (f *hy2BoundFactory) New(net.Addr) (net.PacketConn, error) { - conn, err := listenPacketBound(f.ctx, f.physical) + conn, err := listenPacketBound(f.ctx, f.physical, f.network) if err != nil { f.mu.Lock() f.err = err @@ -339,7 +340,7 @@ func attemptHy2(ctx context.Context, p *profile.Hy2, endpoint netip.AddrPort, ph return 0, errNoAnswer } started := time.Now() - factory := &hy2BoundFactory{ctx: ctx, physical: physical, kind: p.Obfs, password: []byte(p.ObfsPassword)} + factory := &hy2BoundFactory{ctx: ctx, physical: physical, network: networkFor(endpoint.Addr(), "udp"), kind: p.Obfs, password: []byte(p.ObfsPassword)} tlsConfig := client.TLSConfig{ServerName: p.ServerName, InsecureSkipVerify: p.Insecure} if p.HasPin { pin := p.PinSHA256 @@ -406,7 +407,7 @@ func attemptVLESS(ctx context.Context, p *profile.VLESS, endpoint netip.AddrPort return 0, errNoAnswer } started := time.Now() - conn, err := dialBound(ctx, "tcp4", endpoint.String(), physical) + conn, err := dialBound(ctx, networkFor(endpoint.Addr(), "tcp"), endpoint.String(), physical) if err != nil { return 0, errNoAnswer } @@ -501,7 +502,11 @@ func attemptAWG(ctx context.Context, p *profile.AWG, endpoint netip.AddrPort, ph if !ok { return 0, errors.New("AmneziaWG bind cannot select an interface") } - if err := interfaceBind.BindSocketToInterface4(physical.Index, false); err != nil { + bindTo := interfaceBind.BindSocketToInterface4 + if endpoint.Addr().Is6() { + bindTo = interfaceBind.BindSocketToInterface6 + } + if err := bindTo(physical.Index, false); err != nil { return 0, err } keyBytes, err := hex.DecodeString(p.ServerKey) diff --git a/core/internal/diag/probes.go b/core/internal/diag/probes.go index 6012756..5ee6d83 100644 --- a/core/internal/diag/probes.go +++ b/core/internal/diag/probes.go @@ -30,7 +30,7 @@ func checkSTUN(ctx context.Context, physical interfaceInfo, config Config) []uin if len(config.STUNServers) == 0 { return nil } - conn, err := listenPacketBound(ctx, physical) + conn, err := listenPacketBound(ctx, physical, "udp4") if err != nil { return nil } diff --git a/core/internal/diag/runner.go b/core/internal/diag/runner.go index 8b0f5e5..3195181 100644 --- a/core/internal/diag/runner.go +++ b/core/internal/diag/runner.go @@ -655,7 +655,8 @@ func hostAlive(ctx context.Context, dial dialContextFunc, host string, ports []u defer func() { results <- result }() dialCtx, stop := context.WithTimeout(checkCtx, timeout) defer stop() - conn, err := dial(dialCtx, "tcp4", net.JoinHostPort(host, strconv.Itoa(int(port)))) + address, _ := netip.ParseAddr(host) + conn, err := dial(dialCtx, networkFor(address, "tcp"), net.JoinHostPort(host, strconv.Itoa(int(port)))) if conn != nil { _ = conn.Close() } @@ -748,3 +749,11 @@ func numericAddress(host string) (netip.Addr, bool) { ip, err := netip.ParseAddr(strings.Trim(host, "[]")) return ip, err == nil && ip.Is4() } + +// networkFor is proto4 or proto6 by the address's family (an unparsed address is taken for IPv4). +func networkFor(address netip.Addr, proto string) string { + if address.Is6() { + return proto + "6" + } + return proto + "4" +} diff --git a/core/internal/engine/gvisor_bridge_windows.go b/core/internal/engine/gvisor_bridge_windows.go index 9ed8903..bd8a317 100644 --- a/core/internal/engine/gvisor_bridge_windows.go +++ b/core/internal/engine/gvisor_bridge_windows.go @@ -12,6 +12,7 @@ import ( "log/slog" "net" "net/netip" + "slices" "sync" "sync/atomic" "time" @@ -1020,14 +1021,16 @@ func (f countedFlow) ReadFrom() ([]byte, netip.AddrPort, error) { var direct6 struct{ at, ok atomic.Int64 } -// directIPv6 says whether this machine reaches IPv6 beside the tunnel; the routing table is asked at most once in 30 s. +// directIPv6 says whether this machine reaches IPv6 beside the tunnel: a route outside the tunnel to a global address, +// whose interface has a global address of its own (Teredo and 6to4 add a ::/0 route of their own, and with it a false +// yes). The routing table is asked at most once in 30 s. var directIPv6 = func() bool { // a variable for the tests now := time.Now().Unix() if now-direct6.at.Load() < 30 { return direct6.ok.Load() == 1 } var ok int64 - if _, err := netcfg.PhysicalInterfaceIndexFor(netip.MustParseAddr("2001:4860:4860::8888")); err == nil { + if index, err := netcfg.PhysicalInterfaceIndexFor(netip.MustParseAddr("2001:4860:4860::8888")); err == nil && hasGlobalIPv6(index) { ok = 1 } direct6.ok.Store(ok) @@ -1039,3 +1042,25 @@ func directAddressAllowed(address netip.Addr) bool { return address.IsValid() && !address.IsPrivate() && !address.IsLoopback() && !address.IsLinkLocalUnicast() && !address.IsLinkLocalMulticast() && !address.IsMulticast() && !address.IsUnspecified() } + +// hasGlobalIPv6 says whether the interface has an address that IPv6 on the Internet can use. +func hasGlobalIPv6(index uint32) bool { + iface, err := net.InterfaceByIndex(int(index)) + if err != nil { + return false + } + addrs, _ := iface.Addrs() + return slices.ContainsFunc(addrs, func(a net.Addr) bool { + prefix, err := netip.ParsePrefix(a.String()) + return err == nil && globalIPv6(prefix.Addr()) + }) +} + +var tunnelingIPv6 = []netip.Prefix{netip.MustParsePrefix("2001::/32"), netip.MustParsePrefix("2002::/16")} // Teredo, 6to4 + +func globalIPv6(a netip.Addr) bool { + return a.Is6() && !a.Is4In6() && a.IsGlobalUnicast() && !a.IsPrivate() && !slices.ContainsFunc(tunnelingIPv6, func(p netip.Prefix) bool { return p.Contains(a) }) +} + +// HasIPv6 says whether this machine reaches IPv6 outside any tunnel. +func HasIPv6() bool { return directIPv6() } diff --git a/core/internal/engine/ipv6_paths_windows_test.go b/core/internal/engine/ipv6_paths_windows_test.go new file mode 100644 index 0000000..5c4ba1b --- /dev/null +++ b/core/internal/engine/ipv6_paths_windows_test.go @@ -0,0 +1,63 @@ +//go:build windows + +package engine + +import ( + "context" + "net/netip" + "slices" + "testing" + + "github.com/mistgate/mistgate-client/core/internal/profile" +) + +func v6Paths() []profile.Profile { + return []profile.Profile{ + {ID: "v4", Protocol: "hysteria2", Sub: "s", Hy2: &profile.Hy2{Host: "192.0.2.1", Port: 443}}, + {ID: "v6", Protocol: "vless", Sub: "s", VLESS: &profile.VLESS{Host: "2001:db8::1", Port: 443}}, + } +} + +func withIPv6(t *testing.T, has bool) { + t.Helper() + real := directIPv6 + t.Cleanup(func() { directIPv6 = real }) + directIPv6 = func() bool { return has } +} + +// Without IPv6 on the device Auto's choices (Select's order, the background probes) leave IPv6 paths out; the one asked +// for by name stays, and its connect is refused at once with its own code. +func TestIPv6PathsOnADeviceWithoutIPv6(t *testing.T) { + r := &Real{load: func() ([]profile.Profile, error) { return v6Paths(), nil }} + withIPv6(t, false) + if selection, _ := r.Select(Target{Server: "auto"}); !slices.Equal(selection.Order, []string{"v4"}) { + t.Errorf("Auto's order = %v, want the IPv4 path only", selection.Order) + } + if selection, _ := r.Select(Target{Server: "v6"}); !slices.Contains(selection.Order, "v6") { + t.Errorf("a path asked for by name left the order: %v", selection.Order) + } + rtts, skipped := r.Measure(context.Background(), []string{"v6"}) + if len(rtts) != 0 || !slices.Equal(skipped, []string{"v6"}) { + t.Errorf("Measure of an IPv6 path = %v, skipped %v; want it skipped, not dialed", rtts, skipped) + } + err := ipv6Refusal(v6Paths()[1]) + if ErrorCode(err) != "no_ipv6" || ipv6Refusal(v6Paths()[0]) != nil { + t.Errorf("refusals = %v / %v", err, ipv6Refusal(v6Paths()[0])) + } + withIPv6(t, true) + if selection, _ := r.Select(Target{Server: "auto"}); len(selection.Order) != 2 || ipv6Refusal(v6Paths()[1]) != nil { + t.Errorf("with IPv6 the order is %v and the path refused", selection.Order) + } +} + +// Teredo, 6to4 and local addresses are no sign of IPv6 on the Internet. +func TestGlobalIPv6(t *testing.T) { + for address, want := range map[string]bool{ + "2001:db8::1": true, "2a00:1450::1": true, "fe80::1": false, "fd00::1": false, "2001:0:4136:e378::1": false, + "2002:c000:204::1": false, "::1": false, "192.0.2.1": false, "::ffff:192.0.2.1": false, + } { + if got := globalIPv6(netip.MustParseAddr(address)); got != want { + t.Errorf("globalIPv6(%s) = %v, want %v", address, got, want) + } + } +} diff --git a/core/internal/engine/real_other.go b/core/internal/engine/real_other.go index 13def1f..7867358 100644 --- a/core/internal/engine/real_other.go +++ b/core/internal/engine/real_other.go @@ -58,3 +58,6 @@ func (*Real) Measure(context.Context, []string) (map[string]time.Duration, []str func (*Real) DialVPN(context.Context, string, uint16) (net.Conn, error) { return nil, ErrNoTunnel } func (*Real) HomeAddr() string { return "" } + +// HasIPv6: off Windows nothing says otherwise. +func HasIPv6() bool { return true } diff --git a/core/internal/engine/real_windows.go b/core/internal/engine/real_windows.go index 8371151..f7b7cb2 100644 --- a/core/internal/engine/real_windows.go +++ b/core/internal/engine/real_windows.go @@ -540,6 +540,17 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf // the first wave. if target.Server == "" || target.Server == "auto" { _, ring, _ := profile.Ring(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game) + ipv6 := directIPv6() + if !ipv6 { // none on the device: a path whose address is an IPv6 literal is not Auto's to take, so none is noted either + left := dropIPv6(target, ring) + if len(left) < len(ring) { + slog.Info("auto: IPv6 paths left out count=" + strconv.Itoa(len(ring)-len(left))) + } + if len(left) == 0 && len(ring) > 0 { + return Info{}, failure("no_ipv6", "every path needs IPv6") + } + ring = left + } candidates := ring[:0:0] for _, p := range ring { if !configured.Game || p.Protocol == selected.Protocol { // Game mode has chosen the protocol @@ -549,7 +560,7 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf if !slices.ContainsFunc(candidates, func(p profile.Profile) bool { return !slices.Contains(target.Avoid, p.ID) }) { candidates = ring // the chosen protocol failed on every path: the others may be tried } - waves := profile.AutoWaves(candidates, target.Avoid) + waves := profile.AutoWaves(candidates, target.Avoid, ipv6) answered := false if i := slices.IndexFunc(candidates, func(p profile.Profile) bool { return target.takes(p.ID) }); i >= 0 { selected, answered, waves = candidates[i], true, nil // the path that worked lately here: no race @@ -573,6 +584,9 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf selected = waves[0][0] } } + if err := ipv6Refusal(selected); err != nil { + return Info{}, err + } started := selected // as the subscriptions gave it: the override below is not theirs if r.verify != "" { selected.Verify = r.verify @@ -1000,6 +1014,7 @@ func (r *Real) Next(target Target, after string) (string, bool) { return "", false } configured := r.settings() + profiles = dropIPv6(target, profiles) return profile.Next(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game, after) } @@ -1016,6 +1031,7 @@ func (r *Real) Select(target Target) (Selection, bool) { if !ok { return Selection{}, false } + ring = dropIPv6(target, ring) name := home.Name if name == "" { name = home.ID @@ -1123,6 +1139,8 @@ func (r *Real) Measure(ctx context.Context, ids []string) (map[string]time.Durat for _, p := range profiles { switch _, live := diag.LiveGuard(p); { case !slices.Contains(ids, p.ID): + case p.NeedsIPv6() && !directIPv6(): // nothing to dial; the session leaves it out of the memory + skipped = append(skipped, p.ID) case live: skipped = append(skipped, p.ID) default: @@ -1149,7 +1167,7 @@ func (r *Real) Fastest(ctx context.Context, target Target, except string) (strin configured := r.settings() others := profile.Others(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game, except) others = slices.DeleteFunc(others, func(p profile.Profile) bool { return slices.Contains(target.Avoid, p.ID) }) // Auto's own - for _, wave := range profile.AutoWaves(others, nil) { + for _, wave := range profile.AutoWaves(others, nil, directIPv6()) { if best := quickestOf(ctx, wave); best >= 0 { return wave[best].ID, true } @@ -1992,3 +2010,21 @@ func awgHandshakeSeen(text, serverKey string) bool { func awgNeedsStack(useForwarder bool, p profile.Profile) bool { return useForwarder || p.PanelBlockAds || p.NoIPv6 || slices.ContainsFunc(p.AWG.Addresses, func(a netip.Prefix) bool { return a.Addr().Is6() }) } + +// dropIPv6 leaves out the paths a device without IPv6 cannot reach: those whose address is an IPv6 literal. The path +// asked for by name stays (ipv6Refusal turns it away at the connect). +func dropIPv6(target Target, paths []profile.Profile) []profile.Profile { + if directIPv6() { + return paths + } + return slices.DeleteFunc(slices.Clone(paths), func(p profile.Profile) bool { return p.NeedsIPv6() && p.ID != target.Server }) +} + +// ipv6Refusal is the answer to a path of an IPv6 address on a device without IPv6: at once, not after the wait for a +// server that cannot be reached. +func ipv6Refusal(p profile.Profile) error { + if p.NeedsIPv6() && !directIPv6() { + return failure("no_ipv6", "the path's address is IPv6, this device has none") + } + return nil +} diff --git a/core/internal/profile/profile.go b/core/internal/profile/profile.go index b4ecdbe..4139143 100644 --- a/core/internal/profile/profile.go +++ b/core/internal/profile/profile.go @@ -663,18 +663,38 @@ func (p Profile) Endpoint() (string, uint16, error) { } } +// IPv6Literal says whether host (or "host:port") is an IPv6 address written out, with or without brackets. +func IPv6Literal(host string) bool { + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + address, err := netip.ParseAddr(strings.Trim(host, "[]")) + return err == nil && address.Is6() && !address.Is4In6() +} + +// NeedsIPv6 says whether the path's entry address is an IPv6 literal (every one of a TrustTunnel path's), so that a +// device without IPv6 cannot reach it. The panel's `ipv6` flag does not say it, and a relay's arm is only its address. +func (p Profile) NeedsIPv6() bool { + if p.Protocol == "trusttunnel" { + return p.TT != nil && len(p.TT.Addresses) > 0 && !slices.ContainsFunc(p.TT.Addresses, func(a string) bool { return !IPv6Literal(a) }) + } + host, _, err := p.Endpoint() + return err == nil && IPv6Literal(host) +} + const autoWaveSize, autoWaves = 3, 3 // AutoWaves orders the paths Auto may take into the waves it tries one after another: a wave is measured at once, and // the first wave with an answer decides. Direct paths come first (the first wave is only direct ones, if there are // any), then the rest of them, then relays and WARP exits. Inside a wave a path of another transport family than the // one before it, on a host the wave does not have yet, is preferred, so that one block does not take a whole wave. -// `avoid` are the paths that failed lately; when they would leave nothing, they are not avoided. +// `avoid` are the paths that failed lately; when they would leave nothing, they are not avoided. Without `ipv6` (the device +// has none) a path whose address is an IPv6 literal is not taken at all, avoided or not. // ponytail: nine paths at most; the rest are reached by `avoid` on the next attempts. -func AutoWaves(candidates []Profile, avoid []string) [][]Profile { +func AutoWaves(candidates []Profile, avoid []string, ipv6 bool) [][]Profile { var rest, relays []Profile for _, p := range candidates { - if slices.Contains(avoid, p.ID) { + if slices.Contains(avoid, p.ID) || !ipv6 && p.NeedsIPv6() { continue } if p.Direct() { @@ -687,7 +707,7 @@ func AutoWaves(candidates []Profile, avoid []string) [][]Profile { if len(avoid) == 0 { return nil } - return AutoWaves(candidates, nil) // nothing but avoided paths: they are all there is + return AutoWaves(candidates, nil, ipv6) // nothing but avoided paths: they are all there is } if len(rest) == 0 { rest, relays = relays, nil // no direct path: relays from the first wave diff --git a/core/internal/profile/profile_test.go b/core/internal/profile/profile_test.go index 4a016aa..0301d96 100644 --- a/core/internal/profile/profile_test.go +++ b/core/internal/profile/profile_test.go @@ -366,7 +366,7 @@ func TestAutoWaves(t *testing.T) { } for _, test := range tests { var waves []string - for _, wave := range AutoWaves(test.candidates, test.avoid) { + for _, wave := range AutoWaves(test.candidates, test.avoid, true) { ids := make([]string, len(wave)) for i, p := range wave { ids[i] = p.ID @@ -378,3 +378,56 @@ func TestAutoWaves(t *testing.T) { } } } + +func TestIPv6Literal(t *testing.T) { + for host, want := range map[string]bool{ + "192.0.2.1": false, "192.0.2.1:443": false, "node.example": false, "node.example:443": false, "": false, + "2001:db8::1": true, "[2001:db8::1]": true, "[2001:db8::1]:443": true, "::ffff:192.0.2.1": false, + } { + if got := IPv6Literal(host); got != want { + t.Errorf("IPv6Literal(%q) = %v, want %v", host, got, want) + } + } +} + +// A path needs IPv6 when its entry address is an IPv6 literal, whatever the protocol (a relay's arm is just its address). +func TestNeedsIPv6(t *testing.T) { + for name, test := range map[string]struct { + p Profile + want bool + }{ + "hysteria2": {Profile{Protocol: "hysteria2", Hy2: &Hy2{Host: "2001:db8::1", Port: 443}}, true}, + "hysteria2 name": {Profile{Protocol: "hysteria2", Hy2: &Hy2{Host: "node.example", Port: 443}}, false}, + "awg": {Profile{Protocol: "awg", AWG: &AWG{EndpointHost: "[2001:db8::1]", EndpointPort: 51820}}, true}, + "awg ipv4": {Profile{Protocol: "awg", AWG: &AWG{EndpointHost: "192.0.2.1", EndpointPort: 51820}}, false}, + "vless relay arm": {Profile{Protocol: "vless", Via: "relay", VLESS: &VLESS{Host: "2001:db8::2", Port: 443}}, true}, + "trusttunnel": {Profile{Protocol: "trusttunnel", TT: &TrustTunnel{Addresses: []string{"[2001:db8::1]:443"}}}, true}, + "trusttunnel mixed": {Profile{Protocol: "trusttunnel", TT: &TrustTunnel{Addresses: []string{"[2001:db8::1]:443", "192.0.2.1:443"}}}, false}, + "no endpoint": {Profile{Protocol: "vless"}, false}, + } { + if got := test.p.NeedsIPv6(); got != test.want { + t.Errorf("%s: NeedsIPv6 = %v, want %v", name, got, test.want) + } + } +} + +func TestAutoWavesLeavesIPv6PathsToDevicesWithIPv6(t *testing.T) { + v4 := Profile{ID: "a", Protocol: "hysteria2", Hy2: &Hy2{Host: "192.0.2.1", Port: 443}} + v6 := Profile{ID: "b", Protocol: "vless", VLESS: &VLESS{Host: "2001:db8::1", Port: 443}} + count := func(waves [][]Profile) (n int) { + for _, wave := range waves { + n += len(wave) + } + return n + } + if n := count(AutoWaves([]Profile{v4, v6}, nil, true)); n != 2 { + t.Errorf("with IPv6: %d paths, want 2", n) + } + waves := AutoWaves([]Profile{v4, v6}, []string{"a"}, false) // v4 avoided, v6 unusable: the avoided one is all there is + if len(waves) != 1 || len(waves[0]) != 1 || waves[0][0].ID != "a" { + t.Errorf("without IPv6: %v, want the IPv4 path only", waves) + } + if waves := AutoWaves([]Profile{v6}, nil, false); waves != nil { + t.Errorf("only IPv6 paths without IPv6: %v, want none", waves) + } +} diff --git a/core/internal/session/manager.go b/core/internal/session/manager.go index 929e560..7a783b6 100644 --- a/core/internal/session/manager.go +++ b/core/internal/session/manager.go @@ -1487,7 +1487,7 @@ func (m *Manager) stillPatient(state *actorState, code string) bool { // bootRetryCode: the failures a boot connect waits out; the network is not there (yet). func bootRetryCode(code string) bool { - return code == "offline" || code == "server_not_found" || code == "no_server_answers" + return code == "offline" || code == "server_not_found" || code == "no_server_answers" || code == "no_ipv6" } func fatalReconnectCode(code string) bool { diff --git a/core/internal/session/manager_memory_test.go b/core/internal/session/manager_memory_test.go index c3644fc..32eb728 100644 --- a/core/internal/session/manager_memory_test.go +++ b/core/internal/session/manager_memory_test.go @@ -89,6 +89,7 @@ func TestAutoMemory(t *testing.T) { {"a known path that fails is followed by a race, not by the same path", testMemoryKnownFails}, {"two failures in a row put a path in quarantine and a success lifts it", testMemoryQuarantine}, {"offline is not written down", testMemoryOfflineNotRecorded}, + {"no_ipv6 is not written down", testMemoryNoIPv6NotRecorded}, {"the memory outlives a restart and holds no names", testMemoryRestart}, {"a connection that died on one path and comes back on another is a failover", testMemoryFailover}, {"the round trip is noted at the first good probe", testMemoryRTT}, @@ -391,3 +392,25 @@ func TestAutoAfterANamedServerInTheIdleHold(t *testing.T) { t.Fatalf("the attempt went to %q, auto %v: the named server came back", last.Server, status.Auto) } } + +// A path asked for by name that needs IPv6 the device does not have is refused at once, with its own code; it is no +// fault of the path, so nothing is noted, and a boot connect waits it out like a missing network. +func testMemoryNoIPv6NotRecorded(t *testing.T) { + fake := engine.NewFake(engine.FakeConfig{StepDelay: time.Millisecond, FailStartCode: "no_ipv6"}) + fake.SetProfiles(autoProfiles("p1", "p2")...) + c, mem := newClock(), auto.Open("") + mem.Success("net", "p1", 40, c.now()) + manager, subscription := memoryManager(t, fake, mem, c, time.Hour) + for range 3 { + connectAuto(t, manager) + if status := waitForStatus(t, subscription.C, func(status Status) bool { return status.State == "error" }); status.Error != "no_ipv6" { + t.Fatalf("error = %q, want no_ipv6", status.Error) + } + } + if id, ok := mem.Known("net", []auto.Path{{ID: "p1"}, {ID: "p2"}}, c.now()); !ok || id != "p1" || len(mem.Avoid("net", c.now())) != 0 { + t.Fatalf("known = %q, %v; avoid %v: no_ipv6 was written down", id, ok, mem.Avoid("net", c.now())) + } + if !bootRetryCode("no_ipv6") { + t.Error("a boot connect does not wait out no_ipv6") + } +} diff --git a/core/internal/subs/store.go b/core/internal/subs/store.go index bce1934..a8c4d0d 100644 --- a/core/internal/subs/store.go +++ b/core/internal/subs/store.go @@ -99,6 +99,8 @@ type Server struct { NodeLabel string `json:"node_label,omitempty"` ViaCountry string `json:"via_country,omitempty"` IPv6Egress *bool `json:"ipv6_egress,omitempty"` // whether IPv6 leaves through this path; nil: the panel did not say + // Set when the list is read: the path's entry address is an IPv6 literal and this device has no IPv6, so Auto passes it by. + NeedsIPv6 bool `json:"needs_ipv6,omitempty"` // The subscription asks not to check the server's certificate (Hysteria2 "insecure=1", TrustTunnel // "skip_verification"): the window says so on the server's row. Set when the subscription is read, so one saved by a // build before 0.1.7 shows it after its next refresh. @@ -151,6 +153,8 @@ type Store struct { // ASNSeen is called with the subscription's id when a sync that left outside the tunnel brought an ASN: it is the // network the device is in now. It runs in the syncing goroutine and takes no store lock. May be nil. ASNSeen func(sub string) + // IPv6 says that this device reaches IPv6 outside the tunnel. nil: it is taken to (no row is marked needs_ipv6). + IPv6 func() bool reportMu sync.Mutex // after mu, never before it reports map[string]*reportState @@ -234,6 +238,26 @@ func (s *Store) fillVersions() { } } +// ponytail: on a device without IPv6 every read of the list parses the entries once more; cache them if that shows. +func (s *Store) markIPv6(result []Subscription) { + if s.IPv6 == nil || s.IPv6() { + return + } + profiles, _ := s.profiles() + for _, p := range profiles { + if !p.NeedsIPv6() { + continue + } + for i := range result { + for j := range result[i].Servers { + if result[i].ID == p.Sub && result[i].Servers[j].ID == p.ID { + result[i].Servers[j].NeedsIPv6 = true + } + } + } + } +} + func (s *Store) List() []Subscription { s.mu.RLock() defer s.mu.RUnlock() @@ -241,6 +265,7 @@ func (s *Store) List() []Subscription { for i, sub := range s.state.Subscriptions { result[i] = s.withLast(publicCopy(sub.Subscription)) } + s.markIPv6(result) return result } @@ -455,6 +480,10 @@ func (s *Store) refresh(ctx context.Context, id string) (Subscription, error) { func (s *Store) Profiles() ([]profile.Profile, error) { s.mu.RLock() defer s.mu.RUnlock() + return s.profiles() +} + +func (s *Store) profiles() ([]profile.Profile, error) { profiles := make([]profile.Profile, 0) for _, sub := range s.state.Subscriptions { for _, entry := range sub.Entries { diff --git a/core/internal/subs/store_test.go b/core/internal/subs/store_test.go index dd44fa4..715fddd 100644 --- a/core/internal/subs/store_test.go +++ b/core/internal/subs/store_test.go @@ -471,3 +471,34 @@ func mihomoProfileFixture(key string) string { " - name: Plain WG\n type: wireguard\n server: awg4.example\n port: 51822\n ip: 10.66.4.4/32\n private-key: " + key + "\n public-key: " + key + "\n allowed-ips: [0.0.0.0/0]\n" + " - name: Broken proxy\n type: hysteria2\n server: broken.example\n port: 443\n" } + +// On a device without IPv6 the rows of the paths with an IPv6 address are marked; the paths themselves stay in Profiles. +func TestListMarksIPv6PathsOnADeviceWithoutIPv6(t *testing.T) { + store := openTestStore(t, t.TempDir(), nil) + added, err := store.Add(context.Background(), "hy2://auth@[2001:db8::1]:443#v6\nhy2://auth@one.example:443#v4") + if err != nil { + t.Fatal(err) + } + marked := func() []bool { + var marks []bool + for _, server := range store.List()[0].Servers { + marks = append(marks, server.NeedsIPv6) + } + return marks + } + if got := marked(); len(got) != 2 || got[0] || got[1] { + t.Fatalf("no hook: marks = %v, want none", got) + } + has := true + store.IPv6 = func() bool { return has } + if got := marked(); got[0] || got[1] { + t.Fatalf("device with IPv6: marks = %v, want none", got) + } + has = false + if got := marked(); !got[0] || got[1] { + t.Fatalf("device without IPv6: marks = %v, want the first only", got) + } + if profiles, _ := store.Profiles(); len(profiles) != 2 || profiles[0].Sub != added.ID { + t.Fatalf("Profiles = %d, want both paths", len(profiles)) + } +} diff --git a/docs/ipc.md b/docs/ipc.md index 38bd249..fd8ddce 100644 --- a/docs/ipc.md +++ b/docs/ipc.md @@ -125,6 +125,13 @@ all (and while a path is left); only then does it end as any first `connect` doe Auto's next choice (see `on_server_down`). `server_id` is the id of the server in use while connected: names repeat, ids do not. +A path whose entry address (a relay arm's: the relay's) is an IPv6 literal is not for a device without IPv6 outside the tunnel (a route out of the +tunnel to a global address, through an interface that has a global address that is not Teredo's or 6to4's; looked up at most every 30 s). +Auto then takes no such path: not in a race, not in the background probes or a move to a quicker path, and nothing is noted for it in +the memory or the quarantine (one `info` line `auto: IPv6 paths left out` per attempt). A `connect` to one by name ends +at once with `no_ipv6`, with no wait for a server that cannot be reached; so does an Auto whose every path is such. `servers.ping` and +`diag.run` still try these paths as before. The paths stay in `subs.list`, marked `needs_ipv6`. + Auto remembers, for each network, which paths worked: a connect that came up through a path, a failed attempt that ended in `verify_failed`, and a `no_server_answers` of the known path Auto went to at once are noted for the network the machine is on (a race nobody answered names no path, so an outage of the network sets none aside; `offline`, @@ -236,7 +243,7 @@ the application as a connection that closes right after it opens. `state`: `off` · `connecting` · `connected` · `reconnecting` · `error` · `blocked`. `step` while connecting or retrying: `resolve` · `handshake` · `tunnel` · `verify`. `error`: a code such as `no_server_answers`, `no_subscription`, `offline`, `server_not_found`, `auth_rejected`, `tunnel_failed`, `verify_failed`, `unsupported_os`, -or `kill_switch`. +`no_ipv6` (the path's address is IPv6 and the device has no IPv6; retried like `server_not_found`), or `kill_switch`. `reconnecting` means the service detected a dead tunnel and is retrying; whether the network stays closed depends on `kill_switch`. `error` may contain the most recent failed retry code. `blocked` means a retry failed with @@ -678,6 +685,7 @@ on a panel that does not send them): | server | `via_country` | Country code where a `relay` path enters, when it is not the node's own | | server | `ipv6_egress` | `true` or `false`: whether IPv6 leaves through this path. Absent: the panel did not say. On `false` the engine treats the path as having no IPv6 at once (names get no IPv6 addresses, IPv6 destinations are turned away), without probing | | server | `insecure` | `true` when a Hysteria2 link or proxy asks not to check the server's certificate (`insecure=1`, `skip-cert-verify`) and gives no pin: the server is accepted and the window marks its row. Absent otherwise. Set when the subscription is read, from 0.1.7 | +| server | `needs_ipv6` | `true` when the path's entry address (a relay's arm: the relay's) is an IPv6 literal and this device has no IPv6 outside the tunnel just now; absent otherwise. Auto passes such a path by, a `connect` to it ends at once with `no_ipv6`, and the window may dim its row. It is read afresh with every `subs.list` and `subs` event, never stored, and is not the `ipv6` flag of the panel | | server | `purpose` | `whitelist`: a slow last-resort path for networks that pass only an allowlist of sites (the panel marks it). The service never chooses such a server by itself (not in `auto`, not as "the next server") and does not measure it for `rtt`; it is used when named in `connect`, or by `whitelist_auto`. Absent for every other server | | subscription | `telegram` | Telegram proxies: `[{"node", "country", "city", "via", "via_country", "ipv6", "link"}]`. `link` opens in Telegram; it is a secret of the same kind as a server's credentials: for the trusted window only, never logged | | subscription | `devices_used`, `devices_limit` | Devices of this person on the panel and the allowed number; both absent when the panel does not count | From 98e6d1391aca77ae5e73bd9c5d9b0f91fddb57af Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:32:58 +0300 Subject: [PATCH 2/2] Tests: the ordinary-death case stops after one death, a second in a row marks the path by design Co-Authored-By: Claude Fable 5.2 --- core/internal/session/manager_stall_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/core/internal/session/manager_stall_test.go b/core/internal/session/manager_stall_test.go index af21d15..68a9750 100644 --- a/core/internal/session/manager_stall_test.go +++ b/core/internal/session/manager_stall_test.go @@ -134,6 +134,7 @@ func testOrdinaryDeathMarksNothing(t *testing.T) { }) connectAuto(t, manager) waitForStatus(t, subscription.C, connected) + fake.SetFailStartCode("offline") // one death only: a second young one in a row marks the path, and rightly fake.SetProbeErr(errors.New("the probe failed")) waitForStatus(t, subscription.C, func(s Status) bool { return s.State == "reconnecting" }) if data := saved(t, mem, dir); strings.Contains(data, `"bad"`) {