diff --git a/core/cmd/mistgate-clientd/main.go b/core/cmd/mistgate-clientd/main.go index ab852a0..9a69e82 100644 --- a/core/cmd/mistgate-clientd/main.go +++ b/core/cmd/mistgate-clientd/main.go @@ -94,7 +94,8 @@ func main() { } func shouldConnectAtStart(configured settings.Settings) bool { - return configured.LastServer != "" && (configured.Autoconnect || configured.Restore && configured.LastOn) + // "bypass" needs no server, and without a subscription there is no last one + return (configured.LastServer != "" || configured.Mode == "bypass") && (configured.Autoconnect || configured.Restore && configured.LastOn) } // shouldResumeAtStart: the tunnel was up when the service stopped without being told to disconnect (last_up stays set @@ -103,7 +104,7 @@ func shouldConnectAtStart(configured settings.Settings) bool { // nothing to hold and the two settings decide as before. A connect that never came up leaves the network open, before // a restart and after it. func shouldResumeAtStart(configured settings.Settings) bool { - return configured.LastServer != "" && configured.LastUp && configured.KillSwitch != "off" + return configured.LastServer != "" && configured.LastUp && configured.KillSwitchNow() != "off" } // savedServerGone: the server the service would connect to is no longer in any subscription (removed, or the list @@ -304,7 +305,7 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents if geo.ValidRegion(configured.RouteRegion) { region = configured.RouteRegion } - return geoStore.CheckName(configured.RouteMode, region, name, false) + return geoStore.CheckName(configured.RouteMode, region, name, false, false) } } else { real := engine.NewReal(store.Profiles, settingsStore.Get, geoStore, verify) @@ -413,7 +414,7 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents }) diagnostics := diag.NewRunner(diag.Config{Profiles: store.Profiles, Tunnel: func() bool { status, err := manager.Status(ctx) - return err == nil && status.State == "connected" + return err == nil && status.State == "connected" && status.Route != "bypass" // a bypass session has no tunnel to check }, Connected: func() string { // the status carries the profile's name (its id when it has no name), not the id if status, err := manager.Status(ctx); err == nil && status.State == "connected" { diff --git a/core/cmd/mistgate-clientd/main_test.go b/core/cmd/mistgate-clientd/main_test.go index f29f5f8..1ce1db2 100644 --- a/core/cmd/mistgate-clientd/main_test.go +++ b/core/cmd/mistgate-clientd/main_test.go @@ -25,6 +25,8 @@ func TestShouldConnectAtStart(t *testing.T) { {"restore but was off", settings.Settings{LastServer: "a", Restore: true}, false}, {"was on but restore is off", settings.Settings{LastServer: "a", LastOn: true}, false}, {"no last server", settings.Settings{Autoconnect: true, Restore: true, LastOn: true}, false}, + {"bypass needs no last server", settings.Settings{Mode: "bypass", Autoconnect: true}, true}, + {"bypass, nothing set", settings.Settings{Mode: "bypass"}, false}, } { if got := shouldConnectAtStart(c.s); got != c.want { t.Errorf("%s: got %v, want %v", c.name, got, c.want) @@ -41,6 +43,7 @@ func TestShouldResumeAtStart(t *testing.T) { {"was on, kill switch while", settings.Settings{LastServer: "a", LastUp: true, KillSwitch: "while"}, true}, {"was on, kill switch always", settings.Settings{LastServer: "a", LastUp: true, KillSwitch: "always"}, true}, {"was on, kill switch off", settings.Settings{LastServer: "a", LastUp: true, KillSwitch: "off"}, false}, + {"bypass holds nothing", settings.Settings{LastServer: "a", LastUp: true, KillSwitch: "always", Mode: "bypass"}, false}, {"asked for, never up", settings.Settings{LastServer: "a", LastOn: true, KillSwitch: "while"}, false}, {"was off (the person disconnected), kill switch while", settings.Settings{LastServer: "a", KillSwitch: "while"}, false}, {"was off, kill switch always", settings.Settings{LastServer: "a", KillSwitch: "always"}, false}, diff --git a/core/internal/auto/asn_test.go b/core/internal/auto/asn_test.go index 5e940fe..64aa848 100644 --- a/core/internal/auto/asn_test.go +++ b/core/internal/auto/asn_test.go @@ -16,7 +16,7 @@ func TestASNNet(t *testing.T) { if again.ASNNet("s1") != "" { t.Fatal("an unknown network left the old note") } - again.Flush() // the change above started a save of its own: it must be over before the directory goes + again.Flush() // the change above started a save of its own: it must be over before the directory goes var none *Memory // a nil memory remembers nothing none.SetASNNet("s1", "net-a") if none.ASNNet("s1") != "" { diff --git a/core/internal/engine/real_other.go b/core/internal/engine/real_other.go index 7867358..40eed65 100644 --- a/core/internal/engine/real_other.go +++ b/core/internal/engine/real_other.go @@ -44,7 +44,7 @@ func (r *Real) Routes(configured settings.Settings) geo.Routes { return r.geo.Routes(configured.RouteMode, configured.RouteRegion, "") } func (r *Real) CheckSite(configured settings.Settings, name string) geo.Check { - return r.geo.CheckName(configured.RouteMode, "", name, false) + return r.geo.CheckName(configured.RouteMode, "", name, false, false) } func (*Real) RefreshAutoRegion(onChange func()) { if onChange != nil { diff --git a/core/internal/engine/real_windows.go b/core/internal/engine/real_windows.go index f7b7cb2..6ea6d63 100644 --- a/core/internal/engine/real_windows.go +++ b/core/internal/engine/real_windows.go @@ -372,7 +372,8 @@ func (r *Real) directResolver(name, region string, rules *geo.SiteRules) netip.A // CheckSite is routes.check: where the forwarder would send a site now, by the code the flows use. func (r *Real) CheckSite(configured settings.Settings, name string) geo.Check { region := r.routeRegion(configured) - return r.geo.CheckName(configured.RouteMode, region, name, r.directResolver(name, region, r.geo.ActiveSiteRules()).IsValid()) + // no flow gets a bypass strategy yet, so the answer says "never" until the bridge does it + return r.geo.CheckName(configured.RouteMode, region, name, r.directResolver(name, region, r.geo.ActiveSiteRules()).IsValid(), false) } func (r *Real) Routes(configured settings.Settings) geo.Routes { @@ -846,11 +847,11 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf } dns := tunnelDNS(customDNS, selected.PanelDNS, defaultTunnelDNS) configured = r.settings() - if err := r.setFirewall(run, configured.KillSwitch == "off", adapter.LUID(), dns, configured.LAN); err != nil { + if err := r.setFirewall(run, configured.KillSwitchNow() == "off", adapter.LUID(), dns, configured.LAN); err != nil { if runCtx.Err() != nil { return Info{}, runCtx.Err() } - if !consoleFirewallUnavailable(err) || configured.KillSwitch == "always" { + if !consoleFirewallUnavailable(err) || configured.KillSwitchNow() == "always" { return Info{}, failure("tunnel_failed", "enable firewall rules") } } @@ -889,11 +890,11 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf } dns := awgDNS configured = r.settings() - if err := r.setFirewall(run, configured.KillSwitch == "off", adapter.LUID(), dns, configured.LAN); err != nil { + if err := r.setFirewall(run, configured.KillSwitchNow() == "off", adapter.LUID(), dns, configured.LAN); err != nil { if runCtx.Err() != nil { return Info{}, runCtx.Err() } - if !consoleFirewallUnavailable(err) || configured.KillSwitch == "always" { + if !consoleFirewallUnavailable(err) || configured.KillSwitchNow() == "always" { return Info{}, failure("tunnel_failed", "enable firewall rules") } } @@ -1209,7 +1210,7 @@ func (r *Real) startRun(ctx context.Context, hold bool) (context.Context, *realR if hold { settings := r.settings() err = r.setFirewall(run, false, 0, nil, settings.LAN) - if consoleFirewallUnavailable(err) && settings.KillSwitch != "always" { + if consoleFirewallUnavailable(err) && settings.KillSwitchNow() != "always" { err = nil } } @@ -1305,7 +1306,7 @@ func (r *Real) Reapply() { luid = adapter.LUID() } dns := append([]netip.Addr(nil), run.dns...) - doNotRestrict := adapter != nil && configured.KillSwitch == "off" + doNotRestrict := adapter != nil && configured.KillSwitchNow() == "off" if adapter == nil && run.hold { doNotRestrict = false } diff --git a/core/internal/geo/names.go b/core/internal/geo/names.go index 89b1765..d6c80d7 100644 --- a/core/internal/geo/names.go +++ b/core/internal/geo/names.go @@ -14,6 +14,9 @@ const ( RuleDirect RuleVPN RuleBlock + // The name is in the bypass selection and no other rule spoke. Not a route yet: callers that do not know it keep + // deciding as with NoRule. + RuleBypass ) // ByName is the name half of every routing decision (flows and DNS questions use it alike). The panel's ad list blocks @@ -39,6 +42,9 @@ func (r *SiteRules) ByName(mode, name string) RuleVerdict { if mode == "selected" && r.VPN.Len() != 0 && r.VPN.Match(name) { return RuleVPN } + if r.Bypass.Len() != 0 && r.Bypass.Match(name) { + return RuleBypass + } return NoRule } @@ -117,12 +123,23 @@ type Check struct { By string `json:"by"` // mode, site, collection, region or default Rule string `json:"rule"` // the site entry or collection id that matched; empty otherwise DNS string `json:"dns"` // where the question about the name goes: direct or vpn (a blocked one is answered here) + // always: in the bypass selection, a strategy at once; auto: a strategy after a plain attempt failed; never: the + // route is not direct, the name is an exception (the direct selection), or the bypass is not in force. + Bypass string `json:"bypass"` } -// CheckName decides for a name now by the same code as the flows; resolver says that a direct resolver is known. -func (s *Store) CheckName(mode, region, name string, resolver bool) Check { - route, by := DecideName(name, mode, region, s.ActiveSiteRules()) - check := Check{Route: route, By: by, DNS: NameVPN} +// CheckName decides for a name now by the same code as the flows; resolver says that a direct resolver is known, +// bypass that the bypass is in force for direct flows. +func (s *Store) CheckName(mode, region, name string, resolver, bypass bool) Check { + rules := s.ActiveSiteRules() + route, by := DecideName(name, mode, region, rules) + check := Check{Route: route, By: by, DNS: NameVPN, Bypass: "never"} + if bypass && route == NameDirect && rules != nil && !rules.Direct.Match(name) { + check.Bypass = "auto" + if rules.Bypass.Match(name) { + check.Bypass = "always" + } + } if by == byRules { check.By, check.Rule = s.matching(route, name) } diff --git a/core/internal/geo/names_test.go b/core/internal/geo/names_test.go index d14737b..fa178f7 100644 --- a/core/internal/geo/names_test.go +++ b/core/internal/geo/names_test.go @@ -94,21 +94,21 @@ func TestCheckNameSaysWhyAndWhere(t *testing.T) { resolver bool want Check }{ - {"all", "ru", "ads.example", true, Check{"vpn", "mode", "", "vpn"}}, - {"smart", "ru", "sub.ads.example", true, Check{"block", "site", "ads.example", "vpn"}}, - {"smart", "ru", "a.tracker.example", true, Check{"block", "collection", "geosite:adlist", "vpn"}}, - {"smart", "ru", "both.example", false, Check{"block", "site", "both.example", "vpn"}}, - {"smart", "ru", "direct.example", true, Check{"direct", "site", "direct.example", "direct"}}, - {"smart", "ru", "direct.example", false, Check{"direct", "site", "direct.example", "vpn"}}, - {"smart", "ru", "yandex.ru", true, Check{"direct", "region", "", "direct"}}, - {"smart", "ru", "yandex.ru", false, Check{"direct", "region", "", "vpn"}}, - {"smart", "ru", "example.com", true, Check{"vpn", "default", "", "vpn"}}, - {"selected", "", "vpn.example", true, Check{"vpn", "site", "vpn.example", "vpn"}}, - {"selected", "ru", "example.com", true, Check{"direct", "default", "", "direct"}}, - {"selected", "", "example.com", false, Check{"direct", "default", "", "vpn"}}, + {"all", "ru", "ads.example", true, Check{"vpn", "mode", "", "vpn", "never"}}, + {"smart", "ru", "sub.ads.example", true, Check{"block", "site", "ads.example", "vpn", "never"}}, + {"smart", "ru", "a.tracker.example", true, Check{"block", "collection", "geosite:adlist", "vpn", "never"}}, + {"smart", "ru", "both.example", false, Check{"block", "site", "both.example", "vpn", "never"}}, + {"smart", "ru", "direct.example", true, Check{"direct", "site", "direct.example", "direct", "never"}}, + {"smart", "ru", "direct.example", false, Check{"direct", "site", "direct.example", "vpn", "never"}}, + {"smart", "ru", "yandex.ru", true, Check{"direct", "region", "", "direct", "never"}}, + {"smart", "ru", "yandex.ru", false, Check{"direct", "region", "", "vpn", "never"}}, + {"smart", "ru", "example.com", true, Check{"vpn", "default", "", "vpn", "never"}}, + {"selected", "", "vpn.example", true, Check{"vpn", "site", "vpn.example", "vpn", "never"}}, + {"selected", "ru", "example.com", true, Check{"direct", "default", "", "direct", "never"}}, + {"selected", "", "example.com", false, Check{"direct", "default", "", "vpn", "never"}}, } for _, test := range tests { - if got := store.CheckName(test.mode, test.region, test.name, test.resolver); got != test.want { + if got := store.CheckName(test.mode, test.region, test.name, test.resolver, false); got != test.want { t.Errorf("CheckName(%s, %q, %q, %t) = %+v; want %+v", test.mode, test.region, test.name, test.resolver, got, test.want) } } @@ -124,7 +124,7 @@ func TestCheckNameSaysWhyAndWhere(t *testing.T) { if _, _, err := other.SetRules(Rules{Direct: Selection{Collections: []string{"geosite:local"}}}); err != nil { t.Fatal(err) } - if got := other.CheckName("smart", "", "a.local.example", false); got != (Check{"direct", "collection", "geosite:local", "vpn"}) { + if got := other.CheckName("smart", "", "a.local.example", false, false); got != (Check{"direct", "collection", "geosite:local", "vpn", "never"}) { t.Errorf("direct collection: %+v", got) } } @@ -175,7 +175,7 @@ func TestPanelAdListBlocksInEveryModeAndIsLetGo(t *testing.T) { if err := os.WriteFile(filepath.Join(store.dir, "site-category-ads-all.list"), []byte("+.adnet.example\n"), 0600); err != nil { t.Fatal(err) } - if got := store.CheckName("all", "", "x.adnet.example", false); got.Route != NameVPN { + if got := store.CheckName("all", "", "x.adnet.example", false, false); got.Route != NameVPN { t.Fatalf("blocked before the preset asked for it: %+v", got) } store.SetPanelSites(nil, true) @@ -200,17 +200,17 @@ func TestPanelAdListBlocksInEveryModeAndIsLetGo(t *testing.T) { if rules.ByName("all", "adnet.example") != RuleBlock || rules.ByName("all", "direct.example") != NoRule || !rules.HasBlock { t.Error("ByName or HasBlock ignore the ad list") } - if got, want := store.CheckName("all", "", "a.adnet.example", true), (Check{"block", "collection", "geosite:category-ads-all", "vpn"}); got != want { + if got, want := store.CheckName("all", "", "a.adnet.example", true, false), (Check{"block", "collection", "geosite:category-ads-all", "vpn", "never"}); got != want { t.Errorf("CheckName = %+v; want %+v", got, want) } - if got := store.CheckName("smart", "", "a.tracker.example", false); got.Rule != "geosite:adlist" { + if got := store.CheckName("smart", "", "a.tracker.example", false, false); got.Rule != "geosite:adlist" { t.Errorf("the user's own list is no longer named: %+v", got) } // the preset stops asking: the list goes, and the names with it store.SetPanelSites(nil, false) rules = store.ActiveSiteRules() - if rules.Ads != nil || rules.ByName("all", "adnet.example") != NoRule || store.CheckName("all", "", "adnet.example", false).Route != NameVPN { + if rules.Ads != nil || rules.ByName("all", "adnet.example") != NoRule || store.CheckName("all", "", "adnet.example", false, false).Route != NameVPN { t.Error("the ad list stayed after the preset dropped it") } if _, ok := store.siteSet("geosite:category-ads-all"); ok { @@ -294,3 +294,102 @@ func TestNormalizeSiteDomain(t *testing.T) { } } } + +func TestBypassRules(t *testing.T) { + dir := t.TempDir() + store, err := Open(dir) + if err != nil { + t.Fatal(err) + } + // a file written before the bypass selection existed + if got := store.GetRules().Bypass; got.Sites == nil || len(got.Sites)+len(got.Collections)+len(got.Apps) != 0 { + t.Fatalf("no file: %#v", got) + } + for _, bad := range []Rules{ + {Bypass: Selection{Apps: []string{`c:\a\a.exe`}}}, + {Bypass: Selection{Collections: []string{"service:"}}}, + {Bypass: Selection{Collections: []string{"service:Video"}}}, + {Bypass: Selection{Collections: []string{"service:a b"}}}, + } { + if _, _, err := store.SetRules(bad); err != ErrBadRules { + t.Errorf("SetRules(%+v) = %v", bad, err) + } + } + rules := Rules{ + Direct: Selection{Sites: []string{"plain.example", "both.example"}}, + VPN: Selection{Sites: []string{"vpn.example"}}, + Block: Selection{Sites: []string{"ads.example"}}, + Bypass: Selection{Sites: []string{"slow.example", "both.example", "vpn.example", "ads.example"}, Collections: []string{"service:video", "service:gone"}}, + } + if _, changed, err := store.SetRules(rules); err != nil || !changed { + t.Fatal(changed, err) + } + // no catalogue yet: a service has no names + if got := store.ActiveSiteRules().ByName("selected", "video.example"); got != NoRule { + t.Fatalf("no catalogue: %v", got) + } + store.SetServices(func(id string) []string { + if id == "video" { + return []string{"video.example", "Bad Name", "cdn.video.example"} + } + return nil + }) + active := store.ActiveSiteRules() + if !active.HasBypass { + t.Fatal("HasBypass is false") + } + for _, test := range []struct { + mode, name string + want RuleVerdict + }{ + {"all", "slow.example", NoRule}, + {"smart", "slow.example", RuleBypass}, + {"selected", "a.slow.example", RuleBypass}, + {"selected", "a.video.example", RuleBypass}, // a service of the catalogue + {"smart", "both.example", RuleDirect}, // an exception wins + {"selected", "vpn.example", RuleVPN}, + {"smart", "ads.example", RuleBlock}, + {"selected", "other.example", NoRule}, + } { + if got := active.ByName(test.mode, test.name); got != test.want { + t.Errorf("ByName(%s, %s) = %v; want %v", test.mode, test.name, got, test.want) + } + } + // today's callers read a bypass name as one without a rule + if route, by := DecideName("slow.example", "smart", "", active); route != NameVPN || by != byDefault { + t.Errorf("DecideName = %s, %s", route, by) + } + for _, test := range []struct { + mode, name string + bypass bool + want string + }{ + {"selected", "slow.example", true, "always"}, + {"selected", "video.example", true, "always"}, + {"selected", "other.example", true, "auto"}, + {"selected", "other.example", false, "never"}, + {"selected", "vpn.example", true, "never"}, // through the VPN + {"smart", "both.example", true, "never"}, // direct, but an exception + {"selected", "both.example", true, "never"}, // an exception in every mode + {"smart", "ads.example", true, "never"}, + {"all", "slow.example", true, "never"}, + } { + if got := store.CheckName(test.mode, "", test.name, false, test.bypass).Bypass; got != test.want { + t.Errorf("CheckName(%s, %s, %t).Bypass = %s; want %s", test.mode, test.name, test.bypass, got, test.want) + } + } + routes := store.Routes("selected", "none", "") + var seen int + for _, c := range routes.Collections { + if c.ID == "service:video" && c.Available && c.Entries == 2 || c.ID == "service:gone" && !c.Available { + seen++ + } + } + if seen != 2 { + t.Errorf("collections: %+v", routes.Collections) + } + again, err := Open(dir) // a restart + if err != nil || !sameRules(again.GetRules(), store.GetRules()) { + t.Fatalf("after a restart: %+v, %v", again.GetRules(), err) + } +} diff --git a/core/internal/geo/routes.go b/core/internal/geo/routes.go index 2ee6cb1..ee7e9da 100644 --- a/core/internal/geo/routes.go +++ b/core/internal/geo/routes.go @@ -27,6 +27,8 @@ type Rules struct { Direct Selection `json:"direct"` VPN Selection `json:"vpn"` Block Selection `json:"block"` + // Sites and services that get a bypass strategy at once. No programs. A file written before it has none. + Bypass Selection `json:"bypass"` } type SiteCollection struct { @@ -40,8 +42,10 @@ type SiteRules struct { Direct *SiteSet VPN *SiteSet Block *SiteSet + Bypass *SiteSet // read after every other rule: block, direct and vpn win HasDirect bool HasVPN bool + HasBypass bool HasBlock bool // the user's block rules, or the panel's ad list (flows are read for their names then) // The panel's ad list when its preset blocks ads and the list is loaded, else nil. ByName checks it first, in every mode. Ads *SiteSet @@ -59,7 +63,7 @@ func emptySelection() Selection { } func emptyRules() Rules { - return Rules{Direct: emptySelection(), VPN: emptySelection(), Block: emptySelection()} + return Rules{Direct: emptySelection(), VPN: emptySelection(), Block: emptySelection(), Bypass: emptySelection()} } func (s *Store) loadRules() { @@ -202,6 +206,8 @@ func (s *Store) rebuildSiteRules() { add(direct, rules.Direct) add(vpn, rules.VPN) add(block, rules.Block) + bypass := &SiteSet{domains: make(map[string]struct{})} + add(bypass, rules.Bypass) s.mu.Lock() panelNames, blockAds := slices.Clone(s.panelSites), s.blockAds s.mu.Unlock() @@ -221,6 +227,8 @@ func (s *Store) rebuildSiteRules() { Direct: direct, VPN: vpn, Block: block, + Bypass: bypass, + HasBypass: len(rules.Bypass.Collections)+len(rules.Bypass.Sites) != 0, HasDirect: len(rules.Direct.Collections)+len(rules.Direct.Sites) != 0, HasVPN: len(rules.VPN.Collections)+len(rules.VPN.Sites) != 0, HasBlock: len(rules.Block.Collections)+len(rules.Block.Sites) != 0 || ads.Len() != 0, @@ -257,7 +265,11 @@ func normalizeRules(rules Rules) (Rules, error) { if err != nil { return Rules{}, err } - return Rules{Direct: direct, VPN: vpn, Block: block}, nil + bypass, err := normalizeSelection(rules.Bypass, false) + if err != nil { + return Rules{}, err + } + return Rules{Direct: direct, VPN: vpn, Block: block, Bypass: bypass}, nil } func normalizeSelection(selection Selection, allowApps bool) (Selection, error) { @@ -267,7 +279,7 @@ func normalizeSelection(selection Selection, allowApps bool) (Selection, error) collections := make([]string, 0, len(selection.Collections)) seen := make(map[string]struct{}, len(selection.Collections)) for _, collection := range selection.Collections { - if _, _, ok := siteCachePath("", collection); !ok { + if !validCollection(collection) { return Selection{}, ErrBadRules } if _, ok := seen[collection]; !ok { @@ -345,6 +357,7 @@ func cloneRules(rules Rules) Rules { Direct: cloneSelection(rules.Direct), VPN: cloneSelection(rules.VPN), Block: cloneSelection(rules.Block), + Bypass: cloneSelection(rules.Bypass), } } @@ -353,7 +366,7 @@ func cloneSelection(s Selection) Selection { } func sameRules(a, b Rules) bool { - return sameSelection(a.Direct, b.Direct) && sameSelection(a.VPN, b.VPN) && sameSelection(a.Block, b.Block) + return sameSelection(a.Direct, b.Direct) && sameSelection(a.VPN, b.VPN) && sameSelection(a.Block, b.Block) && sameSelection(a.Bypass, b.Bypass) } func sameSelection(a, b Selection) bool { @@ -373,9 +386,9 @@ func sameStrings(a, b []string) bool { } func ruleCollections(rules Rules) []string { - seen := make(map[string]struct{}, len(rules.Direct.Collections)+len(rules.VPN.Collections)+len(rules.Block.Collections)) - collections := make([]string, 0, len(seen)) - for _, collection := range slices.Concat(rules.Direct.Collections, rules.VPN.Collections, rules.Block.Collections) { + seen := make(map[string]struct{}) + var collections []string + for _, collection := range slices.Concat(rules.Direct.Collections, rules.VPN.Collections, rules.Block.Collections, rules.Bypass.Collections) { if _, ok := seen[collection]; !ok { seen[collection] = struct{}{} collections = append(collections, collection) @@ -383,3 +396,59 @@ func ruleCollections(rules Rules) []string { } return collections } + +// A collection is a list that is downloaded ("geosite:", "list:") or a service of the bypass catalogue ("service:"). +func validCollection(collection string) bool { + if _, ok := serviceID(collection); ok { + return true + } + _, _, ok := siteCachePath("", collection) + return ok +} + +func serviceID(collection string) (string, bool) { + id, ok := strings.CutPrefix(collection, "service:") + if !ok || id == "" || len(id) > 32 { + return "", false + } + for _, c := range []byte(id) { + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_') { + return "", false + } + } + return id, true +} + +// SetServices gives the catalogue: the domains of a service by its id (nil for one it does not know). The catalogue +// lives outside this package; a new one is given by calling this again. +func (s *Store) SetServices(domains func(id string) []string) { + if s == nil { + return + } + s.mu.Lock() + s.services = domains + s.mu.Unlock() + s.rebuildSiteRules() + s.signalChange() +} + +// serviceSet reads a service's domains from the catalogue now: nothing is cached but the result. s.mu is held. +func (s *Store) serviceSet(collection, id string) *SiteSet { + delete(s.siteSets, collection) + if s.services == nil { + return nil + } + var set *SiteSet + for _, domain := range s.services(id) { + if domain, ok := normalizeSiteDomain(domain); ok { + if set == nil { + set = &SiteSet{} + } + set.add(domain) + } + } + if set != nil { + s.siteSets[collection] = set + } + return set +} diff --git a/core/internal/geo/sites.go b/core/internal/geo/sites.go index ebb4fbe..cbc9884 100644 --- a/core/internal/geo/sites.go +++ b/core/internal/geo/sites.go @@ -123,6 +123,12 @@ func (s *Store) Sites(collection string) (*SiteSet, bool) { if s == nil { return nil, false } + if id, ok := serviceID(collection); ok { + s.mu.Lock() + set := s.serviceSet(collection, id) + s.mu.Unlock() + return set, set != nil + } path, _, ok := siteCachePath(s.dir, collection) if !ok { return nil, false diff --git a/core/internal/geo/store.go b/core/internal/geo/store.go index bd3299a..7635b90 100644 --- a/core/internal/geo/store.go +++ b/core/internal/geo/store.go @@ -185,8 +185,9 @@ type Store struct { siteLoaded map[string]bool siteRefreshing map[string]bool rules Rules - panelSites []string // "geosite:" lists the panel's DNS split names; kept beside the rules' own - blockAds bool // the panel's preset blocks adsList; the list is one of panelSites then + services func(id string) []string // the bypass catalogue, see SetServices + panelSites []string // "geosite:" lists the panel's DNS split names; kept beside the rules' own + blockAds bool // the panel's preset blocks adsList; the list is one of panelSites then rulesCompileMu sync.Mutex siteRules atomic.Pointer[SiteRules] suggest *Tracker diff --git a/core/internal/ipc/protocol_test.go b/core/internal/ipc/protocol_test.go index d030a0c..a46063d 100644 --- a/core/internal/ipc/protocol_test.go +++ b/core/internal/ipc/protocol_test.go @@ -122,7 +122,7 @@ func TestSettingsMethodsAndEvent(t *testing.T) { t.Fatal(parseErr) } result, _, rpcErr = server.dispatch(context.Background(), request, true) - want := settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "all", RouteRegion: "auto", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto"} + want := settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "all", RouteRegion: "auto", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto", Mode: "vpn", BypassDirect: true} if rpcErr != nil || result != want { t.Fatalf("settings.set = %#v, %#v; want %#v", result, rpcErr, want) } @@ -145,14 +145,14 @@ func TestSettingsMethodsAndEvent(t *testing.T) { if parseErr != nil { t.Fatal(parseErr) } - if result, _, rpcErr = server.dispatch(context.Background(), request, true); rpcErr != nil || result != (settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "smart", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto"}) { + if result, _, rpcErr = server.dispatch(context.Background(), request, true); rpcErr != nil || result != (settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "smart", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto", Mode: "vpn", BypassDirect: true}) { t.Fatalf("route settings.set = %#v, %#v", result, rpcErr) } request, parseErr = ParseRequest([]byte(`{"id":11,"method":"settings.set","params":{"route_mode":"selected"}}`)) if parseErr != nil { t.Fatal(parseErr) } - if result, _, rpcErr = server.dispatch(context.Background(), request, true); rpcErr != nil || result != (settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "selected", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto"}) { + if result, _, rpcErr = server.dispatch(context.Background(), request, true); rpcErr != nil || result != (settings.Settings{KillSwitch: "off", LAN: false, Protocol: "auto", RouteMode: "selected", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto", Mode: "vpn", BypassDirect: true}) { t.Fatalf("selected route settings.set = %#v, %#v", result, rpcErr) } request, parseErr = ParseRequest([]byte(`{"id":10,"method":"routes.get","params":{}}`)) diff --git a/core/internal/ipc/routes_check_test.go b/core/internal/ipc/routes_check_test.go index 14792b8..0f1f133 100644 --- a/core/internal/ipc/routes_check_test.go +++ b/core/internal/ipc/routes_check_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "strings" "testing" "github.com/mistgate/mistgate-client/core/internal/engine" @@ -37,7 +38,7 @@ func checkServer(t *testing.T, withCheck bool) (*Server, *settings.Store, func(m if withCheck { server.Check = func(name string) geo.Check { configured := settingsStore.Get() - return geoStore.CheckName(configured.RouteMode, "ru", name, true) + return geoStore.CheckName(configured.RouteMode, "ru", name, true, false) } } call := func(method, params string) (any, *RPCError) { @@ -108,12 +109,12 @@ func TestRoutesCheck(t *testing.T) { mode, site string want geo.Check }{ - {"all", "ads.example", geo.Check{Route: "vpn", By: "mode", Rule: "", DNS: "vpn"}}, - {"smart", "https://Sub.Ads.Example/path", geo.Check{Route: "block", By: "site", Rule: "ads.example", DNS: "vpn"}}, - {"smart", "direct.example", geo.Check{Route: "direct", By: "site", Rule: "direct.example", DNS: "direct"}}, - {"smart", "yandex.ru.", geo.Check{Route: "direct", By: "region", Rule: "", DNS: "direct"}}, - {"smart", "example.com", geo.Check{Route: "vpn", By: "default", Rule: "", DNS: "vpn"}}, - {"selected", "example.com", geo.Check{Route: "direct", By: "default", Rule: "", DNS: "direct"}}, + {"all", "ads.example", geo.Check{Route: "vpn", By: "mode", Rule: "", DNS: "vpn", Bypass: "never"}}, + {"smart", "https://Sub.Ads.Example/path", geo.Check{Route: "block", By: "site", Rule: "ads.example", DNS: "vpn", Bypass: "never"}}, + {"smart", "direct.example", geo.Check{Route: "direct", By: "site", Rule: "direct.example", DNS: "direct", Bypass: "never"}}, + {"smart", "yandex.ru.", geo.Check{Route: "direct", By: "region", Rule: "", DNS: "direct", Bypass: "never"}}, + {"smart", "example.com", geo.Check{Route: "vpn", By: "default", Rule: "", DNS: "vpn", Bypass: "never"}}, + {"selected", "example.com", geo.Check{Route: "direct", By: "default", Rule: "", DNS: "direct", Bypass: "never"}}, } for _, test := range tests { if _, err := settingsStore.Set(map[string]json.RawMessage{"route_mode": json.RawMessage(fmt.Sprintf("%q", test.mode))}); err != nil { @@ -126,13 +127,24 @@ func TestRoutesCheck(t *testing.T) { t.Errorf("routes.check(%s, %s) = %#v, %#v; want %+v", test.mode, test.site, result, rpcErr, test.want) } } + // the bypass selection is set like the others, and an omitted key keeps it + if _, rpcErr := call("routes.set", `{"bypass":{"sites":["slow.example"],"collections":["service:video"]}}`); rpcErr != nil { + t.Fatal(rpcErr) + } + kept, rpcErr := call("routes.set", `{"direct":{"sites":["direct.example"]}}`) + if text, _ := json.Marshal(kept); rpcErr != nil || !strings.Contains(string(text), `"bypass":{"collections":["service:video"],"sites":["slow.example"],"apps":[]}`) { + t.Fatalf("bypass after another set: %s, %v", text, rpcErr) + } + if _, rpcErr := call("routes.set", `{"bypass":{"apps":["c:\\a\\a.exe"]}}`); rpcErr == nil { + t.Fatal("a program in the bypass selection was accepted") + } // the wire shape if _, err := settingsStore.Set(map[string]json.RawMessage{"route_mode": json.RawMessage(`"smart"`)}); err != nil { t.Fatal(err) } result, _ := call("routes.check", `{"site":"ads.example"}`) encoded, _ := json.Marshal(result) - if string(encoded) != `{"route":"block","by":"site","rule":"ads.example","dns":"vpn"}` { + if string(encoded) != `{"route":"block","by":"site","rule":"ads.example","dns":"vpn","bypass":"never"}` { t.Errorf("wire = %s", encoded) } diff --git a/core/internal/ipc/server.go b/core/internal/ipc/server.go index 650b962..97e6404 100644 --- a/core/internal/ipc/server.go +++ b/core/internal/ipc/server.go @@ -326,6 +326,10 @@ func (s *Server) handle(ctx context.Context, request Request, trusted bool) (any if !mergeSelection(raw, &rules.Block) { return nil, nil, badParams() } + case "bypass": + if !mergeSelection(raw, &rules.Bypass) { + return nil, nil, badParams() + } default: return nil, nil, badParams() } diff --git a/core/internal/netcfg/netcfg_windows.go b/core/internal/netcfg/netcfg_windows.go index 78bf8e7..ede6b97 100644 --- a/core/internal/netcfg/netcfg_windows.go +++ b/core/internal/netcfg/netcfg_windows.go @@ -33,7 +33,8 @@ type Config struct { MTU int Addresses []netip.Prefix DNS []netip.Addr - Bypass netip.Addr + // The server's address, which keeps its route through the physical interface. Invalid: there is no server (bypass). + Bypass netip.Addr } type Adapter struct { @@ -97,7 +98,7 @@ func (a *Adapter) Configure(cfg Config) error { if a.configured { return errors.New("Wintun adapter is already configured") } - if cfg.MTU < 576 || !cfg.Bypass.IsValid() { + if cfg.MTU < 576 { return errors.New("invalid Wintun configuration") } hasIPv4 := false @@ -119,8 +120,10 @@ func (a *Adapter) Configure(cfg Config) error { if err := a.luid.SetIPAddresses(cfg.Addresses); err != nil { return fmt.Errorf("assign Wintun addresses: %w", err) } - if err := a.addBypass(cfg.Bypass); err != nil { - return err + if cfg.Bypass.IsValid() { + if err := a.addBypass(cfg.Bypass); err != nil { + return err + } } for _, route := range []struct { prefix netip.Prefix diff --git a/core/internal/session/manager.go b/core/internal/session/manager.go index 83d9a45..db61045 100644 --- a/core/internal/session/manager.go +++ b/core/internal/session/manager.go @@ -484,7 +484,7 @@ func (m *Manager) run() { m.lastRoutes = m.routes.Snapshot() m.hasRoutes = true } - if m.engine != nil && m.currentSettings().KillSwitch == "always" && m.engine.Hold() { + if m.engine != nil && m.currentSettings().KillSwitchNow() == "always" && m.engine.Hold() { state.status = Status{State: "blocked", SinceUnix: time.Now().Unix(), Error: "kill_switch"} m.hub.Publish("status", state.status) } @@ -619,7 +619,7 @@ func (m *Manager) run() { if m.nextPath(&state, code, request.info.ServerID) { continue } - always := m.currentSettings().KillSwitch == "always" + always := m.currentSettings().KillSwitchNow() == "always" retry := false byRule := state.status.WhitelistByRule switch { @@ -832,7 +832,7 @@ func (m *Manager) connect(state *actorState, target engine.Target, atStart bool) // StepVerify means an in-progress attempt has brought its tunnel up; replacing it must keep the firewall closed. connectingWithTunnel := state.status.State == "connecting" && (state.target.Hold || state.status.Step == string(engine.StepVerify)) - switching := (state.status.State == "connected" || connectingWithTunnel) && settingsNow.KillSwitch != "off" + switching := (state.status.State == "connected" || connectingWithTunnel) && settingsNow.KillSwitchNow() != "off" // Only while a session is being brought back: the idle hold of "always" (blocked, kill_switch) is no session, and a // person who picks Auto there after a named server must get Auto. if reconnecting { @@ -1189,7 +1189,7 @@ func (m *Manager) stop(state *actorState) { state.probeCancel() state.probeCancel = nil } - held := m.engine != nil && m.currentSettings().KillSwitch == "always" && m.engine.Hold() + held := m.engine != nil && m.currentSettings().KillSwitchNow() == "always" && m.engine.Hold() m.endLive(state) state.nextReason, state.prefer, state.returned = "", "", false state.generation++ @@ -1247,7 +1247,7 @@ func (m *Manager) settingsChanged(state *actorState) { state.attemptPath = path } state.target.Hold = m.retryHold(state, configured) - if configured.KillSwitch == "off" && !state.holdReconnect && state.status.State == "reconnecting" { + if configured.KillSwitchNow() == "off" && !state.holdReconnect && state.status.State == "reconnecting" { wasRunning := state.runCancel != nil if wasRunning { state.runCancel() @@ -1261,12 +1261,12 @@ func (m *Manager) settingsChanged(state *actorState) { } } case "off", "error": - if configured.KillSwitch == "always" && m.engine != nil && m.engine.Hold() { + if configured.KillSwitchNow() == "always" && m.engine != nil && m.engine.Hold() { state.status = Status{State: "blocked", SinceUnix: time.Now().Unix(), Error: "kill_switch"} m.hub.Publish("status", state.status) } case "blocked": - if state.status.Error == "kill_switch" && configured.KillSwitch != "always" { + if state.status.Error == "kill_switch" && configured.KillSwitchNow() != "always" { if m.engine != nil { m.engine.Stop() } @@ -1274,7 +1274,7 @@ func (m *Manager) settingsChanged(state *actorState) { state.status = Status{State: "off"} state.target = engine.Target{} m.hub.Publish("status", state.status) - } else if configured.KillSwitch == "always" && m.engine != nil { + } else if configured.KillSwitchNow() == "always" && m.engine != nil { m.engine.Reapply() } } @@ -1503,7 +1503,7 @@ func (m *Manager) retryHold(state *actorState, configured settings.Settings) boo } func holdFor(configured settings.Settings, reconnecting bool) bool { - return configured.KillSwitch == "always" || reconnecting && configured.KillSwitch != "off" + return configured.KillSwitchNow() == "always" || reconnecting && configured.KillSwitchNow() != "off" } func (m *Manager) backoffAt(index int) time.Duration { diff --git a/core/internal/settings/store.go b/core/internal/settings/store.go index fd9d4d0..ec96bf1 100644 --- a/core/internal/settings/store.go +++ b/core/internal/settings/store.go @@ -42,6 +42,10 @@ type Settings struct { ProxyLAN bool `json:"proxy_lan"` // Try the panel's marked whitelist path after every ordinary path in the failover round has failed. WhitelistAuto bool `json:"whitelist_auto"` + // What connect does: "vpn" goes through a server, "bypass" needs none. BypassDirect: in "vpn" the direct flows of + // smart and selected get the bypass too. + Mode string `json:"mode"` + BypassDirect bool `json:"bypass_direct"` } type Store struct { @@ -54,7 +58,16 @@ type Store struct { var ErrBadParams = errors.New("bad settings parameters") func Defaults() Settings { - return Settings{KillSwitch: "while", LAN: true, Protocol: "auto", RouteMode: "all", RouteRegion: "auto", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto"} + return Settings{KillSwitch: "while", LAN: true, Protocol: "auto", RouteMode: "all", RouteRegion: "auto", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto", Mode: "vpn", BypassDirect: true} +} + +// KillSwitchNow is the kill switch that is in force: without a server there is no tunnel whose loss could leak, so +// "bypass" never holds the network. +func (s Settings) KillSwitchNow() string { + if s.Mode == "bypass" { + return "off" + } + return s.KillSwitch } // DNSAddrs is nil for "auto". @@ -140,6 +153,12 @@ func apply(value *Settings, key string, raw json.RawMessage) bool { return false } value.KillSwitch = v + case "mode": + var v string + if json.Unmarshal(raw, &v) != nil || v != "vpn" && v != "bypass" { + return false + } + value.Mode = v case "lan": var v bool if !strictBool(raw, &v) { @@ -170,7 +189,7 @@ func apply(value *Settings, key string, raw json.RawMessage) bool { return false } value.RouteRegion = v - case "autoconnect", "restore", "last_on", "last_up", "proxy", "proxy_lan", "whitelist_auto", "auto_switch": + case "autoconnect", "restore", "last_on", "last_up", "proxy", "proxy_lan", "whitelist_auto", "auto_switch", "bypass_direct": var v bool if !strictBool(raw, &v) { return false @@ -186,6 +205,8 @@ func apply(value *Settings, key string, raw json.RawMessage) bool { value.ProxyLAN = v case "whitelist_auto": value.WhitelistAuto = v + case "bypass_direct": + value.BypassDirect = v case "auto_switch": value.AutoSwitch = v case "last_up": @@ -233,7 +254,7 @@ func apply(value *Settings, key string, raw json.RawMessage) bool { func knownKey(key string) bool { switch key { - case "kill_switch", "lan", "protocol", "game", "route_mode", "route_region", "autoconnect", "restore", "last_on", "last_up", "proxy", "proxy_lan", "whitelist_auto", "auto_switch", "on_server_down", "dns", "mtu", "last_server", "last_sub": + case "kill_switch", "lan", "protocol", "game", "route_mode", "route_region", "autoconnect", "restore", "last_on", "last_up", "proxy", "proxy_lan", "whitelist_auto", "auto_switch", "on_server_down", "dns", "mtu", "last_server", "last_sub", "mode", "bypass_direct": return true default: return false diff --git a/core/internal/settings/store_test.go b/core/internal/settings/store_test.go index 94021c2..d59a10d 100644 --- a/core/internal/settings/store_test.go +++ b/core/internal/settings/store_test.go @@ -25,7 +25,7 @@ func TestStoreRoundTripAndChanges(t *testing.T) { "route_mode": json.RawMessage(`"smart"`), "route_region": json.RawMessage(`"ru"`), } - if got, err := store.Set(patch); err != nil || got != (Settings{KillSwitch: "always", LAN: false, Protocol: "awg", Game: true, RouteMode: "smart", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto"}) { + if got, err := store.Set(patch); err != nil || got != (Settings{KillSwitch: "always", LAN: false, Protocol: "awg", Game: true, RouteMode: "smart", RouteRegion: "ru", OnServerDown: "reconnect", AutoSwitch: true, DNS: "auto", Mode: "vpn", BypassDirect: true}) { t.Fatalf("Set() = %#v, %v", got, err) } select { @@ -250,3 +250,20 @@ func TestAutoSwitchKey(t *testing.T) { t.Fatalf("reopened = %#v, %v: the key was not saved", reopened.Get(), err) } } + +func TestMode(t *testing.T) { + store, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if got := store.Get(); got.Mode != "vpn" || !got.BypassDirect || got.KillSwitchNow() != "while" { + t.Fatalf("defaults: %#v", got) + } + if _, err := store.Set(map[string]json.RawMessage{"mode": json.RawMessage(`"proxy"`)}); err != ErrBadParams { + t.Fatalf("an unknown mode: %v", err) + } + got, err := store.Set(map[string]json.RawMessage{"mode": json.RawMessage(`"bypass"`), "kill_switch": json.RawMessage(`"always"`), "bypass_direct": json.RawMessage(`false`)}) + if err != nil || got.KillSwitch != "always" || got.KillSwitchNow() != "off" || got.BypassDirect { + t.Fatalf("bypass: %#v, %v", got, err) + } +} diff --git a/docs/ipc.md b/docs/ipc.md index bbf4e83..c312b8d 100644 --- a/docs/ipc.md +++ b/docs/ipc.md @@ -96,8 +96,8 @@ at home or on the same PC is a real case. | `routes.get` | none | Route state, rules, and named collection status | | `routes.update` | none | The `routes.get` object as it is now; the downloads go on in the background and a `routes` event follows when they end | | `routes.lists` | none | `{"lists": [{"id": "", "entries": N, "updated_unix": N, "error": ""}], "unique": N, "duplicates": N}` | -| `routes.set` | `{"direct": Selection, "vpn": Selection, "block": Selection}` (any key may be omitted; an omitted one keeps what is stored). A `Selection` is `{"collections": [...], "sites": [...], "apps": [...]}`, any key may be omitted too, and an omitted one keeps what is stored | The `routes.get` object | -| `routes.check` | `{"site": ""}`; a host name or an https URL of one, checked like a site entry | `{"route": "direct" \| "vpn" \| "block", "by": "mode" \| "site" \| "collection" \| "region" \| "default", "rule": "", "dns": "direct" \| "vpn"}` | +| `routes.set` | `{"direct": Selection, "vpn": Selection, "block": Selection, "bypass": Selection}` (any key may be omitted; an omitted one keeps what is stored). A `Selection` is `{"collections": [...], "sites": [...], "apps": [...]}`, any key may be omitted too, and an omitted one keeps what is stored | The `routes.get` object | +| `routes.check` | `{"site": ""}`; a host name or an https URL of one, checked like a site entry | `{"route": "direct" \| "vpn" \| "block", "by": "mode" \| "site" \| "collection" \| "region" \| "default", "rule": "", "dns": "direct" | "vpn", "bypass": "always" | "auto" | "never"}` || "vpn"}` | | `routes.dismiss` | `{"route": "direct" \| "vpn", "site": ""}`; `route` is the `suggest` list the site was in | The `routes.get` object | | `apps.list` | none; a trusted caller only | `{"apps": [{"path": "c:\\tools\\app.exe", "name": "App", "running": true}]}`: the programs for the "Programs" tab (see "Rules by program") | | `diag.run` | `{"sub": ""}` (optional; empty selects the first subscription) | Diagnostic State | @@ -305,7 +305,10 @@ Settings are saved as plain JSON in `\settings.json`; a missing `kill_switch` is `off`, `while`, or `always` (default `while`); `lan` allows private and link-local addresses through the kill switch (default `true`); `protocol` is `auto`, `hysteria2`, `awg`, `vless` or `trusttunnel` (default `auto`); `game` prefers AWG when protocol selection is automatic (default `false`); `route_mode` is `all`, `smart`, or `selected` (default `all`), and -`route_region` is `auto`, `none`, or a two-letter lower-case country code (default `auto`). `settings.set` accepts only these keys, updates only the keys +`route_region` is `auto`, `none`, or a two-letter lower-case country code (default `auto`). `mode` is `vpn` or `bypass` +(default `vpn`): what `connect` does. In `bypass` no server is used and the kill switch is not in force whatever `kill_switch` says: the +network is never held, and the service start connects by `autoconnect` or `restore` without a `last_server`. `bypass_direct` (default `true`) +gives the bypass to the direct flows of `smart` and `selected` in `vpn`. The engine has no `bypass` branch yet: the two keys are stored and nothing more. `settings.set` accepts only these keys, updates only the keys provided, and returns `bad_params` for an unknown key or invalid value. Changes apply immediately to the active firewall policy and are pushed to subscribers of `settings` as a Settings object. When `connect.protocol` is omitted or `auto`, automatic selection uses the configured `protocol`; when that is also `auto`, `game: true` prefers AWG if @@ -624,9 +627,17 @@ name that has such a resolver. A `geosite:` list the panel names is loaded like cache, downloaded when stale) when the tunnel starts, and read from memory only: a name is matched against a list once it has loaded. These lists are not in `routes.lists`. All of it is read when the tunnel starts (a new `sync` applies to the next connect). +The `bypass` selection names the sites and services that get a bypass strategy at once; it takes no programs, and +rules saved before it existed read as an empty one. A name in it is read after every other rule: `block`, `direct` +(an exception: never a strategy) and `vpn` win. `routes.check` answers `bypass`: `always` (in the selection), `auto` +(a strategy after a plain attempt failed) or `never` (the route is not direct, the name is an exception, or the bypass +is not in force). No flow gets a strategy yet, so the answer is `never` for now. + Each selection accepts at most 200 collections and 500 sites. A collection is `geosite:` (lower-case letters, digits, `!`, `@`, and `-`, up to 48 characters) or `list:` (up to 512 URL characters, HTTPS only, no -credentials). GeoSite collections are fetched from MetaCubeX with a jsDelivr fallback. Lists are limited to 8 MiB, +credentials). `service:` (lower-case letters, digits, `-` and `_`, up to 32 characters) is a +service of the bypass catalogue: its domains come from the catalogue, nothing is downloaded, and it is not available +while the catalogue does not know the id. GeoSite collections are fetched from MetaCubeX with a jsDelivr fallback. Lists are limited to 8 MiB, fetched with a 20-second timeout, cached in `\geo\` for 24 hours, and refreshed in the background; a valid stale cache remains usable while refreshing. A site is a hostname whose labels contain letters, digits, or hyphens. An HTTPS URL such as `https://Example.com/x` is accepted and stored as `example.com`. Sites