domotz-remote-pawn
Version:
Domotz Agent
86 lines (80 loc) • 3.01 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
*
*
* Created by Tommaso Latini <tlatini@domotz.com> on 14/09/15.
*/
var factory = function (deviceUtils) {
function parseHost(host) {
var addresses = host.address,
status = host.status[0].$,
hostname = host.hostnames[0],
reason = status.reason,
name = (hostname.trim && hostname.trim() === '') ? '' : hostname.hostname[0].$.name,
ip, mac = null, addr;
if (reason === 'arp-response') {
for (var i = 0; i < addresses.length; i++) {
addr = addresses[i].$;
if (addr.addrtype === 'ipv4') {
ip = addr.addr;
} else if (addr.addrtype === 'mac') {
mac = addr.addr;
}
}
} else if (reason === 'echo-reply' || reason === 'syn-ack') {
for (var j = 0; j < addresses.length; j++) {
addr = addresses[j].$;
if (addr.addrtype === 'ipv4') {
ip = addr.addr;
}
}
} else {
console.warn('NMAP_PARSER - Unsupported reason: ', reason);
return null;
}
return deviceUtils.getDevice(ip, mac, name);
}
function parse(result) {
try {
var ret = {},
hosts = result.nmaprun.host || [];
for (var i = 0; i < hosts.length; i++) {
var device = parseHost(hosts[i]);
console.silly('Parsed Host: ' + JSON.stringify(device));
if (device) {
var mac = device.mac;
if (mac) {
var dp = deviceUtils.deviceProjection(device);
if (ret[mac] === undefined) {
ret[mac] = [dp];
} else {
ret[mac].push(dp);
}
}
}
}
console.verbose('Return parsed list: ' + JSON.stringify(ret));
return ret;
} catch (err) {
console.warn(err.stack);
throw new Error('Error during parsing: Wrong Input');
}
}
return {
parse: parse
};
};
module.exports.factory = factory;