Completed
Pull Request — master (#2936)
by
unknown
04:53
created

includes/snmp.inc.php (3 issues)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/*
3
 * LibreNMS - SNMP Functions
4
 *
5
 * Original Observium code by: Adam Armstrong, Tom Laermans
6
 * Copyright (c) 2010-2012 Adam Armstrong.
7
 *
8
 * Additions for LibreNMS by Paul Gear
9
 * Copyright (c) 2014-2015 Gear Consulting Pty Ltd <http://libertysys.com.au/>
10
 *
11
 * This program is free software: you can redistribute it and/or modify it
12
 * under the terms of the GNU General Public License as published by the
13
 * Free Software Foundation, either version 3 of the License, or (at your
14
 * option) any later version.  Please see LICENSE.txt at the top level of
15
 * the source code distribution for details.
16
 */
17
18
function string_to_oid($string) {
19
    $oid = strlen($string);
20
    for ($i = 0; $i != strlen($string); $i++) {
21
        $oid .= '.'.ord($string[$i]);
22
    }
23
24
    return $oid;
25
26
}//end string_to_oid()
27
28
29
function prep_snmp_setting($device, $setting) {
30
    global $config;
31
32
    if (is_numeric($device[$setting]) && $device[$setting] > 0) {
33
        return $device[$setting];
34
    }
35
    else if (isset($config['snmp'][$setting])) {
36
        return $config['snmp'][$setting];
37
    }
38
39
}//end prep_snmp_setting()
40
41
42
function mibdir($mibdir) {
43
    global $config;
44
    return ' -M '.($mibdir ? $mibdir : $config['mibdir']);
45
46
}//end mibdir()
47
48
49
function snmp_get_multi($device, $oids, $options='-OQUs', $mib=null, $mibdir=null) {
50
    global $debug,$config,$runtime_stats,$mibs_loaded;
51
52
    // populate timeout & retries values from configuration
53
    $timeout = prep_snmp_setting($device, 'timeout');
54
    $retries = prep_snmp_setting($device, 'retries');
55
56
    if (!isset($device['transport'])) {
57
        $device['transport'] = 'udp';
58
    }
59
60
    $cmd  = $config['snmpget'];
61
    $cmd .= snmp_gen_auth($device);
62
63
    if ($options) {
64
        $cmd .= ' '.$options;
65
    }
66
67
    if ($mib) {
68
        $cmd .= ' -m '.$mib;
69
    }
70
71
    $cmd .= mibdir($mibdir);
72
73
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
74
    $cmd .= isset($retries) ? ' -r '.$retries : '';
75
76
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'];
77
    $cmd .= ' '.$oids;
78
79
    if (!$debug) {
80
        $cmd .= ' 2>/dev/null';
81
    }
82
83
    $data = trim(external_exec($cmd));
84
    $runtime_stats['snmpget']++;
85
    $array = array();
86 View Code Duplication
    foreach (explode("\n", $data) as $entry) {
87
        list($oid,$value)  = explode('=', $entry, 2);
88
        $oid               = trim($oid);
89
        $value             = trim($value);
90
        list($oid, $index) = explode('.', $oid, 2);
91
        if (!strstr($value, 'at this OID') && isset($oid) && isset($index)) {
92
            $array[$index][$oid] = $value;
93
        }
94
    }
95
96
    return $array;
97
98
}//end snmp_get_multi()
99
100
101
function snmp_get($device, $oid, $options=null, $mib=null, $mibdir=null) {
102
    global $debug,$config,$runtime_stats,$mibs_loaded;
103
104
    $timeout = prep_snmp_setting($device, 'timeout');
105
    $retries = prep_snmp_setting($device, 'retries');
106
107
    if (!isset($device['transport'])) {
108
        $device['transport'] = 'udp';
109
    }
110
111
    if (strstr($oid, ' ')) {
112
        echo report_this_text("snmp_get called for multiple OIDs: $oid");
113
    }
114
115
    $cmd  = $config['snmpget'];
116
    $cmd .= snmp_gen_auth($device);
117
118
    if ($options) {
119
        $cmd .= ' '.$options;
120
    }
121
122
    if ($mib) {
123
        $cmd .= ' -m '.$mib;
124
    }
125
126
    $cmd .= mibdir($mibdir);
127
128
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
129
    $cmd .= isset($retries) ? ' -r '.$retries : '';
130
131
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'];
132
    $cmd .= ' '.$oid;
133
134
    if (!$debug) {
135
        $cmd .= ' 2>/dev/null';
136
    }
137
138
    $data = trim(external_exec($cmd));
139
140
    $runtime_stats['snmpget']++;
141
142
    if (is_string($data) && (preg_match('/(No Such Instance|No Such Object|No more variables left|Authentication failure)/i', $data))) {
143
        return false;
144
    }
145
    elseif ($data || $data === '0') {
146
        return $data;
147
    }
148
    else {
149
        return false;
150
    }
151
152
}//end snmp_get()
153
154
155
function snmp_walk($device, $oid, $options=null, $mib=null, $mibdir=null) {
156
    global $debug,$config,$runtime_stats;
157
158
    $timeout = prep_snmp_setting($device, 'timeout');
159
    $retries = prep_snmp_setting($device, 'retries');
160
161
    if (!isset($device['transport'])) {
162
        $device['transport'] = 'udp';
163
    }
164
165 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
166
        $snmpcommand = $config['snmpwalk'];
167
    }
168
    else {
169
        $snmpcommand = $config['snmpbulkwalk'];
170
    }
171
172
    $cmd = $snmpcommand;
173
174
    $cmd .= snmp_gen_auth($device);
175
176
    if ($options) {
177
        $cmd .= " $options ";
178
    }
179
180
    if ($mib) {
181
        $cmd .= " -m $mib";
182
    }
183
184
    $cmd .= mibdir($mibdir);
185
186
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
187
    $cmd .= isset($retries) ? ' -r '.$retries : '';
188
189
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$oid;
190
191
    if (!$debug) {
192
        $cmd .= ' 2>/dev/null';
193
    }
194
195
    $data = trim(external_exec($cmd));
196
    $data = str_replace('"', '', $data);
197
198
    if (is_string($data) && (preg_match('/No Such (Object|Instance)/i', $data))) {
199
        $data = false;
200
    }
201
    else {
202
        if (preg_match('/No more variables left in this MIB View \(It is past the end of the MIB tree\)$/', $data)) {
203
            // Bit ugly :-(
204
            $d_ex = explode("\n", $data);
205
            unset($d_ex[(count($d_ex) - 1)]);
206
            $data = implode("\n", $d_ex);
207
        }
208
    }
209
210
    $runtime_stats['snmpwalk']++;
211
212
    return $data;
213
214
}//end snmp_walk()
215
216
217
function snmpwalk_cache_cip($device, $oid, $array=array(), $mib=0) {
218
    global $config, $debug;
219
220
    $timeout = prep_snmp_setting($device, 'timeout');
221
    $retries = prep_snmp_setting($device, 'retries');
222
223
    if (!isset($device['transport'])) {
224
        $device['transport'] = 'udp';
225
    }
226
227 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
228
        $snmpcommand = $config['snmpwalk'];
229
    }
