-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.tcpsocket.js
664 lines (628 loc) · 20.1 KB
/
core.tcpsocket.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
/*globals chrome,fdom:true,console,Promise*/
/*jslint indent:2,white:true,sloppy:true */
/**
* A freedom.js interface to Chrome sockets
* @constructor
* @private
* @param {} cap Capabilities for the provider
* @param {Function} dispatchEvent Method for emitting events.
* @param {number?} id A pre-existing socket Id for the socket.
*/
var Socket_chrome = function(cap, dispatchEvent, id) {
this.dispatchEvent = dispatchEvent;
this.id = id || undefined;
this.namespace = chrome.sockets.tcp;
this.prepareSecureCalled = false;
this.closingId = undefined;
if (this.hasId()) {
Socket_chrome.addActive(this);
chrome.sockets.tcp.setPaused(this.id, false);
}
};
/**
* @private
* @return {boolean}
*/
Socket_chrome.prototype.hasId = function() {
return typeof this.id === 'number';
};
/**
* A static list of active sockets, so that global on-receive messages
* from chrome can be routed properly.
* @static
* @private
* @type {Object.<string,Socket_chrome>}
* @see Socket_chrome.keyForActive
*/
Socket_chrome.active = {};
/**
* Get Information about the socket.
* @method getInfo
* @param {Function} continuation Function to call with information.
* @return {Object} connection and address information about the socket.
*/
Socket_chrome.prototype.getInfo = function(continuation) {
if (this.hasId()) {
// Note: this.namespace used, since this method is common to tcp and
// tcpServer sockets.
this.namespace.getInfo(this.id, function(info) {
// This can happen if the socket is disconnected
// before the callback is invoked.
if (chrome.runtime.lastError) {
continuation({
connected: false
});
} else {
continuation(info);
}
});
} else {
continuation({
connected: false
});
}
};
/**
* Connect to a designated location and begin reading.
* @method connect
* @param {String} hostname The host or ip to connect to.
* @param {number} port The port to connect on.
* @param {Function} cb Function to call with completion or error.
*/
Socket_chrome.prototype.connect = function(hostname, port, cb) {
if (this.hasId()) {
cb(undefined, {
'errcode': 'ALREADY_CONNECTED',
'message': 'Cannot Connect Existing Socket'
});
return;
}
chrome.sockets.tcp.create({'bufferSize' : 1024 * 16}, function(createInfo) {
this.afterCreate_(hostname, port, createInfo, cb);
}.bind(this));
};
/**
* Next steps after chrome.sockets.tcp.create returns
* @method afterCreate_
* @private
* @param {String} hostname The host or ip to connect to.
* @param {number} port The port to connect on.
* @param {Object} createInfo The return value of sockets.tcp.create.
* @param {Function} cb Function to call with completion or error.
*/
Socket_chrome.prototype.afterCreate_ = function(hostname, port, createInfo, cb) {
this.id = createInfo.socketId;
if (this.prepareSecureCalled) {
try {
chrome.sockets.tcp.setPaused(this.id, true,
this.connectInternal_.bind(this, hostname, port, cb));
} catch (e) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'Failed to pause before connecting: ' + e.message
});
}
} else {
this.connectInternal_(hostname, port, cb);
}
};
/**
* Connect to a designated location after a socket is created and prepared.
* @method connectInternal_
* @param {String} hostname The host or ip to connect to.
* @param {number} port The port to connect on.
* @param {Function} cb Function to call with completion or error.
*/
Socket_chrome.prototype.connectInternal_ = function(hostname, port, cb) {
try {
chrome.sockets.tcp.connect(this.id, hostname, port, function(result) {
var error = Socket_chrome.chromeErrorHandler(result);
if (error) {
cb(undefined, error);
} else {
Socket_chrome.addActive(this);
cb();
}
}.bind(this));
} catch (e) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'Chrome Connection Failed: ' + e.message
});
}
};
/**
* Secure an already connected socket.
* @method secure
* @param {Function} cb Function to call with completion or error.
*/
Socket_chrome.prototype.secure = function(cb) {
if (!this.hasId()) {
cb(undefined, {
'errcode': 'NOT_CONNECTED',
'message': 'Cannot secure a disconnected socket'
});
return;
} else if (!this.prepareSecureCalled) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'prepareSecure not called before secure'
});
return;
} else if (!chrome.sockets.tcp.secure) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'Secure method not available'
});
return;
}
chrome.sockets.tcp.secure(this.id, {}, function(secureResult) {
// Always resume the socket, regardless of whether .secure succeeds.
this.resume(function(ret, error) {
if (secureResult !== 0) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'Secure failed: ' + secureResult + ': ' +
Socket_chrome.ERROR_MAP[secureResult]
});
return;
}
if (error) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'Secure failed: error unpausing socket: ' +
error.message
});
return;
}
cb();
}.bind(this));
}.bind(this));
};
/**
* Prepares a socket for becoming secure after the next read event.
* See details at
* https://github.com/freedomjs/freedom/wiki/prepareSecure-API-Usage
* @method prepareSecure
* @param {Function} cb Function to call with completion or error.
*/
Socket_chrome.prototype.prepareSecure = function(cb) {
if (!this.hasId()) {
// ::connect will check this flag and pause the socket before
// creating it.
this.prepareSecureCalled = true;
cb();
return;
}
this.pause(function(ret, error) {
if (error) {
cb(undefined, {
'errcode': 'CONNECTION_FAILED',
'message': 'prepareSecure failed: error pausing socket: ' +
error.message
});
return;
}
this.prepareSecureCalled = true;
cb();
}.bind(this));
};
/**
* Pauses the socket
* @method pause
* @param {Function} cb Function to call when the pause command is executed.
*/
Socket_chrome.prototype.pause = function(cb) {
if (!this.id) {
cb(undefined, {
'errcode': 'UNKNOWN',
'message': 'Cannot pause disconnected socket'
});
return;
}
chrome.sockets.tcp.setPaused(this.id, true, cb);
};
/**
* Unpauses the socket
* @method resume
* @returns {Promise} Promise to be fulfilled on resume.
*/
Socket_chrome.prototype.resume = function(cb) {
if (!this.hasId()) {
cb(undefined, {
'errcode': 'UNKNOWN',
'message': 'Cannot resume disconnected socket'
});
return;
}
chrome.sockets.tcp.setPaused(this.id, false, cb);
};
/**
* Write data to the socket.
* @method write
* @param {ArrayBuffer} data The data to write
* @param {Function} cb Function to call when data is written
*/
Socket_chrome.prototype.write = function(data, cb) {
if (!this.hasId()) {
cb(undefined, {
'errcode': 'NOT_CONNECTED',
'message': 'Cannot Write on Closed Socket'
});
return;
}
chrome.sockets.tcp.send(this.id, data, function(sendInfo) {
// This will happen when the send callback is invoked after the socket
// has closed but before the dispatchDisconnect has been invoked.
if (chrome.runtime.lastError) {
this.dispatchDisconnect();
return cb(undefined, {
'errcode': 'NOT_CONNECTED',
'message': 'Cannot Write on Closed Socket: ' +
chrome.runtime.lastError.message
});
}
if (sendInfo.resultCode < 0) {
var errorObject = this.dispatchDisconnect(sendInfo.resultCode);
return cb(undefined, {
'errcode': errorObject.errcode,
'message': 'Send Error: ' + errorObject.message
});
} else if (sendInfo.bytesSent !== data.byteLength) {
this.dispatchDisconnect();
return cb(undefined, {
'errcode': 'UNKNOWN',
'message': 'Write Partially completed.'
});
}
cb();
}.bind(this));
};
Socket_chrome.ERROR_MAP = {
'0': 'SUCCESS',
// Error codes are at:
// https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h
'-1': 'IO_PENDING',
'-2': 'FAILED',
'-3': 'ABORTED',
'-4': 'INVALID_ARGUMENT',
'-5': 'INVALID_HANDLE',
'-7': 'TIMED_OUT',
'-13': 'OUT_OF_MEMORY',
'-15': 'SOCKET_NOT_CONNECTED',
'-21': 'NETWORK_CHANGED',
'-23': 'SOCKET_IS_CONNECTED',
'-100': 'CONNECTION_CLOSED',
'-101': 'CONNECTION_RESET',
'-102': 'CONNECTION_REFUSED',
'-103': 'CONNECTION_ABORTED',
'-104': 'CONNECTION_FAILED',
'-105': 'NAME_NOT_RESOLVED',
'-106': 'INTERNET_DISCONNECTED',
'-107': 'SSL_PROTOCOL_ERROR',
'-108': 'ADDRESS_INVALID',
'-109': 'ADDRESS_UNREACHABLE',
'-118': 'CONNECTION_TIMED_OUT',
'-121': 'SOCKS_CONNECTION_HOST_UNREACHABLE',
'-200': 'CERT_COMMON_NAME_INVALID',
// See Cordova Plugin socket.js
'-1000': 'GENERIC_CORDOVA_FAILURE'
};
// Map from names in the Chrome error map to corresponding Freedom error codes.
Socket_chrome.FREEDOM_ERROR_MAP = {
'SUCCESS': 'SUCCESS',
'INVALID_ARGUMENT': 'INVALID_ARGUMENT',
'TIMED_OUT': 'TIMED_OUT',
'NETWORK_CHANGED': 'NETWORK_CHANGED',
'SOCKET_NOT_CONNECTED': 'NOT_CONNECTED',
'CONNECTION_CLOSED': 'CONNECTION_CLOSED',
'CONNECTION_RESET': 'CONNECTION_RESET',
'CONNECTION_REFUSED': 'CONNECTION_REFUSED',
'CONNECTION_FAILED': 'CONNECTION_FAILED',
'NAME_NOT_RESOLVED': 'NAME_NOT_RESOLVED',
'INTERNET_DISCONNECTED': 'INTERNET_DISCONNECTED',
'ADDRESS_INVALID': 'ADDRESS_INVALID',
'ADDRESS_UNREACHABLE': 'ADDRESS_UNREACHABLE',
'CONNECTION_TIMED_OUT': 'TIMED_OUT',
'SOCKETS_CONNECTION_HOST_UNREACHABLE': 'HOST_UNREACHABLE',
'UNKNOWN': 'UNKNOWN'
};
/**
* Get the Chrome error string associated with a chrome.socket error code.
* @method errorStringOfCode
* @static
* @private
* @param {Number=} code The error number as described by Chrome
* @returns {String} The error code as defined in the freedom.js interface.
*/
Socket_chrome.errorStringOfCode = function(code) {
return Socket_chrome.ERROR_MAP[String(code)] ||
'UNKNOWN';
};
/**
* Get the Freedom error code associated with a Chrome error string
* @method freedomErrorCode
* @static
* @private
* @param {String=} errorString The Chrome error string
* @return {String} The corresponding Freedom error string (often identical).
*/
Socket_chrome.freedomErrorCode = function(errorString) {
return Socket_chrome.FREEDOM_ERROR_MAP[errorString] || 'UNKNOWN';
};
/**
* Return an error object appropriate for a given Chrome socket result code
* @method chromeErrorHandler
* @static
* @private
* @param {Number=} code The error number as described by Chrome
* @returns {Object} An error object (w/errcode and message fields) or nothing
*/
Socket_chrome.chromeErrorHandler = function(code) {
if (code < 0 || chrome.runtime.lastError) {
var errorString = Socket_chrome.errorStringOfCode(code);
var freedomErrorCode = Socket_chrome.freedomErrorCode(errorString);
return({
'errcode': freedomErrorCode,
'message': 'Chrome Connection Failed: ' + errorString +
' ' + chrome.runtime.lastError.message
});
}
};
/*
* Alert a consumer that a socket is disconnected, with appropriate
* error message.
* @method dispatchDisconnect
* @private
* @param {Number=} code the code returned by chrome when the socket closed.
* @return {{errorcode: string, message: string}} Error JSON object.
*/
Socket_chrome.prototype.dispatchDisconnect = function (code) {
var errorString = Socket_chrome.errorStringOfCode(code);
var freedomErrorCode = Socket_chrome.freedomErrorCode(errorString);
/** @type {string} */ var errorMessage;
if (freedomErrorCode === 'SUCCESS') {
errorMessage = 'Socket closed by call to close';
} else if(freedomErrorCode === 'CONNECTION_CLOSED') {
errorMessage = 'Connection closed gracefully';
} else {
errorMessage = 'Socket Error: ' + code + ': ' + errorString;
}
var errorObject = {
'errcode': freedomErrorCode,
'message': errorMessage
};
// Don't send more than one dispatchDisconnect event.
if (this.hasId()) {
// Every socket must be explicitly closed, even if it has already been
// disconnected, to avoid a memory leak.
this.namespace.close(this.id, function() {
if (chrome.runtime.lastError) {
// https://github.com/freedomjs/freedom-for-chrome/issues/90
console.log("Ignoring runtime.lastError, socket is closed");
}
});
Socket_chrome.removeActive(this.id);
delete this.id;
this.dispatchEvent('onDisconnect', errorObject);
}
return errorObject;
};
/**
* Generates an index key for {@Socket_chrome.active}.
* The key is a string with the format 'type.id', where type is 'client' if
* this is a client socket or 'server' if this is a server socket and id is
* the socket ID.
* @method keyForActive
* @private
* @param {Object} namespace Socket namespace, indicating client or server socket.
* @param {number} id The socketId, as provided by chrome.sockets.
* @static
* @see Socket_chrome.active
*/
Socket_chrome.keyForActive = function(namespace, id) {
return (namespace === chrome.sockets.tcp ? 'client' : 'socket') + '.' + id;
};
/**
* Mark a socket as active, so that dispatched events can be routed to it.
* This method is needed because chrome.sockets exposes a single event handler
* for incoming data across all sockets.
* @method addActive
* @static
* @param {Socket_chrome} socket The socket class associated with the id.
*/
Socket_chrome.addActive = function(socket) {
if (Object.keys(Socket_chrome.active).length === 0) {
if (chrome.sockets.tcp) {
chrome.sockets.tcp.onReceive.addListener(Socket_chrome.handleReadData);
chrome.sockets.tcp.onReceiveError.addListener(
Socket_chrome.handleReadError);
}
if (chrome.sockets.tcpServer) {
chrome.sockets.tcpServer.onAccept.addListener(
Socket_chrome.handleAccept);
chrome.sockets.tcpServer.onAcceptError.addListener(
Socket_chrome.handleAcceptError);
}
}
Socket_chrome.active[Socket_chrome.keyForActive(
socket.namespace, socket.id)] = socket;
};
/**
* Unmark a socket as active, and clean up event handlers if needed.
* @method removeActive
* @static
* @param {Socket_chrome} socket The socket class associated with the id.
*/
Socket_chrome.removeActive = function(socket) {
delete Socket_chrome.active[Socket_chrome.keyForActive(
socket.namespace, socket.id)];
if (Object.keys(Socket_chrome.active).length === 0) {
if (chrome.sockets.tcp) {
chrome.sockets.tcp.onReceive.removeListener(
Socket_chrome.handleReadData);
chrome.sockets.tcp.onReceiveError.removeListener(
Socket_chrome.handleReadError);
}
if (chrome.sockets.tcpServer) {
chrome.sockets.tcpServer.onAccept.removeListener(
Socket_chrome.handleAccept);
chrome.sockets.tcpServer.onAcceptError.removeListener(
Socket_chrome.handleAcceptError);
}
}
};
/**
* React to read data.
* @method handleReadData
* @private
* @param {ReadInfo} readInfo The value returned by onReceive.
* @static
*/
Socket_chrome.handleReadData = function (readInfo) {
var key = Socket_chrome.keyForActive(chrome.sockets.tcp, readInfo.socketId);
if (!(key in Socket_chrome.active)) {
console.warn('Dropped Read: ', readInfo);
return;
}
Socket_chrome.active[key].dispatchEvent('onData', {data: readInfo.data});
};
/**
* React to read errors.
* @method handleReadError
* @private
* @param {readInfo} readInfo The value returned by onReceiveError.
* @static
*/
Socket_chrome.handleReadError = function (readInfo) {
var key = Socket_chrome.keyForActive(chrome.sockets.tcp, readInfo.socketId);
if (!(key in Socket_chrome.active)) {
console.warn('Dropped Read Error: ', readInfo);
return;
}
if (readInfo.resultCode === -100 &&
readInfo.socketId === Socket_chrome.active[key].closingId) {
console.log("Overriding CONNECTION_CLOSED with SUCCESS");
// Hack to deal with unhandled runtime.lastError
// https://github.com/freedomjs/freedom-for-chrome/issues/90
readInfo.resultCode = 0; // replace CONNECTION_CLOSED with SUCCESS
}
Socket_chrome.active[key].dispatchDisconnect(readInfo.resultCode);
};
/**
* React to client accepts.
* @method handleAccept
* @private
* @param {acceptInfo} acceptInfo The value returned by onAccept.
* @static
*/
Socket_chrome.handleAccept = function (acceptInfo) {
var key = Socket_chrome.keyForActive(chrome.sockets.tcpServer,
acceptInfo.socketId);
if (!(key in Socket_chrome.active)) {
console.warn('Dropped Accept: ', acceptInfo);
return;
}
chrome.sockets.tcp.getInfo(acceptInfo.clientSocketId, function(info) {
Socket_chrome.active[key].dispatchEvent('onConnection', {
socket: acceptInfo.clientSocketId,
host: info.peerAddress,
port: info.peerPort
});
});
};
/**
* React to client accept errors.
* @method handleAcceptError
* @private
* @param {acceptInfo} acceptInfo The value returned by onAcceptError.
* @static
*/
Socket_chrome.handleAcceptError = function (acceptInfo) {
var error = Socket_chrome.chromeErrorHandler(acceptInfo.resultCode);
if (error) {
console.error(error.errcode, error.message);
} else {
var key = Socket_chrome.keyForActive(chrome.sockets.tcpServer,
acceptInfo.socketId);
if (!(key in Socket_chrome.active)) {
console.warn('Dropped Accept Error: ', info);
return;
}
Socket_chrome.active[key].dispatchDisconnect(acceptInfo.resultCode);
}
};
/**
* Listen on a socket to accept new clients.
* @method listen
* @param {String} address the address to listen on
* @param {number} port the port to listen on
* @param {Function} callback Callback to call when listening has occured.
*/
Socket_chrome.prototype.listen = function(address, port, callback) {
if (this.hasId()) {
callback(undefined, {
errcode: 'ALREADY_CONNECTED',
message: 'Cannot Listen on existing socket.'
});
return;
}
this.namespace = chrome.sockets.tcpServer;
chrome.sockets.tcpServer.create({}, function(createInfo) {
this.id = createInfo.socketId;
// See https://developer.chrome.com/apps/socket#method-listen
chrome.sockets.tcpServer.listen(
this.id, address, port,
// TODO: find out what the default is, and what this really means, the
// webpage is pretty sparse on it:
// https://developer.chrome.com/apps/socket#method-listen
//
// Length of the socket's listen queue (number of pending connections
// to open)
100,
this.startAcceptLoop.bind(this, callback));
}.bind(this));
};
/**
* @method startAcceptLoop
* @param {Function} callbackFromListen Resolves Freedom's promise for
* |this.listen|
* @param {number} result The argument |result| comes from the callback in
* |chrome.socket.listen|. Its value is a number that represents a chrome
* socket error, as specified in:
* https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h
* @private
*/
Socket_chrome.prototype.startAcceptLoop = function(callbackFromListen, result) {
var error = Socket_chrome.chromeErrorHandler(result);
if (error) {
callbackFromListen(undefined, error);
} else {
callbackFromListen();
Socket_chrome.addActive(this);
}
};
/**
* Close and Destroy a socket
* @method close
* @param {Function} continuation Function to call once socket is destroyed.
*/
Socket_chrome.prototype.close = function(continuation) {
if (this.hasId()) {
// Note: this.namespace used, since this method is common to tcp and
// tcpServer sockets.
this.closingId = this.id; // to ensure dispatching correct close msg
this.namespace.close(this.id, function() {
this.dispatchDisconnect(0);
continuation();
}.bind(this));
} else {
continuation(undefined, {
'errcode': 'SOCKET_CLOSED',
'message': 'Socket Already Closed, or was never opened'
});
}
};
/** REGISTER PROVIDER **/
exports.provider = Socket_chrome;
exports.name = 'core.tcpsocket';