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