make dict_key match new Enterasys entries
[racktables-contribs] / snmpgeneric.php
1 <?php
2
3 /********************************************
4 *
5 * RackTables 0.20.x snmpgeneric extension
6 *
7 * sync an RackTables object with an SNMP device.
8 *
9 * Should work with almost any SNMP capable device.
10 *
11 * reads SNMP tables:
12 * - system
13 * - ifTable
14 * - ifxTable
15 * - ipAddrTable (ipv4 only)
16 * - ipAddressTable (ipv4 + ipv6)
17 *
18 * Features:
19 * - update object attributes
20 * - create networks
21 * - create ports
22 * - add and bind ip addresses
23 *
24 * Known to work with:
25 * - Enterasys SecureStacks, S-Series
26 * - cisco 2620XM (thx to Rob)
27 * - hopefully many others
28 *
29 *
30 * Usage:
31 *
32 * 1. select "SNMP generic sync" tap
33 * 2. select your SNMP config (host, v1, v2c or v3, ...)
34 * 3. hit "Show List"
35 * 4. you will see a selection of all information that could be retrieved
36 * 5. select what should be updated and/or created
37 * 6. hit "Create" Button to make changes to RackTables
38 * 7. repeat step 1. to 6. as often as you like / need
39 *
40 *
41 * needs PHP 5
42 *
43 * TESTED on FreeBSD 9.0, nginx/1.0.12, php 5.3.10, NET-SNMP 5.7.1
44 * and RackTables <= 0.20.3
45 *
46 * (c)2012,2013 Maik Ehinger <m.ehinger@ltur.de>
47 */
48
49 /****
50 * INSTALL
51 *
52 * add to inc/local.php
53 * include 'inc/snmpgeneric.php';
54 *
55 * or create inc/local.php with content
56 *
57 * <?php
58 * include 'inc/snmpgeneric.php';
59 * ?>
60 *
61 */
62
63 /**
64 * The newest version of this plugin can be found at:
65 *
66 * https://github.com/github138/myRT-contribs/tree/develop-0.20.x
67 *
68 */
69
70 /* TODOs
71 *
72 * - code cleanup
73 *
74 * - update visible label on ifAlias change !?
75 *
76 * - test if device supports mibs
77 * - gethostbyaddr / gethostbyname host list
78 * - correct iif_name display if != 1
79 *
80 * - set more Object attributs / fields
81 *
82 */
83
84 require_once('inc/snmp.php');
85
86 $tab['object']['snmpgeneric'] = 'SNMP Generic sync';
87 $tabhandler['object']['snmpgeneric'] = 'snmpgeneric_tabhandler';
88 //$trigger['object']['snmpgeneric'] = 'snmpgeneric_tabtrigger';
89
90 $ophandler['object']['snmpgeneric']['create'] = 'snmpgeneric_opcreate';
91
92 /* snmptranslate command */
93 $sg_cmd_snmptranslate = '/usr/local/bin/snmptranslate';
94
95 /* create ports without connector */
96 $sg_create_noconnector_ports = FALSE;
97
98 /* deselect add port for this snmp port types */
99 $sg_ifType_ignore = array(
100 '1', /* other */
101 '24', /* softwareLoopback */
102 '23', /* ppp */
103 '33', /* rs232 */
104 '34', /* para */
105 '53', /* propVirtual */
106 '77', /* lapd */
107 '131', /* tunnel */
108 '136', /* l3ipvlan */
109 '160', /* usb */
110 '161', /* ieee8023adLag */
111 );
112
113 /* ifType to RT oif_id mapping */
114 $sg_ifType2oif_id = array(
115 /* 440 causes SQLSTATE[23000]: Integrity constraint violation:
116 * 1452 Cannot add or update a child row:
117 * a foreign key constraint fails
118 */
119 // '1' => 440, /* other => unknown 440 */
120 '1' => 1469, /* other => virutal port 1469 */
121 '6' => 24, /* ethernetCsmacd => 1000BASE-T 24 */
122 '24' => 1469, /* softwareLoopback => virtual port 1469 */
123 '33' => 1469, /* rs232 => RS-232 (DB-9) 681 */
124 '34' => 1469, /* para => virtual port 1469 */
125 '53' => 1469, /* propVirtual => virtual port 1469 */
126 '62' => 1195, /* fastEther => 100BASE-FX 1195 */
127 '131' => 1469, /* tunnel => virtual port 1469 */
128 '136' => 1469, /* l3ipvlan => virtual port 1469 */
129 '160' => 1469, /* usb => virtual port 1469 */
130 '161' => 1469, /* ieee8023adLag => virtual port 1469 */
131 );
132
133 /* -------------------------------------------------- */
134
135 /* snmp vendor list http://www.iana.org/assignments/enterprise-numbers */
136
137 $sg_known_sysObjectIDs = array
138 (
139 /* ------------ default ------------ */
140 'default' => array
141 (
142 // 'text' => 'default',
143 'pf' => array('snmpgeneric_pf_entitymib'),
144 'attr' => array
145 (
146 2 => array('pf' => 'snmpgeneric_pf_hwtype'), /* HW Typ*/
147 3 => array('oid' => 'sysName.0'),
148 /* FQDN check only if regex matches */
149 //3 => array('oid' => 'sysName.0', 'regex' => '/^[^ .]+(\.[^ .]+)+\.?/', 'uncheck' => 'no FQDN'),
150 4 => array('pf' => 'snmpgeneric_pf_swtype', 'uncheck' => 'experimental'), /* SW type */
151 14 => array('oid' => 'sysContact.0'), /* Contact person */
152 // 1235 => array('value' => 'Constant'),
153 ),
154 'port' => array
155 (
156 // 'AC-in' => array('porttypeid' => '1-16', 'uncheck' => 'uncheck reason/comment'),
157 // 'name' => array('porttypeid' => '1-24', 'ifDescr' => 'visible label'),
158 ),
159 ),
160
161 /* ------------ ciscoSystems --------------- */
162 /* '9' => array
163 * (
164 * 'text' => 'ciscoSystems',
165 * ),
166 */
167 '9.1' => array
168 (
169 'text' => 'ciscoProducts',
170 'attr' => array(
171 4 => array('pf' => 'snmpgeneric_pf_catalyst'), /* SW type/version */
172 16 => array('pf' => 'snmpgeneric_pf_ciscoflash'), /* flash memory */
173
174 ),
175
176 ),
177 /* ------------ Microsoft --------------- */
178 '311' => array
179 (
180 'text' => 'Microsoft',
181 'attr' => array(
182 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/.* Windows Version (.*?) .*/', 'replacement' => 'Windows \\1', 'uncheck' => 'TODO RT matching'), /*SW type */
183 ),
184 ),
185 /* ------------ Enterasys --------------- */
186 '5624' => array
187 (
188 'text' => 'Enterasys',
189 'attr' => array(
190 4 => array('pf' => 'snmpgeneric_pf_enterasys'), /* SW type/version */
191 ),
192 ),
193
194 /* Enterasys N3 */
195 '5624.2.1.53' => array
196 (
197 'dict_key' => 2021,
198 'text' => 'Matrix N3',
199 ),
200
201 '5624.2.2.284' => array
202 (
203 'dict_key' => 50002,
204 'text' => 'Securestack C2',
205 ),
206
207 '5624.2.1.98' => array
208 (
209 'dict_key' => 50002,
210 'text' => 'Securestack C3',
211 ),
212
213 '5624.2.1.100' => array
214 (
215 'dict_key' => 50002,
216 'text' => 'Securestack B3',
217 ),
218
219 '5624.2.1.128' => array
220 (
221 'dict_key' => 1970,
222 'text' => 'S-series SSA130',
223 ),
224
225 '5624.2.1.129' => array
226 (
227 'dict_key' => 1970,
228 'text' => 'S-series SSA150',
229 ),
230
231 '5624.2.1.137' => array
232 (
233 'dict_key' => 1987,
234 'text' => 'Securestack B5 POE',
235 ),
236
237 /* S3 */
238 '5624.2.1.131' => array
239 (
240 'dict_key' => 1974,
241 'text' => 'S-series S3',
242 ),
243
244 /* S4 */
245 '5624.2.1.132' => array
246 (
247 'dict_key' => 1975,
248 'text' => 'S-series S4'
249 ),
250
251 /* S8 */
252 '5624.2.1.133' => array
253 (
254 'dict_key' => 1977,
255 'text' => 'S-series S8'
256 ),
257
258 '5624.2.1.165' => array
259 (
260 'dict_key' => 1971,
261 'text' => 'S-series Bonded SSA',
262 ),
263
264 /* ------------ net-snmp --------------- */
265 '8072' => array
266 (
267 'text' => 'net-snmp',
268 'attr' => array(
269 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/(.*?) .*? (.*?) .*/', 'replacement' => '\\1 \\2', 'uncheck' => 'TODO RT matching'), /*SW type */
270 ),
271 ),
272
273 /* ------------ Frauenhofer FOKUS ------------ */
274 '12325' => array
275 (
276 'text' => 'Fraunhofer FOKUS',
277 'attr' => array(
278 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/.*? .*? (.*? .*).*/', 'replacement' => '\\1', 'uncheck' => 'TODO RT matching'), /*SW type */
279 ),
280 ),
281
282 '12325.1.1.2.1.1' => array
283 (
284 'dict_key' => 42, /* Server model noname/unknown */
285 'text' => 'BSNMP - mini SNMP daemon (bsnmpd)',
286 ),
287
288 ) + $known_switches;
289 /* add snmp.php known_switches */
290
291 /* ------------ Sample function --------------- */
292 /*
293 * Sample Precessing Function (pf)
294 */
295 function snmpgeneric_pf_sample(&$snmp, &$sysObjectID, $attr_id) {
296
297 $object = &$sysObjectID['object'];
298 $attr = &$sysObjectID['attr'][$attr_id];
299
300 if(!isset($attr['oid']))
301 return;
302
303 /* output success banner */
304 showSuccess('Found sysObjectID '.$sysObjectID['value']);
305
306 /* access attribute oid setting and do snmpget */
307 $oid = $attr['oid'];
308 $value = $snmp->get($oid);
309
310 /* set new attribute value */
311 $attr['value'] = $value;
312
313 /* do not check attribute per default */
314 $attr['uncheck'] = "comment";
315
316 /* set informal comment */
317 $attr['comment'] = "comment";
318
319 /* add additional ports */
320 // $sysObjectID['port']['name'] = array('porttypeid' => '1-24', 'ifPhysAddress' => '001122334455', 'ifDescr' => 'visible label', 'uncheck' => 'comment', 'disabled' => 'porttypeid select disabled');
321
322 /* set other attribute */
323 // $sysObjectID['attr'][1234]['value'] = 'attribute value';
324
325 } /* snmpgeneric_pf_sample */
326
327 /* ------------ Enterasys --------------- */
328
329 function snmpgeneric_pf_enterasys(&$snmp, &$sysObjectID, $attr_id) {
330
331 $attrs = &$sysObjectID['attr'];
332
333 //snmpgeneric_pf_entitymib($snmp, $sysObjectID, $attr_id);
334
335 /* TODO find correct way to get Bootroom and Firmware versions */
336
337 /* Model */
338 /*if(preg_match('/.*\.([^.]+)$/', $sysObjectID['value'], $matches)) {
339 * showNotice('Device '.$matches[1]);
340 *}
341 */
342
343 /* TODO SW type */
344 //$attrs[4]['value'] = 'Enterasys'; /* SW type */
345
346 /* set SW version only if not already set by entitymib */
347 if(isset($attrs[5]['value']) && !empty($attrs[5]['value'])) {
348
349 /* SW version from sysDescr */
350 if(preg_match('/^Enterasys .* Inc\. (.+) [Rr]ev ([^ ]+) ?(.*)$/', $snmp->sysDescr, $matches)) {
351
352 $attrs[5]['value'] = $matches[2]; /* SW version */
353
354 // showSuccess("Found Enterasys Model ".$matches[1]);
355 }
356
357 } /* SW version */
358
359 /* add serial port */
360 //$sysObjectID['port']['console'] = array('porttypeid' => '1-29', 'ifDescr' => 'console', 'disabled' => 'disabled');
361
362 }
363
364 /* ------------ Cisco --------------- */
365
366 /* logic from snmp.php */
367 function snmpgeneric_pf_catalyst(&$snmp, &$sysObjectID, $attr_id) {
368 $attrs = &$sysObjectID['attr'];
369 $ports = &$sysObjectID['port'];
370
371 /* sysDescr multiline on C5200 */
372 if(preg_match ('/.*, Version ([^ ]+), .*/', $snmp->sysDescr, $matches)) {
373 $exact_release = $matches[1];
374 $major_line = preg_replace ('/^([[:digit:]]+\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
375
376 $ios_codes = array
377 (
378 '12.0' => 244,
379 '12.1' => 251,
380 '12.2' => 252,
381 );
382
383 $attrs[5]['value'] = $exact_release;
384
385 if (array_key_exists ($major_line, $ios_codes))
386 $attrs[4]['value'] = $ios_codes[$major_line];
387
388 } /* sw type / version */
389
390 $sysChassi = $snmp->get ('1.3.6.1.4.1.9.3.6.3.0');
391 if ($sysChassi !== FALSE or $sysChassi !== NULL)
392 $attrs[1]['value'] = str_replace ('"', '', $sysChassi);
393
394 $ports['con0'] = array('porttypeid' => '1-29', 'ifDescr' => 'console'); // RJ-45 RS-232 console
395
396 if (preg_match ('/Cisco IOS Software, C2600/', $snmp->sysDescr))
397 $ports['aux0'] = array('porttypeid' => '1-29', 'ifDescr' => 'auxillary'); // RJ-45 RS-232 aux port
398
399 // blade devices are powered through internal circuitry of chassis
400 if ($sysObjectID['value'] != '9.1.749' and $sysObjectID['value'] != '9.1.920')
401 {
402 $ports['AC-in'] = array('porttypeid' => '1-16');
403 }
404
405 } /* snmpgeneric_pf_catalyst */
406
407 /* -------------------------------------------------- */
408 function snmpgeneric_pf_ciscoflash(&$snmp, &$sysObjectID, $attr_id) {
409 /*
410 * ciscoflashMIB = 1.3.6.1.4.1.9.9.10
411 */
412 /*
413 | 16 | uint | flash memory, MB |
414 */
415 $attrs = &$sysObjectID['attr'];
416
417 $ciscoflash = $snmp->walk('1.3.6.1.4.1.9.9.10.1.1.2'); /* ciscoFlashDeviceTable */
418
419 $flash = array_keys($ciscoflash, 'flash');
420
421 foreach($flash as $oid) {
422 if(!preg_match('/(.*)?\.[^\.]+\.([^\.]+)$/',$oid,$matches))
423 continue;
424
425 $index = $matches[2];
426 $prefix = $matches[1];
427
428 showSuccess("Found Flash: ".$ciscoflash[$prefix.'.8.'.$index]." ".$ciscoflash[$prefix.'.2.'.$index]." bytes");
429
430 $attrs[16]['value'] = ceil($ciscoflash[$prefix.'.2.'.$index] / 1024 / 1024); /* ciscoFlashDeviceSize */
431
432 }
433
434 /*
435 * ciscoMemoryPoolMIB = 1.3.6.1.4.1.9.9.48
436 * ciscoMemoryPoolUsed .1.1.1.5
437 * ciscoMemoryPoolFree .1.1.1.6
438 */
439
440 $ciscomem = $snmp->walk('1.3.6.1.4.1.9.9.48');
441
442 if(!empty($ciscomem)) {
443
444 $used = 0;
445 $free = 0;
446
447 foreach($ciscomem as $oid => $value) {
448
449 switch(preg_replace('/.*?(\.1\.1\.1\.[^\.]+)\.[^\.]+$/','\\1',$oid)) {
450 case '.1.1.1.5':
451 $used += $value;
452 break;
453 case '.1.1.1.6':
454 $free += $value;
455 break;
456 }
457
458 }
459
460 $attrs[17]['value'] = ceil(($free + $used) / 1024 / 1024); /* RAM, MB */
461 }
462
463 } /* snmpgeneric_pf_ciscoflash */
464
465 /* -------------------------------------------------- */
466 /* -------------------------------------------------- */
467
468 /* HW Type processor function */
469 function snmpgeneric_pf_hwtype(&$snmp, &$sysObjectID, $attr_id) {
470
471 $attr = &$sysObjectID['attr'][$attr_id];
472
473 if (isset($sysObjectID['dict_key'])) {
474
475 $value = $sysObjectID['dict_key'];
476 showSuccess("Found HW type dict_key: $value");
477
478 /* return array of attr_id => attr_value) */
479 $attr['value'] = $value;
480
481 } else {
482 showNotice("HW type dict_key not set - Unknown OID");
483 }
484
485 } /* snmpgeneric_pf_hwtype */
486
487 /* -------------------------------------------------- */
488
489 /* SW type processor function */
490 /* experimental */
491 /* Find a way to match RT SW types !? */
492 function snmpgeneric_pf_swtype(&$snmp, &$sysObjectID, $attr_id) {
493
494 /* 4 = SW type */
495
496 $attr = &$sysObjectID['attr'][$attr_id];
497
498 $object = &$sysObjectID['object'];
499
500 $objtype_id = $object['objtype_id'];
501
502 if(isset($attr['oid']))
503 $oid = $attr['oid'];
504 else
505 $oid = 'sysDescr.0';
506
507 $raw_value = $snmp->get($oid);
508
509 $replacement = '\\1';
510
511 if(isset($attr['regex'])) {
512 $regex = $attr['regex'];
513
514 if(isset($attr['replacement']))
515 $replacement = $attr['replacement'];
516
517 } else {
518 $list = array('bsd','linux','centos','suse','fedora','ubuntu','windows','solaris','vmware');
519
520 $regex = '/.* ([^ ]*('.implode($list,'|').')[^ ]*) .*/i';
521 $replacement = '\\1';
522 }
523
524 $value = preg_replace($regex, $replacement, $raw_value, -1, $count);
525 //$attr['value'] = $value;
526
527 if(!empty($value) && $count > 0) {
528 /* search dict_key for value in RT Dictionary */
529 /* depends on object type server(13)/switch(14)/router(15) */
530 $result = usePreparedSelectBlade
531 (
532 'SELECT dict_key,dict_value FROM Dictionary WHERE chapter_id in (13,14,15) and dict_value like ? order by dict_key desc limit 1',
533 array ('%'.$value.'%')
534 );
535 $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
536
537 if(!empty($row)) {
538 $RTvalue = key($row);
539
540 if(isset($attr['comment']))
541 $attr['comment'] .= ", $value ($RTvalue) ".$row[$RTvalue];
542 else
543 $attr['comment'] = "$value ($RTvalue) ".$row[$RTvalue];
544
545 showSuccess("Found SW type: $value ($RTvalue) ".$row[$RTvalue]);
546 $value = $RTvalue;
547 }
548
549 /* set attr value */
550 $attr['value'] = $value;
551 // unset($attr['uncheck']);
552
553 }
554
555 if(isset($attr['comment']))
556 $attr['comment'] .= ' (experimental)';
557 else
558 $attr['comment'] = '(experimental)';
559
560 } /* snmpgeneric_pf_swtype */
561
562 /* -------------------------------------------------- */
563 /* try to set SW version
564 * and add some AC ports
565 *
566 */
567 /* needs more testing */
568 function snmpgeneric_pf_entitymib(&$snmp, &$sysObjectID, $attr_id) {
569
570 /* $attr_id == NULL -> device pf */
571
572 $attrs = &$sysObjectID['attr'];
573 $ports = &$sysObjectID['port'];
574
575 $entPhysicalClass = $snmp->walk('.1.3.6.1.2.1.47.1.1.1.1.5'); /* entPhysicalClass */
576
577 if(empty($entPhysicalClass))
578 return;
579
580 showNotice("Found Entity Table (Experimental)");
581
582 /* PhysicalClass
583 * 1:other
584 * 2:unknown
585 * 3:chassis
586 * 4:backplane
587 * 5:container
588 * 6:powerSupply
589 * 7:fan
590 * 8:sensor
591 * 9:module
592 * 10:port
593 * 11:stack
594 * 12:cpu
595 */
596
597 /* chassis */
598
599 /* always index = 1 ??? */
600 $chassis = array_keys($entPhysicalClass, '3'); /* 3 chassis */
601
602 if(0)
603 if(!empty($chassis)) {
604 echo '<table>';
605
606 foreach($chassis as $key => $oid) {
607 /* get index */
608 if(!preg_match('/\.(\d+)$/',$oid, $matches))
609 continue;
610
611 $index = $matches[1];
612
613 $name = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.7.$index");
614 $serialnum = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.11.$index");
615 $mfgname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.12.$index");
616 $modelname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.13.$index");
617
618 //showNotice("$name $mfgname $modelname $serialnum");
619
620 echo("<tr><td>$name</td><td>$mfgname</td><td>$modelname</td><td>$serialnum</td>");
621 }
622 unset($key);
623 unset($oid);
624
625 echo '</table>';
626 } /* chassis */
627
628
629
630 /* modules */
631
632 $modules = array_keys($entPhysicalClass, '9'); /* 9 Modules */
633
634 if(!empty($modules)) {
635
636 echo '<br><br>Modules<br><table>';
637 echo("<tr><th>Name</th><th>MfgName</th><th>ModelName</th><th>HardwareRev</th><th>FirmwareRev</th><th>SoftwareRev</th><th>SerialNum</th>");
638
639 foreach($modules as $key => $oid) {
640
641 /* get index */
642 if(!preg_match('/\.(\d+)$/',$oid, $matches))
643 continue;
644
645 $index = $matches[1];
646
647 $name = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.7.$index");
648 $hardwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.8.$index");
649 $firmwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.9.$index");
650 $softwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.10.$index");
651 $serialnum = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.11.$index");
652 $mfgname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.12.$index");
653 $modelname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.13.$index");
654
655 //showNotice("$name $mfgname $modelname $hardwarerev $firmwarerev $softwarerev $serialnum");
656
657 echo("<tr><td>".(empty($name) ? '-' : $name )."</td><td>$mfgname</td><td>$modelname</td><td>$hardwarerev</td><td>$firmwarerev</td><td>$softwarerev</td><td>$serialnum</td>");
658
659 /* set SW version to first module software version */
660 if($key == 0 ) {
661
662 $attrs[5]['value'] = $softwarerev; /* SW version */
663 $attrs[5]['comment'] = 'entity MIB';
664 }
665
666 }
667 unset($key);
668 unset($oid);
669
670 echo '</table>';
671 }
672
673
674 /* add AC ports */
675 $powersupply = array_keys($entPhysicalClass, '6'); /* 6 powerSupply */
676 $count = 1;
677 foreach($powersupply as $oid) {
678
679 /* get index */
680 if(!preg_match('/\.(\d+)$/',$oid, $matches))
681 continue;
682
683 $index = $matches[1];
684 $descr = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.2.$index");
685
686 $ports['AC-'.$count] = array('porttypeid' => '1-16', 'ifDescr' => $descr, 'comment' => 'entity MIB', 'uncheck' => '');
687 $count++;
688 }
689 unset($oid);
690 }
691
692 /* -------------------------------------------------- */
693
694 /*
695 * regex processor function
696 * needs 'oid' and 'regex'
697 * uses first back reference as attribute value
698 */
699 function snmpgeneric_pf_regex(&$snmp, &$sysObjectID, $attr_id) {
700
701 $attr = &$sysObjectID['attr'][$attr_id];
702
703 if (isset($attr['oid']) && isset($attr['regex'])) {
704
705 $oid = $attr['oid'];
706 $regex = $attr['regex'];
707
708 $raw_value = $snmp->get($oid);
709
710
711 if(isset($attr['replacement']))
712 $replace = $attr['replacement'];
713 else
714 $replace = '\\1';
715
716 $value = preg_replace($regex,$replace, $raw_value);
717
718 /* return array of attr_id => attr_value) */
719 $attr['value'] = $value;
720
721 }
722 // else Warning ??
723
724 } /* snmpgeneric_pf_regex */
725
726 /* -------------------------------------------------- */
727
728 $sg_portiifoptions= getPortIIFOptions();
729 $sg_portiifoptions[-1] = 'sfp'; /* generic sfp */
730
731 $sg_portoifoptions= getPortOIOptions();
732
733 /* -------------------------------------------------- */
734 /* -------------------------------------------------- */
735
736 function snmpgeneric_tabhandler($object_id) {
737
738 if(isset($_POST['snmpconfig'])) {
739 if($_POST['snmpconfig'] == '1') {
740 snmpgeneric_list($object_id);
741 }
742 } else {
743 snmpgeneric_snmpconfig($object_id);
744 }
745 } /* snmpgeneric_tabhandler */
746
747 /* -------------------------------------------------- */
748
749 //function snmpgeneric_tabtrigger() {
750 // return 'std';
751 //} /* snmpgeneric_tabtrigger */
752
753 /* -------------------------------------------------- */
754
755 function snmpgeneric_snmpconfig($object_id) {
756
757 echo '<body onload="document.getElementById(\'submitbutton\').focus();">';
758
759 $object = spotEntity ('object', $object_id);
760 //$object['attr'] = getAttrValues($object_id);
761 $endpoints = findAllEndpoints ($object_id, $object['name']);
762
763 addJS('function showsnmpv3(element) {
764 var style;
765 if(element.value != \''.SNMPgeneric::VERSION_3.'\') {
766 style = \'none\';
767 document.getElementById(\'snmp_community_label\').style.display=\'\';
768 } else {
769 style = \'\';
770 document.getElementById(\'snmp_community_label\').style.display=\'none\';
771 }
772
773 var elements = document.getElementsByName(\'snmpv3\');
774 for(var i=0;i<elements.length;i++) {
775 elements[i].style.display=style;
776 }
777 };',TRUE);
778
779 addJS('function checkInput() {
780 var host = document.getElementById(\'host\');
781
782 if(host.value == "-1") {
783 var newvalue = prompt("Enter Hostname or IP Address","");
784 if(newvalue != "") {
785 host.options[host.options.length] = new Option(newvalue, newvalue);
786 host.value = newvalue;
787 }
788 }
789
790 if(host.value != "-1" && host.value != "")
791 return true;
792 else
793 return false;
794 };',TRUE);
795
796 foreach( $endpoints as $key => $value) {
797 $endpoints[$value] = $value;
798 unset($endpoints[$key]);
799 }
800 unset($key);
801 unset($value);
802
803 foreach( getObjectIPv4Allocations($object_id) as $ip => $value) {
804
805 $ip = ip_format($ip);
806
807 if(!in_array($ip, $endpoints))
808 $endpoints[$ip] = $ip;
809 }
810 unset($ip);
811 unset($value);
812
813 foreach( getObjectIPv6Allocations($object_id) as $value) {
814 $ip = ip_format(ip_parse($value['addrinfo']['ip']));
815
816 if(!in_array($ip, $endpoints))
817 $endpoints[$ip] = $ip;
818 }
819 unset($value);
820
821 /* ask for ip/host name on submit see js checkInput() */
822 $endpoints['-1'] = 'ask me';
823
824 $snmpconfig = $_POST;
825
826 if(!isset($snmpconfig['host'])) {
827 $snmpconfig['host'] = -1;
828
829 /* try to find first FQDN or IP */
830 foreach($endpoints as $value) {
831 if(preg_match('/^[^ .]+(\.[^ .]+)+\.?/',$value)) {
832 $snmpconfig['host'] = $value;
833 break;
834 }
835 }
836 unset($value);
837 }
838
839 // sg_var_dump_html($endpoints);
840
841 if(!isset($snmpconfig['snmpversion']))
842 $snmpconfig['version'] = mySNMP::SNMP_VERSION;
843
844 if(!isset($snmpconfig['community']))
845 $snmpconfig['community'] = getConfigVar('DEFAULT_SNMP_COMMUNITY');
846
847 if(empty($snmpconfig['community']))
848 $snmpconfig['community'] = mySNMP::SNMP_COMMUNITY;
849
850 if(!isset($snmpconfig['sec_level']))
851 $snmpconfig['sec_level'] = NULL;
852
853 if(!isset($snmpconfig['auth_protocol']))
854 $snmpconfig['auth_protocol'] = NULL;
855
856 if(!isset($snmpconfig['auth_passphrase']))
857 $snmpconfig['auth_passphrase'] = NULL;
858
859 if(!isset($snmpconfig['priv_protocol']))
860 $snmpconfig['priv_protocol'] = NULL;
861
862 if(!isset($snmpconfig['priv_passphrase']))
863 $snmpconfig['priv_passphrase'] = NULL;
864
865 echo '<h1 align=center>SNMP Config</h1>';
866 echo '<form method=post name="snmpconfig" onsubmit="return checkInput()" action='.$_SERVER['REQUEST_URI'].' />';
867
868 echo '<table cellspacing=0 cellpadding=5 align=center class=widetable>
869 <tr><th class=tdright>Host:</th><td>';
870
871 echo getSelect ($endpoints, array ('id' => 'host','name' => 'host'), $snmpconfig['host'], FALSE);
872
873 echo'</td></tr>
874 <tr>
875 <th class=tdright><label for=snmpversion>Version:</label></th>
876 <td class=tdleft>';
877
878 echo getSelect (array(SNMPgeneric::VERSION_1 => 'v1', SNMPgeneric::VERSION_2C => 'v2c', SNMPgeneric::VERSION_3 => 'v3'),
879 array ('name' => 'version', 'id' => 'snmpversion', 'onchange' => 'showsnmpv3(this)'),
880 $snmpconfig['version'], FALSE);
881
882 echo '</td>
883 </tr>
884 <tr>
885 <th id="snmp_community_label" class=tdright><label for=community>Community:</label></th>
886 <th name="snmpv3" style="display:none" class=tdright><label for=community>Security Name:</label></th>
887 <td class=tdleft><input type=text name=community value='.$snmpconfig['community'].' ></td>
888 </tr>
889 <tr name="snmpv3" style="display:none;">
890 <th></th>
891 </tr>
892 <tr name="snmpv3" style="display:none;">
893 <th class=tdright><label">Security Level:</label></th>
894 <td class=tdleft>';
895
896 echo getSelect (array('noAuthNoPriv' => 'no Auth and no Priv', 'authNoPriv'=> 'auth without Priv', 'authPriv' => 'auth with Priv'),
897 array ('name' => 'sec_level'),
898 $snmpconfig['sec_level'], FALSE);
899
900 echo '</td></tr>
901 <tr name="snmpv3" style="display:none;">
902 <th class=tdright><label>Auth Type:</label></th>
903 <td class=tdleft>
904 <input name=auth_protocol type=radio value=MD5 '.($snmpconfig['auth_protocol'] == 'MD5' ? ' checked="checked"' : '').'/><label>MD5</label>
905 <input name=auth_protocol type=radio value=SHA '.($snmpconfig['auth_protocol'] == 'SHA' ? ' checked="checked"' : '').'/><label>SHA</label>
906 </td>
907 </tr>
908 <tr name="snmpv3" style="display:none;">
909 <th class=tdright><label>Auth Key:</label></th>
910 <td class=tdleft><input type=password id=auth_passphrase name=auth_passphrase value="'.$snmpconfig['auth_passphrase'].'"></td>
911 </tr>
912 <tr name="snmpv3" style="display:none;">
913 <th class=tdright><label>Priv Type:</label></th>
914 <td class=tdleft>
915 <input name=priv_protocol type=radio value=DES '.($snmpconfig['priv_protocol'] == 'DES' ? ' checked="checked"' : '').'/><label>DES</label>
916 <input name=priv_protocol type=radio value=AES '.($snmpconfig['priv_protocol'] == 'AES' ? ' checked="checked"' : '').'/><label>AES</label>
917 </td>
918 </tr>
919 <tr name="snmpv3" style="display:none;">
920 <th class=tdright><label>Priv Key</label></th>
921 <td class=tdleft><input type=password name=priv_passphrase value="'.$snmpconfig['priv_passphrase'].'"></td>
922 </tr>
923 </tr>
924 <td colspan=2>
925
926 <input type=hidden name=snmpconfig value=1>
927 <input type=submit id="submitbutton" tabindex="1" value="Show List"></td></tr>
928
929 </table></form>';
930
931 } /* snmpgeneric_snmpconfig */
932
933 function snmpgeneric_list($object_id) {
934
935 global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $sg_portoifoptions, $sg_ifType_ignore;
936
937 if(isset($_POST['snmpconfig'])) {
938 $snmpconfig = $_POST;
939 } else {
940 showError("Missing SNMP Config");
941 return;
942 }
943
944 echo '<body onload="document.getElementById(\'createbutton\').focus();">';
945
946 addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname);
947 var value = document.getElementById(classname).checked;
948 for(i=0;i<boxes.length;i++) {
949 if(boxes[i].disabled == false)
950 boxes[i].checked=value;
951 }
952 };', TRUE);
953
954 $object = spotEntity ('object', $object_id);
955
956 $object['attr'] = getAttrValues($object_id);
957
958 $snmpdev = new mySNMP($snmpconfig['version'], $snmpconfig['host'], $snmpconfig['community']);
959
960 if($snmpconfig['version'] == SNMPgeneric::VERSION_3 ) {
961 $snmpdev->setSecurity( $snmpconfig['sec_level'],
962 $snmpconfig['auth_protocol'],
963 $snmpconfig['auth_passphrase'],
964 $snmpconfig['priv_protocol'],
965 $snmpconfig['priv_passphrase']
966 );
967 }
968
969 $snmpdev->init();
970
971 if($snmpdev->getErrno()) {
972 showError($snmpdev->getError());
973 return;
974 }
975
976 /* SNMP connect successfull */
977
978 showSuccess("SNMP v".$snmpconfig['version']." connect to ${snmpconfig['host']} successfull");
979
980 echo '<form name=CreatePorts method=post action='.$_SERVER['REQUEST_URI'].'&module=redirect&op=create>';
981
982 echo "<strong>System Informations</strong>";
983 echo "<table>";
984 // echo "<tr><th>OID</th><th>Value</th></tr>";
985
986 $systemoids = array('sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation');
987 foreach ($systemoids as $shortoid) {
988
989 $value = $snmpdev->{$shortoid};
990
991 if($shortoid == 'sysUpTime') {
992 /* in hundredths of a second */
993 $secs = (int)($value / 100);
994 $days = (int)($secs / (60 * 60 * 24));
995 $secs -= $days * 60 *60 * 24;
996 $hours = (int)($secs / (60 * 60));
997 $secs -= $hours * 60 * 60;
998 $mins = (int)($secs / (60));
999 $secs -= $mins * 60;
1000 $value = "$value ($days $hours:$mins:$secs)";
1001 }
1002
1003 echo "<tr><td title=\"".$snmpdev->lastgetoid."\" align=\"right\">$shortoid: </td><td>$value</td></tr>";
1004
1005 }
1006 unset($shortoid);
1007
1008 echo "</table>";
1009
1010 /* sysObjectID Attributes and Ports */
1011 $sysObjectID['object'] = &$object;
1012
1013 /* get sysObjectID */
1014 $sysObjectID['raw_value'] = $snmpdev->sysObjectID;
1015 //$sysObjectID['raw_value'] = 'NET-SNMP-MIB::netSnmpAgentOIDs.10';
1016
1017 $sysObjectID['value'] = preg_replace('/^.*enterprises\.([\.[:digit:]]+)$/','\\1', $sysObjectID['raw_value']);
1018
1019 /* try snmptranslate to numeric */
1020 if(preg_match('/[^\.0-9]+/',$sysObjectID['value'])) {
1021 $numeric_value = $snmpdev->translatetonumeric($sysObjectID['value']);
1022
1023 if(!empty($numeric_value)) {
1024 showSuccess("sysObjectID: ".$sysObjectID['value']." translated to $numeric_value");
1025 $sysObjectID['value'] = preg_replace('/^.1.3.6.1.4.1.([\.[:digit:]]+)$/','\\1', $numeric_value);
1026 }
1027 }
1028
1029 /* array_merge doesn't work with numeric keys !! */
1030 $sysObjectID['attr'] = array();
1031 $sysObjectID['port'] = array();
1032
1033 $sysobjid = $sysObjectID['value'];
1034
1035 $count = 1;
1036
1037 while($count) {
1038
1039 if(isset($sg_known_sysObjectIDs[$sysobjid])) {
1040 $sysObjectID = $sysObjectID + $sg_known_sysObjectIDs[$sysobjid];
1041
1042 if(isset($sg_known_sysObjectIDs[$sysobjid]['attr']))
1043 $sysObjectID['attr'] = $sysObjectID['attr'] + $sg_known_sysObjectIDs[$sysobjid]['attr'];
1044
1045 if(isset($sg_known_sysObjectIDs[$sysobjid]['port']))
1046 $sysObjectID['port'] = $sysObjectID['port'] + $sg_known_sysObjectIDs[$sysobjid]['port'];
1047
1048 if(isset($sg_known_sysObjectIDs[$sysobjid]['text'])) {
1049 showSuccess("found sysObjectID ($sysobjid) ".$sg_known_sysObjectIDs[$sysobjid]['text']);
1050 }
1051 }
1052
1053 $sysobjid = preg_replace('/\.[[:digit:]]+$/','',$sysobjid, 1, $count);
1054
1055 /* add default sysobjectid */
1056 if($count == 0 && $sysobjid != 'default') {
1057 $sysobjid = 'default';
1058 $count = 1;
1059 }
1060 }
1061
1062 $sysObjectID['vendor_number'] = $sysobjid;
1063
1064 /* device pf */
1065 if(isset($sysObjectID['pf']))
1066 foreach($sysObjectID['pf'] as $function) {
1067 if(function_exists($function)) {
1068 /* call device pf */
1069 $function($snmpdev, $sysObjectID, NULL);
1070 } else {
1071 showWarning("Missing processor function ".$function." for device $sysobjid");
1072 }
1073 }
1074
1075
1076 /* sort attributes maintain numeric keys */
1077 ksort($sysObjectID['attr']);
1078
1079 /* DEBUG */
1080 //sg_var_dump_html($sysObjectID['attr'], "Before processing");
1081
1082 /* needs PHP >= 5 foreach call by reference */
1083 /* php 5.1.6 doesn't seem to work */
1084 //foreach($sysObjectID['attr'] as $attr_id => &$attr) {
1085 foreach($sysObjectID['attr'] as $attr_id => $value) {
1086
1087 $attr = &$sysObjectID['attr'][$attr_id];
1088
1089 if(isset($object['attr'][$attr_id])) {
1090
1091 switch(TRUE) {
1092
1093 case isset($attr['pf']):
1094 if(function_exists($attr['pf'])) {
1095
1096 $attr['pf']($snmpdev, $sysObjectID, $attr_id);
1097
1098 } else {
1099 showWarning("Missing processor function ".$attr['pf']." for attribute $attr_id");
1100 }
1101
1102 break;
1103
1104 case isset($attr['oid']):
1105
1106 $attrvalue = $snmpdev->get($attr['oid']);
1107
1108 if(isset($attr['regex'])) {
1109 $regex = $attr['regex'];
1110
1111 if(isset($attr['replacement'])) {
1112 $replacement = $attr['replacement'];
1113 $attrvalue = preg_replace($regex, $replacement, $attrvalue);
1114 } else {
1115 if(!preg_match($regex, $attrvalue)) {
1116 if(!isset($attr['uncheck']))
1117 $attr['uncheck'] = "regex doesn't match";
1118 } else
1119 unset($attr['uncheck']);
1120 }
1121 }
1122
1123 $attr['value'] = $attrvalue;
1124
1125 break;
1126
1127 case isset($attr['value']):
1128 break;
1129
1130 default:
1131 showError("Error handling attribute id: $attr_id");
1132
1133 }
1134
1135 } else {
1136 showWarning("Object has no attribute id: $attr_id");
1137 unset($sysObjectID['attr'][$attr_id]);
1138 }
1139
1140 }
1141 unset($attr_id);
1142
1143 /* sort again in case there where attribs added ,maintain numeric keys */
1144 ksort($sysObjectID['attr']);
1145
1146 /* print attributes */
1147 echo '<br>Attributes<br><table>';
1148 echo '<tr><th><input type="checkbox" id="attribute" checked="checked" onclick="setchecked(this.id)"></td>';
1149 echo '<th>Name</th><th>Current Value</th><th>new value</th></tr>';
1150
1151 /* DEBUG */
1152 //sg_var_dump_html($sysObjectID['attr'], "After processing");
1153
1154 foreach($sysObjectID['attr'] as $attr_id => &$attr) {
1155
1156 if(isset($object['attr'][$attr_id]) && isset($attr['value'])) {
1157
1158 if($attr['value'] == $object['attr'][$attr_id]['value'])
1159 $attr['uncheck'] = 'Current = new value';
1160
1161 $value = $attr['value'];
1162
1163 $val_key = (isset($object['attr'][$attr_id]['key']) ? ' ('.$object['attr'][$attr_id]['key'].')' : '' );
1164 $comment = '';
1165
1166 if(isset($attr['comment'])) {
1167 if(!empty($attr['comment']))
1168 $comment = $attr['comment'];
1169 }
1170
1171 if(isset($attr['uncheck'])) {
1172 $checked = '';
1173 $comment .= ', '.$attr['uncheck'];
1174 } else {
1175 $checked = ' checked="checked"';
1176 }
1177
1178 $updateattrcheckbox = '<b style="background-color:#00ff00">'
1179 .'<input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr['.$attr_id.']" value="'.$value.'"'
1180 .$checked.'></b>';
1181
1182 $comment = trim($comment,', ');
1183
1184 echo "<tr><td>$updateattrcheckbox</td><td title=\"id: $attr_id\">"
1185 .$object['attr'][$attr_id]['name'].'</td><td style="background-color:#d8d8d8">'
1186 .$object['attr'][$attr_id]['value'].$val_key.'</td><td>'.$value.'</td>'
1187 .'<td style="color:#888888">'.$comment.'</td></tr>';
1188 }
1189 }
1190 unset($attr_id);
1191
1192 echo '</table>';
1193
1194 /* ports */
1195
1196 /* get ports */
1197 amplifyCell($object);
1198
1199 /* set array key to port name */
1200 foreach($object['ports'] as $key => $values) {
1201 $object['ports'][$values['name']] = $values;
1202 unset($object['ports'][$key]);
1203 }
1204
1205 $newporttypeoptions = getNewPortTypeOptions();
1206
1207 // sg_var_dump_html($sysObjectID['port']);
1208
1209 if(!empty($sysObjectID['port'])) {
1210
1211 echo '<br>Vendor / Device specific ports<br>';
1212 echo '<table><tr><th><input type="checkbox" id="moreport" checked="checked" onclick="setchecked(this.id)"></th><th>ifName</th><th>porttypeid</th></tr>';
1213
1214 foreach($sysObjectID['port'] as $name => $port) {
1215
1216 if(array_key_exists($name,$object['ports']))
1217 $disableport = TRUE;
1218 else
1219 $disableport = FALSE;
1220
1221 $comment = '';
1222
1223 if(isset($port['comment'])) {
1224 if(!empty($port['comment']))
1225 $comment = $port['comment'];
1226 }
1227 if(isset($port['uncheck'])) {
1228 $checked = '';
1229 $comment .= ', '.$port['uncheck'];
1230 } else {
1231 $checked = ' checked="checked"';
1232 }
1233
1234 $portcreatecheckbox = '<b style="background-color:'.($disableport ? '#ff0000' : '#00ff00')
1235 .'"><input style="background-color:'.($disableport ? '#ff0000' : '#00ff00').'" class="moreport" type="checkbox" name="portcreate['.$name.']" value="'.$name.'"'
1236 .($disableport ? ' disabled="disbaled"' : $checked ).'></b>';
1237
1238 $formfield = '<input type="hidden" name="ifName['.$name.']" value="'.$name.'">';
1239 echo "<tr>$formfield<td>$portcreatecheckbox</td><td>$name</td>";
1240
1241 if(isset($port['disabled'])) {
1242 $disabledselect = array('disabled' => "disabled");
1243 } else
1244 $disabledselect = array();
1245
1246
1247 foreach($port as $key => $value) {
1248
1249 if($key == 'uncheck' || $key == 'comment')
1250 continue;
1251
1252 /* TODO iif_name */
1253 if($key == 'porttypeid')
1254 $displayvalue = getNiftySelect($newporttypeoptions,
1255 array('name' => "porttypeid[$name]") + $disabledselect, $value);
1256 /* disabled formfied won't be submitted ! */
1257 else
1258 $displayvalue = $value;
1259
1260 $formfield = '<input type="hidden" name="'.$key.'['.$name.']" value="'.$value.'">';
1261 echo "$formfield<td>$displayvalue</td>";
1262 }
1263
1264 $comment = trim($comment,', ');
1265 echo "<td style=\"color:#888888\">$comment</td></tr>";
1266 }
1267 unset($name);
1268 unset($port);
1269
1270 echo '</table>';
1271 }
1272
1273 /* snmp ports */
1274
1275 $ifsnmp = new ifSNMP($snmpdev);
1276
1277 /* ip spaces */
1278
1279 $ipspace = NULL;
1280 foreach($ifsnmp->ipaddress as $ifindex => $ipaddresses) {
1281
1282 foreach($ipaddresses as $ipaddr => $value) {
1283 $addrtype = $value['addrtype'];
1284 $netaddr = $value['net'];
1285 $maskbits = $value['maskbits'];
1286 $netid = NULL;
1287 $linklocal = FALSE;
1288
1289 //echo "<br> - DEBUG: ipspace $ipaddr - $netaddr - $addrtype - $maskbits<br>";
1290
1291 /* check for ip space */
1292 switch($addrtype) {
1293 case 'ipv4':
1294 case 'ipv4z':
1295 if($maskbits == 32)
1296 $netid = 'host';
1297 else
1298 $netid = getIPv4AddressNetworkId(ip_parse($ipaddr));
1299 break;
1300
1301 case 'ipv6':
1302
1303 /* format ipaddr for ip6_parse */
1304 $ipaddr = preg_replace('/((..):(..))/','\\2\\3',$ipaddr);
1305 $ipaddr = preg_replace('/%.*$/','',$ipaddr);
1306
1307 $ip6_bin = ip6_parse($ipaddr);
1308 $ip6_addr = ip_format($ip6_bin);
1309 $netid = getIPv6AddressNetworkId($ip6_bin);
1310
1311 $node = constructIPRange($ip6_bin, $maskbits);
1312
1313 $netaddr = $node['ip'];
1314 $linklocal = substr($ip6_addr,0,5) == "fe80:";
1315
1316 //echo "<br> - DEBUG: ipspace $ipaddr - $addrtype - $maskbits - $netaddr - >$linklocal<<br>";
1317
1318 break;
1319
1320 case 'ipv6z':
1321 /* link local */
1322 $netid = 'ignore';
1323 break;
1324 default:
1325 }
1326
1327 if(empty($netid) && $netaddr != '::1' && $netaddr != '127.0.0.1' && $netaddr != '127.0.0.0' && $netaddr != '0.0.0.0' && !$linklocal) {
1328
1329 $netaddr .= "/$maskbits";
1330 $ipspace[$netaddr] = $addrtype;
1331 }
1332 }
1333 unset($ipaddr);
1334 unset($value);
1335 unset($addrtype);
1336 }
1337 unset($ifindex);
1338 unset($ipaddresses);
1339
1340 /* print ip spaces table */
1341 if(!empty($ipspace)) {
1342 echo '<br><br>Create IP Spaces';
1343 echo '<table><tr><th><input type="checkbox" id="ipspace" onclick="setchecked(this.id)" checked=\"checked\"></th>';
1344 echo '<th>Type</th><th>prefix</th><th>name</th><th width=150 title="reserve network and router addresses">reserve network / router addresses</th></tr>';
1345
1346 $i = 1;
1347 foreach($ipspace as $prefix => $addrtype) {
1348
1349 $netcreatecheckbox = '<b style="background-color:#00ff00">'
1350 .'<input class="ipspace" style="background-color:#00ff00" type="checkbox" name="netcreate['
1351 .$i.']" value="'.$addrtype.'" checked=\"checked\"></b>';
1352
1353 $netprefixfield = '<input type="text" size=50 name="netprefix['.$i.']" value="'.$prefix.'">';
1354
1355 $netnamefield = '<input type="text" name="netname['.$i.']">';
1356
1357 $netreservecheckbox = '<input type="checkbox" name="netreserve['.$i.']">';
1358
1359 echo "<tr><td>$netcreatecheckbox</td><td style=\"color:#888888\">$addrtype</td><td>$netprefixfield</td><td>$netnamefield</td><td>$netreservecheckbox</td></tr>";
1360
1361 $i++;
1362 }
1363 unset($prefix);
1364 unset($addrtype);
1365 unset($i);
1366
1367 echo '</table>';
1368 }
1369
1370
1371 echo "<br><br>ifNumber: ".$ifsnmp->ifNumber."<br><table><tbody valign=\"top\">";
1372
1373 $portcompat = getPortInterfaceCompat();
1374
1375 $ipnets = array();
1376
1377 $ifsnmp->printifInfoTableHeader("<th>add ip</th><th>add port</th><th title=\"update mac\">upd mac</th><th>porttypeid</th><th>comment</th></tr>");
1378
1379 echo '<tr><td colspan="11"></td>
1380 <td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id)">IPv4<br>
1381 <input type="checkbox" id="ipv6addr" onclick="setchecked(this.id)">IPv6</td>
1382 <td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td>
1383 <td><input type="checkbox" id="mac" onclick="setchecked(this.id)" checked="checked"></td></tr>';
1384
1385 foreach($ifsnmp as $if) {
1386
1387 $createport = TRUE;
1388 $disableport = FALSE;
1389 $ignoreport = FALSE;
1390 $port_info = NULL;
1391
1392 $updatemaccheckbox = '';
1393
1394 $hrefs = array();
1395
1396 $comment = "";
1397
1398 if(trim($ifsnmp->ifName($if)) == '') {
1399 $comment .= "no ifName";
1400 $createport = FALSE;
1401 } else {
1402
1403 if(array_key_exists($ifsnmp->ifName($if),$object['ports'])){
1404 $port_info = &$object['ports'][$ifsnmp->ifName($if)];
1405 $comment .= "Name exists";
1406 $createport = FALSE;
1407 $disableport = TRUE;
1408 }
1409 }
1410
1411 if($ifsnmp->ifPhysAddress($if) != '' ) {
1412
1413 $ifPhysAddress = $ifsnmp->ifPhysAddress($if);
1414
1415 $l2port = sg_checkL2Address($ifPhysAddress);
1416
1417 //if(alreadyUsedL2Address($ifPhysAddress, $object_id)) {
1418
1419 if(!empty($l2port)) {
1420 $l2object_id = key($l2port);
1421
1422 $porthref = makeHref(array('page'=>'object', 'tab' => 'ports',
1423 'object_id' => $l2object_id, 'hl_port_id' => $l2port[$l2object_id]));
1424
1425 $comment .= ", L2Address exists";
1426 $hrefs['ifPhysAddress'] = $porthref;
1427 $createport = FALSE;
1428 // $disableport = TRUE;
1429 $updatemaccheckbox = '';
1430 }
1431
1432 $disablemac = true;
1433 if($disableport) {
1434 if($port_info !== NULL) {
1435 if(str_replace(':','',$port_info['l2address']) != $ifPhysAddress)
1436 $disablemac = false;
1437 else
1438 $disablemac = true;
1439 }
1440 } else {
1441 /* port create always updates mac */
1442 $updatemaccheckbox = '<b style="background-color:#00ff00">'
1443 .'<input style="background-color:'
1444 .'#00ff00" type="checkbox"'
1445 .' checked="checked"'
1446 .' disabled=\"disabled\"></b>';
1447 }
1448
1449 if(!$disablemac)
1450 $updatemaccheckbox = '<b style="background-color:'.($disablemac ? '#ff0000' : '#00ff00').'">'
1451 .'<input class="mac" style="background-color:'
1452 .($disablemac ? '#ff0000' : '#00ff00').'" type="checkbox" name="updatemac['.$if.']" value="'
1453 .$object['ports'][$ifsnmp->ifName($if)]['id'].'" checked="checked"'
1454 .($disablemac ? ' disabled=\"disabled\"' : '' ).'></b>';
1455
1456 }
1457
1458
1459 $porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if));
1460
1461 if(in_array($ifsnmp->ifType($if),$sg_ifType_ignore)) {
1462 $comment .= ", ignore if type";
1463 $createport = FALSE;
1464 $ignoreport = TRUE;
1465 }
1466
1467 /* ignore ports without an Connector */
1468 if(!$sg_create_noconnector_ports && ($ifsnmp->ifConnectorPresent($if) == 2)) {
1469 $comment .= ", no Connector";
1470 $createport = FALSE;
1471 }
1472
1473 /* Allocate IPs ipv4 and ipv6 */
1474
1475 $ipaddresses = $ifsnmp->ipaddress($if);
1476
1477 if(!empty($ipaddresses)) {
1478
1479 $ipaddrcell = '<table>';
1480
1481 foreach($ipaddresses as $ipaddr => $value) {
1482 $createipaddr = FALSE;
1483 $disableipaddr = FALSE;
1484 $ipaddrhref = '';
1485 $linklocal = FALSE;
1486
1487 $addrtype = $value['addrtype'];
1488 $maskbits = $value['maskbits'];
1489 $bcast = $value['bcast'];
1490
1491 //echo "<br> - DEBUG: ip $ipaddr - $addrtype - $maskbits - $bcast<br>";
1492
1493 switch($addrtype) {
1494 case 'ipv4z':
1495 case 'ipv4':
1496 if($maskbits == 32)
1497 $bcast = "host";
1498
1499 $inputname = 'ip';
1500 break;
1501
1502 case 'ipv6z':
1503 $disableipaddr = TRUE;
1504 case 'ipv6':
1505 $inputname = 'ipv6';
1506
1507 /* format ipaddr for ip6_parse */
1508 $ipaddr = preg_replace('/((..):(..))/','\\2\\3',$ipaddr);
1509 $ipaddr = preg_replace('/%.*$/','',$ipaddr);
1510
1511 /* ip_parse throws exception on parse errors */
1512 $ip6_bin = ip_parse($ipaddr);
1513 $ipaddr = ip_format($ip6_bin);
1514
1515 $node = constructIPRange($ip6_bin, $maskbits);
1516
1517 $linklocal = ($node['ip'] == 'fe80::');
1518
1519 $createipaddr = FALSE;
1520 break;
1521
1522 } //switch
1523
1524 $address = getIPAddress(ip_parse($ipaddr));
1525
1526 /* only if ip not already allocated */
1527 if(empty($address['allocs'])) {
1528 if(!$ignoreport) {
1529 $createipaddr = TRUE;
1530 }
1531 } else {
1532 $disableipaddr = TRUE;
1533
1534 $ipobject_id = $address['allocs'][0]['object_id'];
1535
1536 $ipaddrhref = makeHref(array('page'=>'object',
1537 'object_id' => $ipobject_id, 'hl_ipv4_addr' => $ipaddr));
1538
1539 }
1540
1541 /* reserved addresses */
1542 if($address['reserved'] == 'yes') {
1543 $comment .= ', '.$address['ip'].' reserved '.$address['name'];
1544 $createipaddr = FALSE;
1545 // $disableipaddr = TRUE;
1546 }
1547
1548 if($ipaddr == '127.0.0.1' || $ipaddr == '0.0.0.0' || $ipaddr == '::1' || $ipaddr == '::' || $linklocal) {
1549 $createipaddr = FALSE;
1550 $disableipaddr = TRUE;
1551 }
1552
1553 if($ipaddr === $bcast) {
1554 $comment .= ", $ipaddr broadcast";
1555 $createipaddr = FALSE;
1556 $disableipaddr = TRUE;
1557 }
1558
1559 if(!$disableipaddr) {
1560 $ipaddrcheckbox = '<b style="background-color:'.($disableipaddr ? '#ff0000' : '#00ff00')
1561 .'"><input class="'.$inputname.'addr" style="background-color:'
1562 .($disableipaddr ? '#ff0000' : '#00ff00')
1563 .'" type="checkbox" name="'.$inputname.'addrcreate['.$ipaddr.']" value="'.$if.'"'
1564 .($disableipaddr ? ' disabled="disabled"' : '')
1565 .($createipaddr ? ' checked="checked"' : '').'></b>';
1566 } else {
1567 $ipaddrcheckbox = '';
1568 }
1569
1570 $ipaddrcell .= "<tr><td>$ipaddrcheckbox</td>";
1571
1572 if(!empty($ipaddrhref)) {
1573 $ipaddrcell .= "<td><a href=$ipaddrhref>$ipaddr/$maskbits</a></td></tr>";
1574 } else {
1575 $ipaddrcell .= "<td>$ipaddr/$maskbits</td></tr>";
1576 }
1577
1578 } // foreach
1579 unset($ipaddr);
1580 unset($value);
1581
1582 $ipaddrcell .= '</table>';
1583
1584 // if(!empty($ipaddresses))
1585 } else {
1586 $ipaddrcreatecheckbox = '';
1587 $ipaddrcell = '';
1588 }
1589
1590 /* checkboxes for add port and add ip */
1591 /* FireFox needs <b style=..>, IE and Opera work with <td style=..> */
1592 if(!$disableport)
1593 $portcreatecheckbox = '<b style="background-color:'.($disableport ? '#ff0000' : '#00ff00')
1594 .'"><input class="ports" style="background-color:'.($disableport ? '#ff0000' : '#00ff00')
1595 .'" type="checkbox" name="portcreate['.$if.']" value="'.$if.'"'
1596 .($disableport ? ' disabled="disbaled"' : '').($createport ? ' checked="checked"' : '').'></b>';
1597 else
1598 $portcreatecheckbox = '';
1599
1600 /* port type id */
1601 /* add port type to newporttypeoptions if missing */
1602 if(strpos(serialize($newporttypeoptions),$porttypeid) === FALSE) {
1603
1604 $portids = explode('-',$porttypeid);
1605 $oif_name = $sg_portoifoptions[$portids[1]];
1606
1607 $newporttypeoptions['auto'] = array($porttypeid => "*$oif_name");
1608 }
1609
1610 $selectoptions = array('name' => "porttypeid[$if]");
1611
1612 if($disableport)
1613 $selectoptions['disabled'] = "disabled";
1614
1615 $porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid);
1616
1617 $comment = trim($comment,', ');
1618
1619 $ifsnmp->printifInfoTableRow($if,"<td>$ipaddrcell</td><td>$portcreatecheckbox</td><td>$updatemaccheckbox</td><td>$porttypeidselect</td><td nowrap=\"nowrap\">$comment</td>", $hrefs);
1620
1621 }
1622 unset($if);
1623
1624 /* preserve snmpconfig */
1625 foreach($_POST as $key => $value) {
1626 echo '<input type=hidden name='.$key.' value='.$value.' />';
1627 }
1628 unset($key);
1629 unset($value);
1630
1631 echo '<tr><td colspan=15 align="right"><p><input id="createbutton" type=submit value="Create Ports and IPs" onclick="return confirm(\'Create selected items?\')"></p></td></tr></tbody></table></form>';
1632
1633 }
1634
1635 /* -------------------------------------------------- */
1636 function snmpgeneric_opcreate() {
1637
1638 $object_id = $_REQUEST['object_id'];
1639 $attr = getAttrValues($object_id);
1640
1641 // sg_var_dump_html($_REQUEST);
1642 // sg_var_dump_html($attr);
1643
1644 /* commitUpdateAttrValue ($object_id, $attr_id, $new_value); */
1645 if(isset($_POST['updateattr'])) {
1646 foreach($_POST['updateattr'] as $attr_id => $value) {
1647 // if(empty($attr[$attr_id]['value']))
1648 if(!empty($value)) {
1649 commitUpdateAttrValue ($object_id, $attr_id, $value);
1650 showSuccess("Attribute ".$attr[$attr_id]['name']." set to $value");
1651 }
1652 }
1653 unset($attr_id);
1654 unset($value);
1655 }
1656 /* updateattr */
1657
1658 /* create ports */
1659 if(isset($_POST['portcreate'])) {
1660 foreach($_POST['portcreate'] as $if => $value) {
1661
1662 $ifName = (isset($_POST['ifName'][$if]) ? trim($_POST['ifName'][$if]) : '' );
1663 $ifPhysAddress = (isset($_POST['ifPhysAddress'][$if]) ? trim($_POST['ifPhysAddress'][$if]) : '' );
1664 $ifAlias = (isset($_POST['ifAlias'][$if]) ? trim($_POST['ifAlias'][$if]) : '' );
1665 $ifDescr = (isset($_POST['ifDescr'][$if]) ? trim($_POST['ifDescr'][$if]) : '' );
1666
1667 $visible_label = (empty($ifAlias) ? '' : $ifAlias.'; ').$ifDescr;
1668
1669 if(empty($ifName)) {
1670 showError('Port without ifName '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
1671 } else {
1672 commitAddPort ($object_id, $ifName, $_POST['porttypeid'][$if], $visible_label, $ifPhysAddress);
1673 showSuccess('Port created '.$ifName.', '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
1674 }
1675 }
1676 unset($if);
1677 unset($value);
1678 }
1679 /* portcreate */
1680
1681 /* net create */
1682 if(isset($_POST['netcreate'])) {
1683 foreach($_POST['netcreate'] as $id => $addrtype) {
1684 $range = $_POST['netprefix'][$id];
1685 $name = $_POST['netname'][$id];
1686 $is_reserved = isset($_POST['netreserve'][$id]);
1687
1688 if($addrtype == 'ipv4' || $addrtype == 'ipv4z')
1689 createIPv4Prefix($range, $name, $is_reserved);
1690 else
1691 createIPv6Prefix($range, $name, $is_reserved);
1692
1693 showSuccess("$range $name created");
1694
1695 }
1696 unset($id);
1697 unset($addrtype);
1698 }
1699 /* netcreate */
1700
1701 /* allocate ipv6 adresses */
1702 if(isset($_POST['ipv6addrcreate'])) {
1703 foreach($_POST['ipv6addrcreate'] as $ipaddr => $if) {
1704
1705 bindIPv6ToObject(ip6_parse($ipaddr), $object_id,$_POST['ifName'][$if], 1); /* connected */
1706 showSuccess("$ipaddr allocated");
1707 }
1708 unset($ipaddr);
1709 unset($if);
1710 }
1711 /* allocate ip adresses */
1712 if(isset($_POST['ipaddrcreate'])) {
1713 foreach($_POST['ipaddrcreate'] as $ipaddr => $if) {
1714
1715 bindIPToObject(ip_parse($ipaddr), $object_id,$_POST['ifName'][$if], 1); /* connected */
1716 showSuccess("$ipaddr allocated");
1717 }
1718 unset($ipaddr);
1719 unset($if);
1720 }
1721 /* ipaddrecreate */
1722
1723 /* update mac addresses only */
1724 if(isset($_POST['updatemac'])) {
1725 foreach($_POST['updatemac'] as $if => $port_id) {
1726
1727 $ifPhysAddress = (isset($_POST['ifPhysAddress'][$if]) ? trim($_POST['ifPhysAddress'][$if]) : '' );
1728
1729 sg_commitUpdatePortl2address($object_id, $port_id, $ifPhysAddress);
1730
1731 $ifName = (isset($_POST['ifName'][$if]) ? trim($_POST['ifName'][$if]) : '' );
1732 showSuccess("l2address updated on $ifName to $ifPhysAddress");
1733 }
1734 unset($if);
1735 unset($port_id);
1736 }
1737 /* updatemac */
1738
1739 } /* snmpgeneric_opcreate */
1740
1741 /* -------------------------------------------------- */
1742
1743 /* returns RT interface type depending on ifType, ifDescr, .. */
1744 function guessRToif_id($ifType,$ifDescr = NULL) {
1745 global $sg_ifType2oif_id;
1746 global $sg_portiifoptions;
1747 global $sg_portoifoptions;
1748
1749 /* default value */
1750 $retval = '24'; /* 1000BASE-T */
1751
1752 if(isset($sg_ifType2oif_id[$ifType])) {
1753 $retval = $sg_ifType2oif_id[$ifType];
1754 }
1755
1756 if(strpos($retval,'-') === FALSE)
1757 $retval = "1-$retval";
1758
1759 /* no ethernetCsmacd */
1760 if($ifType != 6)
1761 return $retval;
1762
1763
1764 /* try to identify outer and inner interface type from ifDescr */
1765
1766 /**********************
1767 * ifDescr samples
1768 *
1769 * Enterasys C3
1770 *
1771 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 45 - no sfp inserted
1772 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 47 - sfp 1000BASE-SX inserted
1773 *
1774 *
1775 * Enterasys S4
1776 *
1777 * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; No GBIC/MGBIC Inserted
1778 * Enterasys Networks, Inc. 1000BASE-SX Mini GBIC w/LC connector
1779 * Enterasys Networks, Inc. 10GBASE SFP+ 10-Gigabit Ethernet Port; No SFP+ Inserted
1780 * Enterasys Networks, Inc. 10GBASE-SR SFP+ 10-Gigabit Ethernet Port (850nm Short Wavelength, 33/82m MMF, LC)
1781 * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; Unknown GBIC/MGBIC Inserted
1782 *
1783 */
1784
1785 foreach($sg_portiifoptions as $iif_id => $iif_type) {
1786
1787 /* TODO better matching */
1788
1789
1790 /* find iif_type */
1791 if(preg_match('/(.*?)('.preg_quote($iif_type).')(.*)/i',$ifDescr,$matches)) {
1792
1793 $oif_type = "empty ".$iif_type;
1794
1795 $no = preg_match('/ no $/i', $matches[1]);
1796
1797 if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[1], $basematch)) {
1798 $oif_type=$basematch[0];
1799 } else {
1800 if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[3], $basematch)) {
1801 $oif_type=$basematch[0];
1802 }
1803 }
1804
1805 if($iif_id == -1) {
1806 /* 2 => SFP-100 or 4 => SFP-1000 */
1807
1808 if(isset($basematch[1])) {
1809 switch($basematch[1]) {
1810 case '100' :
1811 $iif_id = 2;
1812 $iif_type = "SFP-100";
1813 break;
1814 default:
1815 case '1000' :
1816 $iif_id = 4;
1817 $iif_type = "SFP-1000";
1818 break;
1819 }
1820 }
1821
1822 }
1823
1824 if($no) {
1825 $oif_type = "empty ".$iif_type;
1826 }
1827
1828 $oif_type = preg_replace('/BASE/',"Base",$oif_type);
1829
1830 $oif_id = array_search($oif_type,$sg_portoifoptions);
1831
1832 if($oif_id != '') {
1833 $retval = "$iif_id-$oif_id";
1834 }
1835
1836 /* TODO check port compat */
1837
1838 /* stop foreach */
1839 break;
1840 }
1841 }
1842 unset($iif_id);
1843 unset($iif_type);
1844
1845 if(strpos($retval,'-') === FALSE)
1846 $retval = "1-$retval";
1847
1848 return $retval;
1849
1850 }
1851
1852 /* --------------------------------------------------- */
1853
1854 function sg_commitUpdatePortl2address($object_id, $port_id, $port_l2address)
1855 {
1856 $db_l2address = l2addressForDatabase ($port_l2address);
1857
1858 global $dbxlink;
1859 $dbxlink->exec ('LOCK TABLES Port WRITE');
1860 if (alreadyUsedL2Address ($db_l2address, $object_id))
1861 {
1862 $dbxlink->exec ('UNLOCK TABLES');
1863 // FIXME: it is more correct to throw InvalidArgException here
1864 // and convert it to InvalidRequestArgException at upper level,
1865 // when there is a mean to do that.
1866 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
1867 }
1868 usePreparedUpdateBlade
1869 (
1870 'Port',
1871 array
1872 (
1873 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
1874 ),
1875 array
1876 (
1877 'id' => $port_id,
1878 'object_id' => $object_id
1879 )
1880 );
1881 $dbxlink->exec ('UNLOCK TABLES');
1882 } /* sg_commitUpdatePortl2address */
1883
1884 /* ----------------------------------------------------- */
1885
1886 /* returns object_id and port_id to a given l2address */
1887 function sg_checkL2Address ($address)
1888 {
1889 $result = usePreparedSelectBlade
1890 (
1891 'SELECT object_id,id FROM Port WHERE BINARY l2address = ?',
1892 array ($address)
1893 );
1894 $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
1895 return $row;
1896 }
1897
1898 /* returns oi_id and name */
1899 function getPortOIOptions()
1900 {
1901 $result = usePreparedSelectBlade
1902 (
1903 'SELECT dict_key,dict_value from Dictionary where chapter_id = 2',
1904 array ()
1905 );
1906 $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
1907 return $row;
1908 }
1909
1910 /* ------------------------------------------------------- */
1911 class SNMPgeneric {
1912
1913 protected $host;
1914 protected $version;
1915
1916 /* SNMPv1 and SNMPv2c */
1917 protected $community;
1918
1919 /* SNMPv3 */
1920 protected $sec_level;
1921 protected $auth_protocol;
1922 protected $auth_passphrase;
1923 protected $priv_protocol;
1924 protected $priv_passphrase;
1925 // protected $contextName;
1926 // protected $contextEngineID;
1927
1928 const VERSION_1 = 1;
1929 const VERSION_2C = 2;
1930 const VERSION_3 = 3;
1931
1932 protected $result;
1933
1934 function __construct($version, $host, $community) {
1935
1936 $this->host = $host;
1937 $this->version = $version;
1938 $this->community = $community;
1939
1940 set_error_handler(array($this,'ErrorHandler'), E_WARNING);
1941 }
1942
1943 function setSecurity($sec_level, $auth_protocol = 'md5', $auth_passphrase = '', $priv_protocol = 'des', $priv_passphrase = '') {
1944 $this->sec_level = $sec_level;
1945 $this->auth_protocol = $auth_protocol;
1946 $this->auth_passphrase = $auth_passphrase;
1947 $this->priv_protocol = $priv_protocol;
1948 $this->priv_passphrase = $priv_passphrase;
1949 }
1950
1951 function walk( $oid, $suffix_as_key = FALSE) {
1952
1953 switch($this->version) {
1954 case self::VERSION_1:
1955 if($suffix_as_key){
1956 $this->result = snmpwalk($this->host,$this->community,$oid);
1957 } else {
1958 $this->result = snmprealwalk($this->host,$this->community,$oid);
1959 }
1960 break;
1961
1962 case self::VERSION_2C:
1963 if($suffix_as_key){
1964 $this->result = snmp2_walk($this->host,$this->community,$oid);
1965 } else {
1966 $this->result = snmp2_real_walk($this->host,$this->community,$oid);
1967 }
1968 break;
1969
1970 case self::VERSION_3:
1971 if($suffix_as_key){
1972 $this->result = snmp3_walk($this->host,$this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$oid);
1973 } else {
1974 $this->result = snmp3_real_walk($this->host,$this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$oid);
1975 }
1976 break;
1977 }
1978
1979 return $this->result;
1980
1981 }
1982
1983 private function __snmpget($object_id) {
1984
1985 $retval = FALSE;
1986
1987 switch($this->version) {
1988 case self::VERSION_1:
1989 $retval = snmpget($this->host,$this->community,$object_id);
1990 break;
1991
1992 case self::VERSION_2C:
1993 $retval = snmp2_get($this->host,$this->community,$object_id);
1994 break;
1995
1996 case self::VERSION_3:
1997 $retval = snmp3_get($this->host,$this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$object_id);
1998 break;
1999 }
2000
2001 return $retval;
2002 }
2003
2004 function get($object_id, $preserve_keys = false) {
2005
2006 if(is_array($object_id)) {
2007
2008 if( $preserve_keys ) {
2009 foreach($object_id as $oid) {
2010 $this->result[$oid] = $this->__snmpget($oid);
2011 }
2012 unset($oid);
2013 } else {
2014 foreach($object_id as $oid) {
2015 $result_oid = preg_replace('/.\d$/','',$oid);
2016 $this->result[$result_oid] = $this->__snmpget($oid);
2017 }
2018 unset($oid);
2019 }
2020 } else {
2021 $this->result = $this->__snmpget($object_id);
2022 }
2023
2024 return $this->result;
2025
2026 }
2027
2028 function close() {
2029 }
2030
2031 function getErrno() {
2032 return ($this->result === FALSE);
2033 }
2034
2035 function getError() {
2036 $var = error_get_last();
2037 return $var['message'];
2038 }
2039
2040 function Errorhandler($errno, $errstr, $errfile, $errline) {
2041 switch(TRUE) {
2042 case (False !== strpos($errstr,'No Such Object available on this agent at this OID')):
2043 /* no further error processing */
2044 return true;
2045 break;
2046 }
2047
2048 /* proceed with default error handling */
2049 return false;
2050 }
2051 } /* SNMPgeneric */
2052
2053 /* ------------------------------------------------------- */
2054 /*
2055 * SNMP with system OIDs
2056 */
2057 class mySNMP extends SNMPgeneric implements Iterator {
2058
2059 const SNMP_VERSION = SNMPgeneric::VERSION_2C;
2060 const SNMP_COMMUNITY = 'public';
2061
2062 public $lastgetoid;
2063
2064 //private $sysInfo;
2065 private $system;
2066
2067 /* is system table available ? */
2068 private $systemerror = TRUE;
2069
2070 function __construct($version, $host, $community) {
2071 parent::__construct($version, $host, $community);
2072
2073 //snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
2074
2075 /* Return values without SNMP type hint */
2076 snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
2077
2078 /* needs php >= 5.2.0 */
2079 // snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
2080
2081 // snmp_set_quick_print(1);
2082
2083 } /* __construct */
2084
2085 function init() {
2086 /* .iso.org.dod.internet.mgmt.mib-2.system */
2087 $this->system = $this->walk(".1.3.6.1.2.1.1");
2088
2089 $this->systemerror = $this->getErrno() || empty($this->system);
2090 } /* init() */
2091
2092 /* get value from system cache */
2093 private function _getvalue($object_id) {
2094
2095 /* TODO better matching */
2096
2097 if( isset($this->system["SNMPv2-MIB::$object_id"])) {
2098 $this->lastgetoid = "SNMPv2-MIB::$object_id";
2099 return $this->system["SNMPv2-MIB::$object_id"];
2100 } else {
2101 if( isset($this->system[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"])) {
2102 $this->lastgetoid = ".iso.org.dod.internet.mgmt.mib-2.system.$object_id";
2103 return $this->system[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"];
2104 } else {
2105 if( isset($this->system[$object_id])) {
2106 $this->lastgetoid = $object_id;
2107 return $this->system[$object_id];
2108 } else {
2109 foreach($this->system as $key => $value) {
2110 if(strpos($key, $object_id)) {
2111 $this->lastgetoid = $key;
2112 return $value;
2113 }
2114 }
2115 unset($key);
2116 unset($value);
2117 }
2118 }
2119 }
2120
2121 return NULL;
2122 }
2123
2124 function get($object_id, $preserve_keys = false) {
2125
2126 if(!$this->systemerror)
2127 $retval = $this->_getvalue($object_id);
2128 else
2129 $retval = NULL;
2130
2131 if($retval === NULL) {
2132 $this->lastgetoid = $object_id;
2133 $retval = parent::get($object_id,$preserve_keys);
2134 }
2135
2136 return $retval;
2137
2138 } /* get */
2139
2140 function translatetonumeric($oid) {
2141 global $sg_cmd_snmptranslate;
2142
2143 $val = exec(escapeshellcmd($sg_cmd_snmptranslate).' -On '.escapeshellarg($oid), $output, $retval);
2144
2145 if($retval == 0)
2146 return $val;
2147
2148 return FALSE;
2149
2150 } /* translatetonumeric */
2151 /*
2152 function get_new($object_id, $preserve_keys = false) {
2153 $result = parent::get($object_id,$preserve_keys);
2154 return $this->removeDatatype($result);
2155 }
2156
2157 function walk_new($object_id) {
2158 $result = parent::walk($object_id);
2159 return $this->removeDatatype($result);
2160 }
2161
2162 */
2163 /* use snmp_set_valueretrieval(SNMP_VALUE_PLAIN) instead */
2164 /* function removeDatatype($val) {
2165 return preg_replace('/^\w+: /','',$val);
2166 }
2167 */
2168 /* make something like $class->sysDescr work */
2169 function __get($name) {
2170 if($this->systemerror) {
2171 return;
2172 }
2173
2174 $retval = $this->_getvalue($name);
2175
2176 if($retval === NULL) {
2177
2178 $trace = debug_backtrace();
2179 trigger_error(
2180 'Undefinierte Eigenschaft für __call(): ' . $name .
2181 ' in ' . $trace[0]['file'] .
2182 ' Zeile ' . $trace[0]['line'],
2183 E_USER_NOTICE);
2184 }
2185
2186 return $retval;
2187 }
2188
2189
2190 /* Iteration through all system OIDs */
2191 /* Iterator */
2192
2193 function current() {
2194 if($this->systemerror)
2195 return;
2196
2197 return current($this->system);
2198 }
2199
2200 function key() {
2201 if($this->systemerror)
2202 return;
2203
2204 return key($this->system);
2205 }
2206
2207 function next() {
2208 return next($this->system);
2209 }
2210
2211 function valid() {
2212 return ($this->current() !== FALSE) && ($this->systemerror !== TRUE);
2213 }
2214
2215 function rewind() {
2216 if($this->systemerror)
2217 return;
2218
2219 reset($this->system);
2220 }
2221
2222 /* END Iterator */
2223
2224 } /* mySNMP */
2225
2226 /* ------------------------------------------------------- */
2227
2228 class ifSNMP implements Iterator {
2229 private $snmpdevice;
2230 private $ifNumber = 0;
2231 private $ifTable;
2232
2233 private $interfaceserror = TRUE;
2234
2235 function __construct(&$snmpdevice) {
2236 $this->snmpdevice = $snmpdevice;
2237
2238 $this->ifNumber = intval($this->snmpdevice->get('ifNumber.0'));
2239
2240 $this->interfaceserror = $this->snmpdevice->getErrno();
2241
2242 if(!$this->interfaceserror) {
2243 $this->getifTable();
2244 }
2245 }
2246
2247 function getifTable() {
2248 $this->ifTable['ifIndex'] = $this->snmpdevice->walk('ifIndex',TRUE);
2249 $this->ifTable['ifDescr'] = $this->snmpdevice->walk('ifDescr',TRUE);
2250 $this->ifTable['ifAlias'] = $this->snmpdevice->walk('ifAlias',TRUE);
2251 $this->ifTable['ifName'] = $this->snmpdevice->walk('ifName',TRUE);
2252
2253 $this->ifTable['ifType'] = $this->snmpdevice->walk('ifType',TRUE);
2254
2255 $this->ifTable['ifSpeed'] = $this->snmpdevice->walk('ifSpeed',TRUE);
2256
2257 /* notation changes when SNMP_VALUE_PLAIN is set string -> hex!! */
2258 $this->ifTable['ifPhysAddress'] = $this->snmpdevice->walk('ifPhysAddress',TRUE);
2259
2260 $this->ifTable['ifOperStatus'] = $this->snmpdevice->walk('ifOperStatus',TRUE);
2261
2262 $this->ifTable['ifInOctets'] = $this->snmpdevice->walk('ifInOctets',TRUE);
2263 $this->ifTable['ifOutOctets'] = $this->snmpdevice->walk('ifOutOctets',TRUE);
2264
2265 $this->ifTable['ifConnectorPresent'] = $this->snmpdevice->walk('ifConnectorPresent',TRUE);
2266
2267 $this->ifTable['ipaddress'] = array();
2268
2269 /* ip address v4 only ipaddrtable */
2270 $ipAdEntIfIndex = $this->snmpdevice->walk('ipAdEntIfIndex');
2271
2272 if(!empty($ipAdEntIfIndex)) {
2273 $ipAdEntNetMask = $this->snmpdevice->walk('ipAdEntNetMask');
2274
2275 /* all addresses per interface */
2276
2277 reset($ipAdEntNetMask);
2278 foreach($ipAdEntIfIndex as $oid => $value) {
2279
2280 $netmask = current($ipAdEntNetMask);
2281 next($ipAdEntNetMask);
2282
2283 $ipaddr = preg_replace('/.*\.([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/','$1',$oid);
2284
2285 $ifindex = array_search($value,$this->ifTable['ifIndex']);
2286
2287 if($netmask != '0.0.0.0') {
2288 $maskbits = 32-log((ip2long($netmask) ^ 0xffffffff)+1,2);
2289 $net = ip2long($ipaddr) & ip2long($netmask);
2290 $bcast = $net | ( ip2long($netmask) ^ 0xffffffff);
2291
2292 $this->ifTable['ipaddress'][$ifindex][$ipaddr] = array(
2293 'addrtype' => 'ipv4',
2294 'maskbits' => $maskbits,
2295 'net' => long2ip($net),
2296 'bcast' => long2ip($bcast)
2297 );
2298 }
2299
2300 }
2301 unset($oid);
2302 unset($value);
2303
2304 // sg_var_dump_html($this->ipaddress);
2305 // sg_var_dump_html($ipAdEntIfIndex);
2306 // sg_var_dump_html($ipAdEntNetMask);
2307 } /* ipadentifindex */
2308
2309 /* ipv4 ipv6 ipaddresstable */
2310 /* also overwrites ipv4 from ipaddrtable */
2311 $ipAddressIfIndex = $this->snmpdevice->walk('ipAddressIfIndex');
2312
2313 if(!empty($ipAddressIfIndex)) {
2314 $ipAddressPrefix = $this->snmpdevice->walk('ipAddressPrefix');
2315 $ipAddressType = $this->snmpdevice->walk('ipAddressType'); /* 1 unicast, 2 anycast, 3 braodcast */
2316
2317 reset($ipAddressPrefix);
2318 reset($ipAddressType);
2319 foreach($ipAddressIfIndex as $oid => $value) {
2320
2321 $prefix = current($ipAddressPrefix);
2322 next($ipAddressPrefix);
2323
2324 $type = current($ipAddressType);
2325 next($ipAddressType);
2326
2327 if(!preg_match('/.*\.(ipv[46]z?)\.\"(.*)"$/',$oid, $matches))
2328 continue;
2329
2330 /* ipv4 or ipv6 address */
2331 $ifindex = array_search($value,$this->ifTable['ifIndex']);
2332
2333 $net = NULL;
2334 $maskbits = NULL;
2335 $bcast = NULL;
2336
2337 if(preg_match('/\."([\.0-9a-fA-F:%]+)"\.([0-9]+)$/',$prefix,$prefixmatches)) {
2338 $net = $prefixmatches[1];
2339 $maskbits = $prefixmatches[2];
2340
2341 /* ipv4 */
2342 if($matches[1] == 'ipv4z' || $matches[1] == 'ipv4') {
2343 $intnetmask = (int)(0xffffffff << (32 - $maskbits));
2344 $intnet = ip2long($net) & $intnetmask;
2345 $intbcast = $intnet | ( $intnetmask ^ 0xffffffff);
2346
2347 $net = long2ip($intnet);
2348 $bcast = long2ip($intbcast);
2349 }
2350 }
2351
2352 $this->ifTable['ipaddress'][$ifindex][$matches[2]] = array(
2353 'addrtype' => $matches[1],
2354 'maskbits' => $maskbits,
2355 'net' => $net,
2356 'bcast' => $bcast
2357 );
2358 }
2359 unset($oid);
2360 unset($value);
2361
2362 // sg_var_dump_html($ipAddressIfIndex);
2363 // sg_var_dump_html($ipAddressPrefix);
2364 } /* ipaddressifindex */
2365
2366 }
2367
2368 function printifInfoTableHeader($suffix = "") {
2369 if($this->interfaceserror) {
2370 return;
2371 }
2372
2373 echo "<tr>";
2374 foreach ($this->ifTable as $key => $value) {
2375
2376 switch($key) {
2377 case 'ifOperStatus':
2378 $displayvalue = 'if Oper Status';
2379 break;
2380 case 'ifConnectorPresent':
2381 $displayvalue = 'if Con Pres';
2382 break;
2383 case 'ipaddress':
2384 case 'ipaddressv6':
2385 $displayvalue='';
2386 break;
2387 default:
2388 $displayvalue = $key;
2389 }
2390
2391 if(!empty($displayvalue))
2392 echo "<th title=\"$key\">$displayvalue</th>";
2393 }
2394 unset($key);
2395 unset($value);
2396
2397 echo "$suffix</tr>";
2398 }
2399
2400 private $formfieldlist = array('ifName', 'ifDescr', 'ifAlias', 'ifPhysAddress');
2401
2402 function printifInfoTableRow($ifIndex, $suffix = "", $hrefs = NULL) {
2403 if($this->interfaceserror) {
2404 return;
2405 }
2406
2407 echo "<tr".($ifIndex % 2 ? ' style="background-color:#d8d8d8"' : '' ).">";
2408
2409 foreach ($this->ifTable as $key => $value) {
2410
2411 if($key == 'ipaddress' || $key == 'ipaddressv6')
2412 continue;
2413
2414 $textfield = FALSE;
2415
2416 /* minimize posted data to necessary fields */
2417 if(in_array($key,$this->formfieldlist)) {
2418
2419 /* $value would contain raw values; $this->{$key}($ifIndex) post processed values */
2420 $fieldvalue = $this->{$key}($ifIndex);
2421
2422 if(!empty($fieldvalue)) {
2423 if($key == 'ifDescr' || $key == 'ifAlias') {
2424 $formfield = '<input readonly="readonly" type="text" size="15" name="'.$key.'['.$ifIndex.']" value="'
2425 .$this->$key($ifIndex).'">';
2426 $textfield = TRUE;
2427 } else {
2428 $formfield = '<input type="hidden" name="'.$key.'['.$ifIndex.']" value="'.$fieldvalue.'">';
2429 echo $formfield;
2430 }
2431 } else {
2432 if($key == 'ifName') {
2433 /* create textfield set to ifDescr */
2434 $formfield = '<input type="text" size="8" name="'.$key.'['.$ifIndex.']" value="'
2435 .$this->ifDescr($ifIndex).'">';
2436 $textfield = TRUE;
2437 }
2438
2439 }
2440
2441 }
2442
2443
2444 if($textfield)
2445 $displayvalue=$formfield;
2446 else {
2447 $displayvalue = $this->{$key}($ifIndex);
2448
2449 if(isset($hrefs) && isset($hrefs[$key])) {
2450 $displayvalue = "<a href=".$hrefs[$key].">$displayvalue</a>";
2451 }
2452 }
2453
2454 echo "<td nowrap=\"nowrap\">$displayvalue</td>";
2455 }
2456 unset($key);
2457 unset($value);
2458
2459 echo "$suffix</tr>";
2460 }
2461
2462 function formatMACAddr($addr) {
2463
2464 $retval = '';
2465
2466 /* TODO test origin format */
2467 if(strlen($addr)== 6 ) {
2468 $retval = unpack('H12',$addr);
2469 $retval = $retval[1];
2470 }
2471
2472 /* often used as loopback on Enterasys switches */
2473 if($retval == '000000000000') {
2474 $retval = '';
2475 }
2476
2477 return $retval;
2478 }
2479
2480 function ifPhysAddress($index) {
2481
2482 if(isset($this->ifTable['ifPhysAddress'][$index-1])) {
2483 return strtoupper($this->formatMACAddr($this->ifTable['ifPhysAddress'][$index-1]));
2484 }
2485 }
2486
2487 function ipaddress($index) {
2488 if(isset($this->ifTable['ipaddress'][$index-1])) {
2489 return $this->ifTable['ipaddress'][$index-1];
2490 }
2491
2492 }
2493
2494 function &__get($name) {
2495
2496 switch($name) {
2497 case 'ifNumber':
2498 return $this->{$name};
2499 break;
2500 case 'ipaddress':
2501 return $this->ifTable['ipaddress'];
2502 break;
2503 }
2504
2505 $trace = debug_backtrace();
2506
2507 trigger_error(
2508 'Undefinierte Eigenschaft für __get(): ' . $name .
2509 ' in ' . $trace[0]['file'] .
2510 ' Zeile ' . $trace[0]['line'],
2511 E_USER_NOTICE);
2512
2513 return NULL;
2514 }
2515
2516 /* $obj->ifDescr(3) = $ifTable[$name][$arg]*/
2517 function __call($name,$args) {
2518
2519 if($this->interfaceserror)
2520 return;
2521
2522 if(isset($this->ifTable[$name])) {
2523 if(isset($this->ifTable[$name][$args[0]-1])) {
2524 return $this->ifTable[$name][$args[0]-1];
2525 }
2526 } else {
2527
2528 /* for debug */
2529 $trace = debug_backtrace();
2530
2531 trigger_error(
2532 'Undefinierte Methode für __call(): ' . $name .
2533 ' in ' . $trace[0]['file'] .
2534 ' Zeile ' . $trace[0]['line'],
2535 E_USER_NOTICE);
2536 }
2537
2538 return NULL;
2539
2540 } /* __call */
2541
2542 /* Iterator */
2543
2544 private $IteratorIndex = 1;
2545
2546 function current() {
2547 return $this->IteratorIndex;
2548 }
2549
2550 function key() {
2551 }
2552
2553 function next() {
2554 $this->IteratorIndex++;
2555 }
2556
2557 function valid() {
2558 return ($this->IteratorIndex<=$this->ifNumber);
2559 }
2560
2561 function rewind() {
2562 $this->IteratorIndex = 1;
2563 }
2564
2565 /* END Iterator */
2566 }
2567
2568 /* ------------------------------------------------------- */
2569 /* ------------------------------------------------------- */
2570 /* for debugging */
2571 function sg_var_dump_html(&$var, $text = '') {
2572
2573 echo "<pre>------------------Start Var Dump - $text -----------------------\n";
2574 var_dump($var);
2575 echo "\n---------------------END Var Dump - $text -----------------------</pre>";
2576 }
2577 ?>