Beispiel #1
0
int
snmp_init(selector_t *sel)
{
    struct snmp_session session;
#ifdef HAVE_NETSNMP
    netsnmp_transport *transport = NULL;
    static char *snmp_default_port = "udp:162";

    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
			   NETSNMP_DS_LIB_MIB_ERRORS,
			   0);

    init_snmp("ipmi_ui");

    transport = netsnmp_tdomain_transport(snmp_default_port, 1, "udp");
    if (!transport) {
        snmp_sess_perror("ipmi_ui", &session);
	return -1;
    }
#else
    void *transport = NULL;
#endif
    snmp_sess_init(&session);
    session.peername = SNMP_DEFAULT_PEERNAME;
    session.version = SNMP_DEFAULT_VERSION;
    session.community_len = SNMP_DEFAULT_COMMUNITY_LEN;
    session.retries = SNMP_DEFAULT_RETRIES;
    session.timeout = SNMP_DEFAULT_TIMEOUT;
    session.local_port = SNMP_TRAP_PORT;
    session.callback = snmp_input;
    session.callback_magic = transport;
    session.authenticator = NULL;
    session.isAuthoritative = SNMP_SESS_UNKNOWNAUTH;

#ifdef HAVE_NETSNMP
    snmp_session = snmp_add(&session, transport, snmp_pre_parse, NULL);
#else
    snmp_session = snmp_open_ex(&session, snmp_pre_parse,
				NULL, NULL, NULL, NULL);
#endif
    if (snmp_session == NULL) {
        snmp_sess_perror("ipmi_ui", &session);
	return -1;
    }

    ipmi_sel_set_read_fds_handler(sel,
				  snmp_add_read_fds,
				  snmp_check_read_fds,
				  snmp_check_timeout,
				  NULL);

    return 0;
}
Beispiel #2
0
/*
 * send_trap_to_sess: sends a trap to a session but assumes that the
 * pdu is constructed correctly for the session type. 
 */
void
send_trap_to_sess(netsnmp_session * sess, netsnmp_pdu *template_pdu)
{
    netsnmp_pdu    *pdu;

    if (!sess || !template_pdu)
        return;

    DEBUGMSGTL(("trap", "sending trap type=%d, version=%d\n",
                template_pdu->command, sess->version));

    if (sess->version == SNMP_VERSION_1 &&
        (template_pdu->command == SNMP_MSG_TRAP2 ||
         template_pdu->command == SNMP_MSG_INFORM))
        return;                 /* Skip v1 sinks for v2 only traps */
    template_pdu->version = sess->version;
    pdu = snmp_clone_pdu(template_pdu);
    pdu->sessid = sess->sessid; /* AgentX only ? */
    if (snmp_send(sess, pdu) == 0) {
        snmp_sess_perror("snmpd: send_trap", sess);
        snmp_free_pdu(pdu);
    } else {
        snmp_increment_statistic(STAT_SNMPOUTTRAPS);
        snmp_increment_statistic(STAT_SNMPOUTPKTS);
    }
}
Beispiel #3
0
int
create_trap_session(char *sink, u_short sinkport,
                    char *com, int version, int pdutype)
{
    netsnmp_session session, *sesp;
    char           *peername = NULL;

    if ((peername = malloc(strlen(sink) + 4 + 32)) == NULL) {
        return 0;
    } else {
        snprintf(peername, strlen(sink) + 4 + 32, "udp:%s:%hu", sink,
                 sinkport);
    }

    memset(&session, 0, sizeof(netsnmp_session));
    session.peername = peername;
    session.version = version;
    if (com) {
        session.community = (u_char *) com;
        session.community_len = strlen(com);
    }
    sesp = snmp_open(&session);
    free(peername);

    if (sesp) {
        return add_trap_session(sesp, pdutype,
                                (pdutype == SNMP_MSG_INFORM), version);
    }

    /*
     * diagnose snmp_open errors with the input netsnmp_session pointer 
     */
    snmp_sess_perror("snmpd: create_trap_session", &session);
    return 0;
}
Beispiel #4
0
int
init_master_agent(int dest_port, 
                  int (*pre_parse) (struct snmp_session *, snmp_ipaddr),
                  int (*post_parse) (struct snmp_session *, struct snmp_pdu *,int))
{
    struct snmp_session sess, *session;

    if ( ds_get_boolean(DS_APPLICATION_ID, DS_AGENT_ROLE) != MASTER_AGENT )
	return 0; /* no error if ! MASTER_AGENT */

    DEBUGMSGTL(("snmpd","installing master agent on port %d\n", dest_port));

    snmp_sess_init( &sess );
    
    sess.version = SNMP_DEFAULT_VERSION;
    sess.peername = SNMP_DEFAULT_PEERNAME;
    sess.community_len = SNMP_DEFAULT_COMMUNITY_LEN;
     
    sess.local_port = dest_port;
    sess.callback = handle_snmp_packet;
    sess.authenticator = NULL;
    sess.flags = ds_get_int(DS_APPLICATION_ID, DS_AGENT_FLAGS);
    session = snmp_open_ex( &sess, pre_parse, 0, post_parse, 0, 0 );

    if ( session == NULL ) {
      /* diagnose snmp_open errors with the input struct snmp_session pointer */
	snmp_sess_perror("init_master_agent", &sess);
		return 1;
    }
    main_session = session;
	return 0;
}
/**
 * Helper for snmp_init
 */
static void open_session_helper(netsnmp_session *local, netsnmp_session **remote)
{
	*remote = snmp_open(local);

	if (!*remote) {
		snmp_sess_perror("SNMP ack", local);
		exit(EXIT_FAILURE);
	}
}
/*
 * send_trap_to_sess: sends a trap to a session but assumes that the
 * pdu is constructed correctly for the session type. 
 */
