-
-
Notifications
You must be signed in to change notification settings - Fork 11.1k
Expand file tree
/
Copy pathffi.go
More file actions
1453 lines (1336 loc) · 34.6 KB
/
Copy pathffi.go
File metadata and controls
1453 lines (1336 loc) · 34.6 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
//go:build !android && !ios && !macos
package main
/*
#include <stdlib.h>
#include "stdint.h"
*/
import "C"
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"sync"
"sync/atomic"
"time"
"unsafe"
lanterncore "github.com/getlantern/lantern/lantern-core"
"github.com/getlantern/lantern/lantern-core/apps"
"github.com/getlantern/lantern/lantern-core/dart_api_dl"
"github.com/getlantern/lantern/lantern-core/logs"
"github.com/getlantern/lantern/lantern-core/utils"
"github.com/getlantern/radiance/common/settings"
"github.com/getlantern/radiance/vpn"
)
// runOnGoStack wraps utils.RunOffCgoStack for FFI functions that return *C.char.
// CGo-exported functions run on a callback stack whose memory isn't tracked
// by the GC heap bitmap. Allocating Go pointers (like C.CString) on that stack
// triggers bulkBarrierPreWrite panics.
func runOnGoStack(fn func() *C.char) *C.char {
result, _ := utils.RunOffCgoStack(func() (*C.char, error) {
return fn(), nil
})
return result
}
const (
enableLogging = false
)
var (
lanternCore atomic.Pointer[lanterncore.Core]
appDataDir string
appsPort atomic.Int64
logsPort atomic.Int64
statusPort atomic.Int64
privateserverPort atomic.Int64
appEventPort atomic.Int64
)
func requireCore() (lanterncore.Core, *C.char) {
c := lanternCore.Load()
if c == nil {
return nil, C.CString(`{"error":"not_initialized"}`)
}
return *c, nil
}
//export getAppDataDir
func getAppDataDir() *C.char {
return runOnGoStack(func() *C.char {
return C.CString(appDataDir)
})
}
func sendApps(port int64) func(apps ...*apps.AppData) error {
return func(apps ...*apps.AppData) error {
data, err := json.Marshal(apps)
if err != nil {
slog.Error("Error marshalling apps:", "error", err)
return err
}
go dart_api_dl.SendToPort(port, string(data))
return nil
}
}
// / Flutter event emitter implementation for FFI
type ffiFlutterEventEmitter struct{}
func (e *ffiFlutterEventEmitter) SendEvent(event *utils.FlutterEvent) {
slog.Debug("Sending event to Flutter:", "event", event)
port := appEventPort.Load()
if port == 0 {
slog.Error("Apps port is not set, cannot send event")
return
}
eventData, err := json.Marshal(event)
if err != nil {
slog.Error("Error marshalling event:", "error", err)
return
}
slog.Debug("Marshalled event data:", "data", string(eventData))
go dart_api_dl.SendToPort(port, string(eventData))
}
//export setup
func setup(_logDir, _dataDir, _locale, _env *C.char, logP, appsP, statusP, privateServerP, appEventP C.int64_t, consent C.int, api unsafe.Pointer) *C.char {
logDir := C.GoString(_logDir)
dataDir := C.GoString(_dataDir)
appDataDir = dataDir
locale := C.GoString(_locale)
env := C.GoString(_env)
return runOnGoStack(func() *C.char {
core, err := lanterncore.New(&utils.Opts{
LogDir: logDir,
DataDir: dataDir,
Locale: locale,
Env: env,
Deviceid: "",
LogLevel: lanterncore.DefaultLogLevel,
TelemetryConsent: consent == 1,
}, &ffiFlutterEventEmitter{})
if err != nil {
return C.CString(fmt.Sprintf("unable to create LanternCore: %v", err))
}
dart_api_dl.Init(api)
lanternCore.Store(&core)
logsPort.Store(int64(logP))
appsPort.Store(int64(appsP))
statusPort.Store(int64(statusP))
privateserverPort.Store(int64(privateServerP))
appEventPort.Store(int64(appEventP))
// Start the VPN status listener immediately so the UI reflects the
// current VPN state even if the VPN was already connected (e.g. macOS
// system extension started before the Flutter app).
startStatusListener(core)
startLogsListener(core)
slog.Debug("Radiance setup successfully")
return C.CString("ok")
})
}
// updateTelemetryConsent updates the telemetry consent.
//
//export updateTelemetryConsent
func updateTelemetryConsent(consent C.int) *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.UpdateTelemetryConsent(consent != 0); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export isTelemetryEnabled
func isTelemetryEnabled() C.int {
c, _ := requireCore()
if c != nil && c.IsTelemetryEnabled() {
return 1
}
return 0
}
//export isOAuthLogin
func isOAuthLogin() C.int {
c, _ := requireCore()
if c != nil && c.IsOAuthLogin() {
return 1
}
return 0
}
//export getOAuthProvider
func getOAuthProvider() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
return C.CString(c.GetOAuthProvider())
})
}
// availableFeatures returns a list of available features in JSON format.
//
//export availableFeatures
func availableFeatures() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
return C.CString(string(c.AvailableFeatures()))
})
}
//export updateLocale
func updateLocale(_locale *C.char) *C.char {
locale := C.GoString(_locale)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
c.UpdateLocale(locale)
return C.CString("ok")
})
}
//export addSplitTunnelItem
func addSplitTunnelItem(filterTypeC, itemC *C.char) *C.char {
filterType := C.GoString(filterTypeC)
item := C.GoString(itemC)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.AddSplitTunnelItem(filterType, item); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export removeSplitTunnelItem
func removeSplitTunnelItem(filterTypeC, itemC *C.char) *C.char {
filterType := C.GoString(filterTypeC)
item := C.GoString(itemC)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.RemoveSplitTunnelItem(filterType, item); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export setSplitTunnelingEnabled
func setSplitTunnelingEnabled(enabled C.int) *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.SetSplitTunnelingEnabled(enabled != 0); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export isSplitTunnelingEnabled
func isSplitTunnelingEnabled() C.int {
c, _ := requireCore()
if c != nil && c.IsSplitTunnelingEnabled() {
return 1
}
return 0
}
//export loadInstalledApps
func loadInstalledApps(dataDir *C.char) *C.char {
dir := C.GoString(dataDir)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
appsJson, err := c.LoadInstalledApps(dir)
if err != nil {
return C.CString(fmt.Sprintf("error loading installed apps: %v", err))
}
return C.CString(appsJson)
})
}
//export loadInstalledAppIcon
func loadInstalledAppIcon(appPathC, iconPathC *C.char) *C.char {
return runOnGoStack(func() *C.char {
appPath := C.GoString(appPathC)
iconPath := C.GoString(iconPathC)
if appPath == "" && iconPath == "" {
return C.CString("")
}
iconBytes, err := apps.LoadAppIconBytes(appPath, iconPath)
if err != nil || len(iconBytes) == 0 {
return C.CString("")
}
return C.CString(base64.StdEncoding.EncodeToString(iconBytes))
})
}
//export getDataCapInfo
func getDataCapInfo() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
info, err := c.DataCapInfo()
if err != nil {
return SendError(err)
}
return C.CString(info)
})
}
//export reportIssue
func reportIssue(
emailC, typeC, descC, deviceC, modelC, logPathC, attachmentsJSONC *C.char,
) *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
email := C.GoString(emailC)
issueType := C.GoString(typeC)
desc := C.GoString(descC)
device := C.GoString(deviceC)
model := C.GoString(modelC)
logPath := C.GoString(logPathC)
attachmentsJSON := C.GoString(attachmentsJSONC)
if err := c.ReportIssue(
email,
issueType,
desc,
device,
model,
logPath,
attachmentsJSON,
); err != nil {
return C.CString(fmt.Sprintf("error reporting issue: %v", err))
}
return C.CString("ok")
})
}
// getSelectedServerJSON returns the selected server response as raw JSON.
//
//export getSelectedServerJSON
func getSelectedServerJSON() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
data, err := c.GetSelectedServerJSON()
if err != nil {
return SendError(err)
}
return C.CString(string(data))
})
}
// getAutoLocation returns the auto location in JSON format.
//
//export getAutoLocation
func getAutoLocation() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
data, err := c.GetAutoLocationJSON()
if err != nil {
return SendError(err)
}
return C.CString(string(data))
})
}
// isTagAvailable checks if a server with the given tag exists in the server list.
// Returns "true" if found, "false" if not found, or "true" when the check cannot be
// performed (fail-open: allows connection attempts to proceed normally).
//
//export isTagAvailable
func isTagAvailable(_tag *C.char) *C.char {
tag := C.GoString(_tag)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
slog.Warn("Unable to check tag availability (core not ready), assuming available", "tag", tag)
C.free(unsafe.Pointer(errStr))
return C.CString("true")
}
_, found, err := c.GetServerByTagJSON(tag)
if err != nil {
slog.Warn("Error checking tag availability, assuming available", "tag", tag, "error", err)
return C.CString("true")
}
if found {
return C.CString("true")
}
return C.CString("false")
})
}
// GetAvailableServers returns the available servers in JSON format.
//
//export getAvailableServers
func getAvailableServers() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
return C.CString(string(c.GetAvailableServers()))
})
}
func sendStatusToPort(status vpn.VPNStatus, errMsg string) {
slog.Debug("sendStatusToPort called", "status", status)
port := statusPort.Load()
if port == 0 {
slog.Error("Status port is not set, cannot send status")
return
}
msg := map[string]any{"status": status}
if errMsg != "" {
msg["error"] = errMsg
}
slog.Debug("Sending status to port", "port", port)
data, _ := json.Marshal(msg)
slog.Debug("Marshalled status data", "data", string(data))
dart_api_dl.SendToPort(port, string(data))
slog.Debug("Status sent to port successfully", "status", status)
}
var (
statusListenerOnce sync.Once
statusListenerLastMu sync.Mutex
statusListenerLast string
)
// startStatusListener subscribes to radiance's VPN status SSE stream and
// forwards status changes to Flutter via the Dart status port.
func startStatusListener(c lanterncore.Core) {
statusListenerOnce.Do(func() {
go func() {
for {
if statusPort.Load() == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
c.VPNStatusEvents(context.Background(), func(evt vpn.StatusUpdateEvent) {
status, errMsg := mapStatusEvent(evt)
statusListenerLastMu.Lock()
changed := string(status) != statusListenerLast
if changed {
statusListenerLast = string(status)
}
statusListenerLastMu.Unlock()
if changed {
// [vpn-state-trace] hop=ffi_to_port — moment lantern-core forwards
// the parsed status to the Dart ReceivePort. The gap to dart_applied
// measures Dart isolate scheduling + Riverpod notify on Windows.
slog.Info("[vpn-state-trace]", "hop", "ffi_to_port", "status", status, "ts_ms", time.Now().UnixMilli())
sendStatusToPort(status, errMsg)
}
})
// SSE stream disconnected — retry after a short delay.
time.Sleep(500 * time.Millisecond)
}
}()
})
}
var logsListenerOnce sync.Once
// startLogsListener subscribes to radiance's log SSE stream and forwards each
// entry to Flutter via the Dart logs port.
func startLogsListener(c lanterncore.Core) {
logsListenerOnce.Do(func() {
go func() {
for {
port := logsPort.Load()
if port == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
err := logs.Subscribe(context.Background(), c.Client(), func(entry string) {
dart_api_dl.SendToPort(logsPort.Load(), entry)
})
if err != nil {
slog.Debug("log stream disconnected", "error", err)
}
time.Sleep(500 * time.Millisecond)
}
}()
})
}
// mapStatusEvent normalizes a radiance VPN status event for forwarding to
// Dart. Most values pass through unchanged; the exceptions are:
// - vpn.Restarting collapses into vpn.Connecting so the UI shows a
// transitional state during a tunnel restart rather than an unknown
// "restarting" string the Dart parser falls back to disconnected on.
// - A non-empty evt.Error always maps to vpn.ErrorStatus (radiance also
// emits ErrorStatus in this case, but be explicit so the contract
// doesn't depend on radiance always agreeing).
// - An unrecognized status falls back to Disconnected so the UI never
// gets stuck on a stale connected indicator.
func mapStatusEvent(evt vpn.StatusUpdateEvent) (vpn.VPNStatus, string) {
if evt.Error != "" {
return vpn.ErrorStatus, evt.Error
}
switch evt.Status {
case vpn.Connected, vpn.Connecting, vpn.Disconnecting, vpn.Disconnected, vpn.ErrorStatus:
return evt.Status, ""
case vpn.Restarting:
return vpn.Connecting, ""
default:
return vpn.Disconnected, ""
}
}
//export startVPN
func startVPN() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
startStatusListener(c)
if err := checkDaemonReachable(c); err != nil {
return C.CString(err.Error())
}
if err := c.ConnectVPN(""); err != nil {
return C.CString(fmt.Sprintf("start service failed: %v", err))
}
return C.CString("ok")
})
}
//export stopVPN
func stopVPN() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.DisconnectVPN(); err != nil {
return C.CString(fmt.Sprintf("stop service failed: %v", err))
}
return C.CString("ok")
})
}
//export connectToServer
func connectToServer(_tag *C.char) *C.char {
tag := C.GoString(_tag)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
startStatusListener(c)
if err := checkDaemonReachable(c); err != nil {
return SendError(err)
}
// LanternCore.ConnectVPN picks between /vpn/connect and /server/selected
// based on VPNStatus — no dispatch needed here.
if err := c.ConnectVPN(tag); err != nil {
return SendError(fmt.Errorf("start service failed: %w", err))
}
return C.CString("ok")
})
}
//export isVPNConnected
func isVPNConnected() C.int {
c, errStr := requireCore()
if errStr != nil {
return 0
}
running, err := c.IsVPNRunning()
if err != nil {
return 0
}
if running {
return 1
}
return 0
}
// APIS
// Get user data from the local config
//
//export getUserData
func getUserData() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
slog.Debug("Getting user data locally")
bytes, err := c.UserData()
if err != nil {
return SendError(err)
}
return C.CString(string(bytes))
})
}
// Get user data from the server
//
//export fetchUserData
func fetchUserData() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
slog.Debug("Getting user data")
bytes, err := c.FetchUserData()
if err != nil {
return SendError(fmt.Errorf("error fetching user data: %v", err))
}
return C.CString(string(bytes))
})
}
// Fetch stipe subscription payment redirect link
//
//export stripeSubscriptionPaymentRedirect
func stripeSubscriptionPaymentRedirect(subType, _planId, _email, _idempotencyKey *C.char) *C.char {
subscriptionType := C.GoString(subType)
planID := C.GoString(_planId)
email := C.GoString(_email)
idempotencyKey := C.GoString(_idempotencyKey)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
redirect, err := c.StripeSubscriptionPaymentRedirect(subscriptionType, planID, email, idempotencyKey)
if err != nil {
return SendError(err)
}
return C.CString(redirect)
})
}
// Fetch payment redirect link for providers like alipay
//
//export paymentRedirect
func paymentRedirect(_plan, _provider, _email, _idempotencyKey *C.char) *C.char {
plan := C.GoString(_plan)
provider := C.GoString(_provider)
email := C.GoString(_email)
idempotencyKey := C.GoString(_idempotencyKey)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
redirect, err := c.PaymentRedirect(provider, plan, email, idempotencyKey)
if err != nil {
return SendError(err)
}
return C.CString(redirect)
})
}
// Fetch stripe subscription link
//
//export stripeBillingPortalUrl
func stripeBillingPortalUrl() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
url, err := c.StripeBillingPortalUrl()
if err != nil {
return SendError(err)
}
return C.CString(url)
})
}
// Fetch plans from the server
//
//export plans
func plans() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
jsonData, err := c.Plans("non-store")
if err != nil {
return SendError(err)
}
return C.CString(jsonData)
})
}
// OAuth methods
//
//export oauthLoginUrl
func oauthLoginUrl(_provider *C.char) *C.char {
provider := C.GoString(_provider)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
url, err := c.OAuthLoginUrl(provider)
if err != nil {
return SendError(err)
}
return C.CString(url)
})
}
//export oAuthLoginCallback
func oAuthLoginCallback(_oAuthToken *C.char) *C.char {
oAuthToken := C.GoString(_oAuthToken)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
bytes, err := c.OAuthLoginCallback(oAuthToken)
if err != nil {
return SendError(err)
}
return C.CString(string(bytes))
})
}
// User management
//
// login is called when the user logs in with email and password.
//
//export login
func login(_email, _password *C.char) *C.char {
email, password := C.GoString(_email), C.GoString(_password)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
bytes, err := c.Login(email, password)
if err != nil {
return SendError(err)
}
return C.CString(string(bytes))
})
}
//export signup
func signup(_email, _password *C.char) *C.char {
email, password := C.GoString(_email), C.GoString(_password)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.SignUp(email, password); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export logout
func logout(_email *C.char) *C.char {
email := C.GoString(_email)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
bytes, err := c.Logout(email)
if err != nil {
return SendError(err)
}
return C.CString(string(bytes))
})
}
// startRecoveryByEmail will send recovery code to the email
//
//export startRecoveryByEmail
func startRecoveryByEmail(_email *C.char) *C.char {
email := C.GoString(_email)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.StartRecoveryByEmail(email); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// Validate email recovery code
//
//export validateEmailRecoveryCode
func validateEmailRecoveryCode(_email, _code *C.char) *C.char {
email, code := C.GoString(_email), C.GoString(_code)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.ValidateChangeEmailCode(email, code); err != nil {
return SendError(fmt.Errorf("invalid_code: %v", err))
}
return C.CString("ok")
})
}
// Complete recovery by email
//
//export completeRecoveryByEmail
func completeRecoveryByEmail(_email, _newPassword, _code *C.char) *C.char {
email, newPassword, code := C.GoString(_email), C.GoString(_newPassword), C.GoString(_code)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.CompleteRecoveryByEmail(email, newPassword, code); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// removeDevice removes a device by its ID.
//
//export removeDevice
func removeDevice(deviceId *C.char) *C.char {
id := C.GoString(deviceId)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if _, err := c.RemoveDevice(id); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// referralAttachment attaches a referral code to the user's account.
//
//export referralAttachment
func referralAttachment(_referralCode *C.char) *C.char {
referralCode := C.GoString(_referralCode)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
ok, err := c.ReferralAttachment(referralCode)
if err != nil {
return SendError(err)
}
if !ok {
return SendError(fmt.Errorf("failed to get referral attachment"))
}
return C.CString("ok")
})
}
// startChangeEmail initiates the process of changing the user's email address.
//
//export startChangeEmail
func startChangeEmail(_newEmail, _password *C.char) *C.char {
newEmail, password := C.GoString(_newEmail), C.GoString(_password)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.StartChangeEmail(newEmail, password); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// completeChangeEmail completes the process of changing the user's email address.
//
//export completeChangeEmail
func completeChangeEmail(_newEmail, _password, _code *C.char) *C.char {
newEmail, password, code := C.GoString(_newEmail), C.GoString(_password), C.GoString(_code)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.CompleteChangeEmail(newEmail, password, code); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// Delete account permanently
//
//export deleteAccount
func deleteAccount(_email, _password *C.char) *C.char {
email, password := C.GoString(_email), C.GoString(_password)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
bytes, err := c.DeleteAccount(email, password)
if err != nil {
return SendError(err)
}
return C.CString(string(bytes))
})
}
// activationCode create subscription using activation code
//
//export activationCode
func activationCode(_email, _resellerCode *C.char) *C.char {
email, resellerCode := C.GoString(_email), C.GoString(_resellerCode)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
if err := c.ActivationCode(email, resellerCode); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
//export freeCString
func freeCString(cstr *C.char) {
C.free(unsafe.Pointer(cstr))
}
// patchSettings applies a JSON-encoded settings.Settings patch on the daemon.
//
//export patchSettings
func patchSettings(patchJSON *C.char) *C.char {
raw := C.GoString(patchJSON)
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
var updates settings.Settings
if err := json.Unmarshal([]byte(raw), &updates); err != nil {
return SendError(fmt.Errorf("invalid settings JSON: %w", err))
}
if err := c.PatchSettings(updates); err != nil {
return SendError(err)
}
return C.CString("ok")
})
}
// getSettings returns the daemon's current settings as JSON.
//
//export getSettings
func getSettings() *C.char {
return runOnGoStack(func() *C.char {
c, errStr := requireCore()
if errStr != nil {
return errStr
}
data, err := c.GetSettingsJSON()
if err != nil {