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