Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. module.exports = function (RED) {
  2. "use strict";
  3. const SNMP = require("net-snmp");
  4. const sessions = {};
  5. function generateUUID() {
  6. let d = Date.now();
  7. let d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || (Date.now() * Math.random() * 100000);//Time in microseconds since load
  8. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9. let r = Math.random() * 16;//random number between 0 and 16
  10. if (d > 0) {//Use timestamp until depleted
  11. r = (d + r) % 16 | 0;
  12. d = Math.floor(d / 16);
  13. } else {//Use microseconds since page-load if supported
  14. r = (d2 + r) % 16 | 0;
  15. d2 = Math.floor(d2 / 16);
  16. }
  17. return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  18. });
  19. }
  20. function openSession(sessionid, host, user, options) {
  21. // SNMPv3 call
  22. if (options.version === SNMP.Version3) {
  23. sessions[sessionid] = SNMP.createV3Session(host, user, options);
  24. }
  25. // SNMPv1 or SNMPv2c call
  26. else {
  27. sessions[sessionid] = SNMP.createSession(host, user.community, options);
  28. }
  29. return sessions[sessionid];
  30. }
  31. // Any session needs to be closed after completion
  32. function closeSession(sessionid) {
  33. try {
  34. sessions[sessionid].removeAllListeners();
  35. } catch (e) { }
  36. try {
  37. sessions[sessionid].close();
  38. } catch (e) { }
  39. delete sessions[sessionid];
  40. }
  41. function initSnmpNode(node, config) {
  42. node.community = config.community;
  43. node.host = config.host;
  44. node.version = config.version;
  45. node.auth = config.auth;
  46. node.authprot = config.authprot;
  47. node.privprot = config.privprot;
  48. if (node.credentials) {
  49. node.username = node.credentials.username;
  50. node.authkey = node.credentials.authkey;
  51. node.privkey = node.credentials.privkey;
  52. }
  53. node.timeout = Number(config.timeout || 5) * 1000;
  54. }
  55. function prepareSnmpOptions(node, msg) {
  56. let host = node.host || msg.host;
  57. const sessionid = generateUUID();
  58. const user = {}
  59. const options = {};
  60. const compat = { "v1": "1", "v2": "2c", "v2c": "2c", "v3": "3" };
  61. if(compat[node.version]) {
  62. node.version = compat[node.version];
  63. } else if(["1","2c","3"].indexOf(node.version) < 0) {
  64. node.version = "1";
  65. }
  66. options.version = node.version;
  67. if (node.version === "1") {
  68. options.version = SNMP.Version1;
  69. user.community = node.community || msg.community;
  70. } else if (node.version === "2c") {
  71. options.version = SNMP.Version2c;
  72. user.community = node.community || msg.community;
  73. } else if (node.version === "3") {
  74. user.name = node.username || msg.username || "";
  75. user.level = SNMP.SecurityLevel.noAuthNoPriv;
  76. user.authProtocol = SNMP.AuthProtocols.none;
  77. user.authKey = "";
  78. user.privProtocol = SNMP.PrivProtocols.none;
  79. user.privKey = "";
  80. options.version = SNMP.Version3;
  81. if (node.auth === "authNoPriv" || node.auth === "authPriv") {
  82. user.level = SNMP.SecurityLevel.authNoPriv;
  83. user.authProtocol = (node.authprot === "SHA") ? SNMP.AuthProtocols.sha : SNMP.AuthProtocols.md5;
  84. user.authKey = node.authkey || msg.authkey || "";
  85. if (node.auth === "authPriv") {
  86. user.level = SNMP.SecurityLevel.authPriv;
  87. if (node.privprot === "DES" || node.privprot === "AES") {
  88. user.privProtocol = (node.privprot === "AES") ? SNMP.PrivProtocols.aes : SNMP.PrivProtocols.des;
  89. user.privKey = node.privkey || msg.privkey || "";
  90. }
  91. }
  92. }
  93. }
  94. options.timeout = node.timeout;
  95. options.debug = msg.debug || undefined;
  96. options.port = options.port || 161;
  97. options.retries = options.retries || 1;
  98. if (msg.engineID) {
  99. options.engineID = msg.engineID;//The engineID used for SNMPv3 communications, given as a hex string - defaults to a system-generated engineID containing elements of random
  100. }
  101. if (msg.backoff) {
  102. options.backoff = msg.backoff;//The factor by which to increase the timeout for every retry, defaults to 1 for no increase
  103. }
  104. if (msg.backwardsGetNexts) {
  105. options.backwardsGetNexts = msg.backwardsGetNexts;//boolean to allow GetNext operations to retrieve lexicographically preceding OIDs
  106. }
  107. if (msg.idBitsSize === 16 || msg.idBitsSize === 32) {
  108. options.idBitsSize = msg.idBitsSize;//Either 16 or 32, defaults to 32. Used to reduce the size of the generated id for compatibility with some older devices.
  109. }
  110. const ipv = parseIP(host);
  111. if (ipv.version === 4) {
  112. host = ipv.ip;
  113. options.port = ipv.port || options.port;
  114. options.transport = 'udp4';
  115. } else if (ipv.version === 6) {
  116. host = ipv.ip;
  117. options.port = ipv.port || options.port;
  118. options.transport = 'udp6';
  119. } else {
  120. //probably a host name
  121. if (host.indexOf(":") > 0) {
  122. host = host.split(":")[0];
  123. options.port = host.split(":")[1];
  124. }
  125. }
  126. return {
  127. host: host,
  128. sessionid: sessionid,
  129. user: user,
  130. options: options,
  131. }
  132. }
  133. function parseIP(ip) {
  134. const IPV4_PAT = /^(\d+)\.(\d+)\.(\d+)\.(\d+)(?::(\d+)){0,1}$/g;
  135. const IPV6_DOUBLE_COL_PAT = /^\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\]:(\d+)){0,1}$/g;
  136. const ipv4Matcher = IPV4_PAT.exec(ip);
  137. let hex = "";
  138. let port;
  139. let ipOnly = [];
  140. try {
  141. if (ipv4Matcher && ipv4Matcher.length) {
  142. for (let i = 1; i <= 4; i++) {
  143. ipOnly.push(ipv4Matcher[i]);
  144. hex += toHex4(ipv4Matcher[i]);
  145. }
  146. if (ipv4Matcher[5]) {
  147. port = parseInt(ipv4Matcher[5]);
  148. }
  149. return { ip: ipOnly.join("."), hex, port, version: 4 };
  150. }
  151. // IPV6 Must be colons format (a:b:c:d:e:A.B.C.D not currently supported)
  152. let ipv6Pattern = "^\\[{0,1}";
  153. for (let i = 1; i <= 7; i++) {
  154. ipv6Pattern += "([0-9a-f]+):";
  155. }
  156. ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$";
  157. const IPV6_PAT = new RegExp(ipv6Pattern);
  158. // IPV6, double colon
  159. const ipv6DoubleColonMatcher = IPV6_DOUBLE_COL_PAT.exec(ip);
  160. if (ipv6DoubleColonMatcher && ipv6DoubleColonMatcher.length) {
  161. let p1 = ipv6DoubleColonMatcher[1];
  162. if (!p1) {
  163. p1 = "0";
  164. }
  165. let p2 = ipv6DoubleColonMatcher[2];
  166. if (!p2) {
  167. p2 = "0";
  168. }
  169. p1 = p1.padStart(4, "0");
  170. p2 = p2.padStart(4, "0");
  171. ip = p1 + getZeros(8 - numCount(p1) - numCount(p2)) + p2;
  172. if (ipv6DoubleColonMatcher[3]) {
  173. ip = "[" + ip + "]:" + ipv6DoubleColonMatcher[3];
  174. }
  175. }
  176. // IPV6
  177. const ipv6Matcher = IPV6_PAT.exec(ip);
  178. if (ipv6Matcher && ipv6Matcher.length) {
  179. for (let i = 1; i <= 8; i++) {
  180. const p = toHex6(ipv6Matcher[i]).padStart(4, "0");
  181. ipOnly.push(p);
  182. hex += p;
  183. }
  184. if (ipv6Matcher[9]) {
  185. port = parseInt(ipv6Matcher[9]);
  186. }
  187. return { ip: ipOnly.join(":"), hex, port, version: 6 };
  188. }
  189. throw new Error("Unknown address: " + ip);
  190. } catch (error) {
  191. return { ip, hex, port, version: null, error: error };
  192. }
  193. function numCount(/** @type {string} */s) {
  194. return s.split(":").length;
  195. }
  196. function getZeros(/** @type {number} */ count) {
  197. const sb = [":"];
  198. while (count > 0) {
  199. sb.push("0000:");
  200. count--;
  201. }
  202. return sb.join("");
  203. }
  204. function toHex4(/** @type {string} */ s) {
  205. const val = parseInt(s);
  206. if (val < 0 || val > 255) {
  207. throw new Error("Invalid value : " + s);
  208. }
  209. return val.toString(16).padStart(2, "0");
  210. }
  211. function toHex6(/** @type {string} */ s) {
  212. const val = parseInt(s, 16);
  213. if (val < 0 || val > 65536) {
  214. throw new Error("Invalid hex value : " + s);
  215. }
  216. return s;
  217. }
  218. }
  219. function SnmpNode(n) {
  220. const node = this;
  221. RED.nodes.createNode(node, n);
  222. initSnmpNode(node, n);
  223. node.oids = n.oids ? n.oids.replace(/\s/g, "") : "";
  224. node.on("input", function (msg) {
  225. const oids = node.oids || msg.oid;
  226. const { host, sessionid, user, options } = prepareSnmpOptions(node, msg);
  227. if (oids) {
  228. let sess = openSession(sessionid, host, user, options);
  229. sess.on("error", function (err) {
  230. node.error(err, msg);
  231. })
  232. sess.get(oids.split(","), function (error, varbinds) {
  233. if (error) {
  234. node.error(error.toString(), msg);
  235. } else {
  236. for (let i = 0; i < varbinds.length; i++) {
  237. let vb = varbinds[i];
  238. if (SNMP.isVarbindError(vb)) {
  239. node.error(SNMP.varbindError(vb), msg);
  240. vb._error = SNMP.varbindError(vb); //add _error to msg so users can determine the varbind is not valid
  241. }
  242. else {
  243. if (vb.type == 4) { vb.value = vb.value.toString(); }
  244. }
  245. vb.tstr = SNMP.ObjectType[vb.type];
  246. }
  247. msg.payload = varbinds;
  248. msg.oid = oids;
  249. node.send(msg);
  250. }
  251. closeSession(sessionid); // Needed to close the session else a bad or good read could affect future readings
  252. });
  253. } else {
  254. node.warn("No oid(s) to search for");
  255. }
  256. });
  257. }
  258. RED.nodes.registerType("snmp", SnmpNode, {
  259. credentials: {
  260. username: { type: "text" },
  261. authkey: { type: "password" },
  262. privkey: { type: "password" }
  263. }
  264. });
  265. function SnmpSNode(n) {
  266. const node = this;
  267. RED.nodes.createNode(node, n);
  268. initSnmpNode(node, n);
  269. node.varbinds = n.varbinds;
  270. if (node.varbinds && node.varbinds.trim().length === 0) { delete node.varbinds; }
  271. node.on("input", function (msg) {
  272. const { host, sessionid, user, options } = prepareSnmpOptions(node, msg);
  273. const varbinds = (node.varbinds) ? JSON.parse(node.varbinds) : msg.varbinds;
  274. if (varbinds) {
  275. for (let i = 0; i < varbinds.length; i++) {
  276. varbinds[i].type = SNMP.ObjectType[varbinds[i].type];
  277. }
  278. let sess = openSession(sessionid, host, user, options);
  279. sess.on("error", function (err) {
  280. node.error(err, msg);
  281. })
  282. sess.set(varbinds, function (error, varbinds) {
  283. if (error) {
  284. node.error(error.toString(), msg);
  285. } else {
  286. for (let i = 0; i < varbinds.length; i++) {
  287. // for version 2c we must check each OID for an error condition
  288. if (SNMP.isVarbindError(varbinds[i])) {
  289. node.error(SNMP.varbindError(varbinds[i]), msg);
  290. }
  291. }
  292. }
  293. closeSession(sessionid);
  294. });
  295. } else {
  296. node.warn("No varbinds to set");
  297. }
  298. });
  299. }
  300. RED.nodes.registerType("snmp set", SnmpSNode, {
  301. credentials: {
  302. username: { type: "text" },
  303. authkey: { type: "password" },
  304. privkey: { type: "password" }
  305. }
  306. });
  307. function SnmpTNode(n) {
  308. const node = this;
  309. RED.nodes.createNode(node, n);
  310. initSnmpNode(node, n);
  311. node.oids = n.oids ? n.oids.replace(/\s/g, "") : ""
  312. const maxRepetitions = 20;
  313. function sortInt(a, b) {
  314. if (a > b) { return 1; }
  315. else if (b > a) { return -1; } else { return 0; }
  316. }
  317. node.on("input", function (msg) {
  318. const oids = node.oids || msg.oid;
  319. const { host, sessionid, user, options } = prepareSnmpOptions(node, msg);
  320. if (oids) {
  321. msg.oid = oids;
  322. let sess = openSession(sessionid, host, user, options);
  323. sess.on("error", function (err) {
  324. node.error(err, msg);
  325. })
  326. sess.table(oids, maxRepetitions, function (error, table) {
  327. if (error) {
  328. node.error(error.toString(), msg);
  329. } else {
  330. const indexes = [];
  331. for (let index in table) {
  332. if (table.hasOwnProperty(index)) {
  333. indexes.push(parseInt(index));
  334. }
  335. }
  336. indexes.sort(sortInt);
  337. for (let i = 0; i < indexes.length; i++) {
  338. const columns = [];
  339. for (let column in table[indexes[i]]) {
  340. if (table[indexes[i]].hasOwnProperty(column)) {
  341. columns.push(parseInt(column));
  342. }
  343. }
  344. columns.sort(sortInt);
  345. }
  346. msg.payload = table;
  347. node.send(msg);
  348. }
  349. closeSession(sessionid);
  350. });
  351. } else {
  352. node.warn("No oid to search for");
  353. }
  354. });
  355. }
  356. RED.nodes.registerType("snmp table", SnmpTNode, {
  357. credentials: {
  358. username: { type: "text" },
  359. authkey: { type: "password" },
  360. privkey: { type: "password" }
  361. }
  362. });
  363. function SnmpSubtreeNode(n) {
  364. const node = this;
  365. RED.nodes.createNode(node, n);
  366. initSnmpNode(node, n);
  367. node.oids = n.oids ? n.oids.replace(/\s/g, "") : ""
  368. const maxRepetitions = 20;
  369. node.on("input", function (msg) {
  370. const oids = node.oids || msg.oid;
  371. const { host, sessionid, user, options } = prepareSnmpOptions(node, msg);
  372. const response = [];
  373. function feedCb(varbinds) {
  374. for (let i = 0; i < varbinds.length; i++) {
  375. if (SNMP.isVarbindError(varbinds[i])) {
  376. node.error(SNMP.varbindError(varbinds[i]), msg);
  377. } else {
  378. response.push({ oid: varbinds[i].oid, value: varbinds[i].value });
  379. }
  380. }
  381. }
  382. if (oids) {
  383. msg.oid = oids;
  384. let sess = openSession(sessionid, host, user, options);
  385. sess.on("error", function (err) {
  386. node.error(err, msg);
  387. })
  388. sess.subtree(msg.oid, maxRepetitions, feedCb, function (error) {
  389. if (error) {
  390. node.error(error.toString(), msg);
  391. } else {
  392. msg.payload = response;
  393. node.send(msg);
  394. }
  395. closeSession(sessionid);
  396. });
  397. } else {
  398. node.warn("No oid to search for");
  399. }
  400. });
  401. }
  402. RED.nodes.registerType("snmp subtree", SnmpSubtreeNode, {
  403. credentials: {
  404. username: { type: "text" },
  405. authkey: { type: "password" },
  406. privkey: { type: "password" }
  407. }
  408. });
  409. function SnmpWalkerNode(n) {
  410. const node = this;
  411. RED.nodes.createNode(node, n);
  412. initSnmpNode(node, n);
  413. node.oids = n.oids ? n.oids.replace(/\s/g, "") : ""
  414. const maxRepetitions = 20;
  415. node.on("input", function (msg) {
  416. const oids = node.oids || msg.oid;
  417. const { host, sessionid, user, options } = prepareSnmpOptions(node, msg);
  418. const response = [];
  419. function feedCb(varbinds) {
  420. for (let i = 0; i < varbinds.length; i++) {
  421. if (SNMP.isVarbindError(varbinds[i])) {
  422. node.error(SNMP.varbindError(varbinds[i]), msg);
  423. } else {
  424. response.push({ oid: varbinds[i].oid, value: varbinds[i].value });
  425. }
  426. }
  427. }
  428. if (oids) {
  429. msg.oid = oids;
  430. let sess = openSession(sessionid, host, user, options);
  431. sess.on("error", function (err) {
  432. node.error(err, msg);
  433. })
  434. sess.walk(msg.oid, maxRepetitions, feedCb, function (error) {
  435. if (error) {
  436. node.error(error.toString(), msg);
  437. } else {
  438. msg.payload = response;
  439. node.send(msg);
  440. }
  441. closeSession(sessionid);
  442. });
  443. } else {
  444. node.warn("No oid to search for");
  445. }
  446. });
  447. }
  448. RED.nodes.registerType("snmp walker", SnmpWalkerNode, {
  449. credentials: {
  450. username: { type: "text" },
  451. authkey: { type: "password" },
  452. privkey: { type: "password" }
  453. }
  454. });
  455. };