SNMP.pm untested

filter: Statementstmt 0.0% 0 / 810 Branchbran 0.0% 0 / 432 Conditioncond 0.0% 0 / 63 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 87 Podpod 0.0% 0 / 77 totaltotal 0.0% 0 / 1510 CC 217 SCAR 51.4
CC
217
Cov
0%
get_entries
930.0
_get_entries_cb
506.0
new
210.0
CRAP 170.1
1 # -*- mode: perl -*-
2 # ============================================================================
3  
4 package Net::SNMP;
5  
6 # $Id: SNMP.pm,v 6.1 2010/09/10 00:01:22 dtown Rel $
7  
8 # Copyright (c) 1998-2010 David M. Town <dtown@cpan.org>
9 # All rights reserved.
10  
11 # This program is free software; you may redistribute it and/or modify it
12 # under the same terms as the Perl 5 programming language system itself.
13  
14 # Release 4.0.0 of the Net::SNMP module was dedicated to those who died in
15 # the September 11, 2001 terrorist attacks on the United States of America.
16  
17 # ============================================================================
18  
19 =head1 NAME
20  
21 Net::SNMP - Object oriented interface to SNMP
22  
23 =head1 SYNOPSIS
24  
25 The Net::SNMP module implements an object oriented interface to the Simple
26 Network Management Protocol. Perl applications can use the module to retrieve
27 or update information on a remote host using the SNMP protocol. The module
28 supports SNMP version-1, SNMP version-2c (Community-Based SNMPv2), and SNMP
29 version-3. The Net::SNMP module assumes that the user has a basic understanding
30 of the Simple Network Management Protocol and related network management
31 concepts.
32  
33 =head1 DESCRIPTION
34  
35 The Net::SNMP module abstracts the intricate details of the Simple Network
36 Management Protocol by providing a high level programming interface to the
37 protocol. Each Net::SNMP object provides a one-to-one mapping between a Perl
38 object and a remote SNMP agent or manager. Once an object is created, it can
39 be used to perform the basic protocol exchange actions defined by SNMP.
40  
41 A Net::SNMP object can be created such that it has either "blocking" or
42 "non-blocking" properties. By default, the methods used to send SNMP messages
43 do not return until the protocol exchange has completed successfully or a
44 timeout period has expired. This behavior gives the object a "blocking"
45 property because the flow of the code is stopped until the method returns.
46  
47 The optional named argument B<-nonblocking> can be passed to the object
48 constructor with a true value to give the object "non-blocking" behavior.
49 A method invoked by a non-blocking object queues the SNMP message and returns
50 immediately, allowing the flow of the code to continue. The queued SNMP
51 messages are not sent until an event loop is entered by calling the
52 C<snmp_dispatcher()> method. When the SNMP messages are sent, any response to
53 the messages invokes the subroutine defined by the user when the message was
54 originally queued. The event loop exits when all messages have been removed
55 from the queue by either receiving a response, or by exceeding the number of
56 retries at the Transport Layer.
57  
58 =head2 Blocking Objects
59  
60 The default behavior of the methods associated with a Net::SNMP object is to
61 block the code flow until the method completes. For methods that initiate a
62 SNMP protocol exchange requiring a response, a hash reference containing the
63 results of the query is returned. The undefined value is returned by all
64 methods when a failure has occurred. The C<error()> method can be used to
65 determine the cause of the failure.
66  
67 The hash reference returned by a SNMP protocol exchange points to a hash
68 constructed from the VarBindList contained in the SNMP response message. The
69 hash is created using the ObjectName and the ObjectSyntax pairs in the
70 VarBindList. The keys of the hash consist of the OBJECT IDENTIFIERs in dotted
71 notation corresponding to each ObjectName in the VarBindList. The value of
72 each hash entry is set equal to the value of the corresponding ObjectSyntax.
73 This hash reference can also be retrieved using the C<var_bind_list()> method.
74  
75 =head2 Non-blocking Objects
76  
77 When a Net::SNMP object is created having non-blocking behavior, the invocation
78 of a method associated with the object returns immediately, allowing the flow
79 of the code to continue. When a method is invoked that would initiate a SNMP
80 protocol exchange requiring a response, either a true value (i.e. 0x1) is
81 returned immediately or the undefined value is returned if there was a failure.
82 The C<error()> method can be used to determine the cause of the failure.
83  
84 The contents of the VarBindList contained in the SNMP response message can be
85 retrieved by calling the C<var_bind_list()> method using the object reference
86 passed as the first argument to the callback. The value returned by the
87 C<var_bind_list()> method is a hash reference created using the ObjectName and
88 the ObjectSyntax pairs in the VarBindList. The keys of the hash consist of
89 the OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName
90 in the VarBindList. The value of each hash entry is set equal to the value of
91 the corresponding ObjectSyntax. The undefined value is returned if there has
92 been a failure and the C<error()> method may be used to determine the reason.
93  
94 =cut
95  
96 # ============================================================================
97  
98 use strict;
99  
100 ## Validate the version of Perl
101  
102 BEGIN
103 {
104 die 'Perl version 5.6.0 or greater is required' if ($] < 5.006);
105 }
106  
107 ## Version of the Net::SNMP module
108  
109 our $VERSION = 'v6.0.1';
110 $VERSION = eval $VERSION;
111  
112 ## Load our modules
113  
114 use Net::SNMP::Dispatcher();
115 use Net::SNMP::PDU qw( :ALL !DEBUG_INFO );
116 use Net::SNMP::Security();
117 use Net::SNMP::Transport qw( :ports );
118  
119 ## Handle importing/exporting of symbols
120  
121 use base qw( Exporter );
122  
123 our @EXPORT = qw(
124 INTEGER INTEGER32 OCTET_STRING OBJECT_IDENTIFIER IPADDRESS COUNTER
125 COUNTER32 GAUGE GAUGE32 UNSIGNED32 TIMETICKS OPAQUE COUNTER64 NOSUCHOBJECT
126 NOSUCHINSTANCE ENDOFMIBVIEW snmp_dispatcher
127 );
128  
129 our @EXPORT_OK = qw( oid_context_match );
130  
131 our %EXPORT_TAGS = (
132 asn1 => [
133 qw( INTEGER INTEGER32 OCTET_STRING NULL OBJECT_IDENTIFIER SEQUENCE
134 IPADDRESS COUNTER COUNTER32 GAUGE GAUGE32 UNSIGNED32 TIMETICKS
135 OPAQUE COUNTER64 NOSUCHOBJECT NOSUCHINSTANCE ENDOFMIBVIEW
136 GET_REQUEST GET_NEXT_REQUEST GET_RESPONSE SET_REQUEST TRAP
137 GET_BULK_REQUEST INFORM_REQUEST SNMPV2_TRAP REPORT )
138 ],
139 debug => [
140 qw( DEBUG_ALL DEBUG_NONE DEBUG_MESSAGE DEBUG_TRANSPORT DEBUG_DISPATCHER
141 DEBUG_PROCESSING DEBUG_SECURITY snmp_debug )
142 ],
143 generictrap => [
144 qw( COLD_START WARM_START LINK_DOWN LINK_UP AUTHENTICATION_FAILURE
145 EGP_NEIGHBOR_LOSS ENTERPRISE_SPECIFIC )
146 ],
147 snmp => [
148 qw( SNMP_VERSION_1 SNMP_VERSION_2C SNMP_VERSION_3 SNMP_PORT
149 SNMP_TRAP_PORT snmp_debug snmp_dispatcher snmp_dispatch_once
150 snmp_type_ntop oid_base_match oid_lex_cmp oid_lex_sort ticks_to_time )
151 ],
152 translate => [
153 qw( TRANSLATE_NONE TRANSLATE_OCTET_STRING TRANSLATE_NULL
154 TRANSLATE_TIMETICKS TRANSLATE_OPAQUE TRANSLATE_NOSUCHOBJECT
155 TRANSLATE_NOSUCHINSTANCE TRANSLATE_ENDOFMIBVIEW TRANSLATE_UNSIGNED
156 TRANSLATE_ALL )
157 ],
158 );
159  
160 Exporter::export_ok_tags( qw( asn1 debug generictrap snmp translate ) );
161  
162 $EXPORT_TAGS{ALL} = [ @EXPORT_OK ];
163  
164 ## Debugging bit masks
165  
166 sub DEBUG_ALL { 0xff } # All
167 sub DEBUG_NONE { 0x00 } # None
168 sub DEBUG_MESSAGE { 0x02 } # Message/PDU encoding/decoding
169 sub DEBUG_TRANSPORT { 0x04 } # Transport Layer
170 sub DEBUG_DISPATCHER { 0x08 } # Dispatcher
171 sub DEBUG_PROCESSING { 0x10 } # Message Processing
172 sub DEBUG_SECURITY { 0x20 } # Security
173  
174 ## Package variables
175  
176 our $DEBUG = DEBUG_NONE; # Debug mask
177  
178 our $DISPATCHER; # Dispatcher instance
179  
180 our $BLOCKING = 0; # Count of blocking objects
181  
182 our $NONBLOCKING = 0; # Count of non-blocking objects
183  
184 BEGIN
185 {
186 # Validate the creation of the Dispatcher object.
187  
188 if (!defined ($DISPATCHER = Net::SNMP::Dispatcher->instance())) {
189 die 'FATAL: Failed to create Dispatcher instance';
190 }
191  
192 # In older versions of Perl, the UNIVERSAL::VERSION() method does not
193 # handle version defined as v-strings gracefully. We provide our
194 # own handling of versions to account for this.
195  
196 if ($] < 5.009) {
197 *VERSION = \&require_version;
198 }
199 }
200  
201 # [public methods] -----------------------------------------------------------
202  
203 =head1 METHODS
204  
205 When named arguments are expected by the methods, two different styles are
206 supported. All examples in this documentation use the dashed-option style:
207  
208 $object->method(-argument => $value);
209  
210 However, the IO:: style is also allowed:
211  
212 $object->method(Argument => $value);
213  
214 =over
215  
216 =item Non-blocking Objects Arguments
217  
218 When a Net::SNMP object has been created with a "non-blocking" property, most
219 methods that generate a SNMP message take additional arguments to support this
220 property.
221  
222 =over
223  
224 =item Callback
225  
226 Most methods associated with a non-blocking object have an optional named
227 argument called B<-callback>. The B<-callback> argument expects a reference
228 to a subroutine or to an array whose first element must be a reference to a
229 subroutine. The subroutine defined by the B<-callback> option is executed when
230 a response to a SNMP message is received, an error condition has occurred, or
231 the number of retries for the message has been exceeded.
232  
233 When the B<-callback> argument only contains a subroutine reference, the
234 subroutine is evaluated passing a reference to the original Net::SNMP object
235 as the only parameter. If the B<-callback> argument was defined as an array
236 reference, all elements in the array are passed to subroutine after the
237 reference to the Net::SNMP object. The first element, which is required to be
238 a reference to a subroutine, is removed before the remaining arguments are
239 passed to that subroutine.
240  
241 Once one method is invoked with the B<-callback> argument, this argument stays
242 with the object and is used by any further calls to methods using the
243 B<-callback> option if the argument is absent. The undefined value may be
244 passed to the B<-callback> argument to delete the callback.
245  
246 B<NOTE:> The subroutine being passed with the B<-callback> named argument
247 should not cause blocking itself. This will cause all the actions in the event
248 loop to be stopped, defeating the non-blocking property of the Net::SNMP
249 module.
250  
251 =item Delay
252  
253 An optional argument B<-delay> can also be passed to non-blocking objects. The
254 B<-delay> argument instructs the object to wait the number of seconds passed
255 to the argument before executing the SNMP protocol exchange. The delay period
256 starts when the event loop is entered. The B<-delay> parameter is applied to
257 all methods associated with the object once it is specified. The delay value
258 must be set back to 0 seconds to disable the delay parameter.
259  
260 =back
261  
262 =item SNMPv3 Arguments
263  
264 A SNMP context is a collection of management information accessible by a SNMP
265 entity. An item of management information may exist in more than one context
266 and a SNMP entity potentially has access to many contexts. The combination of
267 a contextEngineID and a contextName unambiguously identifies a context within
268 an administrative domain. In a SNMPv3 message, the contextEngineID and
269 contextName are included as part of the scopedPDU. All methods that generate
270 a SNMP message optionally take a B<-contextengineid> and B<-contextname>
271 argument to configure these fields.
272  
273 =over
274  
275 =item Context Engine ID
276  
277 The B<-contextengineid> argument expects a hexadecimal string representing
278 the desired contextEngineID. The string must be 10 to 64 characters (5 to
279 32 octets) long and can be prefixed with an optional "0x". Once the
280 B<-contextengineid> is specified it stays with the object until it is changed
281 again or reset to default by passing in the undefined value. By default, the
282 contextEngineID is set to match the authoritativeEngineID of the authoritative
283 SNMP engine.
284  
285 =item Context Name
286  
287 The contextName is passed as a string which must be 0 to 32 octets in length
288 using the B<-contextname> argument. The contextName stays with the object
289 until it is changed. The contextName defaults to an empty string which
290 represents the "default" context.
291  
292 =back
293  
294 =back
295  
296 =cut
297  
298 {
299 my @trans_argv = qw(
300 hostname (?:de?st|peer)?(?:addr|port) (?:src|sock|local)(?:addr|port)
301 maxmsgsize mtu retries timeout domain listen
302 );
303  
304 sub new
305 {
306 my ($class, %argv) = @_;
307  
308 # Create a new data structure for the object
309 my $this = bless {
310 '_callback' => undef, # Callback
311 '_context_engine_id' => undef, # contextEngineID
312 '_context_name' => undef, # contextName
313 '_delay' => 0, # Message delay
314 '_hostname' => q{}, # Hostname
315 '_discovery_queue' => [], # Pending message queue
316 '_error' => undef, # Error message
317 '_nonblocking' => FALSE, # [Non-]blocking flag
318 '_pdu' => undef, # Message/PDU object
319 '_security' => undef, # Security Model object
320 '_translate' => TRANSLATE_ALL, # Translation mask
321 '_transport' => undef, # Transport Domain object
322 '_transport_argv' => [], # Transport object argv
323 '_version' => SNMP_VERSION_1, # SNMP version
324 }, $class;
325  
326 # Parse the passed arguments
327  
328 for (keys %argv) {
329  
330 if (/^-?debug$/i) {
331 $this->debug(delete $argv{$_});
332 } elsif (/^-?nonblocking$/i) {
333 $this->{_nonblocking} = (delete $argv{$_}) ? TRUE : FALSE;
334 } elsif (/^-?translate$/i) {
335 $this->translate(delete $argv{$_});
336 } elsif (/^-?version$/i) {
337 $this->_version($argv{$_});
338 } else {
339 # Pull out arguments associated with the Transport Domain.
340 my $key = $_;
341 for (@trans_argv) {
342 if ($key =~ /^-?$_$/i) {
343 push @{$this->{_transport_argv}}, $key, delete $argv{$key};
344 last;
345 }
346 }
347 }
348  
349 if (defined $this->{_error}) {
350 $this->_object_type_validate();
351 return wantarray ? (undef, $this->{_error}) : undef;
352 }
353  
354 }
355  
356 # We must validate the object type to prevent blocking and
357 # non-blocking object from existing at the same time.
358  
359 if (!defined $this->_object_type_validate()) {
360 return wantarray ? (undef, $this->{_error}) : undef;
361 }
362  
363 # Create a Security Model object
364  
365 ($this->{_security}, $this->{_error}) = Net::SNMP::Security->new(%argv);
366 if (!defined $this->{_security}) {
367 return wantarray ? (undef, $this->{_error}) : undef;
368 }
369 $this->_error_clear();
370  
371 # Return the object and empty error message (in list context)
372 return wantarray ? ($this, q{}) : $this;
373 }
374  
375 }
376  
377 sub open
378 {
379 my ($this) = @_;
380  
381 # Clear any previous errors
382 $this->_error_clear();
383  
384 # Create a Transport Domain object
385 ($this->{_transport}, $this->{_error}) = Net::SNMP::Transport->new(
386 @{$this->{_transport_argv}}
387 );
388  
389 if (!defined $this->{_transport}) {
390 return $this->_error();
391 }
392 $this->_error_clear();
393  
394 # Keep a copy of the hostname
395 $this->{_hostname} = $this->{_transport}->dest_hostname();
396  
397 # Perform SNMPv3 authoritative engine discovery.
398 if ($this->version() == SNMP_VERSION_3) {
399 $this->_perform_discovery();
400 }
401  
402 return defined($this->{_error}) ? $this->_error() : $this->{_transport};
403 }
404  
405 =head2 session() - create a new Net::SNMP object
406  
407 ($session, $error) = Net::SNMP->session(
408 [-hostname => $hostname,]
409 [-port => $port,]
410 [-localaddr => $localaddr,]
411 [-localport => $localport,]
412 [-nonblocking => $boolean,]
413 [-version => $version,]
414 [-domain => $domain,]
415 [-timeout => $seconds,]
416 [-retries => $count,]
417 [-maxmsgsize => $octets,]
418 [-translate => $translate,]
419 [-debug => $bitmask,]
420 [-community => $community,] # v1/v2c
421 [-username => $username,] # v3
422 [-authkey => $authkey,] # v3
423 [-authpassword => $authpasswd,] # v3
424 [-authprotocol => $authproto,] # v3
425 [-privkey => $privkey,] # v3
426 [-privpassword => $privpasswd,] # v3
427 [-privprotocol => $privproto,] # v3
428 );
429  
430 This is the constructor for Net::SNMP objects. In scalar context, a
431 reference to a new Net::SNMP object is returned if the creation of the object
432 is successful. In list context, a reference to a new Net::SNMP object and an
433 empty error message string is returned. If a failure occurs, the object
434 reference is returned as the undefined value. The error string may be used
435 to determine the cause of the error.
436  
437 Most of the named arguments passed to the constructor define basic attributes
438 for the object and are not modifiable after the object has been created. The
439 B<-timeout>, B<-retries>, B<-maxmsgsize>, B<-translate>, and B<-debug>
440 arguments are modifiable using an accessor method. See their corresponding
441 method definitions for a complete description of their usage, default values,
442 and valid ranges.
443  
444 =over
445  
446 =item Transport Domain Arguments
447  
448 The Net::SNMP module uses UDP/IPv4 as the default Transport Domain to exchange
449 SNMP messages between the local and remote devices. The module also supports
450 UDP/IPv6, TCP/IPv4, and TCP/IPv6 as alternative Transport Domains. The
451 B<-domain> argument can be used to change the Transport Domain by setting the
452 value to one of the following strings: 'udp6', 'udp/ipv6'; 'tcp', 'tcp4',
453 'tcp/ipv4'; 'tcp6', or 'tcp/ipv6'. The B<-domain> argument also accepts
454 the strings 'udp', 'udp4', or 'udp/ipv4' which correspond to the default
455 Transport Domain of UDP/IPv4.
456  
457 The transport address of the destination SNMP device can be specified using
458 the B<-hostname> argument. This argument is optional and defaults to
459 "localhost". The destination port number can be specified as part of the
460 transport address or by using the B<-port> argument. Either a numeric port
461 number or a textual service name can be specified. A numeric port number in
462 parentheses can optionally follow the service name. This port number will
463 be used if the service name cannot be resolved. If the destination port number
464 is not specified, the well-known SNMP port number 161 is used.
465  
466 By default the source transport address and port number are assigned
467 dynamically by the local device on which the Net::SNMP module is being used.
468 This dynamic assignment can be overridden by using the B<-localaddr> and
469 B<-localport> arguments. These arguments accept the same values as the
470 B<-hostname> and B<-port> arguments respectively. The resolved address must
471 correspond to a valid address of an interface on the local device.
472  
473 When using an IPv4 Transport Domain, the transport address can be specified
474 as either an IP network hostname or an IPv4 address in standard dotted notation.
475 The port information can be optionally appended to the hostname or address
476 delimited by a colon. The accepted IPv4 transport address formats are
477 C<address>, C<address:port>, C<hostname>, and C<hostname:port>.
478  
479 When using an IPv6 Transport Domain, the transport address can be specified
480 as an IP hostname (which will be looked up as a DNS quad-A record) or an IPv6
481 address in presentation format. The port information can optionally be
482 included following a colon after the hostname or address. When including this
483 information after an IPv6 address, the address must be enclosed in square
484 brackets. The scope zone index (described in RFC 4007) can be specified after
485 the address as a decimal value delimited by a percent sign. The accepted
486 transport address formats for IPv6 are C<address>, C<address%zone>,
487 C<[address]:port>, C<[address%zone]:port>, C<hostname>, and C<hostname:port>.
488  
489 =item Security Model Arguments
490  
491 The B<-version> argument controls which other arguments are expected or
492 required by the C<session()> constructor. The Net::SNMP module supports
493 SNMPv1, SNMPv2c, and SNMPv3. The module defaults to SNMPv1 if no B<-version>
494 argument is specified. The B<-version> argument expects either a digit (i.e.
495 '1', '2', or '3') or a string specifying the version (i.e. 'snmpv1',
496 'snmpv2c', or 'snmpv3') to define the SNMP version.
497  
498 The Security Model used by the Net::SNMP object is based on the SNMP version
499 associated with the object. If the SNMP version is SNMPv1 or SNMPv2c a
500 Community-based Security Model will be used, while the User-based Security
501 Model (USM) will be used if the version is SNMPv3.
502  
503 =over
504  
505 =item Community-based Security Model Argument
506  
507 If the Security Model is Community-based, the only argument available is the
508 B<-community> argument. This argument expects a string that is to be used as
509 the SNMP community name. By default the community name is set to 'public'
510 if the argument is not present.
511  
512 =item User-based Security Model Arguments
513  
514 The User-based Security Model (USM) used by SNMPv3 requires that a securityName
515 be specified using the B<-username> argument. The creation of a Net::SNMP
516 object with the version set to SNMPv3 will fail if the B<-username> argument
517 is not present. The B<-username> argument expects a string 1 to 32 octets
518 in length.
519  
520 Different levels of security are allowed by the User-based Security Model which
521 address authentication and privacy concerns. A SNMPv3 Net::SNMP object will
522 derive the security level (securityLevel) based on which of the following
523 arguments are specified.
524  
525 By default a securityLevel of 'noAuthNoPriv' is assumed. If the B<-authkey>
526 or B<-authpassword> arguments are specified, the securityLevel becomes
527 'authNoPriv'. The B<-authpassword> argument expects a string which is at
528 least 1 octet in length. Optionally, the B<-authkey> argument can be used so
529 that a plain text password does not have to be specified in a script. The
530 B<-authkey> argument expects a hexadecimal string produced by localizing the
531 password with the authoritativeEngineID for the specific destination device.
532 The C<snmpkey> utility included with the distribution can be used to create
533 the hexadecimal string (see L<snmpkey>).
534  
535 Two different hash algorithms are defined by SNMPv3 which can be used by the
536 Security Model for authentication. These algorithms are HMAC-MD5-96 "MD5"
537 (RFC 1321) and HMAC-SHA-96 "SHA-1" (NIST FIPS PUB 180-1). The default
538 algorithm used by the module is HMAC-MD5-96. This behavior can be changed by
539 using the B<-authprotocol> argument. This argument expects either the string
540 'md5' or 'sha' to be passed to modify the hash algorithm.
541  
542 By specifying the arguments B<-privkey> or B<-privpassword> the securityLevel
543 associated with the object becomes 'authPriv'. According to SNMPv3, privacy
544 requires the use of authentication. Therefore, if either of these two
545 arguments are present and the B<-authkey> or B<-authpassword> arguments are
546 missing, the creation of the object fails. The B<-privkey> and
547 B<-privpassword> arguments expect the same input as the B<-authkey> and
548 B<-authpassword> arguments respectively.
549  
550 The User-based Security Model described in RFC 3414 defines a single encryption
551 protocol to be used for privacy. This protocol, CBC-DES "DES" (NIST FIPS PUB
552 46-1), is used by default or if the string 'des' is passed to the
553 B<-privprotocol> argument. The module also supports RFC 3826 which describes
554 the use of CFB128-AES-128 "AES" (NIST FIPS PUB 197) in the USM. The AES
555 encryption protocol can be selected by passing 'aes' or 'aes128' to the
556 B<-privprotocol> argument. By working with the Extended Security Options
557 Consortium L<http://www.snmp.com/protocol/eso.shtml>, the module also supports
558 CBC-3DES-EDE "Triple-DES" (NIST FIPS 46-3) in the User-based Security Model.
559 This is defined in the draft
560 L<http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt>. The
561 Triple-DES encryption protocol can be selected using the B<-privprotocol>
562 argument with the string '3des' or '3desede'.
563  
564 =back
565  
566 =back
567  
568 =cut
569  
570 sub session
571 {
572 my $class = shift;
573  
574 my ($this, $error) = $class->new(@_);
575  
576 if (defined $this) {
577 if (!defined $this->open()) {
578 return wantarray ? (undef, $this->error()) : undef;
579 }
580 }
581  
582 return wantarray ? ($this, $error) : $this;
583 }
584  
585 sub manager
586 {
587 goto &session;
588 }
589  
590 =head2 close() - clear the Transport Domain associated with the object
591  
592 $session->close();
593  
594 This method clears the Transport Domain and any errors associated with the
595 object. Once closed, the Net::SNMP object can no longer be used to send or
596 receive SNMP messages.
597  
598 =cut
599  
600 sub close
601 {
602 my ($this) = @_;
603  
604 $this->_error_clear();
605 $this->{_pdu} = undef;
606 $this->{_transport} = undef;
607 return;
608 }
609  
610 =head2 snmp_dispatcher() - enter the non-blocking object event loop
611  
612 $session->snmp_dispatcher();
613  
614 This method enters the event loop associated with non-blocking Net::SNMP
615 objects. The method exits when all queued SNMP messages have received a
616 response or have timed out at the Transport Layer. This method is also
617 exported as the stand alone function C<snmp_dispatcher()> by default
618 (see L<"EXPORTS">).
619  
620 =cut
621  
622 sub snmp_dispatcher
623 {
624 return $DISPATCHER->loop();
625 }
626  
627 sub snmp_event_loop
628 {
629 require Carp;
630 Carp::croak('snmp_event_loop() is obsolete, use snmp_dispatcher() instead');
631 goto &snmp_dispatcher;
632 }
633  
634 sub snmp_dispatch_once
635 {
636 return $DISPATCHER->one_event();
637 }
638  
639 =head2 get_request() - send a SNMP get-request to the remote agent
640  
641 $result = $session->get_request(
642 [-callback => sub {},] # non-blocking
643 [-delay => $seconds,] # non-blocking
644 [-contextengineid => $engine_id,] # v3
645 [-contextname => $name,] # v3
646 -varbindlist => \@oids,
647 );
648  
649 This method performs a SNMP get-request query to gather data from the remote
650 agent on the host associated with the Net::SNMP object. The message is built
651 using the list of OBJECT IDENTIFIERs in dotted notation passed to the method
652 as an array reference using the B<-varbindlist> argument. Each OBJECT
653 IDENTIFIER is placed into a single SNMP GetRequest-PDU in the same order that
654 it held in the original list.
655  
656 A reference to a hash is returned in blocking mode which contains the contents
657 of the VarBindList. In non-blocking mode, a true value is returned when no
658 error has occurred. In either mode, the undefined value is returned when an
659 error has occurred. The C<error()> method may be used to determine the cause
660 of the failure.
661  
662 =cut
663  
664 sub get_request
665 {
666 my $this = shift;
667  
668 $this->_error_clear();
669  
670 my @argv;
671  
672 if (!defined $this->_prepare_argv([qw( -callback
673 -delay
674 -contextengineid
675 -contextname
676 -varbindlist )], \@_, \@argv))
677 {
678 return $this->_error();
679 }
680  
681 if (!defined $this->_create_pdu()) {
682 return $this->_error();
683 }
684  
685 if (!defined $this->{_pdu}->prepare_get_request(@argv)) {
686 return $this->_error($this->{_pdu}->error());
687 }
688  
689 return $this->_send_pdu();
690 }
691  
692 =head2 get_next_request() - send a SNMP get-next-request to the remote agent
693  
694 $result = $session->get_next_request(
695 [-callback => sub {},] # non-blocking
696 [-delay => $seconds,] # non-blocking
697 [-contextengineid => $engine_id,] # v3
698 [-contextname => $name,] # v3
699 -varbindlist => \@oids,
700 );
701  
702 This method performs a SNMP get-next-request query to gather data from the
703 remote agent on the host associated with the Net::SNMP object. The message
704 is built using the list of OBJECT IDENTIFIERs in dotted notation passed to the
705 method as an array reference using the B<-varbindlist> argument. Each OBJECT
706 IDENTIFER is placed into a single SNMP GetNextRequest-PDU in the same order
707 that it held in the original list.
708  
709 A reference to a hash is returned in blocking mode which contains the contents
710 of the VarBindList. In non-blocking mode, a true value is returned when no
711 error has occurred. In either mode, the undefined value is returned when an
712 error has occurred. The C<error()> method may be used to determine the cause
713 of the failure.
714  
715 =cut
716  
717 sub get_next_request
718 {
719 my $this = shift;
720  
721 $this->_error_clear();
722  
723 my @argv;
724  
725 if (!defined $this->_prepare_argv([qw( -callback
726 -delay
727 -contextengineid
728 -contextname
729 -varbindlist )], \@_, \@argv))
730 {
731 return $this->_error();
732 }
733  
734 if (!defined $this->_create_pdu()) {
735 return $this->_error();
736 }
737  
738 if (!defined $this->{_pdu}->prepare_get_next_request(@argv)) {
739 return $this->_error($this->{_pdu}->error());
740 }
741  
742 return $this->_send_pdu();
743 }
744  
745 =head2 set_request() - send a SNMP set-request to the remote agent
746  
747 $result = $session->set_request(
748 [-callback => sub {},] # non-blocking
749 [-delay => $seconds,] # non-blocking
750 [-contextengineid => $engine_id,] # v3
751 [-contextname => $name,] # v3
752 -varbindlist => \@oid_value,
753 );
754  
755 This method is used to modify data on the remote agent that is associated
756 with the Net::SNMP object using a SNMP set-request. The message is built
757 using a list of values consisting of groups of an OBJECT IDENTIFIER, an object
758 type, and the actual value to be set. This list is passed to the method as
759 an array reference using the B<-varbindlist> argument. The OBJECT IDENTIFIERs
760 in each trio are to be in dotted notation. The object type is an octet
761 corresponding to the ASN.1 type of value that is to be set. Each of the
762 supported ASN.1 types have been defined and are exported by the package by
763 default (see L<"EXPORTS">).
764  
765 A reference to a hash is returned in blocking mode which contains the contents
766 of the VarBindList. In non-blocking mode, a true value is returned when no
767 error has occurred. In either mode, the undefined value is returned when an
768 error has occurred. The C<error()> method may be used to determine the cause
769 of the failure.
770  
771 =cut
772  
773 sub set_request
774 {
775 my $this = shift;
776  
777 $this->_error_clear();
778  
779 my @argv;
780  
781 if (!defined $this->_prepare_argv([qw( -callback
782 -delay
783 -contextengineid
784 -contextname
785 -varbindlist )], \@_, \@argv))
786 {
787 return $this->_error();
788 }
789  
790 if (!defined $this->_create_pdu()) {
791 return $this->_error();
792 }
793  
794 if (!defined $this->{_pdu}->prepare_set_request(@argv)) {
795 return $this->_error($this->{_pdu}->error());
796 }
797  
798 return $this->_send_pdu();
799 }
800  
801 =head2 trap() - send a SNMP trap to the remote manager
802  
803 $result = $session->trap(
804 [-delay => $seconds,] # non-blocking
805 [-enterprise => $oid,]
806 [-agentaddr => $ipaddress,]
807 [-generictrap => $generic,]
808 [-specifictrap => $specific,]
809 [-timestamp => $timeticks,]
810 -varbindlist => \@oid_value,
811 );
812  
813 This method sends a SNMP trap to the remote manager associated with the
814 Net::SNMP object. All arguments are optional and will be given the following
815 defaults in the absence of a corresponding named argument:
816  
817 =over
818  
819 =item *
820  
821 The default value for the trap B<-enterprise> is "1.3.6.1.4.1", which
822 corresponds to "iso.org.dod.internet.private.enterprises". The enterprise
823 value is expected to be an OBJECT IDENTIFER in dotted notation.
824  
825 =item *
826  
827 When the Transport Domain is UDP/IPv4 or TCP/IPv4, the default value for the
828 trap B<-agentaddr> is the IP address associated with the interface on which
829 the trap will be transmitted. For other Transport Domains the B<-agentaddr>
830 is defaulted to "0.0.0.0". When specified, the agent-addr is expected to be
831 an IpAddress in dotted notation.
832  
833 =item *
834  
835 The default value for the B<-generictrap> type is 6 which corresponds to
836 "enterpriseSpecific". The generic-trap types are defined and can be exported
837 upon request (see L<"EXPORTS">).
838  
839 =item *
840  
841 The default value for the B<-specifictrap> type is 0. No pre-defined values
842 are available for specific-trap types.
843  
844 =item *
845  
846 The default value for the trap B<-timestamp> is the "uptime" of the script.
847 The "uptime" of the script is the number of hundredths of seconds that have
848 elapsed since the script began running. The time-stamp is expected to be a
849 TimeTicks number in hundredths of seconds.
850  
851 =item *
852  
853 The default value for the trap B<-varbindlist> is an empty array reference.
854 The variable-bindings are expected to be in an array format consisting of
855 groups of an OBJECT IDENTIFIER, an object type, and the actual value of the
856 object. This is identical to the list expected by the C<set_request()> method.
857 The OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object
858 type is an octet corresponding to the ASN.1 type for the value. Each of the
859 supported types have been defined and are exported by default (see
860 L<"EXPORTS">).
861  
862 =back
863  
864 A true value is returned when the method is successful. The undefined value
865 is returned when a failure has occurred. The C<error()> method can be used to
866 determine the cause of the failure. Since there are no acknowledgements for
867 Trap-PDUs, there is no way to determine if the remote host actually received
868 the trap.
869  
870 B<NOTE:> When the object is in non-blocking mode, the trap is not sent until
871 the event loop is entered and no callback is ever executed.
872  
873 B<NOTE:> This method can only be used when the version of the object is set to
874 SNMPv1.
875  
876 =cut
877  
878 sub trap
879 {
880 my $this = shift;
881  
882 $this->_error_clear();
883  
884 my @argv;
885  
886 if (!defined $this->_prepare_argv([qw( -delay
887 -enterprise
888 -agentaddr
889 -generictrap
890 -specifictrap
891 -timestamp
892 -varbindlist )], \@_, \@argv))
893 {
894 return $this->_error();
895 }
896  
897 if (!defined $this->_create_pdu()) {
898 return $this->_error();
899 }
900  
901 if (!defined $this->{_pdu}->prepare_trap(@argv)) {
902 return $this->_error($this->{_pdu}->error());
903 }
904  
905 $this->_send_pdu();
906  
907 return defined($this->{_error}) ? $this->_error() : TRUE;
908 }
909  
910 =head2 get_bulk_request() - send a SNMP get-bulk-request to the remote agent
911  
912 $result = $session->get_bulk_request(
913 [-callback => sub {},] # non-blocking
914 [-delay => $seconds,] # non-blocking
915 [-contextengineid => $engine_id,] # v3
916 [-contextname => $name,] # v3
917 [-nonrepeaters => $non_reps,]
918 [-maxrepetitions => $max_reps,]
919 -varbindlist => \@oids,
920 );
921  
922 This method performs a SNMP get-bulk-request query to gather data from the
923 remote agent on the host associated with the Net::SNMP object. All arguments
924 are optional except B<-varbindlist> and will be given the following defaults
925 in the absence of a corresponding named argument:
926  
927 =over
928  
929 =item *
930  
931 The default value for the get-bulk-request B<-nonrepeaters> is 0. The
932 non-repeaters value specifies the number of variables in the
933 variable-bindings list for which a single successor is to be returned.
934  
935 =item *
936  
937 The default value for the get-bulk-request B<-maxrepetitions> is 0. The
938 max-repetitions value specifies the number of successors to be returned for
939 the remaining variables in the variable-bindings list.
940  
941 =item *
942  
943 The B<-varbindlist> argument expects an array reference consisting of a list of
944 OBJECT IDENTIFIERs in dotted notation. Each OBJECT IDENTIFER is placed into a
945 single SNMP GetBulkRequest-PDU in the same order that it held in the original
946 list.
947  
948 =back
949  
950 A reference to a hash is returned in blocking mode which contains the contents
951 of the VarBindList. In non-blocking mode, a true value is returned when no
952 error has occurred. In either mode, the undefined value is returned when an
953 error has occurred. The C<error()> method may be used to determine the cause
954 of the failure.
955  
956 B<NOTE:> This method can only be used when the version of the object is set to
957 SNMPv2c or SNMPv3.
958  
959 =cut
960  
961 sub get_bulk_request
962 {
963 my $this = shift;
964  
965 $this->_error_clear();
966  
967 my @argv;
968  
969 if (!defined $this->_prepare_argv([qw( -callback
970 -delay
971 -contextengineid
972 -contextname
973 -nonrepeaters
974 -maxrepetitions
975 -varbindlist )], \@_, \@argv))
976 {
977 return $this->_error();
978 }
979  
980 if (!defined $this->_create_pdu()) {
981 return $this->_error();
982 }
983  
984 if (!defined $this->{_pdu}->prepare_get_bulk_request(@argv)) {
985 return $this->_error($this->{_pdu}->error());
986 }
987  
988 return $this->_send_pdu();
989 }
990  
991 =head2 inform_request() - send a SNMP inform-request to the remote manager
992  
993 $result = $session->inform_request(
994 [-callback => sub {},] # non-blocking
995 [-delay => $seconds,] # non-blocking
996 [-contextengineid => $engine_id,] # v3
997 [-contextname => $name,] # v3
998 -varbindlist => \@oid_value,
999 );
1000  
1001 This method is used to provide management information to the remote manager
1002 associated with the Net::SNMP object using an inform-request. The message is
1003 built using a list of values consisting of groups of an OBJECT IDENTIFIER,
1004 an object type, and the actual value to be identified. This list is passed
1005 to the method as an array reference using the B<-varbindlist> argument. The
1006 OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object type
1007 is an octet corresponding to the ASN.1 type of value that is to be identified.
1008 Each of the supported ASN.1 types have been defined and are exported by the
1009 package by default (see L<"EXPORTS">).
1010  
1011 The first two variable-bindings fields in the inform-request are specified
1012 by SNMPv2 and should be:
1013  
1014 =over
1015  
1016 =item *
1017  
1018 sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
1019  
1020 =item *
1021  
1022 snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
1023  
1024 =back
1025  
1026 A reference to a hash is returned in blocking mode which contains the contents
1027 of the VarBindList. In non-blocking mode, a true value is returned when no
1028 error has occurred. In either mode, the undefined value is returned when an
1029 error has occurred. The C<error()> method may be used to determine the cause
1030 of the failure.
1031  
1032 B<NOTE:> This method can only be used when the version of the object is set to
1033 SNMPv2c or SNMPv3.
1034  
1035 =cut
1036  
1037 sub inform_request
1038 {
1039 my $this = shift;
1040  
1041 $this->_error_clear();
1042  
1043 my @argv;
1044  
1045 if (!defined $this->_prepare_argv([qw( -callback
1046 -delay
1047 -contextengineid
1048 -contextname
1049 -varbindlist )], \@_, \@argv))
1050 {
1051 return $this->_error();
1052 }
1053  
1054 if (!defined $this->_create_pdu()) {
1055 return $this->_error();
1056 }
1057  
1058 if (!defined $this->{_pdu}->prepare_inform_request(@argv)) {
1059 return $this->_error($this->{_pdu}->error());
1060 }
1061  
1062 return $this->_send_pdu();
1063 }
1064  
1065 =head2 snmpv2_trap() - send a SNMP snmpV2-trap to the remote manager
1066  
1067 $result = $session->snmpv2_trap(
1068 [-delay => $seconds,] # non-blocking
1069 -varbindlist => \@oid_value,
1070 );
1071  
1072 This method sends a snmpV2-trap to the remote manager associated with the
1073 Net::SNMP object. The message is built using a list of values consisting of
1074 groups of an OBJECT IDENTIFIER, an object type, and the actual value to be
1075 identified. This list is passed to the method as an array reference using the
1076 B<-varbindlist> argument. The OBJECT IDENTIFIERs in each trio are to be in
1077 dotted notation. The object type is an octet corresponding to the ASN.1 type
1078 of value that is to be identified. Each of the supported ASN.1 types have
1079 been defined and are exported by the package by default (see L<"EXPORTS">).
1080  
1081 The first two variable-bindings fields in the snmpV2-trap are specified by
1082 SNMPv2 and should be:
1083  
1084 =over
1085  
1086 =item *
1087  
1088 sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
1089  
1090 =item *
1091  
1092 snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
1093  
1094 =back
1095  
1096 A true value is returned when the method is successful. The undefined value
1097 is returned when a failure has occurred. The C<error()> method can be used
1098 to determine the cause of the failure. Since there are no acknowledgements for
1099 SNMPv2-Trap-PDUs, there is no way to determine if the remote host actually
1100 received the snmpV2-trap.
1101  
1102 B<NOTE:> When the object is in non-blocking mode, the snmpV2-trap is not sent
1103 until the event loop is entered and no callback is ever executed.
1104  
1105 B<NOTE:> This method can only be used when the version of the object is set to
1106 SNMPv2c. SNMPv2-Trap-PDUs are supported by SNMPv3, but require the sender of
1107 the message to be an authoritative SNMP engine which is not currently supported
1108 by the Net::SNMP module.
1109  
1110 =cut
1111  
1112 sub snmpv2_trap
1113 {
1114 my $this = shift;
1115  
1116 $this->_error_clear();
1117  
1118 my @argv;
1119  
1120 if (!defined $this->_prepare_argv([qw( -delay
1121 -contextengineid
1122 -contextname
1123 -varbindlist )], \@_, \@argv))
1124 {
1125 return $this->_error();
1126 }
1127  
1128 if (!defined $this->_create_pdu()) {
1129 return $this->_error();
1130 }
1131  
1132 if (!defined $this->{_pdu}->prepare_snmpv2_trap(@argv)) {
1133 return $this->_error($this->{_pdu}->error());
1134 }
1135  
1136 $this->_send_pdu();
1137  
1138 return defined($this->{_error}) ? $this->_error() : TRUE;
1139 }
1140  
1141 =head2 get_table() - retrieve a table from the remote agent
1142  
1143 $result = $session->get_table(
1144 [-callback => sub {},] # non-blocking
1145 [-delay => $seconds,] # non-blocking
1146 [-contextengineid => $engine_id,] # v3
1147 [-contextname => $name,] # v3
1148 -baseoid => $oid,
1149 [-maxrepetitions => $max_reps,] # v2c/v3
1150 );
1151  
1152 This method performs repeated SNMP get-next-request or get-bulk-request
1153 (when using SNMPv2c or SNMPv3) queries to gather data from the remote agent
1154 on the host associated with the Net::SNMP object. The first message sent
1155 is built using the OBJECT IDENTIFIER in dotted notation passed to the method
1156 by the B<-baseoid> argument. Repeated SNMP requests are issued until the
1157 OBJECT IDENTIFIER in the response is no longer a child of the base OBJECT
1158 IDENTIFIER.
1159  
1160 The B<-maxrepetitions> argument can be used to specify the max-repetitions
1161 value that is passed to the get-bulk-requests when using SNMPv2c or SNMPv3.
1162 If this argument is not present, a value is calculated based on the maximum
1163 message size for the Net::SNMP object. If the value is set to 1 or less,
1164 get-next-requests will be used for the queries instead of get-bulk-requests.
1165  
1166 A reference to a hash is returned in blocking mode which contains the contents
1167 of the VarBindList. In non-blocking mode, a true value is returned when no
1168 error has occurred. In either mode, the undefined value is returned when an
1169 error has occurred. The C<error()> method may be used to determine the cause
1170 of the failure.
1171  
1172 B<WARNING:> Results from this method can become very large if the base
1173 OBJECT IDENTIFIER is close to the root of the SNMP MIB tree.
1174  
1175 =cut
1176  
1177 sub get_table
1178 {
1179 my $this = shift;
1180  
1181 $this->_error_clear();
1182  
1183 my @argv;
1184  
1185 # Validate the passed arguments. For backwards compatiblity
1186 # see if the first argument is an OBJECT IDENTIFIER and then
1187 # act accordingly.
1188  
1189 if ((@_) && ($_[0] =~ m/^\.?\d+(?:\.\d+)* *$/)) {
1190 unshift @_, '-baseoid'; # XXX: Side effects?
1191 }
1192  
1193 if (!defined $this->_prepare_argv([qw( -callback
1194 -delay
1195 -contextengineid
1196 -contextname
1197 -baseoid
1198 -maxrepetitions )], \@_, \@argv))
1199 {
1200 return $this->_error();
1201 }
1202  
1203 if ($argv[0] !~ m/^\.?\d+(?:\.\d+)* *$/) {
1204 return $this->_error(
1205 'The base OBJECT IDENTIFIER "%s" is expected in dotted decimal ' .
1206 'notation', $argv[0]
1207 );
1208 }
1209  
1210 # Create a new PDU.
1211 if (!defined $this->_create_pdu()) {
1212 return $this->_error();
1213 }
1214  
1215 # Create table of values that need passed along with the
1216 # callbacks. This just prevents a big argument list.
1217  
1218 my $argv = {
1219 base_oid => $argv[0],
1220 callback => $this->{_pdu}->callback(),
1221 max_reps => 5, # Also used as a limit for loop detection.
1222 repeat_cnt => 0,
1223 table => undef,
1224 types => undef,
1225 use_bulk => FALSE
1226 };
1227  
1228 # Override the callback now that we have stored it.
1229 $this->{_pdu}->callback(
1230 sub
1231 {
1232 $this->{_pdu} = $_[0];
1233 $this->_error_clear();
1234 if ($this->{_pdu}->error()) {
1235 $this->_error($this->{_pdu}->error());
1236 }
1237 $this->_get_table_cb($argv);
1238 return;
1239 }
1240 );
1241  
1242 # Determine if we are going to use get-next-requests or get-bulk-requests
1243 # based on the SNMP version and the -maxrepetitions argument.
1244  
1245 if ($this->version() == SNMP_VERSION_1) {
1246 if (defined $argv[1]) {
1247 return $this->_error(
1248 'The max-repetitions argument is not applicable when using SNMPv1'
1249 );
1250 }
1251 } else {
1252 if (!defined $argv[1]) {
1253 $argv->{use_bulk} = TRUE;
1254 $argv->{max_reps} = $this->_msg_size_max_reps();
1255 } elsif ($argv[1] > 1) {
1256 $argv->{use_bulk} = TRUE;
1257 $argv->{max_reps} = $argv[1];
1258 }
1259 }
1260  
1261 # Create either a get-next-request or get-bulk-request PDU.
1262  
1263 if ($argv->{use_bulk}) {
1264 if (!defined $this->{_pdu}->prepare_get_bulk_request(0,
1265 $argv->{max_reps},
1266 [$argv[0]]))
1267 {
1268 return $this->_error($this->{_pdu}->error());
1269 }
1270 } else {
1271 if (!defined $this->{_pdu}->prepare_get_next_request([$argv[0]])) {
1272 return $this->_error($this->{_pdu}->error());
1273 }
1274 }
1275  
1276 return $this->_send_pdu();
1277 }
1278  
1279 =head2 get_entries() - retrieve table entries from the remote agent
1280  
1281 $result = $session->get_entries(
1282 [-callback => sub {},] # non-blocking
1283 [-delay => $seconds,] # non-blocking
1284 [-contextengineid => $engine_id,] # v3
1285 [-contextname => $name,] # v3
1286 -columns => \@columns,
1287 [-startindex => $start,]
1288 [-endindex => $end,]
1289 [-maxrepetitions => $max_reps,] # v2c/v3
1290 );
1291  
1292 This method performs repeated SNMP get-next-request or get-bulk-request
1293 (when using SNMPv2c or SNMPv3) queries to gather data from the remote agent
1294 on the host associated with the Net::SNMP object. Each message specifically
1295 requests data for each OBJECT IDENTIFIER specified in the B<-columns> array.
1296 The OBJECT IDENTIFIERs must correspond to column entries for a conceptual row
1297 in a table. They may however be columns in different tables as long as each
1298 table is indexed the same way. The optional B<-startindex> and B<-endindex>
1299 arguments may be specified to limit the query to specific rows in the table(s).
1300  
1301 The B<-startindex> can be specified as a single decimal value or in dotted
1302 notation if the index associated with the entry so requires. If the
1303 B<-startindex> is specified, it will be include as part of the query results.
1304 If no B<-startindex> is specified, the first request message will be sent
1305 without an index. To insure that the B<-startindex> is included, the last
1306 sub-identifier in the index is decremented by one. If the last sub-identifier
1307 has a value of zero, the sub-identifier is removed from the index.
1308  
1309 The optional B<-endindex> argument can be specified as a single decimal value
1310 or in dotted notation. If the B<-endindex> is specified, it will be included
1311 as part of the query results. If no B<-endindex> is specified, repeated SNMP
1312 requests are issued until the response no longer returns entries matching
1313 any of the columns specified in the B<-columns> array.
1314  
1315 The B<-maxrepetitions> argument can be used to specify the max-repetitions
1316 value that is passed to the get-bulk-requests when using SNMPv2c or SNMPv3.
1317 If this argument is not present, a value is calculated based on the maximum
1318 message size of the object and the number of columns specified in the
1319 B<-columns> array. If the value is set to 1 or less, get-next-requests will
1320 be used for the queries instead of get-bulk-requests.
1321  
1322 A reference to a hash is returned in blocking mode which contains the contents
1323 of the VarBindList. In non-blocking mode, a true value is returned when no
1324 error has occurred. In either mode, the undefined value is returned when an
1325 error has occurred. The C<error()> method may be used to determine the cause
1326 of the failure.
1327  
1328 =cut
1329  
1330 sub get_entries
1331 {
1332 my $this = shift;
1333  
1334 $this->_error_clear();
1335  
1336 my @argv;
1337  
1338 # Validate the passed arguments.
1339  
1340 if (!defined $this->_prepare_argv([qw( -callback
1341 -delay
1342 -contextengineid
1343 -contextname
1344 -entryoid
1345 -columns
1346 -startindex
1347 -endindex
1348 -maxrepetitions
1349 -rowcallback )], \@_, \@argv))
1350 {
1351 return $this->_error();
1352 }
1353  
1354 if (ref $argv[1] ne 'ARRAY') {
1355 return $this->_error('The columns argument expects an array reference');
1356 }
1357  
1358 if (!scalar @{$argv[1]}) {
1359 return $this->_error('An empty columns list was specified');
1360 }
1361  
1362 # The syntax of get_entries() changes between release 4.1.0 and
1363 # release 4.1.1. For backwards compatibility, we assume the old
1364 # syntax is being used if the "-entryoid" argument is present
1365 # and we silently convert to the new syntax.
1366  
1367 if (defined $argv[0]) {
1368  
1369 # XXX: Argument deprecated after v5.2.0, obsolete in 6.0.1.
1370  
1371 require Carp;
1372 Carp::croak(
1373 'The entryoid argument is obsolete, use the columns argument ' .
1374 'with a list of column OBJECT IDENTIFIERs'
1375 );
1376  
1377 if ($argv[0] !~ m/^\.?\d+(?:\.\d+)* *$/) {
1378 return $this->_error(
1379 'The entryoid value "%s" is expected in dotted decimal notation',
1380 $argv[0]
1381 );
1382 }
1383  
1384 my $columns = {};
1385  
1386 for (@{$argv[1]}) {
1387 if (!m/^\d+$/) {
1388 return $this->_error(
1389 'The columns list value "%s" is expected in positive numeric ' .
1390 'format', $_
1391 );
1392 }
1393 if (exists $columns->{$_}) {
1394 return $this->_error(
1395 'The columns list value "%s" is duplicated in the columns list',
1396 $_
1397 );
1398 } else {
1399 $columns->{$_} = $_;
1400 }
1401 }
1402  
1403 # Now create the new syntax for the columns list.
1404  
1405 $argv[1] = [];
1406  
1407 for (sort { $a <=> $b } (keys %{$columns})) {
1408 push @{$argv[1]}, join q{.}, $argv[0], $_;
1409 }
1410  
1411 }
1412  
1413 # Validate the column list.
1414  
1415 for (@{$argv[1]}) {
1416 if (!m/^\.?\d+(?:\.\d+)* *$/) {
1417 return $this->_error(
1418 'The columns list OBJECT IDENTIFIER "%s" is expected in dotted ' .
1419 'decimal notation', $_
1420 );
1421 }
1422 }
1423  
1424 my $start_index = undef;
1425  
1426 if (defined $argv[2]) {
1427 if ($argv[2] !~ m/^\d+(?:\.\d+)*$/) {
1428 return $this->_error(
1429 'The start index "%s" is expected in dotted decimal notation',
1430 $argv[2]
1431 );
1432 }
1433 my @subids = split m/\./, $argv[2];
1434 if ($subids[-1] > 0) {
1435 $subids[-1]--;
1436 } else {
1437 pop @subids;
1438 }
1439 $start_index = (@subids) ? join(q{.}, @subids) : q{};
1440 }
1441  
1442 if (defined $argv[3]) {
1443 if ($argv[3] !~ /^\d+(?:\.\d+)*$/) {
1444 return $this->_error(
1445 'The end index "%s" is expected in dotted decimal notation',
1446 $argv[3]
1447 );
1448 }
1449 if (defined $argv[2]) {
1450 if (oid_lex_cmp($argv[2], $argv[3]) > 0) {
1451 return $this->_error(
1452 'The end index cannot be less than the start index'
1453 );
1454 }
1455 }
1456 }
1457  
1458 # Undocumented and unsupported "-rowcallback" argument.
1459  
1460 if (defined $argv[5]) {
1461 if (ref $argv[5] eq 'CODE') {
1462 $argv[5] = [$argv[5]];
1463 } elsif ((ref($argv[5]) ne 'ARRAY') || (ref($argv[5]->[0]) ne 'CODE')) {
1464 return $this->_error('The syntax of the row callback is invalid');
1465 }
1466 }
1467  
1468 # Create a new PDU.
1469 if (!defined $this->_create_pdu()) {
1470 return $this->_error();
1471 }
1472  
1473 # Create table of values that need passed along with the
1474 # callbacks. This just prevents a big argument list.
1475  
1476 my $argv = {
1477 callback => $this->{_pdu}->callback(),
1478 columns => $argv[1],
1479 end_index => $argv[3],
1480 entries => undef,
1481 last_index => undef,
1482 max_reps => 0,
1483 row_callback => $argv[5],
1484 start_index => $argv[2],
1485 types => undef,
1486 use_bulk => FALSE
1487 };
1488  
1489 # Override the callback now that we have stored it.
1490 $this->{_pdu}->callback(
1491 sub
1492 {
1493 $this->{_pdu} = $_[0];
1494 $this->_error_clear();
1495 if ($this->{_pdu}->error()) {
1496 $this->_error($this->{_pdu}->error());
1497 }
1498 $this->_get_entries_cb($argv);
1499 return;
1500 }
1501 );
1502  
1503 # Create the varBindList by indexing each column with the start index.
1504 my $vbl =
1505 [
1506 map {
1507 (defined $start_index) ? join q{.}, $_, $start_index : $_
1508 } @{$argv->{columns}}
1509 ];
1510  
1511 # Determine if we are going to use get-next-requests or get-bulk-requests
1512 # based on the SNMP version and the -maxrepetitions argument.
1513  
1514 if ($this->version() == SNMP_VERSION_1) {
1515 if (defined $argv[4]) {
1516 return $this->_error(
1517 'The max-repetitions argument is not applicable when using SNMPv1'
1518 );
1519 }
1520 } else {
1521 if (!defined $argv[4]) {
1522 $argv->{use_bulk} = TRUE;
1523 # Scale the max-repetitions based on the number of columns.
1524 $argv->{max_reps} =
1525 int($this->_msg_size_max_reps() / @{$argv->{columns}}) + 1;
1526 } elsif ($argv[4] > 1) {
1527 $argv->{use_bulk} = TRUE;
1528 $argv->{max_reps} = $argv[4];
1529 }
1530 }
1531  
1532 # Create either a get-next-request or get-bulk-request PDU.
1533  
1534 if ($argv->{use_bulk}) {
1535 if (!defined $this->{_pdu}->prepare_get_bulk_request(0,
1536 $argv->{max_reps},
1537 $vbl))
1538 {
1539 return $this->_error($this->{_pdu}->error());
1540 }
1541 } else {
1542 if (!defined $this->{_pdu}->prepare_get_next_request($vbl)) {
1543 return $this->_error($this->{_pdu}->error());
1544 }
1545 }
1546  
1547 return $this->_send_pdu();
1548 }
1549  
1550 =head2 version() - get the SNMP version from the object
1551  
1552 $rfc_version = $session->version();
1553  
1554 This method returns the current value for the SNMP version associated with
1555 the object. The returned value is the corresponding version number defined by
1556 the RFCs for the protocol version field (i.e. SNMPv1 == 0, SNMPv2c == 1, and
1557 SNMPv3 == 3). The RFC versions are defined as constant by the module and can
1558 be exported by request (see L<"EXPORTS">).
1559  
1560 =cut
1561  
1562 sub version
1563 {
1564 my ($this) = @_;
1565  
1566 return $this->_error('The SNMP version is not modifiable') if (@_ == 2);
1567  
1568 return $this->{_version};
1569 }
1570  
1571 =head2 error() - get the current error message from the object
1572  
1573 $error_message = $session->error();
1574  
1575 This method returns a text string explaining the reason for the last error.
1576 An empty string is returned if no error has occurred.
1577  
1578 =cut
1579  
1580 sub error
1581 {
1582 return $_[0]->{_error} || q{};
1583 }
1584  
1585 =head2 hostname() - get the hostname associated with the object
1586  
1587 $hostname = $session->hostname();
1588  
1589 This method returns the parsed hostname string that is associated with the
1590 object. Any port information and formatting that can be included with the
1591 corresponding C<session()> constructor argument will be stripped and not
1592 included as part of the returned string.
1593  
1594 =cut
1595  
1596 sub hostname
1597 {
1598 return $_[0]->{_hostname};
1599 }
1600  
1601 =head2 error_status() - get the current SNMP error-status from the object
1602  
1603 $error_status = $session->error_status();
1604  
1605 This method returns the numeric value of the error-status contained in the
1606 last SNMP message received by the object.
1607  
1608 =cut
1609  
1610 sub error_status
1611 {
1612 return defined($_[0]->{_pdu}) ? $_[0]->{_pdu}->error_status() : 0;
1613 }
1614  
1615 =head2 error_index() - get the current SNMP error-index from the object
1616  
1617 $error_index = $session->error_index();
1618  
1619 This method returns the numeric value of the error-index contained in the
1620 last SNMP message received by the object.
1621  
1622 =cut
1623  
1624 sub error_index
1625 {
1626 return defined($_[0]->{_pdu}) ? $_[0]->{_pdu}->error_index() : 0;
1627 }
1628  
1629 =head2 var_bind_list() - get the hash reference for the VarBindList values
1630  
1631 $values = $session->var_bind_list();
1632  
1633 This method returns a hash reference created using the ObjectName and the
1634 ObjectSyntax pairs in the VarBindList of the last SNMP message received by
1635 the object. The keys of the hash consist of the OBJECT IDENTIFIERs in dotted
1636 notation corresponding to each ObjectName in the VarBindList. If any of the
1637 OBJECT IDENTIFIERs passed to the request method began with a leading dot, all
1638 of the OBJECT IDENTIFIER hash keys will be prefixed with a leading dot. If
1639 duplicate OBJECT IDENTIFIERs are present in the VarBindList they will be
1640 padded with spaces to make them an unique hash key. The value of each hash
1641 entry is set equal to the value of the corresponding ObjectSyntax. The
1642 undefined value is returned if there has been a failure.
1643  
1644 =cut
1645  
1646 sub var_bind_list
1647 {
1648 return defined($_[0]->{_pdu}) ? $_[0]->{_pdu}->var_bind_list() : undef;
1649 }
1650  
1651 =head2 var_bind_names() - get the array of the ObjectNames in the VarBindList
1652  
1653 @names = $session->var_bind_names();
1654  
1655 This method returns an array containing the OBJECT IDENTIFIERs corresponding
1656 to the ObjectNames in the VarBindList in the order that they were received
1657 in the last SNMP message. The entries in the array will map directly to the
1658 keys in the hash reference returned by the methods that perform SNMP message
1659 exchanges and by the C<var_bind_list()> and C<var_bind_types()> methods. The
1660 array returned for the convenience methods C<get_table()> and C<get_entries()>
1661 will be in lexicographical order. An empty array is returned if there has been
1662 a failure.
1663  
1664 =cut
1665  
1666 sub var_bind_names
1667 {
1668 return defined($_[0]->{_pdu}) ? @{$_[0]->{_pdu}->var_bind_names()} : ();
1669 }
1670  
1671 =head2 var_bind_types() - get the hash reference for the VarBindList ASN.1 types
1672  
1673 $types = $session->var_bind_types();
1674  
1675 This method returns a hash reference created using the ObjectName and the ASN.1
1676 type of the ObjectSyntax in the VarBindList of the last SNMP message received
1677 by the object. The keys of the hash consist of the OBJECT IDENTIFIERs in
1678 dotted notation corresponding to each ObjectName in the VarBindList. The
1679 value of each hash entry is set equal to the ASN.1 type of the corresponding
1680 ObjectSyntax. Constants for the supported ASN.1 types have been defined and
1681 are exported by the package by default (see L<"EXPORTS">). The undefined value
1682 is returned if there has been a failure.
1683  
1684 =cut
1685  
1686 sub var_bind_types
1687 {
1688 return defined($_[0]->{_pdu}) ? $_[0]->{_pdu}->var_bind_types() : undef;
1689 }
1690  
1691 =head2 timeout() - set or get the current timeout period for the object
1692  
1693 $seconds = $session->timeout([$seconds]);
1694  
1695 This method returns the current value for the Transport Layer timeout for
1696 the Net::SNMP object. This value is the number of seconds that the object
1697 will wait for a response from the agent on the remote host. The default
1698 timeout is 5.0 seconds.
1699  
1700 If a parameter is specified, the timeout for the object is set to the provided
1701 value if it falls within the range 1.0 to 60.0 seconds. The undefined value
1702 is returned upon an error and the C<error()> method may be used to determine
1703 the cause.
1704  
1705 =cut
1706  
1707 sub timeout
1708 {
1709 my $this = shift;
1710  
1711 if (!defined $this->{_transport}) {
1712 return $this->_error('The session is closed');
1713 }
1714  
1715 if (defined (my $timeout = $this->{_transport}->timeout(@_))) {
1716 return $timeout;
1717 }
1718  
1719 return $this->_error($this->{_transport}->error());
1720 }
1721  
1722 =head2 retries() - set or get the current retry count for the object
1723  
1724 $count = $session->retries([$count]);
1725  
1726 This method returns the current value for the number of times to retry
1727 sending a SNMP message to the remote host. The default number of retries
1728 is 1.
1729  
1730 If a parameter is specified, the number of retries for the object is set to
1731 the provided value if it falls within the range 0 to 20. The undefined value
1732 is returned upon an error and the C<error()> method may be used to determine
1733 the cause.
1734  
1735 =cut
1736  
1737 sub retries
1738 {
1739 my $this = shift;
1740  
1741 if (!defined $this->{_transport}) {
1742 return $this->_error('The session is closed');
1743 }
1744  
1745 if (defined (my $retries = $this->{_transport}->retries(@_))) {
1746 return $retries;
1747 }
1748  
1749 return $this->_error($this->{_transport}->error());
1750 }
1751  
1752 =head2 max_msg_size() - set or get the current maxMsgSize for the object
1753  
1754 $octets = $session->max_msg_size([$octets]);
1755  
1756 This method returns the current value for the maximum message size
1757 (maxMsgSize) for the Net::SNMP object. This value is the largest message size
1758 in octets that can be prepared or processed by the object. The default
1759 maxMsgSize is 1472 octets for UDP/IPv4, 1452 octets for UDP/IPv6, 1460 octets
1760 for TCP/IPv4, and 1440 octets for TCP/IPv6.
1761  
1762 If a parameter is specified, the maxMsgSize is set to the provided
1763 value if it falls within the range 484 to 65535 octets. The undefined
1764 value is returned upon an error and the C<error()> method may be used to
1765 determine the cause.
1766  
1767 B<NOTE:> When using SNMPv3, the maxMsgSize is actually contained in the SNMP
1768 message (as msgMaxSize). If the value received from a remote device is less
1769 than the current maxMsgSize, the size is automatically adjusted to be the
1770 lower value.
1771  
1772 =cut
1773  
1774 sub max_msg_size
1775 {
1776 my $this = shift;
1777  
1778 if (!defined $this->{_transport}) {
1779 return $this->_error('The session is closed');
1780 }
1781  
1782 if (defined (my $max_size = $this->{_transport}->max_msg_size(@_))) {
1783 return $max_size;
1784 }
1785  
1786 return $this->_error($this->{_transport}->error());
1787 }
1788  
1789 sub mtu
1790 {
1791 goto &max_msg_size;
1792 }
1793  
1794 =head2 translate() - enable or disable the translation mode for the object
1795  
1796 $mask = $session->translate([
1797 $mode |
1798 [ # Perl anonymous ARRAY reference
1799 ['-all' => $mode0,]
1800 ['-octetstring' => $mode1,]
1801 ['-null' => $mode2,]
1802 ['-timeticks' => $mode3,]
1803 ['-opaque' => $mode4,]
1804 ['-nosuchobject' => $mode5,]
1805 ['-nosuchinstance' => $mode6,]
1806 ['-endofmibview' => $mode7,]
1807 ['-unsigned' => $mode8]
1808 ]
1809 ]);
1810  
1811 When the object decodes the GetResponse-PDU that is returned in response to
1812 a SNMP message, certain values are translated into a more "human readable"
1813 form. By default the following translations occur:
1814  
1815 =over
1816  
1817 =item *
1818  
1819 OCTET STRINGs and Opaques containing any octet which is not part of the
1820 character set defined as a DisplayString in RFC 2679 are converted into a
1821 hexadecimal representation prefixed with "0x". The control codes NUL(0x00),
1822 BEL(0x07), BS(0x08), HT(0x09), LF(0x0A), VT(0x0b), FF(0x0C), and CR(0x0D)
1823 are part of the character set and will not trigger translation. The sequence
1824 'CR x' for any x other than LF or NUL is illegal and will trigger translation.
1825  
1826 =item *
1827  
1828 TimeTicks integer values are converted to a time format.
1829  
1830 =item *
1831  
1832 NULL values return the string "NULL" instead of an empty string.
1833  
1834 =item *
1835  
1836 noSuchObject exception values return the string "noSuchObject" instead of an
1837 empty string.
1838  
1839 =item *
1840  
1841 noSuchInstance exception values return the string "noSuchInstance" instead of
1842 an empty string.
1843  
1844 =item *
1845  
1846 endOfMibView exception values return the string "endOfMibView" instead of an
1847 empty string.
1848  
1849 =item *
1850  
1851 Counter64, Counter, Gauge, and TimeTick values that have been incorrectly
1852 encoded as signed negative values are returned as unsigned values.
1853  
1854 =back
1855  
1856 The C<translate()> method can be invoked with two different types of arguments.
1857  
1858 If the argument passed is any Perl variable type except an array reference,
1859 the translation mode for all ASN.1 types is set to either enabled or disabled,
1860 depending on the value of the passed parameter. Any value that Perl would
1861 treat as a true value will set the mode to be enabled for all types, while a
1862 false value will disable translation for all types.
1863  
1864 A reference to an array can be passed to the C<translate()> method in order to
1865 define the translation mode on a per ASN.1 type basis. The array is expected
1866 to contain a list of named argument pairs for each ASN.1 type that is to
1867 be modified. The arguments in the list are applied in the order that they
1868 are passed in via the array. Arguments at the end of the list supercede
1869 those passed earlier in the list. The argument "-all" can be used to specify
1870 that the mode is to apply to all ASN.1 types. Only the arguments for the
1871 ASN.1 types that are to be modified need to be included in the list.
1872  
1873 The C<translate()> method returns a bit mask indicating which ASN.1 types
1874 are to be translated. Definitions of the bit to ASN.1 type mappings can be
1875 exported using the I<:translate> tag (see L<"EXPORTS">). The undefined value
1876 is returned upon an error and the C<error()> method may be used to determine
1877 the cause.
1878  
1879 =cut
1880  
1881 sub translate
1882 {
1883 my ($this, $mask) = @_;
1884  
1885 if (@_ != 2) {
1886 return $this->{_translate};
1887 }
1888  
1889 if (ref($mask) ne 'ARRAY') {
1890  
1891 # Behave like we did before, do (not) translate everything
1892 $this->_translate_mask($_[1], TRANSLATE_ALL);
1893  
1894 } else {
1895  
1896 # Allow the user to turn off and on specific translations. An
1897 # array is used so the order of the arguments controls how the
1898 # mask is defined.
1899  
1900 my @argv = @{$mask};
1901 my $arg;
1902  
1903 while (defined ($arg = shift @argv)) {
1904 if ($arg =~ /^-?all$/i) {
1905 $this->_translate_mask(shift(@argv), TRANSLATE_ALL);
1906 } elsif ($arg =~ /^-?none$/i) {
1907 $this->_translate_mask(!(shift @argv), TRANSLATE_ALL);
1908 } elsif ($arg =~ /^-?octet_?string$/i) {
1909 $this->_translate_mask(shift(@argv), TRANSLATE_OCTET_STRING);
1910 } elsif ($arg =~ /^-?null$/i) {
1911 $this->_translate_mask(shift(@argv), TRANSLATE_NULL);
1912 } elsif ($arg =~ /^-?timeticks$/i) {
1913 $this->_translate_mask(shift(@argv), TRANSLATE_TIMETICKS);
1914 } elsif ($arg =~ /^-?opaque$/i) {
1915 $this->_translate_mask(shift(@argv), TRANSLATE_OPAQUE);
1916 } elsif ($arg =~ /^-?nosuchobject$/i) {
1917 $this->_translate_mask(shift(@argv), TRANSLATE_NOSUCHOBJECT);
1918 } elsif ($arg =~ /^-?nosuchinstance$/i) {
1919 $this->_translate_mask(shift(@argv), TRANSLATE_NOSUCHINSTANCE);
1920 } elsif ($arg =~ /^-?endofmibview$/i) {
1921 $this->_translate_mask(shift(@argv), TRANSLATE_ENDOFMIBVIEW);
1922 } elsif ($arg =~ /^-?unsigned$/i) {
1923 $this->_translate_mask(shift(@argv), TRANSLATE_UNSIGNED);
1924 } else {
1925 return $this->_error(
1926 'The translate argument "%s" is unknown', $arg
1927 );
1928 }
1929 }
1930  
1931 }
1932  
1933 DEBUG_INFO('translate mask = 0x%02x', $this->{_translate});
1934  
1935 return $this->{_translate};
1936 }
1937  
1938 =head2 debug() - set or get the debug mode for the module
1939  
1940 $mask = $session->debug([$mask]);
1941  
1942 This method is used to enable or disable debugging for the Net::SNMP module.
1943 Debugging can be enabled on a per component level as defined by a bit mask
1944 passed to the C<debug()> method. The bit mask is broken up as follows:
1945  
1946 =over
1947  
1948 =item *
1949  
1950 0x02 - Message or PDU encoding and decoding
1951  
1952 =item *
1953  
1954 0x04 - Transport Layer
1955  
1956 =item *
1957  
1958 0x08 - Dispatcher
1959  
1960 =item *
1961  
1962 0x10 - Message Processing
1963  
1964 =item *
1965  
1966 0x20 - Security
1967  
1968 =back
1969  
1970 Symbols representing these bit mask values are defined by the module and can
1971 be exported using the I<:debug> tag (see L<"EXPORTS">). If a non-numeric
1972 value is passed to the C<debug()> method, it is evaluated in boolean context.
1973 Debugging for all of the components is then enabled or disabled based on the
1974 resulting truth value.
1975  
1976 The current debugging mask is returned by the method. Debugging can also be
1977 enabled using the stand alone function C<snmp_debug()>. This function can be
1978 exported by request (see L<"EXPORTS">).
1979  
1980 =cut
1981  
1982 sub debug
1983 {
1984 my (undef, $mask) = @_;
1985  
1986 if (@_ == 2) {
1987  
1988 $DEBUG = ($mask =~ /^\d+$/) ? $mask : ($mask) ? DEBUG_ALL : DEBUG_NONE;
1989  
1990 eval { Net::SNMP::Message->debug($DEBUG & DEBUG_MESSAGE); };
1991 eval { Net::SNMP::Transport->debug($DEBUG & DEBUG_TRANSPORT); };
1992 eval { Net::SNMP::Dispatcher->debug($DEBUG & DEBUG_DISPATCHER); };
1993 eval { Net::SNMP::MessageProcessing->debug($DEBUG & DEBUG_PROCESSING); };
1994 eval { Net::SNMP::Security->debug($DEBUG & DEBUG_SECURITY); };
1995  
1996 }
1997  
1998 return $DEBUG;
1999 }
2000  
2001 sub snmp_debug
2002 {
2003 return debug(undef, $_[0]);
2004 }
2005  
2006 sub pdu
2007 {
2008 return $_[0]->{_pdu};
2009 }
2010  
2011 sub nonblocking
2012 {
2013 return $_[0]->{_nonblocking};
2014 }
2015  
2016 sub security
2017 {
2018 return $_[0]->{_security};
2019 }
2020  
2021 sub transport
2022 {
2023 return $_[0]->{_transport};
2024 }
2025  
2026 =head1 SUBROUTINES
2027  
2028 =head2 oid_base_match() - determine if an OID has a specified OID base
2029  
2030 $value = oid_base_match($base_oid, $oid);
2031  
2032 This function takes two OBJECT IDENTIFIERs in dotted notation and returns a
2033 true value (i.e. 0x1) if the second OBJECT IDENTIFIER is equal to or is a
2034 child of the first OBJECT IDENTIFIER in the SNMP Management Information Base
2035 (MIB). This function can be used in conjunction with the C<get-next-request()>
2036 or C<get-bulk-request()> methods to determine when a OBJECT IDENTIFIER in the
2037 GetResponse-PDU is no longer in the desired MIB tree branch.
2038  
2039 =cut
2040  
2041 sub oid_base_match
2042 {
2043 my ($base, $oid) = @_;
2044  
2045 defined $base || return FALSE;
2046 defined $oid || return FALSE;
2047  
2048 $base =~ s/^\.//o;
2049 $oid =~ s/^\.//o;
2050  
2051 $base = pack 'N*', split m/\./, $base;
2052 $oid = pack 'N*', split m/\./, $oid;
2053  
2054 return (substr($oid, 0, length $base) eq $base) ? TRUE : FALSE;
2055 }
2056  
2057 sub oid_context_match
2058 {
2059 require Carp;
2060 Carp::croak(
2061 'oid_context_match() is obsolete, use oid_base_match() instead'
2062 );
2063  
2064 goto &oid_base_match;
2065 }
2066  
2067 =head2 oid_lex_cmp() - compare two OBJECT IDENTIFIERs lexicographically
2068  
2069 $cmp = oid_lex_cmp($oid1, $oid2);
2070  
2071 This function takes two OBJECT IDENTIFIERs in dotted notation and returns one
2072 of the values 1, 0, -1 if $oid1 is respectively lexicographically greater,
2073 equal, or less than $oid2.
2074  
2075 =cut
2076  
2077 sub oid_lex_cmp
2078 {
2079 my ($aa, $bb) = @_;
2080  
2081 for ($aa, $bb) {
2082 s/^\.//;
2083 s/ /\.0/g;
2084 $_ = pack 'N*', split m/\./;
2085 }
2086  
2087 return $aa cmp $bb;
2088 }
2089  
2090 =head2 oid_lex_sort() - sort a list of OBJECT IDENTIFIERs lexicographically
2091  
2092 @sorted_oids = oid_lex_sort(@oids);
2093  
2094 This function takes a list of OBJECT IDENTIFIERs in dotted notation and returns
2095 the listed sorted in lexicographical order.
2096  
2097 =cut
2098  
2099 sub oid_lex_sort
2100 {
2101 if (@_ <= 1) {
2102 return @_;
2103 }
2104  
2105 return map { $_->[0] }
2106 sort { $a->[1] cmp $b->[1] }
2107 map
2108 {
2109 my $oid = $_;
2110 $oid =~ s/^\.//;
2111 $oid =~ s/ /\.0/g;
2112 [$_, pack 'N*', split m/\./, $oid]
2113 } @_;
2114 }
2115  
2116 =head2 snmp_type_ntop() - convert an ASN.1 type to presentation format
2117  
2118 $text = snmp_type_ntop($type);
2119  
2120 This function takes an ASN.1 type octet and returns a text string suitable for
2121 presentation. Some ASN.1 type definitions map to the same octet value when
2122 encoded. This method cannot distinguish between these multiple mappings and
2123 the most basic type name will be returned.
2124  
2125 =cut
2126  
2127 sub snmp_type_ntop
2128 {
2129 goto &asn1_itoa;
2130 }
2131  
2132 =head2 ticks_to_time() - convert TimeTicks to formatted time
2133  
2134 $time = ticks_to_time($timeticks);
2135  
2136 This function takes an ASN.1 TimeTicks value and returns a string representing
2137 the time defined by the value. The TimeTicks value is expected to be a
2138 non-negative integer value representing the time in hundredths of a second
2139 since some epoch. The returned string will display the time in days, hours,
2140 and seconds format according to the value of the TimeTicks argument.
2141  
2142 =cut
2143  
2144 sub ticks_to_time
2145 {
2146 goto &asn1_ticks_to_time;
2147 }
2148  
2149 sub DESTROY
2150 {
2151 my ($this) = @_;
2152  
2153 # We decrement the object type count when the object goes out of
2154 # existance. We assume that _object_type_validate() was called for
2155 # every creation or else we die.
2156  
2157 if ($this->{_nonblocking}) {
2158 if (--$NONBLOCKING < 0) {
2159 die 'FATAL: Invalid non-blocking object count';
2160 }
2161 } else {
2162 if (--$BLOCKING < 0) {
2163 die 'FATAL: Invalid blocking object count';
2164 }
2165 }
2166 }
2167  
2168 # [private methods] ----------------------------------------------------------
2169  
2170 sub _send_pdu
2171 {
2172 my ($this) = @_;
2173  
2174 # Check to see if we are still in the process of discovering the
2175 # authoritative SNMP engine. If we are, queue the PDU if we are
2176 # running in non-blocking mode.
2177  
2178 if ($this->{_nonblocking} && !$this->{_security}->discovered()) {
2179 push @{$this->{_discovery_queue}}, [$this->{_pdu}, $this->{_delay}];
2180 return TRUE;
2181 }
2182  
2183 # Hand the PDU off to the Dispatcher
2184 $DISPATCHER->send_pdu($this->{_pdu}, $this->{_delay});
2185  
2186 # Activate the dispatcher if we are blocking
2187 if (!$this->{_nonblocking}) {
2188 snmp_dispatcher();
2189 }
2190  
2191 # Return according to blocking mode
2192 return ($this->{_nonblocking}) ? TRUE : $this->var_bind_list();
2193 }
2194  
2195 sub _create_pdu
2196 {
2197 my ($this) = @_;
2198  
2199 # Create the new PDU
2200 ($this->{_pdu}, $this->{_error}) = Net::SNMP::PDU->new(
2201 -version => $this->{_version},
2202 -security => $this->{_security},
2203 -transport => $this->{_transport},
2204 -translate => $this->{_translate},
2205 -callback => $this->_callback_closure(),
2206 -requestid => $DISPATCHER->msg_handle_alloc(),
2207 defined($this->{_context_engine_id}) ?
2208 (-contextengineid => $this->{_context_engine_id}) : (),
2209 defined($this->{_context_name}) ?
2210 (-contextname => $this->{_context_name}) : (),
2211 );
2212  
2213 if (!defined $this->{_pdu}) {
2214 return $this->_error();
2215 }
2216 $this->_error_clear();
2217  
2218 # Return the PDU
2219 return $this->{_pdu};
2220 }
2221  
2222 {
2223 my $versions = {
2224 '(?:snmp)?v?1', SNMP_VERSION_1,
2225 '(?:snmp)?v?2c?', SNMP_VERSION_2C,
2226 '(?:snmp)?v?3', SNMP_VERSION_3,
2227 };
2228  
2229 sub _version
2230 {
2231 my ($this, $version) = @_;
2232  
2233 # XXX: The passed $version is updated as a side effect.
2234  
2235 # Clear any previous error message.
2236 $this->_error_clear();
2237  
2238 if ($version eq q{}) {
2239 return $this->_error('An empty SNMP version was specified');
2240 }
2241  
2242 for (keys %{$versions}) {
2243 if ($version =~ m/^$_$/i) {
2244 $_[1] = $this->{_version} = $versions->{$_};
2245 return TRUE;
2246 }
2247 }
2248  
2249 return $this->_error('The SNMP version "%s" is unknown', $version);
2250 }
2251  
2252 }
2253  
2254 {
2255 # Arguments that apply to the object.
2256 my $obj_args = {
2257 -callback => \&_callback, # non-blocking only
2258 -contextengineid => \&_context_engine_id, # v3 only
2259 -contextname => \&_context_name, # v3 only
2260 -delay => \&_delay, # non-blocking only
2261 };
2262  
2263 sub _prepare_argv
2264 {
2265 my ($this, $allowed, $named, $unnamed) = @_;
2266  
2267 # XXX: Argument $unnamed is updated by reference.
2268  
2269 my %argv;
2270  
2271 # For backwards compatibility, check to see if the first
2272 # argument is an OBJECT IDENTIFIER in dotted notation. If it
2273 # is, assign it to the -varbindlist argument.
2274  
2275 if ((@{$named}) && ($named->[0] =~ m/^\.?\d+(?:\.\d+)* *$/)) {
2276 $argv{-varbindlist} = $named;
2277 } else {
2278 %argv = @{$named};
2279 }
2280  
2281 # Go through the passed argument list and see if the argument is
2282 # allowed. If it is, see if it applies to the object and has a
2283 # matching method call or add it the the new argv list to be
2284 # returned by this method.
2285  
2286 my %new_args;
2287  
2288 for my $key (keys %argv) {
2289 my @match = grep { /^-?\Q$key\E$/i } @{$allowed};
2290 if (@match == 1) {
2291 if (exists $obj_args->{$match[0]}) {
2292 if (!defined $this->${\$obj_args->{$match[0]}}($argv{$key})) {
2293 return $this->_error();
2294 }
2295 } else {
2296 $new_args{$match[0]} = $argv{$key};
2297 }
2298 } else {
2299 return $this->_error('The argument "%s" is unknown', $key);
2300 }
2301 }
2302  
2303 # Create a new ordered unnamed argument list based on the allowed
2304 # list passed, ignoring those that applied to the object.
2305  
2306 for (@{$allowed}) {
2307 next if exists $obj_args->{$_};
2308 push @{$unnamed}, exists($new_args{$_}) ? $new_args{$_} : undef;
2309 }
2310  
2311 return TRUE;
2312 }
2313  
2314 }
2315  
2316 sub _callback
2317 {
2318 my ($this, $callback) = @_;
2319  
2320 # We validate the callback argument and then create an anonymous
2321 # array where the first element is the subroutine reference and
2322 # the second element is an array reference containing arguments
2323 # to pass to the subroutine.
2324  
2325 if (!$this->{_nonblocking}) {
2326 return $this->_error(
2327 'The callback argument is not applicable to blocking objects'
2328 );
2329 }
2330  
2331 my @argv;
2332  
2333 if (!defined $callback) {
2334 $this->{_callback} = undef;
2335 return TRUE;
2336 } elsif ((ref($callback) eq 'ARRAY') && (ref($callback->[0]) eq 'CODE')) {
2337 ($callback, @argv) = @{$callback};
2338 } elsif (ref($callback) ne 'CODE') {
2339 return $this->_error('The syntax of the callback is invalid');
2340 }
2341  
2342 $this->{_callback} = [$callback, \@argv];
2343  
2344 return TRUE;
2345 }
2346  
2347 sub _callback_closure
2348 {
2349 my ($this) = @_;
2350  
2351 # When a response message is received, the Dispatcher will create
2352 # a new PDU object and assign the callback to that object. The
2353 # callback is then executed passing a reference to the PDU object
2354 # as the first argument. We use a closure to assign that passed
2355 # reference to the Net:SNMP object and then invoke the user defined
2356 # callback.
2357  
2358 if (!$this->{_nonblocking} || !defined $this->{_callback}) {
2359 return sub
2360 {
2361 $this->{_pdu} = $_[0];
2362 $this->_error_clear();
2363 if ($this->{_pdu}->error()) {
2364 $this->_error($this->{_pdu}->error());
2365 }
2366 return;
2367 };
2368 }
2369  
2370 my ($callback, $argv) = @{$this->{_callback}};
2371  
2372 return sub
2373 {
2374 $this->{_pdu} = $_[0];
2375 $this->_error_clear();
2376 if ($this->{_pdu}->error()) {
2377 $this->_error($this->{_pdu}->error());
2378 }
2379 $callback->($this, @{$argv});
2380 return;
2381 };
2382 }
2383  
2384 sub _context_engine_id
2385 {
2386 my ($this, $context_engine_id) = @_;
2387  
2388 $this->_error_clear();
2389  
2390 if ($this->version() != SNMP_VERSION_3) {
2391 return $this->_error(
2392 'The contextEngineID argument is only supported in SNMPv3'
2393 );
2394 }
2395  
2396 if (!defined $context_engine_id) {
2397 $this->{_context_engine_id} = undef;
2398 } elsif ($context_engine_id =~ m/^(?:0x)?([A-F0-9]+)$/i) {
2399 my $cei = pack 'H*', length($1) % 2 ? '0'.$1 : $1;
2400 my $len = length $cei;
2401 if ($len < 5 || $len > 32) {
2402 return $this->_error(
2403 'The contextEngineID length of %d is out of range (5..32)', $len
2404 );
2405 }
2406 $this->{_context_engine_id} = $cei;
2407 } else {
2408 return $this->_error(
2409 'The contextEngineID "%s" is expected in hexadecimal format',
2410 $context_engine_id
2411 );
2412 }
2413  
2414 return TRUE;
2415 }
2416  
2417 sub _context_name
2418 {
2419 my ($this, $context_name) = @_;
2420  
2421 $this->_error_clear();
2422  
2423 if ($this->version() != SNMP_VERSION_3) {
2424 return $this->_error(
2425 'The contextName argument is only supported in SNMPv3'
2426 );
2427 }
2428  
2429 if (!defined $context_name) {
2430 $this->{_context_name} = undef;
2431 } elsif (length($context_name) <= 32) {
2432 $this->{_context_name} = $context_name;
2433 } else {
2434 return $this->_error(
2435 'The contextName length of %d is out of range (0..32)',
2436 length $context_name
2437 );
2438 }
2439  
2440 return TRUE;
2441 }
2442  
2443 sub _delay
2444 {
2445 my ($this, $delay) = @_;
2446  
2447 $this->_error_clear();
2448  
2449 if (!$this->{_nonblocking}) {
2450 return $this->_error(
2451 'The delay argument is not applicable to blocking objects'
2452 );
2453 }
2454  
2455 if ($delay !~ /^\d+(?:\.\d+)?$/) {
2456 return $this->_error(
2457 'The delay value "%s" is expected in positive numeric format', $delay
2458 );
2459 }
2460  
2461 if ($delay < 0 || $delay > 31556926) { # Seconds in a year...
2462 return $this->_error(
2463 'The delay value "%s" is out of range (0..31556926)', $delay
2464 );
2465 }
2466  
2467 $this->{_delay} = $delay;
2468  
2469 return TRUE;
2470 }
2471  
2472 sub _object_type_validate
2473 {
2474 my ($this) = @_;
2475  
2476 # Since both non-blocking and blocking objects use the same
2477 # Dispatcher instance, allowing both objects types to exist at
2478 # the same time would cause problems. This method is called
2479 # by the constructor to track the object counts based on the
2480 # non-blocking property and returns an error if the two types
2481 # would exist at the same time.
2482  
2483 my $count = ($this->{_nonblocking}) ? ++$NONBLOCKING : ++$BLOCKING;
2484  
2485 if ($this->{_nonblocking} && $BLOCKING) {
2486 return $this->_error(
2487 'Cannot create non-blocking objects when blocking objects exist'
2488 );
2489 } elsif (!$this->{_nonblocking} && $NONBLOCKING) {
2490 return $this->_error(
2491 'Cannot create blocking objects when non-blocking objects exist'
2492 );
2493 }
2494  
2495 return $count;
2496 }
2497  
2498 sub _perform_discovery
2499 {
2500 my ($this) = @_;
2501  
2502 return TRUE if ($this->{_security}->discovered());
2503  
2504 # RFC 3414 - Section 4: "Discovery... ...may be accomplished by
2505 # generating a Request message with a securityLevel of noAuthNoPriv,
2506 # a msgUserName of zero-length, a msgAuthoritativeEngineID value of
2507 # zero length, and the varBindList left empty."
2508  
2509 # Create a new PDU
2510 if (!defined $this->_create_pdu()) {
2511 return $this->_discovery_failed();
2512 }
2513  
2514 # Create the callback and assign it to the PDU
2515 $this->{_pdu}->callback(
2516 sub
2517 {
2518 $this->{_pdu} = $_[0];
2519 $this->_error_clear();
2520 if ($this->{_pdu}->error()) {
2521 $this->_error($this->{_pdu}->error() . ' during discovery');
2522 }
2523 $this->_discovery_engine_id_cb();
2524 return;
2525 }
2526 );
2527  
2528 # Prepare an empty get-request
2529 if (!defined $this->{_pdu}->prepare_get_request()) {
2530 $this->_error($this->{_pdu}->error());
2531 return $this->_discovery_failed();
2532 }
2533  
2534 # Send the PDU
2535 $DISPATCHER->send_pdu($this->{_pdu}, 0);
2536  
2537 if (!$this->{_nonblocking}) {
2538 snmp_dispatcher();
2539 }
2540  
2541 return ($this->{_error}) ? $this->_error() : TRUE;
2542 }
2543  
2544 sub _discovery_engine_id_cb
2545 {
2546 my ($this) = @_;
2547  
2548 # "The response to this message will be a Report message containing
2549 # the snmpEngineID of the authoritative SNMP engine... ...with the
2550 # usmStatsUnknownEngineIDs counter in the varBindList." If another
2551 # error is returned, we assume snmpEngineID discovery has failed.
2552  
2553 if ($this->{_error} !~ /usmStatsUnknownEngineIDs/) {
2554 return $this->_discovery_failed();
2555 }
2556  
2557 # Clear the usmStatsUnknownEngineIDs error
2558 $this->_error_clear();
2559  
2560 # If the security model indicates that discovery is complete,
2561 # we send any pending messages and return success. If discovery
2562 # is not complete, we probably need to synchronize with the
2563 # remote authoritative engine.
2564  
2565 if ($this->{_security}->discovered()) {
2566 DEBUG_INFO('discovery complete');
2567 return $this->_discovery_complete();
2568 }
2569  
2570 # "If authenticated communication is required, then the discovery
2571 # process should also establish time synchronization with the
2572 # authoritative SNMP engine. This may be accomplished by sending
2573 # an authenticated Request message..."
2574  
2575 # Create a new PDU
2576 if (!defined $this->_create_pdu()) {
2577 return $this->_discovery_failed();
2578 }
2579  
2580 # Create the callback and assign it to the PDU
2581 $this->{_pdu}->callback(
2582 sub
2583 {
2584 $this->{_pdu} = $_[0];
2585 $this->_error_clear();
2586 if ($this->{_pdu}->error()) {
2587 $this->_error($this->{_pdu}->error() . ' during synchronization');
2588 }
2589 $this->_discovery_synchronization_cb();
2590 return;
2591 }
2592 );
2593  
2594 # Prepare an empty get-request
2595 if (!defined $this->{_pdu}->prepare_get_request()) {
2596 $this->_error($this->{_pdu}->error());
2597 return $this->_discovery_failed();
2598 }
2599  
2600 # Send the PDU
2601 $DISPATCHER->send_pdu($this->{_pdu}, 0);
2602  
2603 if (!$this->{_nonblocking}) {
2604 snmp_dispatcher();
2605 }
2606  
2607 return ($this->{_error}) ? $this->_error() : TRUE;
2608 }
2609  
2610 sub _discovery_synchronization_cb
2611 {
2612 my ($this) = @_;
2613  
2614 # "The response... ...will be a Report message containing the up
2615 # to date values of the authoritative SNMP engine's snmpEngineBoots
2616 # and snmpEngineTime... It also contains the usmStatsNotInTimeWindows
2617 # counter in the varBindList..." If another error is returned, we
2618 # assume that the synchronization has failed.
2619  
2620 if (($this->{_security}->discovered()) &&
2621 ($this->{_error} =~ /usmStatsNotInTimeWindows/))
2622 {
2623 $this->_error_clear();
2624 DEBUG_INFO('discovery and synchronization complete');
2625 return $this->_discovery_complete();
2626 }
2627  
2628 # If we received the usmStatsNotInTimeWindows report or no error, but
2629 # we are still not synchronized, provide a generic error message.
2630  
2631 if ((!$this->{_error}) || ($this->{_error} =~ /usmStatsNotInTimeWindows/)) {
2632 $this->_error_clear();
2633 $this->_error('Time synchronization failed during discovery');
2634 }
2635  
2636 DEBUG_INFO('synchronization failed');
2637  
2638 return $this->_discovery_failed();
2639 }
2640  
2641 sub _discovery_failed
2642 {
2643 my ($this) = @_;
2644  
2645 # The discovery process has failed, clear the current PDU and the
2646 # Transport Domain so no one can use this object to send messages.
2647  
2648 $this->{_pdu} = undef;
2649 $this->{_transport} = undef;
2650  
2651 # Inform the command generator about the current error.
2652 while (my $q = shift @{$this->{_discovery_queue}}) {
2653 $q->[0]->status_information($this->{_error});
2654 }
2655  
2656 return $this->_error();
2657 }
2658  
2659 sub _discovery_complete
2660 {
2661 my ($this) = @_;
2662  
2663 # Discovery is complete, send any pending messages.
2664 while (my $q = shift @{$this->{_discovery_queue}}) {
2665 $DISPATCHER->send_pdu(@{$q});
2666 }
2667  
2668 return ($this->{_error}) ? $this->_error() : TRUE;
2669 }
2670  
2671 sub _translate_mask
2672 {
2673 my ($this, $enable, $mask) = @_;
2674  
2675 # Define the translate bitmask for the object based on the
2676 # passed truth value and mask.
2677  
2678 if ($enable) {
2679 $this->{_translate} |= $mask; # Enable
2680 } else {
2681 $this->{_translate} &= ~$mask; # Disable
2682 }
2683  
2684 return $this->{_translate};
2685 }
2686  
2687 sub _msg_size_max_reps
2688 {
2689 my ($this) = @_;
2690  
2691 # Use the maxMsgSize of the object to produce a max-repetitions
2692 # value. This is an attempt to avoid exceeding the maxMsgSize
2693 # in the responses to get-bulk-requests. The scaling factor
2694 # of 0.017 produces a value of 25 with the default maxMsgSize of
2695 # 1472. This was the old hardcoded value used by get_table().
2696  
2697 if (!defined $this->{_transport}) {
2698 return 25;
2699 }
2700  
2701 return int $this->{_transport}->max_msg_size() * 0.017;
2702 }
2703  
2704 sub _get_table_cb
2705 {
2706 my ($this, $argv) = @_;
2707  
2708 # Use get-next-requests or get-bulk-requests until the response is
2709 # not a subtree of the base OBJECT IDENTIFIER. Return the table only
2710 # if there are no errors other than a noSuchName(2) error since the
2711 # table could be at the end of the tree. Also return the table when
2712 # the value of the OID equals endOfMibView(2) when using SNMPv2c.
2713  
2714 # Get the current callback.
2715 my $callback = $this->{_pdu}->callback();
2716  
2717 # Assign the user callback to the PDU.
2718 $this->{_pdu}->callback($argv->{callback});
2719  
2720 my $list = $this->var_bind_list();
2721 my $types = $this->var_bind_types();
2722 my @names = $this->var_bind_names();
2723 my $next = undef;
2724  
2725 while (@names) {
2726  
2727 $next = shift @names;
2728  
2729 # Check to see if we are still in the correct subtree and have
2730 # not received a endOfMibView exception.
2731  
2732 if (!oid_base_match($argv->{base_oid}, $next) ||
2733 ($types->{$next} == ENDOFMIBVIEW))
2734 {
2735 $next = undef; # End of table.
2736 last;
2737 }
2738  
2739 # Add the entry to the table only if it is not already present
2740 # and check to make sure that the remote host does not respond
2741 # incorrectly causing the requests to loop forever.
2742  
2743 if (!exists $argv->{table}->{$next}) {
2744 $argv->{table}->{$next} = $list->{$next};
2745 $argv->{types}->{$next} = $types->{$next};
2746 } elsif (++$argv->{repeat_cnt} > $argv->{max_reps}) {
2747 $this->{_pdu}->status_information(
2748 'A loop was detected with the table on the remote host'
2749 );
2750 return;
2751 }
2752 }
2753  
2754 # Queue the next request if we are not at the end of the table.
2755 if (defined $next) {
2756 $this->_get_table_entries_request_next($argv, $callback, [$next]);
2757 return;
2758 }
2759  
2760 # Clear the PDU error on a noSuchName(2) error status.
2761 if ($this->error_status() == 2) {
2762 $this->{_pdu}->error(undef);
2763 }
2764  
2765 # Check for an empty or nonexistent table.
2766 if (!$this->{_pdu}->error() && !defined $argv->{table}) {
2767 $this->{_pdu}->error('The requested table is empty or does not exist');
2768 }
2769  
2770 # Copy the table to the var_bind_list.
2771 $this->{_pdu}->var_bind_list($argv->{table}, $argv->{types});
2772  
2773 # Notify the command generator to process the results.
2774 $this->{_pdu}->process_response_pdu();
2775  
2776 return;
2777 }
2778  
2779 sub _get_entries_cb
2780 {
2781 my ($this, $argv) = @_;
2782  
2783 # Get the current callback.
2784 my $callback = $this->{_pdu}->callback();
2785  
2786 # Assign the user callback to the PDU.
2787 $this->{_pdu}->callback($argv->{callback});
2788  
2789 # Iterate through the response OBJECT IDENTIFIERs. The response(s)
2790 # will (should) be grouped in the same order as the columns that
2791 # were requested. We use this assumption to map the response(s) to
2792 # get-next/bulk-requests. When using get-bulk-requests, "holes" in
2793 # the table may cause certain columns to run ahead or behind other
2794 # columns, so we cache all entries and sort it out when processing
2795 # the row.
2796  
2797 my $list = $this->var_bind_list();
2798 my $types = $this->var_bind_types();
2799 my @names = $this->var_bind_names();
2800 my $max_index = (defined $argv->{last_index}) ? $argv->{last_index} : '0';
2801 my $last_entry = TRUE;
2802 my $cache = {};
2803  
2804 while (@names) {
2805  
2806 my @row = ();
2807 my $row_index = undef;
2808  
2809 # Match up the responses to the requested columns.
2810  
2811 for my $col_num (0 .. $#{$argv->{columns}}) {
2812  
2813 my $name = shift @names;
2814  
2815 if (!defined $name) {
2816  
2817 # Due to transport layer limitations, the response could have
2818 # been truncated, so do not consider this the last entry.
2819  
2820 DEBUG_INFO('column number / oid number mismatch');
2821 $last_entry = FALSE;
2822 @row = ();
2823 last;
2824 }
2825  
2826 my $column = quotemeta $argv->{columns}->[$col_num];
2827 my $index;
2828  
2829 if ($name =~ m/$column\.(\d+(:?\.\d+)*)/) {
2830  
2831 # Requested column and response column match up.
2832 $index = $1;
2833  
2834 } else {
2835  
2836 # The response column does not map to the the request, there
2837 # could be a "hole" or we are out of entries.
2838  
2839 DEBUG_INFO('last_entry: column mismatch: %s', $name);
2840 $last_entry = TRUE;
2841 next;
2842 }
2843  
2844 DEBUG_INFO('found index [%s]', $index);
2845  
2846 # Validate the index of the response.
2847  
2848 if ((defined $argv->{start_index}) &&
2849 (oid_lex_cmp($index, $argv->{start_index}) < 0))
2850 {
2851 DEBUG_INFO(
2852 'index [%s] less than start_index [%s]',
2853 $index, $argv->{start_index}
2854 );
2855 if (oid_lex_cmp($index, $max_index) > 0) {
2856 $max_index = $index;
2857 $last_entry = FALSE;
2858 DEBUG_INFO('new max_index [%s]', $max_index);
2859 }
2860 next;
2861 } elsif ((defined $argv->{end_index}) &&
2862 (oid_lex_cmp($index, $argv->{end_index}) > 0))
2863 {
2864 DEBUG_INFO(
2865 'last_entry: index [%s] greater than end_index [%s]',
2866 $index, $argv->{end_index}
2867 );
2868 $last_entry = TRUE;
2869 next;
2870 }
2871  
2872 # Cache the current column since it falls into the requested range.
2873  
2874 $cache->{$index}->[$col_num] = $name;
2875  
2876 # To handle "holes" in the conceptual row, checks need to be made
2877 # so that the lowest index for each group of responses is used.
2878  
2879 if (!defined $row_index) {
2880 $row_index = $index;
2881 }
2882  
2883 my $index_cmp = oid_lex_cmp($index, $row_index);
2884  
2885 if ($index_cmp == 0) {
2886  
2887 # The index for this response entry matches, so fill in
2888 # the corresponding row entry.
2889  
2890 $row[$col_num] = $name;
2891  
2892 } elsif ($index_cmp < 0) {
2893  
2894 # The index for this response is less than the current index,
2895 # so we throw out everything and start over.
2896  
2897 @row = ();
2898 $row_index = $index;
2899 $row[$col_num] = $name;
2900 DEBUG_INFO('new minimum row_index [%s]', $row_index);
2901  
2902 } else {
2903  
2904 # There must be a "hole" in the row, do nothing here since this
2905 # entry was cached and will hopefully be taken care of later.
2906  
2907 DEBUG_INFO(
2908 'index [%s] greater than current row_index [%s]',
2909 $index, $row_index
2910 );
2911  
2912 }
2913  
2914 }
2915  
2916 # No row information found, continue.
2917  
2918 if (!@row || !defined $row_index) {
2919 next;
2920 }
2921  
2922 # Now store the results for the conceptual row.
2923  
2924 for my $col_num (0 .. $#{$argv->{columns}}) {
2925  
2926 # Check for cached values that may have been lost due to "holes".
2927 if (!defined $row[$col_num]) {
2928 if (defined $cache->{$row_index}->[$col_num]) {
2929 DEBUG_INFO('using cache: %s', $cache->{$row_index}->[$col_num]);
2930 $row[$col_num] = $cache->{$row_index}->[$col_num];
2931 } else {
2932 next;
2933 }
2934 }
2935  
2936 # Actually store the results.
2937 if (!exists $argv->{entries}->{$row[$col_num]}) {
2938 $last_entry = FALSE;
2939 $argv->{entries}->{$row[$col_num]} = $list->{$row[$col_num]};
2940 $argv->{types}->{$row[$col_num]} = $types->{$row[$col_num]};
2941 } else {
2942 DEBUG_INFO('not adding duplicate: %s', $row[$col_num]);
2943 }
2944  
2945 }
2946  
2947 # Execute the row callback if it is defined.
2948 $this->_get_entries_exec_row_cb($argv, $row_index, \@row);
2949  
2950 # Store the maximum index found to be used for the next request.
2951 if (oid_lex_cmp($row_index, $max_index) > 0) {
2952 $max_index = $row_index;
2953 DEBUG_INFO('new max_index [%s]', $max_index);
2954 }
2955  
2956 }
2957  
2958 # Make sure we are not stuck (looping) on a single index.
2959  
2960 if (defined $argv->{last_index}) {
2961 if (oid_lex_cmp($max_index, $argv->{last_index}) > 0) {
2962 $argv->{last_index} = $max_index;
2963 } elsif ($last_entry == FALSE) {
2964 DEBUG_INFO(
2965 'last_entry: max_index [%s] not greater than last_index [%s])',
2966 $max_index, $argv->{last_index}
2967 );
2968 $last_entry = TRUE;
2969 }
2970 } else {
2971 $argv->{last_index} = $max_index;
2972 }
2973  
2974 # If we have not reached the last requested entry, generate another
2975 # get-next/bulk-request message.
2976  
2977 if ($last_entry == FALSE) {
2978 my $vbl = [ map { join q{.}, $_, $max_index } @{$argv->{columns}} ];
2979 $this->_get_table_entries_request_next($argv, $callback, $vbl);
2980 return;
2981 }
2982  
2983 # Clear the PDU error on a noSuchName(2) error status.
2984 if ($this->error_status() == 2) {
2985 $this->{_pdu}->error(undef);
2986 }
2987  
2988 # Check for an empty or nonexistent table.
2989 if (!$this->{_pdu}->error() && !defined $argv->{entries}) {
2990 $this->{_pdu}->error('The requested entries are empty or do not exist');
2991 }
2992  
2993 # Copy the table to the var_bind_list.
2994 $this->{_pdu}->var_bind_list($argv->{entries}, $argv->{types});
2995  
2996 # Execute the row callback, if there has been an error.
2997 if ($this->{_pdu}->error()) {
2998 $this->_get_entries_exec_row_cb($argv, 0, []);
2999 }
3000  
3001 # Notify the command generator to process the results.
3002 $this->{_pdu}->process_response_pdu();
3003  
3004 return;
3005 }
3006  
3007 sub _get_table_entries_request_next
3008 {
3009 my ($this, $argv, $callback, $vbl) = @_;
3010  
3011 # Copy the current PDU for use in error conditions.
3012 my $pdu = $this->{_pdu};
3013  
3014 # Create a new PDU.
3015 if (!defined $this->_create_pdu()) {
3016 $pdu->status_information($this->error());
3017 return;
3018 }
3019  
3020 # Override the callback with the saved callback.
3021 $this->{_pdu}->callback($callback);
3022  
3023 # Use the contextEngineID and contextName from the previous request
3024 # because the values stored in the object could change.
3025  
3026 if (defined $pdu->context_engine_id()) {
3027 $this->{_pdu}->context_engine_id($pdu->context_engine_id());
3028 }
3029  
3030 if (defined $pdu->context_name()) {
3031 $this->{_pdu}->context_name($pdu->context_name());
3032 }
3033  
3034 # Create the appropriate request.
3035  
3036 if ($argv->{use_bulk}) {
3037 if (!defined $this->{_pdu}->prepare_get_bulk_request(0,
3038 $argv->{max_reps},
3039 $vbl))
3040 {
3041 $pdu->status_information($this->{_pdu}->error());
3042 return;
3043 }
3044 } else {
3045 if (!defined $this->{_pdu}->prepare_get_next_request($vbl)) {
3046 $pdu->status_information($this->{_pdu}->error());
3047 return;
3048 }
3049 }
3050  
3051 # Send the next PDU with no delay.
3052 $DISPATCHER->send_pdu($this->{_pdu}, 0);
3053  
3054 return;
3055 }
3056  
3057 sub _get_entries_exec_row_cb
3058 {
3059 my ($this, $argv, $index, $row) = @_;
3060  
3061 return if !defined $argv->{row_callback};
3062  
3063 my ($cb, @argv) = @{$argv->{row_callback}};
3064  
3065 # Add the "values" found for each column to the front of the
3066 # callback argument list.
3067  
3068 for (my $col_num = $#{$argv->{columns}}; $col_num >= 0; --$col_num) {
3069 if (defined $row->[$col_num]) {
3070 unshift @argv, $argv->{entries}->{$row->[$col_num]};
3071 } else {
3072 unshift @argv, undef;
3073 }
3074 }
3075  
3076 # Prepend the index for the conceptual row.
3077 unshift @argv, $index;
3078  
3079 return eval { $cb->(@argv); };
3080 }
3081  
3082 sub _error
3083 {
3084 my $this = shift;
3085  
3086 # If the PDU callback is still defined when an error occurs, it
3087 # needs to be cleared to prevent the closure from holding up the
3088 # reference count of the object that created the closure.
3089  
3090 if (defined $this->{_pdu} && defined $this->{_pdu}->callback()) {
3091 $this->{_pdu}->callback(undef);
3092 }
3093  
3094 if (!defined $this->{_error}) {
3095 $this->{_error} = (@_ > 1) ? sprintf(shift(@_), @_) : $_[0];
3096 if ($this->debug()) {
3097 printf "error: [%d] %s(): %s\n",
3098 (caller 0)[2], (caller 1)[3], $this->{_error};
3099 }
3100 }
3101  
3102 return;
3103 }
3104  
3105 sub _error_clear
3106 {
3107 return $_[0]->{_error} = undef;
3108 }
3109  
3110 sub require_version
3111 {
3112 my ($this, @argv) = @_;
3113  
3114 # Provide our own method for handling x.y.z version checks and the return
3115 # value of VERISON() in older implementations of Perl. V-string versions
3116 # in Perl 5.10.0 are now treated as version objects and handled properly.
3117  
3118 if (@argv > 0) {
3119 my $wanted = $argv[0];
3120 if ($wanted =~ /(\d+)\.(\d{1,3})\.(\d{1,3})/) {
3121 $argv[0] = sprintf '%d.%03d%03d', $1, $2, $3;
3122 }
3123 }
3124  
3125 my $version = eval
3126 {
3127 sprintf '%d.%03d%03d', unpack 'C*', $this->UNIVERSAL::VERSION(@argv);
3128 };
3129  
3130 if ($@) {
3131 local $_ = $@;
3132 s/ at(?:.*)\n//;
3133 require Carp;
3134 Carp::croak($_);
3135 }
3136  
3137 return $version;
3138 }
3139  
3140 sub DEBUG_INFO
3141 {
3142 return $DEBUG if (!$DEBUG);
3143  
3144 return printf
3145 sprintf('debug: [%d] %s(): ', (caller 0)[2], (caller 1)[3]) .
3146 ((@_ > 1) ? shift(@_) : '%s') .
3147 "\n",
3148 @_;
3149 }
3150  
3151 # [end Net::SNMP code] -------------------------------------------------------
3152 1;
3153 __END__