ffffng/server/services/nodeService.js

473 lines
16 KiB
JavaScript
Raw Permalink Normal View History

2014-05-12 20:08:19 +02:00
'use strict';
angular.module('ffffng')
.service('NodeService', function (
config,
_,
2016-06-07 00:21:26 +02:00
async,
crypto,
fs,
glob,
2016-05-24 21:08:34 +02:00
Logger,
MailService,
Strings,
ErrorTypes,
UrlBuilder
) {
2016-06-07 00:21:26 +02:00
var MAX_PARALLEL_NODES_PARSING = 10;
2014-05-12 20:08:19 +02:00
var linePrefixes = {
hostname: '# Knotenname: ',
nickname: '# Ansprechpartner: ',
email: '# Kontakt: ',
coords: '# Koordinaten: ',
mac: '# MAC: ',
token: '# Token: ',
monitoring: '# Monitoring: ',
monitoringToken: '# Monitoring-Token: '
2014-05-12 20:08:19 +02:00
};
2016-05-23 22:36:27 +02:00
var filenameParts = ['hostname', 'mac', 'key', 'token', 'monitoringToken'];
2014-05-12 20:08:19 +02:00
function generateToken() {
return crypto.randomBytes(8).toString('hex');
}
2016-05-23 22:36:27 +02:00
function findNodeFiles(filter) {
var pattern = _.join(
_.map(filenameParts, function (field) {
return filter.hasOwnProperty(field) ? filter[field] : '*';
}),
'@'
);
2014-06-06 21:22:57 +02:00
return glob.sync(config.server.peersPath + '/' + pattern.toLowerCase());
2014-05-12 20:08:19 +02:00
}
function findFilesInPeersPath(callback) {
glob(config.server.peersPath + '/*', function (err, files) {
if (err) {
return callback(err);
}
async.filter(files, function (file, fileCallback) {
if (file[0] === '.') {
return fileCallback(null, false);
}
fs.lstat(file, function (err, stats) {
if (err) {
return fileCallback(err);
}
fileCallback(null, stats.isFile());
});
}, callback);
});
}
2016-05-23 22:36:27 +02:00
function parseNodeFilename(filename) {
var parts = _.split(filename, '@', filenameParts.length);
var parsed = {};
_.each(_.zip(filenameParts, parts), function (part) {
parsed[part[0]] = part[1];
});
return parsed;
}
function isDuplicate(filter, token) {
var files = findNodeFiles(filter);
2014-05-12 20:08:19 +02:00
if (files.length === 0) {
return false;
}
2016-05-23 22:36:27 +02:00
if (files.length > 1 || !token /* node is being created*/) {
2014-05-12 20:08:19 +02:00
return true;
}
2016-05-23 22:36:27 +02:00
return parseNodeFilename(files[0]).token !== token;
2014-05-12 20:08:19 +02:00
}
2016-05-23 22:36:27 +02:00
function checkNoDuplicates(token, node, nodeSecrets) {
if (isDuplicate({ hostname: node.hostname }, token)) {
2014-05-12 20:08:19 +02:00
return {data: {msg: 'Already exists.', field: 'hostname'}, type: ErrorTypes.conflict};
}
if (node.key) {
2016-05-23 22:36:27 +02:00
if (isDuplicate({ key: node.key }, token)) {
2014-05-12 20:08:19 +02:00
return {data: {msg: 'Already exists.', field: 'key'}, type: ErrorTypes.conflict};
}
}
2016-05-23 22:36:27 +02:00
if (isDuplicate({ mac: node.mac }, token)) {
2014-05-12 20:08:19 +02:00
return {data: {msg: 'Already exists.', field: 'mac'}, type: ErrorTypes.conflict};
}
2016-05-23 22:36:27 +02:00
if (nodeSecrets.monitoringToken && isDuplicate({ monitoringToken: nodeSecrets.monitoringToken }, token)) {
return {data: {msg: 'Already exists.', field: 'monitoringToken'}, type: ErrorTypes.conflict};
}
2014-05-12 20:08:19 +02:00
return null;
}
function toNodeFilename(token, node, nodeSecrets) {
return config.server.peersPath + '/' +
(
node.hostname + '@' +
node.mac + '@' +
(node.key || '') + '@' +
token + '@' +
(nodeSecrets.monitoringToken || '')
).toLowerCase();
}
function writeNodeFile(isUpdate, token, node, nodeSecrets, callback) {
var filename = toNodeFilename(token, node, nodeSecrets);
var data = '';
2014-05-12 20:08:19 +02:00
_.each(linePrefixes, function (prefix, key) {
var value;
switch (key) {
case 'monitoring':
if (node.monitoring && node.monitoringConfirmed) {
value = 'aktiv';
} else if (node.monitoring && !node.monitoringConfirmed) {
value = 'pending';
} else {
value = '';
}
break;
case 'monitoringToken':
value = nodeSecrets.monitoringToken || '';
break;
default:
value = key === 'token' ? token : node[key];
if (_.isUndefined(value)) {
value = _.isUndefined(nodeSecrets[key]) ? '' : nodeSecrets[key];
}
break;
2014-05-12 20:08:19 +02:00
}
data += prefix + value + '\n';
});
if (node.key) {
data += 'key "' + node.key + '";\n';
}
// since node.js is single threaded we don't need a lock
var error;
if (isUpdate) {
2016-05-23 22:36:27 +02:00
var files = findNodeFiles({ token: token });
2014-05-12 20:08:19 +02:00
if (files.length !== 1) {
return callback({data: 'Node not found.', type: ErrorTypes.notFound});
}
2016-05-23 22:36:27 +02:00
error = checkNoDuplicates(token, node, nodeSecrets);
2014-05-12 20:08:19 +02:00
if (error) {
return callback(error);
}
2016-05-24 21:08:34 +02:00
var file = files[0];
try {
fs.unlinkSync(file);
}
catch (error) {
2016-05-24 21:08:34 +02:00
Logger.tag('node', 'save').error('Could not delete old node file: ' + file, error);
return callback({data: 'Could not remove old node data.', type: ErrorTypes.internalError});
}
2014-05-12 20:08:19 +02:00
} else {
2016-05-23 22:36:27 +02:00
error = checkNoDuplicates(null, node, nodeSecrets);
2014-05-12 20:08:19 +02:00
if (error) {
return callback(error);
}
}
try {
fs.writeFileSync(filename, data, 'utf8');
}
catch (error) {
2016-05-24 21:08:34 +02:00
Logger.tag('node', 'save').error('Could not write node file: ' + filename, error);
2014-05-12 20:08:19 +02:00
return callback({data: 'Could not write node data.', type: ErrorTypes.internalError});
}
return callback(null, token, node);
}
2016-05-16 18:27:03 +02:00
function deleteNodeFile(token, callback) {
2016-05-23 22:36:27 +02:00
var files = findNodeFiles({ token: token });
2016-05-16 18:27:03 +02:00
if (files.length !== 1) {
return callback({data: 'Node not found.', type: ErrorTypes.notFound});
}
try {
fs.unlinkSync(files[0]);
}
catch (error) {
2016-05-24 21:08:34 +02:00
Logger.tag('node', 'delete').error('Could not delete node file: ' + file, error);
2016-05-16 18:27:03 +02:00
return callback({data: 'Could not delete node.', type: ErrorTypes.internalError});
}
return callback(null);
}
2014-05-12 20:08:19 +02:00
function parseNodeFile(file, callback) {
fs.readFile(file, function (err, contents) {
if (err) {
return callback(err);
}
2014-05-12 20:08:19 +02:00
var lines = contents.toString();
2014-05-12 20:08:19 +02:00
var node = {};
var nodeSecrets = {};
_.each(lines.split('\n'), function (line) {
var entries = {};
2014-05-12 20:08:19 +02:00
for (var key in linePrefixes) {
if (linePrefixes.hasOwnProperty(key)) {
var prefix = linePrefixes[key];
if (line.substring(0, prefix.length) === prefix) {
entries[key] = Strings.normalizeString(line.substr(prefix.length));
break;
}
2014-05-12 20:08:19 +02:00
}
}
if (_.isEmpty(entries) && line.substring(0, 5) === 'key "') {
entries.key = Strings.normalizeString(line.split('"')[1]);
}
_.each(entries, function (value, key) {
if (key === 'mac') {
node['mac'] = value;
node['mapId'] = _.toLower(value).replace(/:/g, '')
} else if (key === 'monitoring') {
var active = value === 'aktiv';
var pending = value === 'pending';
node.monitoring = active || pending;
node.monitoringConfirmed = active;
node.monitoringState = active ? 'active' : (pending ? 'pending' : '');
} else if (key === 'monitoringToken') {
nodeSecrets.monitoringToken = value;
} else {
node[key] = value;
}
});
2014-05-12 20:08:19 +02:00
});
callback(null, node, nodeSecrets);
});
2014-05-12 20:08:19 +02:00
}
function findNodeDataByFilePattern(filter, callback) {
2016-05-23 22:36:27 +02:00
var files = findNodeFiles(filter);
if (files.length !== 1) {
return callback(null);
}
var file = files[0];
return parseNodeFile(file, callback);
}
function getNodeDataByFilePattern(filter, callback) {
findNodeDataByFilePattern(filter, function (err, node, nodeSecrets) {
if (err) {
return callback(err);
}
if (!node) {
return callback({data: 'Node not found.', type: ErrorTypes.notFound});
}
callback(null, node, nodeSecrets);
});
}
2016-05-20 22:11:35 +02:00
function sendMonitoringConfirmationMail(node, nodeSecrets, callback) {
2016-05-23 22:36:27 +02:00
var confirmUrl = UrlBuilder.monitoringConfirmUrl(nodeSecrets);
var disableUrl = UrlBuilder.monitoringDisableUrl(nodeSecrets);
2016-05-20 22:11:35 +02:00
MailService.enqueue(
config.server.email.from,
node.nickname + ' <' + node.email + '>',
2016-05-20 22:11:35 +02:00
'monitoring-confirmation',
{
node: node,
confirmUrl: confirmUrl,
disableUrl: disableUrl
},
function (err) {
2016-05-24 21:08:34 +02:00
if (err) {
Logger.tag('monitoring', 'confirmation').error('Could not enqueue confirmation mail.', error);
2016-05-20 22:11:35 +02:00
return callback({data: 'Internal error.', type: ErrorTypes.internalError});
}
callback(null);
}
);
}
2014-05-12 20:08:19 +02:00
return {
createNode: function (node, callback) {
var token = generateToken();
var nodeSecrets = {};
node.monitoringConfirmed = false;
if (node.monitoring) {
nodeSecrets.monitoringToken = generateToken();
}
writeNodeFile(false, token, node, nodeSecrets, function (err, token, node) {
if (err) {
return callback(err);
}
if (node.monitoring && !node.monitoringConfirmed) {
2016-05-20 22:11:35 +02:00
return sendMonitoringConfirmationMail(node, nodeSecrets, function (err) {
if (err) {
return callback(err);
}
return callback(null, token, node);
});
}
return callback(null, token, node);
});
2014-05-12 20:08:19 +02:00
},
updateNode: function (token, node, callback) {
this.getNodeDataByToken(token, function (err, currentNode, nodeSecrets) {
if (err) {
return callback(err);
}
var monitoringConfirmed = false;
var monitoringToken = '';
if (node.monitoring) {
if (!currentNode.monitoring) {
// monitoring just has been enabled
monitoringConfirmed = false;
monitoringToken = generateToken();
} else {
// monitoring is still enabled
if (currentNode.email != node.email) {
// new email so we need a new token and a reconfirmation
monitoringConfirmed = false;
monitoringToken = generateToken();
} else {
// email unchanged, keep token (fix if not set) and confirmation state
monitoringConfirmed = currentNode.monitoringConfirmed;
monitoringToken = nodeSecrets.monitoringToken || generateToken();
}
}
}
node.monitoringConfirmed = monitoringConfirmed;
nodeSecrets.monitoringToken = monitoringToken;
writeNodeFile(true, token, node, nodeSecrets, function (err, token, node) {
if (err) {
return callback(err);
}
if (node.monitoring && !node.monitoringConfirmed) {
2016-05-20 22:11:35 +02:00
return sendMonitoringConfirmationMail(node, nodeSecrets, function (err) {
if (err) {
return callback(err);
}
return callback(null, token, node);
});
}
return callback(null, token, node);
});
});
2014-05-12 20:08:19 +02:00
},
internalUpdateNode: function (token, node, nodeSecrets, callback) {
writeNodeFile(true, token, node, nodeSecrets, callback);
},
2016-05-16 18:27:03 +02:00
deleteNode: function (token, callback) {
deleteNodeFile(token, callback);
},
getAllNodes: function (callback) {
var files = findNodeFiles({});
2016-06-07 00:21:26 +02:00
async.mapLimit(
files,
2016-06-07 00:21:26 +02:00
MAX_PARALLEL_NODES_PARSING,
parseNodeFile,
function (err, nodes) {
if (err) {
Logger.tag('nodes').error('Error getting all nodes:', error);
return callback({data: 'Internal error.', type: ErrorTypes.internalError});
}
2016-06-07 12:39:52 +02:00
return callback(null, nodes);
2016-06-07 00:21:26 +02:00
}
);
},
findNodeDataByMac: function (mac, callback) {
return findNodeDataByFilePattern({ mac: mac }, callback);
},
getNodeDataByToken: function (token, callback) {
2016-05-23 22:36:27 +02:00
return getNodeDataByFilePattern({ token: token }, callback);
},
2014-05-12 20:08:19 +02:00
2016-05-23 22:36:27 +02:00
getNodeDataByMonitoringToken: function (monitoringToken, callback) {
return getNodeDataByFilePattern({ monitoringToken: monitoringToken }, callback);
},
fixNodeFilenames: function (callback) {
findFilesInPeersPath(function (err, files) {
if (err) {
return callback(err);
}
async.mapLimit(
files,
MAX_PARALLEL_NODES_PARSING,
function (file, fileCallback) {
parseNodeFile(file, function (err, node, nodeSecrets) {
if (err) {
return fileCallback(err);
}
var expectedFilename = toNodeFilename(node.token, node, nodeSecrets);
if (file !== expectedFilename) {
return fs.rename(file, expectedFilename, function (err) {
if (err) {
return fileCallback(new Error(
'Cannot rename file ' + file + ' to ' + expectedFilename + ' => ' + err
));
}
fileCallback(null);
});
}
fileCallback(null);
});
},
callback
);
});
2014-05-12 20:08:19 +02:00
}
};
});