-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
1201 lines (1045 loc) · 33.9 KB
/
index.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
/* global chrome */
'use strict'
/**
* net
* ===
*
* The net module provides you with an asynchronous network wrapper. It
* contains methods for creating both servers and clients (called streams).
* You can include this module with require('chrome-net')
*/
var EventEmitter = require('events')
var inherits = require('inherits')
var stream = require('stream')
var deprecate = require('util').deprecate
var timers = require('timers')
var Buffer = require('buffer').Buffer
// Track open servers and sockets to route incoming sockets (via onAccept and onReceive)
// to the right handlers.
var servers = {}
var sockets = {}
// Thorough check for Chrome App since both Edge and Chrome implement dummy chrome object
if (
typeof chrome === 'object' &&
typeof chrome.runtime === 'object' &&
typeof chrome.runtime.id === 'string' &&
typeof chrome.sockets === 'object' &&
typeof chrome.sockets.tcpServer === 'object' &&
typeof chrome.sockets.tcp === 'object'
) {
chrome.sockets.tcpServer.onAccept.addListener(onAccept)
chrome.sockets.tcpServer.onAcceptError.addListener(onAcceptError)
chrome.sockets.tcp.onReceive.addListener(onReceive)
chrome.sockets.tcp.onReceiveError.addListener(onReceiveError)
}
function onAccept (info) {
if (info.socketId in servers) {
servers[info.socketId]._onAccept(info.clientSocketId)
} else {
console.error('Unknown server socket id: ' + info.socketId)
}
}
function onAcceptError (info) {
if (info.socketId in servers) {
servers[info.socketId]._onAcceptError(info.resultCode)
} else {
console.error('Unknown server socket id: ' + info.socketId)
}
}
function onReceive (info) {
if (info.socketId in sockets) {
sockets[info.socketId]._onReceive(info.data)
} else {
console.error('Unknown socket id: ' + info.socketId)
}
}
function onReceiveError (info) {
if (info.socketId in sockets) {
sockets[info.socketId]._onReceiveError(info.resultCode)
} else {
if (info.resultCode === -100) return // net::ERR_CONNECTION_CLOSED
console.error('Unknown socket id: ' + info.socketId)
}
}
/**
* Creates a new TCP server. The connectionListener argument is automatically
* set as a listener for the 'connection' event.
*
* @param {Object} options
* @param {function} connectionListener
* @return {Server}
*/
exports.createServer = function (options, connectionListener) {
return new Server(options, connectionListener)
}
/**
* net.connect(options, [connectionListener])
* net.createConnection(options, [connectionListener])
*
* Constructs a new socket object and opens the socket to the given location.
* When the socket is established, the 'connect' event will be emitted.
*
* For TCP sockets, options argument should be an object which specifies:
*
* port: Port the client should connect to (Required).
* host: Host the client should connect to. Defaults to 'localhost'.
* localAddress: Local interface to bind to for network connections.
*
* ===============================================================
*
* net.connect(port, [host], [connectListener])
* net.createConnection(port, [host], [connectListener])
*
* Creates a TCP connection to port on host. If host is omitted,
* 'localhost' will be assumed. The connectListener parameter will be
* added as an listener for the 'connect' event.
*
* @param {Object} options
* @param {function} listener
* @return {Socket}
*/
exports.connect = exports.createConnection = function () {
const argsLen = arguments.length
var args = new Array(argsLen)
for (var i = 0; i < argsLen; i++) args[i] = arguments[i]
args = normalizeConnectArgs(args)
var s = new Socket(args[0])
return Socket.prototype.connect.apply(s, args)
}
inherits(Server, EventEmitter)
/**
* Class: net.Server
* =================
*
* This class is used to create a TCP server.
*
* Event: 'listening'
* Emitted when the server has been bound after calling server.listen.
*
* Event: 'connection'
* - Socket object The connection object
* Emitted when a new connection is made. socket is an instance of net.Socket.
*
* Event: 'close'
* Emitted when the server closes. Note that if connections exist, this event
* is not emitted until all connections are ended.
*
* Event: 'error'
* - Error Object
* Emitted when an error occurs. The 'close' event will be called directly
* following this event. See example in discussion of server.listen.
*/
function Server (options, connectionListener) {
if (!(this instanceof Server)) return new Server(options, connectionListener)
EventEmitter.call(this)
if (typeof options === 'function') {
connectionListener = options
options = {}
this.on('connection', connectionListener)
} else if (options == null || typeof options === 'object') {
options = options || {}
if (typeof connectionListener === 'function') {
this.on('connection', connectionListener)
}
} else {
throw new TypeError('options must be an object')
}
this._connections = 0
Object.defineProperty(this, 'connections', {
get: deprecate(() => this._connections,
'Server.connections property is deprecated. ' +
'Use Server.getConnections method instead.'),
set: deprecate((val) => (this._connections = val),
'Server.connections property is deprecated.'),
configurable: true,
enumerable: false
})
this.id = null // a number > 0
this.connecting = false
this.allowHalfOpen = options.allowHalfOpen || false
this.pauseOnConnect = !!options.pauseOnConnect
this._address = null
this._host = null
this._port = null
this._backlog = null
}
exports.Server = Server
Server.prototype._usingSlaves = false // not used
/**
* server.listen(port, [host], [backlog], [callback])
*
* Begin accepting connections on the specified port and host. If the host is
* omitted, the server will accept connections directed to any IPv4 address
* (INADDR_ANY). A port value of zero will assign a random port.
*
* Backlog is the maximum length of the queue of pending connections. The
* actual length will be determined by your OS through sysctl settings such as
* tcp_max_syn_backlog and somaxconn on linux. The default value of this
* parameter is 511 (not 512).
*
* This function is asynchronous. When the server has been bound, 'listening'
* event will be emitted. The last parameter callback will be added as an
* listener for the 'listening' event.
*
* @return {Socket}
*/
Server.prototype.listen = function (/* variable arguments... */) {
var lastArg = arguments[arguments.length - 1]
if (typeof lastArg === 'function') {
this.once('listening', lastArg)
}
var port = toNumber(arguments[0])
var address
// The third optional argument is the backlog size.
// When the ip is omitted it can be the second argument.
var backlog = toNumber(arguments[1]) || toNumber(arguments[2]) || undefined
if (arguments[0] !== null && typeof arguments[0] === 'object') {
var h = arguments[0]
if (h._handle || h.handle) {
throw new Error('handle is not supported in Chrome Apps.')
}
if (typeof h.fd === 'number' && h.fd >= 0) {
throw new Error('fd is not supported in Chrome Apps.')
}
// The first argument is a configuration object
if (h.backlog) {
backlog = h.backlog
}
if (typeof h.port === 'number' || typeof h.port === 'string' ||
(typeof h.port === 'undefined' && 'port' in h)) {
// Undefined is interpreted as zero (random port) for consistency
// with net.connect().
address = h.host || null
port = h.port
} else if (h.path && isPipeName(h.path)) {
throw new Error('Pipes are not supported in Chrome Apps.')
} else {
throw new Error('Invalid listen argument: ' + h)
}
} else if (isPipeName(arguments[0])) {
// UNIX socket or Windows pipe.
throw new Error('Pipes are not supported in Chrome Apps.')
} else if (arguments[1] === undefined ||
typeof arguments[1] === 'function' ||
typeof arguments[1] === 'number') {
// The first argument is the port, no IP given.
address = null
} else {
// The first argument is the port, the second an IP.
address = arguments[1]
}
// now do something with port, address, backlog
if (this.id) {
this.close()
}
// If port is invalid or undefined, bind to a random port.
assertPort(port)
this._port = port | 0
this._host = address
var isAny6 = !this._host
if (isAny6) {
this._host = '::'
}
this._backlog = typeof backlog === 'number' ? backlog : undefined
this.connecting = true
chrome.sockets.tcpServer.create((createInfo) => {
if (!this.connecting || this.id) {
ignoreLastError()
chrome.sockets.tcpServer.close(createInfo.socketId)
return
}
if (chrome.runtime.lastError) {
this.emit('error', new Error(chrome.runtime.lastError.message))
return
}
var socketId = this.id = createInfo.socketId
servers[this.id] = this
var listen = () => chrome.sockets.tcpServer.listen(this.id, this._host,
this._port, this._backlog,
(result) => {
// callback may be after close
if (this.id !== socketId) {
ignoreLastError()
return
}
if (result !== 0 && isAny6) {
ignoreLastError()
this._host = '0.0.0.0' // try IPv4
isAny6 = false
return listen()
}
this._onListen(result)
})
listen()
})
return this
}
Server.prototype._onListen = function (result) {
this.connecting = false
if (result === 0) {
var idBefore = this.id
chrome.sockets.tcpServer.getInfo(this.id, (info) => {
if (this.id !== idBefore) {
ignoreLastError()
return
}
if (chrome.runtime.lastError) {
this._onListen(-2) // net::ERR_FAILED
return
}
this._address = {
port: info.localPort,
family: info.localAddress &&
info.localAddress.indexOf(':') !== -1 ? 'IPv6' : 'IPv4',
address: info.localAddress
}
this.emit('listening')
})
} else {
this.emit('error', exceptionWithHostPort(result, 'listen', this._host, this._port))
if (this.id) {
chrome.sockets.tcpServer.close(this.id)
delete servers[this.id]
this.id = null
}
}
}
Server.prototype._onAccept = function (clientSocketId) {
// Set the `maxConnections` property to reject connections when the server's
// connection count gets high.
if (this.maxConnections && this._connections >= this.maxConnections) {
chrome.sockets.tcp.close(clientSocketId)
console.warn('Rejected connection - hit `maxConnections` limit')
return
}
this._connections += 1
var acceptedSocket = new Socket({
server: this,
id: clientSocketId,
allowHalfOpen: this.allowHalfOpen,
pauseOnCreate: this.pauseOnConnect
})
acceptedSocket.on('connect', () => this.emit('connection', acceptedSocket))
}
Server.prototype._onAcceptError = function (resultCode) {
this.emit('error', errnoException(resultCode, 'accept'))
this.close()
}
/**
* Stops the server from accepting new connections and keeps existing
* connections. This function is asynchronous, the server is finally closed
* when all connections are ended and the server emits a 'close' event.
* Optionally, you can pass a callback to listen for the 'close' event.
* @param {function} callback
*/
Server.prototype.close = function (callback) {
if (typeof callback === 'function') {
if (!this.id) {
this.once('close', () => callback(new Error('Not running')))
} else {
this.once('close', callback)
}
}
if (this.id) {
chrome.sockets.tcpServer.close(this.id)
delete servers[this.id]
this.id = null
}
this._address = null
this.connecting = false
this._emitCloseIfDrained()
return this
}
Server.prototype._emitCloseIfDrained = function () {
if (this.id || this.connecting || this._connections) {
return
}
process.nextTick(emitCloseNT, this)
}
function emitCloseNT (self) {
if (self.id || self.connecting || self._connections) {
return
}
self.emit('close')
}
Object.defineProperty(Server.prototype, 'listening', {
get: function () {
return !!this._address
},
configurable: true,
enumerable: true
})
/**
* Returns the bound address, the address family name and port of the socket
* as reported by the operating system. Returns an object with three
* properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }
*
* @return {Object} information
*/
Server.prototype.address = function () {
return this._address
}
Server.prototype.unref =
Server.prototype.ref = function () {
// No chrome.socket equivalent
return this
}
/**
* Asynchronously get the number of concurrent connections on the server.
* Works when sockets were sent to forks.
*
* Callback should take two arguments err and count.
*
* @param {function} callback
*/
Server.prototype.getConnections = function (callback) {
process.nextTick(callback, null, this._connections)
}
inherits(Socket, stream.Duplex)
/**
* Class: net.Socket
* =================
*
* This object is an abstraction of a TCP or UNIX socket. net.Socket instances
* implement a duplex Stream interface. They can be created by the user and
* used as a client (with connect()) or they can be created by Node and passed
* to the user through the 'connection' event of a server.
*
* Construct a new socket object.
*
* options is an object with the following defaults:
*
* { fd: null // NO CHROME EQUIVALENT
* type: null
* allowHalfOpen: false // NO CHROME EQUIVALENT
* }
*
* `type` can only be 'tcp4' (for now).
*
* Event: 'connect'
* Emitted when a socket connection is successfully established. See
* connect().
*
* Event: 'data'
* - Buffer object
* Emitted when data is received. The argument data will be a Buffer or
* String. Encoding of data is set by socket.setEncoding(). (See the Readable
* Stream section for more information.)
*
* Note that the data will be lost if there is no listener when a Socket
* emits a 'data' event.
*
* Event: 'end'
* Emitted when the other end of the socket sends a FIN packet.
*
* By default (allowHalfOpen == false) the socket will destroy its file
* descriptor once it has written out its pending write queue. However,
* by setting allowHalfOpen == true the socket will not automatically
* end() its side allowing the user to write arbitrary amounts of data,
* with the caveat that the user is required to end() their side now.
*
* Event: 'timeout'
* Emitted if the socket times out from inactivity. This is only to notify
* that the socket has been idle. The user must manually close the connection.
*
* See also: socket.setTimeout()
*
* Event: 'drain'
* Emitted when the write buffer becomes empty. Can be used to throttle
* uploads.
*
* See also: the return values of socket.write()
*
* Event: 'error'
* - Error object
* Emitted when an error occurs. The 'close' event will be called directly
* following this event.
*
* Event: 'close'
* - had_error Boolean true if the socket had a transmission error
* Emitted once the socket is fully closed. The argument had_error is a
* boolean which says if the socket was closed due to a transmission error.
*/
function Socket (options) {
if (!(this instanceof Socket)) return new Socket(options)
if (typeof options === 'number') {
options = { fd: options } // Legacy interface.
} else if (options === undefined) {
options = {}
}
if (options.handle) {
throw new Error('handle is not supported in Chrome Apps.')
} else if (options.fd !== undefined) {
throw new Error('fd is not supported in Chrome Apps.')
}
options.decodeStrings = true
options.objectMode = false
stream.Duplex.call(this, options)
this.destroyed = false
this._hadError = false // Used by _http_client.js
this.id = null // a number > 0
this._parent = null
this._host = null
this._port = null
this._pendingData = null
this.ondata = null
this.onend = null
this._init()
this._reset()
// default to *not* allowing half open sockets
// Note: this is not possible in Chrome Apps, see https://crbug.com/124952
this.allowHalfOpen = options.allowHalfOpen || false
// shut down the socket when we're finished with it.
this.on('finish', this.destroy)
if (options.server) {
this.server = this._server = options.server
this.id = options.id
sockets[this.id] = this
if (options.pauseOnCreate) {
// stop the handle from reading and pause the stream
// (Already paused in Chrome version)
this._readableState.flowing = false
}
// For incoming sockets (from server), it's already connected.
this.connecting = true
this.writable = true
this._onConnect()
}
}
exports.Socket = Socket
// called when creating new Socket, or when re-using a closed Socket
Socket.prototype._init = function () {
// The amount of received bytes.
this.bytesRead = 0
this._bytesDispatched = 0
// Reserve properties
this.server = null
this._server = null
}
// called when creating new Socket, or when closing a Socket
Socket.prototype._reset = function () {
this.remoteAddress = this.remotePort =
this.localAddress = this.localPort = null
this.remoteFamily = 'IPv4'
this.readable = this.writable = false
this.connecting = false
}
/**
* socket.connect(port, [host], [connectListener])
* socket.connect(options, [connectListener])
*
* Opens the connection for a given socket. If port and host are given, then
* the socket will be opened as a TCP socket, if host is omitted, localhost
* will be assumed. If a path is given, the socket will be opened as a unix
* socket to that path.
*
* Normally this method is not needed, as net.createConnection opens the
* socket. Use this only if you are implementing a custom Socket.
*
* This function is asynchronous. When the 'connect' event is emitted the
* socket is established. If there is a problem connecting, the 'connect'
* event will not be emitted, the 'error' event will be emitted with the
* exception.
*
* The connectListener parameter will be added as an listener for the
* 'connect' event.
*
* @param {Object} options
* @param {function} cb
* @return {Socket} this socket (for chaining)
*/
Socket.prototype.connect = function () {
const argsLen = arguments.length
var args = new Array(argsLen)
for (var i = 0; i < argsLen; i++) args[i] = arguments[i]
args = normalizeConnectArgs(args)
var options = args[0]
var cb = args[1]
if (options.path) {
throw new Error('Pipes are not supported in Chrome Apps.')
}
if (this.id) {
// already connected, destroy and connect again
this.destroy()
}
if (this.destroyed) {
this._readableState.reading = false
this._readableState.ended = false
this._readableState.endEmitted = false
this._writableState.ended = false
this._writableState.ending = false
this._writableState.finished = false
this._writableState.errorEmitted = false
this._writableState.length = 0
this.destroyed = false
}
this.connecting = true
this.writable = true
this._host = options.host || 'localhost'
this._port = options.port
if (typeof this._port !== 'undefined') {
if (typeof this._port !== 'number' && typeof this._port !== 'string') {
throw new TypeError('"port" option should be a number or string: ' + this._port)
}
if (!isLegalPort(this._port)) {
throw new RangeError('"port" option should be >= 0 and < 65536: ' + this._port)
}
}
this._port |= 0
this._init()
this._unrefTimer()
if (typeof cb === 'function') {
this.once('connect', cb)
}
chrome.sockets.tcp.create((createInfo) => {
if (!this.connecting || this.id) {
ignoreLastError()
chrome.sockets.tcp.close(createInfo.socketId)
return
}
if (chrome.runtime.lastError) {
this.destroy(new Error(chrome.runtime.lastError.message))
return
}
this.id = createInfo.socketId
sockets[this.id] = this
chrome.sockets.tcp.setPaused(this.id, true)
chrome.sockets.tcp.connect(this.id, this._host, this._port, (result) => {
// callback may come after call to destroy
if (this.id !== createInfo.socketId) {
ignoreLastError()
return
}
if (result !== 0) {
this.destroy(exceptionWithHostPort(result, 'connect', this._host, this._port))
return
}
this._unrefTimer()
this._onConnect()
})
})
return this
}
Socket.prototype._onConnect = function () {
var idBefore = this.id
chrome.sockets.tcp.getInfo(this.id, (result) => {
if (this.id !== idBefore) {
ignoreLastError()
return
}
if (chrome.runtime.lastError) {
this.destroy(new Error(chrome.runtime.lastError.message))
return
}
this.remoteAddress = result.peerAddress
this.remoteFamily = result.peerAddress &&
result.peerAddress.indexOf(':') !== -1 ? 'IPv6' : 'IPv4'
this.remotePort = result.peerPort
this.localAddress = result.localAddress
this.localPort = result.localPort
this.connecting = false
this.readable = true
this.emit('connect')
// start the first read, or get an immediate EOF.
// this doesn't actually consume any bytes, because len=0
if (!this.isPaused()) this.read(0)
})
}
/**
* The number of characters currently buffered to be written.
* @type {number}
*/
Object.defineProperty(Socket.prototype, 'bufferSize', {
get: function () {
if (this.id) {
var bytes = this._writableState.length
if (this._pendingData) bytes += this._pendingData.length
return bytes
}
}
})
Socket.prototype.end = function (data, encoding) {
stream.Duplex.prototype.end.call(this, data, encoding)
this.writable = false
}
Socket.prototype._write = function (chunk, encoding, callback) {
if (!callback) callback = () => {}
if (this.connecting) {
this._pendingData = chunk
this.once('connect', () => this._write(chunk, encoding, callback))
return
}
this._pendingData = null
if (!this.id) {
callback(new Error('This socket is closed'))
return
}
// assuming buffer is browser implementation (`buffer` package on npm)
var buffer = chunk.buffer
if (chunk.byteLength !== buffer.byteLength) {
buffer = buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength)
}
var idBefore = this.id
chrome.sockets.tcp.send(this.id, buffer, (sendInfo) => {
if (this.id !== idBefore) {
ignoreLastError()
return
}
if (sendInfo.resultCode < 0) {
this._destroy(exceptionWithHostPort(sendInfo.resultCode, 'write', this.remoteAddress, this.remotePort), callback)
} else {
this._unrefTimer()
callback(null)
}
})
this._bytesDispatched += chunk.length
}
Socket.prototype._read = function (bufferSize) {
if (this.connecting || !this.id) {
this.once('connect', () => this._read(bufferSize))
return
}
chrome.sockets.tcp.setPaused(this.id, false)
var idBefore = this.id
chrome.sockets.tcp.getInfo(this.id, (result) => {
if (this.id !== idBefore) {
ignoreLastError()
return
}
if (chrome.runtime.lastError || !result.connected) {
this._onReceiveError(-15) // workaround for https://crbug.com/518161
}
})
}
Socket.prototype._onReceive = function (data) {
var buffer = Buffer.from(data)
var offset = this.bytesRead
this.bytesRead += buffer.length
this._unrefTimer()
if (this.ondata) {
console.error('socket.ondata = func is non-standard, use socket.on(\'data\', func)')
this.ondata(buffer, offset, this.bytesRead)
}
if (!this.push(buffer)) { // if returns false, then apply backpressure
chrome.sockets.tcp.setPaused(this.id, true)
}
}
Socket.prototype._onReceiveError = function (resultCode) {
if (resultCode === -100) { // net::ERR_CONNECTION_CLOSED
if (this.onend) {
console.error('socket.onend = func is non-standard, use socket.on(\'end\', func)')
this.once('end', this.onend)
}
this.push(null)
this.destroy()
} else if (resultCode < 0) {
this.destroy(errnoException(resultCode, 'read'))
}
}
function protoGetter (name, callback) {
Object.defineProperty(Socket.prototype, name, {
configurable: false,
enumerable: true,
get: callback
})
}
/**
* The amount of bytes sent.
* @return {number}
*/
protoGetter('bytesWritten', function bytesWritten () {
if (this.id) return this._bytesDispatched + this.bufferSize
})
Socket.prototype.destroy = function (exception) {
this._destroy(exception)
}
Socket.prototype._destroy = function (exception, cb) {
var fireErrorCallbacks = () => {
if (cb) cb(exception)
if (exception && !this._writableState.errorEmitted) {
process.nextTick(emitErrorNT, this, exception)
this._writableState.errorEmitted = true
}
}
if (this.destroyed) {
// already destroyed, fire error callbacks
fireErrorCallbacks()
return
}
if (this._server) {
this._server._connections -= 1
if (this._server._emitCloseIfDrained) this._server._emitCloseIfDrained()
}
this._reset()
for (var s = this; s !== null; s = s._parent) timers.unenroll(s) // eslint-disable-line node/no-deprecated-api
this.destroyed = true
// If _destroy() has been called before chrome.sockets.tcp.create()
// callback, we don't have an id. Therefore we don't need to close
// or disconnect
if (this.id) {
delete sockets[this.id]
chrome.sockets.tcp.close(this.id, () => {
if (this.destroyed) {
this.emit('close', !!exception)
}
})
this.id = null
}
fireErrorCallbacks()
}
Socket.prototype.destroySoon = function () {
if (this.writable) this.end()
if (this._writableState.finished) this.destroy()
}
/**
* Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
* By default net.Socket do not have a timeout. When an idle timeout is triggered the
* socket will receive a 'timeout' event but the connection will not be severed. The
* user must manually end() or destroy() the socket.
*
* If timeout is 0, then the existing idle timeout is disabled.
*
* The optional callback parameter will be added as a one time listener for the 'timeout' event.
*
* @param {number} timeout
* @param {function} callback
*/
Socket.prototype.setTimeout = function (timeout, callback) {
if (timeout === 0) {
timers.unenroll(this) // eslint-disable-line node/no-deprecated-api
if (callback) {
this.removeListener('timeout', callback)
}
} else {
timers.enroll(this, timeout) // eslint-disable-line node/no-deprecated-api
timers._unrefActive(this)
if (callback) {
this.once('timeout', callback)
}
}
return this
}
Socket.prototype._onTimeout = function () {
this.emit('timeout')
}
Socket.prototype._unrefTimer = function unrefTimer () {
for (var s = this; s !== null; s = s._parent) {
timers._unrefActive(s)
}
}
/**
* Disables the Nagle algorithm. By default TCP connections use the Nagle
* algorithm, they buffer data before sending it off. Setting true for noDelay
* will immediately fire off data each time socket.write() is called. noDelay
* defaults to true.
*
* NOTE: The Chrome version of this function is async, whereas the node
* version is sync. Keep this in mind.
*
* @param {boolean} [noDelay] Optional
* @param {function} callback CHROME-SPECIFIC: Called when the configuration
* operation is done.
*/
Socket.prototype.setNoDelay = function (noDelay, callback) {
if (!this.id) {
this.once('connect', () => this.setNoDelay(noDelay, callback))
return this
}
// backwards compatibility: assume true when `noDelay` is omitted
noDelay = noDelay === undefined ? true : !!noDelay
chrome.sockets.tcp.setNoDelay(this.id, noDelay, chromeCallbackWrap(callback))
return this
}
/**
* Enable/disable keep-alive functionality, and optionally set the initial
* delay before the first keepalive probe is sent on an idle socket. enable
* defaults to false.
*
* Set initialDelay (in milliseconds) to set the delay between the last data
* packet received and the first keepalive probe. Setting 0 for initialDelay
* will leave the value unchanged from the default (or previous) setting.
* Defaults to 0.
*
* NOTE: The Chrome version of this function is async, whereas the node
* version is sync. Keep this in mind.
*
* @param {boolean} [enable] Optional
* @param {number} [initialDelay]
* @param {function} callback CHROME-SPECIFIC: Called when the configuration