Exemple #1
0
/////////////////////////////////////////////////////////////////////////////
// 函数:SetRequest                                                        //
// 说明:设置简单变量的结果                                                //
// 参数:无                                                                //
// 返回值:                                                                //
//      成功返回0,否则返回一个非0 值                                      //
/////////////////////////////////////////////////////////////////////////////
int BasicSNMP::SetRequest()
{
	int nResult = 0;
	Pdu pdu;                               // construct a Pdu object
	Vb vb;                                 // construct a Vb object
	vb.set_oid(oid);                      // set the Oid portion of the Vb
	vb.set_value(m_nOIDValue);                      // set the Oid portion of the Vb
	pdu += vb;   

	SnmpTarget *target;// = &ctarget;
	if(version ==version3)
	{//If SNMP Version Is 3
		nResult = InitUTarget();//Init UTarget
		pdu.set_security_level( m_nSecurityLevel);//Set the Security Level portion of Pdu
		pdu.set_context_name (contextName);//Set the Context Name portion of Pdu
		pdu.set_context_engine_id(contextEngineID);//Set the Context Engine ID portion of Pdu
		target = &utarget; //Set SNMP Target
	}
	else
	{
		target = &ctarget; //Set SNMP Target
	}

	nResult = pSnmp->set(pdu,*target);//Get Reques

	return nResult;
}
Exemple #2
0
int wpdu::load_vbs(snmp_pdu *raw_pdu, const Pdu& pdu)
{
  int status = 0;

   // load up the payload
   // for all Vbs in list, add them to the pdu
   int vb_count;
   Vb tempvb;
   Oid tempoid;
   SmiLPOID smioid;
   SmiVALUE smival;

   vb_count = pdu.get_vb_count();

   for (int z = 0; z < vb_count; z++) {
      pdu.get_vb( tempvb, z);
      tempvb.get_oid( tempoid);
      smioid = tempoid.oidval();
      // what are we trying to convert here (vb oid part or value part)
      status = convert_vb_to_smival( tempvb, &smival );
      if ( status != SNMP_CLASS_SUCCESS)
         return status;

      // add the var to the raw pdu
      cmu_snmp::add_var(raw_pdu, smioid->ptr, (int) smioid->len, &smival);
      free_smival_descriptor( &smival);
    }

  return status;
}
Exemple #3
0
// callback : have received a Pdu from the target host with given read comm str
// this is really simplistic, but gives the general idea
int agent_impl::handle_get( Pdu &pdu, UdpTarget &target)
{
  ACE_TRACE("agent_impl::handle_get");
  OctetStr mgr_rd_str, agent_rd_str;
  target.get_read_community(mgr_rd_str); // requster's read community string
  tgt_.get_read_community(agent_rd_str); // this agent's read community string

  //  1. verify we have a valid read string else drop pdu (no response to caller)
  if (mgr_rd_str != agent_rd_str) {
     ACE_DEBUG((LM_DEBUG, "agent_impl::handle_get: invalid read community recvd\n"));
     return 0;
  }

  // 2. iterate over each varbind in the pdu, filling providing responses
  int fdone = 0;
  for (int i = 0; (i < pdu.get_vb_count()) && !fdone; i++) {
    Vb vb;
    pdu.get_vb(vb, i);
    if (get_response(vb)) { // set a value for the oid if we can else
      set_error_status(&pdu, SNMP_ERROR_NO_SUCH_NAME); // these ought to be member
      set_error_index(&pdu, i); // functions but are not yet...
      fdone++; // trigger flag to exit loop early
    }
    else // failed, return noSuch error
      pdu.set_vb(vb, i);
  }

  // 3. lastly, return the pkt to the caller
  return respond(pdu, target);
}
Exemple #4
0
void getapp::result(Snmp *, int rc)
{
    Vb vb;
    if (rc < 0)
    {
      const char *ptr = snmp_.error_string();
      cout << "ASNMP:ERROR: get command failed reason: " << ptr << endl;
    }
    else
    {
      // check to see if there are any errors
      if (pdu_.get_error_status())
      {
        cout << "ERROR: agent replied as follows\n";
        cout << pdu_.agent_error_reason() << endl;
      }
      else
      {
        VbIter iter(pdu_);
        while (iter.next(vb))
        {
          cout << "\tOid = " << vb.to_string_oid() << "\n";
          cout << "\tValue = " << vb.to_string_value() << "\n";
        }
      }
    }
    cout << "\nASNMP:INFO: command completed normally.\n"<< endl;
    ACE_Reactor::instance()->end_reactor_event_loop();
}
Exemple #5
0
int getapp::run()
{

   //----------[ create a ASNMP session ]-----------------------------------
   if ( snmp_.valid() != SNMP_CLASS_SUCCESS) {
      cout << "\nASNMP:ERROR:Create session failed: "<<
          snmp_.error_string()<< "\n";
      return 1;
   }

   //--------[ build up ASNMP object needed ]-------------------------------
   if (address_.get_port() == 0)
     address_.set_port(DEF_AGENT_PORT);
   target_.set_address( address_);         // make a target using the address

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "\nASNMP:INFO:SNMP Version " << (target_.get_version()+ 1) << \
       " GET SAMPLE PROGRAM \nOID: " << oid_.to_string() << "\n";
   target_.get_address(address_); // target updates port used
   int rc;
   const char *name = address_.resolve_hostname(rc);

   cout << "Device: " << address_ << " ";

   //FUZZ: disable check_for_lack_ACE_OS
   cout << (rc ? "<< did not resolve via gethostbyname() >>" : name) << "\n";
   //FUZZ: enable check_for_lack_ACE_OS

   cout << "[ Retries=" << target_.get_retry() << " \
        Timeout=" << target_.get_timeout() <<" ms " << "Community=" << \
         community_.to_string() << " ]"<< endl;

   if (snmp_.get( pdu_, target_) == SNMP_CLASS_SUCCESS) {
       Vb vb;
      // check to see if there are any errors
      if (pdu_.get_error_status()) {
        cout << "ERROR: agent replied as follows\n";
        cout << pdu_.agent_error_reason() << endl;
      }
      else {
        VbIter iter(pdu_);
        while (iter.next(vb)) {
 	  cout << "\tOid = " << vb.to_string_oid() << "\n";
 	  cout << "\tValue = " << vb.to_string_value() << "\n";
       }
     }
   }
   else {
    const char *ptr = snmp_.error_string();
    cout << "ASNMP:ERROR: get command failed reason: " << ptr << endl;
  }

  cout << "\nASNMP:INFO: command completed normally.\n"<< endl;
  return 0;
}
std::shared_ptr<Data> FlowManager::get_sdu_for_above(const PortId id)
{
    Pdu tmp;
    if (above_buffers_.find(id) == above_buffers_.end()) {
        std::unique_lock<std::mutex> lock(mutex_);
        above_buffers_[id].reset(new Buffer<Pdu>);
    }

    // we know id exists, so we can safely access it
    above_buffers_.at(id)->popFront(tmp);
    return tmp.get_payload();
}
Exemple #7
0
void KeyChange(Snmp* snmp, Pdu& myPdu, 
	       const OctetStr& user, const OctetStr& newpass, 
	       SnmpTarget& target, int type)
{
  struct UsmKeyUpdate *uku = NULL;
  int stat;
  int status;

  uku = usm->key_update_prepare(user, target, newpass,
				myPdu, type, stat);
  if (uku == NULL)
    cout << "Key update preparation failed *************" << endl
         << "with " << snmp->error_msg(stat) << endl <<endl;

  if (( status = snmp->set( myPdu,target)) == SNMP_CLASS_SUCCESS) {
    Vb vb3;
    Oid oid3;
    myPdu.get_vb( vb3,0);
    vb3.get_oid(oid3);
    Vb vb4;
    Oid oid4;
    myPdu.get_vb( vb4,1);
    vb4.get_oid(oid4);
    if (myPdu.get_type() == REPORT_MSG) {
      cout << "Received a reportPDU! with Oid " 
           << oid3.get_printable() << endl
           << snmp->error_msg(oid3) << endl;
      usm->key_update_abort(uku);
    } 
    else {
      cout << flush << endl
           << "Oid = " << vb3.get_printable_oid() << endl
           << "Value = " << vb3.get_printable_value() << endl;
      cout << flush << endl 
           << "Oid = " << vb4.get_printable_oid() << endl
           << "Value = " << vb4.get_printable_value() << endl;
      int resul = usm->key_update_commit(uku, USM_PasswordAllKeyUpdate);
      cout << endl  << "result of local key update: " 
           << resul << endl;

    }
  }
  else {
    cout << "SNMP++ KeyChange Error, " << snmp->error_msg( status)
	 << " (" << status <<")"<< endl;
    usm->key_update_abort(uku);
  }
  
  cout << "******************************** END" 
       << endl << endl << flush;
}
int FlowManager::handle_pdu_from_below(const PortId id, Pdu &pdu)
{
    LOG_DEBUG("handle_frame_from_below()");
    // check if destination address matches
    if (destinations_.find(pdu.get_dest_addr()) == destinations_.end()) {
        // frame is not for us
        LOG_DEBUG("Ignoring frame for " << pdu.get_dest_addr());
        return 0;
    }

    // get corresponding connection handle
    FlowBase* flow = find_flow(pdu, id);
    flow->handle_frame_from_below(pdu);
    return 1;
}
Exemple #9
0
const string & SnmpDG::GetMibObject(const snmp_version  version, const SnmpPara& spr,  const string oid) const
{
	if(!m_inited_success)
	{
		return m_empty_object;
	}
	Snmp::socket_startup();

	UdpAddress address(spr.ip.c_str());
	//string myoid = oid;

	Pdu pdu;
	Vb vb;
	vb.set_oid(oid.c_str());//(myoid.c_str());
	pdu += vb;

	CTarget ctarget(address); 
	ctarget.set_version( version );
	ctarget.set_retry(spr.retry);           
	ctarget.set_timeout(spr.timeout); 
	ctarget.set_readcommunity(spr.community.c_str());
	SnmpTarget *target;
	target = &ctarget;

	int status;
	Snmp snmp(status, 0, false);
	if (status == SNMP_CLASS_SUCCESS)
	{
		if ((status = snmp.get( pdu, *target)) == SNMP_CLASS_SUCCESS)
		{
			pdu.get_vb( vb,0);
			//string oid_tmp = vb.get_printable_oid();
			m_mib_object = vb.get_printable_value();
		}
		else
		{
			m_mib_object = string("");
			SetLastError(status);
		}
	}
	else
	{
		m_mib_object = string("");
		SetLastError(status);
	}
	Snmp::socket_cleanup();  // Shut down socket subsystem
	return m_mib_object;
}
Exemple #10
0
// return a pdu from a buffer
int wpdu::get_pdu(Pdu& pdu, snmp_version& version)
{
  if (iovec_.iov_len == 0)
    return -1; // NO DATA

  snmp_pdu *raw_pdu;
  raw_pdu = cmu_snmp::pdu_create(0);
  if (!raw_pdu) {
    return SNMP_CLASS_RESOURCE_UNAVAIL;
  }

  // max value a client can send us - TODO: replace this with an
  // api to get actual string length
  int status = cmu_snmp::parse( raw_pdu, (unsigned char *)iovec_.iov_base,
                     community_name, comm_len,
                     version, iovec_.iov_len);
  if (status != 0)
    return SNMP_CLASS_INTERNAL_ERROR;

  community_name[comm_len] = 0; // set null based on returned length
  set_request_id( &pdu, raw_pdu->reqid);
  set_error_status( &pdu, (int) raw_pdu->errstat);
  set_error_index( &pdu, (int) raw_pdu->errindex);
  pdu.set_type( raw_pdu->command);

  if (restore_vbs(pdu, raw_pdu)) {
    cmu_snmp::free_pdu(raw_pdu);
    return SNMP_CLASS_INTERNAL_ERROR;
  }

  cmu_snmp::free_pdu(raw_pdu);
  return 0;
}
Exemple #11
0
int sagent::respond(Pdu& pdu,UdpTarget& tgt)
{
  pdu.set_type(sNMP_PDU_RESPONSE);
  transaction tr(pdu, tgt, iv_snmp_session_);
  tr.send();
  return 0;
}
int CNotifyEvent::Callback(SnmpTarget &target, Pdu &pdu, SnmpSocket fd, int status)
{
  Oid trapid;
  pdu.get_notify_id(trapid);
  (void)fd;

  // Make the callback if the trap passed the filters
  if ((m_snmp) && (notify_filter(trapid, target)))
  {
    int reason;

    if (SNMP_CLASS_TL_FAILED == status)
      reason = SNMP_CLASS_TL_FAILED;
    else
      reason = SNMP_CLASS_NOTIFICATION;

    //------[ call into the callback function ]-------------------------
    if (m_snmp->get_notify_callback())
      (m_snmp->get_notify_callback())(
          reason,
          m_snmp,                        // snmp++ session who owns the req
          pdu,                        // trap pdu
          target,                        // target
          m_snmp->get_notify_callback_data()); // callback data
  }
  return SNMP_CLASS_SUCCESS;
}
Exemple #13
0
int Snmp::run_transaction(Pdu& pdu, UdpTarget& target)
{
  int rc, done = 0;

  // 1. set unique id to match this packet on return
  size_t hold_req_id = req_id_++;
  set_request_id(&pdu, hold_req_id);

  // 2. write request to agent
  transaction trans(pdu, target, iv_snmp_session_);

  // this call blocks while it attempts to retrieve agent response
  while (!done) {
    if ((rc = trans.run()) < 0) {
       last_transaction_status_ = rc;
       return rc;
    }
    else {
      trans.result(pdu);
      // verify this is the pdu we are after
      if (pdu.get_request_id() == hold_req_id)
        done = 1 ;
    }
  }
  return 0;
}
Exemple #14
0
Status SnmpManager::handleOperationGetNext(Request *request)
{
    Snmp::socket_startup();
    int status;
    Snmp snmp(status, 0, false);
    if (status != SNMP_CLASS_SUCCESS) {
        /*Setup SNMP FAILED*/
        Helper::log(0, "RequestGetNext Failed");
        Helper::log(1, snmp.error_msg(status));
        Helper::pop("Error", snmp.error_msg(status));
        Snmp::socket_cleanup();
        return Status_FAILED;
    }
    Pdu pdu;
    pdu += request->data;
    CTarget ctarget(request->address);
    ctarget.set_retry(request->retry);
    ctarget.set_timeout(request->timeout);
    ctarget.set_version(request->version);
    ctarget.set_readcommunity(request->community.c_str());
    SnmpTarget *target = &ctarget;
    status = snmp.get_next(pdu, *target);
    if (status == SNMP_CLASS_SUCCESS) {
        /*GetNextRequest SUCCESS*/
        Helper::log(1, "RequestGetNext SUCCESS");
        pdu.get_vb(request->data, 0);
        QString replayOid = request->data.get_printable_oid();
        QString replayValue = request->data.get_printable_value();
    }
    else {
        /*GetNextRequest FAILED*/
        Helper::log(0, "RequestGetNext Failed");
        Helper::log(1, snmp.error_msg(status));
        Helper::pop("Error", snmp.error_msg(status));
        Snmp::socket_cleanup();
        return Status_FAILED;
    }
    Snmp::socket_cleanup();
    qDebug() << "########################################################";
    qDebug() << "Handle RequestGetNext Successfully";
    qDebug() << "Oid:       " << request->data.get_printable_oid();
    qDebug() << "Value:     " << request->data.get_printable_value();
    qDebug() << "########################################################";
    return Status_SUCCESS;
}
Exemple #15
0
int Snmp::validate_args(const Pdu& pdu, const UdpTarget& target) const
{
  // 0. check object status
  if (construct_status_ != SNMP_CLASS_SUCCESS)
     return construct_status_;

  // 1. check args passed
  if ( !pdu.valid() || !target.valid() )
     return SNMP_INVALID_ARGS;
  return 0;
}
Exemple #16
0
int Snmp::set( Pdu &pdu, UdpTarget &target, Snmp_Result * cb)
{
  ACE_TRACE("Snmp::set");
  int rc;
  if ((rc = validate_args(pdu, target)) != 0)
     return rc;

   pdu.set_type( sNMP_PDU_SET);
   check_default_port(target);
   return run_transaction(pdu, target, cb);
}
Exemple #17
0
MibIter::MibIter(Snmp* snmp, Pdu& pdu, UdpTarget *target):
  snmp_(snmp), target_(target), pdu_(pdu), first_(0),
 valid_(0)
{
  // verify we have a valid oid to begin iterating with
  Oid oid;
  Vb vb;
  pdu.get_vb(vb, 0);
  vb.get_oid(oid);
  if (oid.valid())
    valid_ = 1;
}
Exemple #18
0
void callback( int reason, Snmp *snmp, Pdu &pdu, SnmpTarget &target, void *cd)
{
    Vb nextVb;
    int pdu_error;

    cout << "reason: " << reason << endl
         << "msg: " << snmp->error_msg(reason) << endl;

    pdu_error = pdu.get_error_status();
    if (pdu_error) {
        cout << "Response contains error: "
             << snmp->error_msg(pdu_error)<< endl;
    }
    for (int i=0; i<pdu.get_vb_count(); i++)
    {
        pdu.get_vb(nextVb, i);

        cout << "Oid: " << nextVb.get_printable_oid() << endl
             << "Val: " <<  nextVb.get_printable_value() << endl;
    }

    if (pdu.get_type() == sNMP_PDU_INFORM) {
        cout << "pdu type: " << pdu.get_type() << endl;
        cout << "sending response to inform: " << endl;
        nextVb.set_value("This is the response.");
        pdu.set_vb(nextVb, 0);
        snmp->response(pdu, target);
    }
    cout << endl;
}
Exemple #19
0
// return vb of next oid in agent tree, return 1 else return 0, reason set
int MibIter::next(Vb& vb, char *& reason)
{
  int rc;

  if (valid_ == 0) // not valid object
     return -1;

  // 1. poll for value
  if (first_ == 0) {
    rc = snmp_->get( pdu_, *target_);
    first_++;
  }
  else {
   rc = snmp_->get_next( pdu_, *target_);
  }

  if (rc != SNMP_CLASS_SUCCESS) {
       reason = const_cast <char*> (snmp_->error_string());
       return 0;
  }

  // 2. check for problems
  if (pdu_.get_error_status()) {
     reason = const_cast <char*> (pdu_.agent_error_reason());
     return 0;
  }

  // 3. return vb to caller
  pdu_.get_vb(vb, 0);
  Oid nextoid;
  vb.get_oid(nextoid); // and setup next oid to get
  Vb nextvb(nextoid);
  pdu_.delete_all_vbs();
  pdu_ += nextvb; // can't do set_vb as there are no entries to replace

  return 1; // ok
}
Exemple #20
0
// one way, best of luck, non-confirmed alert
int Snmp::trap( Pdu &pdu, UdpTarget &target)
{
  ACE_TRACE("Snmp::trap");
  int rc;
  if ((rc = validate_args(pdu, target)) != 0)
     return rc;

  pdu.set_type( sNMP_PDU_V1TRAP);
  check_default_port(target, DEF_TRAP_PORT);

  // 2. write request to agent
  transaction trans(pdu, target, iv_snmp_session_);
  if (trans.send() > 0)  // expect number of bytes sent on
    return 0;

  last_transaction_status_ = SNMP_CLASS_INTERNAL_ERROR;
  return -1;
}
// return pdu to caller
int transaction::result(Pdu& pdu, char *comm_str, ACE_INET_Addr *from)
{
  // TODO: check to see the sender matches the receiver address..

  // remove any vbs existing in this pdu
  pdu.delete_all_vbs();

 // any data to return?
 if (receive_iovec_.iov_len == 0)
   return -1;

 wpdu tmp(receive_iovec_);

 snmp_version ver;

 // return comm str and from address of incomming pdu if requested
 int rc = tmp.get_pdu(pdu, ver);
 if (comm_str)
   ACE_OS::strcpy(comm_str, (char *)tmp.get_community());
 if (from)
  *from = receive_addr_;
 return rc;
}
Exemple #22
0
void MainWindow::async_callback(int reason, Snmp * /*snmp*/, Pdu &pdu,
				SnmpTarget &target)
{
  Vb nextVb;
  int pdu_error;
  QString prefix_text;
  QString notify_text;

  push_button_get_next->setEnabled(true);

  // What is the reason for this callback?
  if (reason == SNMP_CLASS_NOTIFICATION)
  {
    prefix_text = "Trap:    ";

    // get the notify id for traps
    Oid id;
    pdu.get_notify_id(id);
    notify_text = QString(" ID: %1 Type %2 -- ").arg(id.get_printable())
                  .arg(pdu.get_type());
  }
  else if (reason == SNMP_CLASS_ASYNC_RESPONSE)
  {
    prefix_text = "Response ";
  }
  else if (reason == SNMP_CLASS_TIMEOUT)
  {
    prefix_text = "Timeout  ";
  }
  else
  {
    QString err = QString("\nDid not receive async response/trap: (%1) %2\n")
                  .arg(reason).arg(Snmp::error_msg(reason));
    text_edit_output->append(err);
  }


  // Look at the error status of the Pdu
  pdu_error = pdu.get_error_status();
  if (pdu_error)
  {
    QString err = "\nResponse contains error:\n";
    err += Snmp::error_msg(pdu_error);
    text_edit_output->append(err);
    return;
  }

  // The Pdu must contain at least one Vb
  if (pdu.get_vb_count() == 0)
  {
    QString err = "\nPdu is empty\n";
    text_edit_output->append(err);
    return;
  }

  for (int i=0; i<pdu.get_vb_count(); i++)
  {
    // Get the Vb of the Pdu
    pdu.get_vb(nextVb, i);

    // Get Oid and value from the Vb and display it
    line_edit_obj_id->setText(nextVb.get_printable_oid());
    line_edit_value->setText(nextVb.get_printable_value());

    text_edit_output->append(prefix_text +
			     target.get_address().get_printable() +
			     " -- " +
			     notify_text +
			     line_edit_obj_id->text() + " = " +
			     line_edit_value->text() + "\n");
  }

  // If we received a inform pdu, we have to send a response
  if (pdu.get_type() == sNMP_PDU_INFORM)
  {
    text_edit_output->append("Sending response to inform.\n");

    // just change the value of the first vb
    pdu.get_vb(nextVb, 0);
    nextVb.set_value("This is the response.");
    pdu.set_vb(nextVb, 0);
    snmp->response(pdu, target);
  }
}
Exemple #23
0
// issue a GET-NEXT request
void MainWindow::push_button_get_next_clicked()
{
  int status;

  if (!snmp)
    return;

  push_button_get_next->setEnabled(false);

  // Create a Oid and a address object from the entered values
  Oid oid(line_edit_obj_id->text());
  UdpAddress address(line_edit_target->text());

  // check if the address is valid
  // One problem here: if a hostname is entered, a blocking DNS lookup
  // is done by the address object.
  if (!address.valid())
  {
    QString err = QString("\nInvalid Address or DNS Name: %1\n")
                .arg(line_edit_target->text());
    text_edit_output->append(err);
    push_button_get_next->setEnabled(true);
    return;
  }

  Pdu pdu; // empty Pdu
  Vb vb;   // empty Vb
  SnmpTarget *target; // will point to a CTarget(v1/v2c) or UTarget (v3)

  // Set the Oid part of the Vb
  vb.set_oid(oid);

  // Add the Vb to the Pdu
  pdu += vb;

  // Get retries and timeout values
  int retries = spin_box_retries->value();
  int timeout = 100 * spin_box_timeout->value();
  
  if (radio_button_v3->isChecked())
  {
    // For SNMPv3 we need a UTarget object
    UTarget *utarget = new UTarget(address);

    utarget->set_version(version3);

    utarget->set_security_model(SNMP_SECURITY_MODEL_USM);
    utarget->set_security_name(combo_box_sec_name->currentText());
    
    target = utarget;

    // set the security level to use
    if (combo_box_sec_level->currentText() == "noAuthNoPriv")
      pdu.set_security_level(SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV);
    else if (combo_box_sec_level->currentText() == "authNoPriv")
      pdu.set_security_level(SNMP_SECURITY_LEVEL_AUTH_NOPRIV);
    else
      pdu.set_security_level(SNMP_SECURITY_LEVEL_AUTH_PRIV);

    // Not needed, as snmp++ will set it, if the user does not set it
    pdu.set_context_name(line_edit_context_name->text());
    pdu.set_context_engine_id(line_edit_context_engine_id->text());
  }
  else
  {
    // For SNMPv1/v2c we need a CTarget
    CTarget *ctarget = new CTarget(address);

    if (radio_button_v2->isChecked())
      ctarget->set_version(version2c);
    else
      ctarget->set_version(version1);

    // set the community
    ctarget->set_readcommunity( line_edit_community->text());

    target = ctarget;
  }

  target->set_retry(retries);            // set the number of auto retries
  target->set_timeout(timeout);          // set timeout

  // Now do an async get_next
  status = snmp->get_next(pdu, *target, callback, this);

  // Could we send it?
  if (status == SNMP_CLASS_SUCCESS)
  {
    timer.start(100);
  }
  else
  {
    QString err = QString("\nCould not send async GETNEXT request: %1\n")
                         .arg(Snmp::error_msg(status));
    text_edit_output->append(err);
    push_button_get_next->setEnabled(true);
  }

  // the target is no longer needed
  delete target;
}
Exemple #24
0
int main(int argc, char **argv)
{
   //---------[ check the arg count ]----------------------------------------
   if ( argc < 4 )
     usage();
   if ( strstr( argv[1],"-h") != 0 )
     help();
   if ( strstr( argv[1],"-?") != 0 )
     usage();

#if !defined(_NO_LOGGING) && !defined(WITH_LOG_PROFILES)
   // Set filter for logging
   DefaultLog::log()->set_filter(ERROR_LOG, 7);
   DefaultLog::log()->set_filter(WARNING_LOG, 7);
   DefaultLog::log()->set_filter(EVENT_LOG, 7);
   DefaultLog::log()->set_filter(INFO_LOG, 7);
   DefaultLog::log()->set_filter(DEBUG_LOG, 7);
#endif

   Snmp::socket_startup();  // Initialize socket subsystem

   //---------[ make a GenAddress and Oid object to retrieve ]---------------
   UdpAddress address( argv[1]);      // make a SNMP++ Generic address
   if ( !address.valid()) {           // check validity of address
	  cout << "Invalid Address or DNS Name, " << argv[1] << "\n";
	  usage();
   }

   OctetStr newUser, newPassword;
   if (((strstr( argv[2],"-")==0) && (strstr( argv[3],"-")==0))) {
	newUser = argv[2];
	newPassword = argv[3];
   }
   else
   {
     cout << "wrong parameters..." << endl;
     return 1;
   }

   //---------[ determine options to use ]-----------------------------------
   snmp_version version=version1;                  // default is v1
   int retries=1;                                  // default retries is 1
   int timeout=100;                                // default is 1 second
   u_short port=161;                               // default snmp port is 161
   OctetStr community("public");                   // community name

   OctetStr privPassword("");
   OctetStr authPassword("");
   OctetStr securityName("");
   int securityModel = SNMP_SECURITY_MODEL_USM;
   int securityLevel = SNMP_SECURITY_LEVEL_AUTH_PRIV;
   OctetStr contextName("");
   OctetStr contextEngineID("");
   long authProtocol = SNMP_AUTHPROTOCOL_NONE;
   long privProtocol = SNMP_PRIVPROTOCOL_NONE;
   OctetStr engineID;
   v3MP *v3_MP;

   char *ptr;

   for(int x=1;x<argc;x++) {                           // parse for version
     if ( strstr( argv[x],"-v2")!= 0) {
       version = version2c;
       continue;
     }
     if ( strstr( argv[x],"-r")!= 0) {                 // parse for retries
       ptr = argv[x]; ptr++; ptr++;
       retries = atoi(ptr);
       if (( retries<0)|| (retries>5)) retries=1; 
       continue;
     }
     if ( strstr( argv[x], "-t")!=0) {                 // parse for timeout
       ptr = argv[x]; ptr++; ptr++;
       timeout = atoi( ptr);
       if (( timeout < 100)||( timeout>500)) timeout=100;
       continue;
     }
     if ( strstr( argv[x],"-C")!=0) {
       ptr = argv[x]; ptr++; ptr++;
       community = ptr;
       continue;
     }
     if ( strstr( argv[x],"-P")!=0) {
       ptr = argv[x]; ptr++; ptr++;
       sscanf(ptr, "%hu", &port);
       continue;
     }
#ifdef WITH_LOG_PROFILES
     if ( strstr( argv[x], "-L" ) != 0 ) {
       ptr = argv[x]; ptr++; ptr++;
       DefaultLog::log()->set_profile(ptr);
     }
#endif

     if ( strstr( argv[x],"-v3")!= 0) {
       version = version3;
       continue;
     }
     if ( strstr( argv[x],"-auth") != 0) {
       ptr = argv[x]; ptr+=5;
       if (strcasecmp(ptr, "SHA") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_HMACSHA;
       else if (strcasecmp(ptr, "MD5") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_HMACMD5;
       else if (strcasecmp(ptr, "NONE") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_NONE;
       else
	 cout << "Warning: ignoring unknown auth protocol: " << ptr << endl;
       continue;
     }
     if ( strstr( argv[x],"-priv") != 0) {
       ptr = argv[x]; ptr+=5;
       if (strcasecmp(ptr, "DES") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_DES;
       else if (strcasecmp(ptr, "3DESEDE") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_3DESEDE;
       else if (strcasecmp(ptr, "IDEA") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_IDEA;
       else if (strcasecmp(ptr, "AES128") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES128;
       else if (strcasecmp(ptr, "AES192") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES192;
       else if (strcasecmp(ptr, "AES256") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES256;
       else if (strcasecmp(ptr, "NONE") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_NONE;
       else
	 cout << "Warning: ignoring unknown priv protocol: " << ptr << endl;
       continue;
     }
     if ( strstr( argv[x],"-sn")!=0) {
       ptr = argv[x]; ptr+=3;
       securityName = ptr;
       continue;
      }
     if ( strstr( argv[x], "-sl")!=0) {
       ptr = argv[x]; ptr+=3;
       securityLevel = atoi( ptr);
       if (( securityLevel < SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV) ||
           ( securityLevel > SNMP_SECURITY_LEVEL_AUTH_PRIV))
         securityLevel = SNMP_SECURITY_LEVEL_AUTH_PRIV;
       continue;
     }
     if ( strstr( argv[x], "-sm")!=0) {
       ptr = argv[x]; ptr+=3;
       securityModel = atoi( ptr);
       if (( securityModel < SNMP_SECURITY_MODEL_V1) ||
           ( securityModel > SNMP_SECURITY_MODEL_USM))
         securityModel = SNMP_SECURITY_MODEL_USM;
       continue;
     }
     if ( strstr( argv[x],"-cn")!=0) {
       ptr = argv[x]; ptr+=3;
       contextName = ptr;
       continue;
     }
     if ( strstr( argv[x],"-ce")!=0) {
       ptr = argv[x]; ptr+=3;
       contextEngineID = OctetStr::from_hex_string(ptr);
       continue;
     }
     if ( strstr( argv[x],"-ua")!=0) {
       ptr = argv[x]; ptr+=3;
       authPassword = ptr;
       continue;
     }
     if ( strstr( argv[x],"-up")!=0) {
       ptr = argv[x]; ptr+=3;
       privPassword = ptr;
       continue;
     }
     if ( strstr( argv[x],"-e")!=0) {
       ptr = argv[x]; ptr+=2;
       engineID = OctetStr::from_hex_string(ptr);
       continue;
     }
   }

   //----------[ create a SNMP++ session ]-----------------------------------
   int status;
   // bind to any port and use IPv6 if needed
   Snmp snmp(status, 0, (address.get_ip_version() == Address::version_ipv6));

   if ( status != SNMP_CLASS_SUCCESS) {
      cout << "SNMP++ Session Create Fail, " << snmp.error_msg(status) << "\n";
      return 1;
   }

   //---------[ init SnmpV3 ]--------------------------------------------
   if (version == version3) {
     OctetStr engineId = "snmpPasswd";
     const char *filename = "snmpv3_boot_counter";
     unsigned int snmpEngineBoots = 0;
     int status;

     status = getBootCounter(filename, engineId, snmpEngineBoots);
     if ((status != SNMPv3_OK) && (status < SNMPv3_FILEOPEN_ERROR))
     {
       cout << "Error loading snmpEngineBoots counter: " << status << endl;
       return 1;
     }
     snmpEngineBoots++;
     status = saveBootCounter(filename, engineId, snmpEngineBoots);
     if (status != SNMPv3_OK)
     {
       cout << "Error saving snmpEngineBoots counter: " << status << endl;
       return 1;
     }

     int construct_status;
     v3_MP = new v3MP(engineId, snmpEngineBoots, construct_status);
     if (construct_status != SNMPv3_MP_OK)
     {
       cout << "Error initializing v3MP: " << construct_status << endl;
       return 1;
     }

     usm = v3_MP->get_usm();
     usm->add_usm_user(securityName,
		       authProtocol, privProtocol,
		       authPassword, privPassword);
   }
   else
   {
     // MUST create a dummy v3MP object if _SNMPv3 is enabled!
     int construct_status;
     v3_MP = new v3MP("dummy", 0, construct_status);
   }

   //--------[ build up SNMP++ object needed ]-------------------------------
   Pdu pdu;                               // construct a Pdu object
   Vb vb;                                 // construct a Vb object
   vb.set_oid(Oid("1.3.6.1.2.1.1.1.0"));  // set the Oid portion of the Vb
   pdu += vb;                             // add the vb to the Pdu

   address.set_port(port);
   CTarget ctarget( address);             // make a target using the address
   UTarget utarget( address);

   if (version == version3) {
     utarget.set_version( version);          // set the SNMP version SNMPV1 or V2 or V3
     utarget.set_retry( retries);            // set the number of auto retries
     utarget.set_timeout( timeout);          // set timeout
     utarget.set_security_model( securityModel);
     utarget.set_security_name( securityName);
     pdu.set_security_level( securityLevel);
     pdu.set_context_name (contextName);
     pdu.set_context_engine_id(contextEngineID);
   }
   else {
     ctarget.set_version( version);         // set the SNMP version SNMPV1 or V2
     ctarget.set_retry( retries);           // set the number of auto retries
     ctarget.set_timeout( timeout);         // set timeout
     ctarget.set_readcommunity( community); // set the read community name
   }

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "SNMP++ Get to " << argv[1] << " SNMPV" 

        << ((version==version3) ? (version) : (version+1)) 
        << " Retries=" << retries
        << " Timeout=" << timeout * 10 <<"ms"; 
   if (version == version3)
     cout << endl
          << "securityName= " << securityName.get_printable()
          << ", securityLevel= " << securityLevel
          << ", securityModel= " << securityModel << endl
          << "contextName= " << contextName.get_printable()
          << ", contextEngineID= " << contextEngineID.get_printable()
          << endl;
   else
     cout << " Community=" << community.get_printable() << endl << flush;

   SnmpTarget *target;
   if (version == version3)
     target = &utarget;
   else
     target = &ctarget;
   Pdu pduKeyChange;
   if (version == version3) {
     pduKeyChange.set_security_level( securityLevel);
     pduKeyChange.set_context_name (contextName);
     pduKeyChange.set_context_engine_id(contextEngineID);
   }
   
   snmp.get( pdu, *target);

   KeyChange(&snmp, pduKeyChange, newUser, newPassword, *target, AUTHKEY);

   Snmp::socket_cleanup();  // Shut down socket subsystem
} 
Exemple #25
0
wpdu::wpdu(const Pdu& pdu, const UdpTarget& target):
   valid_flag_(SNMP_CLASS_INVALID ), comm_len(MAX_COMM_STR_LEN)
{
   reset_iov(iovec_);
   version_ = target.get_version();
   int status;
   OctetStr comm_str;

   community_name[0] = 0;

   snmp_pdu *raw_pdu;   // create a raw pdu
   raw_pdu = cmu_snmp::pdu_create( (int) pdu.get_type());
   if (!raw_pdu) {
     valid_flag_ = SNMP_CLASS_RESOURCE_UNAVAIL;
     return;
   }

   raw_pdu->reqid = pdu.get_request_id();
   raw_pdu->errstat= (unsigned long) pdu.get_error_status();
   raw_pdu->errindex= (unsigned long) pdu.get_error_index();

   switch (raw_pdu->command) {
     case sNMP_PDU_GET:
     case sNMP_PDU_GETNEXT:
       target.get_read_community(comm_str);
       break;

     case sNMP_PDU_SET:
       target.get_write_community(comm_str);
       break;

     case sNMP_PDU_V1TRAP:
       target.get_read_community(comm_str);
       if (set_trap_info(raw_pdu, pdu)) // will free raw_pdu
          return;
       break;
     case sNMP_PDU_RESPONSE:
       break;

   default:
     ACE_ASSERT(0);
     return;
   }

   if (load_vbs(raw_pdu, pdu)) {
     cmu_snmp::free_pdu( raw_pdu);
     valid_flag_ = SNMP_CLASS_RESOURCE_UNAVAIL;
     return;
   }

   // TODO: determine how big raw_pdu serializes out to
   iovec_.iov_len = target.get_max_pdu_size();
   ACE_NEW(iovec_.iov_base, char [iovec_.iov_len]);

   // create raw byte stream
   // The intermediate integer is to avoid type-punned pointer
   // dereferencing.
   int out_length = iovec_.iov_len;
   status = cmu_snmp::build( raw_pdu,
                            (unsigned char *)iovec_.iov_base,
                            &out_length,
                            target.get_version(),
                            comm_str.data(),
                            comm_str.length());
   iovec_.iov_len = out_length;

   if ( status != 0) {
     valid_flag_ = SNMP_ERROR_WRONG_ENCODING;
     cmu_snmp::free_pdu( raw_pdu);
     return;
   }

   cmu_snmp::free_pdu( raw_pdu);
   valid_flag_ = SNMP_CLASS_SUCCESS;
}
Exemple #26
0
int CSVBaseSNMP::GetRequest(MonitorResult &ResultList)
{
	WriteLog("\n\n*****************************");
	WriteLog("GetRequest!");

    int nResult = 0;
    Pdu pdu;                                                    // construct a Pdu object
    Vb vb;                                                      // construct a Vb object
    vb.set_oid( oid);                                           // set the Oid portion of the Vb
    pdu += vb;                                                  // add the vb to the Pdu

    SnmpTarget *target;
    if(version == version3)
    {//If SNMP Version Is 3
        nResult = InitUTarget();                                //Init UTarget
        pdu.set_security_level( m_lSecurityLevel);              //Set the Security Level portion of Pdu
        pdu.set_context_name(m_szContextName);                  //Set the Context Name portion of Pdu
        pdu.set_context_engine_id(m_szContextEngineID);         //Set the Context Engine ID portion of Pdu
        target = &m_Utarget;                                    //Set SNMP Target
    }
    else
    {
        target = &m_Ctarget;                                    //Set SNMP Target
    }

    try
    {
        //cout << address << endl;
        //cout << oid.get_printable() << endl;
        if(m_pSnmp)
        {
            nResult = m_pSnmp->get( pdu,*target);               //Get Reques
            if(nResult != 0)
            {//当有错误发生时候
                m_szErrorMsg =  m_pSnmp->error_msg(nResult);
                return nResult;
            }
            for ( int i = 0; i < pdu.get_vb_count(); i ++)
            {
                pdu.get_vb(vb, i);
                if (pdu.get_type() == REPORT_MSG) 
                {
                    Oid tmp;
                    vb.get_oid(tmp);
                    return -5;
                }
                // look for var bind exception, applies to v2 only   
                if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
                {
                    SNMP_Monitor_Result result;
                    result.m_szOID = vb.get_printable_oid();
                    result.m_szValue = vb.get_printable_value();
                    size_t nPosition = result.m_szOID.rfind(".");
                    if(nPosition > 0)
                    {
                        result.m_szIndex = result.m_szOID.substr(nPosition);
                        result.m_szOID = result.m_szOID.substr(0, nPosition - 1);
                    }

					WriteLog(result.m_szIndex.c_str());
					WriteLog(result.m_szValue.c_str());

                    ResultList[i] = result;
                }
                else 
                {
                    m_szErrorMsg =  "End of MIB Reached";
                    return -4;
                }
            }
        }
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetRequest*---", dwError);
        DumpLog("snmpmonitor-request", szMsg, nlen);
    }
    return nResult;
}
Exemple #27
0
int CSVBaseSNMP::GetBulkRequest(MonitorResult &ResultList)
{
	
	WriteLog("\n\n*****************************");
	WriteLog("GetBulkRequest!");

    static const int BULK_BUFF = 10;
    int nResult = 0;
    char chPrvOID[MAX_BUFF_LEN] = {0};
    bool bEnd = false;
    Pdu pdu;                                                // construct a Pdu object
    Vb vb;                                                  // construct a Vb object
    vb.set_oid( oid);                                       // set the Oid portion of the Vb
    pdu += vb;                                              // add the vb to the Pdu

    SnmpTarget *target;
    if(version ==version3)
    {//If SNMP Version Is 3
        nResult = InitUTarget();                            //Init UTarget
        pdu.set_security_level( m_lSecurityLevel);          //Set the Security Level portion of Pdu
        pdu.set_context_name (m_szContextName);             //Set the Context Name portion of Pdu
        pdu.set_context_engine_id(m_szContextEngineID);     //Set the Context Engine ID portion of Pdu
        target = &m_Utarget;                                //Set SNMP Target
    }
    else
    {
        target = &m_Ctarget; //Set SNMP Target
    }
    
    try
    {
        if(m_pSnmp)
        {
            int nIndex = 0, i = 0;
            while (( nResult = m_pSnmp->get_bulk(pdu, *target, 0, BULK_BUFF)) == SNMP_CLASS_SUCCESS) 
            {
                if(bEnd)
                    break;
                for (i = 0; i < pdu.get_vb_count(); i ++) 
                {
                    pdu.get_vb( vb, i);
                    if (pdu.get_type() == REPORT_MSG) 
                    {
                        Oid tmp;
                        vb.get_oid(tmp);
                        return -5;
                    }
                    // look for var bind exception, applies to v2 only   
                    if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
                    {
                        string szOID =  vb.get_printable_oid();
						WriteLog(szOID.c_str());
                        int nPosition = static_cast<int>(szOID.find(m_szStartID));
                        if(nPosition < 0)
                        {
                            bEnd = true;
                            break;
                        }
                        if(static_cast<int>(strlen(chPrvOID)) > 0)
                        {//如果上次OID不为空
                            if(strcmp(vb.get_printable_oid(), chPrvOID) == 0)
                            {//比较OID名称是否相同,相同则退出循环
                                bEnd = true;
                                break;
                            }
                        }
				        //结果赋值
                        if(static_cast<int>(strlen(vb.get_printable_oid())) < MAX_BUFF_LEN)
                            strcpy(chPrvOID, vb.get_printable_oid());

						
                        SNMP_Monitor_Result result;
						result.m_szOID = vb.get_printable_oid();
						if(strcmp(result.m_szOID.substr(0,19).c_str(),"1.3.6.1.2.1.2.2.1.2")==0)
						{
							char str[100];
							vb.get_value(str);
							result.m_szValue=str;
							WriteLog(str);
						}
						else
							result.m_szValue = vb.get_printable_value();
        
                        //nPosition = static_cast<int>(result.m_szOID.find(m_szStartID.c_str()) + m_szStartID.length());
                        //if(nPosition > 0)
                        //{
                        result.m_szIndex = result.m_szOID.substr(m_szStartID.length() + 1);
                        result.m_szOID = result.m_szOID.substr(0, m_szStartID.length());
                        //PrintDebugString("index is " + result.m_szIndex);
                        //}
						WriteLog(result.m_szIndex.c_str());
						WriteLog(result.m_szValue.c_str());

                        ResultList[nIndex] = result;
                        nIndex ++;
                    }
                    else 
                    {
                        m_szErrorMsg = "End of MIB Reached";
                        return -4;
                    }
                }
                // last vb becomes seed of next rquest
                pdu.set_vblist(&vb, 1);
            }
        }
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetBulkRequest*---", dwError);
        DumpLog("snmpmonitor-bulk.log", szMsg, nlen);
    }

    if(nResult == SNMP_ERROR_NO_SUCH_NAME)
    {
        nResult = 0;
    }
	return nResult;
}
Exemple #28
0
int wpdu::set_trap_info(snmp_pdu *raw_pdu, const Pdu& pdu) const
{
  Oid enterprise;
  Oid trapid; // validate caller has set this correctly
  pdu.get_notify_id( trapid);
  if ( !trapid.valid() || trapid.length() < 2 ) {
     cmu_snmp::free_pdu( raw_pdu);
     return SNMP_CLASS_INVALID_NOTIFYID;
  }


  raw_pdu->specific_type=0;

  // TODO: object should emit numeric instead of this kind of mess...
  if ( trapid == coldStart)
    raw_pdu->trap_type = V1_COLD_START;  // cold start
  else if ( trapid == warmStart)
    raw_pdu->trap_type = V1_WARM_START;  // warm start
  else if( trapid == linkDown)
    raw_pdu->trap_type = V1_LINK_DOWN;  // link down
  else if ( trapid == linkUp)
    raw_pdu->trap_type = V1_LINK_UP;  // link up
  else if ( trapid == authenticationFailure )
    raw_pdu->trap_type = V1_AUTH_FAILURE;  // authentication failure
  else if ( trapid == egpNeighborLoss)
    raw_pdu->trap_type = V1_EGP_NEIGHBOR_LOSS;  // egp neighbor loss
  else {
    raw_pdu->trap_type = V1_ENT_SPECIFIC;     // enterprise specific
                               // last oid subid is the specific value
                               // if 2nd to last subid is "0", remove it
                               // enterprise is always the notify oid prefix
   raw_pdu->specific_type = (int) trapid[(int) (trapid.length() - 1)];
   trapid.trim(1);
   if ( trapid[(int)(trapid.length() - 1)] == 0 )
     trapid.trim(1);
   enterprise = trapid;
  }

  if ( raw_pdu->trap_type != V1_ENT_SPECIFIC)
    pdu.get_notify_enterprise( enterprise);
  if ( enterprise.length() > 0) {
    // note!!  To the contrary, enterprise OID val is
    // copied here and raw_pdu->enterprise is freed in free_pdu
    // as it should be (HDN)
    // these are hooks into an SNMP++ oid
    // and therefor the raw_pdu enterprise
    // should not free them. null them out!!
    SmiLPOID rawOid;
    rawOid = enterprise.oidval();
    // HDN - enterprise is a local object, cannot simply assign pointer
    //raw_pdu->enterprise = rawOid->ptr;
    raw_pdu->enterprise_length = (int) rawOid->len;
    ACE_NEW_RETURN(raw_pdu->enterprise,
                   oid[raw_pdu->enterprise_length],-1);
    ACE_OS::memcpy((char *)raw_pdu->enterprise,(char *)rawOid->ptr,
                   raw_pdu->enterprise_length * sizeof(oid));
  }

  TimeTicks timestamp;
  pdu.get_notify_timestamp( timestamp);
  raw_pdu->time = ( unsigned long) timestamp;

  // HDN - set agent addr using the local hostname if possible
  char localHostName[MAXHOSTNAMELEN];
  Snmp::get_host_name(localHostName, MAXHOSTNAMELEN);
  if (ACE_OS::strlen(localHostName) > 0) {
    GenAddress addr(localHostName);
    OctetStr octet;
    addr.to_octet(octet);
    ACE_OS::memcpy(&(raw_pdu->agent_addr.sin_addr),
                   octet.data(),
                   octet.length());
  }

  return 0;
}
Exemple #29
0
int CSNMPMessage::SetPdu(const int reason, const Pdu &pdu,
			 const UdpAddress &fromaddress)
{
  if (Pdu::match_type(m_pdu.get_type(), pdu.get_type()) == false)
  {
    LOG_BEGIN(INFO_LOG | 1);
    LOG("MsgQueue: Response pdu type does not match, pdu is ignored: (id) (type1) (type2)");
    LOG(m_uniqueId);
    LOG(m_pdu.get_type());
    LOG(pdu.get_type());
    LOG_END;

    return -1;
  }

  unsigned short orig_type = m_pdu.get_type();
  if (m_received)
  {
    LOG_BEGIN(WARNING_LOG | 1);
    LOG("MsgQueue: Message is already marked as received (id) (reason) (new reason)");
    LOG(m_uniqueId);
    LOG(reason);
    LOG(m_reason);
    LOG_END;

    // TODO: better check based on error codes
    if (reason || !m_reason)
    {
      LOG_BEGIN(WARNING_LOG | 1);
      LOG("MsgQueue: ignoring the second pdu");
      LOG_END;

      return 0;
    }
  }
  m_received = 1;
  m_pdu = pdu;
  m_reason = reason;

  if ((orig_type == sNMP_PDU_INFORM) &&
      (m_pdu.get_type() == sNMP_PDU_RESPONSE))
  {
    // remove the first two vbs of the pdu if sysUpTime and notify_id
    if (m_pdu.get_vb_count() < 2)
      return 0;

    const Vb &vb1 = m_pdu.get_vb(0);
    if (vb1.get_syntax() != sNMP_SYNTAX_TIMETICKS)   return 0;
    if (vb1.get_oid()    != SNMP_MSG_OID_SYSUPTIME)  return 0;

    const Vb &vb2 = m_pdu.get_vb(1);
    if (vb2.get_syntax() != sNMP_SYNTAX_OID)         return 0;
    if (vb2.get_oid()    != SNMP_MSG_OID_TRAPID)     return 0;

    TimeTicks timeticks;
    Oid oid;

    vb1.get_value(timeticks);
    m_pdu.set_notify_timestamp(timeticks);

    vb2.get_value(oid);
    m_pdu.set_notify_id(oid);

    m_pdu.delete_vb(1);
    m_pdu.delete_vb(0);
  }
  return 0;
}
Exemple #30
0
int main(int argc, char **argv)
{
    //---------[ check the arg count ]----------------------------------------
    if ( argc < 2) {
        cout << "Usage:\n";
        cout << argv[0] << " IpAddress | DNSName [Oid] [options]\n";
        cout << "Oid: sysDescr object is default\n";
        cout << "options: -vN , use SNMP version 1, 2 or 3, default is 1\n";
        cout << "         -PPort , remote port to use\n";
        cout << "         -CCommunity_name, specify community default is 'public' \n";
        cout << "         -rN , retries default is N = 1 retry\n";
        cout << "         -tN , timeout in hundredths of seconds; default is N = 100\n";
#ifdef _SNMPv3
        cout << "         -snSecurityName, " << endl;
        cout << "         -slN , securityLevel to use, default N = 3 = authPriv" << endl;
        cout << "         -smN , securityModel to use, only default N = 3 = USM possible\n";
        cout << "         -cnContextName, default empty string" << endl;
        cout << "         -ceContextEngineID, as hex e.g. 800007E580, default empty string" << endl;
        cout << "         -authPROT, use authentication protocol NONE, SHA or MD5\n";
        cout << "         -privPROT, use privacy protocol NONE, DES, 3DESEDE, IDEA, AES128, AES192 or AES256\n";
        cout << "         -uaAuthPassword\n";
        cout << "         -upPrivPassword\n";
#endif
        return 1;
    }

    Snmp::socket_startup();  // Initialize socket subsystem

    //---------[ make a GenAddress and Oid object to retrieve ]---------------
    UdpAddress address( argv[1]);      // make a SNMP++ Generic address
    if ( !address.valid()) {           // check validity of address
        cout << "Invalid Address or DNS Name, " << argv[1] << "\n";
        return 1;
    }
    Oid oid("1.3.6.1.2.1.1.1");      // default is sysDescr
    if ( argc >= 3) {                  // if 3 args, then use the callers Oid
        if ( strstr( argv[2],"-")==0) {
            oid = argv[2];
            if ( !oid.valid()) {            // check validity of user oid
                cout << "Invalid Oid, " << argv[2] << "\n";
                return 1;
            }
        }
    }

    //---------[ determine options to use ]-----------------------------------
    snmp_version version=version1;                  // default is v1
    int retries=1;                                  // default retries is 1
    int timeout=100;                                // default is 1 second
    u_short port=161;                               // default snmp port is 161
    OctetStr community("public");                   // community name

#ifdef _SNMPv3
    OctetStr privPassword("");
    OctetStr authPassword("");
    OctetStr securityName("");
    int securityModel = SecurityModel_USM;
    int securityLevel = SecurityLevel_authPriv;
    OctetStr contextName("");
    OctetStr contextEngineID("");
    long authProtocol = SNMPv3_usmNoAuthProtocol;
    long privProtocol = SNMPv3_usmNoPrivProtocol;
    v3MP *v3_MP;
#endif

    char *ptr;

    for(int x=1; x<argc; x++) {                         // parse for version
        if ( strstr( argv[x],"-v2")!= 0) {
            version = version2c;
            continue;
        }
        if ( strstr( argv[x],"-r")!= 0) {                 // parse for retries
            ptr = argv[x];
            ptr++;
            ptr++;
            retries = atoi(ptr);
            if (( retries<0)|| (retries>5)) retries=1;
            continue;
        }
        if ( strstr( argv[x], "-t")!=0) {                 // parse for timeout
            ptr = argv[x];
            ptr++;
            ptr++;
            timeout = atoi( ptr);
            if (( timeout < 100)||( timeout>500)) timeout=100;
            continue;
        }
        if ( strstr( argv[x],"-C")!=0) {
            ptr = argv[x];
            ptr++;
            ptr++;
            community = ptr;
            continue;
        }
        if ( strstr( argv[x],"-P")!=0) {
            ptr = argv[x];
            ptr++;
            ptr++;
            sscanf(ptr, "%hu", &port);
            continue;
        }

#ifdef _SNMPv3
        if ( strstr( argv[x],"-v3")!= 0) {
            version = version3;
            continue;
        }
        if ( strstr( argv[x],"-auth") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "SHA") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACSHA;
            else if (strcasecmp(ptr, "MD5") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACMD5;
            else
                authProtocol = SNMP_AUTHPROTOCOL_NONE;
            continue;
        }
        if ( strstr( argv[x],"-priv") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "DES") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_DES;
            else if (strcasecmp(ptr, "3DESEDE") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_3DESEDE;
            else if (strcasecmp(ptr, "IDEA") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_IDEA;
            else if (strcasecmp(ptr, "AES128") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES128;
            else if (strcasecmp(ptr, "AES192") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES192;
            else if (strcasecmp(ptr, "AES256") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES256;
            else
                privProtocol = SNMP_PRIVPROTOCOL_NONE;
            printf("\n\nPrivProt : %ld\n", privProtocol);
            continue;
        }
        if ( strstr( argv[x],"-sn")!=0) {
            ptr = argv[x];
            ptr+=3;
            securityName = ptr;
            continue;
        }
        if ( strstr( argv[x], "-sl")!=0) {
            ptr = argv[x];
            ptr+=3;
            securityLevel = atoi( ptr);
            if (( securityLevel < SecurityLevel_noAuthNoPriv) ||
                    ( securityLevel > SecurityLevel_authPriv))
                securityLevel = SecurityLevel_authPriv;
            continue;
        }
        if ( strstr( argv[x], "-sm")!=0) {
            ptr = argv[x];
            ptr+=3;
            securityModel = atoi( ptr);
            if (( securityModel < SecurityModel_v1) ||
                    ( securityModel > SecurityModel_USM))
                securityModel = SecurityModel_USM;
            continue;
        }
        if ( strstr( argv[x],"-cn")!=0) {
            ptr = argv[x];
            ptr+=3;
            contextName = ptr;
            continue;
        }
        if ( strstr( argv[x],"-ce")!=0) {
            ptr = argv[x];
            ptr+=3;
            contextEngineID = OctetStr::from_hex_string(ptr);
            continue;
        }
        if ( strstr( argv[x],"-ua")!=0) {
            ptr = argv[x];
            ptr+=3;
            authPassword = ptr;
            continue;
        }
        if ( strstr( argv[x],"-up")!=0) {
            ptr = argv[x];
            ptr+=3;
            privPassword = ptr;
            continue;
        }
#endif
    }

    //----------[ create a SNMP++ session ]-----------------------------------
    int status;
    // bind to any port and use IPv6 if needed
    Snmp snmp(status, 0, (address.get_ip_version() == Address::version_ipv6));

    if ( status != SNMP_CLASS_SUCCESS) {
        cout << "SNMP++ Session Create Fail, " << snmp.error_msg(status) << "\n";
        return 1;
    }

    //---------[ init SnmpV3 ]--------------------------------------------
#ifdef _SNMPv3
    if (version == version3) {
        char *engineId = "snmpNextAsync";
        char *filename = "snmpv3_boot_counter";
        unsigned int snmpEngineBoots = 0;
        int status;

        status = getBootCounter(filename, engineId, snmpEngineBoots);
        if ((status != SNMPv3_OK) && (status < SNMPv3_FILEOPEN_ERROR))
        {
            cout << "Error loading snmpEngineBoots counter: " << status << endl;
            return 1;
        }
        snmpEngineBoots++;
        status = saveBootCounter(filename, engineId, snmpEngineBoots);
        if (status != SNMPv3_OK)
        {
            cout << "Error saving snmpEngineBoots counter: " << status << endl;
            return 1;
        }

        int construct_status;
        v3_MP = new v3MP(engineId, snmpEngineBoots, construct_status);

        USM *usm = v3_MP->get_usm();
        usm->add_usm_user(securityName,
                          authProtocol, privProtocol,
                          authPassword, privPassword);
    }
    else
    {
        // MUST create a dummy v3MP object if _SNMPv3 is enabled!
        int construct_status;
        v3_MP = new v3MP("dummy", 0, construct_status);
    }
#endif

    //--------[ build up SNMP++ object needed ]-------------------------------
    Pdu pdu;                               // construct a Pdu object
    Vb vb;                                 // construct a Vb object
    vb.set_oid( oid);                      // set the Oid portion of the Vb
    pdu += vb;                             // add the vb to the Pdu

    address.set_port(port);
    CTarget ctarget( address);             // make a target using the address
#ifdef _SNMPv3
    UTarget utarget( address);

    if (version == version3) {
        utarget.set_version( version);          // set the SNMP version SNMPV1 or V2 or V3
        utarget.set_retry( retries);            // set the number of auto retries
        utarget.set_timeout( timeout);          // set timeout
        utarget.set_security_model( securityModel);
        utarget.set_security_name( securityName);
        pdu.set_security_level( securityLevel);
        pdu.set_context_name (contextName);
        pdu.set_context_engine_id(contextEngineID);
    }
    else {
#endif
        ctarget.set_version( version);         // set the SNMP version SNMPV1 or V2
        ctarget.set_retry( retries);           // set the number of auto retries
        ctarget.set_timeout( timeout);         // set timeout
        ctarget.set_readcommunity( community); // set the read community name
#ifdef _SNMPv3
    }
#endif

    //-------[ issue the request, blocked mode ]-----------------------------
    cout << "SNMP++ GetNext to " << argv[1] << " SNMPV"
#ifdef _SNMPv3
         << ((version==version3) ? (version) : (version+1))
#else
         << (version+1)
#endif
         << " Retries=" << retries
         << " Timeout=" << timeout * 10 <<"ms";
#ifdef _SNMPv3
    if (version == version3)
        cout << endl
             << "securityName= " << securityName.get_printable()
             << ", securityLevel= " << securityLevel
             << ", securityModel= " << securityModel << endl
             << "contextName= " << contextName.get_printable()
             << ", contextEngineID= " << contextEngineID.get_printable()
             << endl;
    else
#endif
        cout << " Community=" << community.get_printable() << endl << flush;

    SnmpTarget *target;
#ifdef _SNMPv3
    if (version == version3)
        target = &utarget;
    else
#endif
        target = &ctarget;

    status = snmp.get_next( pdu, *target, callback,NULL);

    if (status == SNMP_CLASS_SUCCESS)
    {
        cout << "Async GetNext Request sent." << endl;
    }
    else
        cout << "SNMP++ GetNext Error, " << snmp.error_msg( status)
             << " (" << status <<")" << endl ;

    for (int t=1; t<=10; t++)
    {
        snmp.eventListHolder->SNMPProcessPendingEvents();
#ifdef WIN32
        Sleep(1000);
#else
        sleep(1);
#endif
    }

    Snmp::socket_cleanup();  // Shut down socket subsystem
}