Improved some websocket error handling.
Ylian Saint-Hilaire committed
Jan 2, 2019 at 18:34 UTC
7873bbba3f0e299ca90111ab66f90bc366849a62
10 files changed
+45
-37
agents/meshcmd.js
+11
-11
@@ -271,7 +271,7 @@ function run(argv) {
271
SMBiosTables.get(function (data) {
272
var r = SMBiosTables.parse(data);
273
var out = objToString(r, 0, '\r\n');
274
- if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
274
+ if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, Buffer.from(out, 'utf8')); fs.closeSync(file); }
275
exit(1);
276
});
277
} else if (settings.action == 'rawsmbios') {
@@ -280,7 +280,7 @@ function run(argv) {
280
SMBiosTables.get(function (data) {
281
var out = '';
282
for (var i in data) { var header = false; for (var j in data[i]) { if (data[i][j].length > 0) { if (header == false) { out += ('Table type #' + i + ((SMBiosTables.smTableTypes[i] == null) ? '' : (', ' + SMBiosTables.smTableTypes[i]))) + '\r\n'; header = true; } out += (' ' + data[i][j].toString('hex')) + '\r\n'; } } }
283
- if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
283
+ if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, Buffer.from(out, 'utf8')); fs.closeSync(file); }
284
exit(1);
285
});
286
} else if (settings.action == 'route') {
@@ -568,7 +568,7 @@ function readAmtAuditLogEx2(stack, response, status) {
568
var name = ((response[i].Initiator != '') ? (response[i].Initiator + ': ') : '')
569
out += (response[i].Time + ' - ' + name + response[i].Event + '\r\n');
570
}
571
- if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
571
+ if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, Buffer.from(out, 'utf8')); fs.closeSync(file); }
572
}
573
exit(1);
574
}
@@ -802,7 +802,7 @@ function saveEntireAmtStateOk4(stack, messages, tag, status) { if (status == 600
802
function saveEntireAmtStateDone() {
803
if (--IntelAmtEntireStateCalls != 0) return;
804
var out = fs.openSync(settings.output, 'w');
805
- fs.writeSync(out, new Buffer(JSON.stringify(IntelAmtEntireState), 'utf8'));
805
+ fs.writeSync(out, Buffer.from(JSON.stringify(IntelAmtEntireState), 'utf8'));
806
fs.closeSync(out);
807
console.log('Done, results written to ' + settings.output + '.');
808
exit(1);
@@ -1187,7 +1187,7 @@ function kvmCtrlData(channel, cmd) {
1187
// Send the next download block(s)
1188
while (sendNextBlock > 0) {
1189
sendNextBlock--;
1190
- var buf = new Buffer(4096);
1190
+ var buf = Buffer.alloc(4096);
1191
var len = fs.readSync(this.filedownload.f, buf, 4, 4092, null);
1192
this.filedownload.ptr += len;
1193
if (len < 4092) { buf.writeInt32BE(0x01000001, 0); fs.closeSync(this.filedownload.f); delete this.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
@@ -1280,19 +1280,19 @@ function processLmsControlData(data) {
1280
case 1: // Request basic Intel AMT information (CMD = 1)
1281
{ getAmtInfo(function (meinfo, socket) { meinfo.LoginMode = 2; socket.write(Buffer.concat([Buffer.from('0100', 'hex'), Buffer.from(JSON.stringify(meinfo))])); }, this); break; }
1282
case 2: // Intel AMT MEI Unprovision (CMD = 2)
1283
- { if (data.length < 6) break; amtMei.unprovision(data.readUInt32LE(2), function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(2, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1283
+ { if (data.length < 6) break; amtMei.unprovision(data.readUInt32LE(2), function (status, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(2, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1284
case 3: // Intel AMT MEI GetLocalSystemAccount (CMD = 3)
1285
{ amtMei.getLocalSystemAccount(function (account, socket) { socket.write(Buffer.concat([Buffer.from('030000000000', 'hex'), account.raw])); }, this); break; }
1286
case 4: // Instruct Intel AMT to start remote configuration (CMD = 4)
1287
- { amtMei.startConfiguration(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1287
+ { amtMei.startConfiguration(function (status, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1288
case 5: // Instruct Intel AMT to stop remote configuration (CMD = 5)
1289
- { amtMei.stopConfiguration(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1289
+ { amtMei.stopConfiguration(function (status, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1290
case 6: // Instruct Intel AMT connect CIRA (CMD = 6)
1291
- { amtMei.openUserInitiatedConnection(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1291
+ { amtMei.openUserInitiatedConnection(function (status, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1292
case 7: // Instruct Intel AMT disconnect CIRA (CMD = 7)
1293
- { amtMei.closeUserInitiatedConnection(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1293
+ { amtMei.closeUserInitiatedConnection(function (status, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
1294
case 8: // Get Intel AMT CIRA State (CMD = 8)
1295
- { amtMei.getRemoteAccessConnectionStatus(function (state, socket) { var data = new Buffer(6); data.writeUInt16LE(8, 0); data.writeUInt32LE(state.status, 2); socket.write(Buffer.concat([data, state.raw])); }, this); break; }
1295
+ { amtMei.getRemoteAccessConnectionStatus(function (state, socket) { var data = Buffer.alloc(6); data.writeUInt16LE(8, 0); data.writeUInt32LE(state.status, 2); socket.write(Buffer.concat([data, state.raw])); }, this); break; }
1296
}
1297
}
1298
agents/meshcore.js
+2
-2
@@ -1220,7 +1220,7 @@ function createMeshCore(agent) {
1220
var max = 4096;
1221
if ((args['_'].length > 1) && (typeof args['_'][1] == 'number')) { max = args['_'][1]; }
1222
if (max > 4096) max = 4096;
1223
- var buf = new Buffer(max), fd = fs.openSync(args['_'][0], "r"), r = fs.readSync(fd, buf, 0, max); // Read the file content
1223
+ var buf = Buffer.alloc(max), fd = fs.openSync(args['_'][0], "r"), r = fs.readSync(fd, buf, 0, max); // Read the file content
1224
response = buf.toString();
1225
var i = response.indexOf('\n');
1226
if ((i > 0) && (response[i - 1] != '\r')) { response = response.split('\n').join('\r\n'); }
@@ -1843,7 +1843,7 @@ function createMeshCore(agent) {
1843
// Send the next download block(s)
1844
while (sendNextBlock > 0) {
1845
sendNextBlock--;
1846
- var buf = new Buffer(4096);
1846
+ var buf = Buffer.alloc(4096);
1847
var len = fs.readSync(this.filedownload.f, buf, 4, 4092, null);
1848
this.filedownload.ptr += len;
1849
if (len < 4092) { buf.writeInt32BE(0x01000001, 0); fs.closeSync(this.filedownload.f); delete this.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
agents/modules_meshcmd/amt-mei.js
+2
-2
@@ -256,7 +256,7 @@ function amt_heci() {
256
var optional = [];
257
for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
258
259
- var data = new Buffer(4);
259
+ var data = Buffer.alloc(4);
260
data.writeUInt32LE(handle, 0);
261
262
this.sendCommand(0x2D, data, function (header, fn, opt) {
@@ -356,7 +356,7 @@ function amt_heci() {
356
this.unprovision = function unprovision(mode, callback) {
357
var optional = [];
358
for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
359
- var data = new Buffer(4);
359
+ var data = Buffer.alloc(4);
360
data.writeUInt32LE(mode, 0);
361
this.sendCommand(16, data, function (header, fn, opt) {
362
opt.unshift(header.Status);
agents/modules_meshcmd/amt.js
+1
-1
@@ -729,7 +729,7 @@ function AmtStackCreateService(wsmanStack) {
729
e = null;
730
try {
731
es = atob(responses.Body['EventRecords'][i]);
732
- e = new Buffer(es);
732
+ e = Buffer.from(es);
733
} catch (ex) {
734
console.log(ex + " " + responses.Body['EventRecords'][i])
735
}
agents/modules_meshcore/amt-mei.js
+2
-2
@@ -256,7 +256,7 @@ function amt_heci() {
256
var optional = [];
257
for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
258
259
- var data = new Buffer(4);
259
+ var data = Buffer.alloc(4);
260
data.writeUInt32LE(handle, 0);
261
262
this.sendCommand(0x2D, data, function (header, fn, opt) {
@@ -356,7 +356,7 @@ function amt_heci() {
356
this.unprovision = function unprovision(mode, callback) {
357
var optional = [];
358
for (var i = 2; i < arguments.length; ++i) { optional.push(arguments[i]); }
359
- var data = new Buffer(4);
359
+ var data = Buffer.alloc(4);
360
data.writeUInt32LE(mode, 0);
361
this.sendCommand(16, data, function (header, fn, opt) {
362
opt.unshift(header.Status);
agents/modules_meshcore/amt.js
+1
-1
@@ -729,7 +729,7 @@ function AmtStackCreateService(wsmanStack) {
729
e = null;
730
try {
731
es = atob(responses.Body['EventRecords'][i]);
732
- e = new Buffer(es);
732
+ e = Buffer.from(es);
733
} catch (ex) {
734
console.log(ex + " " + responses.Body['EventRecords'][i])
735
}
meshagent.js
+1
-1
@@ -229,7 +229,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
229
obj.send(obj.common.ShortToStr(1) + msg.substring(2, 50) + obj.nonce); // Command 1, hash + nonce. Use the web hash given by the agent.
230
} else {
231
// Check that the server hash matches our own web certificate hash (SHA384)
232
- if ((getWebCertHash(obj.domain) != msg.substring(2, 50)) && (getWebCertFullHash(obj.domain) != msg.substring(2, 50))) { console.log('Agent bad web cert hash (Agent:' + (Buffer.from(msg.substring(2, 50), 'binary').toString('hex').substring(0, 10)) + ' != Server:' + (new Buffer(getWebCertHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + ' or ' + (new Buffer(getWebCertFullHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + '), holding connection (' + obj.remoteaddrport + ').'); return; }
232
+ if ((getWebCertHash(obj.domain) != msg.substring(2, 50)) && (getWebCertFullHash(obj.domain) != msg.substring(2, 50))) { console.log('Agent bad web cert hash (Agent:' + (Buffer.from(msg.substring(2, 50), 'binary').toString('hex').substring(0, 10)) + ' != Server:' + (Buffer.from(getWebCertHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + ' or ' + (new Buffer(getWebCertFullHash(obj.domain), 'binary').toString('hex').substring(0, 10)) + '), holding connection (' + obj.remoteaddrport + ').'); return; }
233
}
234
235
// Use our server private key to sign the ServerHash + AgentNonce + ServerNonce
meshrelay.js
+2
-2
@@ -191,13 +191,13 @@ module.exports.CreateMeshRelay = function (parent, ws, req, domain, user, cookie
191
}
192
});
193
194
- // If error, do nothing.
194
+ // If error, close both sides of the relay.
195
ws.on('error', function (err) {
196
console.log('Relay error from ' + obj.remoteaddr + ', ' + err.toString().split('\r')[0] + '.');
197
closeBothSides();
198
});
199
200
- // If the mesh relay web socket is closed.
200
+ // If the relay web socket is closed, close both sides.
201
ws.on('close', function (req) {
202
closeBothSides();
203
});
redirserver.js
+2
-2
@@ -98,7 +98,7 @@ module.exports.CreateRedirServer = function (parent, db, args, func) {
98
function CheckListenPort(port, func) {
99
var s = obj.net.createServer(function (socket) { });
100
obj.tcpServer = s.listen(port, function () { s.close(function () { if (func) { func(port); } }); }).on("error", function (err) {
101
- if (args.exactports) { console.error("ERROR: MeshCentral HTTP web server port " + port + " not available."); process.exit(); }
101
+ if (args.exactports) { console.error("ERROR: MeshCentral HTTP server port " + port + " not available."); process.exit(); }
102
else { if (port < 65535) { CheckListenPort(port + 1, func); } else { if (func) { func(0); } } }
103
});
104
}
@@ -108,7 +108,7 @@ module.exports.CreateRedirServer = function (parent, db, args, func) {
108
if (port == 0 || port == 65535) { return; }
109
obj.tcpServer = obj.app.listen(port, function () {
110
obj.port = port;
111
- console.log("MeshCentral HTTP redirection web server running on port " + port + ".");
111
+ console.log("MeshCentral HTTP redirection server running on port " + port + ".");
112
obj.parent.updateServerState("redirect-port", port);
113
func(obj.port);
114
}).on("error", function (err) {
webserver.js
+21
-13
@@ -40,7 +40,7 @@ function SerialTunnel(options) {
40
if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; }
41
if (!String.prototype.endsWith) { String.prototype.endsWith = function (searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.lastIndexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; }
42
43
-// Construct a HTTP web server object
43
+// Construct a HTTP server object
44
module.exports.CreateWebServer = function (parent, db, args, certificates) {
45
var obj = {}, i = 0;
46
@@ -1263,8 +1263,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1263
if (ws.forwardclient.xtls == 1) { ws.forwardclient.write(Buffer.from(msg, 'binary')); } else { ws.forwardclient.write(msg); }
1264
});
1265
1266
- // If error, do nothing
1267
- ws.on('error', function (err) { console.log('WEBSERVER WSERR1: ' + err); });
1266
+ // If error, close the associated TCP connection.
1267
+ ws.on('error', function (err) {
1268
+ console.log('CIRA server websocket error from ' + ws._socket.remoteAddress + ', ' + err.toString().split('\r')[0] + '.');
1269
+ Debug(1, 'Websocket relay closed on error.');
1270
+ if (ws.forwardclient && ws.forwardclient.close) { ws.forwardclient.close(); } // TODO: If TLS is used, we need to close the socket that is wrapped by TLS
1271
+ });
1272
1273
// If the web socket is closed, close the associated TCP connection.
1274
ws.on('close', function (req) {
@@ -1318,8 +1322,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1322
ws.forwardclient.write(Buffer.from(msg, 'binary')); // Forward data to the associated TCP connection.
1323
});
1324
1321
- // If error, do nothing
1322
- ws.on('error', function (err) { console.log('WEBSERVER WSERR2: ' + err); });
1325
+ // If error, close the associated TCP connection.
1326
+ ws.on('error', function (err) {
1327
+ console.log('Error with relay web socket connection from ' + ws._socket.remoteAddress + ', ' + err.toString().split('\r')[0] + '.');
1328
+ Debug(1, 'Error with relay web socket connection from ' + ws._socket.remoteAddress + '.');
1329
+ if (ws.forwardclient) { try { ws.forwardclient.destroy(); } catch (e) { } }
1330
+ });
1331
1332
// If the web socket is closed, close the associated TCP connection.
1333
ws.on('close', function () {
@@ -1409,8 +1417,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1417
}
1418
});
1419
1412
- // If error, do nothing
1413
- ws.on('error', function (err) { console.log('WEBSERVER WSERR3: ' + err); });
1420
+ // If error, do nothing.
1421
+ ws.on('error', function (err) { console.log('Echo server error from ' + ws._socket.remoteAddress + ', ' + err.toString().split('\r')[0] + '.'); });
1422
1423
// If closed, do nothing
1424
ws.on('close', function (req) { });
@@ -1523,8 +1531,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
1531
if ((user.siteadmin & 1) == 0) { res.sendStatus(401); return; } // Check if we have server backup rights
1532
1533
// Require modules
1526
- var fs = require('fs');
1527
- var archive = require('archiver')('zip', { level: 9 }); // Sets the compression method to maximum.
1534
+ const fs = require('fs');
1535
+ const archive = require('archiver')('zip', { level: 9 }); // Sets the compression method to maximum.
1536
1537
// Good practice to catch this error explicitly
1538
archive.on('error', function (err) { throw err; });
@@ -2018,7 +2026,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2026
function CheckListenPort(port, func) {
2027
var s = obj.net.createServer(function (socket) { });
2028
obj.tcpServer = s.listen(port, function () { s.close(function () { if (func) { func(port); } }); }).on('error', function (err) {
2021
- if (args.exactports) { console.error('ERROR: MeshCentral HTTPS web server port ' + port + ' not available.'); process.exit(); }
2029
+ if (args.exactports) { console.error('ERROR: MeshCentral HTTPS server port ' + port + ' not available.'); process.exit(); }
2030
else { if (port < 65535) { CheckListenPort(port + 1, func); } else { if (func) { func(0); } } }
2031
});
2032
}
@@ -2029,15 +2037,15 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2037
obj.args.port = port;
2038
if (obj.tlsServer != null) {
2039
if (obj.args.lanonly == true) {
2032
- obj.tcpServer = obj.tlsServer.listen(port, function () { console.log('MeshCentral HTTPS web server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2040
+ obj.tcpServer = obj.tlsServer.listen(port, function () { console.log('MeshCentral HTTPS server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2041
} else {
2034
- obj.tcpServer = obj.tlsServer.listen(port, function () { console.log('MeshCentral HTTPS web server running on ' + certificates.CommonName + ':' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2042
+ obj.tcpServer = obj.tlsServer.listen(port, function () { console.log('MeshCentral HTTPS server running on ' + certificates.CommonName + ':' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2043
obj.parent.updateServerState('servername', certificates.CommonName);
2044
}
2045
obj.parent.updateServerState('https-port', port);
2046
if (args.aliasport != null) { obj.parent.updateServerState('https-aliasport', args.aliasport); }
2047
} else {
2040
- obj.tcpServer = obj.app.listen(port, function () { console.log('MeshCentral HTTP web server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2048
+ obj.tcpServer = obj.app.listen(port, function () { console.log('MeshCentral HTTP server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
2049
obj.parent.updateServerState('http-port', port);
2050
if (args.aliasport != null) { obj.parent.updateServerState('http-aliasport', args.aliasport); }
2051
}