-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibsnmp.js
More file actions
1291 lines (1146 loc) · 38.9 KB
/
libsnmp.js
File metadata and controls
1291 lines (1146 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import snmp from 'net-snmp';
/**
* Libreria SNMP estesa con supporto LLDP/CDP/FDP/EDP (stile NeDi)
*/
class NetMapSNMP {
constructor(community = process.env.SNMP_COMMUNITY || 'public', options = {}) {
this.community = community;
this.defaultOptions = {
timeout: options.timeout || 3000,
retries: options.retries || 1,
version: snmp.Version2c,
...options,
};
}
/**
* Crea una sessione SNMP
*/
createSession(ip, customOptions = {}) {
return snmp.createSession(ip, this.community, {
...this.defaultOptions,
...customOptions,
});
}
/**
* Decodifica valore SNMP
*/
decodeValue(value) {
if (Buffer.isBuffer(value)) {
// MAC address (6 bytes)
if (value.length === 6) {
return Array.from(value)
.map((b) => b.toString(16).padStart(2, '0'))
.join(':');
}
// Prova ASCII
const txt = value.toString('utf8');
if (/^[\x20-\x7E]+$/.test(txt)) return txt;
return value.toString('hex');
}
if (value === null || value === undefined) return '';
return value.toString();
}
/**
* Walk SNMP subtree con timeout
*/
async walk(ip, oid, maxRepetitions = 20, timeout = 5000) {
return new Promise((resolve) => {
const session = this.createSession(ip);
const rows = [];
let completed = false;
// Timeout globale
const timeoutId = setTimeout(() => {
if (!completed) {
completed = true;
session.close();
resolve({ err: 'Timeout', rows: [] });
}
}, timeout);
session.subtree(
oid,
maxRepetitions,
(vb) => {
if (completed) return;
const list = Array.isArray(vb) ? vb : [vb];
for (const v of list) {
if (v?.oid) {
rows.push({ oid: v.oid, type: v.type, value: v.value });
}
}
},
(err) => {
if (completed) return;
completed = true;
clearTimeout(timeoutId);
session.close();
resolve({ err: err ? err.toString() : null, rows });
}
);
});
}
/**
* Get SNMP value
*/
async get(ip, oids) {
return new Promise((resolve) => {
const session = this.createSession(ip);
session.get(oids, (err, varbinds) => {
session.close();
if (err) {
resolve({ err: err.toString(), values: null });
} else {
resolve({ err: null, values: varbinds });
}
});
});
}
/**
* Ottieni sysName
*/
async getSysName(ip) {
const result = await this.get(ip, ['1.3.6.1.2.1.1.5.0']);
if (result.err || !result.values?.[0]?.value) return null;
return this.decodeValue(result.values[0].value);
}
/**
* Ottieni sysDescr
*/
async getSysDescr(ip) {
const result = await this.get(ip, ['1.3.6.1.2.1.1.1.0']);
if (result.err || !result.values?.[0]?.value) return null;
return this.decodeValue(result.values[0].value);
}
/**
* Ottieni sysUpTime
*/
async getSysUpTime(ip) {
const result = await this.get(ip, ['1.3.6.1.2.1.1.3.0']);
if (result.err || !result.values?.[0]?.value) return null;
return result.values[0].value;
}
/**
* Ottieni sysLocation
*/
async getSysLocation(ip) {
const result = await this.get(ip, ['1.3.6.1.2.1.1.6.0']);
if (result.err || !result.values?.[0]?.value) return null;
return this.decodeValue(result.values[0].value);
}
/**
* Ottieni sysObjectID (per identificare vendor/OS)
*/
async getSysObjectID(ip) {
const result = await this.get(ip, ['1.3.6.1.2.1.1.2.0']);
if (result.err || !result.values?.[0]?.value) return null;
return result.values[0].value.toString();
}
/**
* Parse LLDP RemTable (1.0.8802.1.1.2.1.4.1.1)
* Gestisce sia il formato standard che il formato Huawei con timeMark
*/
parseLLDPRemTable(vbs) {
const entries = {};
let debugCount = 0;
const OID_BASE = '1.0.8802.1.1.2.1.4.1.1';
const BASE_PARTS = OID_BASE.split('.').length; // 11
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const len = parts.length;
// L'OID deve essere almeno: base (11) + attr (1) + localPort (1) + remIndex (1) = 14
if (len < BASE_PARTS + 3) {
if (debugCount < 3) {
console.log(`[LLDP-PARSE] OID troppo corto (${len}, attesi almeno ${BASE_PARTS + 3}): ${vb.oid}`);
debugCount++;
}
continue;
}
// Verifica che l'OID inizi con la base
const oidBase = parts.slice(0, BASE_PARTS).join('.');
if (oidBase !== OID_BASE) {
if (debugCount < 3) {
console.log(`[LLDP-PARSE] OID base non corrisponde: ${oidBase} (atteso: ${OID_BASE})`);
debugCount++;
}
continue;
}
// Formati OID supportati:
// Standard (14 parti): 1.0.8802.1.1.2.1.4.1.1.ATTR.localPort.remIndex
// Huawei (15 parti): 1.0.8802.1.1.2.1.4.1.1.ATTR.timeMark.localPort.remIndex
const attr = parts[BASE_PARTS];
let localPort, remIndex;
// Huawei e alcuni vendor usano timeMark (valore numerico, non sempre 0)
// Euristica migliorata: timeMark è tipicamente 0 o valore alto (>512)
// localPort è tipicamente 1-512 (numero porte switch)
if (len >= BASE_PARTS + 4) {
// Formato con timeMark: ATTR.timeMark.localPort.remIndex
const candidateTimeMark = parseInt(parts[BASE_PARTS + 1]);
const candidateLocalPort = parseInt(parts[BASE_PARTS + 2]);
// Se primo valore è 0 o > 512 → è timeMark (formato Huawei)
// Se primo valore è 1-512 e secondo > 512 → formato ambiguo, usa standard
if (candidateTimeMark === 0 || candidateTimeMark > 512) {
// Formato Huawei con timeMark
localPort = parts[BASE_PARTS + 2];
remIndex = parts[BASE_PARTS + 3];
} else if (candidateLocalPort > 512 || len === BASE_PARTS + 4) {
// timeMark basso ma localPort alto → probabilmente timeMark=candidateTimeMark
localPort = parts[BASE_PARTS + 2];
remIndex = parts[BASE_PARTS + 3];
} else {
// Ambiguo: assume formato standard con dati extra
localPort = parts[BASE_PARTS + 1];
remIndex = parts[BASE_PARTS + 2];
}
} else if (len === BASE_PARTS + 3) {
// Formato standard: ATTR.localPort.remIndex
localPort = parts[BASE_PARTS + 1];
remIndex = parts[BASE_PARTS + 2];
} else {
continue; // OID non valido
}
const key = `${localPort}-${remIndex}`;
if (!entries[key]) {
entries[key] = { localPort, remIndex };
}
const entry = entries[key];
// Gestione corretta del TTL per evitare errori di buffer
const processValue = (value) => {
if (attr === '8' && typeof value === 'number') {
// TTL è già un numero
return value;
} else if (attr === '8' && Buffer.isBuffer(value)) {
// TTL come buffer - gestione sicura
try {
if (value.length >= 4) {
return value.readUInt32BE(0);
} else if (value.length >= 2) {
return value.readUInt16BE(0);
} else if (value.length >= 1) {
return value[0];
}
} catch (e) {
// In caso di errore, ritorna il valore decodificato
}
}
return this.decodeValue(value);
};
switch (attr) {
case '4': // chassisSubtype
entry.chassisSubtype = this.decodeValue(vb.value);
break;
case '5': // chassisId
entry.chassisId = this.decodeValue(vb.value);
break;
case '6': // portIdSubtype
entry.portSubtype = this.decodeValue(vb.value);
break;
case '7': // portId
entry.portId = this.decodeValue(vb.value);
break;
case '8': // portDesc (remote port description)
entry.portDesc = this.decodeValue(vb.value);
break;
case '9': // sysName
entry.sysName = this.decodeValue(vb.value);
break;
case '10': // sysDesc
entry.sysDesc = this.decodeValue(vb.value);
break;
case '11': // sysCap
entry.sysCap = this.decodeValue(vb.value);
break;
default:
if (debugCount < 5) {
console.log(`[LLDP-PARSE] Attributo sconosciuto: ${attr} (OID: ${vb.oid}, localPort=${localPort}, remIndex=${remIndex})`);
debugCount++;
}
break;
}
}
return Object.values(entries);
}
/**
* Parse LLDP RemManAddrTable (1.0.8802.1.1.2.1.4.2.1) - IP dei neighbor (METODO NEDI)
* Migliorato per Huawei: supporta sia formato standard che con timeMark
*/
parseLLDPRemManAddrTable(vbs) {
const ipMap = {}; // localPort-remIndex -> IP
let debugCount = 0;
const OID_BASE = '1.0.8802.1.1.2.1.4.2.1';
const BASE_PARTS = OID_BASE.split('.').length; // 11
const isByte = (val) => Number.isInteger(val) && val >= 0 && val <= 255;
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const len = parts.length;
// L'OID deve contenere almeno: base + attr + timeMark? + localPort + remIndex + addrSubtype + addrLen + addr
if (len < BASE_PARTS + 6) {
if (debugCount < 3) {
console.log(`[LLDP-IP] OID troppo corto (${len}): ${vb.oid}`);
debugCount++;
}
continue;
}
// Verifica che l'OID inizi con la base
const oidBase = parts.slice(0, BASE_PARTS).join('.');
if (oidBase !== OID_BASE) continue;
const attr = parts[BASE_PARTS];
// Pattern OID:
// Standard (19 parti): ...4.2.1.ATTR.localPort.remIndex.addrSubtype.addrLen.addr1.addr2.addr3.addr4
// Huawei (20 parti): ...4.2.1.ATTR.timeMark.localPort.remIndex.addrSubtype.addrLen.addr1.addr2.addr3.addr4
let localPort, remIndex, addrSubtype;
// Huawei usa timeMark (può essere 0 o altro valore numerico come 8949)
// Determina il formato in base alla lunghezza dell'OID
const hasTimeMark = len >= BASE_PARTS + 9;
if (hasTimeMark) {
// Formato Huawei con timeMark
localPort = parts[BASE_PARTS + 2];
remIndex = parts[BASE_PARTS + 3];
addrSubtype = parts[BASE_PARTS + 4];
} else if (len >= BASE_PARTS + 8) {
// Formato standard
localPort = parts[BASE_PARTS + 1];
remIndex = parts[BASE_PARTS + 2];
addrSubtype = parts[BASE_PARTS + 3];
} else {
continue;
}
// attr=4: lldpRemManAddrIfId (IP address)
// addrSubtype: 1=IPv4, 2=IPv6
if (attr === '4' && addrSubtype === '1') {
let ip = null;
// METODO 1: usa il buffer dell'OCTET STRING (preferito)
if (Buffer.isBuffer(vb.value) && vb.value.length >= 4) {
const bytes = Array.from(vb.value.slice(-4)).map(b => b & 0xff);
if (bytes.every(isByte)) {
ip = bytes.join('.');
}
} else if (typeof vb.value === 'string') {
// Alcuni vendor restituiscono stringhe "192.168.10.230" o "0A 0A 04 E6"
const matches = vb.value.match(/\d+/g);
if (matches && matches.length >= 4) {
const nums = matches.slice(-4).map(n => Number(n));
if (nums.every(isByte)) {
ip = nums.join('.');
}
}
}
// METODO 2: IP nell'OID (fallback) -> prendi sempre gli ultimi 4 segmenti
if (!ip) {
const suffix = parts.slice(-4).map(n => Number(n));
if (suffix.length === 4 && suffix.every(isByte)) {
ip = suffix.join('.');
} else if (len >= BASE_PARTS + 9) {
const addrOffset = hasTimeMark ? BASE_PARTS + 6 : BASE_PARTS + 5;
const addrParts = [];
for (let i = 0; i < 4; i++) {
const value = Number(parts[addrOffset + i]);
if (!isByte(value)) {
addrParts.length = 0;
break;
}
addrParts.push(value);
}
if (addrParts.length === 4) {
ip = addrParts.join('.');
}
}
}
if (ip) {
const key = `${localPort}-${remIndex}`;
ipMap[key] = ip;
if (debugCount < 5) {
console.log(`[LLDP-IP] Trovato IP ${ip} per localPort=${localPort}, remIndex=${remIndex} (timeMark=${hasTimeMark})`);
debugCount++;
}
} else if (debugCount < 5) {
console.log(`[LLDP-IP] Nessun IP valido per localPort=${localPort}, remIndex=${remIndex}, OID=${vb.oid}`);
debugCount++;
}
}
}
return ipMap;
}
/**
* Parse LLDP LocPortTable (1.0.8802.1.1.2.1.3.7.1)
*/
parseLLDPLocPortTable(vbs) {
const entries = {};
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const len = parts.length;
if (len < 2) continue;
const portNum = parts[len - 1];
const attr = parts[len - 2];
if (!entries[portNum]) {
entries[portNum] = { portNum };
}
const entry = entries[portNum];
switch (attr) {
case '3': // portId
entry.portId = this.decodeValue(vb.value);
break;
case '4': // portDesc
entry.portDesc = this.decodeValue(vb.value);
break;
default:
break;
}
}
return Object.values(entries);
}
/**
* Parse CDP (Cisco Discovery Protocol)
*/
parseCDP(vbs) {
const entries = {};
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
// CDP: 1.3.6.1.4.1.9.9.23.1.2.1.1.X.ifIndex
const len = parts.length;
if (len < 2) continue;
const ifIndex = parts[len - 1];
const attr = parts[len - 2];
if (!entries[ifIndex]) {
entries[ifIndex] = { ifIndex };
}
const entry = entries[ifIndex];
switch (attr) {
case '4': // cdpCacheDeviceId (sysName)
entry.sysName = this.decodeValue(vb.value);
break;
case '5': // cdpCacheDevicePort (portId)
entry.portId = this.decodeValue(vb.value);
break;
case '6': // cdpCachePlatform (sysDesc)
entry.sysDesc = this.decodeValue(vb.value);
break;
case '7': // cdpCacheAddress (IP)
if (Buffer.isBuffer(vb.value) && vb.value.length >= 4) {
entry.ip = Array.from(vb.value.slice(0, 4)).join('.');
}
break;
default:
break;
}
}
return Object.values(entries);
}
/**
* Parse FDP (Foundry Discovery Protocol) - Foundry/Brocade
* OID: 1.3.6.1.4.1.1991.1.1.1.1.1.1
*/
parseFDP(vbs) {
const entries = {};
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const len = parts.length;
if (len < 2) continue;
const ifIndex = parts[len - 1];
const attr = parts[len - 2];
if (!entries[ifIndex]) {
entries[ifIndex] = { ifIndex };
}
const entry = entries[ifIndex];
// FDP ha struttura simile a CDP
switch (attr) {
case '2': // fdpRemChassisId
entry.chassisId = this.decodeValue(vb.value);
break;
case '3': // fdpRemPortId
entry.portId = this.decodeValue(vb.value);
break;
case '4': // fdpRemSysName
entry.sysName = this.decodeValue(vb.value);
break;
default:
break;
}
}
return Object.values(entries);
}
/**
* Parse EDP (Extreme Discovery Protocol) - Extreme Networks
* OID: 1.3.6.1.4.1.1916.1.7.1.1.1
*/
parseEDP(vbs) {
const entries = {};
for (const vb of vbs) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const len = parts.length;
if (len < 2) continue;
const ifIndex = parts[len - 1];
const attr = parts[len - 2];
if (!entries[ifIndex]) {
entries[ifIndex] = { ifIndex };
}
const entry = entries[ifIndex];
switch (attr) {
case '2': // edpRemChassisId
entry.chassisId = this.decodeValue(vb.value);
break;
case '3': // edpRemPortId
entry.portId = this.decodeValue(vb.value);
break;
case '4': // edpRemSysName
entry.sysName = this.decodeValue(vb.value);
break;
default:
break;
}
}
return Object.values(entries);
}
/**
* Discovery completo protocolli (LLDP/CDP/FDP/EDP) con timeout per ogni operazione
*/
async discoverProtocols(ip, timeout = 5000) {
const result = {
ip,
sysName: null,
sysDescr: null,
sysUpTime: null,
sysLocation: null,
sysObjectID: null,
lldp: [],
cdp: [],
fdp: [],
edp: [],
protocols: [],
};
try {
// Informazioni base sistema (con timeout breve)
const [sysName, sysDescr, sysUpTime, sysLocation, sysObjectID] = await Promise.allSettled([
this.getSysName(ip),
this.getSysDescr(ip),
this.getSysUpTime(ip),
this.getSysLocation(ip),
this.getSysObjectID(ip),
]);
result.sysName = sysName.status === 'fulfilled' ? sysName.value : null;
result.sysDescr = sysDescr.status === 'fulfilled' ? sysDescr.value : null;
result.sysUpTime = sysUpTime.status === 'fulfilled' ? sysUpTime.value : null;
result.sysLocation = sysLocation.status === 'fulfilled' ? sysLocation.value : null;
result.sysObjectID = sysObjectID.status === 'fulfilled' ? sysObjectID.value : null;
// Inizializza array errori per tracciamento
result.errors = [];
// LLDP (timeout gestito internamente da walk())
try {
const lldpRem = await this.walk(ip, '1.0.8802.1.1.2.1.4.1.1', 20, timeout);
if (!lldpRem.err && lldpRem.rows.length > 0) {
result.lldp = this.parseLLDPRemTable(lldpRem.rows);
result.protocols.push('LLDP');
} else if (lldpRem.err) {
result.errors.push({ operation: 'lldp_rem', error: lldpRem.err });
}
} catch (err) {
result.errors.push({ operation: 'lldp_rem', error: err.message });
}
// LLDP LocPortTable (mapping porte) - opzionale
try {
const lldpLoc = await this.walk(ip, '1.0.8802.1.1.2.1.3.7.1', 20, timeout);
if (!lldpLoc.err && lldpLoc.rows.length > 0) {
result.lldpLoc = this.parseLLDPLocPortTable(lldpLoc.rows);
}
} catch (err) {
// LocPortTable opzionale - non tracciare errore
}
// LLDP RemManAddrTable (1.0.8802.1.1.2.1.4.2.1) - IP dei neighbor (METODO NEDI)
try {
const lldpRemManAddr = await this.walk(ip, '1.0.8802.1.1.2.1.4.2.1', 20, timeout);
if (!lldpRemManAddr.err && lldpRemManAddr.rows.length > 0) {
const ipMap = this.parseLLDPRemManAddrTable(lldpRemManAddr.rows);
console.log(`[LLDP-IP] ${ip}: Trovati ${Object.keys(ipMap).length} IP in RemManAddrTable`);
let ipAssigned = 0;
result.lldp.forEach(neighbor => {
const key = `${neighbor.localPort}-${neighbor.remIndex}`;
if (ipMap[key]) {
neighbor.ip = ipMap[key];
ipAssigned++;
}
});
console.log(`[LLDP-IP] ${ip}: Assegnati ${ipAssigned} IP ai neighbor (su ${result.lldp.length} totali)`);
} else {
console.log(`[LLDP-IP] ${ip}: RemManAddrTable vuota o errore (rows=${lldpRemManAddr?.rows?.length || 0})`);
}
} catch (err) {
console.log(`[LLDP-IP] ${ip}: Errore lettura RemManAddrTable: ${err.message}`);
result.errors.push({ operation: 'lldp_rem_man_addr', error: err.message });
}
// CDP (Cisco)
try {
const cdp = await this.walk(ip, '1.3.6.1.4.1.9.9.23.1.2.1.1', 20, timeout);
if (!cdp.err && cdp.rows.length > 0) {
result.cdp = this.parseCDP(cdp.rows);
result.protocols.push('CDP');
}
} catch (err) {
// CDP opzionale - non tracciare errore
}
// FDP (Foundry/Brocade)
try {
const fdp = await this.walk(ip, '1.3.6.1.4.1.1991.1.1.1.1.1.1', 20, timeout);
if (!fdp.err && fdp.rows.length > 0) {
result.fdp = this.parseFDP(fdp.rows);
result.protocols.push('FDP');
}
} catch (err) {
// FDP opzionale - non tracciare errore
}
// EDP (Extreme)
try {
const edp = await this.walk(ip, '1.3.6.1.4.1.1916.1.7.1.1.1', 20, timeout);
if (!edp.err && edp.rows.length > 0) {
result.edp = this.parseEDP(edp.rows);
result.protocols.push('EDP');
}
} catch (err) {
// EDP opzionale - non tracciare errore
}
} catch (err) {
result.errors = result.errors || [];
result.errors.push({ operation: 'general', error: err.message });
}
return result;
}
/**
* Ottieni ARP table
*/
async getARPTable(ip) {
const arp = await this.walk(ip, '1.3.6.1.2.1.4.22.1');
if (arp.err || !arp.rows.length) return [];
const entries = [];
const arpMap = {};
for (const vb of arp.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
// ARP: 1.3.6.1.2.1.4.22.1.2.ifIndex.ip
const len = parts.length;
if (len < 3) continue;
const ipAddr = parts.slice(-4).join('.');
const ifIndex = parts[len - 5];
const attr = parts[len - 6];
const key = `${ifIndex}-${ipAddr}`;
if (!arpMap[key]) {
arpMap[key] = { ifIndex: parseInt(ifIndex), ip: ipAddr };
}
if (attr === '2') {
// atPhysAddress
arpMap[key].mac = this.decodeValue(vb.value);
}
}
return Object.values(arpMap);
}
/**
* Ottieni mappatura bridge port → ifIndex
* Necessaria perché su switch stack (es. Huawei) bridge port ≠ ifIndex
* OID: dot1dBasePortIfIndex (1.3.6.1.2.1.17.1.4.1.2)
*/
async getBridgePortMapping(ip) {
const mapping = {};
const result = await this.walk(ip, '1.3.6.1.2.1.17.1.4.1.2');
if (result.err || !result.rows.length) {
return mapping; // Ritorna mapping vuoto, useremo bridge port direttamente come fallback
}
for (const vb of result.rows) {
if (!vb?.oid) continue;
// OID format: 1.3.6.1.2.1.17.1.4.1.2.<bridgePort> = <ifIndex>
const parts = vb.oid.split('.');
const bridgePort = parseInt(parts[parts.length - 1]);
const ifIndex = parseInt(vb.value);
mapping[bridgePort] = ifIndex;
}
return mapping;
}
/**
* Ottieni FDB (Forwarding Database / MAC table)
* NOTA: Usa getBridgePortMapping per convertire bridge port → ifIndex reale
*/
async getFDBTable(ip) {
// Prima ottieni la mappatura bridge port → ifIndex
const bridgePortMap = await this.getBridgePortMapping(ip);
const hasBridgeMapping = Object.keys(bridgePortMap).length > 0;
// Bridge MIB: 1.3.6.1.2.1.17.4.3.1
const fdb = await this.walk(ip, '1.3.6.1.2.1.17.4.3.1');
if (fdb.err || !fdb.rows.length) return [];
const fdbMap = {};
for (const vb of fdb.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
// FDB: 1.3.6.1.2.1.17.4.3.1.2.vlan.mac
const len = parts.length;
if (len < 8) continue;
const mac = parts.slice(-6).map((p) => parseInt(p).toString(16).padStart(2, '0')).join(':');
const vlan = parts[len - 7];
const attr = parts[len - 8];
const key = `${vlan}-${mac}`;
if (!fdbMap[key]) {
fdbMap[key] = { vlan: parseInt(vlan), mac };
}
if (attr === '2') {
// dot1dTpFdbPort - questo è il BRIDGE PORT, non l'ifIndex!
const bridgePort = parseInt(vb.value);
// Converti bridge port → ifIndex usando la mappatura
// Se la mappatura esiste, usala; altrimenti usa bridge port come fallback
if (hasBridgeMapping && bridgePortMap[bridgePort]) {
fdbMap[key].ifIndex = bridgePortMap[bridgePort];
fdbMap[key].bridgePort = bridgePort; // Salva anche il bridge port originale per debug
} else {
fdbMap[key].ifIndex = bridgePort; // Fallback: usa bridge port come ifIndex
fdbMap[key].bridgePort = bridgePort;
}
}
}
return Object.values(fdbMap);
}
/**
* Ottieni interfaces (IF-MIB)
*/
async getInterfaces(ip) {
const ifTable = await this.walk(ip, '1.3.6.1.2.1.2.2.1');
if (ifTable.err || !ifTable.rows.length) return [];
const interfaces = {};
for (const vb of ifTable.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const ifIndex = parts[parts.length - 1];
const attr = parts[parts.length - 2];
if (!interfaces[ifIndex]) {
interfaces[ifIndex] = { ifIndex: parseInt(ifIndex) };
}
const iface = interfaces[ifIndex];
switch (attr) {
case '2': // ifDescr
iface.ifDescr = this.decodeValue(vb.value);
break;
case '3': // ifType
iface.ifType = vb.value;
break;
case '5': // ifSpeed
iface.ifSpeed = vb.value;
break;
case '7': // ifAdminStatus
iface.ifAdminStatus = vb.value;
break;
case '8': // ifOperStatus
iface.ifOperStatus = vb.value;
break;
case '6': // ifPhysAddress
iface.ifPhysAddress = this.decodeValue(vb.value);
break;
default:
break;
}
}
return Object.values(interfaces);
}
/**
* Ottieni interfaces estese (IF-MIB + ifXTable per ifName, ifAlias, ifHighSpeed)
*/
async getInterfacesExtended(ip) {
const interfaces = await this.getInterfaces(ip);
const ifXTable = await this.walk(ip, '1.3.6.1.2.1.31.1.1.1');
if (!ifXTable.err && ifXTable.rows.length) {
const ifMap = {};
interfaces.forEach(iface => { ifMap[iface.ifIndex] = iface; });
for (const vb of ifXTable.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const ifIndex = parts[parts.length - 1];
const attr = parts[parts.length - 2];
if (!ifMap[ifIndex]) continue;
const iface = ifMap[ifIndex];
switch (attr) {
case '1': // ifName
iface.ifName = this.decodeValue(vb.value);
break;
case '15': // ifHighSpeed (Mbps)
iface.ifHighSpeed = vb.value;
break;
case '18': // ifAlias
iface.ifAlias = this.decodeValue(vb.value);
break;
default:
break;
}
}
}
return interfaces;
}
/**
* Ottieni VLAN (Q-BRIDGE-MIB)
* OID: 1.3.6.1.2.1.17.7.1.4.3.1 (dot1qVlanStaticTable)
*/
async getVLANs(ip) {
const vlans = [];
// dot1qVlanStaticName (1.3.6.1.2.1.17.7.1.4.3.1.1)
const vlanNames = await this.walk(ip, '1.3.6.1.2.1.17.7.1.4.3.1.1');
if (!vlanNames.err && vlanNames.rows.length) {
for (const vb of vlanNames.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const vlanId = parseInt(parts[parts.length - 1]);
vlans.push({
vlanId,
vlanName: this.decodeValue(vb.value),
status: 'active',
});
}
}
// Fallback: vtpVlanTable per Cisco (1.3.6.1.4.1.9.9.46.1.3.1.1)
if (vlans.length === 0) {
const vtpVlans = await this.walk(ip, '1.3.6.1.4.1.9.9.46.1.3.1.1.4');
if (!vtpVlans.err && vtpVlans.rows.length) {
for (const vb of vtpVlans.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const vlanId = parseInt(parts[parts.length - 1]);
vlans.push({
vlanId,
vlanName: this.decodeValue(vb.value),
status: 'active',
});
}
}
}
return vlans;
}
/**
* Ottieni VLAN membership per porta (Q-BRIDGE-MIB)
* OID: 1.3.6.1.2.1.17.7.1.4.5.1.1 (dot1qPvid - PVID per porta)
*/
async getPortVLANs(ip) {
const portVlans = [];
// dot1qPvid (PVID - native VLAN)
const pvid = await this.walk(ip, '1.3.6.1.2.1.17.7.1.4.5.1.1');
if (!pvid.err && pvid.rows.length) {
for (const vb of pvid.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const portIndex = parseInt(parts[parts.length - 1]);
portVlans.push({
portIndex,
pvid: vb.value,
tagged: [],
});
}
}
// dot1qVlanCurrentEgressPorts (porte tagged per VLAN)
const egressPorts = await this.walk(ip, '1.3.6.1.2.1.17.7.1.4.2.1.4');
if (!egressPorts.err && egressPorts.rows.length) {
for (const vb of egressPorts.rows) {
if (!vb?.oid) continue;
const parts = vb.oid.split('.');
const vlanId = parseInt(parts[parts.length - 1]);
// Bitmap delle porte
if (Buffer.isBuffer(vb.value)) {
for (let i = 0; i < vb.value.length; i++) {
const byte = vb.value[i];
for (let bit = 0; bit < 8; bit++) {
if (byte & (1 << (7 - bit))) {
const portIndex = i * 8 + bit + 1;
const port = portVlans.find(p => p.portIndex === portIndex);
if (port && !port.tagged.includes(vlanId)) {
port.tagged.push(vlanId);
}
}
}
}
}
}
}
return portVlans;
}
/**
* Ottieni STP info (BRIDGE-MIB)
* OID: 1.3.6.1.2.1.17.2 (dot1dStp)
*/
async getSTPInfo(ip) {
const stp = {
protocolSpecification: null, // 1=unknown, 2=decLb100, 3=ieee8021d
priority: null,
rootBridge: null,
rootPort: null,
rootCost: null,
maxAge: null,
helloTime: null,
forwardDelay: null,
};
const stpScalars = [
'1.3.6.1.2.1.17.2.1.0', // dot1dStpProtocolSpecification
'1.3.6.1.2.1.17.2.2.0', // dot1dStpPriority
'1.3.6.1.2.1.17.2.5.0', // dot1dStpDesignatedRoot
'1.3.6.1.2.1.17.2.6.0', // dot1dStpRootCost
'1.3.6.1.2.1.17.2.7.0', // dot1dStpRootPort
'1.3.6.1.2.1.17.2.8.0', // dot1dStpMaxAge
'1.3.6.1.2.1.17.2.9.0', // dot1dStpHelloTime
'1.3.6.1.2.1.17.2.10.0', // dot1dStpForwardDelay
];
const result = await this.get(ip, stpScalars);
if (!result.err && result.values) {
result.values.forEach((vb, idx) => {
if (!vb?.value) return;
switch (idx) {
case 0: stp.protocolSpecification = vb.value; break;
case 1: stp.priority = vb.value; break;
case 2: stp.rootBridge = this.decodeValue(vb.value); break;
case 3: stp.rootCost = vb.value; break;
case 4: stp.rootPort = vb.value; break;
case 5: stp.maxAge = vb.value / 100; break; // centiseconds
case 6: stp.helloTime = vb.value / 100; break;
case 7: stp.forwardDelay = vb.value / 100; break;