230
    else {
231
        $snmpcommand = $config['snmpbulkwalk'];
232
    }
233
234
    $cmd  = $snmpcommand;
235
    $cmd .= snmp_gen_auth($device);
236
237
    $cmd .= ' -O snQ';
238
    if ($mib) {
239
        $cmd .= " -m $mib";
240
    }
241
242
    $cmd .= mibdir(null);
243
244
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
245
    $cmd .= isset($retries) ? ' -r '.$retries : '';
246
247
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$oid;
248
249
    if (!$debug) {
250
        $cmd .= ' 2>/dev/null';
251
    }
252
253
    $data      = trim(external_exec($cmd));
254
255
    // echo("Caching: $oid\n");
256
    foreach (explode("\n", $data) as $entry) {
257
        list ($this_oid, $this_value) = preg_split('/=/', $entry);
258
        $this_oid   = trim($this_oid);
259
        $this_value = trim($this_value);
260
        $this_oid   = substr($this_oid, 30);
261
        list($ifIndex, $dir, $a, $b, $c, $d, $e, $f) = explode('.', $this_oid);
262
        $h_a = zeropad(dechex($a));
263
        $h_b = zeropad(dechex($b));
264
        $h_c = zeropad(dechex($c));
265
        $h_d = zeropad(dechex($d));
266
        $h_e = zeropad(dechex($e));
267
        $h_f = zeropad(dechex($f));
268
        $mac = "$h_a$h_b$h_c$h_d$h_e$h_f";
269
270
        if ($dir == '1') {
271
            $dir = 'input';
272
        }
273
        else if ($dir == '2') {
274
            $dir = 'output';
275
        }
276
277
        if ($mac && $dir) {
278
            $array[$ifIndex][$mac][$oid][$dir] = $this_value;
279
        }
280
    }//end foreach
281
282
    return $array;
283
284
}//end snmpwalk_cache_cip()
285
286
287
function snmp_cache_ifIndex($device) {
288
    // FIXME: this is not yet using our own snmp_*
289
    global $config, $debug;
290
291
    $timeout = prep_snmp_setting($device, 'timeout');
292
    $retries = prep_snmp_setting($device, 'retries');
293
294
    if (!isset($device['transport'])) {
295
        $device['transport'] = 'udp';
296
    }
297
298 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
299
        $snmpcommand = $config['snmpwalk'];
300
    }
301
    else {
302
        $snmpcommand = $config['snmpbulkwalk'];
303
    }
304
305
    $cmd  = $snmpcommand;
306
    $cmd .= snmp_gen_auth($device);
307
308
    $cmd .= ' -O Qs';
309
    $cmd .= mibdir(null);
310
    $cmd .= ' -m IF-MIB ifIndex';
311
312
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
313
    $cmd .= isset($retries) ? ' -r '.$retries : '';
314
315
    if (!$debug) {
316
        $cmd .= ' 2>/dev/null';
317
    }
318
319
    $data      = trim(external_exec($cmd));
320
321
    $array = array();
322
    foreach (explode("\n", $data) as $entry) {
323
        list ($this_oid, $this_value) = preg_split('/=/', $entry);
324
        list ($this_oid, $this_index) = explode('.', $this_oid, 2);
325
        $this_index                   = trim($this_index);
326
        $this_oid   = trim($this_oid);
327
        $this_value = trim($this_value);
328
        if (!strstr($this_value, 'at this OID') && $this_index) {
329
            $array[] = $this_value;
330
        }
331
    }
332
333
    return $array;