void
send_trap_to_sess(netsnmp_session * sess, netsnmp_pdu *template_pdu)
{
    netsnmp_pdu    *pdu;
    int            result;
    int            len;


    if (!sess || !template_pdu)
        return;

    DEBUGMSGTL(("trap", "sending trap type=%d, version=%ld\n",
                template_pdu->command, sess->version));

#ifndef NETSNMP_DISABLE_SNMPV1
    if (sess->version == SNMP_VERSION_1 &&
        (template_pdu->command != SNMP_MSG_TRAP))
        return;                 /* Skip v1 sinks for v2 only traps */
    if (sess->version != SNMP_VERSION_1 &&
        (template_pdu->command == SNMP_MSG_TRAP))
        return;                 /* Skip v2+ sinks for v1 only traps */
#endif
    template_pdu->version = sess->version;
    pdu = snmp_clone_pdu(template_pdu);
    pdu->sessid = sess->sessid; /* AgentX only ? */

    if ( template_pdu->command == SNMP_MSG_INFORM
#ifdef USING_AGENTX_PROTOCOL_MODULE
         || template_pdu->command == AGENTX_MSG_NOTIFY
#endif
       ) {
        result =
            snmp_async_send(sess, pdu, &handle_inform_response, NULL);
        
    } else {
        if ((sess->version == SNMP_VERSION_3) &&
                (pdu->command == SNMP_MSG_TRAP2) &&
                (sess->securityEngineIDLen == 0)) {
            u_char          tmp[SPRINT_MAX_LEN];

            len = snmpv3_get_engineID(tmp, sizeof(tmp));
            memdup(&pdu->securityEngineID, tmp, len);
            pdu->securityEngineIDLen = len;
        }

        result = snmp_send(sess, pdu);
    }

    if (result == 0) {
        snmp_sess_perror("snmpd: send_trap", sess);
        snmp_free_pdu(pdu);
    } else {
        snmp_increment_statistic(STAT_SNMPOUTTRAPS);
        snmp_increment_statistic(STAT_SNMPOUTPKTS);
    }
}
Beispiel #7
0
/** Write on/off status
*/
double  setMainSwitch(HSNMP m_sessp,float value) {
  struct snmp_pdu* pdu = snmp_pdu_create(SNMP_MSG_SET);    // prepare set-request pdu
  pdu->community = (u_char*)strdup(writeCommunity);
  pdu->community_len = strlen(writeCommunity);

  // for(each SET request to one crate) {
  int v = (int) value;
  snmp_pdu_add_variable(pdu,oidSysMainSwitch,lengthSysMainSwitch,ASN_INTEGER,(u_char*)&v,sizeof(v));
  // } // endfor

  struct snmp_pdu* response;
	int status = snmp_sess_synch_response(m_sessp,pdu,&response);

  /*
  * Process the response.
  */

  if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
    /*
    * SUCCESS: Print the result variables
    */
    struct variable_list *vars;
    
    // debug print
    //for(vars = response->variables; vars; vars = vars->next_variable)
    //  print_variable(vars->name, vars->name_length, vars);

    /* manipuate the information ourselves */
    for(vars = response->variables; vars; vars = vars->next_variable) {
			if (vars->type == ASN_OPAQUE_FLOAT) {				    // 0x78
        value = *vars->val.floatVal;
      }
			else if (vars->type == ASN_OPAQUE_DOUBLE) {			// 0x79
        value = *vars->val.doubleVal;
      }
			else if(vars->type == ASN_INTEGER) {				      // 0x02
				value = (double)*vars->val.integer;
      }
    }
  } else {
    /*
    * FAILURE: print what went wrong!
    */

    if (status == STAT_SUCCESS)
      fprintf(stderr, "Error in packet\nReason: %s\n",
      snmp_errstring(response->errstat));
    else
      snmp_sess_perror("snmpget",snmp_sess_session(m_sessp));
    return 0;
  }
  snmp_free_pdu(response);


  return value;
}
Beispiel #8
0
/** Get current from power supply
*/
double getCurrentMeasurement(HSNMP m_sessp, int channel) {
  double value;

  struct snmp_pdu* pdu = snmp_pdu_create(SNMP_MSG_GET);    // prepare get-request pdu

  // for(each GET request to one crate) {
    snmp_add_null_var(pdu,oidOutputMeasurementCurrent[channel],lengthOutputMeasurementCurrent[channel]);   // generate request data
  // } // endfor

  struct snmp_pdu* response;
	int status = snmp_sess_synch_response(m_sessp,pdu,&response);


  /*
  * Process the response.
  */
  if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
    /*
    * SUCCESS: Print the result variables
    */
    struct variable_list *vars;
    
    // debug print
    //for(vars = response->variables; vars; vars = vars->next_variable)
    //  print_variable(vars->name, vars->name_length, vars);

    /* manipuate the information ourselves */
    for(vars = response->variables; vars; vars = vars->next_variable) {
			if (vars->type == ASN_OPAQUE_FLOAT) {				    // 0x78
        value = *vars->val.floatVal;
      }
			else if (vars->type == ASN_OPAQUE_DOUBLE) {			// 0x79
        value = *vars->val.doubleVal;
      }
			else if(vars->type == ASN_INTEGER) {				      // 0x02
				value = (double)*vars->val.integer;
      }
    }
  } else {
    /*
    * FAILURE: print what went wrong!
    */

    if (status == STAT_SUCCESS)
      fprintf(stderr, "Error in packet\nReason: %s\n",
      snmp_errstring(response->errstat));
    else
      snmp_sess_perror("snmpget",snmp_sess_session(m_sessp));
    return 0;
  }
  snmp_free_pdu(response);


  return value;
}
Beispiel #9
0
void init_master(void)
{
    struct snmp_session sess, *session;

    if ( ds_get_boolean(DS_APPLICATION_ID, DS_AGENT_ROLE) != MASTER_AGENT )
	return;

    DEBUGMSGTL(("agentx/master","initializing...\n"));
    snmp_sess_init( &sess );
    sess.version  = AGENTX_VERSION_1;
    sess.flags  |= SNMP_FLAGS_STREAM_SOCKET;
    if ( ds_get_string(DS_APPLICATION_ID, DS_AGENT_X_SOCKET) )
	sess.peername = strdup(ds_get_string(DS_APPLICATION_ID, DS_AGENT_X_SOCKET));
    else
	sess.peername = strdup(AGENTX_SOCKET);

    if ( sess.peername[0] == '/' ) {
			/*
			 *  If this is a Unix pathname,
			 *  try and create the directory first.
			 */
	if (mkdirhier(sess.peername, AGENT_DIRECTORY_MODE, 1)) {
	    snmp_log(LOG_ERR,
		"Failed to create the directory for the agentX socket: %s\n",
                 sess.peername);
	}
    }
			/*
			 *  Otherwise, let 'snmp_open' interpret the string.
			 */
    sess.local_port  = AGENTX_PORT;         /* Indicate server & set default port */
    sess.remote_port = 0;
    sess.callback = handle_master_agentx_packet;
    session = snmp_open_ex( &sess, 0, agentx_parse, 0, agentx_build,
                            agentx_check_packet );

    if ( session == NULL && sess.s_errno == EADDRINUSE ) {
		/*
		 * Could be a left-over socket (now deleted)
		 * Try again
		 */
        session = snmp_open_ex( &sess, 0, agentx_parse, 0, agentx_build,
                            agentx_check_packet );
    }

    if ( session == NULL ) {
      /* diagnose snmp_open errors with the input struct snmp_session pointer */
	snmp_sess_perror("init_master", &sess);
        if (!ds_get_boolean(DS_APPLICATION_ID, DS_AGENT_NO_ROOT_ACCESS))
          exit(1);
    }

    DEBUGMSGTL(("agentx/master","initializing...   DONE\n"));
}
Beispiel #10
0
// handle err if connection fails
void errHandles(int stat) {
 if (status == STAT_SUCCESS)
        fprintf(stderr, "Error in packet\nReason: %s\n",
                snmp_errstring(response->errstat));
      else if (status == STAT_TIMEOUT)
        fprintf(stderr, "Timeout: No response from %s.\n",
                session.peername);
      else
        snmp_sess_perror("snmpdemoapp", ss);

}
Beispiel #11
0
int
create_trap_session(char *sink, u_short sinkport,
                    char *com, int version, int pdutype)
{
    netsnmp_session session, *sesp;
    char           *peername = NULL;
    int             len;

    len = strlen(sink) + 4 + 32;
    if ((peername = malloc(len)) == NULL) {
        return 0;
    } else if (NULL != strchr(sink,':')) {
        snprintf(peername, len, "%s", sink);
    } else {
        snprintf(peername, len, "udp:%s:%hu", sink, sinkport);
    }

    memset(&session, 0, sizeof(netsnmp_session));
    session.peername = peername;
    session.version = version;
    if (com) {
        session.community = (u_char *) com;
        session.community_len = strlen(com);
    }

    /*
     * for informs, set retries to default
     */
    if (SNMP_MSG_INFORM == pdutype) {
        session.timeout = SNMP_DEFAULT_TIMEOUT;
        session.retries = SNMP_DEFAULT_RETRIES;
    }

    /*
     * if the sink is localhost, bind to localhost, to reduce open ports.
     */
    if ((NULL == netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                       NETSNMP_DS_LIB_CLIENT_ADDR)) && 
        ((0 == strcmp("localhost",sink)) || (0 == strcmp("127.0.0.1",sink))))
        session.localname = "localhost";
    sesp = snmp_open(&session);
    free(peername);

    if (sesp) {
        return add_trap_session(sesp, pdutype,
                                (pdutype == SNMP_MSG_INFORM), version);
    }

    /*
     * diagnose snmp_open errors with the input netsnmp_session pointer 
     */
    snmp_sess_perror("snmpd: create_trap_session", &session);
    return 0;
}
Beispiel #12
0
netsnmp_variable_list *
collect(netsnmp_session * ss, netsnmp_pdu *pdu,
        oid * base, size_t base_length)
{
    netsnmp_pdu    *response;
    int             running = 1;
    netsnmp_variable_list *saved = NULL, **vlpp = &saved;
    int             status;

    while (running) {
        /*
         * gotta catch em all, gotta catch em all! 
         */
        status = snmp_synch_response(ss, pdu, &response);
        if (status != STAT_SUCCESS || !response) {
            snmp_sess_perror("snmpdf", ss);
            exit(1);
        }
        if (response->errstat != SNMP_ERR_NOERROR) {
	    fprintf(stderr, "snmpdf: Error in packet: %s\n",
                    snmp_errstring(response->errstat));
            exit(1);
        }
        if (response && snmp_oid_compare(response->variables->name,
                                         SNMP_MIN(base_length,
                                                  response->variables->
                                                  name_length), base,
                                         base_length) != 0)
            running = 0;
        else {
            /*
             * get response 
             */
            *vlpp = response->variables;
            (*vlpp)->next_variable = NULL;      /* shouldn't be any, but just in case */

            /*
             * create the next request 
             */
            pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
            snmp_add_null_var(pdu, (*vlpp)->name, (*vlpp)->name_length);

            /*
             * finish loop setup 
             */
            vlpp = &((*vlpp)->next_variable);
            response->variables = NULL; /* ahh, forget about it */
        }
        snmp_free_pdu(response);
    }
    return saved;
}
Beispiel #13
0
bool Session::getVariables(const QStringList &oids, QValueVector<QVariant> &retvars, uint32_t &status, int startIndex)
{
	struct snmp_pdu *response = NULL;
	if ( ! m_session )
	{
		status = 0xFFFFFFFF;
		return false;
	}
	
	struct snmp_pdu *pdu = snmp_pdu_create(SNMP_MSG_GET);

	u_long anOID[MAX_OID_LEN];
	
	QStringList::const_iterator it = oids.begin();
	for(int i = 0; i < startIndex; i++) it++; // rough hack, but works
	
	for(int i = 0; it != oids.end() && i < 5; it++, i++ )
	{
		size_t anOID_len = MAX_OID_LEN;
		get_node((*it).latin1(), anOID, &anOID_len);
		snmp_add_null_var(pdu, anOID, anOID_len);
	}
	
	status = snmp_synch_response(m_session, pdu, &response);
	
	//! @todo Error handling should be changed in a more OO way.
	if ( status != STAT_SUCCESS )
	{
		snmp_sess_perror("snmpget", m_session);
		return false;
	}
	
	if ( response->errstat != SNMP_ERR_NOERROR )
	{
		kdWarning() << "Error in packet: " << snmp_errstring(response->errstat) << endl;
		snmp_free_pdu(response);
		return false;
	}

	variable_list *var = response->variables;
	int i = startIndex;
	while( var )
	{
		retvars[i] = snmpvarToVariant(var);
		i++;
		var = var->next_variable;
	}
	
	snmp_free_pdu(response);
	
	return true;
}
Beispiel #14
0
SaErrorT snmp_getn_bulk( struct snmp_session *ss, 
		    oid *bulk_objid, 
		    size_t bulk_objid_len,
		    struct snmp_pdu *bulk_pdu, 
		    struct snmp_pdu **bulk_response,
		    int num_repetitions )
{
	int status;
	SaErrorT rtncode = SA_OK;
//        struct variable_list *vars;

	bulk_pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
 	
	bulk_pdu->non_repeaters = 0; 
	
	bulk_pdu->max_repetitions = num_repetitions;

	snmp_add_null_var(bulk_pdu, bulk_objid, bulk_objid_len);
	
	/* Send the Request out.*/
	status = snmp_synch_response(ss, bulk_pdu, bulk_response);

	/*
	 * Process the response.
	*/
#if 0
	if (status == STAT_SUCCESS) {
		vars = (*bulk_response)->variables;
		if ((*bulk_response)->errstat == SNMP_ERR_NOERROR) {
			if (!CHECH_END(vars->type)) {
                                /* This is one of the exception condition */
				rtncode = SA_ERR_HPI_NOT_PRESENT;
				dbg("snmp exception %d \n",vars->type);
			}
		} else {
			fprintf(stderr, "Error in packet %s\nReason: %s\n",
					(char *)bulk_objid, snmp_errstring((*bulk_response)->errstat));
			if ((*bulk_response)->errstat == SNMP_ERR_NOSUCHNAME)
					(*bulk_response)->errstat = SNMP_NOSUCHOBJECT;
			rtncode = (SaErrorT) (SA_ERR_SNMP_BASE - (*bulk_response)->errstat);
		}
	} else {
		snmp_sess_perror("snmpset", ss);
		rtncode = (SaErrorT) (SA_ERR_SNMP_BASE - status);
	}
#endif
	return(rtncode);

}
Beispiel #15
0
SaErrorT net_snmp_failure(struct snmp_client_hnd *custom_handle, int snmp_status, 
				 struct snmp_pdu *response)
{
	if (snmp_status == STAT_SUCCESS) {
		dbg("Error in packet, Whilst getting Resources\nReason: %s", 
		    snmp_errstring(response->errstat));
		dbg("ERROR: net_snmp_failure %s", 
		    snmp_errstring(response->errstat));
	} else	{
		snmp_sess_perror("snmpget", custom_handle->ss);
		dbg("ERROR: net_snmp_failure");
	}

