SNMP_Session.pm untested

filter: Statementstmt 0.0% 0 / 540 Branchbran 0.0% 0 / 228 Conditioncond 0.0% 0 / 127 Subroutinesub 0.0% 0 / 97 Podpod 0.0% 0 / 75 totaltotal 0.0% 0 / 1067 CC 115 SCAR 43.1
CC
115
Cov
0%
open
306.0
map_table_start_end
210.0
receive_response_3
182.0
CRAP 74.6
1 ### -*- mode: Perl -*-
2 ######################################################################
3 ### SNMP Request/Response Handling
4 ######################################################################
5 ### Copyright (c) 1995-2009, Simon Leinen.
6 ###
7 ### This program is free software; you can redistribute it under the
8 ### "Artistic License 2.0" included in this distribution
9 ### (file "Artistic").
10 ######################################################################
11 ### Created by: See AUTHORS below
12 ######################################################################
13  
14 package SNMP_Session;
15  
16 =head1 NAME
17  
18 SNMP_Session - SNMPv1/v2 Protocol Handling
19  
20 =head1 SYNOPSIS
21  
22 use SNMP_Session;
23 $session = SNMP_Session->open ($host, $community, $port)
24 or die "couldn't open SNMP session to $host";
25 if ($session->get_request_response ($oid1, $oid2, ...)) {
26 ($bindings) = $session->decode_get_response ($session->{pdu_buffer});
27 while ($bindings ne '') {
28 ($binding,$bindings) = decode_sequence ($bindings);
29 ($oid,$value) = decode_by_template ($binding, "%O%@");
30 print pretty_print ($oid)," => ", pretty_print ($value), "\n";
31 }
32 } else {
33 die "No response from agent on $host";
34 }
35  
36 =cut
37  
38 require 5.002;
39  
40 use strict;
41 use Exporter;
42 use vars qw(@ISA $VERSION @EXPORT $errmsg
43 $suppress_warnings
44 $default_avoid_negative_request_ids
45 $default_use_16bit_request_ids);
46 use Socket;
47 use BER '1.05';
48 use Carp;
49  
50 sub map_table ($$$ );
51 sub map_table_4 ($$$$);
52 sub map_table_start_end ($$$$$$);
53 sub index_compare ($$);
54 sub oid_diff ($$);
55  
56 $VERSION = '1.15';
57  
58 @ISA = qw(Exporter);
59  
60 @EXPORT = qw(errmsg suppress_warnings index_compare oid_diff recycle_socket ipv6available);
61  
62 =head1 VARIABLES
63  
64 The C<default_...> variables all specify default values that are used
65 for C<SNMP_Session> objects when no other value is specified. These
66 values can be overridden on a per-session basis, for example by
67 passing additional arguments to the constructor.
68  
69 =cut
70  
71 my $default_debug = 0;
72  
73 ### Default values for the TIMEOUT, RETRIES, and BACKOFF slots of
74 ### SNMP_Session objects - see their documentation below.
75 ###
76 my $default_timeout = 2.0;
77 my $default_retries = 5;
78 my $default_backoff = 1.0;
79  
80 =head2 $default_max_repetitions - default value for C<maxRepetitions>.
81  
82 This specifies how many table rows are requested in C<getBulk>
83 requests. Used when walking tables using C<getBulk> (only available
84 in SNMPv2(c) and later). If this is too small, then a table walk will
85 need unnecessarily many request/response exchanges. If it is too big,
86 the agent may compute many variables after the end of the table. It
87 is recommended to set this explicitly for each table walk by using
88 C<map_table_4()>.
89  
90 =cut
91  
92 my $default_max_repetitions = 12;
93  
94 =head2 $default_avoid_negative_request_ids - default value for
95 C<avoid_negative_request_ids>.
96  
97 Set this to non-zero if you have agents that have trouble with
98 negative request IDs, and don't forget to complain to your agent
99 vendor. According to the spec (RFC 1905), the request-id is an
100 C<Integer32>, i.e. its range is from -(2^31) to (2^31)-1. However,
101 some agents erroneously encode the response ID as an unsigned, which
102 prevents this code from matching such responses to requests.
103  
104 =cut
105  
106 $SNMP_Session::default_avoid_negative_request_ids = 0;
107  
108 =head2 $default_use_16bit_request_ids - default value for C<use_16bit_request_ids>.
109  
110 Set this to non-zero if you have agents that use 16bit request IDs,
111 and don't forget to complain to your agent vendor.
112  
113 =cut
114  
115 $SNMP_Session::default_use_16bit_request_ids = 0;
116  
117 ### Whether all SNMP_Session objects should share a single UDP socket.
118 ###
119 $SNMP_Session::recycle_socket = 0;
120  
121 ### IPv6 initialization code: check that IPv6 libraries are available,
122 ### and if so load them.
123  
124 ### We store the length of an IPv6 socket address structure in the class
125 ### so we can determine if a socket address is IPv4 or IPv6 just by checking
126 ### its length. The proper way to do this would be to use sockaddr_family(),
127 ### but this function is only available in recent versions of Socket.pm.
128 my $ipv6_addr_len;
129  
130 ### Flags to be passed to recv() when non-blocking behavior is
131 ### desired. On most POSIX-like systems this will be set to
132 ### MSG_DONTWAIT, on other systems we leave it at zero.
133 ###
134 my $dont_wait_flags;
135  
136 BEGIN {
137 $ipv6_addr_len = undef;
138 $SNMP_Session::ipv6available = 0;
139 $dont_wait_flags = 0;
140  
141 if (eval {local $SIG{__DIE__};require Socket6;} &&
142 eval {local $SIG{__DIE__};require IO::Socket::INET6; IO::Socket::INET6->VERSION("1.26");}) {
143 Socket6->import(qw(inet_pton inet_ntop getaddrinfo));
144 $ipv6_addr_len = length(Socket6::pack_sockaddr_in6(161, inet_pton(AF_INET6(), "::1")));
145 $SNMP_Session::ipv6available = 1;
146 }
147 eval 'local $SIG{__DIE__};local $SIG{__WARN__};$dont_wait_flags = MSG_DONTWAIT();';
148 }
149  
150 ### Cache for reusable sockets. This is indexed by socket (address)
151 ### family, so that we don't try to reuse an IPv4 socket for IPv6 or
152 ### vice versa.
153 ###
154 my %the_socket = ();
155  
156 =head2 $errmsg - error message from last failed operation.
157  
158 When they encounter errors, the routines in this module will generally
159 return C<undef>) and leave an informative error message in C<$errmsg>).
160  
161 =cut
162  
163 $SNMP_Session::errmsg = '';
164  
165 =head2 $suppress_warnings - whether warnings should be suppressed.
166  
167 If this variable is zero, as is the default, this code will output
168 informative error messages whenever it encounters an error. Set this
169 to a non-zero value if you want to suppress these messages. In any
170 case, the last error message can be found in C<$errmsg>.
171  
172 =cut
173  
174 $SNMP_Session::suppress_warnings = 0;
175  
176 =head1 METHODS in package SNMP_Session
177  
178 The abstract class C<SNMP_Session> defines objects that can be used to
179 communicate with SNMP entities. It has methods to send requests to
180 and receive responses from an agent.
181  
182 Two instantiable subclasses are defined: C<SNMPv1_Session> implements
183 SNMPv1 (RFC 1157) functionality C<SNMPv2c_Session> implements
184 community-based SNMPv2 (RFC 3410-3417).
185  
186 =cut
187  
188 sub get_request { 0 | context_flag () };
189 sub getnext_request { 1 | context_flag () };
190 sub get_response { 2 | context_flag () };
191 sub set_request { 3 | context_flag () };
192 sub trap_request { 4 | context_flag () };
193 sub getbulk_request { 5 | context_flag () };
194 sub inform_request { 6 | context_flag () };
195 sub trap2_request { 7 | context_flag () };
196  
197 sub standard_udp_port { 161 };
198  
199 =head2 open() - create an SNMP session object
200  
201 $session = SNMP_Session->open
202 ($host, $community, $port,
203 $max_pdu_len, $local_port, $max_repetitions,
204 $local_host, $ipv4only);
205  
206 The calling and return conventions are identical to
207 C<SNMPv1_Session::open()>.
208  
209 =cut
210  
211 sub open
212 {
213 return SNMPv1_Session::open (@_);
214 }
215  
216 =head2 timeout() - return timeout value.
217  
218 Initial timeout, in seconds, to wait for a response PDU after a
219 request is sent. Note that when a request is retried, the timeout is
220 increased by B<backoff> (see below). The standard value is 2.0
221 (seconds).
222  
223 =cut
224  
225 sub timeout { $_[0]->{timeout} }
226  
227 =head2 retries() - number of attempts to get a reply.
228  
229 Maximum number of attempts to get a reply for an SNMP request. If no
230 response is received after B<timeout> seconds, the request is resent
231 and a new response awaited with a longer timeout, see the
232 documentation on B<backoff> below. The B<retries> value should be at
233 least 1, because the first attempt counts, too (the name "retries" is
234 confusing, sorry for that).
235  
236 =cut
237  
238 sub retries { $_[0]->{retries} }
239  
240 =head2 backoff() - backoff factor.for timeout on successive retries.
241  
242 Default backoff factor for C<SNMP_Session> objects. This factor is
243 used to increase the TIMEOUT every time an SNMP request is retried.
244 The standard value is 1.0, which means the same timeout is used for
245 all attempts.
246  
247 =cut
248  
249 sub backoff { $_[0]->{backoff} }
250  
251 =head2 set_timeout() - set initial timeout for session
252  
253 =head2 set_retries() - set maximum number of attempts for session
254  
255 =head2 set_backoff() - set backoff factor for session
256  
257 Example usage:
258  
259 $session->set_backoff (1.5);
260  
261 =cut
262  
263 sub set_timeout {
264 my ($session, $timeout) = @_;
265 croak ("timeout ($timeout) must be a positive number") unless $timeout > 0.0;
266 $session->{'timeout'} = $timeout;
267 }
268 sub set_retries {
269 my ($session, $retries) = @_;
270 croak ("retries ($retries) must be a non-negative integer")
271 unless $retries == int ($retries) && $retries >= 0;
272 $session->{'retries'} = $retries;
273 }
274 sub set_backoff {
275 my ($session, $backoff) = @_;
276 croak ("backoff ($backoff) must be a number >= 1.0")
277 unless $backoff == int ($backoff) && $backoff >= 1.0;
278 $session->{'backoff'} = $backoff;
279 }
280  
281 sub encode_request_3 ($$$@) {
282 my($this, $reqtype, $encoded_oids_or_pairs, $i1, $i2) = @_;
283 my($request);
284 local($_);
285  
286 $this->{request_id} = ($this->{request_id} == 0x7fffffff)
287 ? -0x80000000 : $this->{request_id}+1;
288 $this->{request_id} += 0x80000000
289 if ($this->{avoid_negative_request_ids} && $this->{request_id} < 0);
290 $this->{request_id} &= 0x0000ffff
291 if ($this->{use_16bit_request_ids});
292 foreach $_ (@{$encoded_oids_or_pairs}) {
293 if (ref ($_) eq 'ARRAY') {
294 $_ = &encode_sequence ($_->[0], $_->[1])
295 || return $this->ber_error ("encoding pair");
296 } else {
297 $_ = &encode_sequence ($_, encode_null())
298 || return $this->ber_error ("encoding value/null pair");
299 }
300 }
301 $request = encode_tagged_sequence
302 ($reqtype,
303 encode_int ($this->{request_id}),
304 defined $i1 ? encode_int ($i1) : encode_int_0 (),
305 defined $i2 ? encode_int ($i2) : encode_int_0 (),
306 encode_sequence (@{$encoded_oids_or_pairs}))
307 || return $this->ber_error ("encoding request PDU");
308 return $this->wrap_request ($request);
309 }
310  
311 sub encode_get_request {
312 my($this, @oids) = @_;
313 return encode_request_3 ($this, get_request, \@oids);
314 }
315  
316 sub encode_getnext_request {
317 my($this, @oids) = @_;
318 return encode_request_3 ($this, getnext_request, \@oids);
319 }
320  
321 sub encode_getbulk_request {
322 my($this, $non_repeaters, $max_repetitions, @oids) = @_;
323 return encode_request_3 ($this, getbulk_request, \@oids,
324 $non_repeaters, $max_repetitions);
325 }
326  
327 sub encode_set_request {
328 my($this, @encoded_pairs) = @_;
329 return encode_request_3 ($this, set_request, \@encoded_pairs);
330 }
331  
332 sub encode_trap_request ($$$$$$@) {
333 my($this, $ent, $agent, $gen, $spec, $dt, @pairs) = @_;
334 my($request);
335 local($_);
336  
337 foreach $_ (@pairs) {
338 if (ref ($_) eq 'ARRAY') {
339 $_ = &encode_sequence ($_->[0], $_->[1])
340 || return $this->ber_error ("encoding pair");
341 } else {
342 $_ = &encode_sequence ($_, encode_null())
343 || return $this->ber_error ("encoding value/null pair");
344 }
345 }
346 $request = encode_tagged_sequence
347 (trap_request, $ent, $agent, $gen, $spec, $dt, encode_sequence (@pairs))
348 || return $this->ber_error ("encoding trap PDU");
349 return $this->wrap_request ($request);
350 }
351  
352 sub encode_v2_trap_request ($@) {
353 my($this, @pairs) = @_;
354  
355 return encode_request_3($this, trap2_request, \@pairs);
356 }
357  
358 sub decode_get_response {
359 my($this, $response) = @_;
360 my @rest;
361 @{$this->{'unwrapped'}};
362 }
363  
364 sub wait_for_response {
365 my($this) = shift;
366 my($timeout) = shift || 10.0;
367 my($rin,$win,$ein) = ('','','');
368 my($rout,$wout,$eout);
369 vec($rin,$this->sockfileno,1) = 1;
370 select($rout=$rin,$wout=$win,$eout=$ein,$timeout);
371 }
372  
373 =head2 ..._request_response() - Send some request and receive response.
374  
375 Encodes a specific SNMP request, sends it to the destination address
376 of the session, and waits for a matching response. If such a response
377 is received, this function will return the size of the response, which
378 is necessarily greater than zero.
379  
380 An undefined value is returned if some error happens during encoding
381 or sending, or if no matching response is received after the
382 wait/retry schedule is exhausted. See the documentation on the
383 C<timeout()>, C<retries()>, and C<backoff()> methods on how the
384 wait/retry logic works.
385  
386 =head2 get_request_response() - Send C<get> request and receive response.
387  
388 =head2 getnext_request_response() - Send C<get-next> request and receive response.
389  
390 $result = $session->get_request_response (@encoded_oids);
391 $result = $session->getnext_request_response (@encoded_oids);
392  
393 =cut
394  
395 sub get_request_response ($@) {
396 my($this, @oids) = @_;
397 return $this->request_response_5 ($this->encode_get_request (@oids),
398 get_response, \@oids, 1);
399 }
400  
401 sub getnext_request_response ($@) {
402 my($this,@oids) = @_;
403 return $this->request_response_5 ($this->encode_getnext_request (@oids),
404 get_response, \@oids, 1);
405 }
406  
407 =head2 set_request_response() - Send C<set> request and receive response.
408  
409 $result = $session->set_request_response (@encoded_pair_list);
410  
411 This method takes its arguments in a different form; they are a list
412 of pairs - references to two-element arrays - which respresent the
413 variables to be set and the intended values, e.g.
414  
415 ([$encoded_oid_0, $encoded_value_0],
416 [$encoded_oid_1, $encoded_value_1],
417 [$encoded_oid_2, $encoded_value_2], ...)
418  
419 =cut
420  
421 sub set_request_response ($@) {
422 my($this, @pairs) = @_;
423 return $this->request_response_5 ($this->encode_set_request (@pairs),
424 get_response, \@pairs, 1);
425 }
426  
427 sub getbulk_request_response ($$$@) {
428 my($this,$non_repeaters,$max_repetitions,@oids) = @_;
429 return $this->request_response_5
430 ($this->encode_getbulk_request ($non_repeaters,$max_repetitions,@oids),
431 get_response, \@oids, 1);
432 }
433  
434 =head2 trap_request_send() - send SNMPv1 Trap.
435  
436 $result = $session->trap_request_send ($ent, $gent, $gen, $spec, $dt, @pairs);
437  
438 =cut
439  
440 sub trap_request_send ($$$$$$@) {
441 my($this, $ent, $agent, $gen, $spec, $dt, @pairs) = @_;
442 my($req);
443  
444 $req = $this->encode_trap_request ($ent, $agent, $gen, $spec, $dt, @pairs);
445 ## Encoding may have returned an error.
446 return undef unless defined $req;
447 $this->send_query($req)
448 || return $this->error ("send_trap: $!");
449 return 1;
450 }
451  
452 =head2 v2_trap_request_send() - send SNMPv2 Trap.
453  
454 $result = $session->v2_trap_request_send ($trap_oid, $dt, @pairs);
455  
456 =cut
457  
458 sub v2_trap_request_send ($$$@) {
459 my($this, $trap_oid, $dt, @pairs) = @_;
460 my @sysUptime_OID = ( 1,3,6,1,2,1,1,3 );
461 my @snmpTrapOID_OID = ( 1,3,6,1,6,3,1,1,4,1 );
462 my($req);
463  
464 unshift @pairs, [encode_oid (@snmpTrapOID_OID,0),
465 encode_oid (@{$trap_oid})];
466 unshift @pairs, [encode_oid (@sysUptime_OID,0),
467 encode_timeticks ($dt)];
468 $req = $this->encode_v2_trap_request (@pairs);
469 ## Encoding may have returned an error.
470 return undef unless defined $req;
471 $this->send_query($req)
472 || return $this->error ("send_trap: $!");
473 return 1;
474 }
475  
476 sub request_response_5 ($$$$$) {
477 my ($this, $req, $response_tag, $oids, $errorp) = @_;
478 my $retries = $this->retries;
479 my $timeout = $this->timeout;
480 my ($nfound, $timeleft);
481  
482 ## Encoding may have returned an error.
483 return undef unless defined $req;
484  
485 $timeleft = $timeout;
486 while ($retries > 0) {
487 $this->send_query ($req)
488 || return $this->error ("send_query: $!");
489 # IlvJa
490 # Add request pdu to capture_buffer
491 push @{$this->{'capture_buffer'}}, $req
492 if (defined $this->{'capture_buffer'}
493 and ref $this->{'capture_buffer'} eq 'ARRAY');
494 #
495 wait_for_response:
496 ($nfound, $timeleft) = $this->wait_for_response($timeleft);
497 if ($nfound > 0) {
498 my($response_length);
499  
500 $response_length
501 = $this->receive_response_3 ($response_tag, $oids, $errorp, 1);
502 if ($response_length) {
503 # IlvJa
504 # Add response pdu to capture_buffer
505 push (@{$this->{'capture_buffer'}},
506 substr($this->{'pdu_buffer'}, 0, $response_length)
507 )
508 if (defined $this->{'capture_buffer'}
509 and ref $this->{'capture_buffer'} eq 'ARRAY');
510 #
511 return $response_length;
512 } elsif (defined ($response_length)) {
513 goto wait_for_response;
514 # A response has been received, but for a different
515 # request ID or from a different IP address.
516 } else {
517 return undef;
518 }
519 } else {
520 ## No response received - retry
521 --$retries;
522 $timeout *= $this->backoff;
523 $timeleft = $timeout;
524 }
525 }
526 # IlvJa
527 # Add empty packet to capture_buffer
528 push @{$this->{'capture_buffer'}}, ""
529 if (defined $this->{'capture_buffer'}
530 and ref $this->{'capture_buffer'} eq 'ARRAY');
531 #
532 return $this->error ("no response received");
533 }
534  
535 =head2 map_table() - traverse an SNMP table.
536  
537 $result = $session->map_table ([$col0, $col1, ...], $mapfn);
538  
539 This will call the provided function (C<&$mapfn>) once for each row of
540 the table defined by the column OIDs C<$col0>, C<$col1>... If the
541 session can handle SNMPv2 operations, C<get-bulk> will be used to
542 traverse the table. Otherwise, C<get-next> will be used.
543  
544 If the first argument is a list of I<n> columns, the mapping function
545 will be called with I<n+1> arguments. The first argument will be the
546 row index, i.e. the list of sub-IDs that was appended to the provided
547 column OIDs for this row. Note that the row index will be represented
548 as a string, using dot-separated numerical OID notation.
549  
550 The remaining arguments to the mapping function will be the values of
551 each column at the current index. It is possible that the table has
552 "holes", i.e. that for a given row index, not all columns have a
553 value. For columns with no value at the current row index, C<undef>
554 will be passed to the mapping function.
555  
556 If an error is encountered at any point during the table traversal,
557 this method will return undef and leave an error message in C<$errmsg>
558 (which is also written out unless C<$suppress_warnings> is non-zero).
559  
560 Otherwise, the function will return the number of rows traversed,
561 i.e. the number of times that the mapping function has been called.
562  
563 =cut
564  
565 sub map_table ($$$) {
566 my ($session, $columns, $mapfn) = @_;
567 return $session->map_table_4 ($columns, $mapfn,
568 $session->default_max_repetitions ());
569 }
570  
571 =head2 map_table_4() - traverse an SNMP table with more control.
572  
573 =cut
574  
575 sub map_table_4 ($$$$) {
576 my ($session, $columns, $mapfn, $max_repetitions) = @_;
577 return $session->map_table_start_end ($columns, $mapfn,
578 "", undef,
579 $max_repetitions);
580 }
581  
582 =head2 map_table_start_end() - traverse an SNMP table with lower/upper index limits.
583  
584 $result = $session->map_table_start_end ($columns, $mapfn,
585 $start, $end, $max_repetition);
586  
587 Similar to C<map_table_4()>, except that the start and end index can
588 be specified.
589  
590 =cut
591  
592 sub map_table_start_end ($$$$$$) {
593 my ($session, $columns, $mapfn, $start, $end, $max_repetitions) = @_;
594  
595 my @encoded_oids;
596 my $call_counter = 0;
597 my $base_index = $start;
598  
599 do {
600 foreach (@encoded_oids = @{$columns}) {
601 $_=encode_oid (@{$_},split '\.',$base_index)
602 || return $session->ber_error ("encoding OID $base_index");
603 }
604 if ($session->getnext_request_response (@encoded_oids)) {
605 my $response = $session->pdu_buffer;
606 my ($bindings) = $session->decode_get_response ($response);
607 my $smallest_index = undef;
608 my @collected_values = ();
609  
610 my @bases = @{$columns};
611 while ($bindings ne '') {
612 my ($binding, $oid, $value);
613 my $base = shift @bases;
614 ($binding, $bindings) = decode_sequence ($bindings);
615 ($oid, $value) = decode_by_template ($binding, "%O%@");
616  
617 my $out_index;
618  
619 $out_index = oid_diff ($base, $oid);
620 my $cmp;
621 if (!defined $smallest_index
622 || ($cmp = index_compare ($out_index,$smallest_index)) == -1) {
623 $smallest_index = $out_index;
624 grep ($_=undef, @collected_values);
625 push @collected_values, $value;
626 } elsif ($cmp == 1) {
627 push @collected_values, undef;
628 } else {
629 push @collected_values, $value;
630 }
631 }
632 (++$call_counter,
633 &$mapfn ($smallest_index, @collected_values))
634 if defined $smallest_index;
635 $base_index = $smallest_index;
636 } else {
637 return undef;
638 }
639 }
640 while (defined $base_index
641 && (!defined $end || index_compare ($base_index, $end) < 0));
642 $call_counter;
643 }
644  
645 sub index_compare ($$) {
646 my ($i1, $i2) = @_;
647 $i1 = '' unless defined $i1;
648 $i2 = '' unless defined $i2;
649 if ($i1 eq '') {
650 return $i2 eq '' ? 0 : 1;
651 } elsif ($i2 eq '') {
652 return 1;
653 } elsif (!$i1) {
654 return $i2 eq '' ? 1 : !$i2 ? 0 : 1;
655 } elsif (!$i2) {
656 return -1;
657 } else {
658 my ($f1,$r1) = split('\.',$i1,2);
659 my ($f2,$r2) = split('\.',$i2,2);
660  
661 if ($f1 < $f2) {
662 return -1;
663 } elsif ($f1 > $f2) {
664 return 1;
665 } else {
666 return index_compare ($r1,$r2);
667 }
668 }
669 }
670  
671 sub oid_diff ($$) {
672 my($base, $full) = @_;
673 my $base_dotnot = join ('.',@{$base});
674 my $full_dotnot = BER::pretty_oid ($full);
675  
676 return undef unless substr ($full_dotnot, 0, length $base_dotnot)
677 eq $base_dotnot
678 && substr ($full_dotnot, length $base_dotnot, 1) eq '.';
679 substr ($full_dotnot, length ($base_dotnot)+1);
680 }
681  
682 # Pretty_address returns a human-readable representation of an IPv4 or IPv6 address.
683 sub pretty_address {
684 my($addr) = shift;
685 my($port, $addrunpack, $addrstr);
686  
687 # Disable strict subs to stop old versions of perl from
688 # complaining about AF_INET6 when Socket6 is not available
689  
690 if( (defined $ipv6_addr_len) && (length $addr == $ipv6_addr_len)) {
691 ($port,$addrunpack) = Socket6::unpack_sockaddr_in6 ($addr);
692 $addrstr = inet_ntop (AF_INET6(), $addrunpack);
693 } else {
694 ($port,$addrunpack) = unpack_sockaddr_in ($addr);
695 $addrstr = inet_ntoa ($addrunpack);
696 }
697  
698 return sprintf ("[%s].%d", $addrstr, $port);
699 }
700  
701 sub version { $VERSION; }
702  
703  
704 sub error_return ($$) {
705 my ($this,$message) = @_;
706 $SNMP_Session::errmsg = $message;
707 unless ($SNMP_Session::suppress_warnings) {
708 $message =~ s/^/ /mg;
709 carp ("Error:\n".$message."\n");
710 }
711 return undef;
712 }
713  
714 sub error ($$) {
715 my ($this,$message) = @_;
716 my $session = $this->to_string;
717 $SNMP_Session::errmsg = $message."\n".$session;
718 unless ($SNMP_Session::suppress_warnings) {
719 $session =~ s/^/ /mg;
720 $message =~ s/^/ /mg;
721 carp ("SNMP Error:\n".$SNMP_Session::errmsg."\n");
722 }
723 return undef;
724 }
725  
726 sub ber_error ($$) {
727 my ($this,$type) = @_;
728 my ($errmsg) = $BER::errmsg;
729  
730 $errmsg =~ s/^/ /mg;
731 return $this->error ("$type:\n$errmsg");
732 }
733  
734 =head2 receive_trap_1() - receive message on trap socket.
735  
736 This method waits until a message is received on the trap socket. If
737 successful, it returns two values: the message that was received, and
738 the address of the sender as a C<sockaddr> structure. This address
739 can be passed to C<getnameinfo()> to convert it to readable output.
740  
741 This method doesn't check whether the message actually encodes a trap
742 or anything else - the caller should use C<decode_trap_request()> to
743 find out.
744  
745 =cut
746  
747 sub receive_trap_1 ($ ) {
748 my ($this) = @_;
749 my ($remote_addr, $iaddr, $port, $trap, $af);
750 $remote_addr = recv ($this->sock,
751 $this->{'pdu_buffer'},
752 $this->max_pdu_len,0);
753 return undef unless $remote_addr;
754 $trap = $this->{'pdu_buffer'};
755 return ($trap, $remote_addr);
756 }
757  
758 =head2 receive_trap() - receive message on trap socket (deprecated version).
759  
760 This function is identical to C<receive_trap_1()>, except that it
761 returns the sender address as three (formerly two) separate values:
762 The host IP address, the port, and (since version 1.14) the address
763 family. If you use this, please consider moving to
764 C<receive_trap_1()>, because it is easier to process the sender
765 address in sockaddr format, in particular in a world where IPv4 and
766 IPv6 coexist.
767  
768 =cut
769  
770 sub receive_trap ($ ) {
771 my ($this) = @_;
772 my ($trap, $remote_addr) = $this->receive_trap_1 ();
773 return undef unless defined $trap;
774  
775 my ($iaddr, $port, $af);
776 if ((defined $ipv6_addr_len) && (length $remote_addr == $ipv6_addr_len)) {
777 ($port, $iaddr) = Socket6::unpack_sockaddr_in6 ($remote_addr);
778 $af = AF_INET6;
779 } else {
780 ($port, $iaddr) = unpack_sockaddr_in ($remote_addr);
781 $af = AF_INET;
782 }
783 return ($trap, $iaddr, $port, $af);
784 }
785  
786 =head2 decode_trap_request()
787  
788 ($community, $ent, $agent, $gen, $spec, $dt, $bindings)
789 = $session->decode_trap_request ($trap);
790  
791 Given a message such as one returned as the first return value from
792 C<receive_trap_1()> or C<receive_trap()>, try to decode it as some
793 notification PDU. The code can handle SNMPv1 and SNMPv2 traps as well
794 as SNMPv2 INFORMs, although it fails to distinguish traps from
795 informs, which makes it hard to handle informs correctly (they should
796 be acknowledged).
797  
798 The C<$ent>, C<$agent>, C<$gen>, C<$spec>, and C<$dt> values will only
799 be defined for SNMPv1 traps. For SNMPv2 traps and informs, some of
800 this information will be encoded as bindings.
801  
802 =cut
803  
804 sub decode_trap_request ($$) {
805 my ($this, $trap) = @_;
806 my ($snmp_version, $community, $ent, $agent, $gen, $spec, $dt,
807 $request_id, $error_status, $error_index,
808 $bindings);
809 ($snmp_version, $community,
810 $ent, $agent,
811 $gen, $spec, $dt,
812 $bindings)
813 = decode_by_template ($trap, "%{%i%s%*{%O%A%i%i%u%{%@",
814 trap_request);
815 if (!defined $snmp_version) {
816 ($snmp_version, $community,
817 $request_id, $error_status, $error_index,
818 $bindings)
819 = decode_by_template ($trap, "%{%i%s%*{%i%i%i%{%@",
820 trap2_request);
821 if (!defined $snmp_version) {
822 ($snmp_version, $community,$request_id, $error_status, $error_index, $bindings)
823 = decode_by_template ($trap, "%{%i%s%*{%i%i%i%{%@", inform_request);
824 }
825 return $this->error_return ("v2 trap/inform request contained errorStatus/errorIndex "
826 .$error_status."/".$error_index)
827 if defined $error_status && defined $error_index
828 && ($error_status != 0 || $error_index != 0);
829 }
830 if (!defined $snmp_version) {
831 return $this->error_return ("BER error decoding trap:\n ".$BER::errmsg);
832 }
833 return ($community, $ent, $agent, $gen, $spec, $dt, $bindings);
834 }
835  
836 =head1 METHODS in package SNMPv1_Session
837  
838 =cut
839  
840 package SNMPv1_Session;
841  
842 use strict qw(vars subs); # see above
843 use vars qw(@ISA);
844 use SNMP_Session;
845 use Socket;
846 use BER;
847 use IO::Socket;
848 use Carp;
849  
850 BEGIN {
851 if($SNMP_Session::ipv6available) {
852 import IO::Socket::INET6;
853 Socket6->import(qw(inet_pton inet_ntop getaddrinfo));
854 }
855 }
856  
857 @ISA = qw(SNMP_Session);
858  
859 sub snmp_version { 0 }
860  
861 =head2 open() - create an SNMPv1 session object
862  
863 $session = SNMPv1_Session->open
864 ($host, $community, $port,
865 $max_pdu_len, $local_port, $max_repetitions,
866 $local_host, $ipv4only);
867  
868 Note that all arguments except for C<$host> are optional. The
869 C<$host> can be specified either as a hostname or as a numeric
870 address. Numeric IPv6 addresses must be enclosed in square brackets
871 []
872  
873 C<$community> defaults to C<public>.
874  
875 C<$port> defaults to 161, the standard UDP port to send SNMP requests
876 to.
877  
878 C<$max_pdu_len> defaults to 8000.
879  
880 C<$local_port> can be specified if a specific local port is desired,
881 for example because of firewall rules for the response packets. If
882 none is specified, the operating system will choose a random port.
883  
884 C<$max_repetitions> is the maximum number of repetitions requested in
885 C<get-bulk> requests. It is only relevant in SNMPv2(c) and later.
886  
887 C<$local_host> can be used to specify a specific address/interface.
888 It is useful on hosts that have multiple addresses if a specific
889 address should be used, for example because of firewall rules.
890  
891 If C<$ipv4only> is either not present or non-zero, then an IPv4-only
892 socket will be used. This is also the case if the system only
893 supports IPv4. Otherwise, an IPv6 socket is created. IPv6 sockets
894 support both IPv6 and IPv4 requests and responses.
895  
896 =cut
897  
898 sub open {
899 my($this,
900 $remote_hostname,$community,$port,
901 $max_pdu_len,$local_port,$max_repetitions,
902 $local_hostname,$ipv4only) = @_;
903 my($remote_addr,$socket,$sockfamily);
904  
905 $ipv4only = 1 unless defined $ipv4only;
906 $sockfamily = AF_INET;
907  
908 $community = 'public' unless defined $community;
909 $port = SNMP_Session::standard_udp_port unless defined $port;
910 $max_pdu_len = 8000 unless defined $max_pdu_len;
911 $max_repetitions = $default_max_repetitions
912 unless defined $max_repetitions;
913  
914 if ($ipv4only || ! $SNMP_Session::ipv6available) {
915 # IPv4-only code, uses only Socket and INET calls
916 if (defined $remote_hostname) {
917 $remote_addr = inet_aton ($remote_hostname)
918 or return $this->error_return ("can't resolve \"$remote_hostname\" to IP address");
919 }
920 if ($SNMP_Session::recycle_socket && exists $the_socket{$sockfamily}) {
921 $socket = $the_socket{$sockfamily};
922 } else {
923 $socket = IO::Socket::INET->new(Proto => 17,
924 Type => SOCK_DGRAM,
925 LocalAddr => $local_hostname,
926 LocalPort => $local_port)
927 || return $this->error_return ("creating socket: $!");
928 $the_socket{$sockfamily} = $socket
929 if $SNMP_Session::recycle_socket;
930 }
931 $remote_addr = pack_sockaddr_in ($port, $remote_addr)
932 if defined $remote_addr;
933 } else {
934 # IPv6-capable code. Will use IPv6 or IPv4 depending on the address.
935 # Uses Socket6 and INET6 calls.
936  
937 if (defined $remote_hostname) {
938 # If it's a numeric IPv6 addresses, remove square brackets
939 if ($remote_hostname =~ /^\[(.*)\]$/) {
940 $remote_hostname = $1;
941 }
942 my (@res, $socktype_tmp, $proto_tmp, $canonname_tmp);
943 @res = getaddrinfo($remote_hostname, $port, AF_UNSPEC, SOCK_DGRAM);
944 ($sockfamily, $socktype_tmp, $proto_tmp, $remote_addr, $canonname_tmp) = @res;
945 if (scalar(@res) < 5) {
946 return $this->error_return ("can't resolve \"$remote_hostname\" to IPv6 address");
947 }
948 } else {
949 $sockfamily = AF_INET6;
950 }
951  
952 if ($SNMP_Session::recycle_socket && exists $the_socket{$sockfamily}) {
953 $socket = $the_socket{$sockfamily};
954 } elsif ($sockfamily == AF_INET) {
955 $socket = IO::Socket::INET->new(Proto => 17,
956 Type => SOCK_DGRAM,
957 LocalAddr => $local_hostname,
958 LocalPort => $local_port)
959 || return $this->error_return ("creating socket: $!");
960 } else {
961 $socket = IO::Socket::INET6->new(Domain => AF_INET6,
962 Proto => 17,
963 Type => SOCK_DGRAM,
964 LocalAddr => $local_hostname,
965 LocalPort => $local_port)
966 || return $this->error_return ("creating socket: $!");
967 $the_socket{$sockfamily} = $socket
968 if $SNMP_Session::recycle_socket;
969 }
970 }
971 bless {
972 'sock' => $socket,
973 'sockfileno' => fileno ($socket),
974 'community' => $community,
975 'remote_hostname' => $remote_hostname,
976 'remote_addr' => $remote_addr,
977 'sockfamily' => $sockfamily,
978 'max_pdu_len' => $max_pdu_len,
979 'pdu_buffer' => '\0' x $max_pdu_len,
980 'request_id' => (int (rand 0x10000) << 16)
981 + int (rand 0x10000) - 0x80000000,
982 'timeout' => $default_timeout,
983 'retries' => $default_retries,
984 'backoff' => $default_backoff,
985 'debug' => $default_debug,
986 'error_status' => 0,
987 'error_index' => 0,
988 'default_max_repetitions' => $max_repetitions,
989 'use_getbulk' => 1,
990 'lenient_source_address_matching' => 1,
991 'lenient_source_port_matching' => 1,
992 'avoid_negative_request_ids' => $SNMP_Session::default_avoid_negative_request_ids,
993 'use_16bit_request_ids' => $SNMP_Session::default_use_16bit_request_ids,
994 'capture_buffer' => undef,
995 };
996 }
997  
998 =head2 open_trap_session() - create a session for receiving SNMP traps.
999  
1000 $session = open_trap_session ($port, $ipv4only);
1001  
1002 C<$port> defaults to 162, the standard UDP port that SNMP
1003 notifications are sent to.
1004  
1005 If C<$ipv4only> is either not present or non-zero, then an IPv4-only
1006 socket will be used. This is also the case if the system only
1007 supports IPv4. Otherwise, an IPv6 socket is created. IPv6 sockets
1008 can receive messages over both IPv6 and IPv4.
1009  
1010 =cut
1011  
1012 sub open_trap_session (@) {
1013 my ($this, $port, $ipv4only) = @_;
1014 $port = 162 unless defined $port;
1015 $ipv4only = 1 unless defined $ipv4only;
1016 return $this->open (undef, "", 161, undef, $port,
1017 undef, undef, $ipv4only);
1018 }
1019  
1020 sub sock { $_[0]->{sock} }
1021 sub sockfileno { $_[0]->{sockfileno} }
1022 sub remote_addr { $_[0]->{remote_addr} }
1023 sub pdu_buffer { $_[0]->{pdu_buffer} }
1024 sub max_pdu_len { $_[0]->{max_pdu_len} }
1025 sub default_max_repetitions {
1026 defined $_[1]
1027 ? $_[0]->{default_max_repetitions} = $_[1]
1028 : $_[0]->{default_max_repetitions} }
1029 sub debug { defined $_[1] ? $_[0]->{debug} = $_[1] : $_[0]->{debug} }
1030  
1031 sub close {
1032 my($this) = shift;
1033 ## Avoid closing the socket if it may be shared with other session
1034 ## objects.
1035 if (! exists $the_socket{$this->{sockfamily}}
1036 or $this->sock ne $the_socket{$this->{sockfamily}}) {
1037 close ($this->sock) || $this->error ("close: $!");
1038 }
1039 }
1040  
1041 sub wrap_request {
1042 my($this) = shift;
1043 my($request) = shift;
1044  
1045 encode_sequence (encode_int ($this->snmp_version),
1046 encode_string ($this->{community}),
1047 $request)
1048 || return $this->ber_error ("wrapping up request PDU");
1049 }
1050  
1051 my @error_status_code = qw(noError tooBig noSuchName badValue readOnly
1052 genErr noAccess wrongType wrongLength
1053 wrongEncoding wrongValue noCreation
1054 inconsistentValue resourceUnavailable
1055 commitFailed undoFailed authorizationError
1056 notWritable inconsistentName);
1057  
1058 sub unwrap_response_5b {
1059 my ($this,$response,$tag,$oids,$errorp) = @_;
1060 my ($community,$request_id,@rest,$snmpver);
1061  
1062 ($snmpver,$community,$request_id,
1063 $this->{error_status},
1064 $this->{error_index},
1065 @rest)
1066 = decode_by_template ($response, "%{%i%s%*{%i%i%i%{%@",
1067 $tag);
1068 return $this->ber_error ("Error decoding response PDU")
1069 unless defined $snmpver;
1070 return $this->error ("Received SNMP response with unknown snmp-version field $snmpver")
1071 unless $snmpver == $this->snmp_version;
1072 if ($this->{error_status} != 0) {
1073 if ($errorp) {
1074 my ($oid, $errmsg);
1075 $errmsg = $error_status_code[$this->{error_status}] || $this->{error_status};
1076 $oid = $oids->[$this->{error_index}-1]
1077 if $this->{error_index} > 0 && $this->{error_index}-1 <= $#{$oids};
1078 $oid = $oid->[0]
1079 if ref($oid) eq 'ARRAY';
1080 return ($community, $request_id,
1081 $this->error ("Received SNMP response with error code\n"
1082 ." error status: $errmsg\n"
1083 ." index ".$this->{error_index}
1084 .(defined $oid
1085 ? " (OID: ".&BER::pretty_oid($oid).")"
1086 : "")));
1087 } else {
1088 if ($this->{error_index} == 1) {
1089 @rest[$this->{error_index}-1..$this->{error_index}] = ();
1090 }
1091 }
1092 }
1093 ($community, $request_id, @rest);
1094 }
1095  
1096 sub send_query ($$) {
1097 my ($this,$query) = @_;
1098 send ($this->sock,$query,0,$this->remote_addr);
1099 }
1100  
1101 ## Compare two sockaddr_in structures for equality. This is used when
1102 ## matching incoming responses with outstanding requests. Previous
1103 ## versions of the code simply did a bytewise comparison ("eq") of the
1104 ## two sockaddr_in structures, but this didn't work on some systems
1105 ## where sockaddr_in contains other elements than just the IP address
1106 ## and port number, notably FreeBSD.
1107 ##
1108 ## We allow for varying degrees of leniency when checking the source
1109 ## address. By default we now ignore it altogether, because there are
1110 ## agents that don't respond from UDP port 161, and there are agents
1111 ## that don't respond from the IP address the query had been sent to.
1112 ##
1113 ## The address family is stored in the session object. We could use
1114 ## sockaddr_family() to determine it from the sockaddr, but this function
1115 ## is only available in recent versions of Socket.pm.
1116 sub sa_equal_p ($$$) {
1117 my ($this, $sa1, $sa2) = @_;
1118 my ($p1,$a1,$p2,$a2);
1119  
1120 # Disable strict subs to stop old versions of perl from
1121 # complaining about AF_INET6 when Socket6 is not available
1122 if($this->{'sockfamily'} == AF_INET) {
1123 # IPv4 addresses
1124 ($p1,$a1) = unpack_sockaddr_in ($sa1);
1125 ($p2,$a2) = unpack_sockaddr_in ($sa2);
1126 } elsif($this->{'sockfamily'} == AF_INET6()) {
1127 # IPv6 addresses
1128 ($p1,$a1) = Socket6::unpack_sockaddr_in6 ($sa1);
1129 ($p2,$a2) = Socket6::unpack_sockaddr_in6 ($sa2);
1130 } else {
1131 return 0;
1132 }
1133 use strict "subs";
1134  
1135 if (! $this->{'lenient_source_address_matching'}) {
1136 return 0 if $a1 ne $a2;
1137 }
1138 if (! $this->{'lenient_source_port_matching'}) {
1139 return 0 if $p1 != $p2;
1140 }
1141 return 1;
1142 }
1143  
1144 sub receive_response_3 {
1145 my ($this, $response_tag, $oids, $errorp, $dont_block_p) = @_;
1146 my ($remote_addr);
1147 my $flags = 0;
1148 $flags = $dont_wait_flags if defined $dont_block_p and $dont_block_p;
1149 $remote_addr = recv ($this->sock,$this->{'pdu_buffer'},$this->max_pdu_len,$flags);
1150 return $this->error ("receiving response PDU: $!")
1151 unless defined $remote_addr;
1152 return $this->error ("short (".length $this->{'pdu_buffer'}
1153 ." bytes) response PDU")
1154 unless length $this->{'pdu_buffer'} > 2;
1155 my $response = $this->{'pdu_buffer'};
1156 ##
1157 ## Check whether the response came from the address we've sent the
1158 ## request to. If this is not the case, we should probably ignore
1159 ## it, as it may relate to another request.
1160 ##
1161 if (defined $this->{'remote_addr'}) {
1162 if (! $this->sa_equal_p ($remote_addr, $this->{'remote_addr'})) {
1163 if ($this->{'debug'} && !$SNMP_Session::recycle_socket) {
1164 carp ("Response came from ".&SNMP_Session::pretty_address($remote_addr)
1165 .", not ".&SNMP_Session::pretty_address($this->{'remote_addr'}))
1166 unless $SNMP_Session::suppress_warnings;
1167 }
1168 return 0;
1169 }
1170 }
1171 $this->{'last_sender_addr'} = $remote_addr;
1172 my ($response_community, $response_id, @unwrapped)
1173 = $this->unwrap_response_5b ($response, $response_tag,
1174 $oids, $errorp);
1175 if ($response_community ne $this->{community}
1176 || $response_id ne $this->{request_id}) {
1177 if ($this->{'debug'}) {
1178 carp ("$response_community != $this->{community}")
1179 unless $SNMP_Session::suppress_warnings
1180 || $response_community eq $this->{community};
1181 carp ("$response_id != $this->{request_id}")
1182 unless $SNMP_Session::suppress_warnings
1183 || $response_id == $this->{request_id};
1184 }
1185 return 0;
1186 }
1187 if (!defined $unwrapped[0]) {
1188 $this->{'unwrapped'} = undef;
1189 return undef;
1190 }
1191 $this->{'unwrapped'} = \@unwrapped;
1192 return length $this->pdu_buffer;
1193 }
1194  
1195 sub describe {
1196 my($this) = shift;
1197 print $this->to_string (),"\n";
1198 }
1199  
1200 sub to_string {
1201 my($this) = shift;
1202 my ($class,$prefix);
1203  
1204 $class = ref($this);
1205 $prefix = ' ' x (length ($class) + 2);
1206 ($class
1207 .(defined $this->{remote_hostname}
1208 ? " (remote host: \"".$this->{remote_hostname}."\""
1209 ." ".&SNMP_Session::pretty_address ($this->remote_addr).")"
1210 : " (no remote host specified)")
1211 ."\n"
1212 .$prefix." community: \"".$this->{'community'}."\"\n"
1213 .$prefix." request ID: ".$this->{'request_id'}."\n"
1214 .$prefix."PDU bufsize: ".$this->{'max_pdu_len'}." bytes\n"
1215 .$prefix." timeout: ".$this->{timeout}."s\n"
1216 .$prefix." retries: ".$this->{retries}."\n"
1217 .$prefix." backoff: ".$this->{backoff}.")");
1218 ## sprintf ("SNMP_Session: %s (size %d timeout %g)",
1219 ## &SNMP_Session::pretty_address ($this->remote_addr),$this->max_pdu_len,
1220 ## $this->timeout);
1221 }
1222  
1223 ### SNMP Agent support
1224 ### contributed by Mike McCauley <mikem@open.com.au>
1225 ###
1226 sub receive_request {
1227 my ($this) = @_;
1228 my ($remote_addr, $iaddr, $port, $request);
1229  
1230 $remote_addr = recv($this->sock, $this->{'pdu_buffer'},
1231 $this->{'max_pdu_len'}, 0);
1232 return undef unless $remote_addr;
1233  
1234 if( (defined $ipv6_addr_len) && (length $remote_addr == $ipv6_addr_len)) {
1235 ($port,$iaddr) = Socket6::unpack_sockaddr_in6($remote_addr);
1236 } else {
1237 ($port,$iaddr) = unpack_sockaddr_in($remote_addr);
1238 }
1239  
1240 $request = $this->{'pdu_buffer'};
1241 return ($request, $iaddr, $port);
1242 }
1243  
1244 sub decode_request {
1245 my ($this, $request) = @_;
1246 my ($snmp_version, $community, $requestid, $errorstatus, $errorindex, $bindings);
1247  
1248 ($snmp_version, $community, $requestid, $errorstatus, $errorindex, $bindings)
1249 = decode_by_template ($request, "%{%i%s%*{%i%i%i%@", SNMP_Session::get_request);
1250 if (defined $snmp_version)
1251 {
1252 # Its a valid get_request
1253 return(SNMP_Session::get_request, $requestid, $bindings, $community);
1254 }
1255  
1256 ($snmp_version, $community, $requestid, $errorstatus, $errorindex, $bindings)
1257 = decode_by_template ($request, "%{%i%s%*{%i%i%i%@", SNMP_Session::getnext_request);
1258 if (defined $snmp_version)
1259 {
1260 # Its a valid getnext_request
1261 return(SNMP_Session::getnext_request, $requestid, $bindings, $community);
1262 }
1263  
1264 ($snmp_version, $community, $requestid, $errorstatus, $errorindex, $bindings)
1265 = decode_by_template ($request, "%{%i%s%*{%i%i%i%@", SNMP_Session::set_request);
1266 if (defined $snmp_version)
1267 {
1268 # Its a valid set_request
1269 return(SNMP_Session::set_request, $requestid, $bindings, $community);
1270 }
1271  
1272 # Something wrong with this packet
1273 # Decode failed
1274 return undef;
1275 }
1276  
1277 =head1 METHODS in package SNMPv2c_Session
1278  
1279 =cut
1280  
1281 package SNMPv2c_Session;
1282 use strict qw(vars subs); # see above
1283 use vars qw(@ISA);
1284 use SNMP_Session;
1285 use BER;
1286 use Carp;
1287  
1288 @ISA = qw(SNMPv1_Session);
1289  
1290 sub snmp_version { 1 }
1291  
1292 =head2 open() - create an SNMPv2(c) session object
1293  
1294 $session = SNMPv2c_Session->open
1295 ($host, $community, $port,
1296 $max_pdu_len, $local_port, $max_repetitions,
1297 $local_host, $ipv4only);
1298  
1299 The calling and return conventions are identical to
1300 C<SNMPv1_Session::open()>, except that this returns a session object
1301 that supports SNMPv2 operations.
1302  
1303 =cut
1304  
1305 sub open {
1306 my $session = SNMPv1_Session::open (@_);
1307 return undef unless defined $session;
1308 return bless $session;
1309 }
1310  
1311 ## map_table_start_end using get-bulk
1312 ##
1313 sub map_table_start_end ($$$$$$) {
1314 my ($session, $columns, $mapfn, $start, $end, $max_repetitions) = @_;
1315  
1316 my @encoded_oids;
1317 my $call_counter = 0;
1318 my $base_index = $start;
1319 my $ncols = @{$columns};
1320 my @collected_values = ();
1321  
1322 if (! $session->{'use_getbulk'}) {
1323 return SNMP_Session::map_table_start_end
1324 ($session, $columns, $mapfn, $start, $end, $max_repetitions);
1325 }
1326 $max_repetitions = $session->default_max_repetitions
1327 unless defined $max_repetitions;
1328  
1329 for (;;) {
1330 foreach (@encoded_oids = @{$columns}) {
1331 $_=encode_oid (@{$_},split '\.',$base_index)
1332 || return $session->ber_error ("encoding OID $base_index");
1333 }
1334 if ($session->getbulk_request_response (0, $max_repetitions,
1335 @encoded_oids)) {
1336 my $response = $session->pdu_buffer;
1337 my ($bindings) = $session->decode_get_response ($response);
1338 my @colstack = ();
1339 my $k = 0;
1340 my $j;
1341  
1342 my $min_index = undef;
1343  
1344 my @bases = @{$columns};
1345 my $n_bindings = 0;
1346 my $binding;
1347  
1348 ## Copy all bindings into the colstack.
1349 ## The colstack is a vector of vectors.
1350 ## It contains one vector for each "repeater" variable.
1351 ##
1352 while ($bindings ne '') {
1353 ($binding, $bindings) = decode_sequence ($bindings);
1354 my ($oid, $value) = decode_by_template ($binding, "%O%@");
1355  
1356 push @{$colstack[$k]}, [$oid, $value];
1357 ++$k; $k = 0 if $k >= $ncols;
1358 }
1359  
1360 ## Now collect rows from the column stack:
1361 ##
1362 ## Iterate through the column stacks to find the smallest
1363 ## index, collecting the values for that index in
1364 ## @collected_values.
1365 ##
1366 ## As long as a row can be assembled, the map function is
1367 ## called on it and the iteration proceeds.
1368 ##
1369 $base_index = undef;
1370 walk_rows_from_pdu:
1371 for (;;) {
1372 my $min_index = undef;
1373  
1374 for ($k = 0; $k < $ncols; ++$k) {
1375 $collected_values[$k] = undef;
1376 my $pair = $colstack[$k]->[0];
1377 unless (defined $pair) {
1378 $min_index = undef;
1379 last walk_rows_from_pdu;
1380 }
1381 my $this_index
1382 = SNMP_Session::oid_diff ($columns->[$k], $pair->[0]);
1383 if (defined $this_index) {
1384 my $cmp
1385 = !defined $min_index
1386 ? -1
1387 : SNMP_Session::index_compare
1388 ($this_index, $min_index);
1389 if ($cmp == -1) {
1390 for ($j = 0; $j < $k; ++$j) {
1391 unshift (@{$colstack[$j]},
1392 [$min_index,
1393 $collected_values[$j]]);
1394 $collected_values[$j] = undef;
1395 }
1396 $min_index = $this_index;
1397 }
1398 if ($cmp <= 0) {
1399 $collected_values[$k] = $pair->[1];
1400 shift @{$colstack[$k]};
1401 }
1402 }
1403 }
1404 ($base_index = undef), last
1405 if !defined $min_index;
1406 last
1407 if defined $end
1408 and SNMP_Session::index_compare ($min_index, $end) >= 0;
1409 &$mapfn ($min_index, @collected_values);
1410 ++$call_counter;
1411 $base_index = $min_index;
1412 }
1413 } else {
1414 return undef;
1415 }
1416 last if !defined $base_index;
1417 last
1418 if defined $end
1419 and SNMP_Session::index_compare ($base_index, $end) >= 0;
1420 }
1421 $call_counter;
1422 }
1423  
1424 1;
1425  
1426 =head1 EXAMPLES
1427  
1428 The basic usage of these routines works like this:
1429  
1430 use BER;
1431 use SNMP_Session;
1432
1433 # Set $host to the name of the host whose SNMP agent you want
1434 # to talk to. Set $community to the community name under
1435 # which you want to talk to the agent. Set port to the UDP
1436 # port on which the agent listens (usually 161).
1437
1438 $session = SNMP_Session->open ($host, $community, $port)
1439 or die "couldn't open SNMP session to $host";
1440
1441 # Set $oid1, $oid2... to the BER-encoded OIDs of the MIB
1442 # variables you want to get.
1443
1444 if ($session->get_request_response ($oid1, $oid2, ...)) {
1445 ($bindings) = $session->decode_get_response ($session->{pdu_buffer});
1446
1447 while ($bindings ne '') {
1448 ($binding,$bindings) = decode_sequence ($bindings);
1449 ($oid,$value) = decode_by_template ($binding, "%O%@");
1450 print pretty_print ($oid)," => ", pretty_print ($value), "\n";
1451 }
1452 } else {
1453 die "No response from agent on $host";
1454 }
1455  
1456 =head2 Encoding OIDs
1457  
1458 In order to BER-encode OIDs, you can use the function
1459 B<BER::encode_oid>. It takes (a vector of) numeric subids as an
1460 argument. For example,
1461  
1462 use BER;
1463 encode_oid (1, 3, 6, 1, 2, 1, 1, 1, 0)
1464  
1465 will return the BER-encoded OID for the B<sysDescr.0>
1466 (1.3.6.1.2.1.1.1.0) instance of MIB-2.
1467  
1468 =head2 Decoding the results
1469  
1470 When C<get_request_response()> returns success, you must decode the
1471 response PDU from the remote agent. The function
1472 C<decode_get_response()> can be used to do this. It takes a
1473 C<get-response> PDU, checks its syntax and returns the I<bindings>
1474 part of the PDU. This is where the remote agent actually returns the
1475 values of the variables in your query.
1476  
1477 You should iterate over the individual bindings in this I<bindings>
1478 part and extract the value for each variable. In the example above,
1479 the returned bindings are simply printed using the
1480 C<BER::pretty_print()> function.
1481  
1482 For better readability of the OIDs, you can also use the following
1483 idiom, where the C<%pretty_oids> hash maps BER-encoded numerical OIDs
1484 to symbolic OIDs. Note that this simple-minded mapping only works for
1485 response OIDs that exactly match known OIDs, so it's unsuitable for
1486 table walking (where the response OIDs include an additional row
1487 index).
1488  
1489 %ugly_oids = qw(sysDescr.0 1.3.6.1.2.1.1.1.0
1490 sysContact.0 1.3.6.1.2.1.1.4.0);
1491 foreach (keys %ugly_oids) {
1492 $ugly_oids{$_} = encode_oid (split (/\./, $ugly_oids{$_}));
1493 $pretty_oids{$ugly_oids{$_}} = $_;
1494 }
1495 ...
1496 if ($session->get_request_response ($ugly_oids{'sysDescr.0'},
1497 $ugly_oids{'sysContact.0'})) {
1498 ($bindings) = $session->decode_get_response ($session->{pdu_buffer});
1499 while ($bindings ne '') {
1500 ($binding,$bindings) = decode_sequence ($bindings);
1501 ($oid,$value) = decode_by_template ($binding, "%O%@");
1502 print $pretty_oids{$oid}," => ",
1503 pretty_print ($value), "\n";
1504 }
1505 } ...
1506  
1507 =head2 Set Requests
1508  
1509 Set requests are generated much like C<get> or C<getNext> requests
1510 are, with the exception that you have to specify not just OIDs, but
1511 also the values the variables should be set to. Every binding is
1512 passed as a reference to a two-element array, the first element being
1513 the encoded OID and the second one the encoded value. See the
1514 C<test/set-test.pl> script for an example, in particular the
1515 subroutine C<snmpset>.
1516  
1517 =head2 Walking Tables
1518  
1519 Beginning with version 0.57 of C<SNMP_Session.pm>, there is API
1520 support for walking tables. The C<map_table()> method can be used for
1521 this as follows:
1522  
1523 sub walk_function ($$$) {
1524 my ($index, $val1, $val3) = @_;
1525 ...
1526 }
1527
1528 ...
1529 $columns = [$base_oid1, $base_oid3];
1530 $n_rows = $session->map_table ($columns, \&walk_function);
1531  
1532 The I<columns> argument must be a reference to a list of OIDs for table
1533 columns sharing the same index. The method will traverse the table and
1534 call the I<walk_function> for each row. The arguments for these calls
1535 will be:
1536  
1537 =over
1538  
1539 =item 1. the I<row index> as a partial OID in dotted notation, e.g.
1540 C<1.3>, or C<10.0.1.34>.
1541  
1542 =item 2. the values of the requested table columns in that row, in
1543 BER-encoded form. If you want to use the standard C<pretty_print()>
1544 subroutine to decode the values, you can use the following idiom:
1545  
1546 grep (defined $_ && ($_=pretty_print $_), ($val1, $val3));
1547  
1548 =back
1549  
1550 =head2 Walking Tables With C<get-bulk>
1551  
1552 Since version 0.67, C<SNMP_Session> uses a different C<get_table>
1553 implementation for C<SNMPv2c_Session>s. This version uses the
1554 ``powerful C<get-bulk> operator'' to retrieve many table rows with
1555 each request. In general, this will make table walking much faster
1556 under SNMPv2c, especially when round-trip times to the agent are long.
1557  
1558 There is one difficulty, however: With C<get-bulk>, a management
1559 application can specify the maximum number of rows to return in a
1560 single response. C<SNMP_Session.pm> provides a new function,
1561 C<map_table_4>, in which this C<maxRepetitions> value can be specified
1562 explicitly.
1563  
1564 For maximum efficiency, it should be set to a value that is one
1565 greater than the number of rows in the table. If it is smaller, then
1566 C<map_table()> will use more request/response cycles than necessary;
1567 if it is bigger, the agent will have to compute variable bindings
1568 beyond the end of the table (which C<map_table()> will throw away).
1569  
1570 Of course it is usually impossible to know the size of the table in
1571 advance. If you don't specify C<maxRepetitions> when walking a table,
1572 then C<map_table()> will use a per-session default
1573 (C<$session-E<gt>default_max_repetitions>). The default value for this
1574 default is 12.
1575  
1576 If you walk a table multiple times, and the size of the table is
1577 relatively stable, you should use the return value of C<map_table()>
1578 (which is the number of rows it has encountered) to compute the next
1579 value of C<maxRepetitions>. Remember to add one so that C<map_table()>
1580 notices when the table is finished!
1581  
1582 Note that for really big tables, this doesn't make a big difference,
1583 since the table won't fit in a single response packet anyway.
1584  
1585 =head2 Sending Traps
1586  
1587 To send a trap, you have to open an SNMP session to the trap receiver.
1588 Usually this is a process listening to UDP port 162 on a network
1589 management station. Then you can use the C<trap_request_send()> method
1590 to encode and send SNMPv1 traps. There is no way to find out whether
1591 the trap was actually received at the management station - SNMP traps
1592 are fundamentally unreliable.
1593  
1594 When constructing an SNMPv1 trap, you must provide
1595  
1596 =over
1597  
1598 =item * the "enterprise" Object Identifier for the entity that
1599 generates the trap
1600  
1601 =item * your IP address
1602  
1603 =item * the generic trap type
1604  
1605 =item * the specific trap type
1606  
1607 =item * the C<sysUpTime> at the time of trap generation
1608  
1609 =item * a sequence (may be empty) of variable bindings further
1610 describing the trap.
1611  
1612 =back
1613  
1614 For SNMPv2 traps, you need:
1615  
1616 =over
1617  
1618 =item * the trap's OID
1619  
1620 =item * the C<sysUpTime> at the time of trap generation
1621  
1622 =item * the bindings list as above
1623  
1624 =back
1625  
1626 For SNMPv2 traps, the uptime and trap OID are encoded as bindings which
1627 are added to the front of the other bindings you provide.
1628  
1629 Here is a short example:
1630  
1631 my $trap_receiver = "netman.noc";
1632 my $trap_community = "SNMP_Traps";
1633 my $trap_session = $version eq '1'
1634 ? SNMP_Session->open ($trap_receiver, $trap_community, 162)
1635 : SNMPv2c_Session->open ($trap_receiver, $trap_community, 162);
1636 my $myIpAddress = ...;
1637 my $start_time = time;
1638
1639 ...
1640
1641 sub link_down_trap ($$) {
1642 my ($if_index, $version) = @_;
1643 my $genericTrap = 2; # linkDown
1644 my $specificTrap = 0;
1645 my @ifIndexOID = ( 1,3,6,1,2,1,2,2,1,1 );
1646 my $upTime = int ((time - $start_time) * 100.0);
1647 my @myOID = ( 1,3,6,1,4,1,2946,0,8,15 );
1648
1649 warn "Sending trap failed"
1650 unless ($version eq '1')
1651 ? $trap_session->trap_request_send (encode_oid (@myOID),
1652 encode_ip_address ($myIpAddress),
1653 encode_int ($genericTrap),
1654 encode_int ($specificTrap),
1655 encode_timeticks ($upTime),
1656 [encode_oid (@ifIndex_OID,$if_index),
1657 encode_int ($if_index)],
1658 [encode_oid (@ifDescr_OID,$if_index),
1659 encode_string ("foo")])
1660 : $trap_session->v2_trap_request_send (\@linkDown_OID, $upTime,
1661 [encode_oid (@ifIndex_OID,$if_index),
1662 encode_int ($if_index)],
1663 [encode_oid (@ifDescr_OID,$if_index),
1664 encode_string ("foo")]);
1665 }
1666  
1667 =head2 Receiving Traps
1668  
1669 Since version 0.60, C<SNMP_Session.pm> supports the receipt and
1670 decoding of SNMPv1 trap requests. Since version 0.75, SNMPv2 Trap PDUs
1671 are also recognized.
1672  
1673 To receive traps, you have to create a special SNMP session that
1674 passively listens on the SNMP trap transport address, usually on UDP
1675 port 162. Then you can receive traps - actually, SNMPv1 traps, SNMPv2
1676 traps, and SNMPv2 informs, using the C<receive_trap_1()> method and
1677 decode them using C<decode_trap_request()>. The I<enterprise>,
1678 I<agent>, I<generic>, I<specific> and I<sysUptime> return values are
1679 only defined for SNMPv1 traps. In SNMPv2 traps and informs, the
1680 equivalent information is contained in the bindings.
1681  
1682 my $trap_session = SNMPv1_Session->open_trap_session (162, 0)
1683 or die "cannot open trap session";
1684 my ($trap, $sender_sockaddr) = $trap_session->receive_trap_1 ()
1685 or die "cannot receive trap";
1686 my ($community, $enterprise, $agent,
1687 $generic, $specific, $sysUptime, $bindings)
1688 = $trap_session->decode_trap_request ($trap)
1689 or die "cannot decode trap received"
1690 ...
1691 my ($binding, $oid, $value);
1692 while ($bindings ne '') {
1693 ($binding,$bindings) = decode_sequence ($bindings);
1694 ($oid, $value) = decode_by_template ($binding, "%O%@");
1695 print BER::pretty_oid ($oid)," => ",pretty_print ($value),"\n";
1696 }
1697  
1698 =head1 AUTHORS
1699  
1700 Created by: Simon Leinen E<lt>simon.leinen@switch.chE<gt>
1701  
1702 Contributions and fixes by:
1703  
1704 =over
1705  
1706 =item Matthew Trunnell E<lt>matter@media.mit.eduE<gt>
1707  
1708 =item Tobias Oetiker E<lt>tobi@oetiker.chE<gt>
1709  
1710 =item Heine Peters E<lt>peters@dkrz.deE<gt>
1711  
1712 =item Daniel L. Needles E<lt>dan_needles@INS.COME<gt>
1713  
1714 =item Mike Mitchell E<lt>mcm@unx.sas.comE<gt>
1715  
1716 =item Clinton Wong E<lt>clintdw@netcom.comE<gt>
1717  
1718 =item Alan Nichols E<lt>Alan.Nichols@Ebay.Sun.COME<gt>
1719  
1720 =item Mike McCauley E<lt>mikem@open.com.auE<gt>
1721  
1722 =item Andrew W. Elble E<lt>elble@icculus.nsg.nwu.eduE<gt>
1723  
1724 =item Brett T Warden E<lt>wardenb@eluminant.comE<gt>: pretty C<UInteger32>
1725  
1726 =item Michael Deegan E<lt>michael@cnspc18.murdoch.edu.auE<gt>
1727  
1728 =item Sergio Macedo E<lt>macedo@tmp.com.brE<gt>
1729  
1730 =item Jakob Ilves (/IlvJa) E<lt>jakob.ilves@oracle.comE<gt>: PDU capture
1731  
1732 =item Valerio Bontempi E<lt>v.bontempi@inwind.itE<gt>: IPv6 support
1733  
1734 =item Lorenzo Colitti E<lt>lorenzo@colitti.comE<gt>: IPv6 support
1735  
1736 =item Philippe Simonet E<lt>Philippe.Simonet@swisscom.comE<gt>: Export C<avoid...>
1737  
1738 =item Luc Pauwels E<lt>Luc.Pauwels@xalasys.comE<gt>: C<use_16bit_request_ids>
1739  
1740 =item Andrew Cornford-Matheson E<lt>andrew.matheson@corenetworks.comE<gt>: inform
1741  
1742 =item Gerry Dalton E<lt>gerry.dalton@consolidated.comE<gt>: C<strict subs> bug
1743  
1744 =item Mike Fischer E<lt>mlf2@tampabay.rr.comE<gt>: pass MSG_DONTWAIT to C<recv()>
1745  
1746 =back
1747  
1748 =head1 COPYRIGHT
1749  
1750 Copyright (c) 1995-2009, Simon Leinen.
1751  
1752 This program is free software; you can redistribute it under the
1753 "Artistic License 2.0" included in this distribution (file "Artistic").
1754  
1755 =cut