334
335
}//end snmp_cache_ifIndex()
336
337
338
function snmpwalk_cache_oid($device, $oid, $array, $mib=null, $mibdir=null, $snmpflags='-OQUs') {
339
    $data = snmp_walk($device, $oid, $snmpflags, $mib, $mibdir);
340 View Code Duplication
    foreach (explode("\n", $data) as $entry) {
341
        list($oid,$value)  = explode('=', $entry, 2);
342
        $oid               = trim($oid);
343
        $value             = trim($value);
344
        list($oid, $index) = explode('.', $oid, 2);
345
        if (!strstr($value, 'at this OID') && isset($oid) && isset($index)) {
346
            $array[$index][$oid] = $value;
347
        }
348
    }
349
350
    return $array;
351
352
}//end snmpwalk_cache_oid()
353
354
355
// just like snmpwalk_cache_oid except that it returns the numerical oid as the index
356
// this is useful when the oid is indexed by the mac address and snmpwalk would
357
// return periods (.) for non-printable numbers, thus making many different indexes appear
358
// to be the same.
359
function snmpwalk_cache_oid_num($device, $oid, $array, $mib=null, $mibdir=null) {
360
    return snmpwalk_cache_oid($device, $oid, $array, $mib, $mibdir, $snmpflags = '-OQUn');
361
362
}//end snmpwalk_cache_oid_num()
363
364
365
function snmpwalk_cache_multi_oid($device, $oid, $array, $mib=null, $mibdir=null) {
366
    global $cache;
367
368
    if (!(is_array($cache['snmp'][$device['device_id']]) && array_key_exists($oid, $cache['snmp'][$device['device_id']]))) {
369
        $data = snmp_walk($device, $oid, '-OQUs', $mib, $mibdir);
370
        foreach (explode("\n", $data) as $entry) {
371
            list($r_oid,$value) = explode('=', $entry, 2);
372
            $r_oid              = trim($r_oid);
373
            $value              = trim($value);
374
            $oid_parts          = explode('.', $r_oid);
375
            $r_oid              = $oid_parts['0'];
376
            $index              = $oid_parts['1'];
377
            if (isset($oid_parts['2'])) {
378
                $index .= '.'.$oid_parts['2'];
379
            }
380
381
            if (isset($oid_parts['3'])) {
382
                $index .= '.'.$oid_parts['3'];
383
            }
384
385
            if (isset($oid_parts['4'])) {
386
                $index .= '.'.$oid_parts['4'];
387
            }
388
389
            if (isset($oid_parts['5'])) {
390
                $index .= '.'.$oid_parts['5'];
391
            }
392
393
            if (isset($oid_parts['6'])) {
394
                $index .= '.'.$oid_parts['6'];
395
            }
396
397
            if (!strstr($value, 'at this OID') && isset($r_oid) && isset($index)) {
398
                $array[$index][$r_oid] = $value;
399
            }
400
        }//end foreach
401
402
        $cache['snmp'][$device['device_id']][$oid] = $array;
403
    }//end if
404
405
    return $cache['snmp'][$device['device_id']][$oid];
406
407
}//end snmpwalk_cache_multi_oid()
408
409
410 View Code Duplication
function snmpwalk_cache_double_oid($device, $oid, $array, $mib=null, $mibdir=null) {
411
    $data = snmp_walk($device, $oid, '-OQUs', $mib, $mibdir);
412
413
    foreach (explode("\n", $data) as $entry) {
414
        list($oid,$value) = explode('=', $entry, 2);
415
        $oid              = trim($oid);
416
        $value            = trim($value);
417
        list($oid, $first, $second) = explode('.', $oid);
418
        if (!strstr($value, 'at this OID') && isset($oid) && isset($first) && isset($second)) {
419
            $double               = $first.'.'.$second;
420
            $array[$double][$oid] = $value;
421
        }
422
    }
423
424
    return $array;
425
426
}//end snmpwalk_cache_double_oid()
427
428
429 View Code Duplication
function snmpwalk_cache_triple_oid($device, $oid, $array, $mib=null, $mibdir=null) {
430
    $data = snmp_walk($device, $oid, '-OQUs', $mib, $mibdir);
431
432
    foreach (explode("\n", $data) as $entry) {
433
        list($oid,$value) = explode('=', $entry, 2);
434
        $oid              = trim($oid);
435
        $value            = trim($value);
436
        list($oid, $first, $second, $third) = explode('.', $oid);
437
        if (!strstr($value, 'at this OID') && isset($oid) && isset($first) && isset($second)) {
438
            $index               = $first.'.'.$second.'.'.$third;
439
            $array[$index][$oid] = $value;
440
        }
441
    }
442
443
    return $array;
444
445
}//end snmpwalk_cache_triple_oid()
446
447
448
function snmpwalk_cache_twopart_oid($device, $oid, $array, $mib=0) {
449
    global $config, $debug;
450
451
    $timeout = prep_snmp_setting($device, 'timeout');
452
    $retries = prep_snmp_setting($device, 'retries');
453
454
    if (!isset($device['transport'])) {
455
        $device['transport'] = 'udp';
456
    }
457
458 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
459
        $snmpcommand = $config['snmpwalk'];
460
    }
461
    else {
462
        $snmpcommand = $config['snmpbulkwalk'];
463
    }
464
465
    $cmd  = $snmpcommand;
466
    $cmd .= snmp_gen_auth($device);
467
468
    $cmd .= ' -O QUs';
469
    $cmd .= mibdir(null);
470
471
    if ($mib) {
472
        $cmd .= " -m $mib";
473
    }
474
475
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
476
    $cmd .= isset($retries) ? ' -r '.$retries : '';
477
478
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$oid;
479
480
    if (!$debug) {
481
        $cmd .= ' 2>/dev/null';
482
    }
483
484
    $data = trim(external_exec($cmd));
485
486
    foreach (explode("\n", $data) as $entry) {
487
        list($oid,$value) = explode('=', $entry, 2);
488
        $oid              = trim($oid);
489
        $value            = trim($value);
490
        $value            = str_replace('"', '', $value);
491
        list($oid, $first, $second) = explode('.', $oid);
492
        if (!strstr($value, 'at this OID') && isset($oid) && isset($first) && isset($second)) {
493
            $array[$first][$second][$oid] = $value;
494
        }
495
    }
496
497
    return $array;
498
499
}//end snmpwalk_cache_twopart_oid()
500
501
502
function snmpwalk_cache_threepart_oid($device, $oid, $array, $mib=0) {
503
    global $config, $debug;
504
505
    $timeout = prep_snmp_setting($device, 'timeout');
506
    $retries = prep_snmp_setting($device, 'retries');
507
508
    if (!isset($device['transport'])) {
509
        $device['transport'] = 'udp';
510
    }
511
512 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
513
        $snmpcommand = $config['snmpwalk'];
514
    }
515
    else {
516
        $snmpcommand = $config['snmpbulkwalk'];
517
    }
518
519
    $cmd  = $snmpcommand;
520
    $cmd .= snmp_gen_auth($device);
521
522
    $cmd .= ' -O QUs';
523
    $cmd .= mibdir(null);
524
    if ($mib) {
525
        $cmd .= " -m $mib";
526
    }
527
528
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
529
    $cmd .= isset($retries) ? ' -r '.$retries : '';
530
531
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$oid;
532
533
    if (!$debug) {
534
        $cmd .= ' 2>/dev/null';
535
    }
536
537
    $data = trim(external_exec($cmd));
538
539
    foreach (explode("\n", $data) as $entry) {
540
        list($oid,$value) = explode('=', $entry, 2);
541
        $oid              = trim($oid);
542
        $value            = trim($value);
543
        $value            = str_replace('"', '', $value);
544
        list($oid, $first, $second, $third) = explode('.', $oid);
545
546
        if ($debug) {
547
            echo "$entry || $oid || $first || $second || $third\n";
548
        }
549
550
        if (!strstr($value, 'at this OID') && isset($oid) && isset($first) && isset($second) && isset($third)) {
551
            $array[$first][$second][$third][$oid] = $value;
552
        }
553
    }