	return(SA_ERR_HPI_ERROR);
}
Beispiel #16
0
void
snmpd_parse_config_trapsess(const char *word, char *cptr)
{
    char           *argv[MAX_ARGS], *cp = cptr, tmp[SPRINT_MAX_LEN];
    int             argn, arg;
    netsnmp_session session, *ss;

    /*
     * inform or trap?  default to trap 
     */
    traptype = SNMP_MSG_TRAP2;

    /*
     * create the argv[] like array 
     */
    argv[0] = strdup("snmpd-trapsess"); /* bogus entry for getopt() */
    for (argn = 1; cp && argn < MAX_ARGS; argn++) {
        cp = copy_nword(cp, tmp, SPRINT_MAX_LEN);
        argv[argn] = strdup(tmp);
    }

    arg = snmp_parse_args(argn, argv, &session, "C:", trapOptProc);
    ss = snmp_open(&session);

    for (; argn > 0; argn--) {
        free(argv[argn - 1]);
    }

    if (!ss) {
        config_perror
            ("snmpd: failed to parse this line or the remote trap receiver is down.  Possible cause:");
        snmp_sess_perror("snmpd: snmpd_parse_config_trapsess()", &session);
        return;
    }

#ifndef DISABLE_SNMPV1
    if (ss->version == SNMP_VERSION_1) {
        add_trap_session(ss, SNMP_MSG_TRAP, 0, SNMP_VERSION_1);
    } else {
#endif
        add_trap_session(ss, traptype, (traptype == SNMP_MSG_INFORM),
                         ss->version);
#ifndef DISABLE_SNMPV1
    }
#endif
}
Beispiel #17
0
char *session_query(struct snmp_session *ss, struct snmp_pdu *pdu) {

  struct snmp_pdu *response;
  struct variable_list *vars;
  int status;
  char buf[SPRINT_MAX_LEN];
  char *rbuffer=NULL;
    
  /* Send the Request */
  status = snmp_synch_response(ss, pdu, &response);

  /* Process the response */
  if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR )
 {
    /* Success: Print the results */
    /* for (vars=response->variables; vars; vars=vars->next_variable) { */
    vars=response->variables;
    
    if (vars!=NULL && vars->type <ASN_LONG_LEN) {
      if (vars->type == ASN_INTEGER) {
         sprintf(buf,"%ld",*vars->val.integer);
		 rbuffer=malloc(sizeof(char)*(strlen(buf)+1));
     	 memset(rbuffer,'\0',strlen(buf)+1);
         strncpy(rbuffer,buf,strlen(buf));
      } else {
         snprint_variable(buf, sizeof (buf), vars->name, vars->name_length, vars);
         rbuffer=malloc(sizeof(char)*(strlen(buf)+1));
     	 memset(rbuffer,'\0',strlen(buf)+1);
         strncpy(rbuffer,buf,strlen(buf));
	  }
    } else rbuffer = NULL;     

  } else {
    /* Failure: print what went wrong */
    if (status == STAT_SUCCESS)
      fprintf(stderr,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat));
    else
      snmp_sess_perror("snmpget ", ss);
  }

  /* Clean up */
  if (response) snmp_free_pdu(response);

