domotz-remote-pawn
Version:
Domotz Agent
101 lines (94 loc) • 3.63 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 <tommaso@domotz.com> on 25/07/15.
*
* This module recover host information on a UNIX-like operating system (like
* Debian, DSM, Qnap OS).
*
* These information are fundamental for the application, so we recover it
* synchronously at boot and we exit in case of failure.
* The periodical refresh is asynchronous for not blocking nodejs mainloop.
*/
const LOG_PREFIX = 'HOST_INTERFACES';
module.exports.factory = function (resourceLocator) {
var defaultFile = process.env.DOMOTZ_CONF_DIR + '/custom_interfaces.conf',
customInterfaces = null,
counter = 1;
var myConsole = resourceLocator.log.decorateLogs();
var fileManager = resourceLocator.utils.file;
var lodash = resourceLocator.lodash;
/**
* Private IP address ranges
* The ranges and the amount of usable IP's are as follows:
* 10.0.0.0 - 10.255.255.255 Addresses: 16,777,216
* 172.16.0.0 - 172.31.255.255 Addresses: 1,048,576
* 192.168.0.0 - 192.168.255.255 Addresses: 65,536
* @param ip
* @returns {boolean}
*/
function isPrivateIP(ip) {
var octets = ip.split('.'),
b0 = parseInt(octets[0], 10),
b1 = parseInt(octets[1], 10);
return b0 === 10 || (b0 === 172 && b1 >= 16 && b1 <= 31) || (b0 === 192 && b1 === 168);
}
function parse(content) {
/**
* Standard format of domotz interface:
* {
* <name> : {
* mac: <mac>,
* ip: <ip>,
* netmask: <netmask>
* }
* }
*/
var networks = content.split('\n');
var tmp = {};
for (var i = 0; i < networks.length; i++) {
var network = networks[i];
if (network) {
var splitted = network.split('/'),
name = String('0' + counter).slice(-2),
ip = splitted[0],
netmask = parseInt(splitted[1], 10);
if (isPrivateIP(ip)) {
console.info('%s - (%s): Custom NIC with IP address: [%s] ' + 'and Netmask: [%s]', LOG_PREFIX, name, ip, netmask);
tmp[name] = {
ip: ip,
mac: null,
netmask: netmask,
custom: true,
};
counter++;
} else {
console.warn('%s - (%s): IP %s is public. Not allowed to be monitored.', LOG_PREFIX, name, ip);
}
}
}
return tmp;
}
function getCustomInterfaces() {
customInterfaces = customInterfaces || fileManager.readFile(defaultFile, parse) || {};
return lodash.clone(customInterfaces);
}
return {
get: getCustomInterfaces,
parse: parse,
};
};