-
-
Notifications
You must be signed in to change notification settings - Fork 11.1k
Expand file tree
/
Copy pathcore.go
More file actions
1188 lines (1045 loc) · 35.5 KB
/
Copy pathcore.go
File metadata and controls
1188 lines (1045 loc) · 35.5 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 lanterncore
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/getlantern/radiance/account"
"github.com/getlantern/radiance/common"
"github.com/getlantern/radiance/common/env"
"github.com/getlantern/radiance/common/settings"
"github.com/getlantern/radiance/ipc"
"github.com/getlantern/radiance/issue"
"github.com/getlantern/radiance/servers"
"github.com/getlantern/radiance/vpn"
"github.com/getlantern/lantern/lantern-core/apps"
privateserver "github.com/getlantern/lantern/lantern-core/private-server"
"github.com/getlantern/lantern/lantern-core/utils"
"github.com/getlantern/lantern/lantern-core/utils/reportissue"
"github.com/getlantern/lantern/lantern-core/vpn_tunnel"
)
type EventType = string
const (
EventTypeServerLocation EventType = "server-location"
EventTypeConfig EventType = "config"
EventTypeCountryCode EventType = "country-code"
DefaultLogLevel = "trace"
)
// LanternCore wraps an IPC client and provides the interface expected by the FFI and mobile layers.
type LanternCore struct {
client *ipc.Client
ctx context.Context
cancel context.CancelFunc
initOnce sync.Once
eventEmitter utils.FlutterEventEmitter
}
var (
core = &LanternCore{}
initError atomic.Pointer[error]
)
type App interface {
AvailableFeatures() []byte
ReportIssue(
email, issueType, description, device, model, logFilePath, attachmentsJSON string,
) error
IsRadianceConnected() bool
IsVPNRunning() (bool, error)
GetAvailableServers() []byte
MyDeviceId() string
GetServerByTagJSON(tag string) ([]byte, bool, error)
GetSelectedServerJSON() ([]byte, error)
GetSelectedServerTag() (string, error)
GetAutoLocationJSON() ([]byte, error)
CheckDaemonReachable() error
PatchSettings(settings.Settings) error
GetSettingsJSON() ([]byte, error)
PatchEnvVars(map[string]string) (map[string]string, error)
GetEnvVars() map[string]string
RunOfflineURLTests() error
UpdateConfig() error
ReferralAttachment(referralCode string) (bool, error)
UpdateLocale(locale string) error
UpdateTelemetryConsent(consent bool) error
IsTelemetryEnabled() bool
IsOAuthLogin() bool
GetOAuthProvider() string
GetEnabledApps() (string, error)
}
type User interface {
UserData() ([]byte, error)
DataCapInfo() (string, error)
FetchUserData() ([]byte, error)
OAuthLoginUrl(provider string) (string, error)
OAuthLoginCallback(oAuthToken string) ([]byte, error)
Login(email, password string) ([]byte, error)
SignUp(email, password string) error
Logout(email string) ([]byte, error)
StartRecoveryByEmail(email string) error
ValidateChangeEmailCode(email, code string) error
CompleteRecoveryByEmail(email, password, code string) error
DeleteAccount(email, password string) ([]byte, error)
RemoveDevice(deviceId string) (*account.LinkResponse, error)
StartChangeEmail(newEmail, password string) error
CompleteChangeEmail(email, password, code string) error
}
type PrivateServer interface {
DigitalOceanPrivateServer(events utils.PrivateServerEventListener) error
GoogleCloudPrivateServer(events utils.PrivateServerEventListener) error
ValidateSession() error
SelectAccount(account string) error
SelectProject(project string) error
CancelDeployment() error
AddServerManagerInstance(ip, port, accessToken, tag string, events utils.PrivateServerEventListener) error
InviteToServerManagerInstance(ip string, port string, accessToken string, inviteName string) (string, error)
RevokeServerManagerInvite(ip string, port string, accessToken string, inviteName string) error
StartDeployment(location, serverName string) error
AddServersByURL(urls string, skipCertVerification bool) ([]byte, error)
DeleteServer(tag string) error
UpdatePrivateServerName(oldTag, newTag string) error
}
type Payment interface {
StripeSubscription(email, planID string) (string, error)
Plans(channel string) (string, error)
StripeBillingPortalUrl() (string, error)
AcknowledgeGooglePurchase(purchaseToken, planId string) (string, error)
AcknowledgeApplePurchase(receipt, planII string) (string, error)
RestoreGooglePlayPurchase(purchaseToken string) (string, error)
RestoreApplePurchase(receipt string) (string, error)
PaymentRedirect(provider, planID, email, idempotencyKey string) (string, error)
ActivationCode(email, resellerCode string) error
SubscriptionPaymentRedirectURL(redirectBody account.PaymentRedirectData) (string, error)
StripeSubscriptionPaymentRedirect(subscriptionType, planID, email, idempotencyKey string) (string, error)
}
type SplitTunnel interface {
LoadInstalledApps(dataDir string) (string, error)
IsSplitTunnelingEnabled() bool
SetSplitTunnelingEnabled(bool) error
AddSplitTunnelItem(filterType, item string) error
AddSplitTunnelItems(items string) error
RemoveSplitTunnelItem(filterType, item string) error
RemoveSplitTunnelItems(items string) error
GetSplitTunnelItems() (string, error)
GetSplitTunnelItemsFor(filterType string) (string, error)
}
type Ads interface {
SetBlockAdsEnabled(bool) error
IsBlockAdsEnabled() bool
}
type SmartRouting interface {
SetSmartRoutingEnabled(bool) error
IsSmartRoutingEnabled() bool
}
type PeerShare interface {
SetPeerShareEnabled(bool) error
IsPeerShareEnabled() bool
}
type VPN interface {
ConnectVPN(tag string) error
SelectServer(tag string) error
DisconnectVPN() error
VPNStatus() (vpn.VPNStatus, error)
VPNStatusEvents(ctx context.Context, callback func(evt vpn.StatusUpdateEvent)) error
}
type Core interface {
App
User
Payment
PrivateServer
SplitTunnel
Ads
SmartRouting
PeerShare
VPN
Client() *ipc.Client
}
var _ Core = (*LanternCore)(nil)
func New(opts *utils.Opts, eventEmitter utils.FlutterEventEmitter) (Core, error) {
if opts == nil || eventEmitter == nil {
return nil, fmt.Errorf("opts and eventEmitter cannot be nil")
}
core.initOnce.Do(func() {
if opts.LogLevel == "" {
opts.LogLevel = DefaultLogLevel
}
slog.Debug("Initializing LanternCore with opts: ", "opts", opts)
if err := core.initialize(opts, eventEmitter); err != nil {
initError.Store(&err)
}
})
if initError.Load() != nil {
return nil, *initError.Load()
}
return core, nil
}
func (lc *LanternCore) initialize(opts *utils.Opts, eventEmitter utils.FlutterEventEmitter) error {
// Wire up slog for the host process according to how the backend is
// hosted on each platform:
//
// - windows/linux: the UI is a separate process talking to a daemon
// over IPC, so it needs its own full common.Init.
// - darwin/ios: the UI shares its logDir with the tunnel extension,
// which is the process that called common.Init. Re-running it here
// would collide; instead we set up app-process-only logging into a
// distinct file so the two lumberjacks don't race on rotation.
// - android: the backend is embedded in the same process as the UI
// (see init_mobile.go), and Mobile.SetupRadiance has already called
// common.Init by the time we reach here. Fall through with no
// additional setup.
switch runtime.GOOS {
case "windows", "linux":
if err := common.Init(opts.DataDir, opts.LogDir, opts.LogLevel); err != nil {
return fmt.Errorf("common.Init: %w", err)
}
case "darwin", "ios":
setupAppLogging(opts.LogDir, opts.LogLevel)
}
slog.Debug("Starting LanternCore initialization")
if opts.Env == "stage" || opts.Env == "staging" {
slog.Debug("Setting staging environment")
env.SetStagingEnv()
}
ctx, cancel := context.WithCancel(context.Background())
client, err := createClient(ctx, opts)
if err != nil {
cancel()
return fmt.Errorf("failed to create IPC client: %w", err)
}
lc.client = client
lc.ctx = ctx
lc.cancel = cancel
lc.eventEmitter = eventEmitter
go lc.listenAutoSelectedEvents()
go lc.listenConfigEvents()
go lc.listenDataCapEvents()
go lc.fetchUserDataIfNeeded()
slog.Debug("LanternCore initialized successfully")
return nil
}
func (lc *LanternCore) Client() *ipc.Client {
return lc.client
}
// notifyFlutter sends an event to the Flutter frontend via the event emitter.
func (lc *LanternCore) notifyFlutter(event EventType, message string) {
slog.Debug("Notifying Flutter")
lc.eventEmitter.SendEvent(&utils.FlutterEvent{
Type: string(event),
Message: message,
})
}
// fetchUserDataIfNeeded pulls fresh user data from the server at startup
func (lc *LanternCore) fetchUserDataIfNeeded() {
raw := lc.settings()[settings.UserIDKey]
userID := userIDAsInt64(raw)
if userID == 0 {
slog.Debug("Skipping startup user-data fetch: no user ID set", "raw", raw)
return
}
if _, err := lc.client.FetchUserData(lc.ctx); err != nil {
slog.Error("Startup user-data fetch failed", "error", err)
return
}
slog.Debug("Startup user-data fetch succeeded", "userID", userID)
}
// userIDAsInt64 normalizes the radiance UserIDKey value across the storage
// types it can have: int64 (in-process), float64 (after JSON IPC round-trip),
// int (defensive), or a decimal string (mobile.go purchase flow). Returns 0
// for any unrecognized type so the caller treats the user as anonymous.
func userIDAsInt64(v any) int64 {
switch x := v.(type) {
case int64:
return x
case float64:
return int64(x)
case int:
return int64(x)
case string:
n, _ := strconv.ParseInt(x, 10, 64)
return n
}
return 0
}
// listenAutoSelectedEvents listens for auto-selected server changes from the IPC client and forwards
// them to Flutter. Blocks until lc.ctx is cancelled.
func (lc *LanternCore) listenAutoSelectedEvents() {
err := lc.client.AutoSelectedEvents(lc.ctx, func(evt vpn.AutoSelectedEvent) {
tag := strings.TrimSpace(evt.Selected)
if tag == "" {
slog.Debug("auto-selected server not available yet")
return
}
server, found, err := lc.client.GetServerByTag(lc.ctx, tag)
if err != nil || !found {
slog.Error("no server found with tag", "tag", tag, "error", err)
return
}
jsonBytes, err := json.Marshal(server)
if err != nil {
slog.Error("Error marshalling server location", "error", err)
return
}
slog.Debug("Auto location server:", "server", string(jsonBytes))
lc.notifyFlutter(EventTypeServerLocation, string(jsonBytes))
})
if err != nil && lc.ctx.Err() == nil {
slog.Error("auto-selected event stream exited unexpectedly", "error", err)
}
}
// listenConfigEvents listens for config updates from the IPC client and notifies Flutter when they
// occur. Blocks until lc.ctx is cancelled.
func (lc *LanternCore) listenConfigEvents() {
err := lc.client.ConfigEvents(lc.ctx, func() {
slog.Debug("Config updated, notifying Flutter")
lc.notifyFlutter(EventTypeConfig, "")
// Forward the country from the latest config fetch.
countryCode, _ := lc.settings()[settings.CountryCodeKey].(string)
if countryCode != "" {
slog.Debug("Config event: country code updated", "countryCode", countryCode)
lc.notifyFlutter(EventTypeCountryCode, countryCode)
}
})
if err != nil && lc.ctx.Err() == nil {
slog.Error("config event stream exited unexpectedly", "error", err)
}
}
// listenDataCapEvents listens for DataCapInfo updates from the IPC client and forwards them to Flutter.
// Blocks until lc.ctx is cancelled.
func (lc *LanternCore) listenDataCapEvents() {
err := lc.client.DataCapStream(lc.ctx, func(info account.DataCapInfo) {
jsonBytes, err := json.Marshal(info)
if err != nil {
slog.Error("Error marshalling DataCap event", "error", err)
return
}
lc.notifyFlutter("data-cap-event", string(jsonBytes))
})
if err != nil && lc.ctx.Err() == nil {
slog.Error("datacap event stream exited unexpectedly", "error", err)
}
}
/////////////////
// VPN //
/////////////////
// Per-call IPC timeouts. These bound the worst case if lanternd is hung
// (pipe open, no replies). They're long enough to never fire during normal
// operation — the connect path involves real DNS / TLS / sing-box bring-up
// that can take many seconds, while a /vpn/status query should be near-
// instant — but tight enough that a stuck daemon surfaces as a UI error
// instead of an indefinite spinner. The dialer already has a 10 s connect
// timeout (radiance/ipc/conn_windows.go), so these only matter once the
// pipe is established.
const (
ipcConnectTimeout = 60 * time.Second
ipcStateChangeTimeout = 30 * time.Second
ipcStatusTimeout = 10 * time.Second
)
// ConnectVPN routes a connect request through vpn_tunnel.ConnectToServer,
// which picks between /vpn/connect (fresh tunnel) and /server/selected
// (live-tunnel outbound swap) based on VPNStatus. This is load-bearing for
// the Smart-from-connected flow: Jigar's onSmartLocation rewrite
// (server_selection.dart) routes "switch back to auto" through
// startVPN(force: true) → ffi.go:startVPN → c.ConnectVPN(""). Without the
// dispatch the call 500s with ErrTunnelAlreadyConnected from
// radiance/vpn/vpn.go:130 and the user sees a snackbar.
//
// Fixes getlantern/engineering#3291 issue 3.
func (lc *LanternCore) ConnectVPN(tag string) error {
ctx, cancel := context.WithTimeout(lc.ctx, ipcConnectTimeout)
defer cancel()
return vpn_tunnel.ConnectToServer(ctx, lc.client, tag)
}
func (lc *LanternCore) SelectServer(tag string) error {
ctx, cancel := context.WithTimeout(lc.ctx, ipcStateChangeTimeout)
defer cancel()
return lc.client.SelectServer(ctx, tag)
}
func (lc *LanternCore) DisconnectVPN() error {
ctx, cancel := context.WithTimeout(lc.ctx, ipcStateChangeTimeout)
defer cancel()
return lc.client.DisconnectVPN(ctx)
}
func (lc *LanternCore) VPNStatus() (vpn.VPNStatus, error) {
ctx, cancel := context.WithTimeout(lc.ctx, ipcStatusTimeout)
defer cancel()
return lc.client.VPNStatus(ctx)
}
func (lc *LanternCore) IsVPNRunning() (bool, error) {
status, err := lc.VPNStatus()
if err != nil {
return false, err
}
return status == vpn.Connected, nil
}
func (lc *LanternCore) VPNStatusEvents(ctx context.Context, callback func(evt vpn.StatusUpdateEvent)) error {
return lc.client.VPNStatusEvents(ctx, callback)
}
/////////////////
// Settings //
/////////////////
// settings returns the current settings from radiance.
func (lc *LanternCore) settings() settings.Settings {
s, err := lc.client.Settings(lc.ctx)
if err != nil {
slog.Error("Error fetching settings", "error", err)
return settings.Settings{}
}
return s
}
func (lc *LanternCore) UpdateTelemetryConsent(consent bool) error {
return lc.client.EnableTelemetry(lc.ctx, consent)
}
func (lc *LanternCore) SetBlockAdsEnabled(enabled bool) error {
return lc.client.EnableAdBlocking(lc.ctx, enabled)
}
func (lc *LanternCore) IsBlockAdsEnabled() bool {
b, _ := lc.settings()[settings.AdBlockKey].(bool)
return b
}
func (lc *LanternCore) SetSmartRoutingEnabled(enabled bool) error {
return lc.client.EnableSmartRouting(lc.ctx, enabled)
}
func (lc *LanternCore) IsSmartRoutingEnabled() bool {
b, _ := lc.settings()[settings.SmartRoutingKey].(bool)
return b
}
func (lc *LanternCore) SetPeerShareEnabled(enabled bool) error {
_, err := lc.client.PatchSettings(lc.ctx, settings.Settings{settings.PeerShareEnabledKey: enabled})
return err
}
func (lc *LanternCore) IsPeerShareEnabled() bool {
b, _ := lc.settings()[settings.PeerShareEnabledKey].(bool)
return b
}
func (lc *LanternCore) IsTelemetryEnabled() bool {
b, _ := lc.settings()[settings.TelemetryKey].(bool)
return b
}
func (lc *LanternCore) IsOAuthLogin() bool {
b, _ := lc.settings()[settings.OAuthLoginKey].(bool)
return b
}
func (lc *LanternCore) GetOAuthProvider() string {
v, _ := lc.settings()[settings.OAuthProviderKey].(string)
return v
}
func (lc *LanternCore) IsRadianceConnected() bool {
return lc.client != nil
}
func (lc *LanternCore) MyDeviceId() string {
v, _ := lc.settings()[settings.DeviceIDKey].(string)
return v
}
func (lc *LanternCore) UpdateLocale(locale string) error {
_, err := lc.client.PatchSettings(lc.ctx, settings.Settings{settings.LocaleKey: locale})
return err
}
func (lc *LanternCore) AvailableFeatures() []byte {
features, err := lc.client.Features(lc.ctx)
if err != nil {
slog.Error("Error getting features", "error", err)
return nil
}
jsonBytes, err := json.Marshal(features)
if err != nil {
slog.Error("Error marshalling features", "error", err)
return nil
}
return jsonBytes
}
func (lc *LanternCore) GetAvailableServers() []byte {
data, err := lc.client.ServersJSON(lc.ctx)
if err != nil {
slog.Error("Error getting servers", "error", err)
return nil
}
return data
}
func (lc *LanternCore) GetServerByTagJSON(tag string) ([]byte, bool, error) {
return lc.client.GetServerByTagJSON(lc.ctx, tag)
}
func (lc *LanternCore) GetSelectedServerJSON() ([]byte, error) {
return lc.client.SelectedServerJSON(lc.ctx)
}
func (lc *LanternCore) GetSelectedServerTag() (string, error) {
server, exists, err := lc.client.SelectedServer(lc.ctx)
if err != nil {
return "", err
}
if !exists {
return "", nil
}
return server.Tag, nil
}
func (lc *LanternCore) GetAutoLocationJSON() ([]byte, error) {
server, err := lc.client.AutoSelected(lc.ctx)
if err != nil {
return nil, fmt.Errorf("failed to get auto location: %w", err)
}
return json.Marshal(server)
}
func (lc *LanternCore) CheckDaemonReachable() error {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
_, err := lc.client.VPNStatus(ctx)
return err
}
func (lc *LanternCore) PatchSettings(s settings.Settings) error {
_, err := lc.client.PatchSettings(lc.ctx, s)
return err
}
func (lc *LanternCore) GetSettingsJSON() ([]byte, error) {
s, err := lc.client.Settings(lc.ctx)
if err != nil {
return nil, err
}
return json.Marshal(s)
}
func (lc *LanternCore) PatchEnvVars(updates map[string]string) (map[string]string, error) {
return lc.client.PatchEnvVars(lc.ctx, updates)
}
// GetEnvVars returns the daemon's in-memory env vars. Uses an empty PATCH
// because ipc.Client exposes no dedicated GET; the daemon returns the full
// env map on both GET and PATCH.
func (lc *LanternCore) GetEnvVars() map[string]string {
vars, err := lc.client.PatchEnvVars(lc.ctx, map[string]string{})
if err != nil {
slog.Error("Error fetching env vars", "error", err)
return nil
}
return vars
}
func (lc *LanternCore) RunOfflineURLTests() error {
return lc.client.RunOfflineURLTests(lc.ctx)
}
func (lc *LanternCore) UpdateConfig() error {
return lc.client.UpdateConfig(lc.ctx)
}
/////////////////
// Split Tunnel //
/////////////////
// TODO: ??? not sure what to do about this one. it can't access dataDir
func (lc *LanternCore) LoadInstalledApps(dataDir string) (string, error) {
appsList := []*apps.AppData{}
apps.LoadInstalledApps(dataDir, func(a ...*apps.AppData) error {
appsList = append(appsList, a...)
return nil
})
b, err := json.Marshal(appsList)
if err != nil {
return "", err
}
return string(b), nil
}
func (lc *LanternCore) SetSplitTunnelingEnabled(enabled bool) error {
return lc.client.EnableSplitTunneling(lc.ctx, enabled)
}
func (lc *LanternCore) IsSplitTunnelingEnabled() bool {
b, _ := lc.settings()[settings.SplitTunnelKey].(bool)
return b
}
func (lc *LanternCore) AddSplitTunnelItem(filterType, item string) error {
filter := filterFromTypeAndItems(filterType, []string{item})
return lc.client.AddSplitTunnelItems(lc.ctx, filter)
}
func (lc *LanternCore) AddSplitTunnelItems(items string) error {
split := splitCSVClean(items)
filter := platformFilter(split)
return lc.client.AddSplitTunnelItems(lc.ctx, filter)
}
func (lc *LanternCore) RemoveSplitTunnelItem(filterType, item string) error {
filter := filterFromTypeAndItems(filterType, []string{item})
return lc.client.RemoveSplitTunnelItems(lc.ctx, filter)
}
func (lc *LanternCore) RemoveSplitTunnelItems(items string) error {
split := splitCSVClean(items)
filter := platformFilter(split)
return lc.client.RemoveSplitTunnelItems(lc.ctx, filter)
}
func (lc *LanternCore) GetSplitTunnelItems() (string, error) {
filter, err := lc.client.SplitTunnelFilters(lc.ctx)
if err != nil {
return "{}", nil
}
b, err := json.Marshal(filter)
if err != nil {
return "{}", nil
}
return string(b), nil
}
func (lc *LanternCore) GetSplitTunnelItemsFor(filterType string) (string, error) {
filter, err := lc.client.SplitTunnelFilters(lc.ctx)
if err != nil {
return "", err
}
items := itemsForType(filter, filterType)
b, err := json.Marshal(items)
if err != nil {
return "", err
}
return string(b), nil
}
func (lc *LanternCore) GetEnabledApps() (string, error) {
filter, err := lc.client.SplitTunnelFilters(lc.ctx)
if err != nil {
return "", err
}
// Initialize as empty slice so json.Marshal emits "[]" rather than
// "null" when no items are enabled — Dart's jsonDecode("null") returns
// null and the receiver does `as List`, which throws. Was the actual
// cause of "Failed to fetch installed apps" empty list in
// Freshdesk #173774 / #173778 / #173826.
enabledApps := []string{}
enabledApps = append(enabledApps, filter.ProcessPath...)
enabledApps = append(enabledApps, filter.ProcessPathRegex...)
enabledApps = append(enabledApps, filter.PackageName...)
b, err := json.Marshal(enabledApps)
if err != nil {
return "", err
}
return string(b), nil
}
/////////////////
// Issue Report //
/////////////////
func (lc *LanternCore) ReportIssue(email, issueType, description, device, model, logFilePath, attachmentsJSON string) error {
it := parseIssueType(issueType)
var attachments []string
// Windows + Linux have separate UI and daemon logDirs, so the daemon's
// own archive glob misses UI-process logs — pass them through as paths.
// Mobile + macOS already share the directory; no pass-through needed.
// Relies on the UI logDir being readable by the daemon (SYSTEM on
// Windows); %PUBLIC%\Lantern\logs is chosen for that.
if runtime.GOOS == "windows" || runtime.GOOS == "linux" {
attachments = collectLocalLogs(settings.GetString(settings.LogPathKey))
}
if logFilePath != "" {
attachments = append(attachments, logFilePath)
}
firstClassAttachments, err := reportissue.LoadAttachments(attachmentsJSON)
if err != nil {
return fmt.Errorf("load issue attachments: %w", err)
}
return lc.client.ReportIssue(lc.ctx, it, description, email, attachments, firstClassAttachments)
}
// collectLocalLogs returns every *.log directly under dir, with paths shaped
// however filepath.Glob returns them (relative if dir is relative; the
// daemon-side ReportIssue path on windows/linux passes the absolute
// settings.LogPathKey so this is absolute in practice).
//
// Files we can't os.Stat from the UI process are dropped. That's a
// best-effort screen, not a guarantee — the daemon runs as SYSTEM on
// Windows and may be able to read files this process can't, and vice
// versa. The drop avoids attaching obviously-broken paths to issue
// reports; the daemon's own readability check is authoritative.
func collectLocalLogs(dir string) []string {
if dir == "" {
return nil
}
matches, err := filepath.Glob(filepath.Join(dir, "*.log"))
if err != nil {
slog.Warn("ReportIssue: unable to glob local logs", "dir", dir, "err", err)
return nil
}
out := matches[:0]
for _, p := range matches {
if _, err := os.Stat(p); err != nil {
slog.Warn("ReportIssue: skipping log (unreadable from this process)", "path", p, "err", err)
continue
}
out = append(out, p)
}
return out
}
func parseIssueType(s string) issue.IssueType {
switch strings.ToLower(s) {
case "cannot_complete_purchase":
return issue.CannotCompletePurchase
case "cannot_sign_in":
return issue.CannotSignIn
case "spinner_loads_endlessly":
return issue.SpinnerLoadsEndlessly
case "cannot_access_blocked_sites":
return issue.CannotAccessBlockedSites
case "slow":
return issue.Slow
case "cannot_link_device":
return issue.CannotLinkDevice
case "application_crashes":
return issue.ApplicationCrashes
case "update_fails":
return issue.UpdateFails
default:
return issue.Other
}
}
/////////////////
// Account //
/////////////////
func (lc *LanternCore) DataCapInfo() (string, error) {
info, err := lc.client.DataCapInfo(lc.ctx)
if err != nil {
return "", err
}
jsonBytes, err := json.Marshal(info)
if err != nil {
return "", fmt.Errorf("error marshalling DataCapInfo: %w", err)
}
return string(jsonBytes), nil
}
func (lc *LanternCore) UserData() ([]byte, error) {
userData, err := lc.client.UserData(lc.ctx)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) FetchUserData() ([]byte, error) {
userData, err := lc.client.FetchUserData(lc.ctx)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) OAuthLoginUrl(provider string) (string, error) {
return lc.client.OAuthLoginURL(lc.ctx, provider)
}
func (lc *LanternCore) OAuthLoginCallback(oAuthToken string) ([]byte, error) {
userData, err := lc.client.OAuthLoginCallback(lc.ctx, oAuthToken)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) Login(email, password string) ([]byte, error) {
userData, err := lc.client.Login(lc.ctx, email, password)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) SignUp(email, password string) error {
_, _, err := lc.client.SignUp(lc.ctx, email, password)
return err
}
func (lc *LanternCore) Logout(email string) ([]byte, error) {
userData, err := lc.client.Logout(lc.ctx, email)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) StartRecoveryByEmail(email string) error {
return lc.client.StartRecoveryByEmail(lc.ctx, email)
}
func (lc *LanternCore) ValidateChangeEmailCode(email, code string) error {
return lc.client.ValidateEmailRecoveryCode(lc.ctx, email, code)
}
func (lc *LanternCore) CompleteRecoveryByEmail(email, password, code string) error {
return lc.client.CompleteRecoveryByEmail(lc.ctx, email, password, code)
}
func (lc *LanternCore) DeleteAccount(email, password string) ([]byte, error) {
userData, err := lc.client.DeleteAccount(lc.ctx, email, password)
if err != nil {
return nil, err
}
return json.Marshal(userData)
}
func (lc *LanternCore) RemoveDevice(deviceID string) (*account.LinkResponse, error) {
return lc.client.RemoveDevice(lc.ctx, deviceID)
}
func (lc *LanternCore) StartChangeEmail(newEmail, password string) error {
return lc.client.StartChangeEmail(lc.ctx, newEmail, password)
}
func (lc *LanternCore) CompleteChangeEmail(email, password, code string) error {
return lc.client.CompleteChangeEmail(lc.ctx, email, password, code)
}
func (lc *LanternCore) ReferralAttachment(referralCode string) (bool, error) {
return lc.client.ReferralAttach(lc.ctx, referralCode)
}
/////////////////
// Payments //
/////////////////
func (lc *LanternCore) StripeSubscription(email, planID string) (string, error) {
return lc.client.NewStripeSubscription(lc.ctx, email, planID)
}
func (lc *LanternCore) Plans(channel string) (string, error) {
return lc.client.SubscriptionPlans(lc.ctx, channel)
}
func (lc *LanternCore) StripeBillingPortalUrl() (string, error) {
return lc.client.StripeBillingPortalURL(lc.ctx)
}
func (lc *LanternCore) AcknowledgeGooglePurchase(purchaseToken, planId string) (string, error) {
params := map[string]string{
"purchaseToken": purchaseToken,
"planId": planId,
}
return lc.client.VerifySubscription(lc.ctx, account.GoogleService, params)
}
func (lc *LanternCore) AcknowledgeApplePurchase(receipt, planII string) (string, error) {
params := map[string]string{
"receipt": receipt,
"planId": planII,
}
return lc.client.VerifySubscription(lc.ctx, account.AppleService, params)
}
func (lc *LanternCore) RestoreGooglePlayPurchase(purchaseToken string) (string, error) {
params := map[string]string{
"purchaseToken": purchaseToken,
"idempotencyKey": strconv.FormatInt(time.Now().UnixNano(), 10),
}
resp, err := lc.client.RestoreSubscription(lc.ctx, account.GoogleService, params)
if err != nil {
return "", err
}
data, err := json.Marshal(resp)
if err != nil {
return "", fmt.Errorf("error marshalling restore google play purchase response: %w", err)
}
return string(data), nil
}
func (lc *LanternCore) RestoreApplePurchase(receipt string) (string, error) {
params := map[string]string{
"receipt": receipt,
"idempotencyKey": strconv.FormatInt(time.Now().UnixNano(), 10),
}
resp, err := lc.client.RestoreSubscription(lc.ctx, account.AppleService, params)
if err != nil {
return "", err
}
data, err := json.Marshal(resp)
if err != nil {
return "", fmt.Errorf("error marshalling restore apple purchase response: %w", err)
}
return string(data), nil
}
func (lc *LanternCore) SubscriptionPaymentRedirectURL(redirectBody account.PaymentRedirectData) (string, error) {
return lc.client.SubscriptionPaymentRedirectURL(lc.ctx, redirectBody)
}
func (lc *LanternCore) StripeSubscriptionPaymentRedirect(subscriptionType, planID, email, idempotencyKey string) (string, error) {
idempotencyKey, err := normalizePaymentRedirectIdempotencyKey(idempotencyKey)
if err != nil {
return "", err
}
deviceID := lc.MyDeviceId()
redirectBody := account.PaymentRedirectData{
Provider: "stripe",
Plan: planID,
DeviceName: deviceID,
Email: email,
BillingType: account.SubscriptionType(subscriptionType),
IdempotencyKey: idempotencyKey,
}
return lc.SubscriptionPaymentRedirectURL(redirectBody)
}
func (lc *LanternCore) PaymentRedirect(provider, planId, email, idempotencyKey string) (string, error) {
idempotencyKey, err := normalizePaymentRedirectIdempotencyKey(idempotencyKey)
if err != nil {
return "", err
}
deviceName := lc.MyDeviceId()
body := account.PaymentRedirectData{
Provider: provider,
Plan: planId,
DeviceName: deviceName,
Email: email,
IdempotencyKey: idempotencyKey,
}
return lc.client.PaymentRedirect(lc.ctx, body)
}
func normalizePaymentRedirectIdempotencyKey(idempotencyKey string) (string, error) {
idempotencyKey = strings.TrimSpace(idempotencyKey)
if idempotencyKey == "" {
return "", fmt.Errorf("payment redirect idempotency key is required")
}
return idempotencyKey, nil
}
func (lc *LanternCore) ActivationCode(email, resellerCode string) error {
purchase, err := lc.client.ActivationCode(lc.ctx, email, resellerCode)
if err != nil {
return fmt.Errorf("error getting activation code: %w", err)
}
if purchase.Status != "ok" {
return fmt.Errorf("activation code failed: %s", purchase.Status)
}
return nil
}
/////////////////////
// Private Servers //
/////////////////////
func (lc *LanternCore) DigitalOceanPrivateServer(events utils.PrivateServerEventListener) error {
return privateserver.StartDigitalOceanPrivateServerFlow(events, lc.client)
}
func (lc *LanternCore) GoogleCloudPrivateServer(events utils.PrivateServerEventListener) error {