554
555
    return $array;
556
557
}//end snmpwalk_cache_threepart_oid()
558
559
560
function snmp_cache_slotport_oid($oid, $device, $array, $mib=0) {
561
    global $config, $debug;
562
563
    $timeout = prep_snmp_setting($device, 'timeout');
564
    $retries = prep_snmp_setting($device, 'retries');
565
566
    if (!isset($device['transport'])) {
567
        $device['transport'] = 'udp';
568
    }
569
570 View Code Duplication
    if ($device['snmpver'] == 'v1' || $config['os'][$device['os']]['nobulk']) {
571
        $snmpcommand = $config['snmpwalk'];
572
    }
573
    else {
574
        $snmpcommand = $config['snmpbulkwalk'];
575
    }
576
577
    $cmd  = $snmpcommand;
578
    $cmd .= snmp_gen_auth($device);
579
580
    $cmd .= ' -O QUs';
581
    if ($mib) {
582
        $cmd .= " -m $mib";
583
    }
584
585
    $cmd .= mibdir(null);
586
587
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
588
    $cmd .= isset($retries) ? ' -r '.$retries : '';
589
590
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$oid;
591
592
    if (!$debug) {
593
        $cmd .= ' 2>/dev/null';
594
    }
595
596
    $data      = trim(external_exec($cmd));
597
598
    foreach (explode("\n", $data) as $entry) {
599
        $entry                  = str_replace($oid.'.', '', $entry);
600
        list($slotport, $value) = explode('=', $entry, 2);
601
        $slotport               = trim($slotport);
602
        $value                  = trim($value);
603 View Code Duplication
        if ($array[$slotport]['ifIndex']) {
604
            $ifIndex               = $array[$slotport]['ifIndex'];
605
            $array[$ifIndex][$oid] = $value;
606
        }
607
    }
608
609
    return $array;
610
611
}//end snmp_cache_slotport_oid()
612
613
614
function snmp_cache_oid($oid, $device, $array, $mib=0) {
615
    $array = snmpwalk_cache_oid($device, $oid, $array, $mib);
616
    return $array;
617
618
}//end snmp_cache_oid()
619
620
621
function snmp_cache_port_oids($oids, $port, $device, $array, $mib=0) {
622
    global $config, $debug;
623
624
    $timeout = prep_snmp_setting($device, 'timeout');
625
    $retries = prep_snmp_setting($device, 'retries');
626
627
    if (!isset($device['transport'])) {
628
        $device['transport'] = 'udp';
629
    }
630
631
    foreach ($oids as $oid) {
632
        $string .= " $oid.$port";
633
    }
634
635
    $cmd  = $config['snmpget'];
636
    $cmd .= snmp_gen_auth($device);
637
638
    $cmd .= ' -O vq';
639
640
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
641
    $cmd .= isset($retries) ? ' -r '.$retries : '';
642
643
    $cmd .= mibdir(null);
644
    if ($mib) {
645
        $cmd .= " -m $mib";
646
    }
647
648
    $cmd .= ' -t '.$timeout.' -r '.$retries;
649
    $cmd .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' '.$string;
650
651
    if (!$debug) {
652
        $cmd .= ' 2>/dev/null';
653
    }
654
655
    $data   = trim(external_exec($cmd));
656
    $x      = 0;
657
    $values = explode("\n", $data);
658
    // echo("Caching: ifIndex $port\n");
659
    foreach ($oids as $oid) {
660
        if (!strstr($values[$x], 'at this OID')) {
661
            $array[$port][$oid] = $values[$x];
662
        }
663
664
        $x++;
665
    }
666
667
    return $array;
668
669
}//end snmp_cache_port_oids()
670
671
672
function snmp_cache_portIfIndex($device, $array) {
673
    global $config;
674
675
    $timeout = prep_snmp_setting($device, 'timeout');
676
    $retries = prep_snmp_setting($device, 'retries');
677
678
    if (!isset($device['transport'])) {
679
        $device['transport'] = 'udp';
680
    }
681
682
    $cmd  = $config['snmpwalk'];
683
    $cmd .= snmp_gen_auth($device);
684
685
    $cmd .= ' -CI -m CISCO-STACK-MIB -O q';
686
    $cmd .= mibdir(null);
687
688
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
689
    $cmd .= isset($retries) ? ' -r '.$retries : '';
690
691
    $cmd      .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' portIfIndex';
692
    $output    = trim(external_exec($cmd));
693
694
    foreach (explode("\n", $output) as $entry) {
695
        $entry                    = str_replace('CISCO-STACK-MIB::portIfIndex.', '', $entry);
696
        list($slotport, $ifIndex) = explode(' ', $entry, 2);
697 View Code Duplication
        if ($slotport && $ifIndex) {
698
            $array[$ifIndex]['portIfIndex'] = $slotport;
699
            $array[$slotport]['ifIndex']    = $ifIndex;
700
        }
701
    }
702
703
    return $array;
704
705
}//end snmp_cache_portIfIndex()
706
707
708
function snmp_cache_portName($device, $array) {
709
    global $config;
710
711
    $timeout = prep_snmp_setting($device, 'timeout');
712
    $retries = prep_snmp_setting($device, 'retries');
713
714
    if (!isset($device['transport'])) {
715
        $device['transport'] = 'udp';
716
    }
717
718
    $cmd  = $config['snmpwalk'];
719
    $cmd .= snmp_gen_auth($device);
720
721
    $cmd .= ' -CI -m CISCO-STACK-MIB -O Qs';
722
    $cmd .= mibdir(null);
723
724
    $cmd .= isset($timeout) ? ' -t '.$timeout : '';
725
    $cmd .= isset($retries) ? ' -r '.$retries : '';
726
727
    $cmd      .= ' '.$device['transport'].':'.$device['hostname'].':'.$device['port'].' portName';
728
    $output    = trim(external_exec($cmd));
729
    // echo("Caching: portName\n");
730
    foreach (explode("\n", $output) as $entry) {
731
        $entry = str_replace('portName.', '', $entry);
732
        list($slotport, $portName) = explode('=', $entry, 2);
733
        $slotport                  = trim($slotport);
734
        $portName                  = trim($portName);
735
        if ($array[$slotport]['ifIndex']) {
736
            $ifIndex = $array[$slotport]['ifIndex'];
737
            $array[$slotport]['portName'] = $portName;
738
            $array[$ifIndex]['portName']  = $portName;
739
        }
740
    }
741
742
    return $array;
743
744
}//end snmp_cache_portName()
745
746
747
function snmp_gen_auth(&$device) {
748
    global $debug, $vdebug;
749
750
    $cmd = '';
751
752
    if ($device['snmpver'] === 'v3') {
753
        $cmd = " -v3 -n '' -l '".$device['authlevel']."'";
754
755
        if ($device['authlevel'] === 'noAuthNoPriv') {
756
            // We have to provide a username anyway (see Net-SNMP doc)
757
            // FIXME: There are two other places this is set - why are they ignored here?
758
            $cmd .= ' -u root';
759
        }
760
        else if ($device['authlevel'] === 'authNoPriv') {
761
            $cmd .= " -a '".$device['authalgo']."'";
762
            $cmd .= " -A '".$device['authpass']."'";
763
            $cmd .= " -u '".$device['authname']."'";
764
        }
765
        else if ($device['authlevel'] === 'authPriv') {
766
            $cmd .= " -a '".$device['authalgo']."'";
767
            $cmd .= " -A '".$device['authpass']."'";
768
            $cmd .= " -u '".$device['authname']."'";
769
            $cmd .= " -x '".$device['cryptoalgo']."'";
770
            $cmd .= " -X '".$device['cryptopass']."'";
771
        }
772
        else {
773
            if ($debug) {
774
                print 'DEBUG: '.$device['snmpver']." : Unsupported SNMPv3 AuthLevel (wtf have you done ?)\n";
775
            }
776
        }
777
    }
778
    else if ($device['snmpver'] === 'v2c' or $device['snmpver'] === 'v1') {
779
        $cmd  = ' -'.$device['snmpver'];
780
        $cmd .= ' -c '.$device['community'];
781
    }
782
    else {
783
        if ($debug) {
784
            print 'DEBUG: '.$device['snmpver']." : Unsupported SNMP Version (shouldn't be possible to get here)\n";
785
        }
786
    }//end if
787
788
    if ($vdebug) {
789
        print "DEBUG: SNMP Auth options = $cmd\n";
790
    }
791
792
    return $cmd;
793
794
}//end snmp_gen_auth()
795
796
797
/*
798
 * Translate the given MIB into a PHP array.  Each keyword becomes an array index.
799
 *
800
 * Example:
801
 * snmptranslate -Td -On -M mibs -m RUCKUS-ZD-SYSTEM-MIB RUCKUS-ZD-SYSTEM-MIB::ruckusZDSystemStatsNumSta
802
 * .1.3.6.1.4.1.25053.1.2.1.1.1.15.30
803
 * ruckusZDSystemStatsAllNumSta OBJECT-TYPE
804
 *   -- FROM    RUCKUS-ZD-SYSTEM-MIB
805
 *     SYNTAX   Unsigned32
806
 *     MAX-ACCESS       read-only
807
 *     STATUS   current
808
 *     DESCRIPTION      "Number of All client devices"
809
 *   ::= { iso(1) org(3) dod(6) internet(1) private(4) enterprises(1) ruckusRootMIB(25053) ruckusObjects(1) ruckusZD(2) ruckusZDSystemModule(1) ruckusZDSystemMIB(1) ruckusZDSystemObjects(1)
810
 *           ruckusZDSystemStats(15) 30 }
811
 */
