Beispiel #1
0
void view_oid (oid * it, size_t * len, const char *viewName, char *viewSubtree)
{
    int i;

    oid c_oid[SPRINT_MAX_LEN];

    size_t c_oid_length = SPRINT_MAX_LEN;

    int itIndex = VIEW_OID_LEN;

    if (!snmp_parse_oid (viewSubtree, c_oid, &c_oid_length))
    {
        printf ("Error parsing subtree (%s)\n", viewSubtree);
        exit (1);
    }

    *len = itIndex + 2 + strlen (viewName) + c_oid_length;

    it[itIndex++] = strlen (viewName);
    for (i = 0; i < (int) strlen (viewName); i++)
        it[itIndex++] = viewName[i];


    it[itIndex++] = c_oid_length;
    for (i = 0; i < (int) c_oid_length; i++)
        it[itIndex++] = c_oid[i];

    /*
     * sprint_objid(c_oid, it, *len); 
     */
}
Beispiel #2
0
int
add(netsnmp_pdu *pdu, const char *mibnodename,
    oid * index, size_t indexlen)
{
    oid             base[MAX_OID_LEN];
    size_t          base_length = MAX_OID_LEN;

    memset(base, 0, MAX_OID_LEN * sizeof(oid));

    if (!snmp_parse_oid(mibnodename, base, &base_length)) {
        snmp_perror(mibnodename);
        fprintf(stderr, "couldn't find mib node %s, giving up\n",
                mibnodename);
#if HAVE_CURSES_H
        endwin();
#endif
        exit(1);
    }

    if (index && indexlen) {
        memcpy(&(base[base_length]), index, indexlen * sizeof(oid));
        base_length += indexlen;
    }
    DEBUGMSGTL(("add", "created: "));
    DEBUGMSGOID(("add", base, base_length));
    DEBUGMSG(("add", "\n"));
    snmp_add_null_var(pdu, base, base_length);

    return base_length;
}
/**
 * The 'raw' SNMP set function. It should not be used directly in external
 * files. Rather, a non-static wrapper function should be created here that
 * makes the appropriate call in order to preserve source code readability.
 *
 * @return 1 if successful, 0 if not
 */
static int snmp_set(netsnmp_session *s, char *oid_str, char type, const char *val)
{
	netsnmp_pdu *pdu;
	oid the_oid[MAX_OID_LEN];
	size_t oid_len;

	pdu = snmp_pdu_create(SNMP_MSG_SET);
	oid_len = MAX_OID_LEN;

	// Parse the OID
	if (snmp_parse_oid(oid_str, the_oid, &oid_len) == 0) {
		snmp_perror(oid_str);
		return 0;
	}

	// Build the packet to be sent
	if (snmp_add_var(pdu, the_oid, oid_len, type, val) != 0) {
		printf("type: %c, val: %s, oid_str: %s\n", type, val, oid_str);
		snmp_perror("SNMP: Could not add var!");
		return 0;
	}

	// Send the request
	if (snmp_send(s, pdu) == 0) {
		snmp_perror("SNMP: Error while sending!");
		snmp_free_pdu(pdu);
		return 0;
	}

	return 1;
}
void
simpleSNMPsend(struct snmp_session *session,
	       oid *name,
	       size_t name_length)
{
    struct snmp_pdu *pdu;
    oid uptime[MAX_OID_LEN];
    size_t uptime_length;

    /* 
     * Create PDU for GET request and add object names to request.
     */
    pdu = snmp_pdu_create(SNMP_MSG_GET);

    /* 
     * First insert uptime request into PDU.
     */
    uptime_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysUpTime.0",
			uptime, &uptime_length)) {
	    printf("error parsing oid: system.sysUpTime.0\n");
    }
    snmp_add_null_var(pdu, uptime, uptime_length);

    snmp_add_null_var(pdu, name, name_length);

    /* 
     * Perform the request.
     */

    snmp_send(session, pdu);
}
static inline void add_field (
	netsnmp_pdu *trap_pdu,
	u_char asn_type,
	const char *prefix,
	void *value,
	size_t value_size)
{
	oid _oid[MAX_OID_LEN];
	size_t _oid_len = MAX_OID_LEN;
	if (snmp_parse_oid(prefix, _oid, &_oid_len)) {
		snmp_pdu_add_variable (trap_pdu, _oid, _oid_len, asn_type, (u_char *) value, value_size);
	}
}
Beispiel #6
0
static int csnmp_config_add_data_values (data_definition_t *dd, oconfig_item_t *ci)
{
  int i;

  if (ci->values_num < 1)
  {
    WARNING ("snmp plugin: `Values' needs at least one argument.");
    return (-1);
  }

  for (i = 0; i < ci->values_num; i++)
    if (ci->values[i].type != OCONFIG_TYPE_STRING)
    {
      WARNING ("snmp plugin: `Values' needs only string argument.");
      return (-1);
    }

  sfree (dd->values);
  dd->values_len = 0;
  dd->values = (oid_t *) malloc (sizeof (oid_t) * ci->values_num);
  if (dd->values == NULL)
    return (-1);
  dd->values_len = (size_t) ci->values_num;

  for (i = 0; i < ci->values_num; i++)
  {
    dd->values[i].oid_len = MAX_OID_LEN;

    if (NULL == snmp_parse_oid (ci->values[i].value.string,
          dd->values[i].oid, &dd->values[i].oid_len))
    {
      ERROR ("snmp plugin: snmp_parse_oid (%s) failed.",
          ci->values[i].value.string);
      free (dd->values);
      dd->values = NULL;
      dd->values_len = 0;
      return (-1);
    }
  }

  return (0);
} /* int csnmp_config_add_data_instance */
static void add_pdu_var(netsnmp_pdu *pdu, const char *mib_name, int id, const char *value)
{
	oid oid_name[MAX_OID_LEN];
	size_t name_length;

	char buf[4096];
	buf[4095] = '\0';
	snprintf(buf, sizeof(buf)-1, "%s.%d", mib_name, id);

	name_length = MAX_OID_LEN;
	if (snmp_parse_oid(buf, oid_name, &name_length) == NULL) {
		snmp_perror(buf);
		return;
	}

	if (snmp_add_var(pdu, oid_name, name_length, '=', value)) {
		snmp_perror(buf);
		return;
	}
}
Beispiel #8
0
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() */
Beispiel #9
0
/**
 * Bulk walk snmp value to the structure my_oid_result array.
 * Author : lining 15810423651 [email protected] 
 * @param peername  : the remote host ip address.
 * @param oid_argv : the char *oid pointer.
 * @param my_oid_result oid_results : the return values array.
 * @param my_oid_result oid_results_nums : the values array numbers. 
 * @return 0 on success, or others on failure.
 * @return 1 on failure, the argument error.
 * @return 2 on failure, snmp_open return error.
 * @return 3 on failure, snmp_parse_oid return error.
 * @return 4 on failure, snmp_synch_response return status time out.
 * @return 5 on failure, snmp_synch_response return status others.
 * @return 6 on failure, response->errstat end of mib.
 * @return 7 on failure, response->errstat others.
 */
