Repository navigation
Expand file tree
/
Copy pathapp_imported.go
More file actions
422 lines (396 loc) · 15.4 KB
/
Copy pathapp_imported.go
File metadata and controls
422 lines (396 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package main
// A provider's own routing: when the user chooses it, the proxy-groups and
// rules of a complete Clash config replace the route groups (D1 in
// docs/product-ia.md). The config comes from internal/core; here is what the
// rest of the app sees of it. Its groups that rules point at are routes like
// any other, so 今日, the map, 活动 and the menu bar need no second way of
// working; what would edit bowel's route groups is out of reach until the
// user comes back to them.
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
"github.com/oboo/moho/internal/core"
"github.com/oboo/moho/internal/i18n"
"github.com/oboo/moho/internal/mcp"
"github.com/oboo/moho/internal/mihomo"
"github.com/oboo/moho/internal/provider"
"github.com/oboo/moho/internal/routes"
"github.com/oboo/moho/internal/settings"
)
// importedCache is guarded by routesMu. Reading a config is not for every
// connection: applyConfig, which follows every change of the file, drops it.
type importedCache struct {
loaded bool
key string // the provider it was read for, "" when none is in use
now *core.Imported
err string // why the routing in use could not be read
info map[string]routingInfo
}
// routingInfo is what a provider's file brings, as of updatedAt.
type routingInfo struct {
at time.Time
local string // the local files there were to match by name
routing ProviderRouting
}
// localFiles gives, for a `type: file` proxy-provider of config's, the files
// bowel keeps under that name: those of the enabled local file Providers
// called the same. The user put each there; the path the config names for
// its provider is never read (issue #75).
func (a *App) localFiles(config string) func(name string) []string {
return func(name string) []string {
var paths []string
for _, p := range a.providers.List() {
if p.Kind == provider.File && p.Enabled && p.ID != config && p.Name == name {
paths = append(paths, a.providers.Path(p.ID))
}
}
return paths
}
}
// localSig changes when what localFiles has to offer does.
func (a *App) localSig() string {
var b strings.Builder
for _, p := range a.providers.List() {
if p.Kind == provider.File && p.Enabled {
b.WriteString(p.ID + "\x00" + p.Name + "\x00")
}
}
return b.String()
}
func (a *App) dropImported() {
a.routesMu.Lock()
defer a.routesMu.Unlock()
a.imp.loaded, a.routesNow = false, nil
}
// importedNow is the routing in use from a provider's config, nil with
// bowel's own.
func (a *App) importedNow() *core.Imported {
s := a.settings.Get()
a.routesMu.Lock()
defer a.routesMu.Unlock()
return a.importedLocked(s)
}
func (a *App) importedLocked(s settings.Settings) *core.Imported {
key := ""
if p, ok := a.providers.Get(s.ImportedRouting); ok && p.Enabled {
key = p.ID
}
if a.imp.loaded && a.imp.key == key {
return a.imp.now
}
a.imp.loaded, a.imp.key, a.imp.now, a.imp.err = true, key, nil, ""
if key == "" {
return nil
}
data, err := a.providers.Content(key)
var im *core.Imported
if err == nil {
im, err = core.ParseImported(data, a.localFiles(key))
}
if err == nil && im == nil {
err = errors.New(i18n.T("这份配置里没有路由组", "This config has no route groups"))
}
if err != nil {
a.imp.err = err.Error()
return nil
}
if p, ok := a.providers.Get(key); ok {
im = im.Without(p.Hidden) // the nodes the user removed are gone from its routing too
}
// and so are those removed from the local files its proxy-providers read
for _, p := range a.providers.List() {
if p.Kind == provider.File && p.Enabled && p.ID != key {
im = im.WithoutInFile(a.providers.Path(p.ID), p.Hidden)
}
}
a.imp.now = im
return im
}
// listedNode is the name the node list has for one a group names: the
// provider's copy of a node carries its marker, the group's has none.
func (a *App) listedNode(name string, provNodes map[string][]string) string {
if a.importedNow() == nil || name == "" {
return name
}
id := a.settings.Get().ImportedRouting
if full := name + core.NodeSep + id; slices.Contains(provNodes[id], full) {
return full
}
return name
}
// sourceName is the name in the source's config of a node of the node list.
func (a *App) sourceName(node string) string {
if providerOf(node) == a.settings.Get().ImportedRouting {
return display(node)
}
return node
}
func (a *App) ruleCount(s settings.Settings) int {
if im := a.importedNow(); im != nil {
return len(im.Rules)
}
return routes.Count(a.routes()) + len(routes.Active(a.routes(), s.Rules))
}
// importedView is im as it stands in the core.
func (a *App) importedView(s settings.Settings, im *core.Imported, px map[string]mihomo.Proxy, provNodes map[string][]string) *ImportedView {
if im == nil {
return nil
}
v := &ImportedView{Provider: s.ImportedRouting, Name: a.providerTitle(s.ImportedRouting), Rules: len(im.Rules), PausedRules: len(s.Rules), PausedSets: len(a.ruleSetRefs(s)), Groups: []GroupView{}, Unused: im.Unused}
opts := s.Options.Clone()
if v.DNSFill = im.DNS.Apply(&opts); len(v.DNSFill) > 0 {
v.DNSSkipped = im.DNS.Skipped
}
byName := map[string]string{}
for _, r := range a.routes() {
byName[r.Name] = r.ID
}
groups := map[string]bool{}
for _, g := range im.Groups {
groups[core.GroupName(g)] = true
}
for _, g := range im.Groups {
name := core.GroupName(g)
p := px[name]
gv := GroupView{Name: name, Kind: core.GroupKind(g), Route: byName[name], Rules: im.RulesTo(name), Now: p.Now, Selectable: core.GroupKind(g) == "select", Members: []MemberView{}}
leaf := p.Now
for i := 0; i < 16 && px[leaf].Now != ""; i++ {
leaf = px[leaf].Now
}
if leaf != "DIRECT" && leaf != "REJECT" && leaf != "REJECT-DROP" {
gv.Exit = a.listedNode(leaf, provNodes)
}
for _, m := range p.All {
mv := MemberView{Name: m, Group: groups[m]}
if !mv.Group {
mv.Node = a.listedNode(m, provNodes)
}
if h := px[m].Results(); len(h) > 0 {
mv.Tested, mv.Delay = true, h[len(h)-1].Delay
}
gv.Members = append(gv.Members, mv)
}
v.Groups = append(v.Groups, gv)
}
return v
}
// importedIssue is the news line about the routing in use: a config that
// has stopped working, or an update that was not applied.
func (a *App) importedIssue(s settings.Settings, snap Snapshot) *Issue {
a.routesMu.Lock()
why := a.imp.err
a.routesMu.Unlock()
if why != "" {
return &Issue{Level: "warn", Text: i18n.T("读不了这份配置的路由,现在用的是 bowel 路由", "This config's routing can't be read; bowel's routing is in use"), Detail: why, Action: "providers", Label: i18n.T("查看", "View")}
}
if snap.Imported == nil {
return nil
}
for _, p := range snap.Providers {
if p.ID == s.ImportedRouting && p.Error != "" {
return &Issue{Level: "warn", Text: fmt.Sprintf(i18n.T("%s 这次更新没有应用,路由没有变化", "%s: the last update wasn't applied; the routing is unchanged"), p.Name), Detail: p.Error, Action: "providers", Label: i18n.T("查看", "View")}
}
}
a.mu.Lock()
waiting := a.impWaiting
a.mu.Unlock()
return waiting.issue(a.importedNow())
}
// importedWaiting is what a config in use names for the core to download
// that the core has nothing of: rule sets without a rule, and node
// providers without a node. The core fetches them directly, before any
// node is there to go through, so an address that can't be reached from
// this network stays empty.
type importedWaiting struct{ sets, subs []string }
func (w importedWaiting) issue(im *core.Imported) *Issue {
if im == nil || len(w.sets)+len(w.subs) == 0 {
return nil
}
hosts := im.RemoteHosts(slices.Concat(w.subs, w.sets))
detail := fmt.Sprintf(i18n.T("内核直接从 %s 下载它们,现在还没有下到。", "The core downloads them straight from %s and has not got them yet."), strings.Join(hosts, i18n.T("、", ", ")))
if len(w.subs) > 0 {
detail += " " + fmt.Sprintf(i18n.T("没有节点的订阅:%s。", "Subscriptions without nodes: %s."), strings.Join(w.subs, i18n.T("、", ", ")))
}
if len(w.sets) > 0 {
detail += " " + fmt.Sprintf(i18n.T("空的规则集:%s。用到它们的规则在下载好之前不会匹配。", "Empty rule sets: %s. The rules that use them match nothing until they arrive."), strings.Join(w.sets, i18n.T("、", ", ")))
}
detail += " " + i18n.T("如果这些地址在当前网络下打不开,可以改回 bowel 路由,或把配置里的地址换成能直连的镜像。", "If these addresses can't be opened from this network, go back to bowel's routing, or point the config at a mirror that can be reached directly.")
text := fmt.Sprintf(i18n.T("这份配置有 %d 个规则集还没下载下来", "%d of this config's rule sets haven't been downloaded"), len(w.sets))
if len(w.subs) > 0 {
text = fmt.Sprintf(i18n.T("这份配置的订阅「%s」还没下载到节点", "This config's subscription %s has no nodes yet"), w.subs[0])
}
return &Issue{Level: "warn", Text: text, Detail: detail, Action: "providers", Label: i18n.T("查看", "View")}
}
// providerRouting says what p's file brings. Asked for each snapshot, it
// reads a file only when that has changed.
func (a *App) providerRouting(p provider.Provider) ProviderRouting {
s := a.settings.Get()
local := a.localSig()
a.routesMu.Lock()
info, ok := a.imp.info[p.ID]
a.routesMu.Unlock()
if !ok || !info.at.Equal(p.UpdatedAt) || info.local != local {
info = routingInfo{at: p.UpdatedAt, local: local}
if data, err := a.providers.Content(p.ID); err == nil && core.HasGroups(data) {
if im, err := core.ParseImported(data, a.localFiles(p.ID)); err != nil {
info.routing.Problem = err.Error()
var missing *core.MissingFile
if errors.As(err, &missing) {
info.routing.NeedsFile = missing.Name
}
} else if im != nil {
info.routing.Groups, info.routing.Rules, info.routing.Remote = len(im.Groups), len(im.Rules), len(im.ProviderNames())
}
}
a.routesMu.Lock()
if a.imp.info == nil {
a.imp.info = map[string]routingInfo{}
}
a.imp.info[p.ID] = info
a.routesMu.Unlock()
}
r := info.routing
r.InUse = p.Enabled && s.ImportedRouting == p.ID && r.Groups > 0
return r
}
// vetUpdate keeps an update of the provider in use from breaking the
// routing: what comes down must still have working groups, or the last good
// file stays and the update counts as failed. Never the template instead.
func (a *App) vetUpdate(id string, data []byte) error {
s := a.settings.Get()
if s.ImportedRouting != id {
return nil
}
im, err := core.ParseImported(data, a.localFiles(id))
if err == nil && im == nil {
err = errors.New(i18n.T("这次下载的内容里没有路由组", "What was downloaded has no route groups"))
}
if err == nil {
err = a.checkImported(s, im)
}
if err != nil {
return fmt.Errorf(i18n.T("这次更新没有应用,继续用上一份:%w", "This update wasn't applied; the last one stays: %w"), err)
}
return nil
}
func (a *App) checkImported(s settings.Settings, im *core.Imported) error {
cfg, err := a.buildConfig(s, overlayOf(s, a.devEnv()), im)
if err != nil {
return err
}
return a.core.Check(cfg)
}
// setImportedRouting uses provider id's own routing; "" goes back to
// bowel's. The user's rules and route groups are not touched either way.
// Connections already open would stay on the old routing: they are closed
// so that the change shows at once, as a change of rules does.
func (a *App) setImportedRouting(id string) error {
if id != "" {
p, ok := a.providers.Get(id)
if !ok {
return fmt.Errorf(i18n.T("没有这个 Provider: %s", "No such Provider: %s"), id)
}
if !p.Enabled {
return errors.New(i18n.T("这个 Provider 已停用", "This Provider is disabled"))
}
data, err := a.providers.Content(id)
if err != nil {
return err
}
im, err := core.ParseImported(data, a.localFiles(id))
if err != nil {
return err
}
if im == nil {
return errors.New(i18n.T("这份配置里没有路由组", "This config has no route groups"))
}
}
if err := a.updateSettings(func(s *settings.Settings) { s.ImportedRouting = id }); err != nil {
return err
}
_ = a.coreCall(5*time.Second, func(ctx context.Context, c *mihomo.Client) error { return c.CloseAllConnections(ctx) })
go a.locateExits(false)
return nil
}
// fillImportedDNS copies the DNS servers, policy, fake-ip filter and hosts
// of the config in use into the settings, and says which of the config's
// keys it took. Once, when asked: from then on they are settings like any
// typed in, and an update of the config does not change them. A list the
// config lacks stays as it is. If the core refuses the result, the settings
// are as they were.
func (a *App) fillImportedDNS() ([]string, error) {
im := a.importedNow()
if im == nil {
return nil, errors.New(i18n.T("没有在使用导入配置的路由", "No imported config's routing is in use"))
}
var took []string
if err := a.updateSettings(func(s *settings.Settings) { took = im.DNS.Apply(&s.Options) }); err != nil {
return nil, err
}
return took, nil
}
// selectMember points an imported group of the kind the user chooses in at
// member. The core remembers it across reloads (store-selected).
func (a *App) selectMember(group, member string) error {
im := a.importedNow()
if im == nil {
return errors.New(i18n.T("没有这个路由组", "No such route group"))
}
g, ok := im.GroupOf(group)
if !ok {
return errors.New(i18n.T("没有这个路由组", "No such route group"))
}
if core.GroupKind(g) != "select" {
return fmt.Errorf(i18n.T("「%s」的类型是 %s,由内核自己选择", "%s is of the kind %s: the core chooses by itself"), group, core.GroupKind(g))
}
if member == "" {
return errors.New(i18n.T("这个路由组需要选一个成员", "This route group needs a member chosen"))
}
done := a.begin("group:" + group)
defer done()
if err := a.coreCall(5*time.Second, func(ctx context.Context, c *mihomo.Client) error { return c.Select(ctx, group, member) }); err != nil {
return err
}
a.refresh()
return nil
}
// rulesEditable refuses a change to the user's rules while an imported
// config has them paused: it could not take effect.
func (a *App) rulesEditable() error {
if a.importedNow() != nil {
return errors.New(i18n.T("正在使用导入配置的路由,你的规则已暂停。改回 bowel 路由后才能修改", "An imported config's routing is in use and your rules are paused. Go back to bowel's routing to change them"))
}
return nil
}
// mcpImported is the imported routing as agents read it.
func mcpImported(v *ImportedView) map[string]any {
groups := make([]map[string]any, 0, len(v.Groups))
for _, g := range v.Groups {
members := make([]string, 0, len(g.Members))
for _, m := range g.Members {
members = append(members, m.Name)
}
groups = append(groups, map[string]any{"name": g.Name, "kind": g.Kind, "now": g.Now, "exit": display(g.Exit), "selectable": g.Selectable, "rules": g.Rules, "members": members})
}
unused := v.Unused
if unused == nil {
unused = []string{}
}
return map[string]any{"provider": v.Name, "rules": v.Rules, "pausedUserRules": v.PausedRules, "pausedRuleSets": v.PausedSets, "groups": groups, "unusedSettings": unused}
}
// mcpSelectMember is select_node under an imported config.
func (a *App) mcpSelectMember(ctx context.Context, s *mcp.Session, group, member string) (any, error) {
if r, err := a.findRoute(group); err == nil {
group = routes.Group(r)
}
member = a.sourceName(member)
err := a.change(ctx, s, words{"切换路由组的成员", "Choose a route group's member"}, group+" → "+member, func() error { return a.selectMember(group, member) })
if err != nil {
return nil, err
}
return fmt.Sprintf("%s now uses %s.", group, member), nil
}