snmp.cpp

来自「HP公司的SNMP++的Win32版本源码」· C++ 代码 · 共 1,767 行 · 第 1/5 页

CPP
1,767
字号
/*===================================================================

  Copyright (c) 1999
  Hewlett-Packard Company

  ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS.
  Permission to use, copy, modify, distribute and/or sell this software 
  and/or its documentation is hereby granted without fee. User agrees 
  to display the above copyright notice and this license notice in all 
  copies of the software and any documentation of the software. User 
  agrees to assume all liability for the use of the software; Hewlett-Packard 
  makes no representations about the suitability of this software for any 
  purpose. It is provided "AS-IS without warranty of any kind,either express 
  or implied. User hereby grants a royalty-free license to any and all 
  derivatives based upon this software code base. 



  S N M P . C P P

  SNMP CLASS IMPLEMENATION FOR WINDOWS WIN32

  DESCRIPTION:
  This module contains the implementation of the SNMP and
  transport init/deinit functions.

  LANGUAGE:
  ANSI C++

  OPERATING SYSTEM:
  Win32


  DESIGN:
  Peter E Mellquist

  AUTHOR:
  Peter E Mellquist

 
=====================================================================*/
char snmp_cpp_version[]="#(@)SNMP++ 2.8 $Header: snmp.cpp,v 1.25 96/09/11 14:02:06 hmgr Exp $";

//-----[ External C includes ]-----------------------------------------
extern "C"
{
#include "winsnmp.h"  // winsnmp include file
#include <stdio.h>    // standard io
}

#define _INCLUDE_SNMP_ERR_STRINGS

//-----[ SNMP++ Includes ]--------------------------------------------
#include "oid.h"        // class def for oids
#include "vb.h"         // class def for vbs
#include "snmp_pp.h"    // class def for this module
#include "pdu_cont.h"   // pdu container class def

//-----[ macros ]------------------------------------------------------
#define MAX_DOTTED_OID_SIZE 255   // maximum size for a dotted string
#define SNMP_MSG WM_USER+176      // winsnmp callback msg
#define SNMP_GWW_HINSTANCE -6     // gww instance

//-----[ snmp engine variables ]--------------------------------------- 

static char SzSnmpClass[] =  "sppcls32";     // pdu handler registered name

DLLOPT Pdu_Container *pdu_container;         // pointer to pdu container class
int pdu_ref_count=0;                         // reference count of transport
int snmp_ref_count=0;                        // reference count for xport

// mutual exclusion variables for thread safety
CRITICAL_SECTION my_critical_section;                           

#define SNMP_WAIT EnterCriticalSection( &my_critical_section)
#define SNMP_SIGNAL LeaveCriticalSection( &my_critical_section)

//-----[ Trap Builder API ]----------------------------------------
typedef SNMPAPI_STATUS (PASCAL *functionTrap)( HSNMP_PDU, smiLPOID, smiLPIPADDR, smiLPINT, smiLPINT, smiLPTIMETICKS);

//-----[ port setting API ]-----------------------------------------
typedef SNMPAPI_STATUS (PASCAL *functionPortSet) (HSNMP_ENTITY hEntity,WORD port);


//--------------[ well known trap ids ]-----------------------------------
// SMI trap oid def
class snmpTrapsOid: public Oid {
   public: 
   snmpTrapsOid (void):Oid("1.3.6.1.6.3.1.1.5"){};
}; 

// SMI Enterprose Oid
class snmpTrapEnterpriseOid: public Oid {
   public: 
   snmpTrapEnterpriseOid(void):Oid("1.3.6.1.6.3.1.1.4.3.0"){};
}; 

// SMI Cold Start Oid
class coldStartOid: public snmpTrapsOid {
   public: 
   coldStartOid( void){*this+=".1";};
};

// SMI WarmStart Oid
class warmStartOid: public snmpTrapsOid {
   public: 
   warmStartOid( void){*this+=".2";};
};

// SMI LinkDown Oid
class linkDownOid: public snmpTrapsOid {
   public: 
   linkDownOid( void){*this+=".3";};
}; 


// SMI LinkUp Oid
class linkUpOid: public snmpTrapsOid {
   public: 
   linkUpOid( void){*this+=".4";};
};