812
function snmp_mib_parse($oid, $mib, $module, $mibdir=null) {
813
    $fulloid  = explode('.', $oid);
814
    $lastpart = end($fulloid);
815
816
    $cmd  = 'snmptranslate -Td -On';
817
    $cmd .= mibdir($mibdir);
818
    $cmd .= ' -m '.$module.' '.$module.'::';
819
    $cmd .= $lastpart;
820
821
    $result = array();
822
    $lines  = preg_split('/\n+/', trim(shell_exec($cmd)));
823
    foreach ($lines as $l) {
824
        $f = preg_split('/\s+/', trim($l));
825
        // first line is all numeric
826
        if (preg_match('/^[\d.]+$/', $f[0])) {
827
            $result['oid'] = $f[0];
828
            continue;
829
        }
830
831
        // then the name of the object type
832
        if ($f[1] && $f[1] == 'OBJECT-TYPE') {
833
            $result['object_type'] = $f[0];
834
            continue;
835
        }
836
837
        // then the other data elements
838
        if ($f[0] == '--' && $f[1] == 'FROM') {
839
            $result['module'] = $f[2];
840
            continue;
841
        }
842
843
        if ($f[0] == 'MAX-ACCESS') {
844
            $result['max_access'] = $f[1];
845
            continue;
846
        }
847
848
        if ($f[0] == 'STATUS') {
849
            $result[strtolower($f[0])] = $f[1];
850
            continue;
851
        }
852
853
        if ($f[0] == 'SYNTAX') {
854
            $result[strtolower($f[0])] = $f[1];
855
            continue;
856
        }
857
858
        if ($f[0] == 'DESCRIPTION') {
859
            $desc = explode('"', $l);
860
            if ($desc[1]) {
861
                $str = preg_replace('/^[\s.]*/', '', $desc[1]);
862
                $str = preg_replace('/[\s.]*$/', '', $str);
863
                $result[strtolower($f[0])] = $str;
864
            }
865
866
            continue;
867
        }
868
    }//end foreach
869
870
    // The main mib entry doesn't have any useful data in it - only return items that have the syntax specified.
871
    if (isset($result['syntax']) && isset($result['object_type'])) {
872
        $result['mib'] = $mib;
873
        return $result;
874
    }
875
    else {
876
        return null;
877
    }
878
} // snmp_mib_parse
879
880
881
/*
882
 * Walks through the given MIB module, looking for the given MIB.
883
 * NOTE: different from snmp walk - this doesn't touch the device.
884
 * NOTE: There's probably a better way to do this with snmptranslate.
885
 *
886
 * Example:
887
 * snmptranslate -Ts -M mibs -m RUCKUS-ZD-SYSTEM-MIB | grep ruckusZDSystemStats
888
 * .iso.org.dod.internet.private.enterprises.ruckusRootMIB.ruckusObjects.ruckusZD.ruckusZDSystemModule.ruckusZDSystemMIB.ruckusZDSystemObjects.ruckusZDSystemStats
889
 * .iso.org.dod.internet.private.enterprises.ruckusRootMIB.ruckusObjects.ruckusZD.ruckusZDSystemModule.ruckusZDSystemMIB.ruckusZDSystemObjects.ruckusZDSystemStats.ruckusZDSystemStatsNumAP
890
 * .iso.org.dod.internet.private.enterprises.ruckusRootMIB.ruckusObjects.ruckusZD.ruckusZDSystemModule.ruckusZDSystemMIB.ruckusZDSystemObjects.ruckusZDSystemStats.ruckusZDSystemStatsNumSta
891
 * ...
892
 */