//  printf("Result : %s\n",rbuffer);
  return rbuffer;
}
Beispiel #18
0
char *session_set( struct snmp_session *ss,const char *name, const char *value ) {
  struct snmp_pdu *pdu, *response;
  oid anOID[MAX_OID_LEN];
  size_t anOID_len = MAX_OID_LEN;
  struct variable_list *vars;
  int status;
  char buf[SPRINT_MAX_LEN];
  char *rbuffer=NULL;

  /* create PDU for request */
  pdu = snmp_pdu_create(SNMP_MSG_SET);
  get_node(name, anOID, &anOID_len);
  snmp_add_var(pdu, anOID, anOID_len,'i',value);
//  snmp_add_null_var(pdu, anOID, anOID_len);

  /* Send the Request */
  status = snmp_synch_response(ss, pdu, &response);

  /* Process the response */
  if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
    /* Success: Print the results */

    /* for (vars=response->variables; vars; vars=vars->next_variable) { */
    vars=response->variables;
	if (vars!=NULL) {
      snprint_variable(buf, sizeof (buf), vars->name, vars->name_length, vars);
      rbuffer=malloc(sizeof(char)*(strlen(buf)+1));
      memset(rbuffer,'\0',strlen(buf)+1);
      strncpy(rbuffer,buf,strlen(buf));
    } else rbuffer = NULL;     

  } else {
    /* Failure: print what went wrong */
    if (status == STAT_SUCCESS)
       fprintf(stderr,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat));
    else
      snmp_sess_perror("snmpset", ss);
  }

  /* Clean up */
  /*  if (pdu) snmp_free_pdu(pdu); */
  if (response) snmp_free_pdu(response);

  return rbuffer;
}
Beispiel #19
0
static int
create_trap_session2(const char *sink, const char* sinkport,
		     char *com, int version, int pdutype)
{
    netsnmp_transport *t;
    netsnmp_session session, *sesp;

    memset(&session, 0, sizeof(netsnmp_session));
    session.version = version;
    if (com) {
        session.community = (u_char *) com;
        session.community_len = strlen(com);
    }

    /*
     * for informs, set retries to default
     */
    if (SNMP_MSG_INFORM == pdutype) {
        session.timeout = SNMP_DEFAULT_TIMEOUT;
        session.retries = SNMP_DEFAULT_RETRIES;
    }

    /*
     * if the sink is localhost, bind to localhost, to reduce open ports.
     */
    if ((NULL == netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                       NETSNMP_DS_LIB_CLIENT_ADDR)) && 
        ((0 == strcmp("localhost",sink)) || (0 == strcmp("127.0.0.1",sink))))
        session.localname = "localhost";

    t = netsnmp_tdomain_transport_full("snmptrap", sink, 0, NULL, sinkport);
    if (t != NULL) {
	sesp = snmp_add(&session, t, NULL, NULL);

	if (sesp) {
	    return add_trap_session(sesp, pdutype,
				    (pdutype == SNMP_MSG_INFORM), version);
	}
    }
    /*
     * diagnose snmp_open errors with the input netsnmp_session pointer 
     */
    snmp_sess_perror("snmpd: create_trap_session", &session);
    return 0;
}
Beispiel #20
0
// a higher abstraction function takes oid string and SNMP methods and call
void snmpcommand(char* oid,int cmd) {
    SOCK_STARTUP;
    ss = snmp_open(&session);                     /* establish the session */
    if (!ss) {
      snmp_sess_perror("ack", &session);
      SOCK_CLEANUP;
      exit(1);
    }
    pdu = snmp_pdu_create(cmd);
     if ( cmd == SNMP_MSG_GETBULK) { // for bulkget only
    pdu->non_repeaters  = 0;
    pdu->max_repetitions  = 50;
 }
    anOID_len = MAX_OID_LEN;
   get_node(oid, anOID, &anOID_len);
    snmp_add_null_var(pdu, anOID, anOID_len);// all OID should be paired with null for out going req
    status = snmp_synch_response(ss, pdu, &response); // sent req
}
Beispiel #21
0
static netsnmp_session *snmptrapd_add_session(netsnmp_transport *t) {
    netsnmp_session sess, *session = &sess, *rc = NULL;
    snmp_sess_init(session);
    session->peername = SNMP_DEFAULT_PEERNAME;  /* Original code had NULL here */
    session->version = SNMP_DEFAULT_VERSION;
    session->community_len = SNMP_DEFAULT_COMMUNITY_LEN;
    session->retries = SNMP_DEFAULT_RETRIES;
    session->timeout = SNMP_DEFAULT_TIMEOUT;
    session->callback = snmp_input;
    session->callback_magic = (void *) t;
    session->authenticator = NULL;
    sess.isAuthoritative = SNMP_SESS_UNKNOWNAUTH;
    rc = snmp_add(session, t, pre_parse, NULL);
    if (rc == NULL) {
        snmp_sess_perror("snmptrapd", session);
    }
    return rc;
}
Beispiel #22
0
/*
 * send_trap_to_sess: sends a trap to a session but assumes that the
 * pdu is constructed correctly for the session type. 
 */
