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