893
894
895
function snmp_mib_walk($mib, $module, $mibdir=null)
896
{
897
    $cmd    = 'snmptranslate -Ts';
898
    $cmd   .= mibdir($mibdir);
899
    $cmd   .= ' -m '.$module;
900
    $result = array();
901
    $data   = preg_split('/\n+/', shell_exec($cmd));
902
    foreach ($data as $oid) {
903
        // only include oids which are part of this mib
904
        if (strstr($oid, $mib)) {
905
            $obj = snmp_mib_parse($oid, $mib, $module, $mibdir);
906
            if ($obj) {
907
                $result[] = $obj;
908
            }
909
        }
910
    }
911
912
    return $result;
913
914
} // snmp_mib_walk
915
916
917
function quote_column($a)
918
{
919
    return '`'.$a.'`';
920
} // quote_column
921
922
923
function join_array($a, $b)
924
{
925
    return quote_column($a).'='.$b;
926
} // join_array
927
928
929
/*
930
 * Update the given table in the database with the given row & column data.
931
 * @param tablename The table to update
932
 * @param columns   An array of column names
933
 * @param numkeys   The number of columns which are in the primary key of the table; these primary keys must be first in the list of columns
934
 * @param rows      Row data to insert, an array of arrays with column names as the second-level keys
935
 */
936
function update_db_table($tablename, $columns, $numkeys, $rows)
937
{
938
    dbBeginTransaction();
939
    foreach ($rows as $nothing => $obj) {
940
        // create a parameter list based on the columns
941
        $params = array();
942
        foreach ($columns as $column) {
943
            $params[] = $obj[$column];
944
        }
945
        $column_placeholders = array_fill(0, count($columns), '?');
946
947
        // build the "ON DUPLICATE KEY" part
948
        $non_key_columns = array_slice($columns, $numkeys);
949
        $non_key_placeholders = array_slice($column_placeholders, $numkeys);
950
        $update_definitions = array_map("join_array", $non_key_columns, $non_key_placeholders);
951
        $non_key_params = array_slice($params, $numkeys);
952
953
        $sql = 'INSERT INTO `' . $tablename . '` (' .
954
            implode(',', array_map("quote_column", $columns)) .
955
            ') VALUES (' . implode(',', $column_placeholders) .
956
            ') ON DUPLICATE KEY UPDATE ' . implode(',', $update_definitions);
957
        $result = dbQuery($sql, array_merge($params, $non_key_params));
958
        d_echo("Result: $result\n");
959
    }
960
    dbCommitTransaction();
961
} // update_db_table
962
963
/*
964
 * Load the given MIB into the database.
965
 * @return count of objects loaded
966
 */
967
function snmp_mib_load($mib, $module, $included_by, $mibdir = null)
968
{
969
    $mibs = array();
970
    foreach (snmp_mib_walk($mib, $module, $mibdir) as $obj) {
971
        $mibs[$obj['object_type']] = $obj;
972
        $mibs[$obj['object_type']]['included_by'] = $included_by;
973
    }
974
    d_print_r($mibs);
975
    // NOTE: `last_modified` omitted due to being automatically maintained by MySQL
976
    $columns = array('module', 'mib', 'object_type', 'oid', 'syntax', 'description', 'max_access', 'status', 'included_by');
977
    update_db_table('mibdefs', $columns, 3, $mibs);
0 ignored issues
show
3 is of type integer, but the function expects a object<The>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
978
    return count($mibs);
979
980
} // snmp_mib_load
981
982
983
/*
984
 * Turn the given oid (name or numeric value) into a MODULE::mib name.
985
 * @return an array consisting of the module and mib names, or null if no matching MIB is found.
986
 * Example:
987
 * snmptranslate -m all -M mibs .1.3.6.1.4.1.8072.3.2.10 2>/dev/null
988
 * NET-SNMP-TC::linux
989
 */
990
function snmp_translate($oid, $module, $mibdir = null)
991
{
992
    if ($module !== 'all') {
993
        $oid = "$module::$oid";
994
    }
995
996
    $cmd  = 'snmptranslate'.mibdir($mibdir);
997
    $cmd .= " -m $module $oid";
998
    // load all the MIBs looking for our object
999
    $cmd .= ' 2>/dev/null';
1000
    // ignore invalid MIBs
1001
    $lines = preg_split('/\n+/', external_exec($cmd));
1002
    if (empty($lines)) {
1003
        d_echo("No results from snmptranslate\n");
1004
        return null;
1005
    }
1006
1007
    $matches = array();
1008
    if (!preg_match('/(.*)::(.*)/', $lines[0], $matches)) {
1009
        d_echo("This doesn't look like a MIB: $lines[0]\n");
1010
        return null;
1011
    }
1012
1013
    d_echo("SNMP translated: $module::$oid -> $matches[1]::$matches[2]\n");
1014
    return array(
1015
        $matches[1],
1016
        $matches[2],
1017
    );
1018
1019
} // snmp_translate
1020
1021
1022
/*
1023
 * check if the type of the oid is a numeric type, and if so,
1024
 * @return the name of RRD type that is best suited to saving it
1025
 */
