-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lokinet.js
1688 lines (1619 loc) · 50.7 KB
/
lokinet.js
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
// no npm!
const os = require('os')
const fs = require('fs')
const dns = require('dns')
const net = require('net')
const ini = require(__dirname + '/ini')
const path = require('path')
const http = require('http')
const https = require('https')
const urlparser = require('url')
const { spawn, exec, execSync } = require('child_process')
const lib = require('./lib.js')
const configUtil = require('./config.js')
// FIXME: disable rpc if desired
const VERSION = 0.9
//console.log('lokinet launcher version', VERSION, 'registered')
var lokinet_version = 'notStartedYet'
function log() {
var args = []
for (var i in arguments) {
var arg = arguments[i]
//console.log('arg type', arg, 'is', typeof(arg))
if (typeof (arg) == 'object') {
arg = JSON.stringify(arg)
}
args.push(arg)
}
console.log('NETWORK:', args.join(' '))
}
function getBoundIPv4s() {
var nics = os.networkInterfaces()
var ipv4s = []
for (var adapter in nics) {
var ips = nics[adapter]
for (var ipIdx in ips) {
var ipMap = ips[ipIdx]
if (ipMap.address.match(/\./)) {
ipv4s.push(ipMap.address)
}
}
}
return ipv4s
}
var auto_config_test_port, auto_config_test_host, auto_config_test_ips
// this doesn't need to connect completely to get our ip
// it won't get our IP if DNS doesn't work
function getNetworkIP(callback) {
// randomly select an ip
//log('getNetworkIP', auto_config_test_ips)
var ip = auto_config_test_ips[Math.floor(Math.random() * auto_config_test_ips.length)]
//log('getNetworkIP from', ip, auto_config_test_port)
var socket = net.createConnection(auto_config_test_port, ip)
socket.setTimeout(5000)
socket.on('connect', function () {
callback(undefined, socket.address().address)
socket.end()
})
var abort = false
socket.on('timeout', function () {
if (socket.address().address) {
abort = true
var resultIp = socket.address().address
log('getNetworkIP timeout [', ip + ':' + auto_config_test_port, '] but still got outgoing IP:', resultIp)
socket.destroy()
callback(undefined, resultIp)
} else {
// don't have what we need, just wait it out, maybe we'll get lucky
//log('getNetworkIP timeout')
//callback('timeout', 'error')
}
})
socket.on('error', function (e) {
console.error('NETWORK: getNetworkIP error', e)
// FIXME: maybe a retry here
log('getNetworkIP failure test', socket.address().address)
log('getNetworkIP failure, retry?')
if (abort) {
log('getNetworkIP already timed out')
return
}
callback(e, 'error')
})
}
function getIfNameFromIP(ip) {
var nics = os.networkInterfaces()
var ipv4s = []
for (var adapter in nics) {
var ips = nics[adapter]
for (var ipIdx in ips) {
var ipMap = ips[ipIdx]
if (ipMap.address == ip) {
return adapter
}
}
}
return ''
}
// how do we abort protoClient externally and have more than one inflight...
// we set a property in the promise object returned...
function httpGet(url, cb) {
const urlDetails = urlparser.parse(url)
//console.log('httpGet url', urlDetails)
//console.log('httpGet', url)
var protoClient = http
if (urlDetails.protocol == 'https:') {
protoClient = https
}
var ref
var p = new Promise(function(resolve, reject) {
// well somehow this can get hung on macos
var abort = false
var stopWatchdog = setInterval(function () {
if (shuttingDown) {
// [', url, ']
log('hung httpGet but have shutdown request, calling back early and setting abort flag')
clearInterval(stopWatchdog)
// actually cancel the download
if (ref && ref.abort) ref.abort()
abort = true
if (cb) cb()
else reject()
return
}
}, 5000)
ref = protoClient.get({
hostname: urlDetails.hostname,
protocol: urlDetails.protocol,
port: urlDetails.port,
path: urlDetails.path,
timeout: 5000,
headers: {
'User-Agent': 'Mozilla/5.0 Oxen-rancher/' + VERSION
}
}, (resp) => {
//log('httpGet setting up handlers')
clearInterval(stopWatchdog)
resp.setEncoding('binary')
let data = ''
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
// warn if not perfect
if (resp.statusCode != 200) {
log('httpGet result code', resp.statusCode)
}
if (abort) {
// we already called back
return
}
// hijack 300s
if (resp.statusCode === 301 || resp.statusCode === 302) {
if (resp.headers.location) {
let loc = resp.headers.location
if (!loc.match(/^http/)) {
if (loc.match(/^\//)) {
// absolute path
loc = urlDetails.protocol + '//' + urlDetails.hostname + ':' + urlDetails.port + loc
} else {
// relative path
loc = urlDetails.protocol + '//' + urlDetails.hostname + ':' + urlDetails.port + urlDetails.path + loc
}
}
console.log('NETWORK: httpGet Redirecting to', loc)
return httpGet(loc, cb)
}
}
// fail on 400s
if (resp.statusCode === 404 || resp.statusCode === 403) {
if (resp.statusCode === 403) console.error('NETWORK:', url, 'is forbidden')
if (resp.statusCode === 404) console.error('NETWORK:', url, 'is not found')
if (cb) cb()
else reject()
return
}
if (cb) cb(data)
resolve(data)
})
}).on("error", (err) => {
console.error("NETWORK: httpGet Error: " + err.message, 'port', urlDetails.port)
clearInterval(stopWatchdog)
//console.log('err', err)
if (cb) cb()
else reject(err)
})
})
p.ref = ref
return p
}
function dynDNSHandler(data, cb) {
}
function getPublicIPv6(cb) {
//v6.ident.me
}
var getPublicIPv4_retries = 0
async function getPublicIPv4(cb) {
// trust more than one source
// randomly find 2 matching sources
// dns is faster than http
// dig +short myip.opendns.com @resolver1.opendns.com
// httpGet doesn't support https yet...
var publicIpServices = [
{ url: 'https://api.ipify.org' },
{ url: 'https://ipinfo.io/ip' },
{ url: 'https://ipecho.net/plain' },
//{ url: 'http://api.ipify.org' },
//{ url: 'http://ipinfo.io/ip' },
//{ url: 'http://ipecho.net/plain' },
{ url: 'http://ifconfig.me/ip' },
{ url: 'http://ipv4.icanhazip.com' },
{ url: 'http://v4.ident.me' },
{ url: 'http://checkip.amazonaws.com' },
//{ url: 'https://checkip.dyndns.org', handler: dynDNSHandler },
]
var service = []
service[0] = Math.floor(Math.random() * publicIpServices.length)
service[1] = service[0]
while (service[1] == service[0]) {
service[1] = Math.floor(Math.random() * publicIpServices.length)
}
var done = [false, false]
let doneResolver
const donePromise = new Promise(res => {
doneResolver = res
})
function markDone(idx, value) {
if (value === undefined) value = ''
done[idx] = value.trim()
let ready = true
//log('done', done)
for (var i in done) {
if (done[i] === false) {
ready = false
// log('getPublicIPv4', i, 'is not ready')
break
}
}
if (!ready) return
// log('getPublicIPv4 look ups are done', done)
if (done[0] != done[1]) {
// try 2 random services again
getPublicIPv4_retries++
// FIXME was 10, add CLI option to up this for CI
if (getPublicIPv4_retries > 50) {
console.error('NAT detection: Can\'t determine public IP address')
process.exit()
}
log(done[0], 'not equal to', done[1], 'retrying attempt #', getPublicIPv4_retries)
getPublicIPv4(cb)
} else {
// return
//log("found public IP", done[0])
if (cb) cb(done[0])
doneResolver(done[0])
}
}
function doCall(number) {
httpGet(publicIpServices[service[number]].url, function (ip) {
if (ip === false) {
service[number] = (Math.random() * publicIpServices.length)
// retry
console.warn(publicIpServices[service[number]].url, 'failed, retrying')
doCall(number)
return
}
// console.log(number, publicIpServices[service[number]].url, ip)
markDone(number, ip)
})
}
doCall(0)
doCall(1)
return donePromise
}
function portIsFree(ip, port, cb) {
const server = net.createServer((socket) => {
})
server.on('error', (err) => {
if (err.code != 'EADDRINUSE') console.error('portIsFree', err)
cb(false)
})
server.listen(port, ip, () => {
// port is free
server.close(function() {
cb(true)
})
})
}
// used for generating temp filenames
function randomString(len) {
var text = ""
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (var i = 0; i < len; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length))
return text
}
function isDnsPort(ip, port, cb) {
const resolver = new dns.Resolver()
resolver.setServers([ip + ':' + port])
resolver.resolve(auto_config_test_host, function (err, records) {
if (err) console.error('resolve error:', err)
log(auto_config_test_host, records)
cb(records !== undefined)
})
}
function testDNSForLokinet(server, cb) {
const resolver = new dns.Resolver()
resolver.setServers([server])
// incase server is 127.0.0.1:undefined
try {
resolver.resolve('localhost.loki', function (err, records) {
if (err) console.error('NETWORK: localhost.loki resolve err:', err)
//log(server, 'localhost.loki test results', records)
cb(records)
})
} catch (e) {
console.error('NETWORK: testDNSForLokinet error, incorrect server?', server)
cb()
}
}
function lookup(host, cb) {
var resolver = new dns.Resolver()
console.log('lookuping', host, 'against servers', runningConfig.dns.bind)
resolver.setServers([runningConfig.dns.bind])
resolver.resolve(host, function (err, records) {
if (err) {
// not as bad... that's at least a properly formatted response
if (err.code == 'ENOTFOUND') {
records = null
} else
// leave bad
if (err.code == 'ETIMEOUT') {
records = undefined
} else {
console.error('lokinet lookup unknown err', err)
}
}
console.log(host, 'lokinet dns test results', records)
cb(records)
})
}
function findLokiNetDNS(cb) {
const localIPs = getBoundIPv4s()
var checksLeft = 0
var servers = []
function checkDone() {
if (shuttingDown) {
//if (cb) cb()
log('not going to start lokinet, shutting down')
return
}
checksLeft--
if (checksLeft <= 0) {
log('readResolv done')
cb(servers)
}
}
/*
var resolvers = dns.getServers()
console.log('Current resolvers', resolvers)
// check local DNS servers in resolv config
for(var i in resolvers) {
const server = resolvers[i]
var idx = localIPs.indexOf(server)
if (idx != -1) {
// local DNS server
console.log('local DNS server detected', server)
checksLeft++
testDNSForLokinet(server, function(isLokinet) {
if (isLokinet) {
// lokinet
console.log(server, 'is a lokinet DNS server')
servers.push(server)
}
checkDone()
})
}
}
*/
// maybe check all local ips too
for (var i in localIPs) {
const server = localIPs[i]
checksLeft++
testDNSForLokinet(server, function (isLokinet) {
if (isLokinet !== undefined) {
// lokinet
log(server, 'is a lokinet DNS server')
servers.push(server)
}
checkDone()
})
}
}
function readResolv(dns_ip, cb) {
const localIPs = getBoundIPv4s()
var servers = []
var checksLeft = 0
//log('make sure we exclude?', dns_ip)
function checkDone() {
if (shuttingDown) {
//if (cb) cb()
log('not going to start lokinet, shutting down')
return
}
checksLeft--
//log('readResolv reports left', checksLeft)
if (checksLeft <= 0) {
log('readResolv done')
cb(servers)
}
}
var resolvers = dns.getServers()
log('Current resolvers', resolvers)
for (var i in resolvers) {
const server = resolvers[i]
if (server.match(':')) continue // lokinet doesn't like ipv6 dns entries
if (server == dns_ip) {
log('preventing DNS loop on', dns_ip)
continue
}
var idx = localIPs.indexOf(server)
if (idx != -1) {
log('local DNS server detected', server)
checksLeft++ // wait for it
testDNSForLokinet(server, function (isLokinet) {
if (isLokinet === undefined) {
// not lokinet
log(server, 'is not a lokinet DNS server')
// FIXME: but did we actually get a response
// is it a valid dns server?
servers.push(server)
}
checkDone()
})
} else {
// non-local
log('found remote DNS server', server)
servers.push(server)
}
}
checksLeft++
checkDone()
/*
const data = fs.readFileSync('/etc/resolv.conf', 'utf-8')
const lines = data.split(/\n/)
for(var i in lines) {
var line = lines[i].trim()
if (line.match(/#/)) {
var parts = line.split(/#/)
line = parts[0].trim()
}
// done reducing
if (!line) continue
if (line.match(/^nameserver /)) {
const server = line.replace(/^nameserver /, '')
var idx = localIPs.indexOf(server)
if (idx != -1) {
console.log('local DNS server detected', server)
const resolver = new dns.Resolver()
resolver.setServers([server])
checksLeft++
resolver.resolve('localhost.loki', function(err, records) {
//if (err) console.error(err)
//console.log('local dns test results', records)
if (records === undefined) {
// not lokinet
console.log(server, 'is not a lokinet DNS server')
servers.push(server)
}
checkDone()
})
} else {
// non-local
console.log('found remote DNS server', server)
servers.push(server)
}
continue
}
checkDone()
console.error('readResolv unknown', line)
}
return servers
*/
}
// this can really delay the start of lokinet
function findFreePort53(ips, index, cb) {
log('testing', ips[index], 'port 53')
isDnsPort(ips[index], 53, function (res) {
//console.log('isDnsPort res', res)
// false
if (!res) {
log('Found free port 53 on', ips[index], index)
cb(ips[index])
return
}
log('Port 53 is not free on', ips[index], index)
if (index + 1 == ips.length) {
cb()
return
}
findFreePort53(ips, index + 1, cb)
})
}
// https://stackoverflow.com/a/40686853
function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
const sep = path.sep
const initDir = path.isAbsolute(targetDir) ? sep : ''
const baseDir = isRelativeToScript ? __dirname : '.'
return targetDir.split(sep).reduce((parentDir, childDir) => {
const curDir = path.resolve(baseDir, parentDir, childDir)
try {
fs.mkdirSync(curDir)
} catch (err) {
if (err.code === 'EEXIST') { // curDir already exists!
return curDir
}
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`)
}
const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1
if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
throw err // Throw if it's just the last created dir.
}
}
return curDir
}, initDir)
}
function makeMultiplatformPath(path) {
return path
}
var cleanUpBootstrap = false
var cleanUpIni = false
function generateINI(config, need, markDone, cb) {
const homeDir = os.homedir()
//console.log('homeDir', homeDir)
//const data = fs.readFileSync(homeDir + '/.lokinet/lokinet.ini', 'utf-8')
//const jConfig = iniToJSON(data)
//console.dir(jConfig)
//const iConfig = jsonToINI(jConfig)
//console.log(iConfig)
var upstreams, lokinet_free53Ip, lokinet_nic
var use_lokinet_rpc_port = config.rpc_port
var lokinet_bootstrap_path = homeDir + '/.lokinet/bootstrap.signed'
var lokinet_nodedb = homeDir + '/.lokinet/netdb'
if (config.data_dir) {
lokinet_nodedb = config.data_dir + '/netdb'
}
if (config.netdb) {
lokinet_nodedb = config.netdb + '/netdb'
}
if (config.netid) {
lokinet_nodedb += '-' + config.netid
}
if (config.data_dir && !fs.existsSync(config.data_dir)) {
log('making', config.data_dir)
mkDirByPathSync(config.data_dir)
}
if (lokinet_nodedb && !fs.existsSync(lokinet_nodedb)) {
log('making', lokinet_nodedb)
mkDirByPathSync(lokinet_nodedb)
}
var upstreamDNS_servers = []
var params = {
upstreamDNS_servers: upstreamDNS_servers,
lokinet_free53Ip: lokinet_free53Ip,
lokinet_nodedb: lokinet_nodedb,
lokinet_bootstrap_path: lokinet_bootstrap_path,
lokinet_nic: lokinet_nic,
use_lokinet_rpc_port: use_lokinet_rpc_port,
}
if (config.bootstrap_url) {
httpGet(config.bootstrap_url, function (bootstrapData) {
if (bootstrapData) {
cleanUpBootstrap = true
const tmpRcPath = os.tmpdir() + '/' + randomString(8) + '.lokinet_signed'
fs.writeFileSync(tmpRcPath, bootstrapData, 'binary')
log('boostrap wrote', bootstrapData.length, 'bytes to', tmpRcPath)
//lokinet_bootstrap_path = tmpRcPath
params.lokinet_bootstrap_path = tmpRcPath
config.bootstrap_path = tmpRcPath
}
markDone('bootstrap', params)
})
} else {
// seed version (also non-url version?)
//params.lokinet_bootstrap_path = ''
markDone('bootstrap', params)
}
readResolv(config.dns_ip, function (servers) {
upstreamDNS_servers = servers
params.upstreamDNS_servers = servers
upstreams = 'upstream=' + servers.join('\nupstream=')
markDone('upstream', params)
})
// check for lokinet RPC port
log('trying', 'http://' + config.rpc_ip + ':' + config.rpc_port)
httpGet('http://' + config.rpc_ip + ':' + config.rpc_port, function (testData) {
//log('rpc has', testData)
if (testData !== undefined) {
log('Bumping RPC port', testData)
// FIXME: retest new port
use_lokinet_rpc_port = use_lokinet_rpc_port + 1
params.use_lokinet_rpc_port = use_lokinet_rpc_port
}
markDone('rpcCheck', params)
})
var skipDNS = false
if (config.dns_ip || config.dns_port) {
skipDNS = true
markDone('dnsBind', params)
}
getNetworkIP(function (e, ip) {
if (ip == 'error' || !ip) {
console.error('NETWORK: can\'t detect default adapter IP address')
// can't handle the exits here because we don't know if it's an actual requirements
// if we need netIf or dnsBind
if (done.netIf !== undefined || done.dnsBind !== undefined) {
process.exit(1)
}
}
log('detected outgoing interface ip', ip)
lokinet_nic = getIfNameFromIP(ip)
params.lokinet_nic = lokinet_nic
params.interfaceIP = ip
log('detected outgoing interface', lokinet_nic)
markDone('netIf', params)
if (skipDNS) return
var tryIps = ['127.0.0.1']
if (os.platform() == 'linux') {
tryIps = ['127.3.2.1', '127.0.0.1']
}
tryIps.push(ip)
findFreePort53(tryIps, 0, function (free53Ip) {
if (free53Ip === undefined) {
console.error('NETWORK: Cant automatically find an IP to put a lokinet DNS server on')
// can't handle the exits here because we don't know if it's an actual requirements
if (need.dnsBind !== undefined) {
process.exit(1)
}
}
lokinet_free53Ip = free53Ip
params.lokinet_free53Ip = free53Ip
log('binding DNS port 53 to', free53Ip)
markDone('dnsBind', params)
})
})
getPublicIPv4(function (ip) {
//log('generateINI - ip', ip)
params.publicIP = ip
markDone('publicIP', params)
})
}
// unified post auto-config adjustments
// disk to running
function applyConfig(file_config, config_obj) {
// bootstrap section
// router mode: bootstrap is optional (might be a seed if not)
// client mode: bootstrap is required, can't have a seed client
if (file_config.bootstrap_path) {
config_obj.bootstrap = {
'add-node': file_config.bootstrap_path
}
}
// connect section
if (file_config.connects) {
if (config_obj.connect === undefined) config_obj.connect = {}
for(var k in file_config.connects) {
config_obj.connect[k] = file_config.connects[k]
}
}
// router section
if (file_config.nickname) {
config_obj.router.nickname = file_config.nickname
}
if (file_config.transport_privkey) {
config_obj.router['transport-privkey'] = file_config.transport_privkey
}
if (file_config.encryption_privkey) {
config_obj.router['encryption-privkey'] = file_config.encryption_privkey
}
if (file_config.ident_privkey) {
config_obj.router['ident-privkey'] = file_config.ident_privkey
}
if (file_config.contact_file) {
config_obj.router['contact-file'] = file_config.contact_file
}
// set default netid based on testnet
if (file_config.lokid && file_config.lokid.network == "test") {
config_obj.router.netid = 'gamma'
//runningConfig.network['ifaddr'] = '10.254.0.1/24' // hack for Ryan's box
}
if (file_config.netid) {
config_obj.router.netid = file_config.netid
}
// network section
if (file_config.profiling_file) {
if (config_obj.network === undefined) config_obj.network = {}
config_obj.network.profiles = file_config.profiling_file
}
// just pass through (truish/falsish flag)
if (file_config.profiling) {
config_obj.network.profiling = file_config.profiling
}
if (file_config.ifname) {
if (config_obj.network === undefined) config_obj.network = {}
config_obj.network.ifname = file_config.ifname
}
if (file_config.ifaddr) {
if (config_obj.network === undefined) config_obj.network = {}
config_obj.network.ifaddr = file_config.ifaddr
}
// logging section
if (file_config.log_path) {
// make sure section is created
if (config_obj.logging === undefined) config_obj.logging = {}
config_obj.logging.type = 'file'
config_obj.logging.file = file_config.log_path
}
// metrics section
if (file_config.metrics_path) {
// make sure section is created
if (config_obj.metrics === undefined) config_obj.metrics = {}
config_obj.metrics['json-metrics-path'] = file_config.metrics_path + '/metrics.json'
}
// dns section
if (file_config.dns_ip || file_config.dns_port) {
// FIXME: dynamic dns ip
// we'd have to move the DNS autodetection here
// detect free port 53 on ip
// for now just make sure we have sane defaults
var ip = file_config.dns_ip
if (!ip) ip = '127.0.0.1'
var dnsPort = file_config.dns_port
if (dnsPort === undefined) dnsPort = 53
config_obj.dns.bind = ip + ':' + dnsPort
}
// api section
if (file_config.rpc_ip === false) {
config_obj.api.enabled = false
}
}
var runningConfig = {}
var genSnCallbackFired // a lock to make sure we only have one callback inflight at a time
function generateSerivceNodeINI(config, cb) {
const homeDir = os.homedir()
var done = {
bootstrap: false,
upstream: false,
rpcCheck: false,
dnsBind: false,
netIf: false,
publicIP: false,
}
if (config.publicIP) {
done.publicIP = undefined
}
genSnCallbackFired = false
function markDone(completeProcess, params) {
done[completeProcess] = true
let ready = true
for (var i in done) {
if (!done[i]) {
ready = false
//log(i, 'is not ready')
break
}
}
if (shuttingDown) {
//if (cb) cb()
log('not going to start lokinet, shutting down')
return
}
if (!ready) return
// we may have un-required proceses call markDone after we started
if (genSnCallbackFired) return
genSnCallbackFired = true
/*
var keyPath = homeDir + '/.loki/'
//
if (config.lokid && config.lokid.data_dir) {
keyPath = config.lokid.data_dir
// make sure it has a trailing slash
if (keyPath[keyPath.length - 1] != '/') {
keyPath += '/'
}
}
if (config.lokid &&
(config.lokid.network == "test" || config.lokid.network == "demo")) {
keyPath += 'testnet/'
}
keyPath += 'key'
*/
log('markDone params', JSON.stringify(params))
log('PUBLIC', params.publicIP, 'IFACE', params.interfaceIP)
var useNAT = false
if (params.publicIP != params.interfaceIP) {
log('NAT DETECTED MAKE SURE YOU FORWARD UDP PORT', config.public_port, 'on', params.publicIP, 'to', params.interfaceIP)
useNAT = true
}
log('Drafting lokinet service node config')
runningConfig = {
router: {
threads: 4,
'min-routers': 6,
'max-routers': 60,
},
dns: {
upstream: params.upstreamDNS_servers,
bind: params.lokinet_free53Ip + ':53',
},
logging: {
level: 'info',
}, /*
metrics: {
json-metrics-path:
}, */
netdb: {
dir: params.lokinet_nodedb,
},
bind: {
// will be set after
},
network: {
enabled: true,
//profiling: false,
exit: false
},
api: {
enabled: true,
bind: config.rpc_ip + ':' + params.use_lokinet_rpc_port
},
system: {
user: '_lokinet',
group: '_loki'
}
}
if (config.lokid) {
runningConfig.lokid = {
enabled: true,
jsonrpc: config.lokid.rpc_ip + ':' + config.lokid.rpc_port,
//username: config.lokid.rpc_user,
//password: config.lokid.rpc_pass,
//'service-node-seed': keyPath
}
if (config.lokid.rpc_user) {
runningConfig.lokid.username = config.lokid.rpc_user
runningConfig.lokid.password = config.lokid.rpc_pass
}
}
if (useNAT) {
runningConfig.router['public-ip'] = params.publicIP
runningConfig.router['public-port'] = config.public_port
}
// NAT is only used for routers...
// inject manual NAT config?
if (config.public_ip) {
runningConfig.router['public-ip'] = config.public_ip
runningConfig.router['public-port'] = config.public_port
}
if (config.forceNatOff) {
delete runningConfig.router['public-ip']
delete runningConfig.router['public-port']
}
runningConfig.bind[params.lokinet_nic] = config.public_port
if (config.internal_port) {
runningConfig.bind[params.lokinet_nic] = config.internal_port
}
applyConfig(config, runningConfig)
// not in seedMode, make sure we have some way to bootstrap
if (!config.seedMode && !runningConfig.bootstrap && !runningConfig.connect) {
console.error()
console.error('NETWORK: ERROR! No bootstrap or connects and not in seedMode')
console.error()
// should this be shutdown_everything?
process.exit(1)
}
// doesn't work
//runningConfig.network['type'] = 'null' // disable exit
//runningConfig.network['enabled'] = true
cb(ini.jsonToINI(runningConfig))
}
generateINI(config, done, markDone, cb)
}
function generateSerivceNodeINI8(config, cb) {
const homeDir = os.homedir()
var done = {
bootstrap: false,
upstream: false,
rpcCheck: false,
dnsBind: false,
netIf: false,
publicIP: false,
}
if (config.publicIP) {
done.publicIP = undefined
}
genSnCallbackFired = false
function markDone(completeProcess, params) {
done[completeProcess] = true
let ready = true
for (var i in done) {
if (!done[i]) {
ready = false
//log(i, 'is not ready')
break
}
}
if (shuttingDown) {
//if (cb) cb()
log('not going to start lokinet, shutting down')
return
}
if (!ready) return
// we may have un-required proceses call markDone after we started
if (genSnCallbackFired) return
genSnCallbackFired = true
/*
var keyPath = homeDir + '/.loki/'
//
if (config.lokid && config.lokid.data_dir) {
keyPath = config.lokid.data_dir
// make sure it has a trailing slash
if (keyPath[keyPath.length - 1] != '/') {
keyPath += '/'
}
}
if (config.lokid &&
(config.lokid.network == "test" || config.lokid.network == "demo")) {
keyPath += 'testnet/'
}
keyPath += 'key'
*/
log('markDone params', JSON.stringify(params))
log('PUBLIC', params.publicIP, 'IFACE', params.interfaceIP)
var useNAT = false
if (params.publicIP != params.interfaceIP) {
log('NAT DETECTED MAKE SURE YOU FORWARD UDP PORT', config.public_port, 'on', params.publicIP, 'to', params.interfaceIP)
useNAT = true
}
log('Drafting lokinet service node config')
runningConfig = {
router: {
"data-dir": config.data_dir,
},
dns: {
upstream: params.upstreamDNS_servers,
bind: params.lokinet_free53Ip + ':53',
},
logging: {
level: 'info',
}, /*
metrics: {
json-metrics-path:
},
netdb: {
}, */
bind: {
inbound: ':' + (config.public_port),
},
/*
network: {