-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathradiance.go
More file actions
1623 lines (1449 loc) · 52.9 KB
/
Copy pathradiance.go
File metadata and controls
1623 lines (1449 loc) · 52.9 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package backend provides the main interface for all the major components of Radiance.
package backend
import (
"context"
"errors"
"fmt"
"log/slog"
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"sync"
"time"
"github.com/Xuanwo/go-locale"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
C "github.com/getlantern/common"
"github.com/getlantern/publicip"
"github.com/getlantern/radiance/account"
"github.com/getlantern/radiance/common"
"github.com/getlantern/radiance/common/deviceid"
"github.com/getlantern/radiance/common/env"
"github.com/getlantern/radiance/common/settings"
"github.com/getlantern/radiance/config"
"github.com/getlantern/radiance/events"
"github.com/getlantern/radiance/internal"
"github.com/getlantern/radiance/issue"
"github.com/getlantern/radiance/kindling"
"github.com/getlantern/radiance/log"
"github.com/getlantern/radiance/servers"
"github.com/getlantern/radiance/telemetry"
"github.com/getlantern/radiance/traces"
"github.com/getlantern/radiance/unbounded"
"github.com/getlantern/radiance/vpn"
lbA "github.com/getlantern/lantern-box/adapter"
"github.com/sagernet/sing-box/option"
)
const tracerName = "github.com/getlantern/radiance/backend"
// LocalBackend ties all the core functionality of Radiance together. It manages the configuration,
// servers, VPN connection, account management, issue reporting, and telemetry for the application.
//
// A nil LocalBackend is valid for reporting issues.
type LocalBackend struct {
ctx context.Context
cancel context.CancelFunc
confHandler *config.ConfigHandler
issueReporter *issue.IssueReporter
accountClient *account.Client
srvManager *servers.Manager
vpnClient *vpn.VPNClient
splitTunnelMgr *vpn.SplitTunnel
sessionHistory *vpn.SessionHistory
peerClient peerController
peerToggleMu sync.Mutex
peerWG sync.WaitGroup
shutdownFuncs []func() error
closeOnce sync.Once
deviceID string
telemetryCfgSub *events.Subscription[config.NewConfigEvent]
// reused across reconnects; fully released only when telemetry shuts down.
connObserver vpn.ConnObserver
stopConnMetrics context.CancelFunc
connMetricsMu sync.Mutex
dataCapCh chan *account.DataCapInfo // latest datacap update; nil when stream not running
stopDataCap context.CancelFunc
dataCapMu sync.Mutex
stopSelectionHistoryListener context.CancelFunc
selectionHistoryMu sync.Mutex
selectionReporter *selectionReporter
exhaustionGate exhaustionGate
}
type Options struct {
DataDir string
LogDir string
Locale string
LogLevel string
// this should be the platform device ID on mobile devices, desktop platforms will generate their
// own device ID and ignore this value
DeviceID string
// User choice for telemetry consent
TelemetryConsent bool
PlatformInterface vpn.PlatformInterface
// EnvOverrides are applied via os.Setenv before common.Init so sandboxed
// system extensions (macOS/iOS), which don't inherit shell env, still see
// RADIANCE_* vars from the host process. Entries are set verbatim — no
// filtering.
EnvOverrides map[string]string
}
// NewLocalBackend performs global initialization and returns a new LocalBackend instance.
// It should be called once at the start of the application.
func NewLocalBackend(ctx context.Context, opts Options) (*LocalBackend, error) {
// Invariant: a user must always be able to construct a backend and report an
// issue, even when on-disk state is unreadable or incompatible (e.g. after a
// downgrade). Failures loading the server manager, split tunnel, and config
// are logged and degraded, never returned. The only fatal path is
// common.Init, which fails only when the data directory or settings file
// can't be created or read — i.e. the app genuinely cannot run.
// Must run before common.Init: it reads RADIANCE_VERSION once and
// freezes it, so a later Setenv is ignored by the header-fill path.
var envOverrideErrs error
for k, v := range opts.EnvOverrides {
if err := os.Setenv(k, v); err != nil {
envOverrideErrs = errors.Join(envOverrideErrs, fmt.Errorf("apply env override %q: %w", k, err))
}
}
if err := common.Init(opts.DataDir, opts.LogDir, opts.LogLevel); err != nil {
return nil, fmt.Errorf("failed to initialize common components: %w", err)
}
if envOverrideErrs != nil {
slog.Warn("Failed to apply some env overrides", "error", envOverrideErrs)
}
if opts.Locale == "" {
if tag, err := locale.Detect(); err != nil {
opts.Locale = "en-US"
} else {
opts.Locale = tag.String()
}
}
var platformDeviceID string
switch common.Platform {
case "ios", "android":
// The device ID is owned by the native caller and shared to the extension
// through persisted settings so both use the same ID. Unlike the desktop
// branch, don't generate one here — log and continue if it's absent.
switch {
case opts.DeviceID != "":
platformDeviceID = opts.DeviceID
case settings.Exists(settings.DeviceIDKey):
if platformDeviceID = settings.GetString(settings.DeviceIDKey); platformDeviceID == "" {
slog.Warn("No device ID was found")
}
default:
slog.Warn("No device ID was found")
}
default:
platformDeviceID = deviceid.Get(settings.GetString(settings.DataPathKey))
}
dataDir := settings.GetString(settings.DataPathKey)
disableFetch := env.GetBool(env.DisableFetch)
settings.Patch(settings.Settings{
settings.LocaleKey: opts.Locale,
settings.DeviceIDKey: platformDeviceID,
settings.ConfigFetchDisabledKey: disableFetch,
settings.TelemetryKey: opts.TelemetryConsent,
})
accountClient := account.NewClient(kindling.HTTPClient(), dataDir)
svrMgr, err := servers.NewManager(
dataDir, slog.Default().With("service", "server_manager"),
)
if err != nil {
slog.Error("Loading server manager", "error", err)
}
splitTunnelMgr, err := vpn.NewSplitTunnelHandler(
dataDir, slog.Default().With("service", "split_tunnel"),
)
if err != nil {
slog.Error("Loading split tunnel handler", "error", err)
}
vpnClient := vpn.NewVPNClient(dataDir, slog.Default().With("service", "vpn"), opts.PlatformInterface)
peerClient, err := newPeerClient(platformDeviceID)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(ctx)
cOpts := config.Options{
DataPath: dataDir,
Locale: opts.Locale,
AccountClient: accountClient,
HTTPClient: kindling.HTTPClient(),
Logger: slog.Default().With("service", "config_handler"),
}
r := &LocalBackend{
ctx: ctx,
cancel: cancel,
issueReporter: issue.NewIssueReporter(kindling.HTTPClient()),
selectionReporter: newSelectionReporter(kindling.HTTPClient()),
accountClient: accountClient,
confHandler: config.NewConfigHandler(ctx, cOpts),
srvManager: svrMgr,
vpnClient: vpnClient,
splitTunnelMgr: splitTunnelMgr,
peerClient: peerClient,
shutdownFuncs: []func() error{
telemetry.Close, kindling.Close,
},
closeOnce: sync.Once{},
deviceID: platformDeviceID,
dataCapCh: make(chan *account.DataCapInfo, 1),
}
r.sessionHistory = vpn.NewSessionHistory(slog.Default().With("service", "session_history"), r.sessionInfo())
r.shutdownFuncs = append(r.shutdownFuncs, func() error { r.sessionHistory.Close(); return nil })
r.clearSelectedIfMissing()
return r, nil
}
func (r *LocalBackend) Start() {
// eagerly start kindling so it's ready by the time we need to make network requests
kindling.Init()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
result, err := publicip.Detect(ctx, &publicip.Config{
Timeout: 2 * time.Second,
MinConsensus: 1,
Methods: publicip.DefaultMethods(),
})
cancel()
if err != nil {
slog.Warn("Failed to get public IP", "error", err)
} else {
common.SetPublicIP(result.IP.String())
// IP intentionally omitted — Lantern users in censored regions
// can't safely have their public IP in routinely-collected
// client logs. Confidence + sources are enough for operator
// triage; the actual IP is correlated server-side via traces.
slog.Info("Detected public IP", "confidence", result.Confidence, "sources", result.Sources)
}
}()
if settings.GetBool(settings.TelemetryKey) {
if err := r.startTelemetry(); err != nil {
slog.Error("Failed to start telemetry", "error", err)
}
}
r.startVPNStatusListeners()
r.startAutoSelectedListener()
r.startSessionAutoSelectListener()
r.resumePeerShareIfEnabled()
// Wire the broflake / Unbounded widget proxy lifecycle to config
// updates. This single subscription handles all three start/stop
// triggers (local toggle, server feature flag, server-supplied
// config); InitSubscription is sync.Once-guarded so a future Start
// retry after Close won't double-subscribe.
//
// Seed with the already-cached config (loaded from disk before
// Start runs) so an opted-in user auto-starts the widget on
// launch instead of waiting for the next config refresh.
cachedCfg, _ := r.confHandler.GetConfig()
unbounded.InitSubscription(cachedCfg)
// The server derives the country from the client IP, so it's stable for the
// session: react once to record it for issue reports and to apply the
// country-specific transport policy (AMP is disabled in China).
events.SubscribeOnce(func(evt config.NewConfigEvent) {
setCountryCodeFromConfig(evt.New)
applyTransportPolicy()
})
// update VPN outbounds when new config is received
events.SubscribeContext(r.ctx, func(evt config.NewConfigEvent) {
r.applyConfig(evt.New)
go r.prewarmOfflineURLTests("config update")
})
if r.applyCurrentConfig() {
go r.prewarmOfflineURLTests("cached config")
}
r.confHandler.Start()
}
// applyCurrentConfig applies any config already loaded from disk before the
// fetch loop has a chance to refresh it.
func (r *LocalBackend) applyCurrentConfig() bool {
cfg, err := r.confHandler.GetConfig()
if err != nil {
return false
}
setCountryCodeFromConfig(cfg)
applyTransportPolicy()
r.applyConfig(cfg)
return true
}
// prewarmOfflineURLTests records reachability history for the not-yet-connected
// tunnel path and treats connected-tunnel races as harmless.
func (r *LocalBackend) prewarmOfflineURLTests(source string) {
if err := r.RunOfflineURLTests(); err != nil && !errors.Is(err, vpn.ErrTunnelAlreadyConnected) {
// ErrTunnelAlreadyConnected is expected while the VPN is up:
// updateServers already pushed the new outbounds into the live
// tunnel via UpdateOutbounds, so the offline pre-warm, which
// targets the not-yet-connected case, would duplicate work and
// conflict with the live auto-select group.
slog.Error("Failed to run offline URL tests", "source", source, "error", err)
}
}
// applyConfig updates the runtime server state from a config snapshot.
// Startup-loaded cached configs and freshly fetched configs both use this path.
func (r *LocalBackend) applyConfig(cfg *config.Config) {
if cfg == nil {
return
}
list := serverListFromConfig(cfg)
if len(cfg.BanditURLOverrides) > 0 {
if ctx, ok := traces.ExtractBanditTraceContext(cfg.BanditURLOverrides); ok {
// Link this marker span to the API's bandit trace so config receipt
// and the per-outbound callback stay visible in one distributed trace.
_, span := otel.Tracer(tracerName).Start(ctx, "radiance.config_received",
trace.WithAttributes(
attribute.Int("bandit.override_count", len(cfg.BanditURLOverrides)),
attribute.Int("bandit.outbound_count", len(cfg.Options.Outbounds)),
),
)
span.End()
}
}
if err := r.updateServers(list); err != nil {
slog.Error("updating servers in manager", "error", err)
}
}
// setCountryCodeFromConfig stores the config country for diagnostics unless
// an explicit country override is active.
func setCountryCodeFromConfig(cfg *config.Config) {
if env.GetString(env.Country) != "" || cfg == nil || cfg.Country == "" {
return
}
if err := settings.Set(settings.CountryCodeKey, cfg.Country); err != nil {
slog.Error("failed to set country code in settings", "error", err)
}
slog.Info("Set country code from config", "country_code", cfg.Country)
}
// ampEnabledForCountry reports whether the AMP transport works from the given
// country. AMP fronts through Google domains that are unreachable from China.
func ampEnabledForCountry(country string) bool {
return !strings.EqualFold(country, "CN")
}
// applyTransportPolicy enables or disables the AMP transport based on the
// user's country and rebuilds kindling when that changes the enabled set. The
// env override takes precedence over the config-derived country in settings.
func applyTransportPolicy() {
country := settings.GetString(settings.CountryCodeKey)
if override := env.GetString(env.Country); override != "" {
country = override
}
if kindling.EnableTransport(kindling.TransportAMP, ampEnabledForCountry(country)) {
kindling.Close()
kindling.Init()
}
}
// serverListFromConfig converts config outbounds and endpoints into managed
// Lantern servers while preserving location and bandit URL metadata.
func serverListFromConfig(cfg *config.Config) servers.ServerList {
srvs := make([]*servers.Server, 0, len(cfg.Options.Outbounds)+len(cfg.Options.Endpoints))
addSvr := func(tag, typ string, opts any, loc *C.ServerLocation) {
s := &servers.Server{
Tag: tag, Type: typ, IsLantern: true, Options: opts,
}
if loc != nil {
s.Location = *loc
}
srvs = append(srvs, s)
}
for _, out := range cfg.Options.Outbounds {
addSvr(out.Tag, out.Type, out, cfg.OutboundLocations[out.Tag])
}
for _, ep := range cfg.Options.Endpoints {
addSvr(ep.Tag, ep.Type, ep, cfg.OutboundLocations[ep.Tag])
}
return servers.ServerList{Servers: srvs, URLOverrides: cfg.BanditURLOverrides}
}
func (r *LocalBackend) Close() {
r.closeOnce.Do(func() {
slog.Debug("Closing Radiance")
r.closePeerClient()
// unbounded.start spawns its worker on a context.Background-
// derived ctx (it has to outlive any single NewConfigEvent),
// so Close has to explicitly tell it to shut down — otherwise
// the broflake widget goroutine survives backend close and
// leaks until process exit. Use a fresh ctx so a cancelled
// shutdown path doesn't skip the Stop.
stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := unbounded.Stop(stopCtx); err != nil {
slog.Warn("unbounded stop on backend close returned error", "error", err)
}
cancel()
// vpnClient is always set in production via NewLocalBackend, but
// peer-focused unit tests construct partial LocalBackends without
// one. Guard the call so Close stays robust under those paths
// rather than panicking in DisconnectVPN.
if r.vpnClient != nil {
if err := r.DisconnectVPN(); err != nil {
slog.Error("Failed to disconnect VPN on shutdown", "error", err)
}
}
r.cancel() // cancels context, unsubscribes all event listeners and stops child goroutines
for _, shutdown := range r.shutdownFuncs {
if err := shutdown(); err != nil {
slog.Error("Failed to shutdown", "error", err)
}
}
})
}
func (r *LocalBackend) startVPNStatusListeners() {
events.SubscribeContext(r.ctx, func(evt vpn.StatusUpdateEvent) {
r.updateConnMetrics(evt.Status)
})
events.SubscribeContext(r.ctx, func(evt vpn.StatusUpdateEvent) {
r.updateDataCapStream(evt.Status)
})
events.SubscribeContext(r.ctx, func(evt vpn.StatusUpdateEvent) {
r.updateSelectionHistoryListener(evt.Status)
})
events.SubscribeContext(r.ctx, func(vpn.ExhaustionEvent) {
r.refetchOnExhaustion()
})
events.SubscribeContext(r.ctx, func(evt vpn.StatusUpdateEvent) {
switch evt.Status {
case vpn.Disconnected, vpn.ErrorStatus, vpn.Restarting:
r.clearSelectedIfMissing()
}
})
}
func (r *LocalBackend) sessionInfo() vpn.SessionInfo {
return vpn.SessionInfo{
Status: r.vpnClient.Status,
SelectedServer: func() (tag, city, country string) {
server, _, err := r.SelectedServer()
if err != nil || server == nil {
return "", "", ""
}
return server.Tag, server.Location.City, server.Location.Country
},
Bytes: r.vpnClient.Bytes,
}
}
func (r *LocalBackend) Sessions(limit int) []vpn.Session {
return r.sessionHistory.Sessions(limit)
}
//////////////////
// Issue Report //
//////////////////
type issueReportMetadata struct {
country string
deviceID string
reporter *issue.IssueReporter
splitTunnelEnabled bool
}
// buildIssueReportMetadata gathers the backend state needed to file an issue
// report. It is safe to call with a nil or partially initialized backend.
func (r *LocalBackend) buildIssueReportMetadata() issueReportMetadata {
meta := issueReportMetadata{
country: settings.GetString(settings.CountryCodeKey),
}
if r == nil {
meta.reporter = issue.NewIssueReporter(kindling.HTTPClient())
return meta
}
if r.issueReporter != nil {
meta.reporter = r.issueReporter
} else {
meta.reporter = issue.NewIssueReporter(kindling.HTTPClient())
}
meta.deviceID = r.deviceID
// get country from the config returned by the backend
if r.confHandler != nil {
if cfg, err := r.confHandler.GetConfig(); err != nil {
slog.Warn("failed to get config", "error", err)
} else {
if cfg.Country != "" {
meta.country = cfg.Country
}
}
}
if r.splitTunnelMgr != nil {
meta.splitTunnelEnabled = r.splitTunnelMgr.IsEnabled()
}
return meta
}
// ReportIssue allows the user to report an issue with the application. It collects relevant
// information about the user's environment such as country, device ID, user ID, subscription level,
// and locale, and log files to include in the report.
//
// ReportIssue is safe to call with a nil receiver.
func (r *LocalBackend) ReportIssue(issueType issue.IssueType, description, email string, additionalAttachments []string, attachments []*issue.Attachment) error {
ctx, span := otel.Tracer(tracerName).Start(context.Background(), "report_issue")
defer span.End()
meta := r.buildIssueReportMetadata()
attachmentPaths := baseIssueAttachments()
if meta.splitTunnelEnabled {
attachmentPaths = append(attachmentPaths, filepath.Join(settings.GetString(settings.DataPathKey), internal.SplitTunnelFileName))
}
attachmentPaths = append(attachmentPaths, additionalAttachments...)
report := issue.IssueReport{
Type: issueType,
Description: description,
Email: email,
CountryCode: meta.country,
DeviceID: meta.deviceID,
UserID: settings.GetString(settings.UserIDKey),
SubscriptionLevel: settings.GetString(settings.UserLevelKey),
Locale: settings.GetString(settings.LocaleKey),
Attachments: attachments,
AdditionalAttachments: attachmentPaths,
}
if err := meta.reporter.Report(ctx, report); err != nil {
slog.Error("Failed to report issue", "error", err)
return traces.RecordError(ctx, fmt.Errorf("failed to report issue: %w", err))
}
slog.Info("Issue reported successfully")
return nil
}
// baseIssueAttachments returns a list of file paths to include as attachments in every issue report
// in order of importance.
func baseIssueAttachments() []string {
logPath := settings.GetString(settings.LogPathKey)
dataPath := settings.GetString(settings.DataPathKey)
files := []string{
filepath.Join(logPath, internal.CrashLogFileName),
filepath.Join(dataPath, internal.ConfigFileName),
filepath.Join(dataPath, internal.ServersFileName),
filepath.Join(dataPath, internal.DebugBoxOptionsFileName),
}
memdump := filepath.Join(logPath, internal.MemoryDumpFileName)
if _, err := os.Stat(memdump); err == nil {
// put memory dump first in the list so it's prioritized.
files = append([]string{memdump}, files...)
}
return files
}
/////////////////
// Settings //
/////////////////
// UpdateConfig forces an immediate fetch of the latest configuration. It returns
// [config.ErrConfigFetchDisabled] if config fetching is disabled in settings.
func (r *LocalBackend) UpdateConfig() error {
return r.confHandler.Fetch()
}
// Features returns the features available in the current configuration, returned from the server in the
// config response.
func (r *LocalBackend) Features() map[string]bool {
_, span := otel.Tracer(tracerName).Start(context.Background(), "features")
defer span.End()
cfg, err := r.confHandler.GetConfig()
if err != nil {
slog.Info("Failed to get config for features", "error", err)
return map[string]bool{}
}
if cfg == nil {
slog.Info("No config available for features, returning empty map")
return map[string]bool{}
}
slog.Debug("Returning features from config", "features", cfg.Features)
if cfg.Features == nil {
slog.Info("No features available in config, returning empty map")
return map[string]bool{}
}
return cfg.Features
}
func (r *LocalBackend) PatchSettings(updates settings.Settings) error {
curr := settings.GetAllFor(slices.Collect(maps.Keys(updates))...)
diff := updates.Diff(curr)
slog.Log(nil, log.LevelTrace, "Patching settings", "updates", updates, "current", curr, "diff", diff)
if len(diff) == 0 {
return nil
}
if err := settings.Patch(diff); err != nil {
return fmt.Errorf("failed to update settings: %w", err)
}
// telemetry settings
if _, ok := diff[settings.TelemetryKey]; ok {
if settings.GetBool(settings.TelemetryKey) {
if err := r.startTelemetry(); err != nil {
slog.Error("Failed to start telemetry", "error", err)
}
} else {
r.stopTelemetry()
}
}
// vpn settings
k := settings.SplitTunnelKey
if _, ok := diff[k]; ok {
r.splitTunnelMgr.SetEnabled(settings.GetBool(k))
}
if err := r.maybeRestartVPN(diff); err != nil {
return err
}
if _, ok := diff[settings.PeerShareEnabledKey]; ok {
if err := r.applyPeerShare(settings.GetBool(settings.PeerShareEnabledKey)); err != nil {
return err
}
}
// Drive the Unbounded widget proxy off the toggle change immediately
// rather than waiting for the next NewConfigEvent to re-evaluate.
// settings.Patch above has already persisted the new value, so go
// straight to Apply() — SetEnabled would short-circuit on the
// already-matching persisted value and never re-evaluate the
// manager. Apply re-checks the three-condition predicate against
// the cached server-side state and starts or stops accordingly.
if _, ok := diff[settings.UnboundedKey]; ok {
if err := unbounded.Apply(); err != nil {
slog.Warn("unbounded apply failed", "error", err)
}
}
return nil
}
// maybeRestartVPN restarts the VPN connection if either the ad block or smart routing settings
// were changed and the VPN is currently connected. Returns an error if the VPN restart fails;
// otherwise returns nil.
func (r *LocalBackend) maybeRestartVPN(updates settings.Settings) error {
_, adBlockChanged := updates[settings.AdBlockKey]
_, smartRoutingChanged := updates[settings.SmartRoutingKey]
if (adBlockChanged || smartRoutingChanged) && r.vpnClient.Status() == vpn.Connected {
slog.Info("Restarting VPN to apply new settings", "ad_block_changed", adBlockChanged, "smart_routing_changed", smartRoutingChanged)
if err := r.RestartVPN(); err != nil {
return fmt.Errorf(
"failed to restart VPN (ad_block_changed=%v, smart_routing_changed=%v): %w",
adBlockChanged, smartRoutingChanged, err,
)
}
}
return nil
}
/////////////////
// telemetry //
/////////////////
func (r *LocalBackend) startTelemetry() error {
cfg, err := r.confHandler.GetConfig()
if err == nil {
if err := telemetry.Initialize(r.deviceID, *cfg, settings.IsPro()); err != nil {
return fmt.Errorf("failed to initialize telemetry: %w", err)
}
}
if r.telemetryCfgSub != nil {
return nil
}
// subscribe to config changes to update telemetry config
r.telemetryCfgSub = events.SubscribeContext(r.ctx, func(evt config.NewConfigEvent) {
if !settings.GetBool(settings.TelemetryKey) {
return
}
if evt.Old != nil && reflect.DeepEqual(evt.Old.OTEL, evt.New.OTEL) {
// no changes to telemetry config, no need to update
return
}
if err := telemetry.Initialize(r.deviceID, *evt.New, settings.IsPro()); err != nil {
slog.Error("Failed to update telemetry config", "error", err)
}
})
return nil
}
func (r *LocalBackend) stopTelemetry() {
if r.telemetryCfgSub != nil {
r.telemetryCfgSub.Unsubscribe()
r.telemetryCfgSub = nil
}
r.teardownConnMetrics()
telemetry.Close()
}
func (r *LocalBackend) updateConnMetrics(status vpn.VPNStatus) {
if !settings.GetBool(settings.TelemetryKey) {
return
}
r.connMetricsMu.Lock()
defer r.connMetricsMu.Unlock()
if status != vpn.Connected {
r.vpnClient.SetConnObserver(nil)
return
}
if !r.ensureConnMetricsObserverLocked() {
return
}
r.vpnClient.SetConnObserver(r.connObserver)
}
func (r *LocalBackend) ensureConnMetricsObserverLocked() bool {
if r.connObserver != nil {
return true
}
ctx, cancel := context.WithCancel(r.ctx)
observer, err := telemetry.StartConnectionMetrics(ctx, r.vpnClient.ActiveConnectionCount)
if err != nil {
cancel()
slog.Warn("Failed to start connection metrics collection", "error", err)
return false
}
r.connObserver = observer
r.stopConnMetrics = cancel
return true
}
// teardownConnMetrics fully detaches and releases the connection metrics observer.
func (r *LocalBackend) teardownConnMetrics() {
r.connMetricsMu.Lock()
defer r.connMetricsMu.Unlock()
if r.vpnClient != nil {
r.vpnClient.SetConnObserver(nil)
}
if r.stopConnMetrics != nil {
r.stopConnMetrics()
r.stopConnMetrics = nil
}
r.connObserver = nil
}
///////////////////////
// Server management //
///////////////////////
func (r *LocalBackend) AllServers() []*servers.Server {
return r.srvManager.AllServers()
}
func (r *LocalBackend) GetServerByTag(tag string) (*servers.Server, bool) {
return r.srvManager.GetServerByTag(tag)
}
func (r *LocalBackend) RemoveServers(tags []string) error {
removed, err := r.srvManager.RemoveServers(tags)
if err != nil {
return fmt.Errorf("failed to remove servers from ServerManager: %w", err)
}
removedTags := make([]string, 0, len(removed))
for _, srv := range removed {
removedTags = append(removedTags, srv.Tag)
}
if len(removedTags) > 0 {
r.clearSelectedIfMissing()
if err := r.vpnClient.RemoveOutbounds(removedTags); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
return fmt.Errorf("failed to remove outbounds: %w", err)
}
}
return nil
}
func (r *LocalBackend) AddServers(list servers.ServerList) error {
if err := r.srvManager.AddServers(list, false); err != nil {
return fmt.Errorf("failed to add servers to ServerManager: %w", err)
}
if err := r.vpnClient.AddOutbounds(list); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
return fmt.Errorf("failed to add outbounds to VPN client: %w", err)
}
return nil
}
func (r *LocalBackend) AddServersByJSON(config string) ([]string, error) {
list, err := r.srvManager.AddServersByJSON(r.ctx, []byte(config))
if err != nil {
return nil, fmt.Errorf("failed to add servers by JSON: %w", err)
}
if err := r.vpnClient.AddOutbounds(*list); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
return nil, fmt.Errorf("failed to add outbounds to VPN client: %w", err)
}
return list.Tags(), nil
}
func (r *LocalBackend) AddServersByURL(urls []string, skipCertVerification bool) ([]string, error) {
list, err := r.srvManager.AddServersByURL(r.ctx, urls, skipCertVerification)
if err != nil {
return nil, fmt.Errorf("failed to add servers by URL: %w", err)
}
if err := r.vpnClient.AddOutbounds(*list); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
return nil, fmt.Errorf("failed to add outbounds to VPN client: %w", err)
}
return list.Tags(), nil
}
func (r *LocalBackend) AddPrivateServer(tag, ip string, port int, accessToken string, loc C.ServerLocation, joined bool) error {
return r.srvManager.AddPrivateServer(tag, ip, port, accessToken, loc, joined)
}
func (r *LocalBackend) InviteToPrivateServer(ip string, port int, accessToken string, inviteName string) (string, error) {
return r.srvManager.InviteToPrivateServer(ip, port, accessToken, inviteName)
}
func (r *LocalBackend) RevokePrivateServerInvite(ip string, port int, accessToken string, inviteName string) error {
return r.srvManager.RevokePrivateServerInvite(ip, port, accessToken, inviteName)
}
// maxRetainedLanternServers caps the number of working Lantern servers retained
// across config updates.
const maxRetainedLanternServers = 60
func (r *LocalBackend) updateServers(list servers.ServerList) error {
existing := r.srvManager.AllServers()
existingTags := serverTagSet(existing)
list.Servers = slices.DeleteFunc(list.Servers, func(srv *servers.Server) bool {
_, exists := existingTags[srv.Tag]
return exists
})
tagsToEvict := lanternServersToEvict(existing, len(list.Servers), maxRetainedLanternServers)
if len(tagsToEvict) > 0 {
slog.Debug(
"Evicting retained Lantern servers to make room for new config batch",
"count", len(tagsToEvict),
"tags", tagsToEvict,
)
if _, err := r.srvManager.RemoveServers(tagsToEvict); err != nil {
return fmt.Errorf("remove retained Lantern servers: %w", err)
}
}
slog.Debug(
"Adding new Lantern servers from config update",
"count", len(list.Servers),
"tags", slices.Collect(maps.Keys(serverTagSet(list.Servers))),
)
if err := r.srvManager.AddServers(list, false); err != nil {
return fmt.Errorf("add Lantern servers: %w", err)
}
// updateOutbounds evicts any outbound absent from the list; include all
// servers so user-added outbounds aren't removed on a Lantern config update.
allList := servers.ServerList{Servers: r.srvManager.AllServers(), URLOverrides: list.URLOverrides}
if err := r.vpnClient.UpdateOutbounds(allList); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
return fmt.Errorf("failed to update VPN outbounds: %w", err)
}
if r.vpnClient.Status() != vpn.Connected {
r.clearSelectedIfMissing()
}
return nil
}
func serverTagSet(list []*servers.Server) map[string]struct{} {
tags := make(map[string]struct{}, len(list))
for _, srv := range list {
tags[srv.Tag] = struct{}{}
}
return tags
}
// lanternServersToEvict returns the Lantern server tags to remove before the
// next config batch is added. Hard-demoted servers are always evicted so a
// later re-offer is treated as a fresh candidate and re-probed. Remaining
// candidates are evicted oldest-first by SelectionHistory.UpdatedAt; missing
// history sorts oldest.
func lanternServersToEvict(
existing []*servers.Server,
incomingCount, limit int,
) []string {
tagsToEvict := make([]string, 0)
retentionCandidates := make([]*servers.Server, 0, len(existing))
for _, srv := range existing {
if !srv.IsLantern {
continue
}
// Always evict hard-demoted servers.
if isHardDemoted(srv) {
tagsToEvict = append(tagsToEvict, srv.Tag)
continue
}
retentionCandidates = append(retentionCandidates, srv)
}
retentionBudget := max(limit-incomingCount, 0)
if len(retentionCandidates) <= retentionBudget {
return tagsToEvict
}
slices.SortFunc(retentionCandidates, compareSelectionAge)
overflow := len(retentionCandidates) - retentionBudget
for _, srv := range retentionCandidates[:overflow] {
tagsToEvict = append(tagsToEvict, srv.Tag)
}
return tagsToEvict
}
func isHardDemoted(srv *servers.Server) bool {
return srv.SelectionHistory != nil && srv.SelectionHistory.HardDemoted
}
func compareSelectionAge(a, b *servers.Server) int {
return selectionUpdatedAt(a).Compare(selectionUpdatedAt(b))
}
func selectionUpdatedAt(srv *servers.Server) time.Time {
if srv.SelectionHistory == nil {
return time.Time{}
}
return srv.SelectionHistory.UpdatedAt
}
// clearSelectedIfMissing reverts the persisted selection to auto-select when
// the selected server is no longer present in the manager.
func (r *LocalBackend) clearSelectedIfMissing() {
var selected servers.Server
if err := settings.GetStruct(settings.SelectedServerKey, &selected); err != nil {
return
}
if _, found := r.srvManager.GetServerByTag(selected.Tag); found {
return
}
// Persist before notifying the VPN client so the auto-select choice
// survives even if the tunnel isn't running to accept the switch.
r.persistSelection(vpn.AutoSelectTag)
if err := r.vpnClient.SelectServer(vpn.AutoSelectTag); err != nil && !errors.Is(err, vpn.ErrTunnelNotConnected) {
slog.Warn("Failed to switch to auto-select after selected server was removed", "error", err)
}
}
const selectionHistoryFlushInterval = 5 * time.Second
func (r *LocalBackend) updateSelectionHistoryListener(status vpn.VPNStatus) {
r.selectionHistoryMu.Lock()
defer r.selectionHistoryMu.Unlock()
switch status {
case vpn.Connected:
if r.stopSelectionHistoryListener != nil {
r.stopSelectionHistoryListener()
r.stopSelectionHistoryListener = nil
}
storage := r.vpnClient.HistoryStorage()
if storage == nil {
return
}
ctx, cancel := context.WithCancel(r.ctx)
r.stopSelectionHistoryListener = cancel
hook := make(chan struct{}, 1)
storage.SetHook(func(string) {
// Per-tag granularity isn't useful — flushSelectionHistory
// iterates every server. Non-blocking send so storage
// writes never block on a slow flush.
select {
case hook <- struct{}{}:
default:
}
})
go r.runSelectionHistoryListener(ctx, storage, hook)
if r.selectionReportInterval() > 0 {
r.selectionReporter.reset()
go r.runSelectionReporter(ctx, storage)
}
slog.Debug("Started selection history listener")
case vpn.Disconnected, vpn.ErrorStatus:
if r.stopSelectionHistoryListener != nil {
r.stopSelectionHistoryListener()
r.stopSelectionHistoryListener = nil
slog.Debug("Stopped selection history listener")
}
}