void
send_trap_to_sess(netsnmp_session * sess, netsnmp_pdu *template_pdu)
{
    netsnmp_pdu    *pdu;
    int            result;

    if (!sess || !template_pdu)
        return;

    DEBUGMSGTL(("trap", "sending trap type=%d, version=%d\n",
                template_pdu->command, sess->version));

#ifndef DISABLE_SNMPV1
    if (sess->version == SNMP_VERSION_1 &&
        (template_pdu->command != SNMP_MSG_TRAP))
        return;                 /* Skip v1 sinks for v2 only traps */
#endif
    template_pdu->version = sess->version;
    pdu = snmp_clone_pdu(template_pdu);
    pdu->sessid = sess->sessid; /* AgentX only ? */

    if ( template_pdu->command == SNMP_MSG_INFORM
#ifdef USING_AGENTX_PROTOCOL_MODULE
         || template_pdu->command == AGENTX_MSG_NOTIFY
#endif
       ) {
        result =
            snmp_async_send(sess, pdu, &handle_inform_response, NULL);
        
    } else {
        result = snmp_send(sess, pdu);
    }

    if (result == 0) {
        snmp_sess_perror("snmpd: send_trap", sess);
        snmp_free_pdu(pdu);
    } else {
        snmp_increment_statistic(STAT_SNMPOUTTRAPS);
        snmp_increment_statistic(STAT_SNMPOUTPKTS);
    }
}
struct snmp_session *
simpleSNMPopen(gchar *peername,
	       gint port,
	       gchar *community,
	       void *data)
{
    struct snmp_session session, *ss;

    /*
     * initialize session to default values
     */
    snmp_sess_init( &session );

    session.version = SNMP_VERSION_1;
    session.community = community;
    session.community_len = strlen(community);
    session.peername = peername;
    session.remote_port = port;

    session.retries = SNMP_DEFAULT_RETRIES;
    session.timeout = SNMP_DEFAULT_TIMEOUT;

    session.callback = snmp_input;
    session.callback_magic = data; /* most likely a Reader */
    session.authenticator = NULL;

#ifdef STREAM
    session.flags |= SNMP_FLAGS_STREAM_SOCKET;
#endif

    /* 
     * Open an SNMP session.
     */
    ss = snmp_open(&session);
    if (ss == NULL){
        snmp_sess_perror("snmp_open", &session);
        // exit(1);
    }

    return ss;
}
Beispiel #24
0
bool Session::getVariable(const QString &oid, QVariant &retvar, uint32_t &status)
{
	QMutexLocker ml(&m_mutex);
	struct snmp_pdu *response = NULL;
	if ( ! m_session )
	{
		status = 0xFFFFFFFF;
		return false;
	}
	
	// Buffer requestd for net-snmp library
	u_long anOID[MAX_OID_LEN];
	size_t anOID_len = MAX_OID_LEN;
	
	// Prepare the PDU for a GET command
	struct snmp_pdu *pdu = snmp_pdu_create(SNMP_MSG_GET);
	get_node(oid.latin1(), anOID, &anOID_len);
	snmp_add_null_var(pdu, anOID, anOID_len);
	
	status = snmp_synch_response(m_session, pdu, &response);
	
	//! @todo Error handling should be changed in a more OO way.
	if ( status != STAT_SUCCESS )
	{
		snmp_sess_perror("snmpget", m_session);
		return false;
	}
	
	if ( response->errstat != SNMP_ERR_NOERROR )
	{
		kdWarning() << "Error in packet: " << snmp_errstring(response->errstat) << endl;
		snmp_free_pdu(response);
		return false;
	}

	retvar = snmpvarToVariant(response->variables);
	snmp_free_pdu(response);
	
	return true;
}
Beispiel #25
0
/*
 *  Trap handler for forwarding to another destination
 */
