NSNMP/Simple.pm

filter: Statementstmt 99.0% 103 / 104 Branchbran 97.2% 35 / 36 Conditioncond 91.6% 11 / 12 MC/DCmcdc 71.4% 5 / 7 Subroutinesub 95.2% 20 / 21 Podpod 60.0% 3 / 5 totaltotal 95.6% 177 / 185 CC 23 SCAR 17.2
CC
23
Cov
98%
_synchronous_request_response
13.0
get_table
5.0
decode_int
4.0
CRAP 5.6
↑ Summary NSNMP/Agent.pm »
1 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 package NSNMP::Simple;
3 # Copyright (c) 2003-2004 AirWave Wireless, Inc.
4  
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8  
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
11 # disclaimer.
12 # 2. Redistributions in binary form must reproduce the above
13 # copyright notice, this list of conditions and the following
14 # disclaimer in the documentation and/or other materials provided
15 # with the distribution.
16 # 3. The name of the author may not be used to endorse or
17 # promote products derived from this software without specific
18 # prior written permission.
19  
20 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
21 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
24 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
26 # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28 # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 1 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 1 ▶use NSNMP;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 1 ▶use NSNMP::Mapper;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 1 ▶use vars qw($error $error_status $socket);
Subroutine BEGIN: called CC=1 SCAR=0.0
35 # these are negative so as not to collide with SNMP protocol error numbers,
36 # which count up from 1
37 1 ▶use constant noResponse => -1;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 1 ▶use constant badHostName => -2;
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 =head1 NAME
41  
42 NSNMP::Simple - simple interface to get and set synchronously
43  
44 =head1 SYNOPSIS
45  
46 my $sysnameoid = '1.3.6.1.2.1.1.5.0';
47 my $hostname = NSNMP::Simple->get('127.0.0.1', $sysnameoid);
48 die $NSNMP::Simple::error unless defined $hostname;
49 NSNMP::Simple->set('127.0.0.1', $sysnameoid, NSNMP::OCTET_STRING,
50 'thor.cs.cmu.edu', community => 'CMUprivate')
51 or die $NSNMP::Simple::error;
52 my %sysoids = NSNMP::Simple->get_table('127.0.0.1', '1.3.6.1.2.1');
53  
54 =head1 DESCRIPTION
55  
56 NSNMP::Simple lets you get or set a single OID via SNMP with a single
57 line of code. It's easier to use, and roughly an order of magnitude
58 faster, than L<Net::SNMP|Net::SNMP> 4.1.2, but Net::SNMP is still much
59 more mature and complete. I don't presently recommend using
60 NSNMP::Simple in production code.
61  
62 =head1 MODULE CONTENTS
63  
64 =cut
65  
66 # some speed costs on my 500MHz PIII laptop:
67 # it takes:
68 # 3 microseconds to do a function call and return
69 # 2 microseconds to do a hash lookup on a 20char string
70 # 50 microseconds in the kernel to send a packet and receive a response
71 # 600 microseconds to encode the packet, send it, and receive and
72 # decode the response (in user time) (getsysname-lots.pl)
73 # 150 microseconds to do the socket, address, timeout, and error-status
74 # checking
75 # this module does
76 # another 40 microseconds to do the request_id handling (in the normal case:
77 # request ID matches)
78 # a negligible amount of time to handle retry logic
79 # encoding and decoding of non-OCTET_STRING values
80 # all in all: about 1250 microseconds per request-response pair with this
81 # module
82 # although I still haven't implemented traps, v2 and v3, and handling of
83 # failure to socket; all of these will slow this module down more.
84  
85 # XXX refactor this a little more
86  
87 1 my ($nfound, $timeleft);
88 717 ▶sub _read_timeout {
Subroutine _read_timeout: called CC=1 SCAR=0.0
89 717 my ($fh, $timeout) = @_;
90 717 my $rin = '';
91 717 vec($rin, fileno($fh), 1) = 1;
92 717 return select($rin, undef, undef, $timeout);
93 }
94  
95 13 ▶sub _remember_error {
Subroutine _remember_error: called CC=1 SCAR=0.0
96 13 my ($response_decoded) = @_;
97 13 $error_status = $response_decoded->error_status;
98 13 my $error_name = NSNMP->error_description($error_status);
99 13 $error = "Received $error_name($error_status) error-status at error-index "
100 . $response_decoded->error_index;
101 13 return undef;
102 }
103  
104 1 my $request_id = 'aaaa';
105  
106 1 my $response;
107 705 ▶sub _synchronous_request_response {
Subroutine _synchronous_request_response: called CC=13 SCAR=25.7
108 705 my ($host, %args) = @_;
109 705 ▶ $socket ||= IO::Socket::INET->new(Proto => 'udp'); # XXX error check
Condition66%2/3
$NSNMP::Simple::socket ||= "IO::Socket::INET"->new("Proto", "udp")
l!l&&r!l&&!r
70410
MC/DC0%0/2
$NSNMP::Simple::socket ||= "IO::Socket::INET"->new("Proto", "udp")
$NSNMP::Simple::socket "IO::Socket::INET"->new("Proto", "udp")
Truth table66%2/3
A ||= B
A= $NSNMP::Simple::socketB= "IO::Socket::INET"->new("Proto", "udp")
ABresult
1X1
011
000
110 705 my $port = 161; # XXX test
111 705 ▶ $port = $1 if $host =~ s/:(\d+)\z//;
Branch: 1 branch
BranchTrueFalseTotal
if $host =~ s/:(\d+)\z// 704 1 705
112 705 my $iaddr = Socket::inet_aton($host);
113 705 ▶ if (not defined $iaddr) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $iaddr) 2 703 705
114 2 $error = "Unable to resolve destination address '$host'";
115 2 $error_status = badHostName;
116 2 return undef;
117 }
118  
119 # This method of picking request IDs has the following nice properties:
120 # - there are 450 000 request IDs available
121 # - they're always positive, so if they get sign-extended, it's always
122 # with 0s
123 # - they can never be represented in less than 4 bytes
124 # - it's relatively fast
125 703 $request_id++;
126 703 ▶ $request_id = substr($request_id, 1) if length($request_id) > 4;
Branch: 1 branch
BranchTrueFalseTotal
if length $request_id > 4 0 703 703
127  
128 703 ▶ my $tries = 1 + (exists $args{retries} ? $args{retries} : 1);
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'retries'} ? : 8 695 703
129 703 ▶ try: while ($tries--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tries--) 709 7 716
130 709 send $socket, NSNMP->encode(request_id => $request_id, %args), 0,
131 scalar Socket::sockaddr_in($port, $iaddr); # XXX err handling: bad port?
132  
133 709 ▶ my $timeout = (exists $args{timeout} ? $args{timeout} : 5);
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'timeout'} ? : 22 687 709
134 709 for (;;) {
135 # perldoc -f select says, "Most systems do not bother to return
136 # anything useful in $timeleft." Well, Linux 2.4 does; so if
137 # you're using something that doesn't, upgrade.
138 717 ((my $success), $timeout) = _read_timeout($socket, $timeout);
139 717 ▶ next try unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 13 704 717
140  
141 704 $socket->recv($response, 65536, 0); # XXX error handling?
142 704 my $resp_decoded = NSNMP->decode($response);
143 704 ▶ if (not $resp_decoded or $resp_decoded->request_id ne $request_id
Branch: 1 branch
BranchTrueFalseTotal
if (not $resp_decoded or $resp_decoded->request_id ne $request_id and not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/) 8 696 704
Condition100%6/6
not $resp_decoded or $resp_decoded->request_id ne $request_id and not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/
l!l&&r!l&&!r
53696
$resp_decoded->request_id ne $request_id and not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/
!ll&&!rl&&r
69513
MC/DC100%3/3
not $resp_decoded or $resp_decoded->request_id ne $request_id and not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/
not $resp_decoded $resp_decoded->request_id ne $request_id not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/
Truth table100%4/4
not(A) or B and not(C)
A= not $resp_decodedB= $resp_decoded->request_id ne $request_idC= not $resp_decoded->request_id =~ /\A\0+\Q$request_id\E\z/
ABCresult
1XX1
0111
00X0
0100
144 and $resp_decoded->request_id !~ /\A\0+\Q$request_id\E\z/) {
145 # ignore it
146 8 next;
147 }
148 696 ▶ return _remember_error($resp_decoded) if $resp_decoded->error_status;
Branch: 1 branch
BranchTrueFalseTotal
if $resp_decoded->error_status 13 683 696
149 683 ($error, $error_status) = (undef, undef);
150 683 return $resp_decoded;
151 }
152 }
153 7 ($error, $error_status) =
154 ("No response from remote host '$host'", noResponse);
155 7 return undef;
156 }
157  
158 40 ▶sub decode_int {
Subroutine decode_int: called CC=4 SCAR=13.9
Pod undocumented
159 40 my ($intstr) = @_;
160 40 ▶ my $padchar = ("\0" eq ($intstr & "\x80")) ? "\0" : "\377";
Branch: 1 branch
BranchTrueFalseTotal
"\000" eq ($intstr & "\200") ? : 33 7 40
161 40 ▶ $intstr = substr($intstr, length($intstr) - 4) if length($intstr) > 4;
Branch: 1 branch
BranchTrueFalseTotal
if length $intstr > 4 5 35 40
162 40 my $padded = $padchar x (4 - length($intstr)) . $intstr;
163 40 my $num = unpack "N", $padded;
164 40 ▶ $num -= 4294967296 if $padchar ne "\0"; # unpack gave us unsigned
Branch: 1 branch
BranchTrueFalseTotal
if $padchar ne "\0" 7 33 40
165 40 return $num;
166 }
167  
168 my %decoders = (
169 NSNMP::INTEGER => \&decode_int,
170 NSNMP::Counter32 => \&decode_int,
171 NSNMP::Gauge32 => \&decode_int,
172 NSNMP::TimeTicks => \&decode_int,
173 625 ▶ NSNMP::OCTET_STRING => sub { $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
174 2 ▶ NSNMP::IpAddress => sub { join '.', unpack "C*", $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
175 1 ▶ NSNMP::OBJECT_IDENTIFIER => sub { NSNMP->decode_oid($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
176 1 );
177  
178 11 ▶sub encode_int {
Subroutine encode_int: called CC=3 SCAR=11.0
Pod undocumented
179 11 my ($int) = @_;
180 11 my $rv = pack "N", $int;
181 11 ▶ return "\0$rv" if $int >= 0 and (($rv & "\x80") ne "\00");
Branch: 1 branch
BranchTrueFalseTotal
if $int >= 0 and ($rv & "\200") ne "\0" 1 10 11
Condition100%3/3
$int >= 0 and ($rv & "\200") ne "\0"
!ll&&!rl&&r
191
MC/DC100%2/2
$int >= 0 and ($rv & "\200") ne "\0"
$int >= 0 ($rv & "\200") ne "\0"
Truth table100%3/3
A and B
A= $int >= 0B= ($rv & "\200") ne "\0"
ABresult
0X0
100
111
182 10 return $rv;
183 }
184  
185 my %encoders = (
186 NSNMP::INTEGER => \&encode_int,
187 NSNMP::Counter32 => \&encode_int, # XXX test
188 NSNMP::Gauge32 => \&encode_int,
189 NSNMP::TimeTicks => \&encode_int, # XXX test
190 4 ▶ NSNMP::OCTET_STRING => sub { $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
191 1 ▶ NSNMP::IpAddress => sub { pack "C*", split /\./, $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
192 0 ▶ NSNMP::OBJECT_IDENTIFIER => sub { NSNMP->encode_oid($_[0]) }, # XXX test
Subroutine __ANON__: not called CC=1 SCAR=6.9
193 1 );
194  
195 =head2 NSNMP::Simple->get($agent, $oid, %args)
196  
197 Returns the value of C<$oid> on the SNMP agent at C<$agent>, which can
198 be a hostname or an IP address, optionally followed by a colon and a
199 numeric port number, which defaults to 161, the default SNMP port.
200  
201 C<%args> can contain any or all of the following:
202  
203 =over
204  
205 =item C<version =E<gt> $ver>
206  
207 $ver is an SNMP version number (1 or 2 --- 3 isn't yet supported ---
208 see L</BUGS>). Default is 1.
209  
210 =item C<community =E<gt> $comm>
211  
212 Specifies the community string. Default is C<public>.
213  
214 =item C<retries =E<gt> $retries>
215  
216 Specifies retries. Default is 1 --- that is, two tries. Retries are
217 evenly spaced.
218  
219 =item C<timeout =E<gt> $timeout>
220  
221 Specifies a timeout in (possibly fractional) seconds. Default is 5.0.
222  
223 =back
224  
225 Translates the value of C<$oid> into a Perlish value, so, for example,
226 an INTEGER OID whose value is 1 will be returned as "1", not "\001".
227 IpAddresses are translated to dotted-quad notation, integer-like types
228 are translated to integers, and OCTET STRINGS, OPAQUES, and
229 NsapAddresses are left alone.
230  
231 It doesn't return the type of the value at all.
232  
233 In case of failure, it returns C<undef> and sets
234 C<$NSNMP::Simple::error> to a string describing the error in English,
235 in the same format as Net::SNMP's error messages.
236  
237 =cut
238  
239 # Note that I wanted to put that list of %args first in the text, as a
240 # bulleted list. But pod2html barfed on the required blank line after
241 # the =item * line, so I gave up on bulleted lists in POD. Yick.
242  
243 52 ▶sub get {
Subroutine get: called CC=2 SCAR=6.9
Pod documented
244 52 my ($class, $host, $oid, %args) = @_;
245 52 my $response_decoded =
246 _synchronous_request_response($host,
247 type => NSNMP::GET_REQUEST,
248 varbindlist => [[NSNMP->encode_oid($oid),
249 NSNMP::NULL, '']],
250 %args);
251 52 ▶ return undef unless $response_decoded;
Branch: 1 branch
BranchTrueFalseTotal
unless $response_decoded 8 44 52
252 44 my $varbind = ($response_decoded->varbindlist)[0];
253 44 return $decoders{$varbind->[1]}->($varbind->[2]);
254 }
255  
256 =head2 NSNMP::Simple->set($agent, $oid, $type, $value, %args)
257  
258 Sets the value of C<$oid> on the SNMP agent at C<$agent> to the value
259 C<$value>, as BER-encoded type C<$type>. Returns true on success,
260 false on failure, and also sets C<$NSNMP::Simple::error> on failure.
261 Accepts the same C<%args> as C<-E<gt>get>.
262  
263 =cut
264  
265 16 ▶sub set {
Subroutine set: called CC=1 SCAR=0.0
Pod documented
266 16 my ($class, $host, $oid, $type, $value, %args) = @_;
267 return !!_synchronous_request_response($host,
268 type => NSNMP::SET_REQUEST,
269 varbindlist => [[NSNMP->encode_oid($oid),
270 16 $type, $encoders{$type}->($value)]],
271 %args);
272 }
273  
274 =head2 NSNMP::Simple->get_table($agent, $oid, %args)
275  
276 Gets the values of all OIDs under C<$oid> on the SNMP agent at
277 C<$agent>. Returns a list of alternating OIDs and values, in OID
278 lexical order; you can stuff it into a hash if you don't care about
279 the order. If there are no OIDs under C<$oid>, returns an empty list
280 and clears C<$NSNMP::Simple::error>. Note that this can be caused
281 either by misspelling the OID or by actually having an empty table,
282 and there's no way to tell which. (See the note in L<SNMP/BUGS> about
283 the SNMP protocol design.)
284  
285 If any of the component SNMP requests returns an unexpected error,
286 C<get_table> returns an empty list and sets C<$NSNMP::Simple::error>.
287  
288 Note for Net::SNMP users: C<get_table> does not set
289 C<$NSNMP::Simple::error> on an empty table, but Net::SNMP's
290 C<get_table> does.
291  
292 Accepts the same C<%args> as C<-E<gt>get>.
293  
294 The OIDs in the returned list are spelled in ASCII with or without a
295 leading dot, depending on whether or not C<$oid> has a leading dot.
296  
297 =cut
298  
299 13 ▶sub get_table {
Subroutine get_table: called CC=5 SCAR=16.1
Pod documented
300 13 my ($class, $host, $oid, %args) = @_;
301 13 my @rv;
302 my $response;
303 13 my $mapper = NSNMP::Mapper->new($oid => 1);
304 13 my $initial_dot = $oid =~ /\A\./;
305 13 my $encoded_oid = NSNMP->encode_oid($oid);
306 13 for (;;) {
307 637 $response = _synchronous_request_response($host,
308 type => NSNMP::GET_NEXT_REQUEST,
309 varbindlist => [[$encoded_oid, NSNMP::NULL, '']],
310 %args,
311 );
312 637 ▶ if (not defined $response) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response) 12 625 637
313 12 ▶ if ($error_status eq NSNMP::noSuchName) {
Branch: 1 branch
BranchTrueFalseTotal
if ($NSNMP::Simple::error_status eq 2) 10 2 12
314 # end of MIB
315 10 ($error_status, $error) = (undef, undef);
316 10 return @rv;
317 }
318 2 return ();
319 }
320 625 my @varbindlist = $response->varbindlist;
321 625 $encoded_oid = $varbindlist[0][0];
322 625 $oid = NSNMP->decode_oid($varbindlist[0][0]);
323 625 ▶ return @rv unless ($mapper->map($oid))[0];
Branch: 1 branch
BranchTrueFalseTotal
unless ($mapper->map($oid))[0] 1 624 625
324 push @rv, ($initial_dot ? ".$oid" : $oid),
325 624 ▶ $decoders{$varbindlist[0][1]}->($varbindlist[0][2]);
Branch: 1 branch
BranchTrueFalseTotal
$initial_dot ? : 620 4 624
326 }
327 }
328  
329 =head2 $error
330  
331 C<$NSNMP::Simple::error> is undef after any successful subroutine
332 call on this module, and an English string describing the error after
333 any unsuccessful subroutine call.
334  
335 C<$NSNMP::Simple::error_status> is undef when C<$error> is undef,
336 and when C<$error> is defined, C<$error_status> contains an integer
337 describing the type of error. This may be a raw SNMP C<error-status>
338 code, such as NSNMP::noSuchName, or it may be one of the following
339 values:
340  
341 =over
342  
343 =item NSNMP::Simple::noResponse
344  
345 This code means that the remote host sent no response, or at least, no
346 response we could decode, so we timed out. (The timeout value is
347 configurable, as described earlier.)
348  
349 =item NSNMP::Simple::badHostName
350  
351 This code means that C<NSNMP::Simple> couldn't resolve the hostname
352 given. It might be malformed or a nonexistent DNS name, or it might
353 be an existing DNS name, but DNS might be broken for some other
354 reason.
355  
356 =back
357  
358 =head1 FILES
359  
360 None.
361  
362 =head1 AUTHOR
363  
364 Kragen Sitaker E<lt>kragen@pobox.comE<gt>
365  
366 =head1 BUGS
367  
368 This module uses L<the SNMP module|SNMP>, so it inherits most of the
369 bugs of that module.
370  
371 It's still too slow. On my 500MHz laptop, it can SNMP-walk 5675 OIDs
372 in about 7.2 CPU seconds, for less than 800 OIDs per second. ucd-snmp
373 (now confusingly called net-snmp, not to be confused with Net::SNMP)
374 takes 1.8 CPU seconds to perform the same task. That's four times as
375 fast. On the other hand, Net::SNMP manages about 110 OIDs per second,
376 seven times slower still.
377  
378 =cut
379  
380 1 1;
↑ Summary NSNMP/Agent.pm »