This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 975
/
tor.js
1935 lines (1810 loc) · 58.1 KB
/
tor.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict'
/**
* Tor daemon management.
*
* This doesn't actually manage the tor daemon: the parts that did are
* commented out. Rather it just watches the tor daemon's control
* port file for activity and connects to its control socket.
*
* @module tor
*/
const EventEmitter = require('events')
const assert = require('assert')
const electron = require('electron')
const fs = require('fs')
const net = require('net')
const path = require('path')
const stream = require('stream')
/**
* Return the path to the directory where we store tor-related files.
*
* @returns {path}
*/
function torBravePath () {
const bravePath = electron.app.getPath('userData')
return path.join(bravePath, 'tor')
}
/**
* Return the path to the data directory that we use for our tor
* daemon.
*
* @returns {path}
*/
function torDataDirPath () {
return path.join(torBravePath(), 'data')
}
/**
* Return the path to the directory we watch for changes as tor
* starts up.
*
* @returns {path}
*/
function torWatchDirPath () {
return path.join(torBravePath(), 'watch')
}
/**
* Return the path to the file containing the port number for the
* control channel that our tor daemon is listening on.
*
* @returns {path}
*/
function torControlPortPath () {
return path.join(torWatchDirPath(), 'controlport')
}
/*
* Return the path to the file containing the control connection
* authentication cookie.
*
* @returns {path}
*/
function torControlCookiePath () {
return path.join(torWatchDirPath(), 'control_auth_cookie')
}
/**
* State for a tor daemon subprocess.
*/
class TorDaemon extends EventEmitter {
/**
* Initialization-only constructor. No parameters, no nontrivial
* computation, no I/O.
*/
constructor () {
super()
this._process = null // child process
this._watcher = null // fs watcher
this._polling = false // true if we are polling for start
this._retry_poll = null // set if polling, true if should retry on fail
this._control = null // TorControl instance
this._socks_addresses = null // array of tor's socks addresses
this._tor_version = null // string of tor version number
}
/**
* Create the necessary directories and invoke callback when done.
* We assume the parent of torBravePath exists; we create it and
* everything we need underneath it. On failure other than EEXIST,
* may leave directories partially created.
*
* @param {Function(Error)} callback
*/
setup (callback) {
const directories = [
torBravePath(),
torWatchDirPath()
]
const loop = (i) => {
if (i === directories.length) {
return callback(null)
}
assert(i >= 0)
assert(i < directories.length)
fs.mkdir(directories[i], 0o700, (err) => {
if (err && err.code !== 'EEXIST') {
return callback(err)
}
loop(i + 1)
})
}
loop(0)
}
/**
* Start the tor daemon and start watching for it to start up.
* Caller must ensure that the necessary directories have been
* created with {@link TorDaemon#setup}.
*
* This function is asynchronous. If the tor daemon successfully
* launches, this emits a `'launch'` event with the SOCKS address on
* which it is listening. If the tor daemon exits, this emits an
* `'exit'` event.
*/
start () {
// Begin watching for the control port file to be written.
const watchDir = torWatchDirPath()
const watchOpts = {persistent: false}
assert(this._watcher === null)
this._watcher = fs.watch(watchDir, watchOpts, (event, filename) => {
this._watchEvent(event, filename)
})
this._process = 'i am the very seeming of a child process daemon'
// Defer to the next tick so that the user can reliably do
//
// torDaemon.start()
// torDaemon.on('launch', ...)
process.nextTick(() => this._poll())
}
/**
* Stop watching for the tor daemon to start up.
*/
stop () {
assert(this._watcher)
this._watcher.close()
this._watcher = null
}
/**
* Kill the tor daemon and close the control channel.
*/
kill () {
if (!this._process) {
assert(this._process === null)
assert(this._control === null)
return
}
if (this._control) {
this._control.destroy()
}
}
/**
* Internal subroutine. Report an error and kill the daemon.
*
* @param {string} msg - error message
*/
_error (msg) {
this.emit('error', msg)
this.kill()
}
/**
* Internal subroutine. Called by fs.watch when the tor watch
* directory is changed. If the control port file is newly written,
* then the control socket should be available now.
*
* Note: filename is documented to be unreliable, so we don't use
* it. Instead we just check whether the control port file is
* written and matches.
*
* @param {string} event
* @param {string} filename
*/
_watchEvent (event, filename) {
// If the process died in the interim, give up.
if (!this._process) {
console.log('tor: process dead, ignoring watch event')
return
}
// Watcher shouldn't be there without process.
assert(this._watcher)
// If the control connection is already open, nothing to do.
if (this._control) {
return
}
this._poll()
}
/**
* Internal subroutine. Poll for whether tor has started yet, or if
* there is a poll already pending, tell it to retry in case it
* fails.
*/
_poll () {
assert(this._process)
assert(this._control === null)
if (this._polling) {
this._retry_poll = true
return
} else {
assert(this._retry_poll === null)
}
this._polling = true
this._retry_poll = false
this._doPoll()
}
/**
* Internal subroutine. Actually poll for whether tor has started
* yet. If tor is not ready yet, we exit via this._polled(), which
* either waits for another notification or polls again in case
* another notification already came in.
*
* When is tor ready? We need the control port _and_ the control
* authentication cookie. The tor daemon currently writes the
* control port first, and _then_ the control authentication
* cookie. So we open both, and check the mtimes. If either one
* is not there, tor is not ready. If the cookie is older, it is
* stale, from an older run of tor, and so tor is not ready in
* that case.
*/
_doPoll () {
assert(this._process)
assert(this._control === null)
assert(this._polling)
this._eatControlCookie((err, cookie, cookieMtime) => {
if (err) {
// If there's an error, don't worry: the file may have been
// written incompletely, and we will, with any luck, be notified
// again when it has been written completely and renamed to its
// permanent location.
return this._polled()
}
// If the process died in the interim, give up.
if (!this._process) {
return this._polled()
}
// Assert we're in a sane state: we have a process, we have no
// control, and we're polling.
assert(this._process)
assert(this._control === null)
assert(this._polling)
this._eatControlPort((err, portno, portMtime) => {
if (err) {
// If there's an error, don't worry: the file may not be
// ready yet, and we'll be notified when it is.
return this._polled()
}
// If the process died in the interim, give up.
if (!this._process) {
return this._polled()
}
// Assert we're in a sane state: we have a process, we have no
// control, and we're polling.
assert(this._process)
assert(this._control === null)
assert(this._polling)
// Tor writes the control port first, then the auth cookie.
// If the auth cookie is _older_ than the control port, then
// it's definitely stale. If they are the _same age_, then
// probably the control port is older but the file system
// resolution is just not enough to distinguish them.
if (cookieMtime < portMtime) {
console.log(`tor: tossing stale cookie`)
return this._polled()
}
this._openControl(portno, cookie)
})
})
}
/**
* Internal subroutine. Called when done polling. If no control
* socket but asked to retry, arrange to poll again; otherwise,
* restore state.
*/
_polled () {
assert(this._polling)
if (this._retry_poll && this._control === null) {
this._retry_poll = false
return process.nextTick(() => this._doPoll())
}
this._polling = false
this._retry_poll = null
}
/*
* Internal subroutine. Move the control port out of the way to
* commit to it, and read the control port and its mtime.
*
* @param {Function(Error, number, Date)} callback
*/
_eatControlPort (callback) {
// First, rename the file, so that we don't read a stale one later.
const oldf = torControlPortPath()
const newf = torControlPortPath() + '.ack'
fs.rename(oldf, newf, (err) => {
if (err) {
return callback(err, null, null)
}
// Then open the committed control port file.
fs.open(newf, 'r', (err, fd) => {
if (err) {
return callback(err, null, null)
}
// Get the mtime.
fs.fstat(fd, (err, stat) => {
if (err) {
return callback(err, null, null)
}
// Read up to 27 octets, the maximum we will ever need.
const readlen = 'PORT=255.255.255.255:65535\n'.length
const buf = Buffer.alloc(readlen)
fs.read(fd, buf, 0, readlen, null, (err, nread, buf) => {
let portno = null
do { // break for cleanup
if (err) {
break
}
// Make sure the line looks sensible.
const line = buf.slice(0, nread).toString('utf8')
if (!line.startsWith('PORT=') || !line.endsWith('\n')) {
err = new Error(`invalid control port file`)
break
}
if (!line.startsWith('PORT=127.0.0.1:')) {
err = new Error(`control port has non-local address`)
break
}
// Parse the port number.
const portstr = line.slice(
'PORT=127.0.0.1:'.length, line.length - 1)
const portno0 = parseInt(portstr, 10)
if (isNaN(portno) || portno === 0) {
err = new Error(`invalid control port number`)
break
}
// We'll take it!
assert(!err)
portno = portno0
} while (0)
// We're done with the control port file; close it.
fs.close(fd, (err) => {
if (err) {
console.log(`tor: close control port file failed: ${err}`)
}
})
// And call back.
callback(err, portno, stat.mtime)
})
})
})
})
}
/**
* Internal subroutine. Move the control cookie out of the way to
* commit to it, and read the control cookie and its mtime.
*
* @param {Function(Error, Buffer, Date)} callback
*/
_eatControlCookie (callback) {
// First, rename the file, so that we don't read a stale one later.
const oldf = torControlCookiePath()
const newf = torControlCookiePath() + '.ack'
fs.rename(oldf, newf, (err) => {
if (err) {
return callback(err, null, null)
}
// Then open the control cookie file.
fs.open(newf, 'r', (err, fd) => {
if (err) {
return callback(err, null, null)
}
// Get the mtime.
fs.fstat(fd, (err, stat) => {
if (err) {
return callback(err, null, null)
}
// Read up to 33 octets. We should need no more than 32, so 33
// will indicate the file is abnormally large.
const readlen = 33
const buf = Buffer.alloc(readlen)
fs.read(fd, buf, 0, readlen, null, (err, nread, buf) => {
let cookie = null
do { // break for cleanup
if (err) {
break
}
// Check for probable truncation.
if (nread === readlen) {
err = new Error('control cookie too long')
break
}
// We'll take it!
assert(!err)
cookie = buf.slice(0, nread)
} while (0)
// We're done with the control cookie file; close it.
fs.close(fd, (err) => {
if (err) {
console.log(`tor: close control auth cookie file failed: ${err}`)
}
})
// And call back.
callback(err, cookie, stat.mtime)
})
})
})
})
}
/**
* Internal subroutine. Open a control socket, arrange to set up a
* TorControl to manage it, and authenticate to it with a null
* authentication cookie.
*
* @param {number} portno
* @param {Buffer} cookie - secret authentication cookie in raw bits
*/
_openControl (portno, cookie) {
assert(this._process)
assert(this._control === null)
// Create a socket and arrange provisional close/error listeners.
const controlSocket = new net.Socket()
const closeMethod = () => console.log('tor: control socket closed early')
const errorMethod = (err) => {
console.log(`tor: control socket connection error: ${err}`)
controlSocket.destroy(err)
return this._polled()
}
controlSocket.on('close', closeMethod)
controlSocket.on('error', errorMethod)
// Now connect the socket.
controlSocket.connect({host: '127.0.0.1', port: portno}, () => {
// If the process died in the interim, give up.
if (!this._process) {
console.log('tor: process died, closing control')
controlSocket.close((err) => {
if (err) {
console.log(`tor: close control socket failed: ${err}`)
}
})
return this._polled()
}
// Assert we are in a sane state: we have a process, but we have
// no control yet.
assert(this._process)
assert(this._control === null)
// Remove our provisional listeners and hand ownership to
// TorControl.
controlSocket.removeListener('close', closeMethod)
controlSocket.removeListener('error', errorMethod)
const readable = controlSocket
const writable = controlSocket
const control = new TorControl(readable, writable)
this._control = control
this._control.on('error', (err) => this._controlError(control, err))
this._control.on('close', () => this._controlClosed(control))
// We have finished polling, _and_ we are scheduled to be
// notified either by (a) our file system activity watcher, or
// (b) failure on the control channel. That way we won't lose
// any notifications that tor has restarted.
this._polled()
const hexCookie = cookie.toString('hex')
this._control.cmd1(`AUTHENTICATE ${hexCookie}`, (err, status, reply) => {
if (!err) {
if (status !== '250' || reply !== 'OK') {
err = new Error(`Tor error ${status}: ${reply}`)
}
}
if (err) {
return this._error(`authentication failure: ${err}`)
}
this._control.getSOCKSListeners((err, listeners) => {
if (err) {
return this._error(`failed to get socks addresses: ${err}`)
}
this._socks_addresses = listeners
this._control.getVersion((err, version) => {
if (err) {
return this._error(`failed to get version: ${err}`)
}
this._tor_version = version
this.emit('launch', this.getSOCKSAddress())
})
})
})
})
}
/**
* Internal subroutine. Callback for any errors on the control
* socket. Report it to the console and give up by destroying the
* control connection.
*
* @param {TorControl} control
* @param {Error} err
*/
_controlError (control, err) {
if (this._control === control) {
this._control = null
} else {
console.log('tor: control error got deferred')
}
console.log(`tor: control socket error: ${err}`)
control.destroy(err)
}
/*
* Internal subroutine. Callback for when the control socket has
* been closed. Clear it, and interpret it to mean the tor process
* has exited.
*
* TODO(riastradh): Also try to restart tor or anything?
*
* @param {TorControl} control
*/
_controlClosed (control) {
if (this._control === control) {
this._control = null
} else {
console.log('tor: control closure got deferred')
}
// Assume this means the process exited.
this.emit('exit')
// Poll in case we received a watch event for file system activity
// before we actually closed the channel.
this._poll()
}
/**
* Returns the current SOCKS address: a string of the form
* `<IPv4>:<portno>', `[<IPv6>]:<portno>', or `unix:<pathname>'.
* If tor is not initialized yet, or is dead, this returns null
* instead.
*
* @returns {string} SOCKS socket address as string
*/
getSOCKSAddress () {
if (!this._socks_addresses) {
return null
}
return this._socks_addresses[0]
}
/**
* Returns the version of the software running the tor daemon. If
* tor is not initialized yet, or is dead, this returns null
* instead.
*
* @returns {string} tor version number as string
*/
getVersion () {
return this._tor_version
}
/**
* Returns the control socket.
*
* @returns {TorControl}
*/
getControl () {
return this._control
}
/**
* Internal subroutine. Arrange to call handler for asynchronous
* events about info.
*
* @param {string} event - STATUS_CLIENT, STATUS_GENERAL, &c.
* @param {dict} keys - BOOTSTRAP, CIRCUIT_ESTABLISHED, &c.
* @param {string} info - status/bootstrap-phase, status/circuit-established
* @param {Function(Error, string)} statusHandler - called asynchronously
* @param {Function(Error, string)} infoHandler - called for GETINFO
* @param {Function(Error)} callback
*/
_torStatus (event, keys, info, statusHandler, infoHandler, callback) {
const control = this._control
// Subscribe to events.
const statusListener = (data, extra) => {
const args = data.split(' ') // TODO(riastradh): better parsing
if (args.length < 2) {
console.log(`tor: warning: truncated ${event}`)
return
}
if (!(args[1] in keys)) {
// Not for us!
return
}
let err = null
if (args[0] === 'ERR') {
err = new Error(`${data}`)
}
statusHandler(err, data)
}
control.on(`async-${event}`, statusListener)
control.subscribe(event, (err) => {
if (err) {
control.removeListener(`async-${event}`, statusListener)
return callback(err)
}
// Run `GETINFO ${info}' to kick us off, in case it's a long
// time to the next phase or we're wedged.
const getinfoLine = (status, reply) => {
if (status !== '250') {
const err = new Error(`${status} ${reply}`)
return infoHandler(err, null)
}
const prefix = `${info}=`
if (!reply.startsWith(prefix)) {
const err = new Error(`bogus ${info}: ${reply}`)
return infoHandler(err, null)
}
const data = reply.slice(prefix.length)
return infoHandler(err, data)
}
control.cmd(`GETINFO ${info}`, getinfoLine, (err, status, reply) => {
if (!err) {
if (status !== '250') {
err = new Error(`${status} ${reply}`)
}
}
if (err) {
// TODO(riastradh): Unsubscribe and remove listener or not?
return callback(err)
}
// Success!
return callback(null)
})
})
}
/**
* Arrange to call handler with the current bootstrap progress and
* every time it changes. The handler may be called before or after
* the callback.
*
* TODO(riastradh): No way to deregister.
*
* @param {Function(Error, string)} handler
* @param {Function(Error)} callback
*/
onBootstrap (handler, callback) {
const handleStatus = (err, data) => {
// <severity> BOOTSTRAP ... PROGRESS=<num>
const args = data.split(' ') // TODO(riastradh): better parsing
assert(args.length >= 2)
// Find the progress. args[0] is ERR/WARN/NOTICE; args[1] is
// BOOTSTRAP.
assert(args[1] === 'BOOTSTRAP')
for (let i = 2; i < args.length; i++) {
const [k, v] = args[i].split('=')
if (k === 'PROGRESS') {
return handler(err, v)
}
}
// No progress. If there isn't an error already, treat it as
// one.
if (!err) {
err = new Error(`bootstrap without progress: ${data}`)
}
handler(err, null)
}
const handleInfo = (err, data) => {
// <severity> BOOTSTRAP ... PROGRESS=<num>
const args = data.split(' ') // TODO(riastradh): better parsing
if (args.length < 2) {
console.log(`tor: warning: truncated ${event}`)
return
}
if (args[1] !== 'BOOTSTRAP') {
// Not for us!
return
}
if (!err && args[0] === 'ERR') {
err = new Error(`${data}`)
}
handleStatus(err, data)
}
const event = 'STATUS_CLIENT'
const keys = {BOOTSTRAP: 1}
const info = 'status/bootstrap-phase'
this._torStatus(event, keys, info, handleStatus, handleInfo, callback)
}
/**
* Arrange to call handler when tor thinks it can or cannot build
* circuits for client use. The handler may be called before or
* after the callback.
*
* @param {Function(Error, string)} handler
* @param {Function(Error)} callback
*/
onCircuitEstablished (handler, callback) {
const handleStatus = (err, data) => {
if (err) {
return handler(err, null)
}
// <severity> CIRCUIT_ESTABLISHED
// <severity> CIRCUIT_NOT_ESTABLISHED
const args = data.split(' ') // TODO(riastradh): better parsing
if (args[1] === 'CIRCUIT_ESTABLISHED') {
handler(null, true)
} else if (args[1] === 'CIRCUIT_NOT_ESTABLISHED') {
let err = null
for (let i = 2; i < args.length; i++) {
const [k, v] = args[i].split('=')
if (k === 'REASON') {
err = new Error(`tor: ${v}`)
break
}
}
handler(err, false)
} else {
const err = new Error(`tor: bogus circuit establishment info: ${data}`)
handler(err, null)
}
}
const handleInfo = (err, s) => {
if (err) {
return handler(err, null)
}
// 0 or 1
if (s === '1') {
handler(null, true)
} else if (s === '0') {
handler(null, false)
} else {
err = new Error(`tor: bogus circuit establishment info: ${s}`)
handler(err, false)
}
}
const event = 'STATUS_CLIENT'
const keys = {CIRCUIT_ESTABLISHED: 1, CIRCUIT_NOT_ESTABLISHED: 1}
const info = 'status/circuit-established'
this._torStatus(event, keys, info, handleStatus, handleInfo, callback)
}
/**
* Arrange to call handler when tor thinks the network is up or
* down. The handler may be called before or after the callback.
*
* @param {Function(boolean)} handler
* @param {Function(Error)} callback
*/
onNetworkLiveness (handler, callback) {
const control = this._control
// Subscribe to events.
const statusListener = (data, extra) => {
const liveness = {UP: true, DOWN: false}
if (!(data in liveness)) {
console.log(`tor: warning: invalid network liveness: ${data}`)
return
}
handler(liveness[data])
}
control.on('async-NETWORK_LIVENESS', statusListener)
control.subscribe('NETWORK_LIVENESS', (err) => {
if (err) {
control.removeListener('async-NETWORK_LIVENESS', statusListener)
return callback(err)
}
// Run `GETINFO network-liveness' to find out what state we're
// in now before the next state change event.
let err0 = null
const getinfoLine = (status, reply) => {
const liveness = {up: true, down: false}
if (status !== '250') {
err0 = err0 || new Error(`${status} ${reply}`)
return
}
const prefix = 'network-liveness='
if (!reply.startsWith(prefix)) {
err0 = err0 || new Error(`bogus network-liveness: ${reply}`)
return
}
const data = reply.slice(prefix.length)
if (!(data in liveness)) {
err0 = err0 || new Error(`bogus network-liveness: ${data}`)
return
}
return handler(liveness[data])
}
const cmd = 'GETINFO network-liveness'
control.cmd(cmd, getinfoLine, (err, status, reply) => {
if (!err) {
if (err0) {
err = err0
} else if (status !== '250') {
err = new Error(`${status} ${reply}`)
}
}
if (err) {
control.removeListener('async-NETWORK_LIVENESS', statusListener)
control.unsubscribe('NETWORK_LIVENESS', (err1) => {
return callback(err)
})
}
// Success!
return callback(null)
})
})
}
}
/**
* Set of all recognized asynchronous event types in the tor control
* connection for use with SETEVENTS.
*/
const TOR_ASYNC_EVENTS = {
ADDRMAP: 1,
AUTHDIR_NEWDESCS: 1,
BUILDTIMEOUT_SET: 1,
BW: 1,
CELL_STATS: 1,
CIRC: 1,
CIRC_BW: 1,
CIRC_MINOR: 1,
CLIENTS_SEEN: 1,
CONF_CHANGED: 1,
CONN_BW: 1,
DEBUG: 1,
DESCCHANGED: 1,
ERR: 1,
GUARD: 1,
HS_DESC: 1,
// HS_DESC_CONTENT: 1, // omitted because uses data replies
INFO: 1,
NETWORK_LIVENESS: 1,
// NEWCONSENSUS: 1 // omitted because uses data replies
NEWDESC: 1,
NOTICE: 1,
// NS: 1, // omitted because uses data replies
ORCONN: 1,
SIGNAL: 1,
STATUS_CLIENT: 1,
STATUS_GENERAL: 1,
STATUS_SERVER: 1,
STREAM: 1,
STREAM_BW: 1,
TB_EMPTY: 1,
TRANSPORT_LAUNCHED: 1,
WARN: 1
}
/**
* Internal utility class. State for a tor control socket interface.
*
* Emits the following events:
*
* async-${KEYWORD}(line, extra)
* - on asynchronous events from Tor subscribed with
* TorControl.subscribe.
*
* error(err)
* - on error
*
* close
* - at most once when the control connection closes; no more events
* will be emitted.
*/
class TorControl extends EventEmitter {
/**
* Constructor. Takes ownership of readable and writable to read
* from and write to them. The readable must not be paused.
*
* @param {Readable} readable - source for output of tor control connection
* @param {Writable} writable - sink for input to control connection
*/
constructor (readable, writable) {
assert(readable instanceof stream.Readable)
assert(!readable.isPaused())
super()
this._readable = new LineReadable(readable, 4096)
this._readable_on_line = this._onLine.bind(this)
this._readable_on_error = this._onError.bind(this)
this._readable_on_end = this._onEnd.bind(this)
this._readable_on_close = this._onClose.bind(this)
this._readable.on('line', this._readable_on_line)
this._readable.on('error', this._readable_on_error)
this._readable.on('end', this._readable_on_end)
this._readable.on('close', this._readable_on_close)
this._writable = writable
this._writable_on_error = this._onError.bind(this)
this._writable_on_close = this._onClose.bind(this)
this._writable.on('error', this._writable_on_error)
this._writable.on('close', this._writable_on_close)
this._destroyed = false
this._closing = 2 // count of {reader, writer} left to close
this._cmdq = []
this._async_keyword = null
this._async_initial = null
this._async_extra = null
this._async_skip = null
this._tor_events = {}
}
/**
* Destroy the control connection:
* - Destroy the underlying streams.
* - Remove any listeners on the readable and writable.
* - Mark the control closed so it can't be used any more.
* - Pass an error to all callbacks waiting for command completion.
*
* Idempotent. Repeated calls have no effect.
*
* @param {Error} err
*/
destroy (err) {
if (this._destroyed) {
return
}
this._readable.destroy(err)
this._writable.end()
this._writable.destroy(err)
this._readable.removeListener('line', this._readable_on_line)
this._readable.removeListener('error', this._readable_on_error)
this._readable.removeListener('end', this._readable_on_end)
this._readable.removeListener('close', this._readable_on_close)
this._writable.removeListener('error', this._writable_on_error)
this._writable.removeListener('close', this._writable_on_close)
this._destroyed = true
err = err || new Error('tor: control channel destroyed')
while (this._cmdq.length > 0) {
const [, callback] = this._cmdq.shift()
callback(err, null, null)
}
}
/**
* Internal subroutine. Callback for {@link LineReadable} `'line'`
* event on receipt of a line of input, either complete or truncated
* at the maximum length. Parse the line and handle it, triggering
* any asynchronous events or calling a command callback as
* appropriate.
*