1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
|
# -*- mode: Perl -*-
######################################################################
### SNMP Request/Response Handling
######################################################################
### The abstract class SNMP_Session defines objects that can be used
### to communicate with SNMP entities. It has methods to send
### requests to and receive responses from an agent.
###
### Currently it has one subclass, SNMPv1_Session, which implements
### the SNMPv1 protocol.
######################################################################
### Created by: Simon Leinen <simon@switch.ch>
###
### Contributions and fixes by:
###
### Matthew Trunnell <matter@media.mit.edu>
### Tobias Oetiker <oetiker@ee.ethz.ch>
### Heine Peters <peters@dkrz.de>
### Daniel L. Needles <dan_needles@INS.COM>
######################################################################
package SNMP_Session;
require 5.002;
use strict qw(vars subs); # cannot use strict subs here
# because of the way we use
# generated file handles
use Exporter;
use vars qw(@ISA $VERSION @EXPORT $errmsg $suppress_warnings);
use Socket;
use BER;
$VERSION = '0.56';
@ISA = qw(Exporter);
@EXPORT = qw(errmsg suppress_warnings);
my $default_debug = 0;
### Default initial timeout (in seconds) waiting for a response PDU
### after a request is sent. Note that when a request is retried, the
### timeout is increased by BACKOFF (see below).
###
my $default_timeout = 2.0;
### Default number of retries for each SNMP request. If no response
### is received after TIMEOUT seconds, the request is resent and a new
### response awaited with a longer timeout (see the documentation on
### BACKOFF below).
###
my $default_retries = 5;
### Default backoff factor for SNMP_Session objects. This factor is
### used to increase the TIMEOUT every time an SNMP request is
### retried.
###
my $default_backoff = 1.0;
$SNMP_Session::errmsg = '';
$SNMP_Session::suppress_warnings = 0;
sub get_request { 0 | context_flag };
sub getnext_request { 1 | context_flag };
sub get_response { 2 | context_flag };
sub set_request { 3 | context_flag };
sub standard_udp_port { 161 };
sub open
{
return SNMPv1_Session::open (@_);
}
sub timeout { $_[0]->{timeout} }
sub retries { $_[0]->{retries} }
sub backoff { $_[0]->{backoff} }
sub encode_request
{
my($this, $reqtype, @encoded_oids_or_pairs) = @_;
my($request);
local($_);
++$this->{request_id};
foreach $_ (@encoded_oids_or_pairs) {
if (ref ($_) eq 'ARRAY') {
$_ = &encode_sequence ($_->[0], $_->[1])
|| return $this->ber_error ("encoding pair");
} else {
$_ = &encode_sequence ($_, encode_null())
|| return $this->ber_error ("encoding value/null pair");
}
}
$request = encode_tagged_sequence
($reqtype,
encode_int ($this->{request_id}),
encode_int_0, encode_int_0,
encode_sequence (@encoded_oids_or_pairs))
|| return $this->ber_error ("encoding request PDU");
return $this->wrap_request ($request);
}
sub encode_get_request
{
my($this, @oids) = @_;
return encode_request ($this, get_request, @oids);
}
sub encode_getnext_request
{
my($this, @oids) = @_;
return encode_request ($this, getnext_request, @oids);
}
sub encode_set_request
{
my($this, @encoded_pairs) = @_;
return encode_request ($this, set_request, @encoded_pairs);
}
sub decode_get_response
{
my($this, $response) = @_;
my @rest;
@{$this->{'unwrapped'}};
}
sub wait_for_response
{
my($this) = shift;
my($timeout) = shift || 10.0;
my($rin,$win,$ein) = ('','','');
my($rout,$wout,$eout);
vec($rin,$this->sockfileno,1) = 1;
select($rout=$rin,$wout=$win,$eout=$ein,$timeout);
}
sub get_request_response
{
my($this) = shift;
my(@oids) = @_;
return $this->request_response_4 ($this->encode_get_request (@oids),
get_response, \@oids);
}
sub set_request_response
{
my($this) = shift;
my(@pairs) = @_;
return $this->request_response_4 ($this->encode_set_request (@pairs),
get_response, \@pairs);
}
sub getnext_request_response
{
my($this) = shift;
my(@oids) = @_;
return $this->request_response_4 ($this->encode_getnext_request (@oids),
get_response, \@oids);
}
sub request_response_4
{
my $this = shift;
my $req = shift;
my $response_tag = shift;
my $oids = shift;
my $retries = $this->retries;
my $timeout = $this->timeout;
## Encoding may have returned an error.
return undef unless defined($req);
$this->send_query ($req)
|| return $this->error ("send_query: $!");
while ($retries > 0) {
if ($this->wait_for_response($timeout)) {
my($response_length);
$response_length
= $this->receive_response_2 ($response_tag, $oids);
if ($response_length) {
return $response_length;
} else {
return undef;
}
} else {
## No response received - retry
--$retries;
$timeout *= $this->backoff;
$this->send_query ($req)
|| return $this->error ("send_query: $!");
}
}
$this->error ("no response received");
}
sub error_return
{
my $this = shift;
my $message = shift;
$SNMP_Session::errmsg = $message;
unless ($SNMP_Session::suppress_warnings) {
$message =~ s/^/ /mg;
warn ("Error:\n".$message."\n");
}
return undef;
}
sub error
{
my $this = shift;
my $message = shift;
my $session = $this->to_string;
$SNMP_Session::errmsg = $message."\n".$session;
unless ($SNMP_Session::suppress_warnings) {
$session =~ s/^/ /mg;
$message =~ s/^/ /mg;
warn ("SNMP Error:\n".$SNMP_Session::errmsg."\n");
}
return undef;
}
sub ber_error ($ )
{
my ($this,$type) = @_;
my ($errmsg) = $BER::errmsg;
$errmsg =~ s/^/ /mg;
return $this->error ("$type:\n$errmsg");
}
sub version { $VERSION; }
package SNMPv1_Session;
use strict qw(vars subs); # see above
use vars qw(@ISA);
use SNMP_Session;
use Socket;
use BER;
@ISA = qw(SNMP_Session);
sub snmp_version { 0 }
sub open
{
my($this,$remote_hostname,$community,$port,$max_pdu_len) = @_;
my($name,$aliases,$remote_addr,$socket);
my $udp_proto = 0;
$community = 'public' unless defined $community;
$port = SNMP_Session::standard_udp_port unless defined $port;
$max_pdu_len = 8000 unless defined $max_pdu_len;
## Changed upon a suggestion by "Daniel L. Needles"
## <dan_needles@INS.COM>: on Windows'95, passing numeric IP
## addresses to inet_aton() seems to work, but is apparently very
## slow. So if we detect that case, we use a simple conversion.
##
if ($remote_hostname =~ /^\d+\.\d+\.\d+\.\d+(.*)/ )
{
$remote_addr = pack("C*",split /\./, $remote_hostname);
} else {
$remote_addr = inet_aton ($remote_hostname)
|| return $this->error_return ("can't resolve \"$remote_hostname\" to IP address");
}
$socket = 'SNMP'.sprintf ("%s:04x", inet_ntoa ($remote_addr), $port);
(($name,$aliases,$udp_proto) = getprotobyname('udp'))
unless $udp_proto;
$udp_proto=17 unless $udp_proto;
socket ($socket, PF_INET, SOCK_DGRAM, $udp_proto)
|| return $this->error_return ("creating socket: $!");
$remote_addr = pack_sockaddr_in ($port, $remote_addr);
bless {
'sock' => $socket,
'sockfileno' => fileno ($socket),
'community' => $community,
'remote_hostname' => $remote_hostname,
'remote_addr' => $remote_addr,
'max_pdu_len' => $max_pdu_len,
'pdu_buffer' => '\0' x $max_pdu_len,
'request_id' => int (rand 0x80000000 + rand 0xffff),
'timeout' => $default_timeout,
'retries' => $default_retries,
'backoff' => $default_backoff,
'debug' => $default_debug,
};
}
sub sock { $_[0]->{sock} }
sub sockfileno { $_[0]->{sockfileno} }
sub remote_addr { $_[0]->{remote_addr} }
sub pdu_buffer { $_[0]->{pdu_buffer} }
sub max_pdu_len { $_[0]->{max_pdu_len} }
sub close
{
my($this) = shift;
close ($this->sock) || $this->error ("close: $!");
}
sub wrap_request
{
my($this) = shift;
my($request) = shift;
encode_sequence (encode_int ($this->snmp_version),
encode_string ($this->{community}),
$request)
|| return $this->ber_error ("wrapping up request PDU");
}
my @error_status_code = qw(noError tooBig noSuchName badValue readOnly
genErr noAccess wrongType wrongLength
wrongEncoding wrongValue noCreation
inconsistentValue resourceUnavailable
commitFailed undoFailed authorizationError
notWritable inconsistentName);
sub unwrap_response_5
{
my($this,$response,$tag,$request_id,$oids,$community,@rest);
my ($error_status,$error_index,$snmpver);
($this,$response,$tag,$request_id,$oids) = @_;
($snmpver,$community,$request_id,$error_status,$error_index,@rest)
= decode_by_template ($response, "%{%i%s%*{%i%i%i%{%@",
$tag);
return $this->ber_error ("Error decoding response PDU")
unless defined $snmpver;
return $this->error ("Received SNMP response with unknown snmp-version field $snmpver")
unless $snmpver == $this->snmp_version;
if ($error_status != 0 || $error_index != 0) {
my ($oid, $errmsg);
$errmsg = $error_status_code[$error_status] || $error_status;
$oid = $oids->[$error_index-1]
if $error_index > 0 && $error_index-1 <= $#{$oids};
$oid = $oid->[0]
if ref($oid) eq 'ARRAY';
return $this->error ("Received SNMP response with error code\n"
." error status: $errmsg\n"
." index ".$error_index
.(defined($oid)
? " (OID: ".&BER::pretty_oid($oid).")"
: ""));
}
if ($this->{'debug'}) {
warn "$community != $this->{community}"
unless $SNMP_Session::suppress_warnings
|| $community eq $this->{community};
warn "$request_id != $this->{request_id}"
unless $SNMP_Session::suppress_warnings
|| $request_id == $this->{request_id};
}
return undef unless $community eq $this->{community};
return undef unless $request_id == $this->{request_id};
@rest;
}
sub send_query
{
my($this) = shift;
my($query) = shift;
send ($this->sock,$query,0,$this->remote_addr);
}
sub receive_response_2
{
my $this = shift;
my $response_tag = shift;
my $oids = shift;
my($remote_addr);
$remote_addr = recv ($this->sock,$this->{'pdu_buffer'},$this->max_pdu_len,0);
return 0 unless $remote_addr;
my $response = $this->{'pdu_buffer'};
##
## Check whether the response came from the address we've sent the
## request to. If this is not the case, we should probably ignore
## it, as it may relate to another request.
##
if ($this->{'debug'} && $remote_addr ne $this->{'remote_addr'}) {
warn "Response came from ".&pretty_address ($remote_addr)
.", not ".&pretty_address($this->{'remote_addr'})
unless $SNMP_Session::suppress_warnings;
}
my @unwrapped = ();
@unwrapped = $this->unwrap_response_5 ($response, $response_tag, $this->{"request_id"}, $oids);
if (!defined $unwrapped[0]) {
$this->{'unwrapped'} = undef;
return 0;
}
$this->{'unwrapped'} = \@unwrapped;
return length $this->pdu_buffer;
}
sub pretty_address
{
my($addr) = shift;
my($port,$ipaddr) = unpack_sockaddr_in($addr);
return sprintf ("[%s].%d",inet_ntoa($ipaddr),$port);
}
sub describe
{
my($this) = shift;
print $this->to_string (),"\n";
}
sub to_string
{
my($this) = shift;
my ($class,$prefix);
$class = ref($this);
$prefix = ' ' x (length ($class) + 2);
($class." (remote host: \"".$this->{remote_hostname}
."\" ".&pretty_address ($this->remote_addr)."\n"
.$prefix." community: \"".$this->{'community'}."\"\n"
.$prefix." request ID: ".$this->{'request_id'}."\n"
.$prefix."PDU bufsize: ".$this->{'max_pdu_len'}." bytes\n"
.$prefix." timeout: ".$this->{timeout}."s\n"
.$prefix." retries: ".$this->{retries}."\n"
.$prefix." backoff: ".$this->{backoff}.")");
## sprintf ("SNMP_Session: %s (size %d timeout %g)",
## &pretty_address ($this->remote_addr),$this->max_pdu_len,
## $this->timeout);
}
1;
|