int   forward_handler( netsnmp_pdu           *pdu,
                       netsnmp_transport     *transport,
                       netsnmp_trapd_handler *handler)
{
    netsnmp_session session, *ss;
    netsnmp_pdu *pdu2;
    char buf[BUFSIZ], *cp;

    DEBUGMSGTL(( "snmptrapd", "forward_handler (%s)\n", handler->token));

    snmp_sess_init( &session );
    if (strchr( handler->token, ':') == NULL) {
        snprintf( buf, BUFSIZ, "%s:%d", handler->token, SNMP_TRAP_PORT);
        cp = buf;
    } else {
        cp = handler->token;
    }
    session.peername = cp;
    session.version  = pdu->version;
    ss = snmp_open( &session );
    if (!ss)
        return NETSNMPTRAPD_HANDLER_FAIL;

    /* XXX: wjh we should be caching sessions here and not always
       reopening a session.  It's very ineffecient, especially with v3
       INFORMS which may require engineID probing */

    pdu2 = snmp_clone_pdu(pdu);
    if (pdu2->transport_data) {
        free(pdu2->transport_data);
        pdu2->transport_data        = NULL;
        pdu2->transport_data_length = 0;
    }
    if (!snmp_send( ss, pdu2 )) {
	snmp_sess_perror("Forward failed", ss);
	snmp_free_pdu(pdu2);
    }
    snmp_close( ss );
    return NETSNMPTRAPD_HANDLER_OK;
}
Beispiel #26
0
int create_trap_session (char *sink, u_short sinkport,
				char *com,
				int version, int pdutype)
{
    struct snmp_session	 session, *sesp;

    memset (&session, 0, sizeof (struct snmp_session));
    session.peername = sink;
    session.version = version;
    if (com) {
        session.community = (u_char *)com;
        session.community_len = strlen (com);
    }
    session.remote_port = sinkport;
    sesp = snmp_open (&session);

    if (sesp) {
	return( add_trap_session( sesp, pdutype, version ));
    }

    /* diagnose snmp_open errors with the input struct snmp_session pointer */
    snmp_sess_perror("snmpd: create_trap_session", &session);
    return 0;
}
Beispiel #27
0
int snmptop(int argc, char **argv)
{
    netsnmp_session session, *ss;
    int             arg;
    struct hrSWRunTable *oproc;
    int             ocount = 0;
    int             show_idle = 1;
    int             show_os = 1;
    char            ch;
    struct cpuStats oldCpu;
    struct memStats mem;
    int             has_cpu, has_mem; 

    /*
     * get the common command line arguments 
     */
    switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) {
    case NETSNMP_PARSE_ARGS_ERROR:
        exit(1);
    case NETSNMP_PARSE_ARGS_SUCCESS_EXIT:
        exit(0);
    case NETSNMP_PARSE_ARGS_ERROR_USAGE:
        usage();
        exit(1);
    default:
        break;
    }

    if (arg != argc) {
        fprintf(stderr, "snmptop: extra argument: %s\n", argv[arg]);
        exit(1);
    }

    SOCK_STARTUP;

    /*
     * Open an SNMP session.
     */
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmptop", &session);
        SOCK_CLEANUP;
        exit(1);
    }

    ocount = collect_perf(ss, &oproc);
    if (ocount == 0) {
        fprintf(stderr, "snmptop: no processes found\n");
        exit(1);
    }

    collect_cpu(ss, &oldCpu);

    signal(SIGINT, endtop);
    initscr();
    cbreak();
    noecho();
    nonl();
    halfdelay(50);

    while ((ch = getch()) != 'q') {
        int ncount;
        struct hrSWRunTable *nproc;
        int oinx = 0, ninx = 0, line = 0;
        netsnmp_pdu    *pdu;
        netsnmp_pdu    *response = NULL;
        int status;
        time_t clock;
        struct tm *ptm;
        char uptime[40];
        char timestr[40];
        char b1[15], b2[15], b3[15], b4[15];
        struct cpuStats newCpu;

        if (ch == 'c' || ch == 'm' || ch == 'n' || ch == 't') topsort = ch;
        if (ch == 'i') show_idle = !show_idle;
        if (ch == 'o') show_os = !show_os;
        if (ch == 'a') command_args = !command_args;
        if (ch == 'p') command_path = !command_path;

        ncount = collect_perf(ss, &nproc);

        while (oinx < ocount && ninx < ncount) {
            if (oproc[oinx].hrSWRunIndex == nproc[ninx].hrSWRunIndex) {
                nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU-oproc[oinx].hrSWRunPerfCPU;
                ninx++;
                oinx++;
            }
            else if (nproc[oinx].hrSWRunIndex < oproc[ninx].hrSWRunIndex)
                oinx++;
            else {
                nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU;
                ninx++;
            }
        }
        while (ninx < ncount) {
            nproc[ninx].hrSWRunPerfCPUInc = nproc[ninx].hrSWRunPerfCPU;
            ninx++;
        }

        switch (topsort) {
        case 'c':
            qsort(nproc, ncount, sizeof(nproc[0]), cpucomp);
            break;
        case 'm':
            qsort(nproc, ncount, sizeof(nproc[0]), memcomp);
            break;
        case 't':
            qsort(nproc, ncount, sizeof(nproc[0]), totcomp);
            break;
        }

        has_cpu = collect_cpu(ss, &newCpu);
        has_mem = collect_mem(ss, &mem);

        pdu = snmp_pdu_create(SNMP_MSG_GET);
        add(pdu, "HOST-RESOURCES-MIB:hrSystemUptime.0", NULL, 0);
        status = snmp_synch_response(ss, pdu, &response);
        if (status != STAT_SUCCESS || !response ||
                response->errstat != SNMP_ERR_NOERROR) {
            uptime[0] = '\0';
        }
        else {
            netsnmp_variable_list *vlp = response->variables;
            if (vlp->type == SNMP_NOSUCHINSTANCE) abort();
            uptime_string_n(*vlp->val.integer, uptime, sizeof(uptime));
        }
        snmp_free_pdu(response);

        clock = time(NULL);
        ptm = localtime(&clock);
        strftime(timestr, sizeof(timestr), "%H:%M:%S", ptm);

        clear();
        move(0, 0);
        printw("%s %s%s", session.peername, uptime[0] ? "up " : "", uptime);
        move(0, COLS-strlen(timestr)-1);
        printw("%s", timestr);
        if (has_cpu) {
            struct cpuStats deltaCpu;
            u_long sumCpu;

            deltaCpu.user = newCpu.user - oldCpu.user;
            deltaCpu.nice = newCpu.nice - oldCpu.nice;
            deltaCpu.system = newCpu.system - oldCpu.system;
            deltaCpu.idle = newCpu.idle - oldCpu.idle;
            deltaCpu.wait = newCpu.wait - oldCpu.wait;
            deltaCpu.kernel = newCpu.kernel - oldCpu.kernel;
            deltaCpu.intr = newCpu.intr - oldCpu.intr;
            deltaCpu.softintr = newCpu.softintr - oldCpu.softintr;
            deltaCpu.steal = newCpu.steal - oldCpu.steal;
            deltaCpu.guest = newCpu.guest - oldCpu.guest;
            deltaCpu.guestnice = newCpu.guestnice - oldCpu.guestnice;
            oldCpu = newCpu;
            sumCpu = deltaCpu.user + deltaCpu.nice
                + deltaCpu.system + deltaCpu.idle
                + deltaCpu.wait + deltaCpu.kernel + deltaCpu.steal
                + deltaCpu.intr + deltaCpu.softintr
                + deltaCpu.guest + deltaCpu.guestnice;

            printw("\nCPU%%: %4.1fUs %4.1fSy %4.1fId %3.1fWa %3.1fNi %3.1fKe %3.1fHi %3.1fSi %3.1fSt %3.1fGu %3.1fGN",
                (float)deltaCpu.user*100/sumCpu,
                (float)deltaCpu.system*100/sumCpu,
                (float)deltaCpu.idle*100/sumCpu,
                (float)deltaCpu.wait*100/sumCpu,
                (float)deltaCpu.nice*100/sumCpu,
                (float)deltaCpu.kernel*100/sumCpu,
                (float)deltaCpu.intr*100/sumCpu,
                (float)deltaCpu.softintr*100/sumCpu,
                (float)deltaCpu.steal*100/sumCpu,
                (float)deltaCpu.guest*100/sumCpu,
                (float)deltaCpu.guestnice*100/sumCpu);
            line++;
        }

        if (has_mem) {
            printw("\nMem:  %10s Total %10s Used %10s Free %10s Buffer",
                format_humanmem(b1, sizeof b1, mem.totalReal),
                format_humanmem(b2, sizeof b2, mem.totalReal-mem.availReal),
                format_humanmem(b3, sizeof b3, mem.availReal),
                format_humanmem(b4, sizeof b4, mem.buffer));
            line++;
            printw("\nSwap: %10s Total %10s Used %10s Free %10s Cached",
                format_humanmem(b1, sizeof b1, mem.totalSwap),
                format_humanmem(b2, sizeof b2, mem.totalSwap-mem.availSwap),
                format_humanmem(b3, sizeof b3, mem.availSwap),
                format_humanmem(b4, sizeof b4, mem.cached));
            line++;
        }

        printw("\n%7s %4s %6s %10s %11s %5s %-10s",
            "Index", "Type", "Status", "Memory", "Total CPU", "%CPU", "Command");
        line++;
        ninx = 0;
        while (line < LINES && ninx < ncount) {
            struct hrSWRunTable *proc = nproc+ninx;
            const char *hr_status, *hr_type;

            ninx++;
            if (proc->hrSWRunPerfCPUInc == 0 && !show_idle)
                continue;
            if (proc->hrSWRunType != 4 && !show_os)
                continue;

            line++;

            switch (proc->hrSWRunType) {
            case 1: hr_type = "Unkn"; break;
            case 2: hr_type = "Os"; break;
            case 3: hr_type = "Drvr"; break;
            case 4: hr_type = "Appl"; break;
            default: hr_type = "?"; break;
            }

            switch (proc->hrSWRunStatus) {
            case 1: hr_status = "Run"; break;
            case 2: hr_status = "Wait"; break;
            case 3: hr_status = "Event"; break;
            case 4: hr_status = "Inval"; break;
            default: hr_status = "?"; break;
            }

            printw("\n%7lu %4s %6s %10s %11s %5.1f %s %s",
                   proc->hrSWRunIndex,
                   hr_type,
                   hr_status,
                   format_humanmem(b1, sizeof b1, proc->hrSWRunPerfMem),
                   format_sec(b2,sizeof b2, proc->hrSWRunPerfCPU),
                   (float)proc->hrSWRunPerfCPUInc/5,
                   command_path && proc->hrSWRunPath[0] ? proc->hrSWRunPath : proc->hrSWRunName,
                   command_args ? proc->hrSWRunParameters : "");
        }
        refresh();

        qsort(nproc, ncount, sizeof(nproc[0]), pidcomp);
        free_perf(oproc, ocount);
        oproc = nproc;
        ocount = ncount;
    }
    endwin();

    snmp_close(ss);
    SOCK_CLEANUP;
    return 0;
}
Beispiel #28
0
int
snmpps(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    int             arg;
    struct hrSWRunTable *procs;
    int             count, pinx = 0;

    /*
     * get the common command line arguments 
     */
    switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) {
    case NETSNMP_PARSE_ARGS_ERROR:
        exit(1);
    case NETSNMP_PARSE_ARGS_SUCCESS_EXIT:
        exit(0);
    case NETSNMP_PARSE_ARGS_ERROR_USAGE:
        usage();
        exit(1);
    default:
        break;
    }

    if (arg != argc) {
        fprintf(stderr, "snmpps: extra argument: %s\n", argv[arg]);
        exit(1);
    }

    SOCK_STARTUP;

    /*
     * Open an SNMP session.
     */
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpps", &session);
        SOCK_CLEANUP;
        exit(1);
    }

    count = collect_perf(ss, &procs);
    if (count == 0) {
        fprintf(stderr, "snmpps: no processes found\n");
        exit(1);
    }

    switch (topsort) {
    case 'm':
        qsort(procs, count, sizeof(procs[0]), memcomp);
        break;
    case 't':
        qsort(procs, count, sizeof(procs[0]), totcomp);
        break;
    }

    printf("%7s %4s %6s %10s %11s %-10s\n",
        "Index", "Type", "Status", "Memory", "CPU", "Command");

    while (pinx < count) {
        struct hrSWRunTable *proc = procs+pinx;
        const char *hr_status, *hr_type;
        char b1[15], b2[20];

        switch (proc->hrSWRunType) {
        case 1: hr_type = "Unkn"; break;
        case 2: hr_type = "Os"; break;
        case 3: hr_type = "Drvr"; break;
        case 4: hr_type = "Appl"; break;
        default: hr_type = "?"; break;
        }

        switch (proc->hrSWRunStatus) {
        case 1: hr_status = "Run"; break;
        case 2: hr_status = "Wait"; break;
        case 3: hr_status = "Event"; break;
        case 4: hr_status = "Inval"; break;
        default: hr_status = "?"; break;
        }

        printf("%7lu %4s %6s %10s %11.11s %s %s\n",
               proc->hrSWRunIndex,
               hr_type,
               hr_status,
               format_humanmem(b1, sizeof b1, proc->hrSWRunPerfMem),
               format_centisec(b2, sizeof b2, proc->hrSWRunPerfCPU),
               command_path && proc->hrSWRunPath[0] ? proc->hrSWRunPath : proc->hrSWRunName,
               command_args ? proc->hrSWRunParameters : "");

        pinx++;
    }

    snmp_close(ss);
    SOCK_CLEANUP;
    return 0;
}
Beispiel #29
0
int
collect_perf(netsnmp_session *ss, struct hrSWRunTable **fproc)
{
    netsnmp_pdu    *pdu;
    netsnmp_pdu    *response;
    netsnmp_variable_list *vlp;
    oid             base[MAX_OID_LEN];
    size_t          base_length;
    int status, count = 0;
    struct hrSWRunTable *procs = malloc(sizeof(struct hrSWRunTable));

    pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
    base_length =
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunIndex", NULL, 0);
    memcpy(base, pdu->variables->name, base_length * sizeof(oid));

    vlp = collect_procs(ss, pdu, base, base_length);

    while (vlp) {
        size_t len;
        struct hrSWRunTable proc;
        netsnmp_variable_list *vlp2;

        pdu = snmp_pdu_create(SNMP_MSG_GET);

        add(pdu, "HOST-RESOURCES-MIB:hrSWRunName",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunID",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunPath",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunParameters",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunType",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunStatus",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunPerfCPU",
            &vlp->name[base_length], vlp->name_length - base_length);
        add(pdu, "HOST-RESOURCES-MIB:hrSWRunPerfMem",
            &vlp->name[base_length], vlp->name_length - base_length);

        response = NULL;
        status = snmp_synch_response(ss, pdu, &response);
        if (status != STAT_SUCCESS || !response) {
            snmp_sess_perror(progname, ss);
#if HAVE_CURSES_H
            endwin();
#endif
            exit(1);
        }
        if (response->errstat != SNMP_ERR_NOERROR) {
            vlp = vlp->next_variable;
            continue;
        }

        memset(&proc, 0, sizeof(proc));

        proc.hrSWRunIndex = vlp->name[base_length];

        vlp2 = response->variables;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        len = vlp2->val_len;
        proc.hrSWRunName = malloc(len+1);
        memcpy(proc.hrSWRunName, vlp2->val.string, len);
        proc.hrSWRunName[len] = '\0';

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        proc.hrSWRunID = *vlp2->val.integer;

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        len = vlp2->val_len;
        proc.hrSWRunPath = malloc(len+1);
        memcpy(proc.hrSWRunPath, vlp2->val.string, len);
        proc.hrSWRunPath[len] = '\0';

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        len = vlp2->val_len;
        proc.hrSWRunParameters = malloc(len+1);
        memcpy(proc.hrSWRunParameters, vlp2->val.string, len);
        proc.hrSWRunParameters[len] = '\0';

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        proc.hrSWRunType = *vlp2->val.integer;

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        proc.hrSWRunStatus = *vlp2->val.integer;

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        proc.hrSWRunPerfCPU = *vlp2->val.integer;

        vlp2 = vlp2->next_variable;
        if (vlp2->type == SNMP_NOSUCHINSTANCE) goto next;
        proc.hrSWRunPerfMem = *vlp2->val.integer;

        count++;
        procs = realloc(procs, count*sizeof(procs[0]));
        procs[count-1] = proc;

        snmp_free_pdu(response);
        vlp2 = vlp;
        vlp = vlp->next_variable;
        free(vlp2);
        continue;

next:
        if (proc.hrSWRunName) free(proc.hrSWRunName);
        if (proc.hrSWRunPath) free(proc.hrSWRunPath);
        if (proc.hrSWRunParameters) free(proc.hrSWRunParameters);
        snmp_free_pdu(response);
        vlp2 = vlp;
        vlp = vlp->next_variable;
        free(vlp2);
    }
    *fproc = procs;
    return count;
}
Beispiel #30
0
int main(int argc, char *argv[])
{
    char *hostname = NULL;
    struct protoent *p;
    struct protox *tp = NULL;	/* for printing cblocks & stats */
    int allprotos = 1;
    char *community = NULL;
    char *argp;
    struct snmp_session session;
    int dest_port = SNMP_PORT;
    int timeout = SNMP_DEFAULT_TIMEOUT;
    int version = SNMP_VERSION_1;
    int arg;

    init_mib();
    /*
     * Usage: snmpnetstatwalk -v 1 [-q] hostname community ...      or:
     * Usage: snmpnetstat [-v 2 ] [-q] hostname noAuth     ...
     */
    for(arg = 1; arg < argc; arg++){
	if (argv[arg][0] == '-'){
	    switch(argv[arg][1]){
              case 'V':
                fprintf(stderr,"UCD-snmp version: %s\n", VersionInfo);
                exit(0);
                break;

	      case 'h':
		usage();
		exit(0);

	      case 'd':
		snmp_set_dump_packet(1);
		break;

	      case 'q':
		snmp_set_quick_print(1);
		break;

	      case 'D':
                debug_register_tokens(&argv[arg][2]);
		snmp_set_do_debugging(1);
		break;
	      case 'p':
		if (argv[arg][2] != 0) dest_port = atoi(argv[arg]+2);
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else dest_port = atoi(argv[arg]);
		break;

	      case 't':
		if (argv[arg][2] != 0) timeout = atoi(argv[arg]+2);
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else timeout = atoi(argv[arg]);
		timeout *= 1000000;
		break;

	      case 'c':
		if (argv[arg][2] != 0) community = argv[arg]+2;
		else if (++arg == argc) {
		    usage();
		    exit(1);
		}
		else community = argv[arg];
		break;

	      case 'v':
		if (argv[arg][2] != 0) argp = argv[arg]+2;
		else if (arg == argc) {
		    usage();
		    exit(1);
		}
		else argp = argv[arg];
		if (!strcmp(argp,"1"))
		    version = SNMP_VERSION_1;
		else if (!strcmp(argp,"2c"))
		    version = SNMP_VERSION_2c;
		else {
		    fprintf(stderr, "Invalid version: %s\n", argp);
		    usage();
		    exit(1);
		}
		break;

	      case 'a':
		aflag++;
		break;

	      case 'i':
		iflag++;
		break;

	      case 'o':
		oflag++;
		break;

	      case 'n':
		nflag++;
		break;

	      case 'r':
		rflag++;
		break;

	      case 's':
		sflag++;
		break;

	      case 'P':
		if (++arg == argc) {
		    usage();
		    exit(1);
		}
		if ((tp = name2protox(argv [arg])) == NULLPROTOX) {
		  fprintf(stderr, "%s: unknown or uninstrumented protocol\n",
			  argv [arg]);
		  exit(1);
		}
		allprotos = 0;
		tp->pr_wanted = 1;
		break;

	      case 'I':
		iflag++;
		if (*(intrface = argv[arg] + 2) == 0) {
		  if (++arg == argc) {
		      usage();
		      exit(1);
		  }
		  if ((intrface = argv[arg]) == 0)
		    break;
		}
		break;

	      default:
		printf("invalid option: -%c\n", argv[arg][1]);
		break;
	    }
	    continue;
	}
	if (hostname == NULL){
	    hostname = argv[arg];
	} else if ((version == SNMP_VERSION_1 || version == SNMP_VERSION_2c)
                   && community == NULL){
	    community = argv[arg]; 
	} else if (isdigit(argv[arg][0])) {
            interval = atoi(argv[arg]);
            if (interval <= 0){
		usage();
		exit(1);
	    }
	    iflag++;
	} else {
	    usage();
	    exit(1);
	}
    }
    
    if (!hostname ||
	((version == SNMP_VERSION_1 || version == SNMP_VERSION_2c) && !community)) {
	usage();
	exit(1);
    }

    snmp_sess_init(&session);
    session.peername = hostname;
    session.remote_port = dest_port;
    session.timeout = timeout;
    if (version == SNMP_VERSION_1 || version == SNMP_VERSION_2c){
        session.version = version;
        session.community = (u_char *)community;
        session.community_len = strlen((char *)community);
    }

    SOCK_STARTUP;

    /* open an SNMP session */
    Session = snmp_open(&session);
    if (Session == NULL){
      /* diagnose snmp_open errors with the input struct snmp_session pointer */
        snmp_sess_perror("snmpnetstat", &session);
        SOCK_CLEANUP;
	exit(1);
    }

    /*
     * Keep file descriptors open to avoid overhead
     * of open/close on each call to get* routines.
     */
    sethostent(1);
    setnetent(1);
    setprotoent(1);
    setservent(1);

    if (iflag) {
	intpr(interval);
    }
    if (oflag) {
	intpro(interval);
    }
    if (rflag) {
	if (sflag)
	    rt_stats();
	else
	    routepr();
    }
    
    if (iflag || rflag || oflag)
	;
    else {

    while ((p = getprotoent46())) {
	for (tp = protox; tp->pr_name; tp++) {
	    if (strcmp(tp->pr_name, p->p_name) == 0)
		break;
	}
	if (tp->pr_name == 0 || (tp->pr_wanted == 0 && allprotos == 0))
	    continue;
	if (sflag) {
	    if (tp->pr_stats)
		(*tp->pr_stats)();
	} else
	    if (tp->pr_cblocks)
		(*tp->pr_cblocks)(tp->pr_name);
    }
    } /* ! iflag, rflag, oflag */

    endprotoent();
    endservent();
    endnetent();
    endhostent();

    snmp_close(Session);

    SOCK_CLEANUP;
    return 0;
}