1026
function oid_rrd_type($oid, $mibdef)
1027
{
1028
    if (!isset($mibdef[$oid])) {
1029
        return false;
1030
    }
1031
1032
    switch ($mibdef[$oid]['syntax']) {
1033
    case 'OCTET':
1034
    case 'IpAddress':
1035
        return false;
1036
1037
    case 'TimeTicks':
1038
        // FIXME
1039
        return false;
1040
1041
    case 'INTEGER':
1042
    case 'Integer32':
1043
        return 'GAUGE:600:U:U';
1044
1045
    case 'Counter32':
1046
    case 'Counter64':
1047
        return 'COUNTER:600:0:U';
1048
1049
    case 'Gauge32':
1050
    case 'Unsigned32':
1051
        return 'GAUGE:600:0:U';
1052
1053
    }
1054
1055
    return false;
1056
} // oid_rrd_type
1057
1058
1059
/*
1060
 * Construct a graph names for use in the database.
1061
 * Tag each as in use on this device in &$graphs.
1062
 * Update the database with graph definitions as needed.
1063
 * We don't include the index in the graph name - that is handled at display time.
1064
 */
1065
function tag_graphs($mibname, $oids, $mibdef, &$graphs)
1066
{
1067
    foreach ($oids as $index => $array) {
1068
        foreach ($array as $oid => $val) {
1069
            $graphname          = $mibname.'-'.$mibdef[$oid]['shortname'];
1070
            $graphs[$graphname] = true;
1071
        }
1072
    }
1073
1074
} // tag_graphs
1075
1076
1077
/*
1078
 * Ensure a graph_type definition exists in the database for the entities in this MIB
1079
 */
1080
function update_mib_graph_types($mibname, $oids, $mibdef, $graphs)
1081
{
1082
    $seengraphs = array();
1083
1084
    // Get the list of graphs currently in the database
1085
    // FIXME: there's probably a more efficient way to do this
1086
    foreach (dbFetch('SELECT DISTINCT `graph_subtype` FROM `graph_types` WHERE `graph_subtype` LIKE ?', array("$mibname-%")) as $graph) {
1087
        $seengraphs[$graph['graph_subtype']] = true;
1088
    }
1089
1090
    foreach ($oids as $index => $array) {
1091
        $i = 1;
1092
        foreach ($array as $oid => $val) {
1093
            $graphname = "$mibname-".$mibdef[$oid]['shortname'];
1094
1095
            // add the graph if it's not in the database already
1096
            if ($graphs[$graphname] && !$seengraphs[$graphname]) {
1097
                // construct a graph definition based on the MIB definition
1098
                $graphdef                  = array();
1099
                $graphdef['graph_type']    = 'device';
1100
                $graphdef['graph_subtype'] = $graphname;
1101
                $graphdef['graph_section'] = 'mib';
1102
                $graphdef['graph_descr']   = $mibdef[$oid]['description'];
1103
                $graphdef['graph_order']   = $i++;
1104
                // TODO: add colours, unit_text, and ds
1105
                // add graph to the database
1106
                dbInsert($graphdef, 'graph_types');
1107
            }
1108
        }
1109
    }
1110
} // update_mib_graph_types
1111
1112
1113
/*
1114
 * Save all of the measurable oids for the device in their own RRDs.
1115
 * Save the current value of all the oids in the database.
1116
 */
1117
function save_mibs($device, $mibname, $oids, $mibdef, &$graphs)
1118
{
1119
    $usedoids = array();
1120
    $deviceoids = array();
1121
    foreach ($oids as $index => $array) {
1122
        foreach ($array as $obj => $val) {
1123
            // build up the device_oid row for saving into the database
1124
            $numvalue = is_numeric($val) ? $val + 0 : 0;
1125
            $deviceoids[] = array(
1126
                'device_id'     => $device['device_id'],
1127
                'oid'           => $mibdef[$obj]['oid'].".".$index,
1128
                'module'        => $mibdef[$obj]['module'],
1129
                'mib'           => $mibdef[$obj]['mib'],
1130
                'object_type'   => $obj,
1131
                'value'         => $val,
1132
                'numvalue'      => $numvalue,
1133
            );
1134
1135
            $type = oid_rrd_type($obj, $mibdef);
1136
            if ($type === false) {
1137
                continue;
1138
            }
1139
1140
            $usedoids[$index][$obj] = $val;
1141
1142
            $tags = array(
1143
                'rrd_def'       => array("DS:mibval:$type"),
1144
                'rrd_name'      => array($mibname, $mibdef[$obj]['shortname'], $index),
1145
                'rrd_oldname'   => array($mibname, $mibdef[$obj]['object_type'], $index),
1146
                'index'         => $index,
1147
                'oid'           => $mibdef[$obj]['oid'],
1148
                'module'        => $mibdef[$obj]['module'],
1149
                'mib'           => $mibdef[$obj]['mib'],
1150
                'object_type'   => $obj,
1151
            );
1152
            data_update($device, 'mibval', $tags, $val);
1153
        }
1154
    }
1155
1156
    tag_graphs($mibname, $usedoids, $mibdef, $graphs);
1157
    update_mib_graph_types($mibname, $usedoids, $mibdef, $graphs);
1158
1159
    // update database
1160
    $columns = array('device_id', 'oid', 'module', 'mib', 'object_type', 'value', 'numvalue');
1161
    update_db_table('device_oids', $columns, 2, $deviceoids);
0 ignored issues
show
2 is of type integer, but the function expects a object<The>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1162
} // save_mibs
1163
1164
1165
/*
1166
 * @return an array of MIB objects matching $module, $name, keyed by object_type
1167
 */
