-
Notifications
You must be signed in to change notification settings - Fork 467
/
main.js
1636 lines (1527 loc) · 43.9 KB
/
main.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
// =============================
require('module-alias/register')
// =============================
const electron = require('electron')
const { app, systemPreferences, Menu, Tray, BrowserWindow, dialog, shell } = electron
const path = require('path')
const { spawn, execSync } = require('child_process')
const log = require('electron-log')
const sudo = require('sudo-prompt')
const defaultGateway = require('default-gateway')
const os = require('os')
const fs = require('fs')
const net = require('net')
const util = require('util')
const Netmask = require('netmask').Netmask
const Store = require('electron-store')
const AutoLaunch = require('auto-launch')
const prompt = require('electron-prompt')
const https = require('https')
const semver = require('semver')
const i18n = require('i18next')
const i18nextBackend = require('i18next-node-fs-backend')
const config = require('@mellow/config/config')
const convert = require('@mellow/config/convert')
const isDarwin = process.platform == 'darwin'
const isLinux = process.platform == 'linux'
const isWin32 = process.platform == 'win32'
let win = null
let running = false
let helperVerified = false
let coreNeedResume = false
let tray = null
let trayMenu = null
let core = null
let coreInterrupt = false
let origGw = null
let origGwScope = null
let sendThrough = null
var pacServer = null
let originalDnsServers = null
let defaultFakeDnsExcludes = (() => {
switch (process.platform) {
case 'win32':
const domains = [
'dns.msftncsi.com',
'msftconnecttest.com'
]
return domains.join(',')
default:
return ''
}
})()
var tunName
switch (process.platform) {
case 'darwin':
tunName = 'utun233'
break
case 'win32':
tunName = 'mellow-tap0'
break
case 'linux':
tunName = 'tun1'
break
}
let tunAddr = '10.255.0.2'
let tunMask = '255.255.255.0'
let tunGw = '10.255.0.1'
var tunAddrBlock = new Netmask(tunAddr, tunMask)
var localesPath
if (app.isPackaged) {
localesPath = path.join(process.resourcesPath, 'src/locales/{{lng}}/{{ns}}.json')
} else {
localesPath = path.join(__dirname, 'locales/{{lng}}/{{ns}}.json')
}
const i18nextOptions = {
debug: true,
backend: {
loadPath: localesPath
},
fallbackLng: 'en'
}
i18n.use(i18nextBackend)
i18n.init(i18nextOptions)
const autoLauncher = new AutoLaunch({name: 'Mellow'})
const schema = {
autoLaunch: {
type: 'boolean',
default: false
},
autoConnect: {
type: 'boolean',
default: false
},
checkUpdates: {
type: 'boolean',
default: true
},
loglevel: {
type: 'string',
default: 'info'
},
configUrl: {
type: 'string',
default: 'https://raw.githubusercontent.com/mellow-io/mellow/master/template/example.conf'
},
selectedConfig: {
type: 'string',
default: ''
},
sniffing: {
type: 'boolean',
default: true
},
fakeDns: {
type: 'boolean',
default: false
},
systemDns: {
type: 'string',
default: '114.114.114.114,8.8.8.8'
},
systemProxy: {
type: 'boolean',
default: true
},
udpTimeout: {
type: 'string',
default: '1m0s'
},
hideDockIcon: {
type: 'boolean',
default: false
},
fakeDnsExcludes: {
type: 'string',
default: defaultFakeDnsExcludes
},
beginningPort: {
type: 'integer',
default: 2884
},
}
const store = new Store({name: 'preference', schema: schema})
let beginningPort = store.get('beginningPort')
let coreRpcPort = beginningPort + 0
let systemProxyHttpPort = beginningPort + 1
let systemProxySocksPort = beginningPort + 2
let pacServerPort = beginningPort + 3
function resetAutoLaunch() {
if (store.get('autoLaunch')) {
autoLauncher.isEnabled().then((isEnabled) => {
if (!isEnabled) {
// Enabled in Mellow but found disabled in system preferences.
autoLauncher.enable()
}
}).catch((err) => {
dialog.showErrorBox('Error', 'Failed to check auto launcher status.')
})
} else {
autoLauncher.isEnabled().then((isEnabled) => {
if (isEnabled) {
// Disabled in Mellow but found enabled in system preferences.
autoLauncher.disable()
}
}).catch((err) => {
dialog.showErrorBox('Error', 'Failed to check auto launcher status.')
})
}
}
resetAutoLaunch()
var helperResourcePath
if (app.isPackaged) {
helperResourcePath = path.join(process.resourcesPath, 'src/helper')
} else {
helperResourcePath = path.join(path.join(__dirname, 'helper'), process.platform)
for (let f of ['geo.mmdb', 'geosite.dat']) {
src = path.join(path.join(__dirname, 'helper'), f)
dst = path.join(helperResourcePath, f)
if (!fs.existsSync(dst)) {
fs.copyFileSync(src, dst)
}
}
}
var helperInstallPath
var helperFiles
var executableHelperFiles
switch (process.platform) {
case 'darwin':
helperInstallPath = "/Library/Application Support/Mellow"
helperFiles = [
'geo.mmdb',
'geosite.dat',
'core',
'md5sum',
'route'
]
executableHelperFiles = [
'core',
'md5sum',
'route'
]
break
case 'linux':
helperInstallPath = '/usr/local/mellow'
helperFiles = [
'geo.mmdb',
'geosite.dat',
'core',
'md5sum',
'ip'
]
executableHelperFiles = [
'core',
'md5sum',
'ip'
]
break
}
let logPath = log.transports.file.findLogPath('Mellow')
let configFolder = path.join(app.getPath('userData'), 'config')
let lagecyConfigFile = path.join(app.getPath('userData'), 'cfg.json')
let runningConfig = path.join(app.getPath('userData'), 'running-config.json')
const createConfigFolderIfNotExists = () => {
if (!fs.existsSync(configFolder)) {
fs.mkdirSync(configFolder, { recursive: true })
log.info(util.format('Created config folder %s', configFolder))
}
}
createConfigFolderIfNotExists()
const handleLagecyConfigFile = () => {
if (fs.existsSync(lagecyConfigFile)) {
const newPath = path.join(configFolder, 'cfg.json')
fs.renameSync(lagecyConfigFile, newPath)
log.info(util.format('Renamed lagecy config file %s to %s', lagecyConfigFile, newPath))
}
}
handleLagecyConfigFile()
var md5Cmd
var routeCmd
var coreCmd
var setDnsCmd
switch(process.platform) {
case 'linux':
md5Cmd = path.join(helperInstallPath, 'md5sum')
coreCmd = path.join(helperInstallPath, 'core')
routeCmd = path.join(helperInstallPath, 'ip')
break
case 'darwin':
md5Cmd = path.join(helperInstallPath, 'md5sum')
coreCmd = path.join(helperInstallPath, 'core')
routeCmd = path.join(helperInstallPath, 'route')
setDnsCmd = path.join(helperResourcePath, 'setdnsservers')
break
case 'win32':
coreCmd = path.join(helperResourcePath, 'core.exe')
break
}
function isDarkMode() {
return (systemPreferences.getUserDefault('AppleInterfaceStyle', 'string') == 'Dark')
}
const trayIcon = {
get on() {
switch (process.platform) {
case 'linux':
return path.join(__dirname, 'assets/tray-on-icon.png')
case 'darwin':
if (isDarkMode()) {
return path.join(__dirname, 'assets/tray-on-icon-light.png')
} else {
return path.join(__dirname, 'assets/tray-on-icon.png')
}
case 'win32':
return path.join(__dirname, 'assets/tray-on-icon-win.ico')
}
},
get off() {
switch (process.platform) {
case 'linux':
return path.join(__dirname, 'assets/tray-off-icon.png')
case 'darwin':
if (isDarkMode()) {
return path.join(__dirname, 'assets/tray-off-icon-light.png')
} else {
return path.join(__dirname, 'assets/tray-off-icon.png')
}
case 'win32':
return path.join(__dirname, 'assets/tray-off-icon.png')
}
}
}
const state = {
Disconnected: 'Disconnected',
Connecting: 'Connecting',
Connected: 'Connected'
}
var currentState = state.Disconnected
function isConnected() {
return (currentState == state.Connected)
}
function setState(s) {
switch (s) {
case state.Disconnected:
tray.setImage(trayIcon.off)
break
case state.Connecting:
tray.setImage(trayIcon.off)
break
case state.Connected:
tray.setImage(trayIcon.on)
break
default:
throw 'Invalid State'
}
currentState = s
}
let themeChangedNotifier = null
switch (process.platform) {
case 'darwin':
themeChangedNotifier = systemPreferences.subscribeNotification('AppleInterfaceThemeChangedNotification', (e, i) => {
setState(currentState)
})
break
}
function monitorPowerEvent() {
electron.powerMonitor.on('lock-screen', () => {
log.info('Screen locked.')
})
electron.powerMonitor.on('unlock-screen', () => {
log.info('Screen unlocked.')
})
electron.powerMonitor.on('suspend', () => {
log.info('Device suspended.')
if (isWin32) {
coreNeedResume = true
down()
}
})
electron.powerMonitor.on('resume', async () => {
log.info('Device resumed.')
await delay(2000)
up()
})
}
function checkHelper() {
log.info('Checking helper files.')
for (let f of helperFiles) {
try {
resourceFile = path.join(helperResourcePath, f)
installedFile = path.join(helperInstallPath, f)
resourceSum = execSync(util.format('"%s" "%s"', md5Cmd, resourceFile))
installedSum = execSync(util.format('"%s" "%s"', md5Cmd, installedFile))
if (resourceSum.toString() != installedSum.toString()) {
log.info('md5 checksum not match:')
log.info(util.format('[%s "%s"] not match [%s "%s"]', resourceFile, resourceSum, installedFile, installedSum))
return false
}
} catch (err) {
if (err.status == 1) {
dialog.showErrorBox('Error', 'Failed checksum helper files, it seems md5/md5sum or awk command is missing.')
} else {
log.info(err)
return false
}
}
}
for (let f of executableHelperFiles) {
installedFile = path.join(helperInstallPath, f)
try {
execSync(util.format('sh -c "[ -x \'%s\' ]"', installedFile))
} catch (err) {
log.info('File requires execute permission', installedFile)
return false
}
}
return true
}
function startPacServer() {
const requestListener = (req, res) => {
const script = util.format('function FindProxyForURL(url, host) { return "SOCKS5 127.0.0.1:%s; SOCKS 127.0.0.1:%s" }', systemProxySocksPort, systemProxySocksPort)
console.log(req.url)
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
})
res.write(script)
res.end()
}
const http = require('http')
pacServer = http.createServer(requestListener)
pacServer.listen(pacServerPort, '127.0.0.1')
}
function stopPacServer() {
if (pacServer) {
pacServer.close()
}
}
function configureSystemProxy(enabled) {
switch (process.platform) {
case 'darwin':
var configureProxy = path.join(helperResourcePath, 'configure_proxy')
var configureProxyCmd = util.format('"%s" "%s"', configureProxy, enabled ? 'on' : 'off', systemProxyHttpPort, systemProxySocksPort)
log.info(util.format('Set system proxy with command: %s', configureProxyCmd))
execSync(configureProxyCmd)
break
case 'win32':
if (enabled) {
startPacServer()
} else {
stopPacServer()
}
var configureProxy = path.join(helperResourcePath, 'configure_proxy.bat')
var configureProxyCmd = util.format('"%s" "%s" %s', configureProxy, enabled ? 'on' : 'off', pacServerPort)
log.info(util.format('Set system proxy with command: %s', configureProxyCmd))
execSync(configureProxyCmd)
break
}
}
async function startCore(callback) {
coreInterrupt = false
var v2json
const selectedConfig = store.get('selectedConfig')
if (selectedConfig.length == 0) {
dialog.showMessageBox({ message: i18n.t('Please select a config.') })
return
}
if (selectedConfig.includes('.conf')) {
try {
const content = fs.readFileSync(selectedConfig, 'utf-8')
let subConfig = {}
routingRuleSubConfig = convert.readSubConfigBySection(content, 'RoutingRule')
if (routingRuleSubConfig.length != 0) {
subConfig['RoutingRule'] = {}
routingRuleSubConfig.forEach((filename) => {
subConfig['RoutingRule'][filename] = fs.readFileSync(path.join(configFolder, filename), 'utf-8')
})
}
v2json = convert.constructJson(content, subConfig)
} catch(err) {
dialog.showErrorBox('Error', 'Config error: ' + err)
return
}
} else if (selectedConfig.includes('.json')) {
try {
var content = fs.readFileSync(selectedConfig, 'utf-8')
content = convert.removeJsonComments(content)
v2json = JSON.parse(content)
} catch (err) {
dialog.showErrorBox('Error', 'Config error: ' + err)
return
}
} else {
dialog.showErrorBox('Config Error', 'Unknown config suffix')
return
}
if (store.get('systemProxy')) {
const systemProxyOpts = {
enabled: store.get('systemProxy'),
httpPort: systemProxyHttpPort,
socksPort: systemProxySocksPort
}
const inbounds = convert.constructSystemInbounds(systemProxyOpts)
v2json = convert.appendInbounds(v2json, inbounds)
}
const parsedConfig = JSON.stringify(v2json, null, 2)
if (parsedConfig) {
f = fs.openSync(runningConfig, 'w')
fs.writeFileSync(f, parsedConfig)
fs.closeSync(f)
} else {
dialog.showErrorBox('Config Error', 'Parsing config failed')
return
}
if (isWin32) {
log.info('Ensuring tap device sets up correctly.')
try {
out = await sudoExec(util.format('"%s" "%s" %s', path.join(helperResourcePath, 'ensure_tap_device.bat'), path.join(helperResourcePath, 'tap-windows6'), tunName))
log.info(out)
} catch (err) {
dialog.showErrorBox('Error', 'TAP device not ready: ' + err)
return
}
}
if (isDarwin || isWin32) {
configureSystemProxy(store.get('systemProxy'))
}
var params
var cmd
switch (process.platform) {
case 'linux':
case 'darwin':
params = [
'-tunName', tunName,
'-tunAddr', tunAddr,
'-tunMask', tunMask,
'-tunGw', tunGw,
'-sendThrough', sendThrough,
'-vconfig', runningConfig,
'-proxyType', 'v2ray',
'-udpTimeout', store.get('udpTimeout'),
'-relayICMP',
'-loglevel', store.get('loglevel')
]
break
case 'win32':
// The flag order is important, some flags won't work in specific
// flag order, and I don't known exactly why is it.
params = [
'-tunName', tunName,
'-tunAddr', tunAddr,
'-tunMask', tunMask,
'-tunGw', tunGw,
'-tunDns', store.get('systemDns'),
'-rpcPort', coreRpcPort.toString(),
'-sendThrough', sendThrough,
'-proxyType', 'v2ray',
'-udpTimeout', store.get('udpTimeout'),
'-relayICMP',
'-loglevel', store.get('loglevel'),
'-vconfig', runningConfig
]
break
}
if (store.get('sniffing')) {
params.push(...['-sniffingType', 'http,tls'])
} else {
params.push(...['-sniffingType', 'none'])
}
if (store.get('fakeDns')) {
params.push('-fakeDns')
params.push(...['-fakeDnsExcludes', store.get('fakeDnsExcludes')])
}
let env = Object.create(process.env)
switch (process.platform) {
case 'linux':
case 'darwin':
env.LANG = 'en_US.UTF-8'
break
case 'win32':
break
}
core = spawn(coreCmd, params, { env: env })
core.stdout.on('data', (data) => {
log.info(data.toString())
})
core.stderr.on('data', (data) => {
log.info(data.toString())
})
core.on('close', (code, signal) => {
log.info('Core stopped, code', code, 'signal' , signal)
if (coreNeedResume) {
// Change status and wait for the resume event callback to be called so the core will be restarted.
log.info('Core will restart upon device resume.')
coreNeedResume = false
core = null
return
}
if (code && code != 0) {
log.info('Core fails to startup, interrupt the starting procedure.')
coreInterrupt = true
core = null
dialog.showErrorBox('Error', util.format('Failed to start the Core, see "%s" for more details.', logPath))
}
setState(state.Disconnected)
})
core.on('error', (err) => {
log.info('Core errored.')
coreInterrupt = true
core = null
if ((isDarwin || isWin32) && store.get('systemProxy')) {
configureSystemProxy(false)
}
setState(state.Disconnected)
log.info(err)
dialog.showErrorBox('Error', util.format('Failed to start the Core, see "%s" for more details.', logPath))
})
log.info('Core started.')
if (callback !== null) {
callback()
}
}
function isPrivateIP(ip) {
return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
/^f[cd][0-9a-f]{2}:/i.test(ip) ||
/^fe80:/i.test(ip) ||
/^::1$/.test(ip) ||
/^::$/.test(ip)
}
async function configRoute() {
if (coreInterrupt) {
log.info('Start interrupted.')
coreInterrupt = false
return
}
switch (process.platform) {
case 'linux':
case 'darwin':
if (tunGw === null || origGw === null || origGwScope === null) {
return
}
break
case 'win32':
if (tunGw === null || origGw === null) {
return
}
break
default:
dialog.showErrorBox('Error', 'Unsupported platform: ' + process.platform)
}
gw = null
for (i = 0; i < 5; i++) {
gw = getDefaultGateway()
if (gw === null) {
await delay(2 * 1000)
log.info('Retrying to get the default gateway.')
continue
}
break
}
log.info('The default gateway before configuring routes:')
log.info(gw)
if (gw === null) {
dialog.showErrorBox('Error', util.format('Failed to find the default gateway, see "%s" for more details.', logPath))
}
// Try to find the TUN interface, it must exists and up before we can
// add routes to it. We now wait for the core to open the device.
tunIface = null
for (i = 0; i < 10; i++) {
tunIface = findTunInterface()
if (tunIface === null) {
await delay(2 * 1000)
log.info('Retrying to find the TUN interface.')
continue
}
break
}
if (tunIface === null) {
dialog.showErrorBox('Error', util.format('Failed to find the TUN interface, see "%s" for more details.', logPath))
return
}
log.info('The TUN interface before configuring routes:')
log.info(tunIface)
try {
switch (process.platform) {
case 'darwin':
execSync(util.format('"%s" delete default', routeCmd))
execSync(util.format('"%s" delete default -ifscope %s', routeCmd, origGwScope))
execSync(util.format('"%s" add default %s', routeCmd, tunGw))
execSync(util.format('"%s" add default %s -ifscope %s', routeCmd, origGw, origGwScope))
const dnsServers = require('dns').getServers()
if ((dnsServers.length == 0) || (isPrivateIP(dnsServers[0]))) {
execSync(util.format('"%s" "%s"', setDnsCmd, store.get('systemDns').split(',').join(' ')))
originalDnsServers = dnsServers
log.info('Set system DNS', store.get('systemDns'))
}
break
case 'win32':
await sudoExec(util.format('"%s" %s %s', path.join(helperResourcePath, 'config_route.bat'), tunGw, tunName))
break
case 'linux':
execSync(util.format('"%s" %s %s %s %s %s', path.join(helperResourcePath, 'config_route'), routeCmd, tunGw, origGw, origGwScope, sendThrough))
break
}
log.info('Set ' + tunGw + ' as the default gateway.')
} catch (err) {
log.info(err)
log.info(err)
dialog.showErrorBox('Error', util.format('Failed to configure routes, see "%s" for more details.', logPath))
}
setState(state.Connected)
trayMenu.items[0].enabled = false
trayMenu.items[1].enabled = true
trayMenu.items[2].enabled = true
tray.setContextMenu(trayMenu)
}
async function recoverRoute() {
if (origGw !== null) {
log.info('Restore ' + origGw + ' as the default gateway.')
try {
switch (process.platform) {
case 'darwin':
execSync(util.format('"%s" delete default', routeCmd))
execSync(util.format('"%s" delete default -ifscope %s', routeCmd, origGwScope))
execSync(util.format('"%s" add default %s', routeCmd, origGw))
if (originalDnsServers) {
execSync(util.format('"%s" "%s"', setDnsCmd, originalDnsServers.join(' ')))
log.info('Recover system DNS servers to', originalDnsServers.join(' '))
}
break
case 'win32':
await sudoExec(util.format('"%s" %s', path.join(helperResourcePath, 'recover_route.bat'), tunName))
break
case 'linux':
execSync(util.format('"%s" %s %s', path.join(helperResourcePath, 'recover_route'), routeCmd, sendThrough, origGw))
break
}
} catch (error) {
log.info(error.stdout)
log.info(error.stderr)
dialog.showErrorBox('Error', util.format('Failed to configure routes, see "%s" for more details.', logPath))
}
} else {
dialog.showErrorBox('Error', 'Failed to recover original network, original gateway is missing.')
}
}
function stopCoreWindows() {
return new Promise((resolve, reject) => {
// We want a graceful shutdown for the core, but sending signals
// not work on Windows, use TCP instead.
c = new net.Socket()
c.connect(coreRpcPort, '127.0.0.1', () => {
c.write('SIGINT')
})
c.on('data', (data) => {
if (data.toString() == 'OK') {
c.destroy()
core = null
resolve()
}
})
c.on('error', (err) => {
log.info('management RPC error:')
log.info(err)
reject()
})
})
}
async function stopCore() {
if (core !== null) {
if (isWin32) {
await stopCoreWindows()
} else {
core.kill('SIGTERM')
core = null
}
}
if ((isDarwin || isWin32) && store.get('systemProxy')) {
configureSystemProxy(false)
}
setState(state.Disconnected)
}
const delay = ms => new Promise(res => setTimeout(res, ms))
async function up() {
switch (process.platform) {
case 'darwin':
case 'linux':
if (!helperVerified) {
if (!checkHelper()) {
success = await installHelper()
if (!success) {
return
}
}
helperVerified = true
}
break
}
gw = null
for (i = 0; i < 5; i++) {
gw = getDefaultGateway()
if (gw === null) {
await delay(1000)
log.info('Retrying to get the default gateway.')
continue
}
break
}
if (gw === null) {
// Default gateway is missing, already tried 5 times to get it and
// all failed, better to show an error to user and stop the core
// for the moment.
stopCore()
dialog.showErrorBox('Error', 'Failed to find the default gateway, please ensure your network is reachable. You may try to restart/reconnect the network/wifi.')
return
} else if (tunAddrBlock.contains(gw['gateway'])) {
// Routing seems ready, check if the core should restart.
if (core === null) {
startCore(null)
running = true
return
}
return
} else {
// This is the original gateway.
origGw = gw['gateway']
log.info('Original gateway is ' + origGw)
st = null
for (i = 0; i < 5; i++) {
st = findOriginalSendThrough(gw)
if (st === null) {
await delay(1000)
log.info('Retrying to find the original send through address.')
continue
}
break
}
if (st !== null) {
log.info('Original send through ' + st['address'] + ' ' + st['interface'])
sendThrough = st['address']
origGwScope = st['interface']
} else {
log.info('Can not find original send through.')
sendThrough = null
origGwScope = null
stopCore()
return
}
// Original gateway and original send through were found, start the core
// if necessary.
if (core === null) {
startCore(configRoute)
running = true
} else {
// Core is running but the default gateway is not the tun interface,
// it's very likely network has been reset due to network changes.
// And the original gateway is also very likely point to a different
// IP, we must restart the core and pass the correct send through address.
await stopCore()
startCore(configRoute)
running = true
}
}
}
async function down() {
log.info('Shutting down the core.')
// Get the gateway first since stopping the core may causes
// the route to be deleted.
gw = getDefaultGateway()
if (core) {
await stopCore()
}
// Recover default route only if current route is to tunGw.
if (gw !== null && tunAddrBlock.contains(gw['gateway'])) {
recoverRoute()
}
running = false
setState(state.Disconnected)
log.info('Core downed.')
trayMenu.items[0].enabled = true
trayMenu.items[1].enabled = false
trayMenu.items[2].enabled = false
tray.setContextMenu(trayMenu)
}
// {gateway: '1.2.3.4', interface: 'en1'}
function getDefaultGateway() {
try {
return defaultGateway.v4.sync()
} catch(error) {
return null
}
}
// {address: '192.168.1.1', interface: 'en0'}
function findOriginalSendThrough(gw) {
if (gw === null) {
return null
}
ifaces = os.networkInterfaces()
for (name in ifaces) {
if (name == gw['interface']) {
for (let info of ifaces[name]) {
if (info['family'] == 'IPv4' && !info['internal'] && info['cidr'] !== undefined) {
block = new Netmask(info['cidr'])
if (block.contains(gw['gateway'])) {
return {address: info['address'], interface: name}
}
}
}
}
}
return null
}
function findTunInterface() {
ifaces = os.networkInterfaces()
for (k in ifaces) {
for (let addrObj of ifaces[k]) {
cidr = addrObj['cidr']
if (addrObj['family'] == 'IPv4' && !addrObj['internal'] && cidr !== undefined) {
block = new Netmask(cidr)
if (block.contains(tunGw)) {
return {address: addrObj['address'], interface: k}
}
}
}
}
return null
}
async function sudoExec(cmd) {
return new Promise((resolve, reject) => {
var options = { name: 'Mellow' }
sudo.exec(cmd, options, (err, stdout, stderr) => {
if (err) {
log.info(stderr)
log.info(stdout)
reject(err)
}
resolve(stdout)
})
})
}
async function installHelper() {
log.info('Installing helper.')
var installer
var cmd
if (isLinux) {
let tmpResDir = '/tmp/mellow_helper_res'
execSync(util.format('cp -r "%s" "%s"', helperResourcePath, tmpResDir))
installer = path.join(tmpResDir, 'install_helper')
cmd = util.format('"%s" "%s" "%s"', installer, tmpResDir, helperInstallPath)
} else {
installer = path.join(helperResourcePath, 'install_helper')
cmd = util.format('"%s" "%s" "%s"', installer, helperResourcePath, helperInstallPath)
}
log.info('Executing:', cmd)