int my_snmp_bulkwalk(const char *peername, 
				     const char *community, 
				     const char *oid_argv, 
				     my_oid_result *oid_results, 
				     unsigned int *oid_results_nums) {

  	if(peername == NULL) {
		printf("[ERROR] my_snmp_walk: the peername pointer is null\n");
		return 1;
	}
	
	if(community == NULL) {
		printf("[ERROR] my_snmp_walk: the community pointer is null\n");
		return 1;
	}
	
	if(oid_argv == NULL) {
		printf("[ERROR] my_snmp_walk: the oid_argv pointer is null\n");	
		return 1;
	}

	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	numprinted = 0;
	int	reps = 10, non_reps = 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);


	init_snmp("snmpapp");
	snmp_sess_init(&session);
	session.version = SNMP_VERSION_2c;
	session.community = (char*)community;
	session.community_len = strlen(session.community);
	session.peername = (char*)peername;
	session.timeout = 1000000;
	session.retries = 1;

	rootlen = MAX_OID_LEN;
	if(snmp_parse_oid(oid_argv, root, &rootlen) == NULL) {
		printf("[ERROR] my_snmp_bulkwalk: call snmp_parse_oid function failed\n");
		snmp_close(ss);
        SOCK_CLEANUP;		
		return 2;
	}

    SOCK_STARTUP;
    ss = snmp_open(&session);
    if(ss == NULL) {
        printf("[ERROR] my_snmp_bulkwalk: cakk snnp_open function failed\n");
		snmp_close(ss);
        SOCK_CLEANUP;
        return 3;
    }


    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);

    while(running) {

        pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
        pdu->non_repeaters = non_reps;
        pdu->max_repetitions = reps;
        snmp_add_null_var(pdu, name, name_length);

        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((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0)) {
                        running = 0;
                        continue;
                    }
		
					get_bulkwalk_oid_values(vars, &oid_results[numprinted]);
                    numprinted++;
			
                    if((vars->type != SNMP_ENDOFMIBVIEW) && (vars->type != SNMP_NOSUCHOBJECT) && (vars->type != SNMP_NOSUCHINSTANCE)) {
                        if(check && snmp_oid_compare(name, name_length, vars->name, vars->name_length) >= 0) {
                            running = 0;
                        }
                        if(vars->next_variable == NULL) {
							
							unsigned int count;
							for(count = 0; count < vars->name_length; count++) {
								oid_results[numprinted - 1].oid_name[count] = vars->name[count];
								oid_results[numprinted - 1].oid_name_length = vars->name_length;
							}
                            memmove(name, vars->name, vars->name_length * sizeof(oid));
                            name_length = vars->name_length;
                        }
                    } else {
                        running = 0;
                    }
                }
            } else {
                running = 0;
                if(response->errstat == SNMP_ERR_NOSUCHNAME) {
					printf("[ERROR] my_snmp_bulkwalk: have reached the end of MIB file\n");
					*oid_results_nums = numprinted;
					snmp_close(ss);
					SOCK_CLEANUP;		
					return 6;
                } else {
					printf("[ERROR] my_snmp_bulkwalk: return response->errstat others error\n");
					*oid_results_nums = numprinted;
					snmp_close(ss);
					SOCK_CLEANUP;			
					return 7;
                }
            }
        } else if(status == STAT_TIMEOUT) {
			printf("[ERROR] my_snmp_bulkwalk: return status is session time out\n");
			running = 0;
			*oid_results_nums = numprinted;
			snmp_close(ss);
			SOCK_CLEANUP;			
			return 4;
        } else {
			printf("[ERROR] my_snmp_bulkwalk: return session response error\n");
            running = 0;
			*oid_results_nums = numprinted;
			snmp_close(ss);
			SOCK_CLEANUP;
			return 5;
        }
		
        if(response) {
            snmp_free_pdu(response);
		}
    }
	
	*oid_results_nums = numprinted;
    snmp_close(ss);
    SOCK_CLEANUP;
	
    return 0;	
}
Beispiel #10
0
/** @internal */
void
netsnmp_config_parse_table_set(const char *token, char *line)
{
    oid             name[MAX_OID_LEN], table_name[MAX_OID_LEN];
    size_t          name_length = MAX_OID_LEN, table_name_length =
        MAX_OID_LEN;
    struct tree    *tp, *indexnode;
    netsnmp_table_data_set *table_set;
    data_set_tables *tables;
    struct index_list *index;
    unsigned int    mincol = 0xffffff, maxcol = 0;
    u_char          type;
    char           *pos;

    /*
     * instatiate a fake table based on MIB information 
     */
    DEBUGMSGTL(("9:table_set_add_table", "processing '%s'\n", line));
    if (NULL != (pos = strchr(line,' '))) {
        config_pwarn("ignoring extra tokens on line");
        snmp_log(LOG_WARNING,"  ignoring '%s'\n", pos);
        *pos = '\0';
    }

    /*
     * check for duplicate table
     */
    tables = (data_set_tables *) netsnmp_get_list_data(auto_tables, line);
    if (NULL != tables) {
        config_pwarn("duplicate table definition");
        return;
    }

    /*
     * parse oid and find tree structure
     */
    if (!snmp_parse_oid(line, table_name, &table_name_length)) {
        config_pwarn
            ("can't instatiate table since I can't parse the table name");
        return;
    }
    if(NULL == (tp = get_tree(table_name, table_name_length,
                              get_tree_head()))) {
        config_pwarn("can't instatiate table since "
                     "I can't find mib information about it");
        return;
    }

    if (NULL == (tp = tp->child_list) || NULL == tp->child_list) {
        config_pwarn("can't instatiate table since it doesn't appear to be "
                     "a proper table (no children)");
        return;
    }

    /*
     * check for augments indexes
     */
    if (NULL != tp->augments) {
        if (!snmp_parse_oid(tp->augments, table_name, &table_name_length)) {
            config_pwarn("I can't parse the augment tabel name");
            snmp_log(LOG_WARNING, "  can't parse %s\n", tp->augments);
            return;
        }
        if(NULL == (tp = get_tree(table_name, table_name_length,
                                  get_tree_head()))) {
            config_pwarn("can't instatiate table since "
                         "I can't find mib information about augment table");
            snmp_log(LOG_WARNING, "  table %s not found in tree\n",
                     tp->augments);
            return;
        }

        table_set = netsnmp_create_table_data_set(line);
    
        /*
         * loop through indexes and add types 
         */
        for (index = tp->indexes; index; index = index->next) {
            if (!snmp_parse_oid(index->ilabel, name, &name_length) ||
                (NULL ==
                 (indexnode = get_tree(name, name_length, get_tree_head())))) {
                config_pwarn("can't instatiate table since "
                             "I don't know anything about one index");
                snmp_log(LOG_WARNING, "  index %s not found in tree\n",
                         index->ilabel);
                return;             /* xxx mem leak */
            }
            
            type = mib_to_asn_type(indexnode->type);
            if (type == (u_char) - 1) {
                config_pwarn("unknown index type");
                return;             /* xxx mem leak */
            }
            if (index->isimplied)   /* if implied, mark it as such */
                type |= ASN_PRIVATE;
            
            DEBUGMSGTL(("table_set_add_row",
                        "adding default index of type %d\n", type));
            netsnmp_table_dataset_add_index(table_set, type);
        }
    }
    else
        table_set = netsnmp_create_table_data_set(line);
    
    /*
     * loop through indexes and add types 
     */
    for (index = tp->indexes; index; index = index->next) {
        if (!snmp_parse_oid(index->ilabel, name, &name_length) ||
            (NULL ==
             (indexnode = get_tree(name, name_length, get_tree_head())))) {
            config_pwarn("can't instatiate table since "
                         "I don't know anything about one index");
            snmp_log(LOG_WARNING, "  index %s not found in tree\n",
                     index->ilabel);
            return;             /* xxx mem leak */
        }

        type = mib_to_asn_type(indexnode->type);
        if (type == (u_char) - 1) {
            config_pwarn("unknown index type");
            return;             /* xxx mem leak */
        }
        if (index->isimplied)   /* if implied, mark it as such */
            type |= ASN_PRIVATE;

        DEBUGMSGTL(("table_set_add_row",
                    "adding default index of type %d\n", type));
        netsnmp_table_dataset_add_index(table_set, type);
    }

    /*
     * loop through children and add each column info 
     */
    for (tp = tp->child_list; tp; tp = tp->next_peer) {
        int             canwrite = 0;
        type = mib_to_asn_type(tp->type);
        if (type == (u_char) - 1) {
            config_pwarn("unknown column type");
            return;             /* xxx mem leak */
        }

        DEBUGMSGTL(("table_set_add_row",
                    "adding column %s(%d) of type %d (access %d)\n",
                    tp->label, tp->subid, type, tp->access));

        switch (tp->access) {
        case MIB_ACCESS_CREATE:
            table_set->allow_creation = 1;
        case MIB_ACCESS_READWRITE:
        case MIB_ACCESS_WRITEONLY:
            canwrite = 1;
        case MIB_ACCESS_READONLY:
            DEBUGMSGTL(("table_set_add_row",
                        "adding column %d of type %d\n", tp->subid, type));
            netsnmp_table_set_add_default_row(table_set, tp->subid, type,
                                              canwrite, NULL, 0);
            mincol = SNMP_MIN(mincol, tp->subid);
            maxcol = SNMP_MAX(maxcol, tp->subid);
            break;

        case MIB_ACCESS_NOACCESS:
        case MIB_ACCESS_NOTIFY:
            break;

        default:
            config_pwarn("unknown column access type");
            break;
        }
    }

    /*
     * register the table 
     */
    netsnmp_register_table_data_set(netsnmp_create_handler_registration
                                    (line, NULL, table_name,
                                     table_name_length,
                                     HANDLER_CAN_RWRITE), table_set, NULL);

    netsnmp_register_auto_data_table(table_set, NULL);
}
Beispiel #11
0
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() */
static void
apply_plugin_config()
{
  Reader *reader, *nreader;
  gchar  *name;
  gint   row;

  if (!list_modified)
    return;

  for (reader = readers; reader; reader = readers) {
    readers = reader->next;
    destroy_reader(reader);
  }

  for (row = 0; row < GTK_CLIST(reader_clist)->rows; ++row)
    {
      gint i;
      i = 0;
      reader = g_new0(Reader, 1);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      gkrellm_dup_string(&reader->label, name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      gkrellm_dup_string(&reader->peer, name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->port = atoi(name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      gkrellm_dup_string(&reader->community, name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      gkrellm_dup_string(&reader->oid_str, name);
      reader->objid_length = MAX_OID_LEN;
      if (!snmp_parse_oid(reader->oid_str,
			  reader->objid, &reader->objid_length)) {
//FIXME:
	  printf("error parsing oid: %s\n", reader->oid_str);
      }

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      gkrellm_dup_string(&reader->unit, name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->delay = atoi(name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->divisor = atoi(name);

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->delta = (strcmp(name, "yes") == 0) ? TRUE : FALSE;

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->scale = (strcmp(name, "yes") == 0) ? TRUE : FALSE;

      gtk_clist_get_text(GTK_CLIST(reader_clist), row, i++, &name);
      reader->active = (strcmp(name, "yes") == 0) ? TRUE : FALSE;

      if (!readers)
          readers = reader;
      else { 
	  for (nreader = readers; nreader->next ; nreader = nreader->next);
	  nreader->next = reader;
      }
      create_reader(main_vbox, reader, 1);
    }
  list_modified = 0;
}
void
netsnmp_parse_override(const char *token, char *line)
{
    char           *cp;
    char            buf[SNMP_MAXBUF], namebuf[SNMP_MAXBUF];
    int             readwrite = 0;
    oid             oidbuf[MAX_OID_LEN];
    size_t          oidbuf_len = MAX_OID_LEN;
    int             type;
    override_data  *thedata;
    netsnmp_handler_registration *the_reg;

    cp = copy_nword(line, namebuf, sizeof(namebuf) - 1);
    if (strcmp(namebuf, "-rw") == 0) {
        readwrite = 1;
        cp = copy_nword(cp, namebuf, sizeof(namebuf) - 1);
    }

    if (!cp) {
        config_perror("no oid specified");
        return;
    }

    if (!snmp_parse_oid(namebuf, oidbuf, &oidbuf_len)) {
        config_perror("illegal oid");
        return;
    }
    cp = copy_nword(cp, buf, sizeof(buf) - 1);

    if (!cp && strcmp(buf, "null") != 0) {
        config_perror("no variable value specified");
        return;
    }

    {
        struct { const char* key; int value; } const strings[] = {
            { "counter", ASN_COUNTER },
            { "counter64", ASN_COUNTER64 },
            { "integer", ASN_INTEGER },
            { "ipaddress", ASN_IPADDRESS },
            { "nsap", ASN_NSAP },
            { "null", ASN_NULL },
            { "object_id", ASN_OBJECT_ID },
            { "octet_str", ASN_OCTET_STR },
            { "opaque", ASN_OPAQUE },
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
            { "opaque_counter64", ASN_OPAQUE_COUNTER64 },
            { "opaque_double", ASN_OPAQUE_DOUBLE },
            { "opaque_float", ASN_OPAQUE_FLOAT },
            { "opaque_i64", ASN_OPAQUE_I64 },
            { "opaque_u64", ASN_OPAQUE_U64 },
#endif
            { "timeticks", ASN_TIMETICKS },
            { "uinteger", ASN_GAUGE },
            { "unsigned", ASN_UNSIGNED },
            { NULL, 0 }
        }, * run;
        for(run = strings; run->key && strcasecmp(run->key, buf) < 0; ++run);
        if(run->key && strcasecmp(run->key, buf) == 0)
            type = run->value;
        else {
            config_perror("unknown type specified");
            return;
        }
    }

    if (cp)
        copy_nword(cp, buf, sizeof(buf) - 1);
    else
        buf[0] = 0;

    thedata = SNMP_MALLOC_TYPEDEF(override_data);
    if (!thedata) {
        config_perror("memory allocation failure");
        return;
    }
    thedata->type = type;

    switch (type) {
    case ASN_INTEGER:
        MALLOC_OR_DIE(sizeof(long));
        *((long *) thedata->value) = strtol(buf, NULL, 0);
        break;

    case ASN_COUNTER:
    case ASN_TIMETICKS:
    case ASN_UNSIGNED:
        MALLOC_OR_DIE(sizeof(u_long));
        *((u_long *) thedata->value) = strtoul(buf, NULL, 0);
        break;

    case ASN_OCTET_STR:
    case ASN_BIT_STR:
        if (buf[0] == '0' && buf[1] == 'x') {
            /*
             * hex 
             */
            thedata->value_len =
                hex_to_binary2((u_char *)(buf + 2), strlen(buf) - 2,
                               (char **) &thedata->value);
        } else {
            thedata->value = strdup(buf);
            thedata->value_len = strlen(buf);
        }
        break;

    case ASN_OBJECT_ID:
        read_config_read_objid(buf, (oid **) & thedata->value,
                               &thedata->value_len);
        break;

    case ASN_NULL:
        thedata->value_len = 0;
        break;

    default:
        SNMP_FREE(thedata);
        config_perror("illegal/unsupported type specified");
        return;
    }

    if (!thedata->value && thedata->type != ASN_NULL) {
        config_perror("memory allocation failure");
        free(thedata);
        return;
    }

    the_reg = SNMP_MALLOC_TYPEDEF(netsnmp_handler_registration);
    if (!the_reg) {
        config_perror("memory allocation failure");
        free(thedata);
        return;
    }

    the_reg->handlerName = strdup(namebuf);
    the_reg->priority = 255;
    the_reg->modes = (readwrite) ? HANDLER_CAN_RWRITE : HANDLER_CAN_RONLY;
    the_reg->handler =
        netsnmp_create_handler("override", override_handler);
    the_reg->rootoid = snmp_duplicate_objid(oidbuf, oidbuf_len);
    the_reg->rootoid_len = oidbuf_len;
    if (!the_reg->rootoid || !the_reg->handler || !the_reg->handlerName) {
        if (the_reg->handler)
            SNMP_FREE(the_reg->handler->handler_name);
        SNMP_FREE(the_reg->handler);
        SNMP_FREE(the_reg->handlerName);
        SNMP_FREE(the_reg);
        config_perror("memory allocation failure");
        free(thedata);
        return;
    }
    the_reg->handler->myvoid = thedata;

    if (netsnmp_register_instance(the_reg)) {
        config_perror("oid registration failed within the agent");
        SNMP_FREE(thedata->value);
        free(thedata);
        return;
    }
}
Beispiel #14
0
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;
}
Beispiel #15
0
/**
 * Get snmp value to the structure my_oid_result array.
 * Author : lining 15810423651 [email protected] 
 * @param peername  : the remote host ip address.
 * @param oid_argvs : the oids pointer array.
 * @param my_oid_result oid_result : the return values. 
 * @return 0 on success, or others on failure.
 * @return 1 on failure, the argument value error.
 * @return 2 on failure, snmp_open return error.
 * @return 3 on failure, snmp_parse_oid return error.
 * @return 4 on failure, snmp_synch_response return status time out.
 * @return 5 on failure, snmp_synch_response return status others.
 */
int my_snmp_get(const char *peername, 
				const char *community, 
				const char *oid_argv, 
				my_oid_result *oid_result) {
	
	netsnmp_session	session;
	netsnmp_session *sess_handle;
	netsnmp_pdu	*pdu;
	netsnmp_pdu	*response;
	netsnmp_variable_list	*vars;
	
	oid oids[MAX_OID_LEN];
    size_t	oids_length;

    int	status;
    int	failures = 0;
	oids_length = 0;
	
	if (peername == NULL) {
		printf("[ERROR] my_snmp_get: the peername pointer is null\n");
		return 1;
	}
	if (community == NULL) {
		printf("[ERROR] my_snmp_get: the community pointer is null\n");
		return 1;
	}
	if (oid_argv == NULL) {
		printf("[ERROR] my_snmp_get: the oid_argv pointer is null\n");
		return 1;
	}
	
	init_snmp("snmpget");
	snmp_sess_init(&session);
	session.version = SNMP_VERSION_2c;
	session.community = (char*)community;
	session.community_len = strlen(session.community);
	session.peername = (char*)peername;
	session.timeout = 3000000;
	session.retries = 1;
	
    SOCK_STARTUP;

    sess_handle = snmp_open(&session);
    if (sess_handle == NULL) {
        SOCK_CLEANUP;
		printf("[ERROR] my_snmp_get: call snmp_open function failed, return sess_handle is null\n");
        return 2;
    }

    pdu = snmp_pdu_create(SNMP_MSG_GET);

	oids_length = MAX_OID_LEN;

	if (!snmp_parse_oid(oid_argv, oids, &oids_length)) {
		snmp_perror(oid_argv);
		failures++;
	} else {
		snmp_add_null_var(pdu, oids, oids_length);
	}
    if (failures) {
        SOCK_CLEANUP;
		printf("[ERROR] my_snmp_get: call snmp_parse_oid function failed\n");
        return 3;
    }
	
    status = snmp_synch_response(sess_handle, pdu, &response);
	
    if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	
		for (vars = response->variables; vars; vars = vars->next_variable) {
			get_oid_value(vars, &oid_result);
		}
		
    } else if (status == STAT_TIMEOUT) {
		printf("[ERROR] my_snmp_get: call snmp_synch_response function failed, return status time out\n");
        return 4;
    } else {
		printf("[ERROR] my_snmp_get: call snmp_synch_response function failed, return status others\n");
        return 5;
    }

    if (response) {
        snmp_free_pdu(response);
	}
    snmp_close(sess_handle);
    SOCK_CLEANUP;
	
    return 0;
}
Beispiel #16
0
/*! \fn char *snmp_getnext(host_t *current_host, char *snmp_oid)
 *  \brief performs a single snmp_getnext for a specific snmp OID
 *
 *	This function will poll a specific snmp OID for a host.  The host snmp
 *  session must already be established.
 *
 *  \return returns the character representaton of the snmp OID, or "U" if
 *  unsuccessful.
 *
 */
char *snmp_getnext(host_t *current_host, char *snmp_oid) {
	struct snmp_pdu *pdu       = NULL;
	struct snmp_pdu *response  = NULL;
	struct variable_list *vars = NULL;
	size_t anOID_len           = MAX_OID_LEN;
	oid    anOID[MAX_OID_LEN];
	int    status;
	char   *result_string;

	if (!(result_string = (char *) malloc(RESULTS_BUFFER))) {
		die("ERROR: Fatal malloc error: snmp.c snmp_get!");
	}
	result_string[0] = '\0';

	status           = STAT_DESCRIP_ERROR;

	if (current_host->snmp_session != NULL) {
		anOID_len = MAX_OID_LEN;
		pdu       = snmp_pdu_create(SNMP_MSG_GETNEXT);

		if (!snmp_parse_oid(snmp_oid, anOID, &anOID_len)) {
			SPINE_LOG(("ERROR: Problems parsing SNMP OID\n"));
			SET_UNDEFINED(result_string);
			return result_string;
		}else{
			snmp_add_null_var(pdu, anOID, anOID_len);
		}

		/* poll host */
		status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response);

		/* liftoff, successful poll, process it!! */
		if (status == STAT_SUCCESS) {
			if (response == NULL) {
				SPINE_LOG(("ERROR: An internal Net-Snmp error condition detected in Cacti snmp_get\n"));

				SET_UNDEFINED(result_string);
				status = STAT_ERROR;
			}else{
				if (response->errstat == SNMP_ERR_NOERROR) {
					vars = response->variables;

					#ifdef USE_NET_SNMP
					snprint_value(result_string, RESULTS_BUFFER, anOID, anOID_len, vars);
					#else
					sprint_value(result_string, anOID, anOID_len, vars);
					#endif
				}
			}
		}

		if (response) {
			snmp_free_pdu(response);
			response = NULL;
		}
	}else{
		status = STAT_DESCRIP_ERROR;
	}

	if (status != STAT_SUCCESS) {
		current_host->ignore_host = TRUE;

		SET_UNDEFINED(result_string);
	}

	return result_string;
}
Beispiel #17
0
/*! \fn char *snmp_get_multi(host_t *current_host, snmp_oids_t *snmp_oids, int num_oids)
 *  \brief performs multiple OID snmp_get's in a single network call
 *
 *	This function will a group of snmp OID's for a host.  The host snmp
 *  session must already be established.  The function will modify elements of
 *  the snmp_oids array with the results from the snmp api call.
 *
 */
void snmp_get_multi(host_t *current_host, snmp_oids_t *snmp_oids, int num_oids) {
	struct snmp_pdu *pdu       = NULL;
	struct snmp_pdu *response  = NULL;
	struct variable_list *vars = NULL;
	int status;
	int i;
	int max_repetitions = 1;
	int non_repeaters   = 0;
	int array_count;
	int index_count;

	/* get rid of some compiler warnings */
	errstat  = 0;
	errindex = 0;

	struct nameStruct {
	    oid             name[MAX_OID_LEN];
	    size_t          name_len;
	} *name, *namep;

	/* load up oids */
	namep = name = (struct nameStruct *) calloc(num_oids, sizeof(*name));
	pdu = snmp_pdu_create(SNMP_MSG_GET);
	for (i = 0; i < num_oids; i++) {
		namep->name_len = MAX_OID_LEN;

		if (!snmp_parse_oid(snmp_oids[i].oid, namep->name, &namep->name_len)) {
 			SPINE_LOG(("Host[%i] ERROR: Problems parsing Multi SNMP OID! (oid: %s)\n", current_host->id, snmp_oids[i].oid));

 			/* Mark this OID as "bad" */
			SET_UNDEFINED(snmp_oids[i].result);
		}else{
			snmp_add_null_var(pdu, namep->name, namep->name_len);
		}

		namep++;
	}

	status = STAT_DESCRIP_ERROR;

	/* execute the multi-get request */
	retry:
	status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response);

	/* liftoff, successful poll, process it!! */
	if (status == STAT_SUCCESS) {
		if (response == NULL) {
			SPINE_LOG(("ERROR: An internal Net-Snmp error condition detected in Cacti snmp_get_multi\n"));
			status = STAT_ERROR;
		}else{
			if (response->errstat == SNMP_ERR_NOERROR) {
				vars = response->variables;

				for(i = 0; i < num_oids && vars; i++) {
					if (!IS_UNDEFINED(snmp_oids[i].result)) {
						#ifdef USE_NET_SNMP
						snmp_snprint_value(snmp_oids[i].result, RESULTS_BUFFER, vars->name, vars->name_length, vars);
						#else
						sprint_value(snmp_oids[i].result, vars->name, vars->name_length, vars);
						#endif

						vars = vars->next_variable;
					}
				}
			}else{
				if (response->errindex != 0) {
					index_count = 1;
					array_count = 0;

					/* Find our index against errindex */
					while (array_count < num_oids) {
						if (IS_UNDEFINED(snmp_oids[array_count].result) ) {
							array_count++;
						}else{
							/* if we have found our error, exit */
							if (index_count == response->errindex) {
								SET_UNDEFINED(snmp_oids[array_count].result);

								break;
							}
							array_count++;
							index_count++;
						}

					}

					/* remote the invalid OID from the PDU */
					pdu = snmp_fix_pdu(response, SNMP_MSG_GET);

					/* free the previous response */
					snmp_free_pdu(response);

					response = NULL;
					if (pdu != NULL) {
						/* retry the request */
						goto retry;
					}else{
					    /* all OID's errored out so exit cleanly */
						status = STAT_SUCCESS;
					}
				}else{
					status = STAT_DESCRIP_ERROR;
				}
			}
		}
	}

	if (status != STAT_SUCCESS) {
		current_host->ignore_host = 1;
		for (i = 0; i < num_oids; i++) {
			SET_UNDEFINED(snmp_oids[i].result);
		}
	}

	if (response != NULL) {
		snmp_free_pdu(response);
	}
}
void
parse_expression(const char *token, char *line)
{
    char   buf[ SPRINT_MAX_LEN];
    char   ename[EXP_STR1_LEN+1];
    oid    name_buf[MAX_OID_LEN];
    size_t name_len;
    char *cp, *cp2;
    struct expExpression *entry;
    struct expObject     *object;
    netsnmp_session *sess = NULL;
    int    type=EXPVALTYPE_COUNTER;
    int    i=1;

    DEBUGMSGTL(("disman:expr:conf", "Parsing expression config...  "));

    memset(buf,   0, sizeof(buf));
    memset(ename, 0, sizeof(ename));

    for (cp = copy_nword(line, buf, SPRINT_MAX_LEN);
         ;
         cp = copy_nword(cp,   buf, SPRINT_MAX_LEN)) {

        if (buf[0] == '-' ) {
            switch (buf[1]) {
            case 't':   /*  type */
                switch (buf[2]) {
                case 'c':   type = EXPVALTYPE_COUNTER;   break;
                case 'u':   type = EXPVALTYPE_UNSIGNED;  break;
                case 't':   type = EXPVALTYPE_TIMETICKS; break;
                case 'i':   type = EXPVALTYPE_INTEGER;   break;
                case 'a':   type = EXPVALTYPE_IPADDRESS; break;
                case 's':   type = EXPVALTYPE_STRING;    break;
                case 'o':   type = EXPVALTYPE_OID;       break;
                case 'C':   type = EXPVALTYPE_COUNTER64; break;
                }
                break;
            case 'u':   /*  user */
                cp     = copy_nword(cp, buf, SPRINT_MAX_LEN);
                sess   = netsnmp_iquery_user_session(buf);
                break;
            }
        } else {
            break;
        }
    }

    memcpy(ename, buf, sizeof(ename));
 /* cp    = copy_nword(line, ename, sizeof(ename)); */
    entry = expExpression_createEntry( "snmpd.conf", ename, 1 );
    if (!entry)
        return;

    cp2 = entry->expExpression;
    while (cp && *cp) {
        /*
         * Copy everything that can't possibly be a MIB
         * object name into the expression field...
         */
        /*   XXX - TODO - Handle string literals */
        if (!isalpha(*cp)) {
           *cp2++ = *cp++;
           continue;
        }
        /*
         * ... and copy the defined functions across as well
         *   XXX - TODO
         */

        /*
         * Anything else is presumably a MIB object (or instance).
         * Create an entry in the expObjectTable, and insert a
         *   corresponding parameter in the expression itself.
         */
        name_len = MAX_OID_LEN;
        cp = copy_nword(cp, buf, SPRINT_MAX_LEN);
        snmp_parse_oid( buf, name_buf, &name_len );
        object = expObject_createEntry( "snmpd.conf", ename, i, 1 );
        memcpy( object->expObjectID, name_buf, name_len*sizeof(oid));
        object->expObjectID_len = name_len;
        object->flags |= EXP_OBJ_FLAG_VALID
                      |  EXP_OBJ_FLAG_ACTIVE
                      |  EXP_OBJ_FLAG_OWILD;
        /*
         * The first such object can also be used as the
         * expExpressionPrefix
         */
        if ( i == 1 ) {
            memcpy( entry->expPrefix, name_buf, name_len*sizeof(oid));
            entry->expPrefix_len = name_len;
            object->flags |= EXP_OBJ_FLAG_PREFIX;
        }
        sprintf(cp2, "$%d", i++);
        while (*cp2)
            cp2++;  /* Skip over this parameter */
    }

    if (sess)
        entry->session      = sess;
    else
        entry->session      = netsnmp_query_get_default_session();
    entry->expDeltaInterval = 10;
    entry->expValueType     = type;
    entry->flags |= EXP_FLAG_VALID
                 |  EXP_FLAG_ACTIVE;
    expExpression_enable( entry );
    DEBUGMSG(("disman:expr:conf", "(%s, %s)\n", ename,
                                                entry->expExpression));
}
Beispiel #19
0
void
parse_setEvent( const char *token, char *line )
{
    char   ename[MTE_STR1_LEN+1];
    char   buf[SPRINT_MAX_LEN];
    oid    name_buf[MAX_OID_LEN];
    size_t name_buf_len;
    long   value;
    int    wild = 1;
    struct mteEvent  *entry;
    char  *cp;

    DEBUGMSGTL(("disman:event:conf", "Parsing setEvent config...  "));

    memset( ename, 0, sizeof(ename));
    cp = copy_nword(line, ename,  MTE_STR1_LEN);
    if (!cp || ename[0] == '\0') {
        config_perror("syntax error: no event name");
        return;
    }

    if (cp && *cp=='-' && *(cp+1)=='I') {
        wild = 0;               /* an instance assignment */
        cp = skip_token( cp );
    }

    /*
     *  Parse the SET assignment in the form "OID = value"
     */
    cp = copy_nword(cp, buf,  SPRINT_MAX_LEN);
    if ( buf[0] == '\0' ) {
        config_perror("syntax error: no set OID");
        return;
    }
    name_buf_len = MAX_OID_LEN;
    if (!snmp_parse_oid(buf, name_buf, &name_buf_len)) {
        snmp_log(LOG_ERR, "setEvent OID: %s\n", buf);
        config_perror("unknown set OID");
        return;
    }
    if (cp && *cp == '=') {
        cp = skip_token( cp );   /* skip the '=' assignment character */
    }
    value = strtol( cp, NULL, 0);

    /*
     *  If the entry has parsed successfully, then create,
     *     populate and activate the new event entry.
     */
    entry = _find_typed_mteEvent_entry("snmpd.conf", ename, MTE_EVENT_SET);
    if (!entry) {
        return;
    }
    memcpy( entry->mteSetOID, name_buf, name_buf_len*sizeof(oid));
    entry->mteSetOID_len = name_buf_len;
    entry->mteSetValue   = value;
    if (wild)
        entry->flags       |= MTE_SET_FLAG_OBJWILD;
    entry->mteEventActions |= MTE_EVENT_SET;
    entry->flags           |= MTE_EVENT_FLAG_ENABLED |
                              MTE_EVENT_FLAG_ACTIVE  |
                              MTE_EVENT_FLAG_FIXED   |
                              MTE_EVENT_FLAG_VALID;
    return;
}
Beispiel #20
0
void
parse_notificationEvent( const char *token, char *line )
{
    char   ename[MTE_STR1_LEN+1];
    char   buf[SPRINT_MAX_LEN];
    oid    name_buf[MAX_OID_LEN];
    size_t name_buf_len;
    struct mteEvent  *entry;
    struct mteObject *object;
    int    wild = 1;
    int    idx  = 0;
    char  *cp;
#ifndef NETSNMP_DISABLE_MIB_LOADING
    struct tree         *tp;
#endif
    struct varbind_list *var;

    DEBUGMSGTL(("disman:event:conf", "Parsing notificationEvent config\n"));

    /*
     * The event name could be used directly to index the mteObjectsTable.
     * But it's quite possible that the same name could also be used to
     * set up a mteTriggerTable entry (with trigger-specific objects).
     *
     * To avoid such a clash, we'll add a prefix ("_E").
     */
    memset(ename, 0, sizeof(ename));
    ename[0] = '_';
    ename[1] = 'E';
    cp = copy_nword(line, ename+2,  MTE_STR1_LEN-2);
    if (!cp || ename[2] == '\0') {
        config_perror("syntax error: no event name");
        return;
    }
    
    /*
     *  Parse the notification OID field ...
     */
    cp = copy_nword(cp, buf,  SPRINT_MAX_LEN);
    if ( buf[0] == '\0' ) {
        config_perror("syntax error: no notification OID");
        return;
    }
    name_buf_len = MAX_OID_LEN;
    if (!snmp_parse_oid(buf, name_buf, &name_buf_len)) {
        snmp_log(LOG_ERR, "notificationEvent OID: %s\n", buf);
        config_perror("unknown notification OID");
        return;
    }

    /*
     *  ... and the relevant object/instances.
     */
    if ( cp && *cp=='-' && *(cp+1)=='m' ) {
#ifdef NETSNMP_DISABLE_MIB_LOADING
        config_perror("Can't use -m if MIB loading is disabled");
        return;
#else
        /*
         * Use the MIB definition to add the standard
         *   notification payload to the mteObjectsTable.
         */
        cp = skip_token( cp );
        tp = get_tree( name_buf, name_buf_len, get_tree_head());
        if (!tp) {
            config_perror("Can't locate notification payload info");
            return;
        }
        for (var = tp->varbinds; var; var=var->next) {
            idx++;
            object = mteObjects_addOID( "snmpd.conf", ename, idx,
                                         var->vblabel, wild );
            idx    = object->mteOIndex;
        }
#endif
    }
    while (cp) {
        if ( *cp == '-' ) {
            switch (*(cp+1)) {
            case 'm':
                config_perror("-m option must come first");
                return;
            case 'i':   /* exact instance */
            case 'w':   /* "not-wild" (backward compatability) */
                wild = 0;
                break;
            case 'o':   /* wildcarded object  */
                wild = 1;
                break;
            default:
                config_perror("unrecognised option");
                return;
            }
            cp = skip_token( cp );
            if (!cp) {
                config_perror("missing parameter");
                return;
            }
        }
        idx++;
        cp     = copy_nword(cp, buf,  SPRINT_MAX_LEN);
        object = mteObjects_addOID( "snmpd.conf", ename, idx, buf, wild );
        idx    = object->mteOIndex;
        wild   = 1;    /* default to wildcarded objects */
    }

    /*
     *  If the entry has parsed successfully, then create,
     *     populate and activate the new event entry.
     */
    entry = _find_typed_mteEvent_entry("snmpd.conf", ename+2,
                                       MTE_EVENT_NOTIFICATION);
    if (!entry) {
        mteObjects_removeEntries( "snmpd.conf", ename );
        return;
    }
    entry->mteNotification_len = name_buf_len;
    memcpy( entry->mteNotification, name_buf, name_buf_len*sizeof(oid));
    memcpy( entry->mteNotifyOwner,  "snmpd.conf",  10 );
    memcpy( entry->mteNotifyObjects, ename, MTE_STR1_LEN );
    entry->mteEventActions |= MTE_EVENT_NOTIFICATION;
    entry->flags           |= MTE_EVENT_FLAG_ENABLED |
                              MTE_EVENT_FLAG_ACTIVE  |
                              MTE_EVENT_FLAG_FIXED   |
                              MTE_EVENT_FLAG_VALID;
    return;
}
Beispiel #21
0
int main (int argc, char *argv[])
{
    netsnmp_session session, *ss;

    netsnmp_pdu *pdu, *response;

    oid name[MAX_OID_LEN];

    size_t name_length;

    int arg;

    int status;

    char *trap = NULL;

    char *prognam;

    int exitval = 0;

#ifndef NETSNMP_DISABLE_SNMPV1
    char *specific = NULL, *description = NULL, *agent = NULL;

    in_addr_t *pdu_in_addr_t;
#endif

    prognam = strrchr (argv[0], '/');
    if (prognam)
        prognam++;
    else
        prognam = argv[0];

    putenv (strdup ("POSIXLY_CORRECT=1"));

    if (strcmp (prognam, "snmpinform") == 0)
        inform = 1;
    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;
    }

    SOCK_STARTUP;

    session.callback = snmp_input;
    session.callback_magic = NULL;

    /*
     * setup the local engineID which may be for either or both of the
     * contextEngineID and/or the securityEngineID.
     */
    setup_engineID (NULL, NULL);

    /* if we don't have a contextEngineID set via command line
       arguments, use our internal engineID as the context. */
    if (session.contextEngineIDLen == 0 || session.contextEngineID == NULL)
    {
        session.contextEngineID = snmpv3_generate_engineID (&session.contextEngineIDLen);
    }

    if (session.version == SNMP_VERSION_3 && !inform)
    {
        /*
         * for traps, we use ourselves as the authoritative engine
         * which is really stupid since command line apps don't have a
         * notion of a persistent engine.  Hence, our boots and time
         * values are probably always really wacked with respect to what
         * a manager would like to see.
         * 
         * The following should be enough to:
         * 
         * 1) prevent the library from doing discovery for engineid & time.
         * 2) use our engineid instead of the remote engineid for
         * authoritative & privacy related operations.
         * 3) The remote engine must be configured with users for our engineID.
         * 
         * -- Wes 
         */

        /*
         * pick our own engineID 
         */
        if (session.securityEngineIDLen == 0 || session.securityEngineID == NULL)
        {
            session.securityEngineID = snmpv3_generate_engineID (&session.securityEngineIDLen);
        }

        /*
         * set boots and time, which will cause problems if this
         * machine ever reboots and a remote trap receiver has cached our
         * boots and time...  I'll cause a not-in-time-window report to
         * be sent back to this machine. 
         */
        if (session.engineBoots == 0)
            session.engineBoots = 1;
        if (session.engineTime == 0)    /* not really correct, */
            session.engineTime = get_uptime ();    /* but it'll work. Sort of. */
    }

    ss = snmp_add (&session, netsnmp_transport_open_client ("snmptrap", session.peername), NULL, NULL);
    if (ss == NULL)
    {
        /*
         * diagnose netsnmp_transport_open_client and snmp_add errors with
         * the input netsnmp_session pointer
         */
        snmp_sess_perror ("snmptrap", &session);
        SOCK_CLEANUP;
        exit (1);
    }

#ifndef NETSNMP_DISABLE_SNMPV1
    if (session.version == SNMP_VERSION_1)
    {
        if (inform)
        {
            fprintf (stderr, "Cannot send INFORM as SNMPv1 PDU\n");
            SOCK_CLEANUP;
            exit (1);
        }
        pdu = snmp_pdu_create (SNMP_MSG_TRAP);
        if (!pdu)
        {
            fprintf (stderr, "Failed to create trap PDU\n");
            SOCK_CLEANUP;
            exit (1);
        }
        pdu_in_addr_t = (in_addr_t *) pdu->agent_addr;
        if (arg == argc)
        {
            fprintf (stderr, "No enterprise oid\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        if (argv[arg][0] == 0)
        {
            pdu->enterprise = (oid *) malloc (sizeof (objid_enterprise));
            memcpy (pdu->enterprise, objid_enterprise, sizeof (objid_enterprise));
            pdu->enterprise_length = sizeof (objid_enterprise) / sizeof (oid);
        }
        else
        {
            name_length = MAX_OID_LEN;
            if (!snmp_parse_oid (argv[arg], name, &name_length))
            {
                snmp_perror (argv[arg]);
                usage ();
                SOCK_CLEANUP;
                exit (1);
            }
            pdu->enterprise = (oid *) malloc (name_length * sizeof (oid));
            memcpy (pdu->enterprise, name, name_length * sizeof (oid));
            pdu->enterprise_length = name_length;
        }
        if (++arg >= argc)
        {
            fprintf (stderr, "Missing agent parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        agent = argv[arg];
        if (agent != NULL && strlen (agent) != 0)
        {
            int ret = netsnmp_gethostbyname_v4 (agent, pdu_in_addr_t);

            if (ret < 0)
            {
                fprintf (stderr, "unknown host: %s\n", agent);
                exit (1);
            }
        }
        else
        {
            *pdu_in_addr_t = get_myaddr ();
        }
        if (++arg == argc)
        {
            fprintf (stderr, "Missing generic-trap parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        trap = argv[arg];
        pdu->trap_type = atoi (trap);
        if (++arg == argc)
        {
            fprintf (stderr, "Missing specific-trap parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        specific = argv[arg];
        pdu->specific_type = atoi (specific);
        if (++arg == argc)
        {
            fprintf (stderr, "Missing uptime parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        description = argv[arg];
        if (description == NULL || *description == 0)
            pdu->time = get_uptime ();
        else
            pdu->time = atol (description);
    }
    else
#endif
    {
        long sysuptime;

        char csysuptime[20];

        pdu = snmp_pdu_create (inform ? SNMP_MSG_INFORM : SNMP_MSG_TRAP2);
        if (!pdu)
        {
            fprintf (stderr, "Failed to create notification PDU\n");
            SOCK_CLEANUP;
            exit (1);
        }
        if (arg == argc)
        {
            fprintf (stderr, "Missing up-time parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        trap = argv[arg];
        if (*trap == 0)
        {
            sysuptime = get_uptime ();
            sprintf (csysuptime, "%ld", sysuptime);
            trap = csysuptime;
        }
        snmp_add_var (pdu, objid_sysuptime, sizeof (objid_sysuptime) / sizeof (oid), 't', trap);
        if (++arg == argc)
        {
            fprintf (stderr, "Missing trap-oid parameter\n");
            usage ();
            SOCK_CLEANUP;
            exit (1);
        }
        if (snmp_add_var (pdu, objid_snmptrap, sizeof (objid_snmptrap) / sizeof (oid), 'o', argv[arg]) != 0)
        {
            snmp_perror (argv[arg]);
            SOCK_CLEANUP;
            exit (1);
        }
    }
    arg++;

    while (arg < argc)
    {
        arg += 3;
        if (arg > argc)
        {
            fprintf (stderr, "%s: Missing type/value for variable\n", argv[arg - 3]);
            SOCK_CLEANUP;
            exit (1);
        }
        name_length = MAX_OID_LEN;
        if (!snmp_parse_oid (argv[arg - 3], name, &name_length))
        {
            snmp_perror (argv[arg - 3]);
            SOCK_CLEANUP;
            exit (1);
        }
        if (snmp_add_var (pdu, name, name_length, argv[arg - 2][0], argv[arg - 1]) != 0)
        {
            snmp_perror (argv[arg - 3]);
            SOCK_CLEANUP;
            exit (1);
        }
    }

    if (inform)
        status = snmp_synch_response (ss, pdu, &response);
    else
        status = snmp_send (ss, pdu) == 0;
    if (status)
    {
        snmp_sess_perror (inform ? "snmpinform" : "snmptrap", ss);
        if (!inform)
            snmp_free_pdu (pdu);
        exitval = 1;
    }
    else if (inform)
        snmp_free_pdu (response);

    snmp_close (ss);
    snmp_shutdown ("snmpapp");
    SOCK_CLEANUP;
    return exitval;
}
Beispiel #22
0
static rsRetVal omsnmp_sendsnmp(wrkrInstanceData_t *pWrkrData, uchar *psz)
{
	DEFiRet;

	netsnmp_pdu    *pdu = NULL;
	oid             enterpriseoid[MAX_OID_LEN];
	size_t          enterpriseoidlen = MAX_OID_LEN;
	oid				oidSyslogMessage[MAX_OID_LEN];
	size_t			oLen = MAX_OID_LEN;
	int             status;
	char            *trap = NULL;
	const char		*strErr = NULL;
	instanceData *pData;

	pData = pWrkrData->pData;
	/* Init SNMP Session if necessary */
	if (pWrkrData->snmpsession == NULL) {
		CHKiRet(omsnmp_initSession(pWrkrData));
	}
	
	/* String should not be NULL */
	ASSERT(psz != NULL);
	dbgprintf( "omsnmp_sendsnmp: ENTER - Syslogmessage = '%s'\n", (char*)psz);

	/* If SNMP Version1 is configured !*/
	if(pWrkrData->snmpsession->version == SNMP_VERSION_1) {
		pdu = snmp_pdu_create(SNMP_MSG_TRAP);

		/* Set enterprise */
		if(!snmp_parse_oid(pData->szEnterpriseOID == NULL ? "1.3.6.1.4.1.3.1.1" : (char*)pData->szEnterpriseOID,
				   enterpriseoid, &enterpriseoidlen )) {
			strErr = snmp_api_errstring(snmp_errno);
			errmsg.LogError(0, RS_RET_DISABLE_ACTION, "omsnmp_sendsnmp: Parsing EnterpriseOID "
					"failed '%s' with error '%s' \n", pData->szSyslogMessageOID, strErr);
			ABORT_FINALIZE(RS_RET_DISABLE_ACTION);
		}
		pdu->enterprise = (oid *) MALLOC(enterpriseoidlen * sizeof(oid));
		memcpy(pdu->enterprise, enterpriseoid, enterpriseoidlen * sizeof(oid));
		pdu->enterprise_length = enterpriseoidlen;

		/* Set Traptype */
		pdu->trap_type = pData->iTrapType; 
		
		/* Set SpecificType */
		pdu->specific_type = pData->iSpecificType;

		/* Set Updtime */
		pdu->time = get_uptime();
	}
	/* If SNMP Version2c is configured !*/
	else if (pWrkrData->snmpsession->version == SNMP_VERSION_2c) 
	{
		long sysuptime;
		char csysuptime[20];
		
		/* Create PDU */
		pdu = snmp_pdu_create(SNMP_MSG_TRAP2);
		
		/* Set uptime */
		sysuptime = get_uptime();
		snprintf( csysuptime, sizeof(csysuptime) , "%ld", sysuptime);
		trap = csysuptime;
		snmp_add_var(pdu, objid_sysuptime, sizeof(objid_sysuptime) / sizeof(oid), 't', trap);

		/* Now set the SyslogMessage Trap OID */
		if ( snmp_add_var(pdu, objid_snmptrap, sizeof(objid_snmptrap) / sizeof(oid), 'o',
			pData->szSnmpTrapOID == NULL ?  "1.3.6.1.4.1.19406.1.2.1" : (char*) pData->szSnmpTrapOID
			) != 0) {
			strErr = snmp_api_errstring(snmp_errno);
			errmsg.LogError(0, RS_RET_DISABLE_ACTION, "omsnmp_sendsnmp: Adding trap OID failed '%s' with error '%s' \n", pData->szSnmpTrapOID, strErr);
			ABORT_FINALIZE(RS_RET_DISABLE_ACTION);
		}
	}

	/* SET TRAP PARAMETER for SyslogMessage! */
/*	dbgprintf( "omsnmp_sendsnmp: SyslogMessage '%s'\n", psz );*/

	/* First create new OID object */
	if (snmp_parse_oid(pData->szSyslogMessageOID == NULL ?
			    "1.3.6.1.4.1.19406.1.1.2.1" : (char*)pData->szSyslogMessageOID,
				oidSyslogMessage, &oLen)) {
		int iErrCode = snmp_add_var(pdu, oidSyslogMessage, oLen, 's', (char*) psz);
		if (iErrCode) {
			const char *str = snmp_api_errstring(iErrCode);
			errmsg.LogError(0, RS_RET_DISABLE_ACTION,  "omsnmp_sendsnmp: Invalid SyslogMessage OID, error code '%d' - '%s'\n", iErrCode, str );
			ABORT_FINALIZE(RS_RET_DISABLE_ACTION);
		}
	} else {
		strErr = snmp_api_errstring(snmp_errno);
		errmsg.LogError(0, RS_RET_DISABLE_ACTION, "omsnmp_sendsnmp: Parsing SyslogMessageOID failed '%s' with error '%s' \n", pData->szSyslogMessageOID, strErr);

		ABORT_FINALIZE(RS_RET_DISABLE_ACTION);
	}

	/* Send the TRAP */
	status = snmp_send(pWrkrData->snmpsession, pdu) == 0;
	if (status)
	{
		/* Debug Output! */
		int iErrorCode = pWrkrData->snmpsession->s_snmp_errno;
		errmsg.LogError(0, RS_RET_SUSPENDED,  "omsnmp_sendsnmp: snmp_send failed error '%d', Description='%s'\n", iErrorCode*(-1), api_errors[iErrorCode*(-1)]);

		/* Clear Session */
		omsnmp_exitSession(pWrkrData);

		ABORT_FINALIZE(RS_RET_SUSPENDED);
	}

finalize_it:
	if(iRet != RS_RET_OK) {
		if(pdu != NULL) {
			snmp_free_pdu(pdu);
		}
	}

	dbgprintf( "omsnmp_sendsnmp: LEAVE\n");
	RETiRet;
}
Beispiel #23
0
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;
}
static void
load_plugin_config(gchar *config_line)
{
  Reader *reader, *nreader = NULL;

  gchar   proto[CFG_BUFSIZE], bufl[CFG_BUFSIZE];
  gchar   bufc[CFG_BUFSIZE], bufp[CFG_BUFSIZE];
  gchar   bufo[CFG_BUFSIZE], bufu[CFG_BUFSIZE];
  gchar   buft[CFG_BUFSIZE], peer[CFG_BUFSIZE];
  gint    n;

  if (sscanf(config_line, GKRELLM_CHARTCONFIG_KEYWORD " %s %[^\n]", bufl, bufc) == 2) {
	g_strdelimit(bufl, "_", ' ');
	/* look for any such reader */
	for (reader = readers; reader ; reader = reader->next) {
		if (!strcmp(reader->label, bufl)) {
			nreader = reader;
			break;
		}
	}
	/* look for unconf'd reader */
	for (reader = readers; reader ; reader = reader->next) {
		if (!strcmp(reader->label, bufl) && !reader->chart_config) {
			nreader = reader;
			break;
		}
	}
	if (!nreader) {/* well... */
		fprintf(stderr, "chart_config appeared before chart, this isn't handled\n%s\n", config_line);
		return;
	}
	//"chart_config in "
	gkrellm_load_chartconfig(&nreader->chart_config, bufc, /*max_cd*/1);
  	return;
  }
  
  reader = g_new0(Reader, 1); 

  n = sscanf(config_line, "%s %[^:]://%[^@]@%[^:]:%[^:]:%d/%s %s %d %d %d %d",
	     bufl, proto, bufc, buft, bufp, &reader->port, bufo, bufu,
	     &reader->delay, &reader->delta,
	     &reader->divisor, &reader->scale);
  if (n >= 6) {
	g_snprintf(peer, CFG_BUFSIZE, "%s:%s", buft, bufp);
	peer[CFG_BUFSIZE-1] = '\0';
  } else
	  n = sscanf(config_line, "%s %[^:]://%[^@]@%[^:]:%d/%s %s %d %d %d %d",
	     bufl, proto, bufc, peer, &reader->port, bufo, bufu,
	     &reader->delay, &reader->delta,
	     &reader->divisor, &reader->scale);
  if (n >= 7)
    {
      if (g_strcasecmp(proto, "snmp") == 0) {
	gkrellm_dup_string(&reader->label, bufl);
	gkrellm_dup_string(&reader->community, bufc);
	gkrellm_dup_string(&reader->peer, peer);
	if (reader->delay < 10)
	    reader->delay = 100;
	if (reader->divisor == 0)
	    reader->divisor = 1;

	gkrellm_dup_string(&reader->oid_str, bufo);

	reader->objid_length = MAX_OID_LEN;
	if (!snmp_parse_oid(reader->oid_str,
			    reader->objid, &reader->objid_length)) {
//FIXME:
	    printf("error parsing oid: %s\n", reader->oid_str);
	}

	if (n > 7) {
	    gkrellm_dup_string(&reader->unit, bufu);
	} else {
	    gkrellm_dup_string(&reader->unit, "");
	}

	g_strdelimit(reader->label, "_", ' ');
	g_strdelimit(reader->unit, "_", ' ');

	// reader->old_sample = "SNMP"; // be nice.
      }

      if (!readers)
	  readers = reader;
      else { 
 	  for (nreader = readers; nreader->next ; nreader = nreader->next);
	  nreader->next = reader;
      }

    }
}
void
parse_notificationEvent(const char *token, char *line) {
    char            name_buf[64];
    char            oid_name_buf[SPRINT_MAX_LEN];
    oid             oid_buf[MAX_OID_LEN];
    size_t          oid_buf_len = MAX_OID_LEN;
    int             wild = 1;
    netsnmp_table_row *row;
    long tlong;
    char tc;

    /* get the owner */
    const char *owner = "snmpd.conf";

    /* get the name */
    char *cp = copy_nword(line, name_buf, SPRINT_MAX_LEN);

    if (!cp || name_buf[0] == '\0') {
        config_perror("syntax error.");
        return;
    }

    for(row = table_set->table->first_row; row; row = row->next) {
        if (strcmp(row->indexes->val.string, owner) == 0 &&
            strcmp(row->indexes->next_variable->val.string,
                   name_buf) == 0) {
            config_perror("An eventd by that name has already been defined.");
            return;
        }
    }

    /* now, get all the trap oid */
    cp = copy_nword(cp, oid_name_buf, SPRINT_MAX_LEN);

    if (oid_name_buf[0] == '\0') {
        config_perror("syntax error.");
        return;
    }
    if (!snmp_parse_oid(oid_name_buf, oid_buf, &oid_buf_len)) {
        snmp_log(LOG_ERR,"namebuf: %s\n",oid_name_buf);
        config_perror("unable to parse trap oid");
        return;
    }

    /*
     * add to the mteEventNotificationtable to point to the
     * notification and the objects.
     */
    row = netsnmp_create_table_data_row();

    /* indexes */
    netsnmp_table_row_add_index(row, ASN_OCTET_STR, owner, strlen(owner));
    netsnmp_table_row_add_index(row, ASN_PRIV_IMPLIED_OCTET_STR,
                                name_buf, strlen(name_buf));


    /* columns */
    netsnmp_set_row_column(row, COLUMN_MTEEVENTNOTIFICATION, ASN_OBJECT_ID,
                           (char *) oid_buf, oid_buf_len * sizeof(oid));
    netsnmp_set_row_column(row, COLUMN_MTEEVENTNOTIFICATIONOBJECTSOWNER,
                           ASN_OCTET_STR, owner, strlen(owner));
    netsnmp_set_row_column(row, COLUMN_MTEEVENTNOTIFICATIONOBJECTS,
                           ASN_OCTET_STR, name_buf, strlen(name_buf));

    netsnmp_table_data_add_row(mteEventNotif_table_set->table, row);

    /*
     * add to the mteEventTable to make it a notification to trigger
     * notification and the objects.
     */
    row = netsnmp_create_table_data_row();

    /* indexes */
    netsnmp_table_row_add_index(row, ASN_OCTET_STR, owner, strlen(owner));
    netsnmp_table_row_add_index(row, ASN_PRIV_IMPLIED_OCTET_STR,
                                name_buf, strlen(name_buf));


    /* columns */
    tc = (u_char)0x80;
    netsnmp_set_row_column(row, COLUMN_MTEEVENTACTIONS, ASN_OCTET_STR,
                           &tc, 1);
    tlong = MTETRIGGERENABLED_TRUE;
    netsnmp_set_row_column(row, COLUMN_MTEEVENTENABLED,
                           ASN_INTEGER, (char *) &tlong, sizeof(tlong));
    tlong = RS_ACTIVE;
    netsnmp_set_row_column(row, COLUMN_MTEEVENTENTRYSTATUS,
                           ASN_INTEGER, (char *) &tlong, sizeof(tlong));

    netsnmp_table_data_add_row(table_set->table, row);
    
    /*
     * now all the objects to put into the trap's object row
     */
    while(cp) {
        cp = copy_nword(cp, oid_name_buf, SPRINT_MAX_LEN);
        if (strcmp(oid_name_buf, "-w") == 0) {
            wild = 0;
            continue;
        }
        oid_buf_len = MAX_OID_LEN;
        if (!snmp_parse_oid(oid_name_buf, oid_buf, &oid_buf_len)) {
            config_perror("unable to parse an object oid");
            return;
        }
        mte_add_object_to_table("snmpd.conf", name_buf,
                                oid_buf, oid_buf_len, wild);
        wild = 1;
    }
}
gchar *
snmp_probe(gchar *peer, gint port, gchar *community)
{
    oid sysDescr[MAX_OID_LEN];
    size_t sysDescr_length;
    oid sysObjectID[MAX_OID_LEN];
    size_t sysObjectID_length;
    oid sysUpTime[MAX_OID_LEN];
    size_t sysUpTime_length;
    oid sysContact[MAX_OID_LEN];
    size_t sysContact_length;
    oid sysName[MAX_OID_LEN];
    size_t sysName_length;
    oid sysLocation[MAX_OID_LEN];
    size_t sysLocation_length;

    struct snmp_session session, *ss;
    struct snmp_pdu *pdu, *response;
    struct variable_list *vars;

    int count;
    int status;

    char textbuf[1024]; 
    char *result = NULL;
    char *tmp = NULL;

    /* transform interesting OIDs */
    sysDescr_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysDescr.0", sysDescr, &sysDescr_length))
	    printf("error parsing oid: system.sysDescr.0\n");

    sysObjectID_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysObjectID.0", sysObjectID, &sysObjectID_length))
	    printf("error parsing oid: system.sysObjectID.0\n");

    sysUpTime_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysUpTime.0", sysUpTime, &sysUpTime_length))
	    printf("error parsing oid: system.sysUpTime.0\n");

    sysContact_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysContact.0", sysContact, &sysContact_length))
	    printf("error parsing oid: system.sysContact.0\n");

    sysName_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysName.0", sysName, &sysName_length))
	    printf("error parsing oid: system.sysName.0\n");

    sysLocation_length = MAX_OID_LEN;
    if (!snmp_parse_oid("system.sysLocation.0", sysLocation, &sysLocation_length))
	    printf("error parsing oid: system.sysLocation.0\n");

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

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

#ifdef STREAM
    session.flags |= SNMP_FLAGS_STREAM_SOCKET;
    fprintf (stderr, "local port set to: %d\n", session.local_port);
#endif

    /* 
     * Open an SNMP session.
     */
    ss = snmp_open(&session);
    if (ss == NULL){
      fprintf (stderr, "local port set to: %d\n", session.local_port);
      snmp_sess_perror("snmp_open", &session);
      exit(1);
    }

    /* 
     * Create PDU for GET request and add object names to request.
     */
    pdu = snmp_pdu_create(SNMP_MSG_GET);

    snmp_add_null_var(pdu, sysDescr, sysDescr_length);
    snmp_add_null_var(pdu, sysObjectID, sysObjectID_length);
    snmp_add_null_var(pdu, sysUpTime, sysUpTime_length);
    snmp_add_null_var(pdu, sysContact, sysContact_length);
    snmp_add_null_var(pdu, sysName, sysName_length);
    snmp_add_null_var(pdu, sysLocation, sysLocation_length);

    /* 
     * 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){
        /* just render all vars */
        for(vars = response->variables; vars; vars = vars->next_variable) {
	    snprint_variable(textbuf, 1023, vars->name, vars->name_length, vars);
	    textbuf[1023] = '\0';
	    if (result) {
	        tmp = result;
		result = g_strdup_printf("%s\n%s\n", tmp, textbuf);
		g_free(tmp);
	    } else {
		result = g_strdup_printf("%s\n", textbuf);
	    }
	}
                              
      } else {
        fprintf(stderr, "Error in packet\nReason: %s\n",
                snmp_errstring(response->errstat));

        if (response->errstat == SNMP_ERR_NOSUCHNAME){
          fprintf(stderr, "This name doesn't exist: ");
          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");
        }

        /* retry if the errored variable was successfully removed */
        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){
        snmp_close(ss);
        return g_strdup_printf("Timeout: No Response from %s.\n", session.peername);

    } else {    /* status == STAT_ERROR */
      fprintf (stderr, "local port set to: %d\n", session.local_port);
      snmp_sess_perror("STAT_ERROR", ss);
      snmp_close(ss);
      return NULL;

    }  /* endif -- STAT_SUCCESS */

    if (response)
      snmp_free_pdu(response);
    snmp_close(ss);

    return result;
}
Beispiel #27
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;
}
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;
}
Beispiel #29
0
void
proxy_parse_config(const char *token, char *line)
{
    /*
     * proxy args [base-oid] [remap-to-remote-oid] 
     */

    netsnmp_session session, *ss;
    struct simple_proxy *newp, **listpp;
    char            args[MAX_ARGS][SPRINT_MAX_LEN], *argv[MAX_ARGS];
    int             argn, arg;
    char           *cp;
    netsnmp_handler_registration *reg;

    context_string = NULL;

    DEBUGMSGTL(("proxy_config", "entering\n"));

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

    for (arg = 0; arg < argn; arg++) {
        DEBUGMSGTL(("proxy_args", "final args: %d = %s\n", arg,
                    argv[arg]));
    }

    DEBUGMSGTL(("proxy_config", "parsing args: %d\n", argn));
    /* Call special parse_args that allows for no specified community string */
    arg = snmp_parse_args(argn, argv, &session, "C:", proxyOptProc);

    /* reset this in case we modified it */
    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
                           NETSNMP_DS_LIB_IGNORE_NO_COMMUNITY, 0);
    
    if (arg < 0) {
        config_perror("failed to parse proxy args");
        return;
    }
    DEBUGMSGTL(("proxy_config", "done parsing args\n"));

    if (arg >= argn) {
        config_perror("missing base oid");
        return;
    }

    /*
     * usm_set_reportErrorOnUnknownID(0); 
     *
     * hack, stupid v3 ASIs. 
     */
    /*
     * XXX: on a side note, we don't really need to be a reference
     * platform any more so the proper thing to do would be to fix
     * snmplib/snmpusm.c to pass in the pdu type to usm_process_incoming
     * so this isn't needed. 
     */
    ss = snmp_open(&session);
    /*
     * usm_set_reportErrorOnUnknownID(1); 
     */
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpget", &session);
        SOCK_CLEANUP;
        return;
    }

    newp = (struct simple_proxy *) calloc(1, sizeof(struct simple_proxy));

    newp->sess = ss;
    DEBUGMSGTL(("proxy_init", "name = %s\n", args[arg]));
    newp->name_len = MAX_OID_LEN;
    if (!snmp_parse_oid(args[arg++], newp->name, &newp->name_len)) {
        snmp_perror("proxy");
        config_perror("illegal proxy oid specified\n");
        return;
    }

    if (arg < argn) {
        DEBUGMSGTL(("proxy_init", "base = %s\n", args[arg]));
        newp->base_len = MAX_OID_LEN;
        if (!snmp_parse_oid(args[arg++], newp->base, &newp->base_len)) {
            snmp_perror("proxy");
            config_perror("illegal variable name specified (base oid)\n");
            return;
        }
    }
    if ( context_string )
        newp->context = strdup(context_string);

    DEBUGMSGTL(("proxy_init", "registering at: "));
    DEBUGMSGOID(("proxy_init", newp->name, newp->name_len));
    DEBUGMSG(("proxy_init", "\n"));

    /*
     * add to our chain 
     */
    /*
     * must be sorted! 
     */
    listpp = &proxies;
    while (*listpp &&
           snmp_oid_compare(newp->name, newp->name_len,
                            (*listpp)->name, (*listpp)->name_len) > 0) {
        listpp = &((*listpp)->next);
    }

    /*
     * listpp should be next in line from us. 
     */
    if (*listpp) {
        /*
         * make our next in the link point to the current link 
         */
        newp->next = *listpp;
    }
    /*
     * replace current link with us 
     */
    *listpp = newp;

    reg = netsnmp_create_handler_registration("proxy",
                                              proxy_handler,
                                              newp->name,
                                              newp->name_len,
                                              HANDLER_CAN_RWRITE);
    reg->handler->myvoid = newp;
    if (context_string)
        reg->contextName = strdup(context_string);

    netsnmp_register_handler(reg);
}
Beispiel #30
0
int main(int argc, char *argv[])
{
    struct snmp_session session, *ss;
    struct snmp_pdu *pdu;
    struct snmp_pdu *response;
    struct variable_list *vars;
    int arg;
    int count;
    int current_name = 0;
    char *names[128];
    oid name[MAX_OID_LEN];
    int name_length;
    int status;

    /* get the common command line arguments */
    arg = snmp_parse_args(argc, argv, &session);

    /* get the object names */
    for(; arg < argc; arg++)
      names[current_name++] = argv[arg];
    
    SOCK_STARTUP;

    /* open an SNMP session */
    snmp_synch_setup(&session);
    ss = snmp_open(&session);
    if (ss == NULL){
      snmp_perror("snmpget");
      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)) {
        fprintf(stderr, "Invalid object identifier: %s\n", names[count]);
        failures++;
      } else
        snmp_add_null_var(pdu, name, name_length);
    }
    if (failures) {
      SOCK_CLEANUP;
      exit(1);
    }

    /* do the request */
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->errstat == SNMP_ERR_NOSUCHNAME){
          fprintf(stderr, "This name doesn't exist: ");
          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");
        }
        if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GET)) != NULL)
          goto retry;
      }
    } else if (status == STAT_TIMEOUT){
	fprintf(stderr,"Timeout: No Response from %s.\n", session.peername);
	snmp_close(ss);
	SOCK_CLEANUP;
	exit(1);
    } else {    /* status == STAT_ERROR */
      snmp_perror("snmpget");
      snmp_close(ss);
      SOCK_CLEANUP;
      exit(1);
    }

    if (response)
      snmp_free_pdu(response);
    snmp_close(ss);
    SOCK_CLEANUP;
    exit (0);
}