-
Notifications
You must be signed in to change notification settings - Fork 45
/
init.go
1805 lines (1561 loc) · 47.7 KB
/
init.go
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 visor pkg/visor/init.go
package visor
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"mime"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/ccding/go-stun/stun"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/skycoin/dmsg/pkg/direct"
dmsgdisc "github.com/skycoin/dmsg/pkg/disc"
"github.com/skycoin/dmsg/pkg/dmsg"
"github.com/skycoin/dmsg/pkg/dmsgctrl"
"github.com/skycoin/dmsg/pkg/dmsgcurl"
"github.com/skycoin/dmsg/pkg/dmsghttp"
"github.com/skycoin/dmsg/pkg/dmsgpty"
"github.com/skycoin/skywire-utilities/pkg/cipher"
"github.com/skycoin/skywire-utilities/pkg/logging"
"github.com/skycoin/skywire-utilities/pkg/netutil"
utilenv "github.com/skycoin/skywire-utilities/pkg/skyenv"
"github.com/skycoin/skywire/internal/vpn"
"github.com/skycoin/skywire/pkg/app/appdisc"
"github.com/skycoin/skywire/pkg/app/appevent"
"github.com/skycoin/skywire/pkg/app/appnet"
"github.com/skycoin/skywire/pkg/app/appserver"
"github.com/skycoin/skywire/pkg/app/launcher"
"github.com/skycoin/skywire/pkg/dmsgc"
"github.com/skycoin/skywire/pkg/routefinder/rfclient"
"github.com/skycoin/skywire/pkg/router"
"github.com/skycoin/skywire/pkg/routing"
"github.com/skycoin/skywire/pkg/servicedisc"
"github.com/skycoin/skywire/pkg/skyenv"
"github.com/skycoin/skywire/pkg/transport"
"github.com/skycoin/skywire/pkg/transport/network"
"github.com/skycoin/skywire/pkg/transport/network/addrresolver"
"github.com/skycoin/skywire/pkg/transport/network/stcp"
ts "github.com/skycoin/skywire/pkg/transport/setup"
"github.com/skycoin/skywire/pkg/transport/tpdclient"
"github.com/skycoin/skywire/pkg/utclient"
"github.com/skycoin/skywire/pkg/util/osutil"
"github.com/skycoin/skywire/pkg/visor/dmsgtracker"
"github.com/skycoin/skywire/pkg/visor/logserver"
"github.com/skycoin/skywire/pkg/visor/visorconfig"
vinit "github.com/skycoin/skywire/pkg/visor/visorinit"
)
type visorCtxKey int
const visorKey visorCtxKey = iota
type runtimeErrsCtxKey int
const runtimeErrsKey runtimeErrsCtxKey = iota
const ownerRWX = 0700
// Visor initialization is split into modules, that can be initialized independently
// Modules are declared here as package-level variables, but also need to be registered
// in the modules system: they need init function and dependencies and their name to be set
// To add new piece of functionality to visor, you need to create a new module variable
// and register it properly in registerModules function
var (
// Event broadcasting system
ebc vinit.Module
// Address resolver
ar vinit.Module
// App discovery
disc vinit.Module
// Stun module
sc vinit.Module
// SUDPH module
sudphC vinit.Module
// STCPR module
stcprC vinit.Module
// STCP module
stcpC vinit.Module
// dmsg pty: a remote terminal to the visor working over dmsg protocol
pty vinit.Module
// Dmsg module
dmsgC vinit.Module
// Transportability checker ensures the visor can accept transports by creating a self-transport or exiting after 3 failed attempts to create one
tc vinit.Module
// TPD concurrency checker removes transports from tpd that the visor does not have registered locally
tpdco vinit.Module
// Transport manager
tr vinit.Module
// Transport setup
trs vinit.Module
// Routing system
rt vinit.Module
// Application launcher
launch vinit.Module
// CLI
cli vinit.Module
// hypervisors to control this visor
hvs vinit.Module
// Uptime tracker
ut vinit.Module
// Public visors: automatically establish connections to public visors
pvs vinit.Module
// Public visor: advertise current visor as public
pv vinit.Module
// Transport module (this is not a functional module but a grouping of all heavy transport types initializations)
tm vinit.Module
// hypervisor module
hv vinit.Module
// Dmsg ctrl module
dmsgCtrl vinit.Module
// Dmsg http log server module
dmsgHTTPLogServer vinit.Module
// System survey module
systemSurvey vinit.Module
// Dmsg http module
dmsgHTTP vinit.Module
// Dmsg trackers module
dmsgTrackers vinit.Module
// Skywire Forwarding conn module
skyFwd vinit.Module
// Ping module
pi vinit.Module
// visor that groups all modules together
vis vinit.Module
// config initialization
// visorConfig vinit.Module
)
// register all modules: instantiate modules with correct names and dependencies, wrap init
// functions to have access to visor and runtime errors channel
func registerModules(logger *logging.MasterLogger) {
// utility module maker, to avoid passing logger and wrapping each init function
// in withVisorCtx
maker := func(name string, f initFn, deps ...*vinit.Module) vinit.Module {
return vinit.MakeModule(name, withInitCtx(f), logger, deps...)
}
// visorConfig = maker("visor_config", initVisorConfig)
dmsgHTTP = maker("dmsg_http", initDmsgHTTP)
ebc = maker("event_broadcaster", initEventBroadcaster)
ar = maker("address_resolver", initAddressResolver, &dmsgHTTP)
disc = maker("discovery", initDiscovery, &dmsgHTTP)
tr = maker("transport", initTransport, &ar, &ebc, &dmsgHTTP)
sc = maker("stun_client", initStunClient)
sudphC = maker("sudph", initSudphClient, &sc, &tr)
stcprC = maker("stcpr", initStcprClient, &tr)
stcpC = maker("stcp", initStcpClient, &tr)
dmsgC = maker("dmsg", initDmsg, &ebc, &dmsgHTTP)
dmsgCtrl = maker("dmsg_ctrl", initDmsgCtrl, &dmsgC, &tr)
dmsgHTTPLogServer = maker("dmsghttp_logserver", initDmsgHTTPLogServer, &dmsgC, &tr)
systemSurvey = maker("system_survey", initSystemSurvey, &dmsgHTTPLogServer)
dmsgTrackers = maker("dmsg_trackers", initDmsgTrackers, &dmsgC)
pty = maker("dmsg_pty", initDmsgpty, &dmsgC)
rt = maker("router", initRouter, &tr, &dmsgC, &dmsgHTTP)
launch = maker("launcher", initLauncher, &ebc, &disc, &dmsgC, &tr, &rt)
cli = maker("cli", initCLI)
hvs = maker("hypervisors", initHypervisors, &dmsgC)
ut = maker("uptime_tracker", initUptimeTracker, &dmsgHTTP)
pv = maker("public_autoconnect", initPublicAutoconnect, &tr, &disc)
trs = maker("transport_setup", initTransportSetup, &dmsgC, &tr)
tm = vinit.MakeModule("transports", vinit.DoNothing, logger, &sc, &sudphC, &dmsgCtrl, &dmsgHTTPLogServer, &dmsgTrackers, &launch)
pvs = maker("public_visor", initPublicVisor, &tr, &ar, &disc, &stcprC)
skyFwd = maker("sky_forward_conn", initSkywireForwardConn, &dmsgC, &dmsgCtrl, &tr, &launch)
pi = maker("ping", initPing, &dmsgC, &tm)
tc = maker("transportable", initEnsureVisorIsTransportable, &dmsgC, &tm)
tpdco = maker("tpd_concurrency", initEnsureTPDConcurrency, &dmsgC, &tm)
vis = vinit.MakeModule("visor", vinit.DoNothing, logger, &ebc, &ar, &disc, &pty,
&tr, &rt, &launch, &cli, &hvs, &ut, &pv, &pvs, &trs, &stcpC, &stcprC, &skyFwd, &pi, &systemSurvey, &tc, &tpdco)
hv = maker("hypervisor", initHypervisor, &vis)
}
type initFn func(context.Context, *Visor, *logging.Logger) error
/*
func initVisorConfig(ctx context.Context, v *Visor, log *logging.Logger) error {
const ebcTimeout = time.Second
ebc := appevent.NewBroadcaster(log, ebcTimeout)
v.pushCloseStack("event_broadcaster", ebc.Close)
v.initLock.Lock()
v.ebc = ebc
v.initLock.Unlock()
return nil
}
*/
func initDmsgHTTP(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
var keys cipher.PubKeys
servers := v.conf.Dmsg.Servers
if len(servers) == 0 {
return nil
}
keys = append(keys, v.conf.PK)
entries := direct.GetAllEntries(keys, servers)
dClient := direct.NewClient(entries, v.MasterLogger().PackageLogger("dmsg_http:direct_client"))
dmsgDC, closeDmsgDC, err := direct.StartDmsg(ctx, v.MasterLogger().PackageLogger("dmsg_http:dmsgDC"),
v.conf.PK, v.conf.SK, dClient, dmsg.DefaultConfig())
if err != nil {
return fmt.Errorf("failed to start dmsg: %w", err)
}
dmsgHTTP := http.Client{Transport: dmsghttp.MakeHTTPTransport(ctx, dmsgDC)}
v.pushCloseStack("dmsg_http", func() error {
closeDmsgDC()
return nil
})
v.initLock.Lock()
v.dClient = dClient
v.dmsgHTTP = &dmsgHTTP
v.dmsgDC = dmsgDC
v.initLock.Unlock()
time.Sleep(time.Duration(len(entries)) * time.Second)
return nil
}
func initEventBroadcaster(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
const ebcTimeout = time.Second
ebc := appevent.NewBroadcaster(log, ebcTimeout)
v.pushCloseStack("event_broadcaster", ebc.Close)
v.initLock.Lock()
v.ebc = ebc
v.initLock.Unlock()
return nil
}
func initAddressResolver(ctx context.Context, v *Visor, log *logging.Logger) error {
conf := v.conf.Transport
httpC, err := getHTTPClient(ctx, v, conf.AddressResolver)
if err != nil {
return err
}
// only needed for dmsghttp
pIP, err := getPublicIP(v, conf.AddressResolver)
if err != nil {
return err
}
arClient, err := addrresolver.NewHTTP(conf.AddressResolver, v.conf.PK, v.conf.SK, httpC, pIP, log, v.MasterLogger())
if err != nil {
err = fmt.Errorf("failed to create address resolver client: %w", err)
return err
}
v.initLock.Lock()
v.arClient = arClient
v.initLock.Unlock()
doneCh := make(chan struct{}, 1)
v.pushCloseStack("address_resolver", func() error {
doneCh <- struct{}{}
return nil
})
return nil
}
func initDiscovery(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
// Prepare app discovery factory.
factory := appdisc.Factory{
Log: v.MasterLogger().PackageLogger("app_discovery"),
MLog: v.MasterLogger(),
}
conf := v.conf.Launcher
httpC, err := getHTTPClient(ctx, v, conf.ServiceDisc)
if err != nil {
return err
}
if conf.ServiceDisc != "" {
factory.PK = v.conf.PK
factory.SK = v.conf.SK
factory.ServiceDisc = conf.ServiceDisc
factory.DisplayNodeIP = conf.DisplayNodeIP
factory.Client = httpC
// only needed for dmsghttp
pIP, err := getPublicIP(v, conf.ServiceDisc)
if err != nil {
return err
}
factory.ClientPublicIP = pIP
}
v.initLock.Lock()
v.serviceDisc = factory
v.initLock.Unlock()
return nil
}
func initStunClient(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
sc := network.GetStunDetails(v.conf.StunServers, log)
v.initLock.Lock()
v.stunClient = sc
v.initLock.Unlock()
v.stunReadyOnce.Do(func() { close(v.stunReady) })
return nil
}
func initDmsg(ctx context.Context, v *Visor, log *logging.Logger) (err error) { //nolint:all
if v.conf.Dmsg == nil {
return fmt.Errorf("cannot initialize dmsg: empty configuration")
}
httpC, err := getHTTPClient(ctx, v, v.conf.Dmsg.Discovery)
if err != nil {
return err
}
dmsgC := dmsgc.New(v.conf.PK, v.conf.SK, v.ebc, v.conf.Dmsg, httpC, v.MasterLogger())
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
dmsgC.Serve(ctx)
}()
v.pushCloseStack("dmsg", func() error {
if err := dmsgC.Close(); err != nil {
return err
}
wg.Wait()
return nil
})
v.initLock.Lock()
v.dmsgC = dmsgC
v.initLock.Unlock()
return nil
}
func initDmsgCtrl(ctx context.Context, v *Visor, _ *logging.Logger) error {
dmsgC := v.dmsgC
if dmsgC == nil {
return nil
}
const dmsgTimeout = time.Second * 20
logger := dmsgC.Logger().WithField("timeout", dmsgTimeout)
logger.Debug("Connecting to the dmsg network...")
select {
case <-time.After(dmsgTimeout):
logger.Warn("Failed to connect to the dmsg network, will try again later.")
go func() {
<-v.dmsgC.Ready()
logger.Debug("Connected to the dmsg network.")
v.tpM.InitDmsgClient(ctx, dmsgC)
}()
case <-v.dmsgC.Ready():
logger.Debug("Connected to the dmsg network.")
v.tpM.InitDmsgClient(ctx, dmsgC)
}
// dmsgctrl setup
cl, err := dmsgC.Listen(visorconfig.DmsgCtrlPort)
if err != nil {
return err
}
v.pushCloseStack("dmsgctrl", cl.Close)
dmsgctrl.ServeListener(cl, 0)
return nil
}
func initDmsgHTTPLogServer(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
dmsgC := v.dmsgC
if dmsgC == nil {
return fmt.Errorf("cannot initialize dmsg log server: dmsg not configured")
}
logger := v.MasterLogger().PackageLogger("dmsghttp_logserver")
var printLog bool
if v.MasterLogger().GetLevel() == logrus.DebugLevel || v.MasterLogger().GetLevel() == logrus.TraceLevel {
printLog = true
}
//whitelist access to the surveys for the hypervisor, dmsggpty whitelist, and for the surveywhitelist of keys which is fetched from the conf service
var whitelistedPKs []cipher.PubKey
if v.conf.SurveyWhitelist != nil {
whitelistedPKs = append(whitelistedPKs, v.conf.SurveyWhitelist...)
}
if v.conf.Hypervisors != nil {
whitelistedPKs = append(whitelistedPKs, v.conf.Hypervisors...)
}
if v.conf.Dmsgpty != nil {
if v.conf.Dmsgpty.Whitelist != nil {
whitelistedPKs = append(whitelistedPKs, v.conf.Dmsgpty.Whitelist...)
}
}
lsAPI := logserver.New(logger, v.conf.Transport.LogStore.Location, v.conf.LocalPath, v.conf.DmsgHTTPServerPath, whitelistedPKs, &v.survey, printLog)
lis, err := dmsgC.Listen(visorconfig.DmsgHTTPPort)
if err != nil {
return err
}
go func() {
<-ctx.Done()
if err := lis.Close(); err != nil {
logger.WithError(err).Error()
}
}()
logger.WithField("dmsg_addr", fmt.Sprintf("dmsg://%v", lis.Addr().String())).
Debug("Serving...")
srv := &http.Server{
ReadHeaderTimeout: 2 * time.Second,
IdleTimeout: 30 * time.Second,
Handler: lsAPI,
}
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
err = srv.Serve(lis)
if errors.Is(err, dmsg.ErrEntityClosed) {
return
}
if err != nil {
logger.WithError(err).Error("Logserver exited with error.")
}
}()
v.pushCloseStack("dmsghttp.logserver", func() error {
if err := srv.Close(); err != nil {
return err
}
wg.Wait()
return nil
})
return nil
}
func initSystemSurvey(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
go GenerateSurvey(v, log, true)
return nil
}
func initDmsgTrackers(ctx context.Context, v *Visor, _ *logging.Logger) error { //nolint:all
dmsgC := v.dmsgC
dtm := dmsgtracker.NewDmsgTrackerManager(v.MasterLogger(), dmsgC, 0, 0)
v.pushCloseStack("dmsg_tracker_manager", func() error {
return dtm.Close()
})
v.initLock.Lock()
v.dtm = dtm
v.initLock.Unlock()
v.dtmReadyOnce.Do(func() { close(v.dtmReady) })
return nil
}
func initSudphClient(ctx context.Context, v *Visor, log *logging.Logger) error {
var serviceURL dmsgcurl.URL
_ = serviceURL.Fill(v.conf.Transport.AddressResolver) //nolint:errcheck
// don't start sudph if we are connection to AR via dmsghttp
if serviceURL.Scheme == "dmsg" {
log.Info("SUDPH transport wont be available under dmsghttp")
return nil
}
if v.stunClient != nil {
switch v.stunClient.NATType {
case stun.NATSymmetric, stun.NATSymmetricUDPFirewall:
log.Warnf("SUDPH transport wont be available as visor is under %v", v.stunClient.NATType.String())
default:
v.tpM.InitClient(ctx, network.SUDPH, v.conf.Transport.SudphPort)
}
}
return nil
}
func initStcprClient(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
v.tpM.InitClient(ctx, network.STCPR, v.conf.Transport.StcprPort)
return nil
}
func initStcpClient(ctx context.Context, v *Visor, log *logging.Logger) error { //nolint:all
if v.conf.STCP != nil {
v.tpM.InitClient(ctx, network.STCP, 0)
}
return nil
}
func initTransport(ctx context.Context, v *Visor, log *logging.Logger) error {
managerLogger := v.MasterLogger().PackageLogger("transport_manager")
tpdC, err := connectToTpDisc(ctx, v, managerLogger)
if err != nil {
err := fmt.Errorf("failed to create transport discovery client: %w", err)
return err
}
var logS transport.LogStore
if v.conf.Transport.LogStore.Type == visorconfig.MemoryLogStore {
logS = transport.InMemoryTransportLogStore()
} else if v.conf.Transport.LogStore.Type == visorconfig.FileLogStore {
logS, err = transport.FileTransportLogStore(ctx, v.conf.Transport.LogStore.Location, time.Duration(v.conf.Transport.LogStore.RotationInterval), log)
if err != nil {
return err
}
} else {
return fmt.Errorf("invalid store type: %v", v.conf.Transport.LogStore.Type)
}
pTps, err := v.conf.GetPersistentTransports()
if err != nil {
err := fmt.Errorf("failed to get persistent transports: %w", err)
return err
}
tpMConf := transport.ManagerConfig{
PubKey: v.conf.PK,
SecKey: v.conf.SK,
DiscoveryClient: tpdC,
LogStore: logS,
PersistentTransportsCache: pTps,
}
// todo: pass down configuration?
var table stcp.PKTable
var listenAddr string
if v.conf.STCP != nil {
table = stcp.NewTable(v.conf.STCP.PKTable)
listenAddr = v.conf.STCP.ListeningAddress
}
factory := network.ClientFactory{
PK: v.conf.PK,
SK: v.conf.SK,
ListenAddr: listenAddr,
PKTable: table,
ARClient: v.arClient,
EB: v.ebc,
MLogger: v.MasterLogger(),
}
tpM, err := transport.NewManager(managerLogger, v.arClient, v.ebc, &tpMConf, factory)
if err != nil {
err := fmt.Errorf("failed to start transport manager: %w", err)
return err
}
ctx, cancel := context.WithCancel(context.Background())
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
tpM.Serve(ctx)
}()
v.pushCloseStack("transport.manager", func() error {
cancel()
tpM.Close()
wg.Wait()
return nil
})
v.initLock.Lock()
v.tpM = tpM
v.initLock.Unlock()
return nil
}
func initTransportSetup(ctx context.Context, v *Visor, log *logging.Logger) error {
ctx, cancel := context.WithCancel(ctx)
// To remove the block set by NewTransportListener if dmsg is not initialized
go func() {
ts, err := ts.NewTransportListener(ctx, v.conf.PK, v.conf.Transport.TransportSetupPKs, v.dmsgC, v.tpM, v.MasterLogger())
if err != nil {
log.Warn(err)
cancel()
}
select {
case <-ctx.Done():
default:
go ts.Serve(ctx)
}
}()
// waiting for at least one transport to initialize
<-v.tpM.Ready()
v.pushCloseStack("transport_setup.rpc", func() error {
cancel()
return nil
})
return nil
}
func initSkywireForwardConn(ctx context.Context, v *Visor, log *logging.Logger) error {
ctx, cancel := context.WithCancel(ctx)
// waiting for at least one transport to initialize
<-v.tpM.Ready()
connApp := appnet.Addr{
Net: appnet.TypeSkynet,
PubKey: v.conf.PK,
Port: routing.Port(skyenv.SkyForwardingServerPort),
}
l, err := appnet.ListenContext(ctx, connApp)
if err != nil {
cancel()
return err
}
v.pushCloseStack("sky_forwarding", func() error {
cancel()
if cErr := l.Close(); cErr != nil {
log.WithError(cErr).Error("Error closing listener.")
}
return nil
})
go func() {
for {
log.Debug("Accepting sky forwarding conn...")
conn, err := l.Accept()
if err != nil {
if !errors.Is(appnet.ErrClosedConn, err) {
log.WithError(err).Error("Failed to accept conn")
}
return
}
log.Debug("Accepted sky forwarding conn")
v.pushCloseStack("sky_forwarding", func() error {
cancel()
if cErr := conn.Close(); cErr != nil {
log.WithError(cErr).Error("Error closing conn.")
}
return nil
})
log.Debug("Wrapping conn...")
wrappedConn, err := appnet.WrapConn(conn)
if err != nil {
log.WithError(err).Error("Failed to wrap conn")
return
}
rAddr := wrappedConn.RemoteAddr().(appnet.Addr)
log.Debugf("Accepted sky forwarding conn on %s from %s", wrappedConn.LocalAddr(), rAddr.PubKey)
go handleServerConn(log, wrappedConn, v)
}
}()
return nil
}
func handleServerConn(log *logging.Logger, remoteConn net.Conn, v *Visor) {
buf := make([]byte, 32*1024)
n, err := remoteConn.Read(buf)
if err != nil {
log.WithError(err).Error("Failed to read packet")
return
}
var cMsg clientMsg
err = json.Unmarshal(buf[:n], &cMsg)
if err != nil {
log.WithError(err).Error("Failed to marshal json")
sendError(log, remoteConn, err)
return
}
log.Debugf("Received: %v", cMsg)
lHost := fmt.Sprintf("localhost:%v", cMsg.Port)
ok := isPortRegistered(cMsg.Port, v)
if !ok {
log.Errorf("Port :%v not registered", cMsg.Port)
sendError(log, remoteConn, fmt.Errorf("Port :%v not registered", cMsg.Port))
return
}
ok = isPortAvailable(log, cMsg.Port)
if ok {
log.Errorf("Failed to dial port %v", cMsg.Port)
sendError(log, remoteConn, fmt.Errorf("Failed to dial port %v", cMsg.Port))
return
}
log.Debugf("Forwarding %s", lHost)
// send nil error to indicate to the remote connection that everything is ok
sendError(log, remoteConn, nil)
go forward(log, remoteConn, lHost)
}
// forward reads a http.Request from the remote conn of the requesting visor forwards that request
// to the requested local server and forwards the http.Response from the local server to the requesting
// visor via the remote conn
func forward(log *logging.Logger, remoteConn net.Conn, lHost string) {
for {
buf := make([]byte, 32*1024)
n, err := remoteConn.Read(buf)
if err != nil {
log.WithError(err).Error("Failed to read packet")
closeConn(log, remoteConn)
return
}
req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(buf[:n])))
if err != nil {
log.WithError(err).Error("Failed to ReadRequest")
closeConn(log, remoteConn)
return
}
req.RequestURI = ""
req.URL.Scheme = "http"
req.URL.Host = lHost
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.WithError(err).Error("Failed to Do req")
closeConn(log, remoteConn)
return
}
err = resp.Write(remoteConn)
if err != nil {
log.WithError(err).Error("Failed to Write")
closeConn(log, remoteConn)
return
}
}
}
func sendError(log *logging.Logger, remoteConn net.Conn, sendErr error) {
var sReply serverReply
if sendErr != nil {
sErr := sendErr.Error()
sReply = serverReply{
Error: &sErr,
}
}
srvReply, err := json.Marshal(sReply)
if err != nil {
log.WithError(err).Error("Failed to unmarshal json")
}
_, err = remoteConn.Write([]byte(srvReply))
if err != nil {
log.WithError(err).Error("Failed write server msg")
}
log.Debugf("Server reply sent %s", srvReply)
// close conn if we send an error
if sendErr != nil {
closeConn(log, remoteConn)
}
}
func closeConn(log *logging.Logger, conn net.Conn) {
if err := conn.Close(); err != nil {
log.WithError(err).Errorf("Error closing client %s connection", conn.RemoteAddr())
}
}
type clientMsg struct {
Port int `json:"port"`
}
type serverReply struct {
Error *string `json:"error,omitempty"`
}
func initPing(ctx context.Context, v *Visor, log *logging.Logger) error {
ctx, cancel := context.WithCancel(ctx)
// waiting for at least one transport to initialize
<-v.tpM.Ready()
connApp := appnet.Addr{
Net: appnet.TypeSkynet,
PubKey: v.conf.PK,
Port: routing.Port(skyenv.SkyPingPort),
}
l, err := appnet.ListenContext(ctx, connApp)
if err != nil {
cancel()
return err
}
v.pushCloseStack("skywire_ping", func() error {
cancel()
if cErr := l.Close(); cErr != nil {
log.WithError(cErr).Error("Error closing listener.")
}
return nil
})
go func() {
for {
log.Debug("Accepting sky ping conn...")
conn, err := l.Accept()
if err != nil {
if !errors.Is(err, appnet.ErrClosedConn) {
log.WithError(err).Error("Failed to accept ping conn")
}
return
}
log.Debug("Accepted sky ping conn")
log.Debug("Wrapping conn...")
wrappedConn, err := appnet.WrapConn(conn)
if err != nil {
log.WithError(err).Error("Failed to wrap conn")
return
}
rAddr := wrappedConn.RemoteAddr().(appnet.Addr)
log.Debugf("Accepted sky ping conn on %s from %s", wrappedConn.LocalAddr(), rAddr.PubKey)
go handlePingConn(log, wrappedConn, v)
}
}()
return nil
}
func handlePingConn(log *logging.Logger, remoteConn net.Conn, v *Visor) {
for {
buf := make([]byte, (32+v.pingPcktSize)*1024)
n, err := remoteConn.Read(buf)
if err != nil {
if !errors.Is(err, io.EOF) {
log.WithError(err).Error("Failed to read packet")
}
return
}
var size PingSizeMsg
err = json.Unmarshal(buf[:n], &size)
if err != nil {
log.WithError(err).Error("Failed to unmarshal json")
return
}
_, err = remoteConn.Write([]byte("ok"))
if err != nil {
log.WithError(err).Error("Failed to write message")
return
}
var ping []byte
for len(ping) != size.Size {
n, err = remoteConn.Read(buf)
if err != nil {
if !errors.Is(err, io.EOF) {
log.WithError(err).Error("Failed to read packet")
}
return
}
ping = append(ping, buf[:n]...)
}
var msg PingMsg
err = json.Unmarshal(ping, &msg)
if err != nil {
log.WithError(err).Error("Failed to unmarshal json")
return
}
now := time.Now()
diff := now.Sub(msg.Timestamp)
v.pingConns[msg.PingPk].latency <- diff
log.Debugf("Received: %s", buf[:n])
}
}
// getRouteSetupHooks aka autotransport
func getRouteSetupHooks(ctx context.Context, v *Visor, log *logging.Logger) []router.RouteSetupHook {
retrier := netutil.NewRetrier(log, time.Second, time.Second*20, 3, 1.3)
return []router.RouteSetupHook{
func(rPK cipher.PubKey, tm *transport.Manager) error {
establishedTransports, _ := v.Transports([]string{string(network.STCPR), string(network.SUDPH), string(network.DMSG)}, []cipher.PubKey{v.conf.PK}, false) //nolint
for _, transportSum := range establishedTransports {
if transportSum.Remote.Hex() == rPK.Hex() {
log.Debugf("Established transport exist. Type: %s", transportSum.Type)
return nil
}
}
allTransports, err := v.arClient.Transports(ctx)
if err != nil {
log.WithError(err).Warn("failed to fetch AR transport")
}
dmsgFallback := func() error {
return retrier.Do(ctx, func() error {
_, err := tm.SaveTransport(ctx, rPK, network.DMSG, transport.LabelAutomatic)
if err != nil {
log.Debugf("Establishing automatic DMSG transport failed.")
}
return err
})
}
// check visor's AR transport
if allTransports == nil && !v.conf.Transport.PublicAutoconnect {
// skips if there's no AR transports
log.Warn("empty AR transports")
return dmsgFallback()
}
transports, ok := allTransports[rPK]
if !ok {
log.WithField("pk", rPK.String()).Warn("pk not found in the transports")
// check if automatic transport is available, if it does,
// continue with route creation
return dmsgFallback()
}
// try to establish direct connection to rPK (single hop) using SUDPH or STCPR
trySTCPR := false
trySUDPH := false
for _, trans := range transports {
nType := network.Type(trans)
if nType == network.STCPR {
trySTCPR = true
continue
}
// Wait until stun client is ready
<-v.stunReady
// skip if SUDPH is under symmetric NAT / under UDP firewall.
if nType == network.SUDPH && (v.stunClient.NATType == stun.NATSymmetric ||
v.stunClient.NATType == stun.NATSymmetricUDPFirewall) {
continue
}
trySUDPH = true
}
// trying to establish direct connection to rPK using STCPR
if trySTCPR {
err := retrier.Do(ctx, func() error {
_, err := tm.SaveTransport(ctx, rPK, network.STCPR, transport.LabelAutomatic)
return err
})
if err == nil {
return nil
}
log.Debugf("Establishing automatic STCPR transport failed.")
}
// trying to establish direct connection to rPK using SUDPH
if trySUDPH {
err := retrier.Do(ctx, func() error {
_, err := tm.SaveTransport(ctx, rPK, network.SUDPH, transport.LabelAutomatic)
return err
})
if err == nil {
return nil
}
log.Debugf("Establishing automatic SUDPH transport failed.")
}
return dmsgFallback()
},
}
}
func initRouter(ctx context.Context, v *Visor, log *logging.Logger) error {
conf := v.conf.Routing
httpC, err := getHTTPClient(ctx, v, conf.RouteFinder)
if err != nil {
return err
}
rfClient := rfclient.NewHTTP(conf.RouteFinder, time.Duration(conf.RouteFinderTimeout), httpC, v.MasterLogger())
logger := v.MasterLogger().PackageLogger("router")
rConf := router.Config{
Logger: logger,
MasterLogger: v.MasterLogger(),
PubKey: v.conf.PK,
SecKey: v.conf.SK,
TransportManager: v.tpM,
RouteFinder: rfClient,
RouteGroupDialer: router.NewSetupNodeDialer(),
SetupNodes: conf.RouteSetupNodes,
RulesGCInterval: 0, // TODO
MinHops: v.conf.Routing.MinHops,
}