UNPKG

domotz-remote-pawn

Version:

Domotz Agent

107 lines (97 loc) 3.9 kB
/** 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 18/01/16. */ const MAC_VALIDATOR = /^(?!(?:ff:ff:ff:ff:ff:ff|00:00:00:00:00:00))(?:[\da-f]{2}:){5}[\da-f]{2}$/i; var factory = function (q, proc, nic) { function getAsync(info, iface) { var cmd = nic.cmd[info](iface); var validator = nic.validator[info]; return proc.exec(cmd, { timeout: 5000 }).then(validator); } function getIfacePromise(iface) { var promises = [q(iface), getAsync('mac', iface), getAsync('ip', iface), getAsync('netmask', iface)]; return q.all(promises).spread(nic.getNicDescriptor); } function getDefaultGatewayAsync() { return getAsync('gateway'); } function getInterfacesAsync() { return getAsync('interfaces') .then(function (list) { var interfacesList = []; list.forEach(function (iface) { console.debug('Recover info for NIC: ' + iface); var asyncInfoPromise = getIfacePromise(iface); interfacesList.push(asyncInfoPromise); }); return q.allSettled(interfacesList); }) .then(function (list) { var validInterfaces = []; console.verbose('Get all promise: ' + JSON.stringify(list)); list.forEach(function (promise) { if (promise.state === 'fulfilled') { validInterfaces.push(promise.value); } }); return validInterfaces; }); } function getDefaultGatewayAsyncWin() { return require('default-gateway') .v4() .then(function (res) { return { ip: res.gateway, interface: res.interface, }; }); } function getInterfacesAsyncWin() { var validInterfaces = []; const interfaces = require('os').networkInterfaces(); Object.keys(interfaces).forEach(function (interfaceName) { interfaces[interfaceName].forEach(function (element) { if (element.family === 'IPv4') { var name = interfaceName; var ip = element.address; var mac = element.mac; var netmask = parseInt(element.cidr ? element.cidr.split('/')[1] : ''); if (!mac || !MAC_VALIDATOR.test(mac.toLowerCase())) { return; } validInterfaces.push({ name: name, mac: mac.toUpperCase(), ip: ip, netmask: netmask, }); } }); }); return q.resolve(validInterfaces); } return { getInterfacesAsync: getInterfacesAsync, getDefaultGatewayAsync: getDefaultGatewayAsync, getInterfacesAsyncWin: getInterfacesAsyncWin, getDefaultGatewayAsyncWin: getDefaultGatewayAsyncWin, }; }; module.exports.factory = factory;