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