		       SNMP support for Perl 5
		       -----------------------

		Copyright (c) 1995-2007, Simon Leinen
			 All rights reserved

This program is free software; you can redistribute it under the
"Artistic License" included in this distribution (file "Artistic").

	       Author: Simon Leinen  <simon.leinen@switch.ch>
			    Contributors:
		 Tobias Oetiker	 <tobi@oetiker.ch>
	       Matthew Trunnell	 <matter@media.mit.edu>
		 Andrzej Tobola	 <san@iem.pw.edu.pl>
		      Dave Rand	 <dlr@Bungi.com>
		   Heine Peters	 <peters@dkrz.de>
		      Yufang HU	 <yhu@casc.com>
	       Philippe Simonet	 <Philippe.Simonet@swisscom.com>
	      Daniel L. Needles	 <dan_needles@INS.COM>
			Dan Cox	 <dcox@lexmark.com>
	       Iouri Pakhomenko	 <pakhomenko@gmd.de>
		   Niels Bakker	 <niels@euro.net>
		  Mike Mitchell  <mcm@unx.sas.com>
                   Alan Nichols  <Alan.Nichols@Ebay.Sun.COM>
                  Mike McCauley  <mikem@open.com.au>
		Andrew W. Elble  <elble@icculus.nsg.nwu.edu>
		Paul E. Erkkila  <pee@gblx.net>
		 Johannes Demel  <demel@zid.tuwien.ac.at>
		 Rik Hoorelbeke  <rik.hoorelbeke@pandora.be>
		 Brett T Warden  <wardenb@eluminant.com>
		 Alistair Mills  <alistair@alizta.com>
		  Bert Driehuis  <driehuis@playbeing.org>
                 Michael Deegan  <michael@cnspc18.murdoch.edu.au>
           Jakob Ilves (/IlvJa)  <jakob.ilves@oracle.com>
		   Jan Kasprzak  <kas@informatics.muni.cz>
	       Valerio Bontempi  <v.bontempi@inwind.it>
		Lorenzo Colitti  <lorenzo@colitti.com>
		   Joerg Kummer  <JOERG.KUMMER@Roche.COM>
           Christopher J. Tengi  <tengi@CS.Princeton.EDU>
                    Luc Pauwels  <Luc.Pauwels@xalasys.com>
                   Milen Pavlov  <milen@batmbg.com>
       Andrew Cornford-Matheson  <andrew.matheson@corenetworks.com>
                   Gerry Dalton  <gerry.dalton@consolidated.com>
		 Jan van Keulen  <cologne@email.com>

	http://www.switch.ch/misc/leinen/snmp/perl/index.html

This archive contains Perl 5 modules SNMP_Session.pm and BER.pm,
which, when used together, provide rudimentary access to remote SNMP
(v1) agents.

This module differs from existing SNMP packages in that it is
completely stand-alone, i.e. you don't need to have another SNMP
package such as Net-SNMP.  It is also written entirely in Perl, so you
don't have to compile any C modules.  It uses the Perl 5 Socket.pm
module and should therefore be very portable, even to non-Unix systems.

The SNMP operations currently supported are "get", "get-next", and
"set", as well as trap generation and reception.

For an excellent example of the type of application this is useful
for, see Tobias Oetiker's ``mrtg'' (Multi Router Traffic Grapher)
tool: <URL:http://oss.oetiker.ch/mrtg/>

				Usage
				.....

The basic usage of these routines works like this:

	use BER;
	require 'SNMP_Session.pm';
	
	# Set $host to the name of the host whose SNMP agent you want
	# to talk to.  Set $community to the community name under
	# which you want to talk to the agent.  Set port to the UDP
	# port on which the agent listens (usually 161).
	
	$session = SNMP_Session->open ($host, $community, $port)
	    or die "couldn't open SNMP session to $host";
	
	# Set $oid1, $oid2... to the BER-encoded OIDs of the MIB
	# variables you want to get.
	
	if ($session->get_request_response ($oid1, $oid2, ...)) {
	    ($bindings) = $session->decode_get_response ($session->{pdu_buffer});
	
	    while ($bindings ne '') {
	        ($binding,$bindings) = &decode_sequence ($bindings);
	        ($oid,$value) = &decode_by_template ($binding, "%O%@");
	        print &pretty_print ($oid)," => ", &pretty_print ($value), "\n";
	    }
	} else {
	    die "No response from agent on $host";
	}
			    Encoding OIDs
			    .............

