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