// SMI Authentication Failure Oid
class authenticationFailureOid: public snmpTrapsOid {
   public: 
   authenticationFailureOid( void){*this+=".5";};
}; 

// SMI egpneighborloss Oid
class egpNeighborLossOid: public snmpTrapsOid {
   public: 
   egpNeighborLossOid( void){*this+=".6";};
};

const coldStartOid coldStart;
const warmStartOid warmStart;
const linkDownOid linkDown;
const linkUpOid linkUp;
const authenticationFailureOid authenticationFailure;
const egpNeighborLossOid egpNeighborLoss;
const snmpTrapEnterpriseOid snmpTrapEnterprise;


//-----------------------------------------------------------------------
//--------[ extract_from_varbindlist ]-----------------------------------
//-----------------------------------------------------------------------
// loop through all vbs in the VArbind list extracting each
// vb into the SNMP++ Vb ojbects
int extract_from_varbindlist( HSNMP_VBL hRecvVbl,  // handle to winsnmp vbl
                              Pdu &pdu)            // Snmp++ Pdu to extract into
{
   int z;                            // looping variable
   SNMPAPI_STATUS vb_status;         // status of VB extract
   smiVALUE SnmpValue;               // A received value
   smiOID RecvOid;                   // a received oid
   char stroid[MAX_DOTTED_OID_SIZE]; // string oid
   TimeTicks tt;                     // timeticks object
   Counter32 ctr;                    // counter object
   Gauge32 gge;                      // gauge object
   Vb tempvb;                        // temp vb object
   int vb_count;                     // count of pdu vbs

   //-----[ delete existing vblist from pdu ] --------------------------
   pdu.set_vblist(&tempvb, 0);

   //-----[ loop through and extract response vb's] --------------------
   SNMPDEBUG("++ SNMP++, In Extract From Vb List \n");
   vb_count = SnmpCountVbl( hRecvVbl);
   for (z=1;z<=vb_count;z++)
   {
      // get the vb
      SNMPDEBUG("++ SNMP++, Get VB \n");
      vb_status = SnmpGetVb( hRecvVbl,
                             z,
                             &RecvOid,
                             &SnmpValue);
      // if it is a good status then extract
      // it into the vb object else the
      // error index should point to it
      // so we just skip it
      //
      // if the status was successful,
      // then we need to copy the oid
      // and value portions to the vb object
      // when finished, we need to free the oid
      // and the smivalue portion if its an oid or octet
      if ( vb_status == SNMPAPI_SUCCESS)
      {
         // copy the smivalue data into the vb object
         // to be returned
         SnmpOidToStr( &RecvOid,MAX_DOTTED_OID_SIZE,stroid);
         tempvb.set_oid(stroid);
         // clean up memory created by WinSnmp
         SnmpFreeDescriptor(SNMP_SYNTAX_OID, (smiLPOPAQUE) &RecvOid);
         switch( SnmpValue.syntax)
         {
            // null , do nothing
            case SNMP_SYNTAX_NULL:
            case SNMP_SYNTAX_NOSUCHOBJECT:
            case SNMP_SYNTAX_NOSUCHINSTANCE:
            case SNMP_SYNTAX_ENDOFMIBVIEW:
            break;

            // octects
            case SNMP_SYNTAX_OCTETS:
            case SNMP_SYNTAX_BITS:
            case SNMP_SYNTAX_OPAQUE:
            {
               OctetStr octetstr( (unsigned char far *) SnmpValue.value.string.ptr,
                                  ( size_t) SnmpValue.value.string.len);
               tempvb.set_value( octetstr);
               SnmpFreeDescriptor( SNMP_SYNTAX_OCTETS,
                                   (smiLPOPAQUE)&SnmpValue.value.string );
            }
            break;

            // ip addresses
            case SNMP_SYNTAX_IPADDR:
            {
               IpAddress ipa("0.0.0.0"); // make it valid first
               ipa[0] = SnmpValue.value.string.ptr[0];
               ipa[1] = SnmpValue.value.string.ptr[1];
               ipa[2] = SnmpValue.value.string.ptr[2];
               ipa[3] = SnmpValue.value.string.ptr[3];
               tempvb.set_value( ipa);
			   SnmpFreeDescriptor( SNMP_SYNTAX_IPADDR,
								   (smiLPIPADDR) &SnmpValue.value.string );
            }
            break;

            // oid
            case SNMP_SYNTAX_OID:
            {
               SnmpOidToStr( &SnmpValue.value.oid,MAX_DOTTED_OID_SIZE,stroid);
               Oid oidvb(stroid);
               tempvb.set_value( oidvb);
               SnmpFreeDescriptor( SNMP_SYNTAX_OID,
                                   (smiLPOPAQUE)&SnmpValue.value.oid );
            }
            break;

            // int 32
            case SNMP_SYNTAX_INT32:
               tempvb.set_value( (signed long int) SnmpValue.value.sNumber);
            break;

            // time ticks
            case SNMP_SYNTAX_TIMETICKS:
               tt =  (unsigned long) SnmpValue.value.uNumber;
               tempvb.set_value( tt);
            break;

            // counter
            case SNMP_SYNTAX_CNTR32:
               ctr = (unsigned long) SnmpValue.value.uNumber;
               tempvb.set_value( ctr);
            break;

            // gauge
            case SNMP_SYNTAX_GAUGE32:
               gge = (unsigned long) SnmpValue.value.uNumber;
               tempvb.set_value( gge);
            break;

            // u int 32
            case SNMP_SYNTAX_UINT32:
               tempvb.set_value( (unsigned long int) SnmpValue.value.uNumber);
            break;

            // 64 bit counter
            case SNMP_SYNTAX_CNTR64:
               Counter64 c64( (unsigned long int) SnmpValue.value.hNumber.hipart,
                              (unsigned long int) SnmpValue.value.hNumber.lopart);
               tempvb.set_value( c64);
            break;

            } // end switch
         }  // end if vb status is good
         pdu += tempvb;
       } // end for all vb's

   SNMPDEBUG("++ SNMP++, End Extract From Vblist \n");
   return 0;
}  // end extract_from_varbindlist