In order to BER-encode OIDs, you can use the function BER::encode_oid.
It takes (a vector of) numeric subids as an argument.  For example,

	use BER;
	encode_oid (1, 3, 6, 1, 2, 1, 1, 1, 0)

will return the BER-encoded OID for the sysDescr.0 (1.3.6.1.2.1.1.1.0)
instance of MIB-2.

			 Decoding the results
			 ....................

When get_request_response returns success, you must decode the
response PDU from the remote agent.  The function
`decode_get_response' can be used to do this.  It takes a get-response
PDU, checks its syntax and returns the "bindings" part of the PDU.
This is where the remote agent actually returns the values of the
variables in your query.

You should iterate over the individual bindings in this "bindings"
part and extract the value for each variable.  In the example above,
the returned bindings are simply printed using the BER::pretty_print
function.

For better readability of the OIDs, you can also use the following
idiom, where the %pretty_oids hash maps BER-encoded numerical OIDs to
symbolic OIDs. Note that this simple-minded mapping only works for
response OIDs that exactly match known OIDs, so it's unsuitable for
table walking (where the response OIDs include an additional row
index).

	%ugly_oids = qw(sysDescr.0      1.3.6.1.2.1.1.1.0
	                sysContact.0    1.3.6.1.2.1.1.4.0);
	foreach (keys %ugly_oids) {
	    $ugly_oids{$_} = encode_oid (split (/\./, $ugly_oids{$_}));
	    $pretty_oids{$ugly_oids{$_}} = $_;
	}
	...
	if ($session->get_request_response ($ugly_oids{'sysDescr.0'},
	                                    $ugly_oids{'sysContact.0'})) {
	    ($bindings) = $session->decode_get_response
		($session->{pdu_buffer});
	    while ($bindings ne '') {
	        ($binding,$bindings) = &decode_sequence ($bindings);
	        ($oid,$value) = &decode_by_template ($binding, "%O%@");
	        print $pretty_oids{$oid}," => ",
	              &pretty_print ($value), "\n";
	    }
	} ...

			     Set Requests
			     ............

Set requests are generated much like get or getNext requests are, with
the exception that you have to specify not just OIDs, but also the
values the variables should be set to.  Every binding is passed as a
reference to a two-element array, the first element being the encoded
OID and the second one the encoded value.  See the `test/set-test.pl'
script for an example, in particular the subroutine `snmpset'.

			    Walking Tables
			    ..............

Beginning with version 0.57 of SNMP_Session.pm, there is API support
for walking tables.  The map_table method can be used for this as
follows:

	sub walk_function ($$$) {
	  my ($index, $val1, $val3) = @_;
	  ...
	}
	
	...
	$columns = [$base_oid1, $base_oid3];
	$n_rows = $session->map_table ($columns, \&walk_function);

The COLUMNS argument must be a reference to a list of OIDs for table
columns sharing the same index.  The method will traverse the table
and call the WALK_FUNCTION for each row. The arguments for these calls
will be:

* the row index as a partial OID in dotted notation, e.g. "1.3", or
  "10.0.1.34".

* the values of the requested table columns in that row, in
  BER-encoded form.  If you want to use the standard pretty_print
  subroutine to decode the values, you can use the following idiom:

	grep (defined $_ && ($_=pretty_print $_), ($val1, $val3));

			    Sending Traps
			    .............

To send a trap, you have to open an SNMP session to the trap receiver.
Usually this is a process listening to UDP port 162 on a network
management station.  Then you can use the trap_request_send method to
encode and send the trap.  There is no way to find out whether the
trap was actually received at the management station - SNMP traps are
fundamentally unreliable.

When constructing an SNMPv1 trap, you must provide

* the "enterprise" Object Identifier for the entity that generates the
  trap

* your IP address

* the generic trap type

* the specific trap type

* the sysUpTime at the time of trap generation

* a sequence (may be empty) of variable bindings further describing
 the trap.

For SNMPv2 traps, you need:

* the trap's OID

* the sysUpTime at the time of trap generation

* the bindings list as above

For SNMPv2 traps, the uptime and trap OID are encoded as bindings
which are added to the front of the other bindings you provide.

Here is a short example:

	my $trap_receiver = "netman.noc";
	my $trap_community = "SNMP_Traps";
	my $trap_session = $version eq '1'
	    ? SNMP_Session->open ($trap_receiver, $trap_community, 162)
	    : SNMPv2c_Session->open ($trap_receiver, $trap_community, 162);
	my $trap_session = SNMP_Session->open ($trap_receiver, $trap_community, 162);
	my $myIpAddress = ...;
	my $start_time = time;
	
	...
	
	sub link_down_trap ($$) {
	  my ($if_index, $version) = @_;
	  my $genericTrap = 2;		# linkDown
	  my $specificTrap = 0;
	  my @ifIndexOID = ( 1,3,6,1,2,1,2,2,1,1 );
	  my $upTime = int ((time - $start_time) * 100.0);
	  my @myOID = ( 1,3,6,1,4,1,2946,0,8,15 );
	
	  warn "Sending trap failed"
	    unless ($version eq '1')
		? $trap_session->trap_request_send (encode_oid (@myOID),
						    encode_ip_address ($myIpAddress),
						    encode_int ($genericTrap),
						    encode_int ($specificTrap),
						    encode_timeticks ($upTime),
						    [encode_oid (@ifIndex_OID,$if_index),
						     encode_int ($if_index)],
						    [encode_oid (@ifDescr_OID,$if_index),
						     encode_string ("foo")])
		    : $trap_session->v2_trap_request_send (\@linkDown_OID, $upTime,
							   [encode_oid (@ifIndex_OID,$if_index),
							    encode_int ($if_index)],
							   [encode_oid (@ifDescr_OID,$if_index),
							    encode_string ("foo")]);
	}

			   Receiving Traps
			   ...............

Since version 0.60, SNMP_Session.pm supports the receipt and decoding
of SNMPv1 trap requests.  Since version 0.75, SNMPv2 Trap PDUs are
also recognized.

To receive traps, you have to create a special SNMP session that
passively listens on the SNMP trap transport address (usually UDP port
162).  Then you can receive traps (actually, SNMPv1 traps, SNMPv2
traps, and SNMPv2 informs) using the receive_trap method and decode
them using decode_trap_request.  The enterprise, agent, generic,
specific and sysUptime return values are only defined for SNMPv1
traps.  In SNMPv2 traps and informs, the equivalent information is
contained in the bindings.

	my $trap_session = SNMPv1_Session->open_trap_session ()
	  or die "cannot open trap session";
	my ($trap, $sender_addr, $sender_port) = $trap_session->receive_trap ()
	  or die "cannot receive trap";
	my ($community, $enterprise, $agent,
	    $generic, $specific, $sysUptime, $bindings)
	  = $session->decode_trap_request ($trap)
	    or die "cannot decode trap received"
	...
	my ($binding, $oid, $value);
	while ($bindings ne '') {
	    ($binding,$bindings) = &decode_sequence ($bindings);
	    ($oid, $value) = decode_by_template ("%O%@");
	    print BER::pretty_oid ($oid)," => ",pretty_print ($value),"\n";
	}

			     Future Plans
			     ............

			    SNMPv3 Support

The code could first be restructured to follow the modularization
proposed in RFC 2271 (An Architecture for Describing SNMP Management
Frameworks).  The existing SNMPv1 and SNMPv2c support must somehow be
retrofitted to this framework.  Later, one could add support for
SNMPv3 PDU formats and for user-based security.

			  Higher-Level APIs

The current programming interface is very close to the level of SNMP
operations and PDUs.  For actual management applications, there are
probably more convenient interfaces that could be defined.
