local-network-scan
Version:
A lightweight library to quickly scan local network
286 lines • 15.4 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.scanLocalNetwork = void 0;
var axios_1 = __importDefault(require("axios"));
var ip_1 = __importDefault(require("ip"));
var ping_1 = __importDefault(require("ping"));
var promise_timeout_1 = require("promise-timeout");
var arp_1 = require("./arp");
/** Rhe logger, default it's the Node.JS console */
var logger = console;
/** Keep mac vendors results in cache */
var vendorsCache = new Map();
/**
* Detect local network to scan
* @param localNetwork The local network to scan (Optional)
* @returns The localNetwork to scan
*/
function getNetworkAddress(localNetwork) {
// If localNetwork passed, just make sure it's valid
if (localNetwork) {
var parts = localNetwork.split('.');
if (parts.length === 3) {
return localNetwork;
}
throw new Error('localNetwork should be xxx.xxx.xxx');
}
// Get device IP
var machineIp = ip_1.default.address();
var machineIpParts = machineIp.split('.');
if (machineIpParts.length !== 4) {
throw new Error("Machine don't own IP address, have to pass localNetwork option");
}
// Get network only address
return machineIpParts.slice(0, -1).join('.');
}
/**
* Query https://macvendors.com/ API
* @param mac The mac to query for
* @returns The vendor results
*/
function getVendor(mac) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var vendorRes, vendorBody, vendor, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 2, , 3]);
if (vendorsCache.has(mac)) {
logger.info("[local-network-scan] found mac " + mac + " hit in cache");
return [2 /*return*/, vendorsCache.get(mac) || ''];
}
logger.info("[local-network-scan] Feting mac " + mac + " vendor...");
return [4 /*yield*/, (0, axios_1.default)("http://macvendors.co/api/" + mac + "/json")];
case 1:
vendorRes = _b.sent();
vendorBody = vendorRes.data;
vendor = ((_a = vendorBody === null || vendorBody === void 0 ? void 0 : vendorBody.result) === null || _a === void 0 ? void 0 : _a.company) || '';
vendorsCache.set(mac, vendor);
logger.info("[local-network-scan] Feting mac " + mac + " vendor finished");
return [2 /*return*/, vendor];
case 2:
error_1 = _b.sent();
logger.error("[local-network-scan] Feting mac " + mac + " vendor failed, " + error_1);
return [2 /*return*/, ''];
case 3: return [2 /*return*/];
}
});
});
}
/**
* Ping device, detect if there is a device and if so, get his mac from ARP table
* @param ip The ip to ping
* @param options The scan option
* @returns ResolvedDevice object, or undefined if there is no devices on current IP
*/
function pingDevice(ip) {
return __awaiter(this, void 0, void 0, function () {
var pingResult, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, ping_1.default.promise.probe(ip, { timeout: 0.5 })];
case 1:
pingResult = _a.sent();
if (!pingResult.alive) {
// If no device there, return undefined and abort
return [2 /*return*/];
}
return [2 /*return*/, {
ip: ip,
}];
case 2:
error_2 = _a.sent();
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
}
/**
* Scan local network devices in parallel
* @param options See @see ScanOptions
* @returns The network devices collection
*/
function scanLocalNetwork(options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var pingBatches, batch, _loop_1, index, sampleStartPing, localDevicesResults, _i, _a, _b, batch_1, pingCalls, batchResults, localDevices, sampleEndPing, sampleStartARP, macTable, _c, localDevices_1, localDevice, error_3, sampleEndARP, sampleStartVendor, vendorQueries, _loop_2, _d, localDevices_2, localDevice, error_4, sampleEndVendor, pingsDurationS, arpDurationS, vendorsDurationS, totalS;
var _this = this;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (options.logger) {
// Load the logger, if it's passed
logger = options.logger;
}
if (options.clearVendorsCache) {
vendorsCache.clear();
}
options.queryVendor = options.queryVendor || false;
options.beachesSize = options.beachesSize || 50;
options.pingTimeoutMS = options.pingTimeoutMS || 1000 * 2.5;
options.queryVendorsTimeoutMS = options.queryVendorsTimeoutMS || 1000 * 60;
// First calc the network addresses
options.localNetwork = getNetworkAddress(options.localNetwork);
pingBatches = {};
batch = 0;
_loop_1 = function (index) {
// If the batch is full (means )
if (index % options.beachesSize === 0) {
batch = index; // Keep the device index as bach key
pingBatches[batch] = [];
}
// Prepare the ping promise to ping device index X
var pingCall = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, promise_timeout_1.timeout)(pingDevice(options.localNetwork + "." + index), (options.pingTimeoutMS || 0)).catch(function () { return undefined; })];
case 1: return [2 /*return*/, _a.sent()];
}
});
}); };
// Add ping call to the bach
pingBatches[batch].push(pingCall);
};
for (index = 0; index < 255; index++) {
_loop_1(index);
}
sampleStartPing = new Date();
localDevicesResults = [];
logger.info("[local-network-scan] Pinging the network devices...\"");
_i = 0, _a = Object.entries(pingBatches);
_e.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
_b = _a[_i], batch_1 = _b[0], pingCalls = _b[1];
logger.info("[local-network-scan] Invoking ping batch \"" + batch_1 + "...\"");
return [4 /*yield*/, Promise.all(pingCalls.map(function (c) { return c().catch(function () { return undefined; }); }))];
case 2:
batchResults = _e.sent();
logger.info("[local-network-scan] Invoking ping batch \"" + batch_1 + " done\"");
localDevicesResults.push.apply(localDevicesResults, batchResults);
_e.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
localDevices = localDevicesResults.filter(function (d) { return !!d; });
logger.info("[local-network-scan] Pinging the network devices finished\"");
sampleEndPing = new Date();
sampleStartARP = new Date();
logger.info("[local-network-scan] Reading ARP table...\"");
_e.label = 5;
case 5:
_e.trys.push([5, 7, , 8]);
return [4 /*yield*/, (0, arp_1.getNetworkTableMap)(options)];
case 6:
macTable = _e.sent();
// Load up the mac results to the devices
for (_c = 0, localDevices_1 = localDevices; _c < localDevices_1.length; _c++) {
localDevice = localDevices_1[_c];
localDevice.mac = macTable.get(localDevice.ip);
}
return [3 /*break*/, 8];
case 7:
error_3 = _e.sent();
logger.error("" + JSON.stringify(error_3 || ''));
return [3 /*break*/, 8];
case 8:
logger.info("[local-network-scan] Reading ARP table finished\"");
sampleEndARP = new Date();
sampleStartVendor = new Date();
if (!options.queryVendor) return [3 /*break*/, 13];
logger.info("[local-network-scan] Fetching devices vendors ...\"");
vendorQueries = [];
_loop_2 = function (localDevice) {
if (!localDevice.mac) {
return "continue";
}
vendorQueries.push(function () { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = localDevice;
return [4 /*yield*/, getVendor(localDevice.mac)];
case 1:
_a.vendor = _b.sent();
return [2 /*return*/];
}
});
}); });
};
for (_d = 0, localDevices_2 = localDevices; _d < localDevices_2.length; _d++) {
localDevice = localDevices_2[_d];
_loop_2(localDevice);
}
_e.label = 9;
case 9:
_e.trys.push([9, 11, , 12]);
return [4 /*yield*/, (0, promise_timeout_1.timeout)(Promise.all(vendorQueries.map(function (q) { return q().catch(function () { return undefined; }); })), options.queryVendorsTimeoutMS)];
case 10:
_e.sent();
return [3 /*break*/, 12];
case 11:
error_4 = _e.sent();
logger.error("[local-network-scan] Fetching devices vendors timeout, avoiding vendors fetch\"");
return [3 /*break*/, 12];
case 12:
logger.info("[local-network-scan] Fetching devices vendors finished\"");
_e.label = 13;
case 13:
sampleEndVendor = new Date();
pingsDurationS = (sampleEndPing.getTime() - sampleStartPing.getTime()) / 1000;
arpDurationS = (sampleEndARP.getTime() - sampleStartARP.getTime()) / 1000;
vendorsDurationS = (sampleEndVendor.getTime() - sampleStartVendor.getTime()) / 1000;
totalS = pingsDurationS + arpDurationS + vendorsDurationS;
logger.info("[local-network-scan] Scanning network devices finished with total " + localDevices.length + " devices, pings took " + pingsDurationS + "s, ARP read took " + arpDurationS + "s, fetch vendors took " + vendorsDurationS + "s, total " + totalS + "s");
return [2 /*return*/, localDevices];
}
});
});
}
exports.scanLocalNetwork = scanLocalNetwork;
//# sourceMappingURL=index.js.map