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); }
void perr(struct snmp_pdu *resp) { if(resp) fprintf(stderr, "error: %s\n", snmp_errstring(resp->errstat)); snmp_perror("error"); snmp_close(ses); SOCK_CLEANUP; exit(1); }
/* report the value interfaces.ifNumber.0, actually the number of interfaces */ static int snmp_get_ifcount(struct snmp_session *ss) { int nifaces = -1; oid ifcount[] = { 1, 3, 6, 1, 2, 1, 2, 1, 0 }; struct snmp_pdu *pdu; struct snmp_pdu *response = NULL; int status; if ((pdu = snmp_pdu_create(SNMP_MSG_GET)) == NULL) { ifstat_error("snmp_pdu_create: %s", snmp_api_errstring(snmp_errno)); return -1; } snmp_add_null_var(pdu, ifcount, sizeof(ifcount) / sizeof(oid)); if ((status = snmp_synch_response(ss, pdu, &response)) != STAT_SUCCESS || response->errstat != SNMP_ERR_NOERROR || response->variables == NULL || response->variables->type != ASN_INTEGER) { if (status == STAT_SUCCESS) ifstat_error("snmp: Error: %s", snmp_errstring(response->errstat)); else ifstat_error("snmpget(interfaces.ifNumber.0): %s", snmp_sess_errstring(ss)); if (response) snmp_free_pdu(response); return -1; } nifaces = *(response->variables->val.integer); snmp_free_pdu(response); if (nifaces < 0) return -1; return nifaces; }
/* * simple printing of returned data */ int snmpStoreResult (tSession *session, struct snmp_pdu *pdu, char **result) { char buf[RESULTSIZE]; struct variable_list *vp; struct snmp_session *sp = session->sess; unsigned int o = session->current_oid; unsigned int i,j; *result = (char*)calloc(RESULTSIZE+1, sizeof(char)); vp = pdu->variables; if (pdu->errstat == SNMP_ERR_NOERROR) { while (vp) { snprint_value(*result, RESULTSIZE, vp->name, vp->name_length, vp); // tolower & remove spaces and linebreaks for (i=0, j=0; i<strlen(*result); i++) { if ((*result)[i] > 0x22) { if ((*result)[i] >= 0x41 && (*result)[i] <= 0x5A) { (*result)[j] = (*result)[i] + 0x20; } else { (*result)[j] = (*result)[i]; } j++; } } (*result)[j] = 0; // fix lancom snr if (session->oidList.oid[o].id_oidtype == 12 && ( session->oidList.oid[o].id_type == 2 || session->oidList.oid[o].id_type == 5 || session->oidList.oid[o].id_type == 9 || session->oidList.oid[o].id_type == 24 )) { snprintf(*result, RESULTSIZE, "%.0f", atoi(*result) * 0.64); } snprint_variable(buf, sizeof(buf), vp->name, vp->name_length, vp); syslog(LOG_DEBUG, "snmpStoreResult: %s: %s", sp->peername, buf); vp = vp->next_variable; } return 1; } else { if (vp) { snprint_objid(buf, sizeof(buf), vp->name, vp->name_length); } else { strcpy(buf, "(empty buf)"); } syslog(LOG_ERR, "snmpStoreResult: %s: %s: (%s)", sp->peername, buf, snmp_errstring(pdu->errstat)); if (pdu->errstat == SNMP_ERR_NOSUCHNAME) { snprintf(*result, RESULTSIZE, "U"); return 1; } return 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; }
/** 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; }
int return_data(int status, struct snmp_session *sp, struct snmp_pdu *pdu) { char buf[1024]; struct variable_list *vp; int ix; char *getdata = NULL; switch (status) { case STAT_SUCCESS: vp = pdu->variables; if (pdu->errstat == SNMP_ERR_NOERROR) { while (vp) { snprint_variable(buf, sizeof(buf), vp->name, vp->name_length, vp); /*mjpark------------------------------------------*/ getdata = (char *)malloc(1 + vp->val_len); memcpy(getdata, vp->val.string, vp->val_len); getdata[vp->val_len] = '\0'; #if 0 //Data over flow... int nVal; memcpy((void *)&nVal, getdata, 4); #else unsigned long int nVal; memcpy((void *)&nVal, getdata, sizeof(unsigned long int)); #endif gpSnmp->val = nVal; //debug print /* printf("data length(%d), unsigned long int size(%d), int(%d)\n",vp->val_len, sizeof(unsigned long int), sizeof(int)); */ printf("snmpVal(%d), psnmp(%p)\n", nVal, gpSnmp); /*------------------------------------------------*/ vp = vp->next_variable; } free(getdata); } else { for (ix = 1; vp && ix != pdu->errindex; vp = vp->next_variable, ix++); if (vp) snprint_objid(buf, sizeof(buf), vp->name, vp->name_length); else strcpy(buf, "(none)"); fprintf(stdout, "%s: %s: %s\n", sp->peername, buf, snmp_errstring(pdu->errstat)); } return 1; case STAT_TIMEOUT: fprintf(stdout, "%s: Timeout\n", sp->peername); return 0; case STAT_ERROR: snmp_perror(sp->peername); return 0; } return 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); }
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; }
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; }
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); }
/* * write value of given oid */ static int MPC_write(struct snmp_session *sptr, const char *objname, char type, char *value) { oid name[MAX_OID_LEN]; size_t namelen = MAX_OID_LEN; struct snmp_pdu *pdu; struct snmp_pdu *resp; DEBUGCALL; /* convert objname into oid; return FALSE if invalid */ if (!read_objid(objname, name, &namelen)) { LOG(PIL_CRIT, "%s: cannot convert %s to oid.", __FUNCTION__, objname); return (FALSE); } /* create pdu */ if ((pdu = snmp_pdu_create(SNMP_MSG_SET)) != NULL) { /* add to be written value to pdu */ snmp_add_var(pdu, name, namelen, type, value); /* send pdu and get response; return NULL if error */ if (snmp_synch_response(sptr, pdu, &resp) == STAT_SUCCESS) { /* go through the returned vars */ if (resp->errstat == SNMP_ERR_NOERROR) { /* request successful done */ snmp_free_pdu(resp); return (TRUE); } else { LOG(PIL_CRIT, "%s: error in response packet, reason %ld [%s]." , __FUNCTION__, resp->errstat, snmp_errstring(resp->errstat)); } } else { MPC_error(sptr, __FUNCTION__, "error sending/receiving pdu"); } /* free pdu (again: necessary?) */ snmp_free_pdu(resp); } else { MPC_error(sptr, __FUNCTION__, "cannot create pdu"); } /* error */ return (FALSE); }
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; }
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; }
static int snmp_get_nextif(struct snmp_session *ss, int index) { oid ifindex[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 1, 0 }; int len = sizeof(ifindex) / sizeof(oid); struct snmp_pdu *pdu; struct snmp_pdu *response = NULL; struct variable_list *vars; int status; if (index >= 0) ifindex[len - 1] = index; if ((pdu = snmp_pdu_create(SNMP_MSG_GETNEXT)) == NULL) { ifstat_error("snmp_pdu_create: %s", snmp_api_errstring(snmp_errno)); return -1; } snmp_add_null_var(pdu, ifindex, (index < 0) ? len - 1 : len); if ((status = snmp_synch_response(ss, pdu, &response)) != STAT_SUCCESS || response->errstat != SNMP_ERR_NOERROR || response->variables == NULL) { if (status == STAT_SUCCESS) ifstat_error("snmp: Error: %s", snmp_errstring(response->errstat)); else ifstat_error("snmpgetnext(interfaces.ifTable.ifEntry.ifIndex...): %s", snmp_sess_errstring(ss)); if (response != NULL) snmp_free_pdu(response); return -1; } for(vars = response->variables; vars; vars = vars->next_variable) { /* check that the variable is under the base oid */ if (vars->name_length != len) continue; if (memcmp(ifindex, vars->name, sizeof(ifindex) - sizeof(oid)) != 0) continue; index = vars->name[vars->name_length - 1]; snmp_free_pdu(response); return index; } snmp_free_pdu(response); return -1; }
int print_result(int status, struct snmp_session *sp, struct snmp_pdu *pdu) { char buf[1024]; struct variable_list *vp; int ix; struct timeval now; struct timezone tz; struct tm *tm; gettimeofday(&now, &tz); tm = localtime(&now.tv_sec); fprintf(stdout, "%.2d:%.2d:%.2d.%.6d, status: %d, ", tm->tm_hour, tm->tm_min, tm->tm_sec, now.tv_usec, status); switch (status) { case STAT_SUCCESS: vp = pdu->variables; if (pdu->errstat == SNMP_ERR_NOERROR) { while (vp) { snprint_variable(buf, sizeof(buf), vp->name, vp->name_length, vp); fprintf(stdout, ":%s: %s\n", sp->peername, buf); vp = vp->next_variable; } } else { for (ix = 1; vp && ix != pdu->errindex; vp = vp->next_variable, ix++) ; if (vp) snprint_objid(buf, sizeof(buf), vp->name, vp->name_length); else strcpy(buf, "(none)"); fprintf(stdout, ":%s: %s: %s\n", sp->peername, buf, snmp_errstring(pdu->errstat)); } return 1; case STAT_TIMEOUT: fprintf(stdout, ":%s: Timeout\n", sp -> peername); return 0; case STAT_ERROR: snmp_perror(sp->peername); return 0; } return 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; }
/* * Store data received in response PDU */ int print_result (int status, req_t *req, struct snmp_pdu *pdu) { struct variable_list *vp; size_t len; keyrecord_t *kwalk; int keyoidlen; oid_t *owalk; int done; switch (status) { case STAT_SUCCESS: if (pdu->errstat == SNMP_ERR_NOERROR) { unsigned char *valstr = NULL, *oidstr = NULL; size_t valsz = 0, oidsz = 0; okcount++; switch (dataoperation) { case GET_KEYS: /* * Find the keyrecord currently processed for this request, and * look through the unresolved keys to see if we have a match. * If we do, determine the index for data retrieval. */ vp = pdu->variables; len = 0; sprint_realloc_value(&valstr, &valsz, &len, 1, vp->name, vp->name_length, vp); len = 0; sprint_realloc_objid(&oidstr, &oidsz, &len, 1, vp->name, vp->name_length); dbgprintf("Got key-oid '%s' = '%s'\n", oidstr, valstr); for (kwalk = req->currentkey, done = 0; (kwalk && !done); kwalk = kwalk->next) { /* Skip records where we have the result already, or that are not keyed */ if (kwalk->indexoid || (kwalk->indexmethod != req->currentkey->indexmethod)) { continue; } keyoidlen = strlen(req->currentkey->indexmethod->keyoid); switch (kwalk->indexmethod->idxtype) { case MIB_INDEX_IN_OID: /* Does the key match the value we just got? */ if (*kwalk->key == '*') { /* Match all. Add an extra key-record at the end. */ keyrecord_t *newkey; newkey = (keyrecord_t *)calloc(1, sizeof(keyrecord_t)); memcpy(newkey, kwalk, sizeof(keyrecord_t)); newkey->indexoid = strdup(oidstr + keyoidlen + 1); newkey->key = valstr; valstr = NULL; newkey->next = kwalk->next; kwalk->next = newkey; done = 1; } else if (strcmp(valstr, kwalk->key) == 0) { /* Grab the index part of the OID */ kwalk->indexoid = strdup(oidstr + keyoidlen + 1); done = 1; } break; case MIB_INDEX_IN_VALUE: /* Does the key match the index-part of the result OID? */ if (*kwalk->key == '*') { /* Match all. Add an extra key-record at the end. */ keyrecord_t *newkey; newkey = (keyrecord_t *)calloc(1, sizeof(keyrecord_t)); memcpy(newkey, kwalk, sizeof(keyrecord_t)); newkey->indexoid = valstr; valstr = NULL; newkey->key = strdup(oidstr + keyoidlen + 1); newkey->next = kwalk->next; kwalk->next = newkey; done = 1; } else if ((*(oidstr+keyoidlen) == '.') && (strcmp(oidstr+keyoidlen+1, kwalk->key)) == 0) { /* * Grab the index which is the value. * Avoid a strdup by grabbing the valstr pointer. */ kwalk->indexoid = valstr; valstr = NULL; valsz = 0; done = 1; } break; } } break; case GET_DATA: owalk = req->curr_oid; vp = pdu->variables; while (vp) { valsz = len = 0; sprint_realloc_value((unsigned char **)&owalk->result, &valsz, &len, 1, vp->name, vp->name_length, vp); owalk = owalk->next; vp = vp->next_variable; } break; } if (valstr) xfree(valstr); if (oidstr) xfree(oidstr); } else { errorcount++; errprintf("ERROR %s: %s\n", req->hostip[req->hostipidx], snmp_errstring(pdu->errstat)); } return 1; case STAT_TIMEOUT: timeoutcount++; dbgprintf("%s: Timeout\n", req->hostip); if (req->hostip[req->hostipidx+1]) { req->hostipidx++; startonehost(req, 1); } return 0; case STAT_ERROR: errorcount++; snmp_sess_perror(req->hostip[req->hostipidx], req->sess); return 0; } return 0; }
/*int get_value_snmp(double *result,char *result_str,DB_ITEM *item,char *error, int max_error_len)*/ int get_value_snmp(DB_ITEM *item, AGENT_RESULT *value) { #define NEW_APPROACH struct snmp_session session, *ss; struct snmp_pdu *pdu; struct snmp_pdu *response; #ifdef NEW_APPROACH char temp[MAX_STRING_LEN]; #endif oid anOID[MAX_OID_LEN]; size_t anOID_len = MAX_OID_LEN; struct variable_list *vars; int status; char *p, *c; double dbl; unsigned char *ip; char error[MAX_STRING_LEN]; int ret=SUCCEED; zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP()"); init_result(value); /* assert((item->type == ITEM_TYPE_SNMPv1)||(item->type == ITEM_TYPE_SNMPv2c)); */ assert((item->type == ITEM_TYPE_SNMPv1)||(item->type == ITEM_TYPE_SNMPv2c)||(item->type == ITEM_TYPE_SNMPv3)); snmp_sess_init( &session ); /* session.version = version;*/ if(item->type == ITEM_TYPE_SNMPv1) { session.version = SNMP_VERSION_1; } else if(item->type == ITEM_TYPE_SNMPv2c) { session.version = SNMP_VERSION_2c; } else if(item->type == ITEM_TYPE_SNMPv3) { session.version = SNMP_VERSION_3; } else { zbx_snprintf(error,sizeof(error),"Error in get_value_SNMP. Wrong item type [%d]. Must be SNMP.", item->type); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } if(item->useip == 1) { #ifdef NEW_APPROACH zbx_snprintf(temp,sizeof(temp),"%s:%d", item->host_ip, item->snmp_port); session.peername = temp; session.remote_port = item->snmp_port; #else session.peername = item->host_ip; session.remote_port = item->snmp_port; #endif } else { #ifdef NEW_APPROACH zbx_snprintf(temp, sizeof(temp), "%s:%d", item->host_dns, item->snmp_port); session.peername = temp; session.remote_port = item->snmp_port; #else session.peername = item->host_dns; session.remote_port = item->snmp_port; #endif } if( (session.version == SNMP_VERSION_1) || (item->type == ITEM_TYPE_SNMPv2c)) { session.community = (u_char *)item->snmp_community; session.community_len = strlen((void *)session.community); zabbix_log( LOG_LEVEL_DEBUG, "SNMP [%s@%s:%d]", session.community, session.peername, session.remote_port); } else if(session.version == SNMP_VERSION_3) { /* set the SNMPv3 user name */ session.securityName = item->snmpv3_securityname; session.securityNameLen = strlen(session.securityName); /* set the security level to authenticated, but not encrypted */ if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV) { session.securityLevel = SNMP_SEC_LEVEL_NOAUTH; } else if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV) { session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV; /* set the authentication method to MD5 */ session.securityAuthProto = usmHMACMD5AuthProtocol; session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN; session.securityAuthKeyLen = USM_AUTH_KU_LEN; if (generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) item->snmpv3_authpassphrase, strlen(item->snmpv3_authpassphrase), session.securityAuthKey, &session.securityAuthKeyLen) != SNMPERR_SUCCESS) { zbx_snprintf(error,sizeof(error),"Error generating Ku from authentication pass phrase."); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } } else if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV) { session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV; /* set the authentication method to MD5 */ session.securityAuthProto = usmHMACMD5AuthProtocol; session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN; session.securityAuthKeyLen = USM_AUTH_KU_LEN; if (generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) item->snmpv3_authpassphrase, strlen(item->snmpv3_authpassphrase), session.securityAuthKey, &session.securityAuthKeyLen) != SNMPERR_SUCCESS) { zbx_snprintf(error,sizeof(error),"Error generating Ku from authentication pass phrase."); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } /* set the private method to DES */ session.securityPrivProto = usmDESPrivProtocol; session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN; session.securityPrivKeyLen = USM_PRIV_KU_LEN; if (generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) item->snmpv3_privpassphrase, strlen(item->snmpv3_privpassphrase), session.securityPrivKey, &session.securityPrivKeyLen) != SNMPERR_SUCCESS) { zbx_snprintf(error,sizeof(error),"Error generating Ku from priv pass phrase."); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } } zabbix_log( LOG_LEVEL_DEBUG, "SNMPv3 [%s@%s:%d]", session.securityName, session.peername, session.remote_port); } else { zbx_snprintf(error,sizeof(error),"Error in get_value_SNMP. Unsupported session.version [%d]", (int)session.version); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } zabbix_log( LOG_LEVEL_DEBUG, "OID [%s]", item->snmp_oid); SOCK_STARTUP; ss = snmp_open(&session); if(ss == NULL) { SOCK_CLEANUP; zbx_snprintf(error,sizeof(error),"Error doing snmp_open()"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); return NOTSUPPORTED; } zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.2"); pdu = snmp_pdu_create(SNMP_MSG_GET); /* Changed to snmp_parse_oid */ /* read_objid(item->snmp_oid, anOID, &anOID_len);*/ snmp_parse_oid(item->snmp_oid, anOID, &anOID_len); #if OTHER_METHODS get_node("sysDescr.0", anOID, &anOID_len); read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len); read_objid("system.sysDescr.0", anOID, &anOID_len); #endif snmp_add_null_var(pdu, anOID, anOID_len); zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.3"); status = snmp_synch_response(ss, pdu, &response); zabbix_log( LOG_LEVEL_DEBUG, "Status send [%d]", status); zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.4"); zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 1"); if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 2"); /* for(vars = response->variables; vars; vars = vars->next_variable) { print_variable(vars->name, vars->name_length, vars); }*/ for(vars = response->variables; vars; vars = vars->next_variable) { int count=1; zabbix_log( LOG_LEVEL_DEBUG, "AV loop(%d)", vars->type); /* if( (vars->type == ASN_INTEGER) ||*/ if( (vars->type == ASN_UINTEGER)|| (vars->type == ASN_COUNTER) || #ifdef OPAQUE_SPECIAL_TYPES (vars->type == ASN_UNSIGNED64) || #endif (vars->type == ASN_TIMETICKS) || (vars->type == ASN_GAUGE) ) { /* *result=(long)*vars->val.integer;*/ /* * This solves situation when large numbers are stored as negative values * http://sourceforge.net/tracker/index.php?func=detail&aid=700145&group_id=23494&atid=378683 */ /*zbx_snprintf(result_str,sizeof(result_str),"%ld",(long)*vars->val.integer);*/ /* zbx_snprintf(result_str,sizeof(result_str),"%lu",(long)*vars->val.integer);*/ /* Not correct. Returns huge values. */ /* SET_UI64_RESULT(value, (zbx_uint64_t)*vars->val.integer);*/ if (vars->type == ASN_GAUGE && *vars->val.integer >= 4294967294) { SET_UI64_RESULT(value, (unsigned long)0); } else { SET_UI64_RESULT(value, (unsigned long)*vars->val.integer); } zabbix_log( LOG_LEVEL_DEBUG, "OID [%s] Type [%d] UI64[" ZBX_FS_UI64 "]", item->snmp_oid, vars->type, (zbx_uint64_t)*vars->val.integer); zabbix_log( LOG_LEVEL_DEBUG, "OID [%s] Type [%d] ULONG[%lu]", item->snmp_oid, vars->type, (zbx_uint64_t)(unsigned long)*vars->val.integer); } else if(vars->type == ASN_COUNTER64) { /* Incorrect code for 32 bit platforms */ /* SET_UI64_RESULT(value, ((vars->val.counter64->high)<<32)+(vars->val.counter64->low));*/ SET_UI64_RESULT(value, (((zbx_uint64_t)vars->val.counter64->high)<<32)+((zbx_uint64_t)vars->val.counter64->low)); } else if(vars->type == ASN_INTEGER #define ASN_FLOAT (ASN_APPLICATION | 8) #define ASN_DOUBLE (ASN_APPLICATION | 9) #ifdef OPAQUE_SPECIAL_TYPES || (vars->type == ASN_INTEGER64) #endif ) { /* Negative integer values are converted to double */ if(*vars->val.integer<0) { SET_DBL_RESULT(value, (double)*vars->val.integer); } else { SET_UI64_RESULT(value, (zbx_uint64_t)*vars->val.integer); } } #ifdef OPAQUE_SPECIAL_TYPES else if(vars->type == ASN_FLOAT) { SET_DBL_RESULT(value, *vars->val.floatVal); } else if(vars->type == ASN_DOUBLE) { SET_DBL_RESULT(value, *vars->val.doubleVal); } #endif else if(vars->type == ASN_OCTET_STR) { if(item->value_type == ITEM_VALUE_TYPE_FLOAT) { p = malloc(vars->val_len+1); if(p) { memcpy(p, vars->val.string, vars->val_len); p[vars->val_len] = '\0'; dbl = strtod(p, NULL); SET_DBL_RESULT(value, dbl); } else { zbx_snprintf(error,sizeof(error),"Cannot allocate required memory"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); } } else if(item->value_type != ITEM_VALUE_TYPE_STR) { zbx_snprintf(error,sizeof(error),"Cannot store SNMP string value (ASN_OCTET_STR) in item having numeric type"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret = NOTSUPPORTED; } else { zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%s]", vars->val.string); zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%d]", vars->val_len); p = malloc(1024); if(p) { memset(p,0,1024); snprint_value(p, 1023, vars->name, vars->name_length, vars); /* Skip STRING: and STRING_HEX: */ c=strchr(p,':'); if(c==NULL) { SET_STR_RESULT(value, strdup(p)); } else { SET_STR_RESULT(value, strdup(c+1)); } zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%s]", p); free(p); } else { zbx_snprintf(error,MAX_STRING_LEN-1,"Cannot allocate required memory"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); } /* p = malloc(vars->val_len+1); if(p) { zabbix_log( LOG_LEVEL_WARNING, "Result [%s] len [%d]",vars->val.string,vars->val_len); memcpy(p, vars->val.string, vars->val_len); p[vars->val_len] = '\0'; SET_STR_RESULT(value, p); } else { zbx_snprintf(error,sizeof(error),"Cannot allocate required memory"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); }*/ } } else if(vars->type == ASN_IPADDRESS) { /* ip = vars->val.string; zbx_snprintf(result_str,sizeof(result_str),"%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);*/ /* if(item->type == 0) { ret = NOTSUPPORTED; }*/ if(item->value_type != ITEM_VALUE_TYPE_STR) { zbx_snprintf(error,sizeof(error),"Cannot store SNMP string value (ASN_IPADDRESS) in item having numeric type"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret = NOTSUPPORTED; } else { p = malloc(MAX_STRING_LEN); if(p) { ip = vars->val.string; zbx_snprintf(p,MAX_STRING_LEN-1,"%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); SET_STR_RESULT(value, p); } else { zbx_snprintf(error,MAX_STRING_LEN-1,"Cannot allocate required memory"); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); } } } else { /* count is not really used. Has to be removed */ count++; zbx_snprintf(error,sizeof(error),"OID [%s] value #%d has unknow type [%X]", item->snmp_oid, count, vars->type); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret = NOTSUPPORTED; } } } else { if (status == STAT_SUCCESS) { zabbix_log( LOG_LEVEL_WARNING, "SNMP error in packet. Reason: %s\n", snmp_errstring(response->errstat)); if(response->errstat == SNMP_ERR_NOSUCHNAME) { zbx_snprintf(error,sizeof(error),"SNMP error [%s]", snmp_errstring(response->errstat)); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret=NOTSUPPORTED; } else { zbx_snprintf(error,sizeof(error),"SNMP error [%s]", snmp_errstring(response->errstat)); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret=NOTSUPPORTED; } } else if(status == STAT_TIMEOUT) { zbx_snprintf(error,sizeof(error),"Timeout while connecting to [%s]", session.peername); /* snmp_sess_perror("snmpget", ss);*/ zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret = NETWORK_ERROR; } else { zbx_snprintf(error,sizeof(error),"SNMP error [%d]", status); zabbix_log( LOG_LEVEL_ERR, "%s", error); SET_MSG_RESULT(value, strdup(error)); ret=NOTSUPPORTED; } } if (response) { snmp_free_pdu(response); } snmp_close(ss); SOCK_CLEANUP; return ret; }
/* * Generic SNMP object fetcher * * st=1 snmpget() - query an agent and return a single value. * st=2 snmpwalk() - walk the mib and return a single dimensional array * containing the values. * st=3 snmprealwalk() and snmpwalkoid() - walk the mib and return an * array of oid,value pairs. * st=5-8 ** Reserved ** * st=11 snmpset() - query an agent and set a single value * */ void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st) { zval **a1, **a2, **a3, **a4, **a5, **a6, **a7; struct snmp_session session, *ss; struct snmp_pdu *pdu=NULL, *response; struct variable_list *vars; char *objid; oid name[MAX_NAME_LEN]; int name_length; int status, count,rootlen=0,gotroot=0; oid root[MAX_NAME_LEN]; char buf[2048]; char buf2[2048]; int keepwalking=1; long timeout=SNMP_DEFAULT_TIMEOUT; long retries=SNMP_DEFAULT_RETRIES; int myargc = ZEND_NUM_ARGS(); char type = (char) 0; char *value = (char *) 0; if (myargc < 3 || myargc > 7 || zend_get_parameters_ex(myargc, &a1, &a2, &a3, &a4, &a5, &a6, &a7) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string_ex(a1); convert_to_string_ex(a2); convert_to_string_ex(a3); if (st == 11) { if (myargc < 5) { WRONG_PARAM_COUNT; } convert_to_string_ex(a4); convert_to_string_ex(a5); if(myargc > 5) { convert_to_long_ex(a6); timeout = (*a6)->value.lval; } if(myargc > 6) { convert_to_long_ex(a7); retries = (*a7)->value.lval; } type = (*a4)->value.str.val[0]; value = (*a5)->value.str.val; } else { if(myargc > 3) { convert_to_long_ex(a4); timeout = (*a4)->value.lval; } if(myargc > 4) { convert_to_long_ex(a5); retries = (*a5)->value.lval; } } objid = (*a3)->value.str.val; if (st >= 2) { /* walk */ rootlen = MAX_NAME_LEN; if ( strlen(objid) ) { /* on a walk, an empty string means top of tree - no error */ if ( read_objid(objid, root, &rootlen) ) { gotroot = 1; } else { php_error(E_WARNING,"Invalid object identifier: %s\n", objid); } } if (gotroot == 0) { memmove((char *)root, (char *)objid_mib, sizeof(objid_mib)); rootlen = sizeof(objid_mib) / sizeof(oid); gotroot = 1; } } memset(&session, 0, sizeof(struct snmp_session)); session.peername = (*a1)->value.str.val; session.version = SNMP_VERSION_1; /* * FIXME: potential memory leak * This is a workaround for an "artifact" (Mike Slifcak) * in (at least) ucd-snmp 3.6.1 which frees * memory it did not allocate */ #ifdef UCD_SNMP_HACK session.community = (u_char *)strdup((*a2)->value.str.val); /* memory freed by SNMP library, strdup NOT estrdup */ #else session.community = (u_char *)(*a2)->value.str.val; #endif session.community_len = (*a2)->value.str.len; session.retries = retries; session.timeout = timeout; session.authenticator = NULL; snmp_synch_setup(&session); if ((ss = snmp_open(&session)) == NULL) { php_error(E_WARNING,"Could not open snmp\n"); RETURN_FALSE; } if (st >= 2) { memmove((char *)name, (char *)root, rootlen * sizeof(oid)); name_length = rootlen; if (array_init(return_value) == FAILURE) { php_error(E_WARNING, "Cannot prepare result array"); RETURN_FALSE; } } while(keepwalking) { keepwalking=0; if (st == 1) { pdu = snmp_pdu_create(SNMP_MSG_GET); name_length = MAX_NAME_LEN; if ( !read_objid(objid, name, &name_length) ) { php_error(E_WARNING,"Invalid object identifier: %s\n", objid); RETURN_FALSE; } snmp_add_null_var(pdu, name, name_length); } else if (st == 11) { pdu = snmp_pdu_create(SNMP_MSG_SET); if (snmp_add_var(pdu, name, name_length, type, value)) { php_error(E_WARNING,"Could not add variable: %s\n", name); RETURN_FALSE; } } else if (st >= 2) { pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); snmp_add_null_var(pdu, name, name_length); } retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) { if (st >= 2 && st != 11 && (vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { continue; /* not part of this subtree */ } if (st != 11) { sprint_value(buf,vars->name, vars->name_length, vars); } #if 0 Debug("snmp response is: %s\n",buf); #endif if (st == 1) { RETVAL_STRING(buf,1); } else if (st == 2) { add_next_index_string(return_value,buf,1); /* Add to returned array */ } else if (st == 3) { sprint_objid(buf2, vars->name, vars->name_length); add_assoc_string(return_value,buf2,buf,1); } if (st >= 2 && st != 11) { if (vars->type != SNMP_ENDOFMIBVIEW && vars->type != SNMP_NOSUCHOBJECT && vars->type != SNMP_NOSUCHINSTANCE) { memmove((char *)name, (char *)vars->name,vars->name_length * sizeof(oid)); name_length = vars->name_length; keepwalking = 1; } } } } else { if (st != 2 || response->errstat != SNMP_ERR_NOSUCHNAME) { php_error(E_WARNING,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errstat == SNMP_ERR_NOSUCHNAME) { for (count=1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++); if (vars) { sprint_objid(buf,vars->name, vars->name_length); } php_error(E_WARNING,"This name does not exist: %s\n",buf); } if (st == 1) { if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GET)) != NULL) { goto retry; } } else if (st == 11) { if ((pdu = snmp_fix_pdu(response, SNMP_MSG_SET)) != NULL) { goto retry; } } else if (st >= 2) { if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETNEXT)) != NULL) { goto retry; } } RETURN_FALSE; } } } else if (status == STAT_TIMEOUT) { php_error(E_WARNING,"No Response from %s\n", (*a1)->value.str.val); RETURN_FALSE; } else { /* status == STAT_ERROR */ php_error(E_WARNING,"An error occurred, Quitting...\n"); RETURN_FALSE; } if (response) { snmp_free_pdu(response); } } /* keepwalking */ snmp_close(ss); }
int main (int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; netsnmp_variable_list *vars; int arg; int count; int status; int exitval = 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; } names = argc - arg; if (names < non_repeaters) { fprintf (stderr, "snmpbulkget: need more objects than <nonrep>\n"); exit (1); } namep = name = (struct nameStruct *) calloc (names, sizeof (*name)); while (arg < argc) { namep->name_len = MAX_OID_LEN; if (snmp_parse_oid (argv[arg], namep->name, &namep->name_len) == NULL) { snmp_perror (argv[arg]); exit (1); } arg++; namep++; } 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 ("snmpbulkget", &session); SOCK_CLEANUP; exit (1); } /* * create PDU for GETBULK request and add object name to request */ pdu = snmp_pdu_create (SNMP_MSG_GETBULK); pdu->non_repeaters = non_repeaters; pdu->max_repetitions = max_repetitions; /* fill the packet */ for (arg = 0; arg < names; arg++) snmp_add_null_var (pdu, name[arg].name, name[arg].name_len); /* * do the request */ status = snmp_synch_response (ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { /* * check resulting variables */ for (vars = response->variables; vars; vars = vars->next_variable) print_variable (vars->name, vars->name_length, vars); } else { /* * error in response, print it */ if (response->errstat == SNMP_ERR_NOSUCHNAME) { printf ("End of MIB.\n"); } else { fprintf (stderr, "Error in packet.\nReason: %s\n", snmp_errstring (response->errstat)); if (response->errindex != 0) { fprintf (stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && (count != response->errindex); vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid (stderr, vars->name, vars->name_length); fprintf (stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf (stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror ("snmpbulkget", ss); exitval = 1; } if (response) snmp_free_pdu (response); snmp_close (ss); SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; int arg; oid name[MAX_OID_LEN]; size_t name_length; oid root[MAX_OID_LEN]; size_t rootlen; int count; int running; int status; int check; int exitval = 0; netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "includeRequested", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_INCLUDE_REQUESTED); netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "printStatistics", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_PRINT_STATISTICS); netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "dontCheckOrdering", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); /* * 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; } /* * get the initial object and subtree */ if (arg < argc) { /* * specified on the command line */ rootlen = MAX_OID_LEN; if (snmp_parse_oid(argv[arg], root, &rootlen) == NULL) { snmp_perror(argv[arg]); exit(1); } } else { /* * use default value */ memmove(root, objid_mib, sizeof(objid_mib)); rootlen = sizeof(objid_mib) / sizeof(oid); } 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("snmpbulkwalk", &session); SOCK_CLEANUP; exit(1); } /* * setup initial object name */ memmove(name, root, rootlen * sizeof(oid)); name_length = rootlen; running = 1; check = !netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_INCLUDE_REQUESTED)) { snmp_get_and_print(ss, root, rootlen); } while (running) { /* * create PDU for GETBULK request and add object name to request */ pdu = snmp_pdu_create(SNMP_MSG_GETBULK); pdu->non_repeaters = non_reps; pdu->max_repetitions = reps; /* fill the packet */ snmp_add_null_var(pdu, name, name_length); /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { /* * check resulting variables */ for (vars = response->variables; vars; vars = vars->next_variable) { if ((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0)) { /* * not part of this subtree */ running = 0; continue; } numprinted++; print_variable(vars->name, vars->name_length, vars); if ((vars->type != SNMP_ENDOFMIBVIEW) && (vars->type != SNMP_NOSUCHOBJECT) && (vars->type != SNMP_NOSUCHINSTANCE)) { /* * not an exception value */ if (check && snmp_oid_compare(name, name_length, vars->name, vars->name_length) >= 0) { fprintf(stderr, "Error: OID not increasing: "); fprint_objid(stderr, name, name_length); fprintf(stderr, " >= "); fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); running = 0; exitval = 1; } /* * Check if last variable, and if so, save for next request. */ if (vars->next_variable == NULL) { memmove(name, vars->name, vars->name_length * sizeof(oid)); name_length = vars->name_length; } } else { /* * an exception value, so stop */ running = 0; } } } else { /* * error in response, print it */ running = 0; if (response->errstat == SNMP_ERR_NOSUCHNAME) { printf("End of MIB\n"); } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); running = 0; exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpbulkwalk", ss); running = 0; exitval = 1; } if (response) snmp_free_pdu(response); } if (numprinted == 0 && status == STAT_SUCCESS) { /* * no printed successful results, which may mean we were * pointed at an only existing instance. Attempt a GET, just * for get measure. */ snmp_get_and_print(ss, root, rootlen); } snmp_close(ss); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_PRINT_STATISTICS)) { printf("Variables found: %d\n", numprinted); } SOCK_CLEANUP; return exitval; }
void build_valuetable(void) { struct expExpressionTable_data *expstorage, *expfound; struct expObjectTable_data *objstorage, *objfound = NULL; struct header_complex_index *hcindex, *object_hcindex; char *expression; size_t expression_len; oid *index; char *result, *resultbak; char *temp, *tempbak; int i = 0, j, l; temp = malloc(100); result = malloc(100); tempbak = temp; memset(result, 0, 100); *result = '\0'; resultbak = result; DEBUGMSGTL(("expValueTable", "building valuetable... \n")); for (hcindex = expExpressionTableStorage; hcindex != NULL; hcindex = hcindex->next) { expstorage = (struct expExpressionTable_data *) hcindex->data; if (expstorage->expExpressionEntryStatus == RS_ACTIVE) { expression = expstorage->expExpression; expression_len = expstorage->expExpressionLen; while (*expression != '\0') { if (*expression == '$') { i++; for (j = 1; j < 100; j++) { if ((*(expression + j) == '+') || (*(expression + j) == '-') || (*(expression + j) == '*') || (*(expression + j) == '/') || (*(expression + j) == '(') || (*(expression + j) == ')') || *(expression + j) == '\0') { break; } } strncpy(temp, expression + 1, j - 1); *(temp + j - 1) = '\0'; l = atoi(temp); for (object_hcindex = expObjectTableStorage; object_hcindex != NULL; object_hcindex = object_hcindex->next) { objstorage = (struct expObjectTable_data *) object_hcindex-> data; if (!strcmp (objstorage->expExpressionOwner, expstorage->expExpressionOwner) && (objstorage->expExpressionOwnerLen == expstorage->expExpressionOwnerLen) && !strcmp(objstorage->expExpressionName, expstorage->expExpressionName) && (objstorage->expExpressionNameLen == expstorage->expExpressionNameLen) && (l == objstorage->expObjectIndex)) { if (objfound == NULL) { expfound = expstorage; objfound = objstorage; } if (objstorage->expObjectIDWildcard == EXPOBJCETIDWILDCARD_TRUE) objfound = objstorage; } } expression = expression + j; } else { expression++; } }; } if (!objfound) { continue; } if (objfound->expObjectIDWildcard == EXPOBJCETIDWILDCARD_FALSE) { index = calloc(1, MAX_OID_LEN); *index = 0; *(index + 1) = 0; *(index + 2) = 0; expValueTable_add(expstorage, objfound->expExpressionOwner, objfound->expExpressionOwnerLen, objfound->expExpressionName, objfound->expExpressionNameLen, index, 3); } else { oid *targetOID; size_t taggetOID_len; targetOID = objfound->expObjectID; struct snmp_pdu *pdu; struct snmp_pdu *response; oid *next_OID; size_t next_OID_len; taggetOID_len = objfound->expObjectIDLen; int status; struct snmp_session *ss; /* * Initialize the SNMP library */ /* * set the SNMP version number */ session.version = expstorage->pdu_version; /* * set the SNMPv1 community name used for authentication */ session.community = expstorage->pdu_community; session.community_len = expstorage->pdu_community_len; /* * Open the session */ SOCK_STARTUP; ss = snmp_open(&session); /* establish the session */ if (!ss) { snmp_perror("ack"); snmp_log(LOG_ERR, "something horrible happened!!!\n"); exit(2); } next_OID = targetOID; next_OID_len = taggetOID_len; do { index = calloc(1, MAX_OID_LEN); pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); snmp_add_null_var(pdu, next_OID, next_OID_len); /* * Send the Request out. */ status = snmp_synch_response(ss, pdu, &response); /* * Process the response. */ if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { /* * SUCCESS: Print the result variables */ if (((response->variables->type >= SNMP_NOSUCHOBJECT && response->variables->type <= SNMP_ENDOFMIBVIEW) || snmp_oid_compare(targetOID, taggetOID_len, response->variables->name, taggetOID_len) != 0)) { break; } /* add to expValueTable */ *index = 0; *(index + 1) = 0; memcpy(index + 2, response->variables->name + taggetOID_len, (response->variables->name_length - taggetOID_len) * sizeof(oid)); expValueTable_add(expstorage, objfound->expExpressionOwner, objfound->expExpressionOwnerLen, objfound->expExpressionName, objfound->expExpressionNameLen, index, response->variables->name_length - taggetOID_len + 2); next_OID = response->variables->name; next_OID_len = response->variables->name_length; } 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); } } while (TRUE); } } }
void *poller(void *thread_args) { worker_t *worker = (worker_t *) thread_args; crew_t *crew = worker->crew; target_t *entry = NULL; void *sessp = NULL; struct snmp_session session; struct snmp_pdu *pdu = NULL; struct snmp_pdu *response = NULL; oid anOID[MAX_OID_LEN]; size_t anOID_len = MAX_OID_LEN; struct variable_list *vars = NULL; unsigned long long result = 0; unsigned long long last_value = 0; unsigned long long insert_val = 0; int status = 0, bits = 0, init = 0; char query[BUFSIZE]; char storedoid[BUFSIZE]; char result_string[BUFSIZE]; if (set.verbose >= HIGH) printf("Thread [%d] starting.\n", worker->index); if (MYSQL_VERSION_ID > 40000) mysql_thread_init(); else my_thread_init(); while (1) { if (set.verbose >= DEVELOP) printf("Thread [%d] locking (wait on work)\n", worker->index); PT_MUTEX_LOCK(&crew->mutex); while (current == NULL) { PT_COND_WAIT(&crew->go, &crew->mutex); } if (set.verbose >= DEVELOP) printf("Thread [%d] done waiting, received go (work cnt: %d)\n", worker->index, crew->work_count); if (current != NULL) { if (set.verbose >= HIGH) printf("Thread [%d] processing %s %s (%d work units remain in queue)\n", worker->index, current->host, current->objoid, crew->work_count); snmp_sess_init(&session); if (set.snmp_ver == 2) session.version = SNMP_VERSION_2c; else session.version = SNMP_VERSION_1; session.peername = current->host; session.remote_port = set.snmp_port; session.community = current->community; session.community_len = strlen(session.community); sessp = snmp_sess_open(&session); anOID_len = MAX_OID_LEN; pdu = snmp_pdu_create(SNMP_MSG_GET); read_objid(current->objoid, anOID, &anOID_len); entry = current; last_value = current->last_value; init = current->init; insert_val = 0; bits = current->bits; strncpy(storedoid, current->objoid, sizeof(storedoid)); current = getNext(); } if (set.verbose >= DEVELOP) printf("Thread [%d] unlocking (done grabbing current)\n", worker->index); PT_MUTEX_UNLOCK(&crew->mutex); snmp_add_null_var(pdu, anOID, anOID_len); if (sessp != NULL) status = snmp_sess_synch_response(sessp, pdu, &response); else status = STAT_DESCRIP_ERROR; /* Collect response and process stats */ PT_MUTEX_LOCK(&stats.mutex); if (status == STAT_DESCRIP_ERROR) { stats.errors++; printf("*** SNMP Error: (%s) Bad descriptor.\n", session.peername); } else if (status == STAT_TIMEOUT) { stats.no_resp++; printf("*** SNMP No response: (%s@%s).\n", session.peername, storedoid); } else if (status != STAT_SUCCESS) { stats.errors++; printf("*** SNMP Error: (%s@%s) Unsuccessuful (%d).\n", session.peername, storedoid, status); } else if (status == STAT_SUCCESS && response->errstat != SNMP_ERR_NOERROR) { stats.errors++; printf("*** SNMP Error: (%s@%s) %s\n", session.peername, storedoid, snmp_errstring(response->errstat)); } else if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { stats.polls++; } PT_MUTEX_UNLOCK(&stats.mutex); /* Liftoff, successful poll, process it */ if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { vars = response->variables; #ifdef OLD_UCD_SNMP sprint_value(result_string, anOID, anOID_len, vars); #else snprint_value(result_string, BUFSIZE, anOID, anOID_len, vars); #endif switch (vars->type) { /* * Switch over vars->type and modify/assign result accordingly. */ case ASN_COUNTER64: if (set.verbose >= DEBUG) printf("64-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string); result = vars->val.counter64->high; result = result << 32; result = result + vars->val.counter64->low; break; case ASN_COUNTER: if (set.verbose >= DEBUG) printf("32-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string); result = (unsigned long) *(vars->val.integer); break; case ASN_INTEGER: if (set.verbose >= DEBUG) printf("Integer result: (%s@%s) %s\n", session.peername, storedoid, result_string); result = (unsigned long) *(vars->val.integer); break; case ASN_GAUGE: if (set.verbose >= DEBUG) printf("32-bit gauge: (%s@%s) %s\n", session.peername, storedoid, result_string); result = (unsigned long) *(vars->val.integer); break; case ASN_TIMETICKS: if (set.verbose >= DEBUG) printf("Timeticks result: (%s@%s) %s\n", session.peername, storedoid, result_string); result = (unsigned long) *(vars->val.integer); break; case ASN_OPAQUE: if (set.verbose >= DEBUG) printf("Opaque result: (%s@%s) %s\n", session.peername, storedoid, result_string); result = (unsigned long) *(vars->val.integer); break; default: if (set.verbose >= DEBUG) printf("Unknown result type: (%s@%s) %s\n", session.peername, storedoid, result_string); } /* Gauge Type */ if (bits == 0) { if (result != last_value) { insert_val = result; if (set.verbose >= HIGH) printf("Thread [%d]: Gauge change from %lld to %lld\n", worker->index, last_value, insert_val); } else { if (set.withzeros) insert_val = result; if (set.verbose >= HIGH) printf("Thread [%d]: Gauge steady at %lld\n", worker->index, insert_val); } /* Counter Wrap Condition */ } else if (result < last_value) { PT_MUTEX_LOCK(&stats.mutex); stats.wraps++; PT_MUTEX_UNLOCK(&stats.mutex); if (bits == 32) insert_val = (THIRTYTWO - last_value) + result; else if (bits == 64) insert_val = (SIXTYFOUR - last_value) + result; if (set.verbose >= LOW) { printf("*** Counter Wrap (%s@%s) [poll: %llu][last: %llu][insert: %llu]\n", session.peername, storedoid, result, last_value, insert_val); } /* Not a counter wrap and this is not the first poll */ } else if ((last_value >= 0) && (init != NEW)) { insert_val = result - last_value; /* Print out SNMP result if verbose */ if (set.verbose == DEBUG) printf("Thread [%d]: (%lld-%lld) = %llu\n", worker->index, result, last_value, insert_val); if (set.verbose == HIGH) printf("Thread [%d]: %llu\n", worker->index, insert_val); /* last_value < 0, so this must be the first poll */ } else { if (set.verbose >= HIGH) printf("Thread [%d]: First Poll, Normalizing\n", worker->index); } /* Check for bogus data, either negative or unrealistic */ if (insert_val > entry->maxspeed || result < 0) { if (set.verbose >= LOW) printf("*** Out of Range (%s@%s) [insert_val: %llu] [oor: %lld]\n", session.peername, storedoid, insert_val, entry->maxspeed); insert_val = 0; PT_MUTEX_LOCK(&stats.mutex); stats.out_of_range++; PT_MUTEX_UNLOCK(&stats.mutex); } if (!(set.dboff)) { if ( (insert_val > 0) || (set.withzeros) ) { PT_MUTEX_LOCK(&crew->mutex); snprintf(query, sizeof(query), "INSERT INTO %s VALUES (%d, NOW(), %llu)", entry->table, entry->iid, insert_val); if (set.verbose >= DEBUG) printf("SQL: %s\n", query); status = mysql_query(&mysql, query); if (status) printf("*** MySQL Error: %s\n", mysql_error(&mysql)); PT_MUTEX_UNLOCK(&crew->mutex); if (!status) { PT_MUTEX_LOCK(&stats.mutex); stats.db_inserts++; PT_MUTEX_UNLOCK(&stats.mutex); } } /* insert_val > 0 or withzeros */ } /* !dboff */ } /* STAT_SUCCESS */ if (sessp != NULL) { snmp_sess_close(sessp); if (response != NULL) snmp_free_pdu(response); } if (set.verbose >= DEVELOP) printf("Thread [%d] locking (update work_count)\n", worker->index); PT_MUTEX_LOCK(&crew->mutex); crew->work_count--; /* Only if we received a positive result back do we update the last_value object */ if (status == STAT_SUCCESS) entry->last_value = result; if (init == NEW) entry->init = LIVE; if (crew->work_count <= 0) { if (set.verbose >= HIGH) printf("Queue processed. Broadcasting thread done condition.\n"); PT_COND_BROAD(&crew->done); } if (set.verbose >= DEVELOP) printf("Thread [%d] unlocking (update work_count)\n", worker->index); PT_MUTEX_UNLOCK(&crew->mutex); } /* while(1) */ }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response = NULL; netsnmp_variable_list *vars; int arg; int count; int current_name = 0; int current_type = 0; int current_value = 0; char *names[SNMP_MAX_CMDLINE_OIDS]; char types[SNMP_MAX_CMDLINE_OIDS]; char *values[SNMP_MAX_CMDLINE_OIDS]; oid name[MAX_OID_LEN]; size_t name_length; int status; int exitval = 0; putenv(strdup("POSIXLY_CORRECT=1")); /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } if (arg >= argc) { fprintf(stderr, "Missing object name\n"); usage(); exit(1); } if ((argc - arg) > 3*SNMP_MAX_CMDLINE_OIDS) { fprintf(stderr, "Too many assignments specified. "); fprintf(stderr, "Only %d allowed in one request.\n", SNMP_MAX_CMDLINE_OIDS); usage(); exit(1); } /* * get object names, types, and values */ for (; arg < argc; arg++) { DEBUGMSGTL(("snmp_parse_args", "handling (#%d): %s %s %s\n", arg,argv[arg], arg+1 < argc ? argv[arg+1] : NULL, arg+2 < argc ? argv[arg+2] : NULL)); names[current_name++] = argv[arg++]; if (arg < argc) { switch (*argv[arg]) { case '=': case 'i': case 'u': case 't': case 'a': case 'o': case 's': case 'x': case 'd': case 'b': #ifdef OPAQUE_SPECIAL_TYPES case 'I': case 'U': case 'F': case 'D': #endif /* OPAQUE_SPECIAL_TYPES */ types[current_type++] = *argv[arg++]; break; default: fprintf(stderr, "%s: Bad object type: %c\n", argv[arg - 1], *argv[arg]); exit(1); } } else { fprintf(stderr, "%s: Needs type and value\n", argv[arg - 1]); exit(1); } if (arg < argc) values[current_value++] = argv[arg]; else { fprintf(stderr, "%s: Needs value\n", argv[arg - 2]); 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("snmpset", &session); SOCK_CLEANUP; exit(1); } /* * create PDU for SET request and add object names and values to request */ pdu = snmp_pdu_create(SNMP_MSG_SET); for (count = 0; count < current_name; count++) { name_length = MAX_OID_LEN; if (snmp_parse_oid(names[count], name, &name_length) == NULL) { snmp_perror(names[count]); failures++; } else if (snmp_add_var (pdu, name, name_length, types[count], values[count])) { snmp_perror(names[count]); failures++; } } if (failures) { SOCK_CLEANUP; exit(1); } /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (!quiet) { for (vars = response->variables; vars; vars = vars->next_variable) print_variable(vars->name, vars->name_length, vars); } } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && (count != response->errindex); vars = vars->next_variable, count++); if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } exitval = 2; } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpset", ss); exitval = 1; } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; netsnmp_variable_list *vars; int arg; int count; int current_name = 0; char *names[128]; oid name[MAX_OID_LEN]; size_t name_length; int status; int exitval = 0; /* * get the common command line arguments */ switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } if (arg >= argc) { fprintf(stderr, "Missing object name\n"); usage(); exit(1); } /* * get the object names */ for (; arg < argc; arg++) names[current_name++] = argv[arg]; 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("snmpget", &session); SOCK_CLEANUP; exit(1); } /* * Create PDU for GET request and add object names to request. */ pdu = snmp_pdu_create(SNMP_MSG_GET); for (count = 0; count < current_name; count++) { name_length = MAX_OID_LEN; if (!snmp_parse_oid(names[count], name, &name_length)) { snmp_perror(names[count]); failures++; } else snmp_add_null_var(pdu, name, name_length); } if (failures) { SOCK_CLEANUP; exit(1); } /* * Perform the request. * * If the Get Request fails, note the OID that caused the error, * "fix" the PDU (removing the error-prone OID) and retry. */ retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) print_variable(vars->name, vars->name_length, vars); } else { fprintf(stderr, "Error in packet\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) { fprint_objid(stderr, vars->name, vars->name_length); } fprintf(stderr, "\n"); } exitval = 2; /* * retry if the errored variable was successfully removed */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_APP_DONT_FIX_PDUS)) { pdu = snmp_fix_pdu(response, SNMP_MSG_GET); snmp_free_pdu(response); response = NULL; if (pdu != NULL) { goto retry; } } } /* endif -- SNMP_ERR_NOERROR */ } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s.\n", session.peername); exitval = 1; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpget", ss); exitval = 1; } /* endif -- STAT_SUCCESS */ if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return exitval; } /* end main() */
int main(int argc, char ** argv) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; oid anOID[MAX_OID_LEN]; size_t anOID_len; netsnmp_variable_list *vars; int status; int count=1; /* * Initialize the SNMP library */ init_snmp("snmpdemoapp"); /* * Initialize a "session" that defines who we're going to talk to */ snmp_sess_init( &session ); /* set up defaults */ session.peername = strdup("test.net-snmp.org"); /* set up the authentication parameters for talking to the server */ #ifdef DEMO_USE_SNMP_VERSION_3 /* Use SNMPv3 to talk to the experimental server */ /* set the SNMP version number */ session.version=SNMP_VERSION_3; /* set the SNMPv3 user name */ session.securityName = strdup("MD5User"); session.securityNameLen = strlen(session.securityName); /* set the security level to authenticated, but not encrypted */ session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV; /* set the authentication method to MD5 */ session.securityAuthProto = usmHMACMD5AuthProtocol; session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol)/sizeof(oid); session.securityAuthKeyLen = USM_AUTH_KU_LEN; /* set the authentication key to a MD5 hashed version of our passphrase "The Net-SNMP Demo Password" (which must be at least 8 characters long) */ if (generate_Ku(session.securityAuthProto, session.securityAuthProtoLen, (u_char *) our_v3_passphrase, strlen(our_v3_passphrase), session.securityAuthKey, &session.securityAuthKeyLen) != SNMPERR_SUCCESS) { snmp_perror(argv[0]); snmp_log(LOG_ERR, "Error generating Ku from authentication pass phrase. \n"); exit(1); } #else /* we'll use the insecure (but simplier) SNMPv1 */ /* set the SNMP version number */ session.version = SNMP_VERSION_1; /* set the SNMPv1 community name used for authentication */ session.community = "demopublic"; session.community_len = strlen(session.community); #endif /* SNMPv1 */ /* * Open the session */ SOCK_STARTUP; ss = snmp_open(&session); /* establish the session */ if (!ss) { snmp_sess_perror("ack", &session); SOCK_CLEANUP; exit(1); } /* * Create the PDU for the data for our request. * 1) We're going to GET the system.sysDescr.0 node. */ pdu = snmp_pdu_create(SNMP_MSG_GET); anOID_len = MAX_OID_LEN; if (!snmp_parse_oid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len)) { snmp_perror(".1.3.6.1.2.1.1.1.0"); SOCK_CLEANUP; exit(1); } #if OTHER_METHODS /* * These are alternatives to the 'snmp_parse_oid' call above, * e.g. specifying the OID by name rather than numerically. */ read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len); get_node("sysDescr.0", anOID, &anOID_len); read_objid("system.sysDescr.0", anOID, &anOID_len); #endif snmp_add_null_var(pdu, anOID, anOID_len); /* * Send the Request out. */ status = snmp_synch_response(ss, pdu, &response); /* * Process the response. */ if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { /* * SUCCESS: Print the result variables */ 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_OCTET_STR) { char *sp = (char *)malloc(1 + vars->val_len); memcpy(sp, vars->val.string, vars->val_len); sp[vars->val_len] = '\0'; printf("value #%d is a string: %s\n", count++, sp); free(sp); } else printf("value #%d is NOT a string! Ack!\n", count++); } } else { /* * FAILURE: print what went wrong! */ 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); } /* * Clean up: * 1) free the response. * 2) close the session. */ if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; return (0); } /* main() */
/* * read value of given oid and return it as string */ static void * MPC_read(struct snmp_session *sptr, const char *objname, int type) { oid name[MAX_OID_LEN]; size_t namelen = MAX_OID_LEN; struct variable_list *vars; struct snmp_pdu *pdu; struct snmp_pdu *resp; static char response_str[MAX_STRING]; static int response_int; DEBUGCALL; /* convert objname into oid; return NULL if invalid */ if (!read_objid(objname, name, &namelen)) { LOG(PIL_CRIT, "%s: cannot convert %s to oid.", __FUNCTION__, objname); return (NULL); } /* create pdu */ if ((pdu = snmp_pdu_create(SNMP_MSG_GET)) != NULL) { /* get-request have no values */ snmp_add_null_var(pdu, name, namelen); /* send pdu and get response; return NULL if error */ if (snmp_synch_response(sptr, pdu, &resp) == SNMPERR_SUCCESS) { /* request succeed, got valid response ? */ if (resp->errstat == SNMP_ERR_NOERROR) { /* go through the returned vars */ for (vars = resp->variables; vars; vars = vars->next_variable) { /* return response as string */ if ((vars->type == type) && (type == ASN_OCTET_STR)) { memset(response_str, 0, MAX_STRING); strncpy(response_str, (char *)vars->val.string, MIN(vars->val_len, MAX_STRING)); snmp_free_pdu(resp); return ((void *) response_str); } /* return response as integer */ if ((vars->type == type) && (type == ASN_INTEGER)) { response_int = *vars->val.integer; snmp_free_pdu(resp); return ((void *) &response_int); } } } else { LOG(PIL_CRIT, "%s: error in response packet, reason %ld [%s]." , __FUNCTION__, resp->errstat, snmp_errstring(resp->errstat)); } } else { MPC_error(sptr, __FUNCTION__, "error sending/receiving pdu"); } /* free repsonse pdu (necessary?) */ snmp_free_pdu(resp); } else { MPC_error(sptr, __FUNCTION__, "cannot create pdu"); } /* error: return nothing */ return (NULL); }
SaErrorT snmp_bc_bulk_selcache( struct oh_handler_state *handle, SaHpiResourceIdT id) { struct snmp_bc_hnd *custom_handle; SaErrorT err; int isdst; sel_entry sel_entry; SaHpiEventT tmpevent; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; LogSource2ResourceT logsrc2res; int count; int running; int status; char logstring[MAX_ASN_STR_LEN]; char objoid[SNMP_BC_MAX_OID_LENGTH]; oid name[MAX_OID_LEN]; oid root[MAX_OID_LEN]; size_t rootlen; size_t name_length; size_t str_len; int reps; if (!handle) { err("Invalid parameter."); return(SA_ERR_HPI_INVALID_PARAMS); } str_len = MAX_ASN_STR_LEN; isdst=0; custom_handle = (struct snmp_bc_hnd *)handle->data; reps = custom_handle->count_per_getbulk; /* --------------------------------------------------- */ /* Set initial Event Log Entry OID and root tree */ /* --------------------------------------------------- */ if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { snprintf(objoid, SNMP_BC_MAX_OID_LENGTH, "%s", SNMP_BC_SEL_ENTRY_OID_RSA); } else { snprintf(objoid, SNMP_BC_MAX_OID_LENGTH, "%s",SNMP_BC_SEL_ENTRY_OID); } rootlen = MAX_OID_LEN; read_objid(objoid, root, &rootlen); /* --------------------------------------------------- */ /* Object ID for GETBULK request */ /* --------------------------------------------------- */ g_memmove(name, root, rootlen * sizeof(oid)); name_length = rootlen; running = 1; while (running) { /* --------------------------------------------------- */ /* Create PDU for GETBULK request */ /* --------------------------------------------------- */ pdu = snmp_pdu_create(SNMP_MSG_GETBULK); status = snmp_getn_bulk(custom_handle->sessp, name, name_length, pdu, &response, reps); if (pdu) snmp_free_pdu(pdu); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) { /* ------------------------------------------------- */ /* Check if this variable is of the same OID tree */ /* ------------------------------------------------- */ if ((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0)) { /* Exit vars processing */ running = 0; continue; } if ((vars->type != SNMP_ENDOFMIBVIEW) && (vars->type != SNMP_NOSUCHOBJECT) && (vars->type != SNMP_NOSUCHINSTANCE)) { if (snmp_oid_compare(name, name_length, vars->name, vars->name_length) >= 0) { fprintf(stderr, "Error: OID not increasing: "); fprint_objid(stderr, name, name_length); fprintf(stderr, " >= "); fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); running = 0; } /* ---------------------------------- */ /* Check if last variable, */ /* and if so, save for next request. */ /* ---------------------------------- */ if (vars->next_variable == NULL) { g_memmove(name, vars->name, vars->name_length * sizeof(oid)); name_length = vars->name_length; } /* ---------------------------------- */ /* ---------------------------------- */ /* ---------------------------------- */ if ((running == 1) && (vars->type == ASN_OCTET_STR)) { if (vars->val_len < MAX_ASN_STR_LEN) str_len = vars->val_len; else str_len = MAX_ASN_STR_LEN; /* ---------------------------------- */ /* Guarantee NULL terminated string */ /* ---------------------------------- */ // memcpy(logstring, vars->val.string, str_len); g_memmove(logstring, vars->val.string, str_len); logstring[str_len] = '\0'; err = snmp_bc_parse_sel_entry(handle,logstring, &sel_entry); isdst = sel_entry.time.tm_isdst; snmp_bc_log2event(handle, logstring, &tmpevent, isdst, &logsrc2res); err = oh_el_prepend(handle->elcache, &tmpevent, NULL, NULL); if (custom_handle->isFirstDiscovery == SAHPI_FALSE) err = snmp_bc_add_to_eventq(handle, &tmpevent, SAHPI_TRUE); } } else { /* Stop on an exception value */ running = 0; } } /* end for */ } else { /* if (response->errstat != SNMP_ERR_NOERROR) */ /* --------------------------------------------- */ /* Error condition is seen in response, */ /* for now, print the error then exit */ /* Not sure what to do for recovery */ running = 0; if (response->errstat == SNMP_ERR_NOSUCHNAME) { printf("End of MIB\n"); } else { fprintf(stderr, "Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); } } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response\n"); running = 0; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmp_bulk_sel",custom_handle->sessp ); running = 0; } if (response) snmp_free_pdu(response); } return(SA_OK); }
unsigned long Evaluate_Expression(struct expValueTable_data *vtable_data) { struct header_complex_index *hcindex; struct expObjectTable_data *objstorage, *objfound; struct expValueTable_data *valstorage; valstorage = vtable_data; char *expression; char *result, *resultbak; char *temp, *tempbak; char intchar[10]; int i = 0, j, k, l; long value; unsigned long result_u_long; temp = malloc(100); result = malloc(100); tempbak = temp; memset(result, 0, 100); *result = '\0'; resultbak = result; expression = vtable_data->expression_data->expExpression; while (*expression != '\0') { if (*expression == '$') { objfound = NULL; i++; for (j = 1; j < 100; j++) { if ((*(expression + j) == '+') || (*(expression + j) == '-') || (*(expression + j) == '*') || (*(expression + j) == '/') || (*(expression + j) == '(') || (*(expression + j) == ')') || *(expression + j) == '\0') { break; } } strncpy(temp, expression + 1, j - 1); *(temp + j - 1) = '\0'; l = atoi(temp); expression = expression + j; /* * here use snmpget to get value */ for (hcindex = expObjectTableStorage; hcindex != NULL; hcindex = hcindex->next) { objstorage = (struct expObjectTable_data *) hcindex->data; if (!strcmp (objstorage->expExpressionOwner, valstorage->expExpressionOwner) && (objstorage->expExpressionOwnerLen == valstorage->expExpressionOwnerLen) && !strcmp(objstorage->expExpressionName, valstorage->expExpressionName) && (objstorage->expExpressionNameLen == valstorage->expExpressionNameLen) && (l == objstorage->expObjectIndex)) { objfound = objstorage; break; } } if (!objfound) { /* have err */ return 0; } struct snmp_session *ss; struct snmp_pdu *pdu; struct snmp_pdu *response; oid anOID[MAX_OID_LEN]; size_t anOID_len; memcpy(anOID, objfound->expObjectID, objfound->expObjectIDLen * sizeof(oid)); anOID_len = objfound->expObjectIDLen; if (objfound->expObjectIDWildcard == EXPOBJCETIDWILDCARD_TRUE) { anOID_len = anOID_len + valstorage->expValueInstanceLen - 2; memcpy(anOID + objfound->expObjectIDLen, valstorage->expValueInstance + 2, (valstorage->expValueInstanceLen - 2) * sizeof(oid)); } struct variable_list *vars; int status; /* * Initialize the SNMP library */ /* * Initialize a "session" that defines who we're going to talk to */ session.version = vtable_data->expression_data->pdu_version; /* * set the SNMPv1 community name used for authentication */ session.community = vtable_data->expression_data->pdu_community; session.community_len = vtable_data->expression_data->pdu_community_len; /* * Open the session */ SOCK_STARTUP; ss = snmp_open(&session); /* establish the session */ if (!ss) { /* err */ exit(2); } pdu = snmp_pdu_create(SNMP_MSG_GET); snmp_add_null_var(pdu, anOID, anOID_len); /* * Send the Request out. */ status = snmp_synch_response(ss, pdu, &response); /* * Process the response. */ if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { /* * SUCCESS: Print the result variables */ vars = response->variables; value = *(vars->val.integer); sprintf(intchar, "%lu", value); for (k = 1; k <= strlen(intchar); k++) { *result = intchar[k - 1]; result++; } } 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: * 1) free the response. * 2) close the session. */ if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; } else { *result = *expression; result++; expression++; } } result_u_long = get_result(resultbak); free(tempbak); free(resultbak); return result_u_long; }