From 41be3dfba83b53a6eedc9e6ba1e97c21ea504a10 Mon Sep 17 00:00:00 2001 From: jeffjiang Date: Mon, 23 Nov 2026 07:50:02 +0800 Subject: [PATCH 1/2] Add app store commands to clash-cli profiles, rules append/remove and dns policy drive the App's configuration store through the new app-store-v1 controller capability. The store only accepts writes on the App Group socket, so the client gained --socket/CLASH_SOCKET: a controller listener stays read-only for these endpoints, and a refusal says so instead of blaming the secret. --- cli/HELP.txt | 57 +++- cli/appstore.go | 498 +++++++++++++++++++++++++++++ cli/appstore_test.go | 728 +++++++++++++++++++++++++++++++++++++++++++ cli/args.go | 8 +- cli/commands.go | 12 +- cli/main.go | 18 +- cli/session.go | 45 ++- 7 files changed, 1351 insertions(+), 15 deletions(-) create mode 100644 cli/appstore.go create mode 100644 cli/appstore_test.go diff --git a/cli/HELP.txt b/cli/HELP.txt index 7379189a..84b8101c 100644 --- a/cli/HELP.txt +++ b/cli/HELP.txt @@ -1,6 +1,6 @@ --- name: clash-cli -description: 通过 Clash App 内置的 clash-cli,在 Mac 终端里实时监控和控制 Clash App(本机 Mac,或局域网里的 iPhone / iPad / Apple TV)。支持状态/连接/流量/规则查询、规则命中分析、节点与策略组切换、节点测速、DNS 查询。当用户提到 Clash App、切换节点、查看连接、实时流量、规则匹配、节点测速、外部控制器时使用。 +description: 通过 Clash App 内置的 clash-cli,在 Mac 终端里实时监控和控制 Clash App(本机 Mac,或局域网里的 iPhone / iPad / Apple TV)。支持状态/连接/流量/规则查询、规则命中分析、节点与策略组切换、节点测速、DNS 查询,以及 App 配置里追加规则与 DNS 策略的读写。当用户提到 Clash App、切换节点、查看连接、实时流量、规则匹配、节点测速、外部控制器、追加规则、nameserver-policy 时使用。 --- # Clash App 控制器(Clash App 内置的 clash-cli) @@ -60,7 +60,9 @@ clash-cli status | `clash-cli traffic [秒]` | 实时流量(瞬时速率 + 累计) | | `clash-cli connections [N]` | 活跃连接列表(host → 策略链 → 命中规则 → 上下行),默认前 20 | | `clash-cli configs` | 当前运行配置(端口/tun/dns 等),只输出 JSON,可直接接 `jq`;`--json` 是控制器原样的回答。端口实际监听在哪看 `clash-cli status`:port、socks-port、mixed-port、redir-port、tproxy-port 先看 `allow-lan`,关着时只在 127.0.0.1 上,`bind-address` 写什么都不起作用;开着时才按 `bind-address`(没写就是 `*`),再由 `lan-allowed-ips`/`lan-disallowed-ips` 筛设备。App 里「允许局域网连接」关着时会把 `allow-lan` 改成 false。`listeners:` 里自己写的监听不归它管 | -| `clash-cli rules [N]` | 规则列表(默认前 10,0 = 全部) | +| `clash-cli rules [N]` | 规则列表(默认前 10,0 = 全部);这是运行态,改配置见 §4 的配置库 | +| `clash-cli profiles` | App 里的配置列表(`*` 当前),带追加规则条数;`--json` 是控制器原样的回答 | +| `clash-cli dns policy [--profile ]` | 这份配置的 DNS 策略:`nameserver-policy` 与 `fake-ip-filter`(缺省当前配置) | | `clash-cli rule match <域名\|IP\|URL>` | **规则命中分析**:这条连接会命中哪条规则、走哪条链 | | `clash-cli provider list` | 节点集与规则集 | | `clash-cli dns query <域名> [type]` | 走内核 DNS 查询,返回 Answer 数组 | @@ -98,7 +100,7 @@ clash-cli status ## 4. 影响边界(写操作) - **写操作**:`proxy set`、`mode`、`group unfix`、`group test`、`provider update`、`conn close `、`flush` - 会改变运行状态,执行前先确认目标存在(`proxy get`、`proxies`、`connections`)。 + 会改变运行状态;`rules append|remove`、`dns policy set|clear` 会改配置库(见本节末尾)。执行前先确认目标存在(`proxy get`、`proxies`、`connections`、`profiles`)。 每次写操作前,人读输出会先打印要改的是哪台设备、哪个内核版本。 - `provider update` 让隧道向服务器检查一次,按结果报:已更新(条数前后对比)、没有变化、打开 Clash 后生效(新内容已取到,App 打开后用上;原因在 --json 的 pendingReason 里); 检查失败时报集合名和内核给的原因(原样),退出码 1。检查失败或控制器报错时退出码非 0(隧道还在检查、等不及回答的 504 也算控制器报错)。 @@ -108,17 +110,58 @@ clash-cli status - **`reload`、`check` 不可用**:配置由 Clash App 管理(组合、切换、检查都在 App 里),这两个命令返回退出码 5。 要换配置、更新订阅或检查配置文件,请在 App 里操作。 +### 配置库:`rules append|remove`、`dns policy` + +这一组命令改的是 App 的**配置库**(`~/Library/Group Containers/group.com.hako.network/working/store/profiles.json` 里的 +`override.appendRules`、`override.prependRules`,以及 `legacyRuntimePatchJSON` 里的 `dns.nameserver-policy`、`dns.fake-ip-filter`), +**不是现在的运行态**:改动**下次连接生效**(现在连着的连接仍按旧规则),也不重建派生产物(那是 App 在连接时做的)。 +内核没给 `app-store-v1` 能力时,这些命令退出码 5,并说明「还不支持 App 配置读写(app-store-v1)」。 + +写配置库只接受本机 **App Group socket**(App 和内核在同一个工作目录里的 `clash.sock`)。控制器监听——默认的 +`127.0.0.1:9090`,以及局域网档——对这些接口只读:那里的写入会被拒绝(退出码 1,并提示改用 `--socket`), +读取不受影响。局域网写入要等安全评审后再开放。 + +```bash +clash-cli --socket "$HOME/Library/Group Containers/group.com.hako.network/working/clash.sock" profiles +clash-cli --socket "$HOME/Library/Group Containers/group.com.hako.network/working/clash.sock" \ + rules append 'DOMAIN-SUFFIX,corp.example.com,DIRECT' +``` + +```bash +clash-cli profiles # 列配置,* 是当前;--json 拿原样回答 +clash-cli rules append 'DOMAIN-SUFFIX,corp.example.com,DIRECT' \ + 'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve' +clash-cli rules remove 'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve' +clash-cli rules append 'DOMAIN,foo.example.com,PROXY' --profile XSUS # 指定配置(id 或名称) +clash-cli dns policy # 看 nameserver-policy / fake-ip-filter +clash-cli dns policy set '+.corp.example.com=10.78.226.116,10.78.226.117' +clash-cli dns policy clear # 清空 nameserver-policy +clash-cli dns policy clear --fake-ip-filter +``` + +- `--profile` 缺省是当前配置(`profiles` 里带 `*` 的那个),也可以给 id 或名称;有同名配置时要求用 id。 +- `rules append` 合并写入并去重:本来就在的规则跳过,输出里说明跳过几条;`rules remove` 只删完全一致的规则。 + 去重后没有变化时不写入,只报现有条数。 +- `dns policy set` 按域名合并:同一个域名再设一次会整体替换它的地址列表;要清空某个域名就用 `dns policy clear`。 + `dns policy clear` 默认只清 `nameserver-policy`,加 `--fake-ip-filter` 时只清 `fake-ip-filter`(两者互斥,各跑一次)。 +- 写入由内核在跨进程锁里原子落盘(先写临时文件再改名),并保留配置里其它字段(`prependRules`、`tun`、`sniffer`、未知字段)不被改动; + App 与内核共用同一个锁文件,App 之后的保存不会把这里的改动盖掉。 +- 校验在控制器那侧:每条规则 1..512 字节、不含换行、最多 5000 条;域名非空且 ≤253 字节,地址是合法 IP 或 + `https://`/`tls://`/`quic://`/`h3://`/`dhcp://` 前缀且 ≤512 字节。非法时控制器回 400、不落盘,CLI 原样转述(退出码 1)。 + ## 5. 环境与安全注意事项 - 拿到密钥的人可以完全控制 Clash(模式、局域网共享、选节点、断连接、清缓存)。不要把密钥贴进公开的地方; 在 App 里「重新生成」后旧密钥立即失效,用旧密钥打开的流也会断开。 - 局域网档只走 TLS,并只接受局域网来源;本机档只听 127.0.0.1。 -- 环境变量:`CLASH_API`(默认 `http://127.0.0.1:9090`)、`CLASH_SECRET`、`CLASH_FINGERPRINT`、`CLASH_TIMEOUT`(默认 8 秒)。 +- 环境变量:`CLASH_API`(默认 `http://127.0.0.1:9090`)、`CLASH_SECRET`、`CLASH_FINGERPRINT`、`CLASH_SOCKET`、 + `CLASH_TIMEOUT`(默认 8 秒)。 - 全局选项(放在命令前后都行;与环境变量同时给出时用选项的值):`-u` / `--url`、`--secret`、`--secret-stdin`、 - `--fingerprint`、`--timeout`、`--json`。`CLASH_TIMEOUT` 写得不合法时无论给不给 `--timeout` 都报退出码 2。 + `--fingerprint`、`--socket`、`--timeout`、`--json`。`--socket` 走本机 App Group socket 而不是 TCP 控制器; + 配置库写入只在这个 socket 上生效。`CLASH_TIMEOUT` 写得不合法时无论给不给 `--timeout` 都报退出码 2。 - 切换节点时节点名必须与策略组成员**精确匹配**(含空格/emoji/特殊字符,如「🇭🇰香港trojan1」)。 -- 退出码:0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持(含 `reload`、`check`); - 6 证书指纹不符或未确认。 +- 退出码:0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持(含 `reload`、`check`, + 以及内核没有 `app-store-v1` 时的配置读写);6 证书指纹不符或未确认。 - 已知指纹记在 `~/.config/clash-cli/known_hosts`(App 内置版在沙盒容器里: `~/Library/Containers/.clash-cli/Data/.config/clash-cli/known_hosts`)。 diff --git a/cli/appstore.go b/cli/appstore.go new file mode 100644 index 00000000..ae65a992 --- /dev/null +++ b/cli/appstore.go @@ -0,0 +1,498 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + "sort" + "strings" +) + +// The App keeps its configuration library (store/profiles.json) as the source of +// truth and rebuilds the derived files on connect. These commands only edit the +// inputs (appendRules/prependRules and the DNS policy inside the runtime patch), +// so they never race with the App's generator: changes apply on the next connect. + +const ( + appStoreCapability = "app-store-v1" + appStoreRoot = "/clash/v1/app" + appStoreEffective = "next-connect" + appStoreNote = "改动在下次连接生效(现在连着的连接仍按旧规则)" +) + +type appProfileActive struct { + ProfileID string `json:"profileID"` + Revision string `json:"revision"` +} + +type appProfile struct { + ID string `json:"id"` + Label string `json:"label"` + Order int `json:"order"` + ActiveRevision string `json:"activeRevision"` + Active bool `json:"active"` + AppendedRules int `json:"appendedRules"` + PrependedRules bool `json:"prependedRules"` + Patched bool `json:"patched"` +} + +type appProfilesIndex struct { + Active appProfileActive `json:"active"` + Profiles []appProfile `json:"profiles"` +} + +type appProfileRules struct { + ID string `json:"id"` + PrependRules bool `json:"prependRules"` + AppendRules []string `json:"appendRules"` + PatchJSON string `json:"patchJSON"` +} + +type appDNSPolicy struct { + NameserverPolicy map[string][]string `json:"nameserverPolicy"` + FakeIPFilter []string `json:"fakeIPFilter"` +} + +// appDNSPolicyWrite leaves a nil field out of the request, which the controller +// reads as "keep this part as it is". +type appDNSPolicyWrite struct { + NameserverPolicy *map[string][]string `json:"nameserverPolicy,omitempty"` + FakeIPFilter *[]string `json:"fakeIPFilter,omitempty"` +} + +type appRulesResult struct { + ProfileID string `json:"profileID"` + Label string `json:"label,omitempty"` + Added int `json:"added"` + Removed int `json:"removed,omitempty"` + Count int `json:"count"` + AppendRules []string `json:"appendRules"` + Effective string `json:"effective"` +} + +type appDNSPolicyResult struct { + ProfileID string `json:"profileID"` + Label string `json:"label,omitempty"` + NameserverPolicy map[string][]string `json:"nameserverPolicy,omitempty"` + FakeIPFilter []string `json:"fakeIPFilter,omitempty"` + Cleared string `json:"cleared,omitempty"` + Effective string `json:"effective"` +} + +func (s *session) requireAppStore() error { + if slices.Contains(s.caps.Capabilities, appStoreCapability) { + return nil + } + return failure(exitUnsupported, "unsupported", + "这个 Clash App(内核 %s)还不支持 App 配置读写(%s),请更新 App", s.caps.CoreVersion, appStoreCapability) +} + +func appProfilePath(id, suffix string) string { + return appStoreRoot + "/profiles/" + pathEscape(id) + "/" + suffix +} + +func appProfileTitle(profile appProfile) string { + switch { + case profile.Label != "" && profile.ID != "": + return fmt.Sprintf("%s(%s)", profile.Label, profile.ID) + case profile.Label != "": + return profile.Label + case profile.ID != "": + return profile.ID + } + return "未命名的配置" +} + +func (s *session) appProfiles() (appProfilesIndex, json.RawMessage, error) { + var index appProfilesIndex + var raw json.RawMessage + if err := s.call(http.MethodGet, appStoreRoot+"/profiles", nil, nil, &raw); err != nil { + return index, nil, err + } + if err := json.Unmarshal(raw, &index); err != nil { + return index, raw, failure(exitPeerError, "bad-response", "配置列表不是 JSON: %v", err) + } + return index, raw, nil +} + +func (s *session) resolveAppProfile(name string) (appProfile, error) { + index, _, err := s.appProfiles() + if err != nil { + return appProfile{}, err + } + if name == "" { + if index.Active.ProfileID == "" { + return appProfile{}, failure(exitPeerError, "bad-response", "控制器没有说哪个配置是当前配置(clash-cli profiles 查看)") + } + for _, profile := range index.Profiles { + if profile.ID == index.Active.ProfileID { + return profile, nil + } + } + return appProfile{ID: index.Active.ProfileID, Active: true, ActiveRevision: index.Active.Revision}, nil + } + for _, profile := range index.Profiles { + if profile.ID == name { + return profile, nil + } + } + var matches []appProfile + for _, profile := range index.Profiles { + if profile.Label == name { + matches = append(matches, profile) + } + } + switch len(matches) { + case 1: + return matches[0], nil + case 0: + return appProfile{}, usage("clash-cli --profile %q:没有这个配置(clash-cli profiles 查看现有配置)", name) + } + return appProfile{}, usage("clash-cli --profile %q:有 %d 个同名配置,请改用 id(clash-cli profiles 查看)", name, len(matches)) +} + +func (s *session) appRules(id string) (appProfileRules, json.RawMessage, error) { + var rules appProfileRules + var raw json.RawMessage + if err := s.call(http.MethodGet, appProfilePath(id, "rules"), nil, nil, &raw); err != nil { + return rules, nil, err + } + if err := json.Unmarshal(raw, &rules); err != nil { + return rules, raw, failure(exitPeerError, "bad-response", "%s 的规则不是 JSON: %v", id, err) + } + if rules.AppendRules == nil { + rules.AppendRules = []string{} + } + return rules, raw, nil +} + +func (s *session) writeAppRules(id string, prepend bool, appendRules []string) error { + if appendRules == nil { + appendRules = []string{} + } + return s.call(http.MethodPut, appProfilePath(id, "rules"), nil, struct { + PrependRules bool `json:"prependRules"` + AppendRules []string `json:"appendRules"` + }{prepend, appendRules}, nil) +} + +func (s *session) appDNSPolicy(id string) (appDNSPolicy, json.RawMessage, error) { + var policy appDNSPolicy + var raw json.RawMessage + if err := s.call(http.MethodGet, appProfilePath(id, "dns-policy"), nil, nil, &raw); err != nil { + return policy, nil, err + } + if err := json.Unmarshal(raw, &policy); err != nil { + return policy, raw, failure(exitPeerError, "bad-response", "%s 的 DNS 策略不是 JSON: %v", id, err) + } + return policy, raw, nil +} + +func (s *session) writeAppDNSPolicy(id string, policy appDNSPolicyWrite) error { + return s.call(http.MethodPut, appProfilePath(id, "dns-policy"), nil, policy, nil) +} + +func cmdAppProfiles(s *session, p parsedArguments) error { + if len(p.positional) > 1 { + return usage("clash-cli profiles") + } + if err := s.requireAppStore(); err != nil { + return err + } + index, raw, err := s.appProfiles() + if err != nil { + return err + } + s.out.succeed(raw, func() { printAppProfiles(s.out, index) }) + return nil +} + +func printAppProfiles(out *output, index appProfilesIndex) { + if len(index.Profiles) == 0 { + out.printf("App 里还没有配置\n") + return + } + var rows [][]string + for _, profile := range index.Profiles { + marker := "" + if profile.Active || profile.ID == index.Active.ProfileID { + marker = "*" + } + revision := profile.ActiveRevision + if revision == "" { + revision = "-" + } + label := profile.Label + if label == "" { + label = "-" + } + rows = append(rows, []string{marker, label, profile.ID, revision, fmt.Sprint(profile.AppendedRules)}) + } + out.table([]string{"当前", "名称", "id", "修订", "追加规则"}, rows) +} + +// cmdRulesEdit handles `rules append|remove`, which edits the App's configuration +// instead of the running rule list. +func cmdRulesEdit(s *session, p parsedArguments, verb string, rules []string) error { + if len(rules) == 0 { + return usage("clash-cli rules %s <规则>... [--profile ]", verb) + } + for _, rule := range rules { + if strings.TrimSpace(rule) == "" { + return usage("clash-cli rules %s:规则不能是空的", verb) + } + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + current, _, err := s.appRules(profile.ID) + if err != nil { + return err + } + var merged []string + added, removed := 0, 0 + switch verb { + case "append": + merged, added = mergeAppendRules(current.AppendRules, rules) + case "remove": + merged, removed = removeAppendRules(current.AppendRules, rules) + } + result := appRulesResult{ + ProfileID: profile.ID, Label: profile.Label, Added: added, Removed: removed, + Count: len(merged), AppendRules: merged, Effective: appStoreEffective, + } + if added == 0 && removed == 0 { + s.out.succeed(result, func() { + s.out.printf("%s的追加规则没有变化(现有 %d 条)\n", appProfileTitle(profile), len(merged)) + }) + return nil + } + s.announce() + if err := s.writeAppRules(profile.ID, current.PrependRules, merged); err != nil { + return err + } + s.out.succeed(result, func() { + switch verb { + case "append": + s.out.printf("✓ %s追加 %d 条规则,现在共 %d 条\n", appProfileTitle(profile), added, len(merged)) + if skipped := len(rules) - added; skipped > 0 { + s.out.printf(" · 其中 %d 条本来就有,没有重复追加\n", skipped) + } + case "remove": + s.out.printf("✓ %s移除 %d 条规则,现在共 %d 条\n", appProfileTitle(profile), removed, len(merged)) + } + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +// mergeAppendRules appends the rules that are missing, keeping the existing order +// and dropping duplicates from both the existing list and the arguments. +func mergeAppendRules(existing, added []string) ([]string, int) { + merged := make([]string, 0, len(existing)+len(added)) + seen := make(map[string]bool, len(existing)+len(added)) + for _, rule := range existing { + if seen[rule] { + continue + } + seen[rule] = true + merged = append(merged, rule) + } + appended := 0 + for _, rule := range added { + if seen[rule] { + continue + } + seen[rule] = true + merged = append(merged, rule) + appended++ + } + return merged, appended +} + +func removeAppendRules(existing, removed []string) ([]string, int) { + drop := make(map[string]bool, len(removed)) + for _, rule := range removed { + drop[rule] = true + } + kept := make([]string, 0, len(existing)) + for _, rule := range existing { + if drop[rule] { + continue + } + kept = append(kept, rule) + } + return kept, len(existing) - len(kept) +} + +func cmdDNSPolicy(s *session, p parsedArguments) error { + args := p.positional[2:] + if len(args) == 0 { + return dnsPolicyShow(s, p) + } + switch args[0] { + case "set": + return dnsPolicySet(s, p, args[1:]) + case "clear": + return dnsPolicyClear(s, p, args[1:]) + } + return usage("clash-cli dns policy | dns policy set '+.域名=地址[,地址]'... | dns policy clear [--fake-ip-filter]") +} + +func dnsPolicyShow(s *session, p parsedArguments) error { + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + policy, raw, err := s.appDNSPolicy(profile.ID) + if err != nil { + return err + } + s.out.succeed(raw, func() { + s.out.printf("DNS 策略:%s\n", appProfileTitle(profile)) + printNameserverPolicy(s.out, policy.NameserverPolicy, " ") + printFakeIPFilter(s.out, policy.FakeIPFilter, " ") + }) + return nil +} + +func dnsPolicySet(s *session, p parsedArguments, pairs []string) error { + if len(pairs) == 0 { + return usage("clash-cli dns policy set '+.域名=地址[,地址]'... [--profile ]") + } + added, err := parseNameserverPairs(pairs) + if err != nil { + return err + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + current, _, err := s.appDNSPolicy(profile.ID) + if err != nil { + return err + } + merged := make(map[string][]string, len(current.NameserverPolicy)+len(added)) + for domain, servers := range current.NameserverPolicy { + merged[domain] = servers + } + for domain, servers := range added { + merged[domain] = servers + } + s.announce() + if err := s.writeAppDNSPolicy(profile.ID, appDNSPolicyWrite{NameserverPolicy: &merged}); err != nil { + return err + } + result := appDNSPolicyResult{ + ProfileID: profile.ID, Label: profile.Label, NameserverPolicy: merged, Effective: appStoreEffective, + } + s.out.succeed(result, func() { + s.out.printf("✓ %s写入 %d 条 nameserver-policy,现有 %d 条:\n", appProfileTitle(profile), len(added), len(merged)) + for _, domain := range sortedKeys(added) { + s.out.printf(" %s → %s\n", domain, strings.Join(added[domain], ",")) + } + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +func dnsPolicyClear(s *session, p parsedArguments, rest []string) error { + fakeIPFilter := p.has("fake-ip-filter") + if len(rest) > 0 { + return usage("clash-cli dns policy clear [--fake-ip-filter] [--profile ]") + } + if err := s.requireAppStore(); err != nil { + return err + } + profile, err := s.resolveAppProfile(p.flags["profile"]) + if err != nil { + return err + } + write := appDNSPolicyWrite{} + cleared := "nameserverPolicy" + result := appDNSPolicyResult{ProfileID: profile.ID, Label: profile.Label, Effective: appStoreEffective} + if fakeIPFilter { + empty := []string{} + write.FakeIPFilter = &empty + cleared = "fakeIPFilter" + result.FakeIPFilter = empty + } else { + empty := map[string][]string{} + write.NameserverPolicy = &empty + cleared = "nameserverPolicy" + } + result.Cleared = cleared + s.announce() + if err := s.writeAppDNSPolicy(profile.ID, write); err != nil { + return err + } + s.out.succeed(result, func() { + label := map[string]string{"nameserverPolicy": "nameserver-policy", "fakeIPFilter": "fake-ip-filter"}[cleared] + s.out.printf("✓ 已清空 %s的 %s\n", appProfileTitle(profile), label) + s.out.printf(" · %s\n", appStoreNote) + }) + return nil +} + +func parseNameserverPairs(pairs []string) (map[string][]string, error) { + policy := make(map[string][]string, len(pairs)) + for _, pair := range pairs { + domain, servers, ok := strings.Cut(pair, "=") + domain = strings.TrimSpace(domain) + if !ok || domain == "" || strings.TrimSpace(servers) == "" { + return nil, usage("clash-cli dns policy set:参数写成 '+.域名=地址[,地址]',收到 %q", pair) + } + var list []string + for _, server := range strings.Split(servers, ",") { + server = strings.TrimSpace(server) + if server == "" { + return nil, usage("clash-cli dns policy set:%s 的地址里有一个是空的", domain) + } + list = append(list, server) + } + policy[domain] = append(policy[domain], list...) + } + return policy, nil +} + +func printNameserverPolicy(out *output, policy map[string][]string, indent string) { + if len(policy) == 0 { + out.printf("%snameserver-policy:没有设置\n", indent) + return + } + out.printf("%snameserver-policy(%d 条):\n", indent, len(policy)) + for _, domain := range sortedKeys(policy) { + out.printf("%s %s → %s\n", indent, domain, strings.Join(policy[domain], ",")) + } +} + +func printFakeIPFilter(out *output, filter []string, indent string) { + if len(filter) == 0 { + out.printf("%sfake-ip-filter:没有设置\n", indent) + return + } + out.printf("%sfake-ip-filter(%d 条):\n", indent, len(filter)) + for _, item := range filter { + out.printf("%s %s\n", indent, item) + } +} + +func sortedKeys[V any](items map[string]V) []string { + names := make([]string, 0, len(items)) + for name := range items { + names = append(names, name) + } + sort.Strings(names) + return names +} diff --git a/cli/appstore_test.go b/cli/appstore_test.go new file mode 100644 index 00000000..e3005b09 --- /dev/null +++ b/cli/appstore_test.go @@ -0,0 +1,728 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// fakeAppStore is a stand-in controller: it serves the App store endpoints from +// fixture JSON and records the bodies that were written. +type fakeAppStore struct { + mu sync.Mutex + capabilities []string + profiles string + profilesCode int + rules map[string]string + dns map[string]string + runtimeRules string + codes map[string]int + puts []fakePut +} + +type fakePut struct { + Path string + Body string +} + +func (f *fakeAppStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + body, _ := io.ReadAll(r.Body) + if r.Method == http.MethodPut { + f.puts = append(f.puts, fakePut{Path: r.URL.Path, Body: string(body)}) + } + if code := f.codes[r.Method+r.URL.Path]; code != 0 { + w.WriteHeader(code) + fmt.Fprint(w, `{"message":"控制器拒绝了这次改动"}`) + return + } + switch { + case r.URL.Path == "/clash/v1/capabilities": + _ = json.NewEncoder(w).Encode(capabilities{API: 1, Platform: "macos", CoreVersion: "1.19.32", Capabilities: f.capabilities}) + case r.URL.Path == "/clash/v1/app/profiles": + if f.profilesCode != 0 { + w.WriteHeader(f.profilesCode) + fmt.Fprint(w, `{"message":"the App has not published its profile index yet"}`) + return + } + fmt.Fprint(w, f.profiles) + case r.URL.Path == "/rules": + fmt.Fprint(w, f.runtimeRules) + case strings.HasPrefix(r.URL.Path, "/clash/v1/app/profiles/"): + rest := strings.TrimPrefix(r.URL.Path, "/clash/v1/app/profiles/") + id, kind, ok := strings.Cut(rest, "/") + if !ok { + http.NotFound(w, r) + return + } + if r.Method == http.MethodPut { + w.WriteHeader(http.StatusNoContent) + return + } + store := map[string]string{} + switch kind { + case "rules": + store = f.rules + case "dns-policy": + store = f.dns + } + payload, found := store[id] + if !found { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `{"message":"unknown profile"}`) + return + } + fmt.Fprint(w, payload) + default: + http.NotFound(w, r) + } +} + +func (f *fakeAppStore) written(t *testing.T) (string, map[string]any) { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + if len(f.puts) != 1 { + t.Fatalf("expected exactly one write, got %d: %+v", len(f.puts), f.puts) + } + var decoded map[string]any + if err := json.Unmarshal([]byte(f.puts[0].Body), &decoded); err != nil { + t.Fatalf("write body is not JSON (%q): %v", f.puts[0].Body, err) + } + return f.puts[0].Path, decoded +} + +const testProfileIndex = `{"active":{"profileID":"p2","revision":"r9"},"profiles":[` + + `{"id":"p1","label":"Home","order":1,"activeRevision":"r3","appendedRules":0},` + + `{"id":"p2","label":"XSUS","order":-1,"activeRevision":"r9","active":true,"appendedRules":2,"prependedRules":true,"patched":false}]}` + +func newAppStoreSession(t *testing.T, store *fakeAppStore) (*session, *bytes.Buffer) { + t.Helper() + server := httptest.NewServer(store) + t.Cleanup(server.Close) + var stdout, stderr bytes.Buffer + env := environment{ + getenv: func(string) string { return "" }, + stdin: strings.NewReader(""), + stdout: &stdout, stderr: &stderr, + homeDir: t.TempDir(), + } + out := &output{stdout: &stdout, stderr: &stderr} + s, err := connect(env, globalOptions{url: server.URL, timeout: 3 * time.Second}, out) + if err != nil { + t.Fatalf("connect: %v", err) + } + return s, &stdout +} + +func args(positional ...string) parsedArguments { + return parsedArguments{positional: positional, flags: map[string]string{}} +} + +func withFlags(parsed parsedArguments, pairs ...string) parsedArguments { + for i := 0; i+1 < len(pairs); i += 2 { + parsed.flags[pairs[i]] = pairs[i+1] + } + return parsed +} + +func exitOf(t *testing.T, err error) int { + t.Helper() + var cli *cliError + if !errors.As(err, &cli) { + t.Fatalf("expected a *cliError, got %v", err) + } + return cli.exit +} + +func TestAppStoreMissingCapability(t *testing.T) { + cases := [][]string{ + {"profiles"}, + {"rules", "append", "DOMAIN-SUFFIX,a.com,DIRECT"}, + {"dns", "policy"}, + } + for _, positional := range cases { + t.Run(strings.Join(positional, " "), func(t *testing.T) { + store := &fakeAppStore{profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + var err error + switch positional[0] { + case "profiles": + err = cmdAppProfiles(s, args(positional...)) + case "rules": + err = cmdRules(s, args(positional...)) + case "dns": + err = cmdDNS(s, args(positional...)) + } + if err == nil { + t.Fatalf("expected a capability failure, got none (stdout %q)", stdout.String()) + } + if exit := exitOf(t, err); exit != exitUnsupported { + t.Fatalf("expected exit %d, got %d (%v)", exitUnsupported, exit, err) + } + if !strings.Contains(err.Error(), "还不支持 App 配置读写") || !strings.Contains(err.Error(), appStoreCapability) { + t.Fatalf("message should name the missing capability, got %q", err.Error()) + } + if len(store.puts) != 0 { + t.Fatalf("nothing should be written, got %+v", store.puts) + } + }) + } +} + +func TestAppStoreProfilesTable(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + if err := cmdAppProfiles(s, args("profiles")); err != nil { + t.Fatalf("profiles: %v", err) + } + output := stdout.String() + lines := strings.Split(strings.TrimSpace(output), "\n") + if len(lines) != 3 { + t.Fatalf("expected a header and two rows, got %q", output) + } + for _, want := range []string{"当前", "名称", "id", "修订", "追加规则"} { + if !strings.Contains(lines[0], want) { + t.Fatalf("header %q is missing %q", lines[0], want) + } + } + var active, inactive string + for _, line := range lines[1:] { + if strings.HasPrefix(strings.TrimSpace(line), "*") { + active = line + continue + } + inactive = line + } + if active == "" || inactive == "" { + t.Fatalf("expected one marked row and one unmarked row, got %q", output) + } + if !strings.Contains(active, "XSUS") { + t.Fatalf("the marked row should be the active profile, got %q", active) + } + if !strings.Contains(active, "p2") || !strings.Contains(active, "r9") || !strings.Contains(active, "2") { + t.Fatalf("active row should carry id/revision/rule count, got %q", active) + } + if !strings.Contains(inactive, "Home") { + t.Fatalf("inactive row should name the other profile, got %q", inactive) + } +} + +func TestAppStoreProfilesJSON(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, stdout := newAppStoreSession(t, store) + s.out.json = true + if err := cmdAppProfiles(s, args("profiles")); err != nil { + t.Fatalf("profiles: %v", err) + } + var envelope struct { + OK bool `json:"ok"` + Data struct { + Active struct { + ProfileID string `json:"profileID"` + Revision string `json:"revision"` + } `json:"active"` + Profiles []struct { + ID string `json:"id"` + AppendedRules int `json:"appendedRules"` + } `json:"profiles"` + } `json:"data"` + } + if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil { + t.Fatalf("stdout is not the JSON envelope (%q): %v", stdout.String(), err) + } + if !envelope.OK || envelope.Data.Active.ProfileID != "p2" || envelope.Data.Active.Revision != "r9" { + t.Fatalf("unexpected envelope: %s", stdout.String()) + } + if len(envelope.Data.Profiles) != 2 || envelope.Data.Profiles[1].AppendedRules != 2 { + t.Fatalf("profiles should be passed through unchanged: %s", stdout.String()) + } +} + +func TestAppStoreProfilesUnpublished(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profilesCode: http.StatusServiceUnavailable} + s, _ := newAppStoreSession(t, store) + err := cmdAppProfiles(s, args("profiles")) + if exit := exitOf(t, err); exit != exitPeerError { + t.Fatalf("expected exit %d, got %d (%v)", exitPeerError, exit, err) + } + if !strings.Contains(err.Error(), "has not published") { + t.Fatalf("the controller message should be passed through, got %q", err.Error()) + } +} + +func TestAppStoreRulesAppend(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{"rules-match-v1", appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":true,"appendRules":["DOMAIN-SUFFIX,a.com,DIRECT","OLD,RULE"],"patchJSON":"{}"}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, args("rules", "append", "DOMAIN-SUFFIX,a.com,DIRECT", "DOMAIN-SUFFIX,b.com,PROXY")) + if err != nil { + t.Fatalf("rules append: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p2/rules" { + t.Fatalf("the write should target the active profile, got %q", path) + } + if body["prependRules"] != true { + t.Fatalf("prependRules should be passed through, got %v", body["prependRules"]) + } + got, _ := body["appendRules"].([]any) + want := []string{"DOMAIN-SUFFIX,a.com,DIRECT", "OLD,RULE", "DOMAIN-SUFFIX,b.com,PROXY"} + if len(got) != len(want) { + t.Fatalf("expected %v, got %v", want, got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("expected %v, got %v", want, got) + } + } + if _, exists := body["patchJSON"]; exists { + t.Fatalf("patchJSON is not writable, got %v", body) + } + text := stdout.String() + if !strings.Contains(text, "追加 1 条") || !strings.Contains(text, "共 3 条") { + t.Fatalf("expected the count and the newly added rules, got %q", text) + } + if !strings.Contains(text, "下次连接生效") { + t.Fatalf("expected the next-connect hint, got %q", text) + } + if !strings.Contains(text, "1 条本来就有") { + t.Fatalf("expected the duplicate note, got %q", text) + } +} + +func TestAppStoreRulesAppendNoop(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":["OLD,RULE"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "append", "OLD,RULE")); err != nil { + t.Fatalf("rules append: %v", err) + } + if len(store.puts) != 0 { + t.Fatalf("an unchanged list should not be written, got %+v", store.puts) + } + if !strings.Contains(stdout.String(), "没有变化") { + t.Fatalf("expected a no-op message, got %q", stdout.String()) + } +} + +func TestAppStoreRulesRemoveByLabel(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p1": `{"id":"p1","prependRules":false,"appendRules":["A,RULE","B,RULE"]}`, + "p2": `{"id":"p2","prependRules":false,"appendRules":["A,RULE","B,RULE","C,RULE"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "remove", "B,RULE"), "profile", "Home")) + if err != nil { + t.Fatalf("rules remove: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p1/rules" { + t.Fatalf("--profile should select by label, got %q", path) + } + got, _ := body["appendRules"].([]any) + if len(got) != 1 || got[0] != "A,RULE" { + t.Fatalf("only the matching rule should go, got %v", got) + } + if !strings.Contains(stdout.String(), "移除 1 条规则") { + t.Fatalf("expected the removal count, got %q", stdout.String()) + } +} + +func TestAppStoreRulesRemoveMatches(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":["A,RULE","B,RULE","C,RULE"]}`, + }, + } + s, _ := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "remove", "B,RULE", "MISSING,RULE")); err != nil { + t.Fatalf("rules remove: %v", err) + } + _, body := store.written(t) + got, _ := body["appendRules"].([]any) + if len(got) != 2 || got[0] != "A,RULE" || got[1] != "C,RULE" { + t.Fatalf("expected the untouched rules in order, got %v", got) + } +} + +func TestAppStoreRulesUnknownProfile(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex} + s, _ := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "append", "A,RULE"), "profile", "Nope")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } + if !strings.Contains(err.Error(), "--profile") || !strings.Contains(err.Error(), "profiles") { + t.Fatalf("the message should point at --profile and the profiles command, got %q", err.Error()) + } + if len(store.puts) != 0 { + t.Fatalf("nothing should be written, got %+v", store.puts) + } +} + +func TestAppStoreRulesAmbiguousLabel(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: `{"active":{"profileID":"p1","revision":"r1"},"profiles":[` + + `{"id":"p1","label":"Same","order":0,"active":true},{"id":"p2","label":"Same","order":1}]}`, + } + s, _ := newAppStoreSession(t, store) + err := cmdRules(s, withFlags(args("rules", "append", "A,RULE"), "profile", "Same")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } + if !strings.Contains(err.Error(), "同名") { + t.Fatalf("expected a duplicate-label hint, got %q", err.Error()) + } +} + +func TestAppStoreRulesWriteRejected(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":[]}`, + }, + codes: map[string]int{"PUT/clash/v1/app/profiles/p2/rules": http.StatusBadRequest}, + } + s, stdout := newAppStoreSession(t, store) + err := cmdRules(s, args("rules", "append", "TOO,LONG")) + if exit := exitOf(t, err); exit != exitPeerError { + t.Fatalf("expected exit %d, got %d (%v)", exitPeerError, exit, err) + } + if !strings.Contains(err.Error(), "控制器拒绝了这次改动") { + t.Fatalf("the controller message should be passed through, got %q", err.Error()) + } + if strings.Contains(stdout.String(), "✓") { + t.Fatalf("a rejected write should not claim success, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicyShow(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.didichuxing.com":["10.78.226.116"]},"fakeIPFilter":["+.example.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy")); err != nil { + t.Fatalf("dns policy: %v", err) + } + text := stdout.String() + for _, want := range []string{"DNS 策略:XSUS(p2)", "+.didichuxing.com → 10.78.226.116", "+.example.com"} { + if !strings.Contains(text, want) { + t.Fatalf("expected %q in the output, got %q", want, text) + } + } +} + +func TestAppStoreDNSPolicyShowEmpty(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{"p2": `{}`}, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy")); err != nil { + t.Fatalf("dns policy: %v", err) + } + if !strings.Contains(stdout.String(), "nameserver-policy:没有设置") || !strings.Contains(stdout.String(), "fake-ip-filter:没有设置") { + t.Fatalf("empty parts should say so, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicySetMerges(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.a.com":["1.1.1.1"]},"fakeIPFilter":["+.keep.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + err := cmdDNS(s, args("dns", "policy", "set", "+.b.com=2.2.2.2, 3.3.3.3")) + if err != nil { + t.Fatalf("dns policy set: %v", err) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p2/dns-policy" { + t.Fatalf("unexpected path %q", path) + } + if _, exists := body["fakeIPFilter"]; exists { + t.Fatalf("fakeIPFilter should be left alone, got %v", body) + } + policy, _ := body["nameserverPolicy"].(map[string]any) + if len(policy) != 2 { + t.Fatalf("the existing entry should be merged, got %v", policy) + } + servers, _ := policy["+.b.com"].([]any) + if len(servers) != 2 || servers[0] != "2.2.2.2" || servers[1] != "3.3.3.3" { + t.Fatalf("expected two trimmed servers, got %v", policy["+.b.com"]) + } + if !strings.Contains(stdout.String(), "写入 1 条") { + t.Fatalf("expected the merged count, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicySetRejectsBadPair(t *testing.T) { + store := &fakeAppStore{capabilities: []string{appStoreCapability}, profiles: testProfileIndex, dns: map[string]string{"p2": `{}`}} + s, _ := newAppStoreSession(t, store) + err := cmdDNS(s, args("dns", "policy", "set", "+.b.com")) + if exit := exitOf(t, err); exit != exitUsage { + t.Fatalf("expected exit %d, got %d (%v)", exitUsage, exit, err) + } +} + +func TestAppStoreDNSPolicyClear(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{ + "p2": `{"nameserverPolicy":{"+.a.com":["1.1.1.1"]},"fakeIPFilter":["+.keep.com"]}`, + }, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdDNS(s, args("dns", "policy", "clear")); err != nil { + t.Fatalf("dns policy clear: %v", err) + } + _, body := store.written(t) + policy, ok := body["nameserverPolicy"].(map[string]any) + if !ok || len(policy) != 0 { + t.Fatalf("clear should send an empty nameserverPolicy, got %v", body) + } + if _, exists := body["fakeIPFilter"]; exists { + t.Fatalf("fakeIPFilter should be left alone, got %v", body) + } + if !strings.Contains(stdout.String(), "已清空 XSUS(p2)的 nameserver-policy") { + t.Fatalf("expected the clear message, got %q", stdout.String()) + } +} + +func TestAppStoreDNSPolicyClearFakeIPFilter(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + dns: map[string]string{"p2": `{"fakeIPFilter":["+.keep.com"]}`}, + } + s, _ := newAppStoreSession(t, store) + if err := cmdDNS(s, withFlags(args("dns", "policy", "clear"), "fake-ip-filter", "1")); err != nil { + t.Fatalf("dns policy clear --fake-ip-filter: %v", err) + } + _, body := store.written(t) + if _, exists := body["nameserverPolicy"]; exists { + t.Fatalf("nameserverPolicy should be left alone, got %v", body) + } + filter, ok := body["fakeIPFilter"].([]any) + if !ok || len(filter) != 0 { + t.Fatalf("expected an empty fakeIPFilter, got %v", body) + } +} + +func TestAppStoreRuntimeRulesUnchanged(t *testing.T) { + store := &fakeAppStore{ + profiles: testProfileIndex, + runtimeRules: `{"rules":[{"type":"DOMAIN-SUFFIX","payload":"a.com","proxy":"DIRECT"}]}`, + } + s, stdout := newAppStoreSession(t, store) + if err := cmdRules(s, args("rules", "5")); err != nil { + t.Fatalf("rules 5: %v", err) + } + if !strings.Contains(stdout.String(), "规则 1 条") { + t.Fatalf("the running rule list should still work, got %q", stdout.String()) + } + if len(store.puts) != 0 { + t.Fatalf("reading rules must not write, got %+v", store.puts) + } +} + +func TestMergeAppendRules(t *testing.T) { + merged, appended := mergeAppendRules([]string{"A", "B", "A"}, []string{"B", "C", "C", "D"}) + if appended != 2 { + t.Fatalf("expected 2 new rules, got %d (%v)", appended, merged) + } + want := []string{"A", "B", "C", "D"} + if len(merged) != len(want) { + t.Fatalf("expected %v, got %v", want, merged) + } + for i := range want { + if merged[i] != want[i] { + t.Fatalf("expected %v, got %v", want, merged) + } + } +} + +func TestAppStoreRunReportsMissingCapability(t *testing.T) { + store := &fakeAppStore{profiles: testProfileIndex} + server := httptest.NewServer(store) + defer server.Close() + for _, tc := range []struct { + name string + args []string + }{{"human", []string{"profiles"}}, {"json", []string{"--json", "profiles"}}} { + t.Run(tc.name, func(t *testing.T) { + var stdout, stderr bytes.Buffer + env := environment{ + args: tc.args, + getenv: func(key string) string { + if key == "CLASH_API" { + return server.URL + } + return "" + }, + stdin: strings.NewReader(""), + stdout: &stdout, stderr: &stderr, + homeDir: t.TempDir(), + } + if exit := run(env); exit != exitUnsupported { + t.Fatalf("expected exit %d, got %d (stdout %q, stderr %q)", exitUnsupported, exit, stdout.String(), stderr.String()) + } + if tc.name == "human" { + if !strings.Contains(stderr.String(), "还不支持 App 配置读写") { + t.Fatalf("expected the hint on stderr, got %q", stderr.String()) + } + return + } + var envelope struct { + OK bool `json:"ok"` + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil { + t.Fatalf("stdout is not a JSON envelope (%q): %v", stdout.String(), err) + } + if envelope.OK || envelope.Error.Code != "unsupported" || !strings.Contains(envelope.Error.Message, appStoreCapability) { + t.Fatalf("unexpected envelope: %s", stdout.String()) + } + }) + } +} + +// Writing the profile store is refused on a controller listener; the refusal +// must point at the App Group socket instead of blaming the secret. +func TestWriteRefusalPointsAtTheSocket(t *testing.T) { + refusal := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/clash/v1/capabilities": + _ = json.NewEncoder(w).Encode(capabilities{API: 1, Platform: "macos", CoreVersion: "1.19.32", Capabilities: []string{appStoreCapability}}) + case r.URL.Path == "/clash/v1/app/profiles": + fmt.Fprint(w, testProfileIndex) + case r.URL.Path == "/clash/v1/app/profiles/p2/rules" && r.Method == http.MethodPut: + w.Header().Set("X-Clash-Refusal", appStoreLocalWritesOnly) + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, "the App profile store accepts writes only over the App Group socket; LAN controller clients are read-only") + case r.URL.Path == "/clash/v1/app/profiles/p2/rules": + fmt.Fprint(w, `{"id":"p2","prependRules":false,"appendRules":[],"patchJSON":"{}"}`) + default: + http.NotFound(w, r) + } + }) + server := httptest.NewServer(refusal) + defer server.Close() + + var stdout, stderr bytes.Buffer + env := environment{ + getenv: func(key string) string { + if key == "CLASH_API" { + return server.URL + } + return "" + }, + stdin: strings.NewReader(""), stdout: &stdout, stderr: &stderr, homeDir: t.TempDir(), + } + out := &output{stdout: &stdout, stderr: &stderr} + s, err := connect(env, globalOptions{url: server.URL, timeout: 3 * time.Second}, out) + if err != nil { + t.Fatalf("connect: %v", err) + } + err = cmdRules(s, args("rules", "append", "DOMAIN,refused.example,DIRECT")) + if err == nil { + t.Fatal("a refused write was reported as success") + } + if exit := exitOf(t, err); exit != exitPeerError { + t.Fatalf("refusal exit = %d, want %d (%v)", exit, exitPeerError, err) + } + message := err.Error() + if !strings.Contains(message, "--socket") || !strings.Contains(message, "App Group socket") { + t.Fatalf("the refusal should point at --socket, got %q", message) + } + if strings.Contains(message, "密钥") { + t.Fatalf("a policy refusal must not blame the secret, got %q", message) + } +} + +// --socket sends the same requests over the App Group socket, which is the +// only place the store accepts writes. +func TestSocketOptionWritesOverTheAppGroupSocket(t *testing.T) { + store := &fakeAppStore{ + capabilities: []string{appStoreCapability}, + profiles: testProfileIndex, + rules: map[string]string{ + "p2": `{"id":"p2","prependRules":false,"appendRules":[],"patchJSON":"{}"}`, + }, + } + directory, err := os.MkdirTemp("/tmp", "clash-cli-socket") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(directory) }) + socket := filepath.Join(directory, "clash.sock") + listener, err := net.Listen("unix", socket) + if err != nil { + t.Fatalf("listen on %s: %v", socket, err) + } + server := &http.Server{Handler: store} + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { _ = server.Close() }) + + var stdout, stderr bytes.Buffer + env := environment{getenv: func(string) string { return "" }, stdin: strings.NewReader(""), + stdout: &stdout, stderr: &stderr, homeDir: t.TempDir()} + out := &output{stdout: &stdout, stderr: &stderr} + s, err := connect(env, globalOptions{url: "http://127.0.0.1:9090", socket: socket, timeout: 3 * time.Second}, out) + if err != nil { + t.Fatalf("connect over %s: %v", socket, err) + } + if err := cmdRules(s, args("rules", "append", "DOMAIN,via-socket.example,DIRECT")); err != nil { + t.Fatalf("rules append over the socket: %v (stderr %q)", err, stderr.String()) + } + path, body := store.written(t) + if path != "/clash/v1/app/profiles/p2/rules" { + t.Fatalf("the write should target the active profile over the socket, got %q", path) + } + if rules, _ := body["appendRules"].([]any); len(rules) != 1 || rules[0] != "DOMAIN,via-socket.example,DIRECT" { + t.Fatalf("appendRules = %v", body["appendRules"]) + } +} diff --git a/cli/args.go b/cli/args.go index 4f5dfa94..34d5cb64 100644 --- a/cli/args.go +++ b/cli/args.go @@ -14,12 +14,12 @@ type parsedArguments struct { func (p parsedArguments) has(name string) bool { return p.flags[name] != "" } var ( - globalValueOptions = map[string]string{"u": "url", "url": "url", "secret": "secret", "fingerprint": "fingerprint", "timeout": "timeout"} + globalValueOptions = map[string]string{"u": "url", "url": "url", "secret": "secret", "fingerprint": "fingerprint", "timeout": "timeout", "socket": "socket"} globalBoolOptions = map[string]string{"json": "json", "secret-stdin": "secret-stdin"} commandValueOptions = map[string]string{"level": "level", "test-url": "test-url", "delay-timeout": "delay-timeout", - "geodata-dir": "geodata-dir", "interval": "interval"} + "geodata-dir": "geodata-dir", "interval": "interval", "profile": "profile"} commandBoolOptions = map[string]string{"f": "follow", "follow": "follow", "resolve": "resolve", "all": "all", - "h": "help", "help": "help"} + "fake-ip-filter": "fake-ip-filter", "h": "help", "help": "help"} ) func parseArguments(args []string, options *globalOptions) (parsedArguments, error) { @@ -62,6 +62,8 @@ func parseArguments(args []string, options *globalOptions) (parsedArguments, err options.secret = v case "fingerprint": options.fingerprint = v + case "socket": + options.socket = v case "timeout": timeout, err := parseTimeout(v) if err != nil { diff --git a/cli/commands.go b/cli/commands.go index fd2d32da..099526f5 100644 --- a/cli/commands.go +++ b/cli/commands.go @@ -32,6 +32,7 @@ func init() { "conn": cmdConn, "traffic": cmdTraffic, "rules": cmdRules, + "profiles": cmdAppProfiles, "configs": cmdConfigs, "dns": cmdDNS, "logs": cmdLogs, @@ -987,7 +988,11 @@ func cmdLogs(s *session, p parsedArguments) error { } func cmdRules(s *session, p parsedArguments) error { - return listRules(s, p.positional[1:]) + rest := p.positional[1:] + if len(rest) > 0 && (rest[0] == "append" || rest[0] == "remove") { + return cmdRulesEdit(s, p, rest[0], rest[1:]) + } + return listRules(s, rest) } func listRules(s *session, rest []string) error { @@ -1213,8 +1218,11 @@ func ruleMatch(s *session, target string, pairs []string, resolve bool) error { func cmdDNS(s *session, p parsedArguments) error { args := p.positional[1:] + if len(args) > 0 && args[0] == "policy" { + return cmdDNSPolicy(s, p) + } if len(args) < 2 || (args[0] != "query" && args[0] != "explain") { - return usage("clash-cli dns query <域名> [type] | dns explain <域名> [type]") + return usage("clash-cli dns query <域名> [type] | dns explain <域名> [type] | dns policy [set|clear]") } recordType := "A" if len(args) > 2 { diff --git a/cli/main.go b/cli/main.go index 7f7d0c6e..135a6325 100644 --- a/cli/main.go +++ b/cli/main.go @@ -61,6 +61,7 @@ type globalOptions struct { secret string secretStdin bool fingerprint string + socket string json bool timeout time.Duration } @@ -70,6 +71,7 @@ func run(env environment) int { url: firstNonEmpty(env.getenv("CLASH_API"), "http://127.0.0.1:9090"), secret: env.getenv("CLASH_SECRET"), fingerprint: env.getenv("CLASH_FINGERPRINT"), + socket: env.getenv("CLASH_SOCKET"), timeout: 8 * time.Second, } var timeoutErr error @@ -225,6 +227,7 @@ const usageText = `clash-cli —— Clash App 内置的命令行工具 --secret 密钥 控制器密钥($CLASH_SECRET;在 App 的 更多 › 客户端设置 › 外部控制器 里复制) --secret-stdin 从标准输入第一行读密钥 --fingerprint 指纹 期望的证书指纹 sha256:AB:CD:...($CLASH_FINGERPRINT);不给时首次连接会问一次并记住 + --socket 路径 直连本机 App Group socket($CLASH_SOCKET);配置库的写入只在这个 socket 上被接受 --json 每条命令在 stdout 输出一个 JSON:{"cli":1,"ok":...} --timeout 时长 单次请求超时($CLASH_TIMEOUT,默认 8 秒;不作用于流) @@ -260,8 +263,19 @@ const usageText = `clash-cli —— Clash App 内置的命令行工具 conn close 关闭一条或全部连接(all 会打断下载与 SSH) flush fakeip|dns 清空 fake-ip 池或 DNS 缓存 +配置库(改 App 里存的那份配置,不动现在的连接,下次连接生效): + profiles App 里的配置列表(* 当前) + rules append <规则>... 往这份配置里追加规则(--profile ,缺省当前配置) + rules remove <规则>... 从这份配置里删掉这些规则 + dns policy 这份配置的 DNS 策略 + dns policy set '+.域名=地址[,地址]'... + 合并写入 nameserver-policy + dns policy clear [--fake-ip-filter] + 清空 nameserver-policy(或 fake-ip-filter) + 改的是 App 的配置库(store/profiles.json),不重建派生产物;内核还不支持时退出码 5。 + 不提供: reload、check(配置由 Clash App 管理和检查,退出码 5)。 -退出码: 0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒;5 不是 Clash App 的控制器或不支持; -6 证书指纹不符或未确认。 +退出码: 0 成功;1 控制器报错;2 用法;3 连不上;4 密钥被拒; +5 不是 Clash App 的控制器或不支持(含配置库不支持);6 证书指纹不符或未确认。 ` diff --git a/cli/session.go b/cli/session.go index d3319140..075d3257 100644 --- a/cli/session.go +++ b/cli/session.go @@ -62,9 +62,23 @@ func connect(env environment, options globalOptions, out *output) (*session, err base.Path, base.RawQuery, base.Fragment = "", "", "" hostport := controllerHostPort(base) + dial := (&net.Dialer{Timeout: options.timeout}).DialContext + if options.socket != "" { + // Profile writes (rules append/remove, dns policy) are only accepted on + // the App's App Group socket; a controller listener is read-only for + // them. --socket dials that socket directly, for the same routes. + socket := options.socket + dial = func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: options.timeout}).DialContext(ctx, "unix", socket) + } + base = &url.URL{Scheme: "http", Host: "app-group"} + hostport = socket + options.url = "unix:" + socket + } + transport := &http.Transport{ Proxy: nil, - DialContext: (&net.Dialer{Timeout: options.timeout}).DialContext, + DialContext: dial, TLSHandshakeTimeout: options.timeout, ForceAttemptHTTP2: true, } @@ -404,7 +418,19 @@ func (s *session) call(method, path string, query url.Values, body any, into any return nil } +// appStoreLocalWritesOnly is the refusal marker the kernel sets when a write +// did not arrive on the App Group socket. +const appStoreLocalWritesOnly = "app-store-local-writes-only" + func peerFailure(response *http.Response) error { + if response.Header.Get("X-Clash-Refusal") == appStoreLocalWritesOnly { + hint := "" + if socket := appGroupSocketHint(); socket != "" { + hint = "(这台 Mac 上找到 " + socket + ")" + } + return failure(exitPeerError, "local-writes-only", + "App 只在本机 App Group socket 上接受配置库的写入,控制器监听只读;用 --socket%s 或设 CLASH_SOCKET 再试", hint) + } data, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10)) message := strings.TrimSpace(string(data)) var upstream struct { @@ -467,3 +493,20 @@ func (s *session) streamEnded(cause error) error { } return failure(exitUnreachable, "stream-ended", "控制器关闭了这条流") } + +// appGroupSocketHint looks for the App's control socket so a refused write can +// name it. The identifier differs between builds, so the directory is globbed +// instead of hardcoded. +func appGroupSocketHint() string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + matches, _ := filepath.Glob(filepath.Join(home, "Library", "Group Containers", "*", "working", "clash.sock")) + for _, match := range matches { + if _, err := os.Stat(match); err == nil { + return match + } + } + return "" +} From 482e62dec14f1ded15426d233972ccc2a6de43ba Mon Sep 17 00:00:00 2001 From: jeffjiang Date: Mon, 23 Nov 2026 07:50:03 +0800 Subject: [PATCH 2/2] Share the profile store with the App across processes The app-store endpoints write config inputs (override rules and the runtime DNS patch) straight into the profile store. Without this, the derived files are only rebuilt when the app decides to regenerate them, so an edit made over the controller stayed invisible until an unrelated change forced a rebuild. A stamp keeps a fingerprint of the inputs the published revision was built from, and the activation preflight compares it before starting. profiles.json now has one writer protocol on both sides of the process boundary: the App and the kernel flock /profiles.lock around a read-modify-write, and write a new file before renaming it over the old one. The App's read-then-save sections hold that same lock, and a directory watch re-reads the store when another process changed it, republishing when the active profile's inputs moved. The lock file is the kernel's; neither side keeps a second copy of the state. --- .../Shared/ConfigResourceStore.swift | 2 + .../ConfigStore/ActiveRevisionMigration.swift | 14 +++- .../ProfileActivationCoordinator.swift | 1 + .../ConfigStore/ProfileInputsStamp.swift | 77 +++++++++++++++++++ .../Sources/ConfigStore/ProfileStore.swift | 42 ++++++++-- .../ProfileStoreCrossProcessLock.swift | 71 +++++++++++++++++ .../ProfileStoreDirectoryWatcher.swift | 73 ++++++++++++++++++ .../Sources/ConfigUI/ProfilesView.swift | 45 ++++++++++- 8 files changed, 314 insertions(+), 11 deletions(-) create mode 100644 apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift create mode 100644 apple/ClashClient/Sources/ConfigStore/ProfileStoreCrossProcessLock.swift create mode 100644 apple/ClashClient/Sources/ConfigStore/ProfileStoreDirectoryWatcher.swift diff --git a/apple/ClashClient/Shared/ConfigResourceStore.swift b/apple/ClashClient/Shared/ConfigResourceStore.swift index a6d443ab..68517dfc 100644 --- a/apple/ClashClient/Shared/ConfigResourceStore.swift +++ b/apple/ClashClient/Shared/ConfigResourceStore.swift @@ -209,6 +209,8 @@ final class ConfigResourceStore { activeDirectoryURL.appendingPathComponent(Name.compatibilityConfiguration) } + var workingDirectoryURL: URL { workingURL } + init( containerURL: URL, maximumConfigurationBytes: Int = ConfigResourceStore.defaultMaximumConfigurationBytes, diff --git a/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift b/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift index f96d0cec..be5e9325 100644 --- a/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift +++ b/apple/ClashClient/Sources/ConfigStore/ActiveRevisionMigration.swift @@ -89,7 +89,11 @@ final class ActiveRevisionMigrator { profileID: currentPointer.profileID, revision: currentPointer.revision ) - if validates(active) { + let inputsChanged = ProfileInputsStamp.inputsChanged( + currentPointer, + workingDirectory: store.workingDirectoryURL + ) + if !inputsChanged, validates(active) { return StartupConfigurationPreparation( configuration: active, recovery: .current @@ -112,8 +116,12 @@ final class ActiveRevisionMigrator { } expectedPointer = rebuiltPointer } catch { - - + if validates(active) { + return StartupConfigurationPreparation( + configuration: active, + recovery: .current + ) + } } } diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift b/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift index 384aba17..a0f09b5c 100644 --- a/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift +++ b/apple/ClashClient/Sources/ConfigStore/ProfileActivationCoordinator.swift @@ -3482,6 +3482,7 @@ final class ProfileActivationCoordinator { } PublishedSourceLedger.record(published, digest: sourceDigest?.ledger) PublishedRulesAsWritten.record(published, section: rulesAsWritten, workingDirectory: coreHomeDir) + ProfileInputsStamp.record(published, profile: profile, workingDirectory: coreHomeDir) diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift b/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift new file mode 100644 index 00000000..de1432f9 --- /dev/null +++ b/apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift @@ -0,0 +1,77 @@ +import CryptoKit +import Foundation + +enum ProfileInputsStamp { + static let fileName = "published-inputs.json" + private static let schemaVersion = 1 + private static let storeDirectoryName = "store" + + private struct Record: Codable { + let schemaVersion: Int + let profileID: String + let revision: String + let inputs: String + } + + private struct Inputs: Encodable { + let appendRules: [String] + let prependRules: Bool + let legacyRuntimePatchJSON: String? + } + + private static func url(workingDirectory: URL) -> URL { + workingDirectory + .appendingPathComponent(storeDirectoryName, isDirectory: true) + .appendingPathComponent(fileName) + } + + private static func digest(of profile: Profile) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(Inputs( + appendRules: profile.override.appendRules, + prependRules: profile.override.prependRules, + legacyRuntimePatchJSON: profile.legacyRuntimePatchJSON + )) else { return "" } + return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + + static func record(_ pointer: ActiveConfigurationPointer, profile: Profile, workingDirectory: URL) { + let file = url(workingDirectory: workingDirectory) + let record = Record( + schemaVersion: schemaVersion, + profileID: pointer.profileID, + revision: pointer.revision, + inputs: digest(of: profile) + ) + guard let data = try? JSONEncoder().encode(record) else { return } + try? FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try? data.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + } + + private static func read(workingDirectory: URL) -> Record? { + guard let data = try? Data(contentsOf: url(workingDirectory: workingDirectory)) else { return nil } + return try? JSONDecoder().decode(Record.self, from: data) + } + + static func inputsChanged(_ pointer: ActiveConfigurationPointer, workingDirectory: URL) -> Bool { + guard let profile = storedProfile(pointer.profileID, workingDirectory: workingDirectory) else { + return false + } + guard let record = read(workingDirectory: workingDirectory) else { return true } + return record.schemaVersion != schemaVersion + || record.profileID != pointer.profileID + || record.revision != pointer.revision + || record.inputs != digest(of: profile) + } + + private static func storedProfile(_ profileID: String, workingDirectory: URL) -> Profile? { + let file = workingDirectory + .appendingPathComponent(storeDirectoryName, isDirectory: true) + .appendingPathComponent("profiles.json") + return ProfileStore(fileURL: file).load().first { $0.id == profileID } + } +} diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileStore.swift b/apple/ClashClient/Sources/ConfigStore/ProfileStore.swift index 512b22bc..942acb90 100644 --- a/apple/ClashClient/Sources/ConfigStore/ProfileStore.swift +++ b/apple/ClashClient/Sources/ConfigStore/ProfileStore.swift @@ -53,7 +53,34 @@ final class ProfileStore { } func save(_ profiles: [Profile]) throws { - try Self.withWriteLock { try write(profiles) } + try withWriteLock { try write(profiles) } + } + + // Every write takes the in-process lock, then the cross-process lock file + // the kernel and the tunnel extension use, so a concurrent CLI write cannot + // land between our read and our save. + func withWriteLock(_ body: () throws -> T) throws -> T { + try Self.withWriteLock { + try fileManager.createDirectory(at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true) + let lock = crossProcessLock() + try lock.lock() + defer { lock.unlock() } + return try body() + } + } + + // Guarded by `writeLock`; one lock object per store directory so a nested + // hold on the same thread re-enters instead of deadlocking on flock. + nonisolated(unsafe) private static var crossProcessLocks: [String: ProfileStoreCrossProcessLock] = [:] + + private func crossProcessLock() -> ProfileStoreCrossProcessLock { + let directory = fileURL.deletingLastPathComponent().standardizedFileURL.path + if let lock = Self.crossProcessLocks[directory] { return lock } + let lock = ProfileStoreCrossProcessLock( + directory: URL(fileURLWithPath: directory, isDirectory: true)) + Self.crossProcessLocks[directory] = lock + return lock } @@ -98,7 +125,7 @@ final class ProfileStore { @discardableResult func updateIfPresent(id: String, when condition: (Profile) -> Bool = { _ in true }, _ change: (inout Profile) throws -> Void) throws -> Profile? { - try Self.withWriteLock { + try withWriteLock { var profiles = load() guard let index = profiles.firstIndex(where: { $0.id == id }), condition(profiles[index]) else { return nil @@ -111,6 +138,9 @@ final class ProfileStore { + // In-process only. Code that reads and then saves the whole list needs the + // instance variant, which holds the cross-process lock for the whole + // read-modify-write. static func withWriteLock(_ body: () throws -> T) rethrows -> T { writeLock.lock() lockDepth += 1 @@ -131,7 +161,7 @@ final class ProfileStore { static let didChangeNotification = Notification.Name("ClashProfileStoreDidChange") func upsert(_ profile: Profile) throws { - try Self.withWriteLock { + try withWriteLock { var profiles = load() if let idx = profiles.firstIndex(where: { $0.id == profile.id }) { profiles[idx] = profile @@ -143,7 +173,7 @@ final class ProfileStore { } func remove(id: String) throws { - try Self.withWriteLock { try write(load().filter { $0.id != id }) } + try withWriteLock { try write(load().filter { $0.id != id }) } } @@ -153,7 +183,7 @@ final class ProfileStore { @discardableResult func updateAll(_ change: (inout [Profile]) throws -> Void) throws -> Bool { - try Self.withWriteLock { + try withWriteLock { var profiles = load() let before = profiles try change(&profiles) @@ -167,7 +197,7 @@ final class ProfileStore { @discardableResult func insertIfAbsent(_ profile: Profile) throws -> Bool { - try Self.withWriteLock { + try withWriteLock { var profiles = load() guard !profiles.contains(where: { $0.id == profile.id }) else { return false } profiles.append(profile) diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileStoreCrossProcessLock.swift b/apple/ClashClient/Sources/ConfigStore/ProfileStoreCrossProcessLock.swift new file mode 100644 index 00000000..27e4c3c2 --- /dev/null +++ b/apple/ClashClient/Sources/ConfigStore/ProfileStoreCrossProcessLock.swift @@ -0,0 +1,71 @@ +import Foundation + +/// The lock every writer of `profiles.json` takes, in this process and in the +/// others: the App, the tunnel extension's app-store endpoints and `clash-cli` +/// all flock `/profiles.lock` around a read-modify-write, so a save can +/// never drop an edit made by another process in the meantime. +/// +/// The file is the same one the kernel takes (`app_store_route.go`); the +/// protocol is "flock the lock file, re-read `profiles.json`, write a new file +/// and rename it over the old one". Locking the lock file rather than the +/// store itself keeps the lock valid across the rename. +final class ProfileStoreCrossProcessLock { + enum Failure: LocalizedError, Equatable { + case unavailable(Int32) + case timedOut + + var errorDescription: String? { + switch self { + case .unavailable: + return "The profile list's lock file could not be opened, so the change was not saved." + case .timedOut: + return "Another process is still editing the profile list, so the change was not saved. Try again." + } + } + } + + private static let retryInterval: useconds_t = 20_000 + + private let fileURL: URL + private var descriptor: Int32 = -1 + private var depth = 0 + + init(directory: URL) { + fileURL = directory.appendingPathComponent("profiles.lock") + } + + /// Reentrant. A nested call deepens the hold instead of opening a second + /// descriptor, which flock would block on against its own holder. + func lock(waitingUpTo timeout: TimeInterval = 5) throws { + if depth > 0 { + depth += 1 + return + } + let descriptor = open(fileURL.path, O_CREAT | O_RDWR | O_CLOEXEC, 0o600) + guard descriptor >= 0 else { throw Failure.unavailable(errno) } + let deadline = Date().addingTimeInterval(timeout) + while flock(descriptor, LOCK_EX | LOCK_NB) != 0 { + let code = errno + guard code == EWOULDBLOCK || code == EAGAIN else { + close(descriptor) + throw Failure.unavailable(code) + } + guard Date() < deadline else { + close(descriptor) + throw Failure.timedOut + } + usleep(Self.retryInterval) + } + self.descriptor = descriptor + depth = 1 + } + + func unlock() { + guard depth > 0 else { return } + depth -= 1 + guard depth == 0, descriptor >= 0 else { return } + _ = flock(descriptor, LOCK_UN) + close(descriptor) + descriptor = -1 + } +} diff --git a/apple/ClashClient/Sources/ConfigStore/ProfileStoreDirectoryWatcher.swift b/apple/ClashClient/Sources/ConfigStore/ProfileStoreDirectoryWatcher.swift new file mode 100644 index 00000000..a0963853 --- /dev/null +++ b/apple/ClashClient/Sources/ConfigStore/ProfileStoreDirectoryWatcher.swift @@ -0,0 +1,73 @@ +import Foundation + +extension Notification.Name { + /// Posted when the profile store directory changed on disk. Writes from + /// this process post it too; observers compare the re-read store with what + /// they already have before doing anything. + static let clashProfileStoreDirectoryDidChange = + Notification.Name("ClashProfileStoreDirectoryDidChange") +} + +/// Watches a profile store directory so the App notices writes made outside +/// this process: `clash-cli`, or the tunnel extension's app-store endpoints. +@MainActor +final class ProfileStoreDirectoryWatcher { + static let shared = ProfileStoreDirectoryWatcher() + + private struct Watched { + let source: DispatchSourceFileSystemObject + } + + private var watched: [String: Watched] = [:] + private var retries: [String: DispatchWorkItem] = [:] + + func watch(directory: URL?) { + guard let directory else { return } + let path = directory.standardizedFileURL.path + guard watched[path] == nil, retries[path] == nil else { return } + start(path: path) + } + + private func start(path: String) { + let descriptor = open(path, O_EVTONLY) + guard descriptor >= 0 else { + // The store directory is created on the first save; try again a + // little later instead of watching nothing for the whole session. + retry(path: path) + return + } + let source = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .rename, .delete], + queue: .main + ) + source.setEventHandler { [weak self, weak source] in + guard let self, let source else { return } + if source.data.contains(.delete) || source.data.contains(.rename) { + // The directory itself moved or vanished: re-open it later. + self.restart(path: path) + } else { + NotificationCenter.default.post( + name: .clashProfileStoreDirectoryDidChange, object: nil) + } + } + source.setCancelHandler { close(descriptor) } + source.resume() + watched[path] = Watched(source: source) + } + + private func restart(path: String) { + watched.removeValue(forKey: path)?.source.cancel() + retry(path: path) + } + + private func retry(path: String) { + guard retries[path] == nil else { return } + let work = DispatchWorkItem { [weak self] in + self?.retries[path] = nil + self?.start(path: path) + } + retries[path] = work + DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: work) + } +} diff --git a/apple/ClashClient/Sources/ConfigUI/ProfilesView.swift b/apple/ClashClient/Sources/ConfigUI/ProfilesView.swift index ddb5bd72..7003c7d5 100644 --- a/apple/ClashClient/Sources/ConfigUI/ProfilesView.swift +++ b/apple/ClashClient/Sources/ConfigUI/ProfilesView.swift @@ -1405,6 +1405,7 @@ final class ProfilesViewModel: ObservableObject { private var republishedObserver: NSObjectProtocol? private var profileEditedObserver: NSObjectProtocol? private var providerContentObserver: NSObjectProtocol? + private var profileStoreDirectoryObserver: NSObjectProtocol? private var foregroundObserver: NSObjectProtocol? @@ -1646,6 +1647,9 @@ final class ProfilesViewModel: ObservableObject { if let providerContentObserver { NotificationCenter.default.removeObserver(providerContentObserver) } + if let profileStoreDirectoryObserver { + NotificationCenter.default.removeObserver(profileStoreDirectoryObserver) + } if let scriptLibraryObserver { NotificationCenter.default.removeObserver(scriptLibraryObserver) } @@ -1675,6 +1679,10 @@ final class ProfilesViewModel: ObservableObject { private func observeStoreReplacement() { + // The container may not be known yet on the first load; asking again on + // later loads starts the watch once it is, because this runs each time. + ProfileStoreDirectoryWatcher.shared.watch( + directory: workingDir?.appendingPathComponent("store")) guard storeReplacementObserver == nil else { return } storeReplacementObserver = NotificationCenter.default.addObserver( forName: .clashProfileStoreReplaced, @@ -1816,6 +1824,20 @@ final class ProfilesViewModel: ObservableObject { self.load() } } + + + + + + profileStoreDirectoryObserver = NotificationCenter.default.addObserver( + forName: .clashProfileStoreDirectoryDidChange, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.profilesChangedOutsideTheModel() + } + } #if os(iOS) @@ -1855,6 +1877,22 @@ final class ProfilesViewModel: ObservableObject { + // A write landed in the store from another process. Re-read it, and if the + // active profile's CLI-edited inputs changed, publish them again so the + // tunnel stops running the old rules. + private func profilesChangedOutsideTheModel() { + guard let profileStore else { return } + let stored = profileStore.load().sorted { ($0.order, $0.id) < ($1.order, $1.id) } + guard stored != profiles else { return } + load() + guard let workingDir, let container, + let store = try? ConfigResourceStore(containerURL: container), + let pointer = try? store.activePointer(), + ProfileInputsStamp.inputsChanged(pointer, workingDirectory: workingDir) + else { return } + restageIfActive(pointer.profileID) + } + func recomposeIfModulesMovedSincePublication() { guard let container, !appIsInBackground() else { return } let locations = ModuleLocations(container: container) @@ -8579,7 +8617,7 @@ final class ProfilesViewModel: ObservableObject { - private func withProfileLock(_ body: () throws -> T) rethrows -> T { + private func withProfileLock(_ body: () throws -> T) throws -> T { profileLockDepth += 1 defer { profileLockDepth -= 1 @@ -8589,7 +8627,10 @@ final class ProfilesViewModel: ObservableObject { pending.forEach { $0() } } } - return try ProfileStore.withWriteLock(body) + guard let profileStore else { return try ProfileStore.withWriteLock(body) } + // Load-then-save sections hold the same lock file the App store and the + // kernel use, so a CLI write cannot land in the middle. + return try profileStore.withWriteLock(body) }