1168
function load_mibdefs($module, $name)
1169
{
1170
    $params = array($module, $name);
1171
    $result = array();
1172
    $object_types = array();
1173
    foreach (dbFetchRows("SELECT * FROM `mibdefs` WHERE `module` = ? AND `mib` = ?", $params) as $row) {
1174
        $mib = $row['object_type'];
1175
        $object_types[] = $mib;
1176
        $result[$mib] = $row;
1177
    }
1178
1179
    // add shortname to each element
1180
    $prefix = longest_matching_prefix($name, $object_types);
1181
    foreach ($result as $mib => $m) {
1182
        if (strlen($prefix) > 2) {
1183
            $result[$mib]['shortname'] = preg_replace("/^$prefix/", '', $m['object_type'], 1);
1184
        }
1185
        else {
1186
            $result[$mib]['shortname'] = $m['object_type'];
1187
        }
1188
    }
1189
1190
    d_print_r($result);
1191
    return $result;
1192
} // load_mibdefs
1193
1194
/*
1195
 * @return an array of MIB names and modules for $device from the database
1196
 */
1197
function load_device_mibs($device)
1198
{
1199
    $params = array($device['device_id']);
1200
    $result = array();
1201
    foreach (dbFetchRows("SELECT `mib`, `module` FROM device_mibs WHERE device_id = ?", $params) as $row) {
1202
        $result[$row['mib']] = $row['module'];
1203
    }
1204
    return $result;
1205
} // load_device_mibs
1206
1207
1208
/*
1209
 * Run MIB-based polling for $device.  Update $graphs with the results.
1210
 */
1211
function poll_mibs($device, &$graphs)
1212
{
1213
    if (!is_mib_poller_enabled($device)) {
1214
        return;
1215
    }
1216
1217
    echo 'MIB: polling ';
1218
    d_echo("\n");
1219
1220
    foreach (load_device_mibs($device) as $name => $module) {
1221
        echo "$name ";
1222
        d_echo("\n");
1223
        $oids = snmpwalk_cache_oid($device, $name, array(), $module, null, "-OQUsb");
1224
        d_print_r($oids);
1225
        save_mibs($device, $name, $oids, load_mibdefs($module, $name), $graphs);
1226
    }
1227
    echo "\n";
1228
} // poll_mibs
1229
1230
/*
1231
 * Take a list of MIB name => module pairs.
1232
 * Validate MIBs and store the device->mib mapping in the database.
1233
 * See includes/discovery/os/ruckuswireless.inc.php for an example of usage.
1234
 */
1235
function register_mibs($device, $mibs, $included_by)
1236
{
1237
    if (!is_mib_poller_enabled($device)) {
1238
        return;
1239
    }
1240
1241
    echo "MIB: registering\n";
1242
1243
    foreach ($mibs as $name => $module) {
1244
        $translated = snmp_translate($name, $module);
1245
        if ($translated) {
1246
            $mod = $translated[0];
1247
            $nam = $translated[1];
1248
            echo "     $mod::$nam\n";
1249
            if (snmp_mib_load($nam, $mod, $included_by) > 0) {
1250
                // NOTE: `last_modified` omitted due to being automatically maintained by MySQL
1251
                $columns = array('device_id', 'module', 'mib', 'included_by');
1252
                $rows = array();
1253
                $rows[] = array(
1254
                    'device_id'   => $device['device_id'],
1255
                    'module'      => $mod,
1256
                    'mib'         => $nam,
1257
                    'included_by' => $included_by,
1258
                );
1259
                update_db_table('device_mibs', $columns, 3, $rows);
0 ignored issues
show
3 is of type integer, but the function expects a object<The>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1260
            }
1261
            else {
1262
                echo("MIB: Could not load definition for $mod::$nam\n");
1263
            }
1264
        }
1265
        else {
1266
            echo("MIB: Could not find $module::$name\n");
1267
        }
1268
    }
1269
1270
    echo "\n";
1271
1272
} // register_mibs
1273
1274
/**
1275
 * SNMPWalk_array_num - performs a numeric SNMPWalk and returns an array containing $count indexes
1276
 * One Index:
1277
 *  From: 1.3.6.1.4.1.9.9.166.1.15.1.1.27.18.655360 = 0
1278
 *  To: $array['1.3.6.1.4.1.9.9.166.1.15.1.1.27.18']['655360'] = 0
1279
 * Two Indexes:
1280
 *  From: 1.3.6.1.4.1.9.9.166.1.15.1.1.27.18.655360 = 0
1281
 *  To: $array['1.3.6.1.4.1.9.9.166.1.15.1.1.27']['18']['655360'] = 0
1282
 * And so on...
1283
 * Think snmpwalk_cache_*_oid but for numeric data.
1284
 *
1285
 * Why is this useful?
1286
 * Some SNMP data contains a single index (eg. ifIndex in IF-MIB) and some is dual indexed
1287
 * (eg. PolicyIndex/ObjectsIndex in CISCO-CLASS-BASED-QOS-MIB).
1288
 * The resulting array allows us to easily access the top level index we want and iterate over the data from there.
1289
 *
1290
 * @param $device
1291
 * @param $OID
1292
 * @param int $indexes
1293
 * @internal param $string
1294
 * @return array
1295
 */
1296
function snmpwalk_array_num($device,$oid,$indexes=1) {
1297
    $array = array();
1298
    $string = snmp_walk($device, $oid, '-Osqn');
1299
1300
    if ( $string === false) {
1301
        // False means: No Such Object.
1302
        return false;
1303
    }
1304
    if ($string == "") {
1305
        // Empty means SNMP timeout or some such.
1306
        return null;
1307
    }
1308
1309
    // Let's turn the string into something we can work with.
1310
    foreach (explode("\n", $string) as $line) {
1311
        if ($line[0] == '.') {
1312
            // strip the leading . if it exists.
1313
            $line = substr($line,1);
1314
        }
1315
        list($key, $value) = explode(' ', $line, 2);
1316
        $prop_id = explode('.', $key);
1317
        $value = trim($value);
1318
1319
        // if we have requested more levels that exist, set to the max.
1320
        if ($indexes > count($prop_id)) {
1321
            $indexes = count($prop_id)-1;
1322
        }
1323
1324
        for ($i=0;$i<$indexes;$i++) {
1325
            // Pop the index off.
1326
            $index = array_pop($prop_id);
1327
            $value = array($index => $value);
1328
        }
1329
1330
        // Rebuild our key
1331
        $key = implode('.',$prop_id);
1332
1333
        // Add the entry to the master array
1334
        $array = array_replace_recursive($array,array($key => $value));
1335
    }
1336
    return $array;
1337
}
1338