BER.pm untested

filter: Statementstmt 0.0% 0 / 420 Branchbran 0.0% 0 / 188 Conditioncond 0.0% 0 / 99 Subroutinesub 0.0% 0 / 118 Podpod 0.0% 0 / 113 totaltotal 0.0% 0 / 938 CC 95 SCAR 56.1
CC
95
Cov
0%
decode_by_template_2
1260.0
encode_oid
110.0
pretty_print
110.0
CRAP 274.1
1 ### -*- mode: Perl -*-
2 ######################################################################
3 ### BER (Basic Encoding Rules) encoding and decoding.
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 ### This module implements encoding and decoding of ASN.1-based data
12 ### structures using the Basic Encoding Rules (BER). Only the subset
13 ### necessary for SNMP is implemented.
14 ######################################################################
15 ### Create by: See AUTHORS below
16 ######################################################################
17  
18 package BER;
19  
20 =head1 NAME
21  
22 BER - Basic Encoding Rules (BER) of Abstract Syntax Notation One (ASN.1)
23  
24 =head1 SYNOPSIS
25  
26 use BER;
27 $encoded = encode_sequence (encode_int (123), encode_string ("foo"));
28 ($i, $s) = decode_by_template ($encoded, "%{%i%s");
29 # $i will now be 123, $s the string "foo".
30  
31 =head1 DESCRIPTION
32  
33 This is a simple library to encode and decode data using the Basic
34 Encoding Rules (BER) of Abstract Syntax Notation One (ASN.1). It does
35 not claim to be a complete implementation of the standard, but
36 implements enough of the BER standard to encode and decode SNMP
37 messages.
38  
39 =cut
40  
41 require 5.002;
42  
43 use strict;
44 use vars qw(@ISA @EXPORT $VERSION $pretty_print_timeticks
45 %pretty_printer %default_printer $errmsg);
46 use Exporter;
47  
48 $VERSION = '1.14';
49  
50 @ISA = qw(Exporter);
51  
52 @EXPORT = qw(context_flag constructor_flag
53 encode_int encode_int_0 encode_null encode_oid
54 encode_sequence encode_tagged_sequence
55 encode_string encode_ip_address encode_timeticks
56 encode_uinteger32 encode_counter32 encode_counter64
57 encode_gauge32
58 decode_sequence decode_by_template
59 pretty_print pretty_print_timeticks
60 hex_string hex_string_of_type
61 encoded_oid_prefix_p errmsg
62 register_pretty_printer unregister_pretty_printer);
63  
64 =head1 VARIABLES
65  
66 =cut
67  
68 =head2 $pretty_print_timeticks (default: 1)
69  
70 If non-zero (the default), C<pretty_print> will convert TimeTicks to
71 "human readable" strings containing days, hours, minutes and seconds.
72  
73 If the variable is zero, C<pretty_print> will simply return an
74 unsigned integer representing hundredths of seconds. If you prefer
75 this, bind C<$pretty_print_timeticks> to zero.
76  
77 =cut
78  
79 $pretty_print_timeticks = 1;
80  
81 =head2 $errmsg - error message from last failed operation.
82  
83 When they encounter errors, the routines in this module will generally
84 return C<undef>) and leave an informative error message in
85 C<$errmsg>).
86  
87 =cut
88  
89 ### Prototypes
90 sub encode_header ($$);
91 sub encode_int_0 ();
92 sub encode_int ($);
93 sub encode_oid (@);
94 sub encode_null ();
95 sub encode_sequence (@);
96 sub encode_tagged_sequence ($@);
97 sub encode_string ($);
98 sub encode_ip_address ($);
99 sub encode_timeticks ($);
100 sub pretty_print ($);
101 sub pretty_using_decoder ($$);
102 sub pretty_string ($);
103 sub pretty_intlike ($);
104 sub pretty_unsignedlike ($);
105 sub pretty_oid ($);
106 sub pretty_uptime ($);
107 sub pretty_uptime_value ($);
108 sub pretty_ip_address ($);
109 sub pretty_generic_sequence ($);
110 sub register_pretty_printer ($);
111 sub unregister_pretty_printer ($);
112 sub hex_string ($);
113 sub hex_string_of_type ($$);
114 sub decode_oid ($);
115 sub decode_by_template;
116 sub decode_by_template_2;
117 sub decode_sequence ($);
118 sub decode_int ($);
119 sub decode_intlike ($);
120 sub decode_unsignedlike ($);
121 sub decode_intlike_s ($$);
122 sub decode_string ($);
123 sub decode_length ($@);
124 sub encoded_oid_prefix_p ($$);
125 sub decode_subid ($$$);
126 sub decode_generic_tlv ($);
127 sub error (@);
128 sub template_error ($$$);
129  
130 sub version () { $VERSION; }
131  
132 =head1 METHODS
133 =cut
134  
135 ### Flags for different types of tags
136  
137 sub universal_flag { 0x00 }
138 sub application_flag { 0x40 }
139 sub context_flag { 0x80 }
140 sub private_flag { 0xc0 }
141  
142 sub primitive_flag { 0x00 }
143 sub constructor_flag { 0x20 }
144  
145 ### Universal tags
146  
147 sub boolean_tag { 0x01 }
148 sub int_tag { 0x02 }
149 sub bit_string_tag { 0x03 }
150 sub octet_string_tag { 0x04 }
151 sub null_tag { 0x05 }
152 sub object_id_tag { 0x06 }
153 sub sequence_tag { 0x10 }
154 sub set_tag { 0x11 }
155 sub uptime_tag { 0x43 }
156  
157 ### Flag for length octet announcing multi-byte length field
158  
159 sub long_length { 0x80 }
160  
161 ### SNMP specific tags
162  
163 sub snmp_ip_address_tag { 0x00 | application_flag () }
164 sub snmp_counter32_tag { 0x01 | application_flag () }
165 sub snmp_gauge32_tag { 0x02 | application_flag () }
166 sub snmp_timeticks_tag { 0x03 | application_flag () }
167 sub snmp_opaque_tag { 0x04 | application_flag () }
168 sub snmp_nsap_address_tag { 0x05 | application_flag () }
169 sub snmp_counter64_tag { 0x06 | application_flag () }
170 sub snmp_uinteger32_tag { 0x07 | application_flag () }
171  
172 ## Error codes (SNMPv2 and later)
173 ##
174 sub snmp_nosuchobject { context_flag () | 0x00 }
175 sub snmp_nosuchinstance { context_flag () | 0x01 }
176 sub snmp_endofmibview { context_flag () | 0x02 }
177  
178 ### pretty-printer initialization code. Create a hash with
179 ### the most common types of pretty-printer routines.
180  
181 BEGIN {
182 $default_printer{int_tag()} = \&pretty_intlike;
183 $default_printer{snmp_counter32_tag()} = \&pretty_unsignedlike;
184 $default_printer{snmp_gauge32_tag()} = \&pretty_unsignedlike;
185 $default_printer{snmp_counter64_tag()} = \&pretty_unsignedlike;
186 $default_printer{snmp_uinteger32_tag()} = \&pretty_unsignedlike;
187 $default_printer{octet_string_tag()} = \&pretty_string;
188 $default_printer{object_id_tag()} = \&pretty_oid;
189 $default_printer{snmp_ip_address_tag()} = \&pretty_ip_address;
190  
191 %pretty_printer = %default_printer;
192 }
193  
194 #### Encoding
195  
196 sub encode_header ($$) {
197 my ($type,$length) = @_;
198 return pack ("CC", $type, $length) if $length < 128;
199 return pack ("CCC", $type, long_length | 1, $length) if $length < 256;
200 return pack ("CCn", $type, long_length | 2, $length) if $length < 65536;
201 return error ("Cannot encode length $length yet");
202 }
203  
204 =head2 encode_int_0() - encode the integer 0.
205  
206 This is functionally identical to C<encode_int(0)>.
207  
208 =cut
209  
210 sub encode_int_0 () {
211 return pack ("CCC", 2, 1, 0);
212 }
213  
214 =head2 encode_int() - encode an integer using the generic
215 "integer" type tag.
216  
217 =cut
218  
219 sub encode_int ($) {
220 return encode_intlike ($_[0], int_tag);
221 }
222  
223 =head2 encode_uinteger32() - encode an integer using the SNMP
224 UInteger32 tag.
225  
226 =cut
227  
228 sub encode_uinteger32 ($) {
229 return encode_intlike ($_[0], snmp_uinteger32_tag);
230 }
231  
232 =head2 encode_counter32() - encode an integer using the SNMP
233 Counter32 tag.
234  
235 =cut
236  
237 sub encode_counter32 ($) {
238 return encode_intlike ($_[0], snmp_counter32_tag);
239 }
240  
241 =head2 encode_counter64() - encode an integer using the SNMP
242 Counter64 tag.
243  
244 =cut
245  
246 sub encode_counter64 ($) {
247 return encode_intlike ($_[0], snmp_counter64_tag);
248 }
249  
250 =head2 encode_gauge32() - encode an integer using the SNMP Gauge32
251 tag.
252  
253 =cut
254  
255 sub encode_gauge32 ($) {
256 return encode_intlike ($_[0], snmp_gauge32_tag);
257 }
258  
259 ### encode_intlike ($int, $tag)
260 ###
261 ### Generic function to BER-encode an arbitrary integer using a given
262 ### tag. This function can handle large integers. It doesn't check
263 ### whether the integer is in a suitable range for the given type tag
264 ### - that is expected to be done by the caller.
265 ###
266 sub encode_intlike ($$) {
267 my ($int, $tag)=@_;
268 my ($sign, $val, @vals);
269 $sign = ($int >= 0) ? 0 : 0xff;
270 if (ref $int && $int->isa ("Math::BigInt")) {
271 for(;;) {
272 $val = $int->copy()->bmod (256);
273 unshift(@vals, $val);
274 return encode_header ($tag, $#vals + 1).pack ("C*", @vals)
275 if ($int >= -128 && $int < 128);
276 $int->bsub ($sign)->bdiv (256);
277 }
278 } else {
279 for(;;) {
280 $val = $int & 0xff;
281 unshift(@vals, $val);
282 return encode_header ($tag, $#vals + 1).pack ("C*", @vals)
283 if ($int >= -128 && $int < 128);
284 $int -= $sign, $int = int($int / 256);
285 }
286 }
287 }
288  
289 =head2 encode_oid() - encode an object ID, passed as a list of
290 sub-IDs.
291  
292 $encoded = encode_oid (1,3,6,1,...);
293 =cut
294  
295 sub encode_oid (@) {
296 my @oid = @_;
297 my ($result,$subid);
298  
299 $result = '';
300 ## Ignore leading empty sub-ID. The favourite reason for
301 ## those to occur is that people cut&paste numeric OIDs from
302 ## CMU/UCD SNMP including the leading dot.
303 shift @oid if $oid[0] eq '';
304  
305 return error ("Object ID too short: ", join('.',@oid))
306 if $#oid < 1;
307 ## The first two subids in an Object ID are encoded as a single
308 ## byte in BER, according to a funny convention. This poses
309 ## restrictions on the ranges of those subids. In the past, I
310 ## didn't check for those. But since so many people try to use
311 ## OIDs in CMU/UCD SNMP's format and leave out the mib-2 or
312 ## enterprises prefix, I introduced this check to catch those
313 ## errors.
314 ##
315 return error ("first subid too big in Object ID ", join('.',@oid))
316 if $oid[0] > 2;
317 $result = shift (@oid) * 40;
318 $result += shift @oid;
319 return error ("second subid too big in Object ID ", join('.',@oid))
320 if $result > 255;
321 $result = pack ("C", $result);
322 foreach $subid (@oid) {
323 if ( ($subid>=0) && ($subid<128) ){ #7 bits long subid
324 $result .= pack ("C", $subid);
325 } elsif ( ($subid>=128) && ($subid<16384) ){ #14 bits long subid
326 $result .= pack ("CC", 0x80 | $subid >> 7, $subid & 0x7f);
327 }
328 elsif ( ($subid>=16384) && ($subid<2097152) ) {#21 bits long subid
329 $result .= pack ("CCC",
330 0x80 | (($subid>>14) & 0x7f),
331 0x80 | (($subid>>7) & 0x7f),
332 $subid & 0x7f);
333 } elsif ( ($subid>=2097152) && ($subid<268435456) ){ #28 bits long subid
334 $result .= pack ("CCCC",
335 0x80 | (($subid>>21) & 0x7f),
336 0x80 | (($subid>>14) & 0x7f),
337 0x80 | (($subid>>7) & 0x7f),
338 $subid & 0x7f);
339 } elsif ( ($subid>=268435456) && ($subid<4294967296) ){ #32 bits long subid
340 $result .= pack ("CCCCC",
341 0x80 | (($subid>>28) & 0x0f), #mask the bits beyond 32
342 0x80 | (($subid>>21) & 0x7f),
343 0x80 | (($subid>>14) & 0x7f),
344 0x80 | (($subid>>7) & 0x7f),
345 $subid & 0x7f);
346 } else {
347 return error ("Cannot encode subid $subid");
348 }
349 }
350 encode_header (object_id_tag, length $result).$result;
351 }
352  
353 =head2 encode_null() - encode a null object.
354  
355 This is used e.g. in binding lists for variables that don't have a
356 value (yet)
357  
358 =cut
359  
360 sub encode_null () { encode_header (null_tag, 0); }
361  
362 =head2 encode_sequence()
363  
364 =head2 encode_tagged_sequence()
365  
366 $encoded = encode_sequence (encoded1, encoded2, ...);
367 $encoded = encode_tagged_sequence (tag, encoded1, encoded2, ...);
368  
369 Take already encoded values, and extend them to an encoded sequence.
370 C<encoded_sequence> uses the generic sequence tag, while with
371 C<encode_tagged_sequence> you can specify your own tag.
372 =cut
373  
374 sub encode_sequence (@) { encode_tagged_sequence (sequence_tag, @_); }
375  
376 sub encode_tagged_sequence ($@) {
377 my ($tag,$result);
378  
379 $tag = shift @_;
380 $result = join '',@_;
381 return encode_header ($tag | constructor_flag, length $result).$result;
382 }
383  
384 =head2 encode_string() - encode a Perl string as an OCTET STRING.
385 =cut
386  
387 sub encode_string ($) {
388 my ($string)=@_;
389 return encode_header (octet_string_tag, length $string).$string;
390 }
391  
392 =head2 encode_ip_address() - encode an IPv4 address.
393  
394 This can either be passed as a four-octet sequence in B<network byte
395 order>, or as a text string in dotted-quad notation,
396 e.g. "192.0.2.234".
397  
398 =cut
399  
400 sub encode_ip_address ($) {
401 my ($addr)=@_;
402 my @octets;
403  
404 if (length $addr == 4) {
405 ## Four bytes... let's suppose that this is a binary IP address
406 ## in network byte order.
407 return encode_header (snmp_ip_address_tag, length $addr).$addr;
408 } elsif (@octets = ($addr =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/)) {
409 return encode_ip_address (pack ("CCCC", @octets));
410 } else {
411 return error ("IP address must be four bytes long or a dotted-quad");
412 }
413 }
414  
415 =head2 encode_timeticks() - encode an integer as a C<TimeTicks>
416 object.
417  
418 The integer should count hundredths of a second since the epoch
419 defined by C<sysUpTime.0>.
420  
421 =cut
422  
423 sub encode_timeticks ($) {
424 my ($tt) = @_;
425 return encode_intlike ($tt, snmp_timeticks_tag);
426 }
427  
428 #### Decoding
429  
430 =head2 pretty_print() - convert an encoded byte sequence into
431 human-readable form.
432  
433 This function can be extended by registering pretty-printing methods
434 for specific type codes. Most BER type codes used in SNMP already
435 have such methods pre-registered by default. See
436 C<register_pretty_printer> for how new methods can be added.
437  
438 =cut
439  
440 sub pretty_print ($) {
441 my ($packet) = @_;
442 return undef unless defined $packet;
443 my $result = ord (substr ($packet, 0, 1));
444 if (exists ($pretty_printer{$result})) {
445 return &{$pretty_printer{$result}} ($packet);
446 }
447 return ($pretty_print_timeticks
448 ? pretty_uptime ($packet)
449 : pretty_unsignedlike ($packet))
450 if $result == uptime_tag;
451 return "(null)" if $result == null_tag;
452 return error ("Exception code: noSuchObject") if $result == snmp_nosuchobject;
453 return error ("Exception code: noSuchInstance") if $result == snmp_nosuchinstance;
454 return error ("Exception code: endOfMibView") if $result == snmp_endofmibview;
455  
456 # IlvJa
457 # pretty print sequences and their contents.
458  
459 my $ctx_cons_flags = context_flag | constructor_flag;
460  
461 if($result == (&constructor_flag | &sequence_tag) # sequence
462 || $result == (0 | $ctx_cons_flags) #get_request
463 || $result == (1 | $ctx_cons_flags) #getnext_request
464 || $result == (2 | $ctx_cons_flags) #response
465 || $result == (3 | $ctx_cons_flags) #set_request
466 || $result == (4 | $ctx_cons_flags) #trap_request
467 || $result == (5 | $ctx_cons_flags) #getbulk_request
468 || $result == (6 | $ctx_cons_flags) #inform_request
469 || $result == (7 | $ctx_cons_flags) #trap2_request
470 )
471 {
472 my $pretty_result = pretty_generic_sequence($packet);
473 $pretty_result =~ s/^/ /gm; #Indent.
474  
475 my $seq_type_desc =
476 {
477 (constructor_flag | sequence_tag) => "Sequence",
478 (0 | $ctx_cons_flags) => "GetRequest",
479 (1 | $ctx_cons_flags) => "GetNextRequest",
480 (2 | $ctx_cons_flags) => "Response",
481 (3 | $ctx_cons_flags) => "SetRequest",
482 (4 | $ctx_cons_flags) => "Trap",
483 (5 | $ctx_cons_flags) => "GetBulkRequest",
484 (6 | $ctx_cons_flags) => "InformRequest",
485 (7 | $ctx_cons_flags) => "SNMPv2-Trap",
486 (8 | $ctx_cons_flags) => "Report",
487 }->{($result)};
488  
489 return $seq_type_desc . "{\n" . $pretty_result . "\n}";
490 }
491  
492 return sprintf ("#<unprintable BER type 0x%x>", $result);
493 }
494  
495 sub pretty_using_decoder ($$) {
496 my ($decoder, $packet) = @_;
497 my ($decoded,$rest);
498 ($decoded,$rest) = &$decoder ($packet);
499 return error ("Junk after object") unless $rest eq '';
500 return $decoded;
501 }
502  
503 sub pretty_string ($) {
504 pretty_using_decoder (\&decode_string, $_[0]);
505 }
506  
507 sub pretty_intlike ($) {
508 my $decoded = pretty_using_decoder (\&decode_intlike, $_[0]);
509 $decoded;
510 }
511  
512 sub pretty_unsignedlike ($) {
513 return pretty_using_decoder (\&decode_unsignedlike, $_[0]);
514 }
515  
516 sub pretty_oid ($) {
517 my ($oid) = shift;
518 my ($result,$subid,$next);
519 my (@oid);
520 $result = ord (substr ($oid, 0, 1));
521 return error ("Object ID expected") unless $result == object_id_tag;
522 ($result, $oid) = decode_length ($oid, 1);
523 return error ("inconsistent length in OID") unless $result == length $oid;
524 @oid = ();
525 $subid = ord (substr ($oid, 0, 1));
526 push @oid, int ($subid / 40);
527 push @oid, $subid % 40;
528 $oid = substr ($oid, 1);
529 while ($oid ne '') {
530 $subid = ord (substr ($oid, 0, 1));
531 if ($subid < 128) {
532 $oid = substr ($oid, 1);
533 push @oid, $subid;
534 } else {
535 $next = $subid;
536 $subid = 0;
537 while ($next >= 128) {
538 $subid = ($subid << 7) + ($next & 0x7f);
539 $oid = substr ($oid, 1);
540 $next = ord (substr ($oid, 0, 1));
541 }
542 $subid = ($subid << 7) + $next;
543 $oid = substr ($oid, 1);
544 push @oid, $subid;
545 }
546 }
547 join ('.', @oid);
548 }
549  
550 sub pretty_uptime ($) {
551 my ($packet,$uptime);
552  
553 ($uptime,$packet) = &decode_unsignedlike (@_);
554 pretty_uptime_value ($uptime);
555 }
556  
557 sub pretty_uptime_value ($) {
558 my ($uptime) = @_;
559 my ($seconds,$minutes,$hours,$days,$result);
560 ## We divide the uptime by hundred since we're not interested in
561 ## sub-second precision.
562 $uptime = int ($uptime / 100);
563  
564 $days = int ($uptime / (60 * 60 * 24));
565 $uptime %= (60 * 60 * 24);
566  
567 $hours = int ($uptime / (60 * 60));
568 $uptime %= (60 * 60);
569  
570 $minutes = int ($uptime / 60);
571 $seconds = $uptime % 60;
572  
573 if ($days == 0){
574 $result = sprintf ("%d:%02d:%02d", $hours, $minutes, $seconds);
575 } elsif ($days == 1) {
576 $result = sprintf ("%d day, %d:%02d:%02d",
577 $days, $hours, $minutes, $seconds);
578 } else {
579 $result = sprintf ("%d days, %d:%02d:%02d",
580 $days, $hours, $minutes, $seconds);
581 }
582 return $result;
583 }
584  
585  
586 sub pretty_ip_address ($) {
587 my $pdu = shift;
588 my ($length, $rest);
589 return error ("IP Address tag (".snmp_ip_address_tag.") expected")
590 unless ord (substr ($pdu, 0, 1)) == snmp_ip_address_tag;
591 ($length,$pdu) = decode_length ($pdu, 1);
592 return error ("Length of IP address should be four")
593 unless $length == 4;
594 sprintf "%d.%d.%d.%d", unpack ("CCCC", $pdu);
595 }
596  
597 # IlvJa
598 # Returns a string with the pretty prints of all
599 # the elements in the sequence.
600 sub pretty_generic_sequence ($) {
601 my ($pdu) = shift;
602  
603 my $rest;
604  
605 my $type = ord substr ($pdu, 0 ,1);
606 my $flags = context_flag | constructor_flag;
607
608 return error (sprintf ("Tag 0x%x is not a valid sequence tag",$type))
609 unless ($type == (&constructor_flag | &sequence_tag) # sequence
610 || $type == (0 | $flags) #get_request
611 || $type == (1 | $flags) #getnext_request
612 || $type == (2 | $flags) #response
613 || $type == (3 | $flags) #set_request
614 || $type == (4 | $flags) #trap_request
615 || $type == (5 | $flags) #getbulk_request
616 || $type == (6 | $flags) #inform_request
617 || $type == (7 | $flags) #trap2_request
618 );
619
620 my $curelem;
621 my $pretty_result; # Holds the pretty printed sequence.
622 my $pretty_elem; # Holds the pretty printed current elem.
623 my $first_elem = 'true';
624
625 # Cut away the first Tag and Length from $packet and then
626 # init $rest with that.
627 (undef, $rest) = decode_length ($pdu, 1);
628 while($rest)
629 {
630 ($curelem,$rest) = decode_generic_tlv($rest);
631 $pretty_elem = pretty_print($curelem);
632
633 $pretty_result .= "\n" if not $first_elem;
634 $pretty_result .= $pretty_elem;
635
636 # The rest of the iterations are not related to the
637 # first element of the sequence so..
638 $first_elem = '' if $first_elem;
639 }
640 return $pretty_result;
641 }
642  
643 =head2 hex_string() - convert OCTET STRING to hexadecimal notation.
644  
645 =cut
646  
647 sub hex_string ($) {
648 hex_string_of_type ($_[0], octet_string_tag);
649 }
650  
651 =head2 hex_string_of_type() - convert octet string to hex, and check
652 type against given tag.
653  
654 =cut
655  
656 sub hex_string_of_type ($$) {
657 my ($pdu, $wanted_type) = @_;
658 my ($length);
659 return error ("BER tag ".$wanted_type." expected")
660 unless ord (substr ($pdu, 0, 1)) == $wanted_type;
661 ($length,$pdu) = decode_length ($pdu, 1);
662 hex_string_aux ($pdu);
663 }
664  
665 sub hex_string_aux ($) {
666 my ($binary_string) = @_;
667 my ($c, $result);
668 $result = '';
669 for $c (unpack "C*", $binary_string) {
670 $result .= sprintf "%02x", $c;
671 }
672 $result;
673 }
674  
675 sub decode_oid ($) {
676 my ($pdu) = @_;
677 my ($result,$pdu_rest);
678 my (@result);
679 $result = ord (substr ($pdu, 0, 1));
680 return error ("Object ID expected") unless $result == object_id_tag;
681 ($result, $pdu_rest) = decode_length ($pdu, 1);
682 return error ("Short PDU")
683 if $result > length $pdu_rest;
684 @result = (substr ($pdu, 0, $result + (length ($pdu) - length ($pdu_rest))),
685 substr ($pdu_rest, $result));
686 @result;
687 }
688  
689 # IlvJa
690 # This takes a PDU and returns a two element list consisting of
691 # the first element found in the PDU (whatever it is) and the
692 # rest of the PDU
693 sub decode_generic_tlv ($) {
694 my ($pdu) = @_;
695 my (@result);
696 my ($elemlength,$pdu_rest) = decode_length ($pdu, 1);
697 @result = (# Extract the first element.
698 substr ($pdu, 0, $elemlength + (length ($pdu)
699 - length ($pdu_rest)
700 )
701 ),
702 #Extract the rest of the PDU.
703 substr ($pdu_rest, $elemlength)
704 );
705 @result;
706 }
707  
708 =head2 decode_by_template() - decode complex object according to a
709 template.
710  
711 ($var1, ...) = decode_by_template ($pdu, $template, ...);
712  
713 The template can contain various %X directives. Some directives
714 consume additional arguments following the template itself. Most
715 directives will cause values to be returned. The values are returned
716 as a sequence in the order of the directives that generated them.
717  
718 =over 4
719  
720 =item %{ - decode sequence.
721  
722 This doesn't assign any return value, just checks and skips the
723 tag/length fields of the sequence. By default, the tag should be the
724 generic sequence tag, but a tag can also be specified in the
725 directive. The directive can either specify the tag as a prefix,
726 e.g. C<%99{> will require a sequence tag of 99, or if the directive is
727 given as C<%*{>, the tag will be taken from the next argument.
728  
729 =item %s - decode string
730  
731 =item %i - decode integer
732  
733 =item %u - decode unsigned integer
734  
735 =item %O - decode Object ID (OID)
736  
737 =item %A - decode IPv4 address
738  
739 =item %@ - assigns the remaining undecoded part of the PDU to the next
740 return value.
741  
742 =back
743  
744 =cut
745  
746 sub decode_by_template {
747 my ($pdu) = shift;
748 local ($_) = shift;
749 return decode_by_template_2 ($pdu, $_, 0, 0, @_);
750 }
751  
752 my $template_debug = 0;
753  
754 sub decode_by_template_2 {
755 my ($pdu, $template, $pdu_index, $template_index);
756 local ($_);
757 $pdu = shift;
758 $template = $_ = shift;
759 $pdu_index = shift;
760 $template_index = shift;
761 my (@results);
762 my ($length,$expected,$read,$rest);
763 return undef unless defined $pdu;
764 while (0 < length ($_)) {
765 if (substr ($_, 0, 1) eq '%') {
766 print STDERR "template $_ ", length $pdu," bytes remaining\n"
767 if $template_debug;
768 $_ = substr ($_,1);
769 ++$template_index;
770 if (($expected) = /^(\d+|\*|)\{(.*)/) {
771 ## %{
772 $template_index += length ($expected) + 1;
773 print STDERR "%{\n" if $template_debug;
774 $_ = $2;
775 $expected = shift | constructor_flag if ($expected eq '*');
776 $expected = sequence_tag | constructor_flag
777 if $expected eq '';
778 return template_error ("Unexpected end of PDU",
779 $template, $template_index)
780 if !defined $pdu or $pdu eq '';
781 return template_error ("Expected sequence tag $expected, got ".
782 ord (substr ($pdu, 0, 1)),
783 $template,
784 $template_index)
785 unless (ord (substr ($pdu, 0, 1)) == $expected);
786 ($length,$pdu) = decode_length ($pdu, 1)
787 or return template_error ("cannot read length",
788 $template, $template_index);
789 return template_error ("Expected length $length, got ".length $pdu ,
790 $template, $template_index)
791 unless length $pdu == $length;
792 } elsif (($expected,$rest) = /^(\*|)s(.*)/) {
793 ## %s
794 $template_index += length ($expected) + 1;
795 ($expected = shift) if $expected eq '*';
796 ($read, $pdu) = decode_string ($pdu)
797 or return template_error ("cannot read string",
798 $template, $template_index);
799 print STDERR "%s => $read\n" if $template_debug;
800 if ($expected eq '') {
801 push @results, $read;
802 } else {
803 return template_error ("Expected $expected, read $read",
804 $template, $template_index)
805 unless $expected eq $read;
806 }
807 $_ = $rest;
808 } elsif (($rest) = /^A(.*)/) {
809 ## %A
810 $template_index += 1;
811 {
812 my ($tag, $length, $value);
813 $tag = ord (substr ($pdu, 0, 1));
814 return error ("Expected IP address, got tag ".$tag)
815 unless $tag == snmp_ip_address_tag;
816 ($length, $pdu) = decode_length ($pdu, 1);
817 return error ("Inconsistent length of InetAddress encoding")
818 if $length > length $pdu;
819 return template_error ("IP address must be four bytes long",
820 $template, $template_index)
821 unless $length == 4;
822 $read = substr ($pdu, 0, $length);
823 $pdu = substr ($pdu, $length);
824 }
825 print STDERR "%A => $read\n" if $template_debug;
826 push @results, $read;
827 $_ = $rest;
828 } elsif (/^O(.*)/) {
829 ## %O
830 $template_index += 1;
831 $_ = $1;
832 ($read,$pdu) = decode_oid ($pdu)
833 or return template_error ("cannot read OID",
834 $template, $template_index);
835 print STDERR "%O => ".pretty_oid ($read)."\n"
836 if $template_debug;
837 push @results, $read;
838 } elsif (($expected,$rest) = /^(\d+|\*|)i(.*)/) {
839 ## %i
840 $template_index += length ($expected) + 1;
841 print STDERR "%i\n" if $template_debug;
842 $_ = $rest;
843 ($read, $pdu) = decode_int ($pdu)
844 or return template_error ("cannot read int",
845 $template, $template_index);
846 if ($expected eq '') {
847 push @results, $read;
848 } else {
849 $expected = int (shift) if $expected eq '*';
850 return template_error (sprintf ("Expected %d (0x%x), got %d (0x%x)",
851 $expected, $expected, $read, $read),
852 $template, $template_index)
853 unless ($expected == $read)
854 }
855 } elsif (($rest) = /^u(.*)/) {
856 ## %u
857 $template_index += 1;
858 print STDERR "%u\n" if $template_debug;
859 $_ = $rest;
860 ($read, $pdu) = decode_unsignedlike ($pdu)
861 or return template_error ("cannot read uptime",
862 $template, $template_index);
863 push @results, $read;
864 } elsif (/^\@(.*)/) {
865 ## %@
866 $template_index += 1;
867 print STDERR "%@\n" if $template_debug;
868 $_ = $1;
869 push @results, $pdu;
870 $pdu = '';
871 } else {
872 return template_error ("Unknown decoding directive in template: $_",
873 $template, $template_index);
874 }
875 } else {
876 if (substr ($_, 0, 1) ne substr ($pdu, 0, 1)) {
877 return template_error ("Expected ".substr ($_, 0, 1).", got ".substr ($pdu, 0, 1),
878 $template, $template_index);
879 }
880 $_ = substr ($_,1);
881 $pdu = substr ($pdu,1);
882 }
883 }
884 return template_error ("PDU too long", $template, $template_index)
885 if length ($pdu) > 0;
886 return template_error ("PDU too short", $template, $template_index)
887 if length ($_) > 0;
888 @results;
889 }
890  
891 =head2 decode_sequence() - Split sequence into components.
892  
893 ($first, $rest) = decode_sequence ($pdu);
894  
895 Checks whether the PDU has a sequence type tag and a plausible length
896 field. Splits the initial element off the list, and returns both this
897 and the remainder of the PDU.
898  
899 =cut
900  
901 sub decode_sequence ($) {
902 my ($pdu) = @_;
903 my ($result);
904 my (@result);
905 $result = ord (substr ($pdu, 0, 1));
906 return error ("Sequence expected")
907 unless $result == (sequence_tag | constructor_flag);
908 ($result, $pdu) = decode_length ($pdu, 1);
909 return error ("Short PDU")
910 if $result > length $pdu;
911 @result = (substr ($pdu, 0, $result), substr ($pdu, $result));
912 @result;
913 }
914  
915 sub decode_int ($) {
916 my ($pdu) = @_;
917 my $tag = ord (substr ($pdu, 0, 1));
918 return error ("Integer expected, found tag ".$tag)
919 unless $tag == int_tag;
920 decode_intlike ($pdu);
921 }
922  
923 sub decode_intlike ($) {
924 decode_intlike_s ($_[0], 1);
925 }
926  
927 sub decode_unsignedlike ($) {
928 decode_intlike_s ($_[0], 0);
929 }
930  
931 my $have_math_bigint_p = 0;
932  
933 sub decode_intlike_s ($$) {
934 my ($pdu, $signedp) = @_;
935 my ($length,$result);
936 ($length,$pdu) = decode_length ($pdu, 1);
937 my $ptr = 0;
938 $result = unpack ($signedp ? "c" : "C", substr ($pdu, $ptr++, 1));
939 if ($length > 5 || ($length == 5 && $result > 0)) {
940 require 'Math/BigInt.pm' unless $have_math_bigint_p++;
941 $result = new Math::BigInt ($result);
942 }
943 while (--$length > 0) {
944 $result *= 256;
945 $result += unpack ("C", substr ($pdu, $ptr++, 1));
946 }
947 ($result, substr ($pdu, $ptr));
948 }
949  
950 sub decode_string ($) {
951 my ($pdu) = shift;
952 my ($result);
953 $result = ord (substr ($pdu, 0, 1));
954 return error ("Expected octet string, got tag ".$result)
955 unless $result == octet_string_tag;
956 ($result, $pdu) = decode_length ($pdu, 1);
957 return error ("Short PDU")
958 if $result > length $pdu;
959 return (substr ($pdu, 0, $result), substr ($pdu, $result));
960 }
961  
962 sub decode_length ($@) {
963 my ($pdu) = shift;
964 my $index = shift || 0;
965 my ($result);
966 my (@result);
967 $result = ord (substr ($pdu, $index, 1));
968 if ($result & long_length) {
969 if ($result == (long_length | 1)) {
970 @result = (ord (substr ($pdu, $index+1, 1)), substr ($pdu, $index+2));
971 } elsif ($result == (long_length | 2)) {
972 @result = ((ord (substr ($pdu, $index+1, 1)) << 8)
973 + ord (substr ($pdu, $index+2, 1)), substr ($pdu, $index+3));
974 } else {
975 return error ("Unsupported length");
976 }
977 } else {
978 @result = ($result, substr ($pdu, $index+1));
979 }
980 @result;
981 }
982  
983 =head2 register_pretty_printer() - register pretty-printing methods for
984 typecodes.
985  
986 This function takes a hashref that specifies functions to call when
987 the specified value type is being printed. It returns the number of
988 functions that were registered.
989 =cut
990 sub register_pretty_printer($)
991 {
992 my ($h_ref) = shift;
993 my ($type, $val, $cnt);
994  
995 $cnt = 0;
996 while(($type, $val) = each %$h_ref) {
997 if (ref $val eq "CODE") {
998 $pretty_printer{$type} = $val;
999 $cnt++;
1000 }
1001 }
1002 return($cnt);
1003 }
1004  
1005 # This takes a hashref that specifies functions to call when
1006 # the specified value type is being printed. It removes the
1007 # functions from the list for the types specified.
1008 # It returns the number of functions that were unregistered.
1009 sub unregister_pretty_printer($)
1010 {
1011 my ($h_ref) = shift;
1012 my ($type, $val, $cnt);
1013  
1014 $cnt = 0;
1015 while(($type, $val) = each %$h_ref) {
1016 if ((exists ($pretty_printer{$type}))
1017 && ($pretty_printer{$type} == $val)) {
1018 if (exists($default_printer{$type})) {
1019 $pretty_printer{$type} = $default_printer{$type};
1020 } else {
1021 delete $pretty_printer{$type};
1022 }
1023 $cnt++;
1024 }
1025 }
1026 return($cnt);
1027 }
1028  
1029 #### OID prefix check
1030  
1031 ### encoded_oid_prefix_p OID1 OID2
1032 ###
1033 ### OID1 and OID2 should be BER-encoded OIDs.
1034 ### The function returns non-zero iff OID1 is a prefix of OID2.
1035 ### This can be used in the termination condition of a loop that walks
1036 ### a table using GetNext or GetBulk.
1037 ###
1038 sub encoded_oid_prefix_p ($$) {
1039 my ($oid1, $oid2) = @_;
1040 my ($i1, $i2);
1041 my ($l1, $l2);
1042 my ($subid1, $subid2);
1043 return error ("OID tag expected") unless ord (substr ($oid1, 0, 1)) == object_id_tag;
1044 return error ("OID tag expected") unless ord (substr ($oid2, 0, 1)) == object_id_tag;
1045 ($l1,$oid1) = decode_length ($oid1, 1);
1046 ($l2,$oid2) = decode_length ($oid2, 1);
1047 for ($i1 = 0, $i2 = 0;
1048 $i1 < $l1 && $i2 < $l2;
1049 ++$i1, ++$i2) {
1050 ($subid1,$i1) = &decode_subid ($oid1, $i1, $l1);
1051 ($subid2,$i2) = &decode_subid ($oid2, $i2, $l2);
1052 return 0 unless $subid1 == $subid2;
1053 }
1054 return $i2 if $i1 == $l1;
1055 return 0;
1056 }
1057  
1058 ### decode_subid OID INDEX
1059 ###
1060 ### Decodes a subid field from a BER-encoded object ID.
1061 ### Returns two values: the field, and the index of the last byte that
1062 ### was actually decoded.
1063 ###
1064 sub decode_subid ($$$) {
1065 my ($oid, $i, $l) = @_;
1066 my $subid = 0;
1067 my $next;
1068  
1069 while (($next = ord (substr ($oid, $i, 1))) >= 128) {
1070 $subid = ($subid << 7) + ($next & 0x7f);
1071 ++$i;
1072 return error ("decoding object ID: short field")
1073 unless $i < $l;
1074 }
1075 return (($subid << 7) + $next, $i);
1076 }
1077  
1078 sub error (@) {
1079 $errmsg = join ("",@_);
1080 return undef;
1081 }
1082  
1083 sub template_error ($$$) {
1084 my ($errmsg, $template, $index) = @_;
1085 return error ($errmsg."\n ".$template."\n ".(' ' x $index)."^");
1086 }
1087  
1088 1;
1089  
1090 =head1 AUTHORS
1091  
1092 Created by: Simon Leinen E<lt>simon.leinen@switch.chE<gt>
1093  
1094 Contributions and fixes by:
1095  
1096 =over
1097  
1098 =item Andrzej Tobola E<lt>san@iem.pw.edu.plE<gt>: Added long String decode
1099  
1100 =item Tobias Oetiker E<lt>tobi@oetiker.chE<gt>: Added 5 Byte Integer decode ...
1101  
1102 =item Dave Rand E<lt>dlr@Bungi.comE<gt>: Added C<SysUpTime> decode
1103  
1104 =item Philippe Simonet E<lt>sip00@vg.swissptt.chE<gt>: Support larger subids
1105  
1106 =item Yufang HU E<lt>yhu@casc.comE<gt>: Support even larger subids
1107  
1108 =item Mike Mitchell E<lt>Mike.Mitchell@sas.comE<gt>: New generalized C<encode_int()>
1109  
1110 =item Mike Diehn E<lt>mdiehn@mindspring.netE<gt>: C<encode_ip_address()>
1111  
1112 =item Rik Hoorelbeke E<lt>rik.hoorelbeke@pandora.beE<gt>: C<encode_oid()> fix
1113  
1114 =item Brett T Warden E<lt>wardenb@eluminant.comE<gt>: pretty C<UInteger32>
1115  
1116 =item Bert Driehuis E<lt>driehuis@playbeing.orgE<gt>: Handle SNMPv2 exception codes
1117  
1118 =item Jakob Ilves (/IlvJa) E<lt>jakob.ilves@oracle.comE<gt>: PDU decoding
1119  
1120 =item Jan Kasprzak E<lt>kas@informatics.muni.czE<gt>: Fix for PDU syntax check
1121  
1122 =item Milen Pavlov E<lt>milen@batmbg.comE<gt>: Recognize variant length for ints
1123  
1124 =back
1125  
1126 =head1 COPYRIGHT
1127  
1128 Copyright (c) 1995-2009, Simon Leinen.
1129  
1130 This program is free software; you can redistribute it under the
1131 "Artistic License 2.0" included in this distribution (file "Artistic").
1132  
1133 =cut