//-------------------[ returns error string ]--------------------------
char * Snmp::error_msg( const int c)
{
   return ((c<0)?
           ((c<MAX_NEG_ERROR)?nErrs[-(MAX_NEG_ERROR)+1]:nErrs[-c]):
            ((c>MAX_POS_ERROR)?pErrs[MAX_POS_ERROR+1]:pErrs[c]));
}


//-----------------------------------------------------------------------
//--------------------[ async handler ]----------------------------------
//-----------------------------------------------------------------------
// Prepares the async message to be callled to the
// callback function
void FAR  process_async_event( int reason,
                               long int lnRecvRequestId,
                               HSNMP_SESSION session_handle,
                               smiINT lnErrorStatus,
                               smiINT lnErrorIndex,
                               HSNMP_VBL hRecvVbl,
                               HSNMP_CONTEXT hRecvContext,
                               HSNMP_ENTITY hDstRecvEnt,
                               Snmp* spp_session,
                               snmp_callback callback,
                               void * personality)
{
   int vb_count;                     // number of vbs
   Vb* vbs;                          // vbs, dynamically instantiated
   SNMPAPI_STATUS gen_status;        // status of getting a vb
   unsigned char agent_addr[40];     // agent address space
   smiOCTETS octet_community;        // octet community name
   unsigned char community_name[255]; // community name for async passing
   CTarget v1target;                // v1 target to use
   Pdu pdu;                          // instantiated pdu object


   // get the var bind list from WinSnmp
   // if vb count is zero then nothing to
   // do return out;
   vb_count = (int) SnmpCountVbl( hRecvVbl);
   if ( vb_count == 0)
   {
      SNMPDEBUG("-- SNMP++, Async Handler Vb count = 0\n");
	  (callback)(   reason,                    // reason
                 (Snmp*) spp_session,          // snmp++ session who own the req
                 (Pdu&) pdu,                   // pdu
                 (SnmpTarget&) v1target,       // target
                 (void*) personality);         // callback data

      return;
   }

   // dynamically instantiate a list of
   // Vb obejcts
   // return if new error
   vbs = new Vb[vb_count];
   if ( vbs == 0)
   {
     SNMPDEBUG("-- SNMP++, Async Handler new Vb Fail\n");
     return;  // if new error then return
   }

   // stuff them into the pdu
   pdu.set_vblist( (Vb*) vbs, vb_count);

   // extract vbs from WinSNMP var bind list into
   // Snmp++ pdu objects
   extract_from_varbindlist( hRecvVbl, pdu);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?