Example #1
0
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu, *response;
    netsnmp_variable_list *vars;
    int             arg;
    char           *gateway;

    int             count;
    struct varInfo *vip;
    u_int           value = 0;
    struct counter64 c64value;
    float           printvalue;
    time_t          last_time = 0;
    time_t          this_time;
    time_t          delta_time;
    int             sum;        /* what the heck is this for, its never used? */
    char            filename[128] = { 0 };
    struct timeval  tv;
    struct tm       tm;
    char            timestring[64] = { 0 }, valueStr[64] = {
    0}, maxStr[64] = {
    0};
    char            outstr[256] = { 0 }, peakStr[64] = {
    0};
    int             status;
    int             begin, end, last_end;
    int             print = 1;
    int             exit_code = 1;

    SOCK_STARTUP;

    switch (arg = snmp_parse_args(argc, argv, &session, "C:", &optProc)) {
    case NETSNMP_PARSE_ARGS_ERROR:
        goto out;
    case NETSNMP_PARSE_ARGS_SUCCESS_EXIT:
        exit_code = 0;
        goto out;
    case NETSNMP_PARSE_ARGS_ERROR_USAGE:
        usage();
        goto out;
    default:
        break;
    }

    gateway = session.peername;

    for (; optind < argc; optind++) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "%s: Too many variables specified (max %d)\n",
	    	argv[optind], MAX_ARGS);
	    goto out;
	}
        varinfo[current_name++].name = argv[optind];
    }

    if (current_name == 0) {
        usage();
        goto out;
    }

    if (dosum) {
	if (current_name >= MAX_ARGS) {
	    fprintf(stderr, "Too many variables specified (max %d)\n",
	    	MAX_ARGS);
	    goto out;
	}
        varinfo[current_name++].name = NULL;
    }

    /*
     * open an SNMP session 
     */
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpdelta", &session);
        goto out;
    }

    if (tableForm && timestamp) {
        printf("%s", gateway);
    }
    for (count = 0; count < current_name; count++) {
        vip = varinfo + count;
        if (vip->name) {
            vip->oidlen = MAX_OID_LEN;
            vip->info_oid = (oid *) malloc(sizeof(oid) * vip->oidlen);
            if (snmp_parse_oid(vip->name, vip->info_oid, &vip->oidlen) ==
                NULL) {
                snmp_perror(vip->name);
                goto close_session;
            }
            sprint_descriptor(vip->descriptor, vip);
            if (tableForm)
                printf("\t%s", vip->descriptor);
        } else {
            vip->oidlen = 0;
            strlcpy(vip->descriptor, SumFile, sizeof(vip->descriptor));
        }
        vip->value = 0;
        zeroU64(&vip->c64value);
        vip->time = 0;
        vip->max = 0;
        if (peaks) {
            vip->peak_count = -1;
            vip->peak = 0;
            vip->peak_average = 0;
        }
    }

    wait_for_period(period);

    end = current_name;
    sum = 0;
    while (1) {
        pdu = snmp_pdu_create(SNMP_MSG_GET);

        if (deltat)
            snmp_add_null_var(pdu, sysUpTimeOid, sysUpTimeLen);

        if (end == current_name)
            count = 0;
        else
            count = end;
        begin = count;
        for (; count < current_name
             && count < begin + varbindsPerPacket - deltat; count++) {
            if (varinfo[count].oidlen)
                snmp_add_null_var(pdu, varinfo[count].info_oid,
                                  varinfo[count].oidlen);
        }
        last_end = end;
        end = count;

      retry:
        status = snmp_synch_response(ss, pdu, &response);
        if (status == STAT_SUCCESS) {
            if (response->errstat == SNMP_ERR_NOERROR) {
                if (timestamp) {
                    gettimeofday(&tv, (struct timezone *) 0);
                    memcpy(&tm, localtime((time_t *) & tv.tv_sec),
                           sizeof(tm));
                    if (((period % 60)
                         && (!peaks || ((period * peaks) % 60)))
                        || keepSeconds)
                        sprintf(timestring, " [%02d:%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min, tm.tm_sec,
                                tm.tm_mon + 1, tm.tm_mday);
                    else
                        sprintf(timestring, " [%02d:%02d %d/%d]",
                                tm.tm_hour, tm.tm_min,
                                tm.tm_mon + 1, tm.tm_mday);
                }

                vars = response->variables;
                if (deltat) {
                    if (!vars || !vars->val.integer) {
                        fprintf(stderr, "Missing variable in reply\n");
                        continue;
                    } else {
                        this_time = *(vars->val.integer);
                    }
                    vars = vars->next_variable;
                } else {
                    this_time = 1;
                }

                for (count = begin; count < end; count++) {
                    vip = varinfo + count;

                    if (vip->oidlen) {
                        if (!vars || !vars->val.integer) {
                            fprintf(stderr, "Missing variable in reply\n");
                            break;
                        }
                        vip->type = vars->type;
                        if (vars->type == ASN_COUNTER64) {
                            u64Subtract(vars->val.counter64,
                                        &vip->c64value, &c64value);
                            memcpy(&vip->c64value, vars->val.counter64,
                                   sizeof(struct counter64));
                        } else {
                            value = *(vars->val.integer) - vip->value;
                            vip->value = *(vars->val.integer);
                        }
                        vars = vars->next_variable;
                    } else {
                        value = sum;
                        sum = 0;
                    }
                    delta_time = this_time - vip->time;
                    if (delta_time <= 0)
                        delta_time = 100;
                    last_time = vip->time;
                    vip->time = this_time;
                    if (last_time == 0)
                        continue;

                    if (vip->oidlen && vip->type != ASN_COUNTER64) {
                        sum += value;
                    }

                    if (tableForm) {
                        if (count == begin) {
                            sprintf(outstr, "%s", timestring + 1);
                        } else {
                            outstr[0] = '\0';
                        }
                    } else {
                        sprintf(outstr, "%s %s", timestring,
                                vip->descriptor);
                    }

                    if (deltat || tableForm) {
                        if (vip->type == ASN_COUNTER64) {
                            fprintf(stderr,
                                    "time delta and table form not supported for counter64s\n");
                            goto close_session;
                        } else {
                            printvalue =
                                ((float) value * 100) / delta_time;
                            if (tableForm)
                                sprintf(valueStr, "\t%.2f", printvalue);
                            else
                                sprintf(valueStr, " /sec: %.2f",
                                        printvalue);
                        }
                    } else {
                        printvalue = (float) value;
                        sprintf(valueStr, " /%d sec: ", period);
                        if (vip->type == ASN_COUNTER64)
                            printU64(valueStr + strlen(valueStr),
                                     &c64value);
                        else
                            sprintf(valueStr + strlen(valueStr), "%u",
                                    value);
                    }

                    if (!peaks) {
                        strcat(outstr, valueStr);
                    } else {
                        print = 0;
                        if (vip->peak_count == -1) {
                            if (wait_for_peak_start(period, peaks) == 0)
                                vip->peak_count = 0;
                        } else {
                            vip->peak_average += printvalue;
                            if (vip->peak < printvalue)
                                vip->peak = printvalue;
                            if (++vip->peak_count == peaks) {
                                if (deltat)
                                    sprintf(peakStr,
                                            " /sec: %.2f	(%d sec Peak: %.2f)",
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                else
                                    sprintf(peakStr,
                                            " /%d sec: %.0f	(%d sec Peak: %.0f)",
                                            period,
                                            vip->peak_average /
                                            vip->peak_count, period,
                                            vip->peak);
                                vip->peak_average = 0;
                                vip->peak = 0;
                                vip->peak_count = 0;
                                print = 1;
                                strcat(outstr, peakStr);
                            }
                        }
                    }

                    if (printmax) {
                        if (printvalue > vip->max) {
                            vip->max = printvalue;
                        }
                        if (deltat)
                            sprintf(maxStr, "	(Max: %.2f)", vip->max);
                        else
                            sprintf(maxStr, "	(Max: %.0f)", vip->max);
                        strcat(outstr, maxStr);
                    }

                    if (print) {
                        if (fileout) {
                            sprintf(filename, "%s-%s", gateway,
                                    vip->descriptor);
                            print_log(filename, outstr + 1);
                        } else {
                            if (tableForm)
                                printf("%s", outstr);
                            else
                                printf("%s\n", outstr + 1);
                            fflush(stdout);
                        }
                    }
                }
                if (end == last_end && tableForm)
                    printf("\n");
            } else {
                if (response->errstat == SNMP_ERR_TOOBIG) {
                    if (response->errindex <= varbindsPerPacket
                        && response->errindex > 0) {
                        varbindsPerPacket = response->errindex - 1;
                    } else {
                        if (varbindsPerPacket > 30)
                            varbindsPerPacket -= 5;
                        else
                            varbindsPerPacket--;
                    }
                    if (varbindsPerPacket <= 0) {
                        exit_code = 5;
                        break;
                    }
                    end = last_end;
                    continue;
                } else 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");
                    /*
                     * Don't exit when OIDs from file are not found on agent
                     * exit_code = 1;
                     * break;
                     */
                } else {
                    fprintf(stderr, "Error in packet: %s\n",
                            snmp_errstring(response->errstat));
                    exit_code = 1;
                    break;
                }

                /*
                 * 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;
                }
            }

        } else if (status == STAT_TIMEOUT) {
            fprintf(stderr, "Timeout: No Response from %s\n", gateway);
            response = NULL;
            exit_code = 1;
            break;
        } else {                /* status == STAT_ERROR */
            snmp_sess_perror("snmpdelta", ss);
            response = NULL;
            exit_code = 1;
            break;
        }

        if (response)
            snmp_free_pdu(response);
        if (end == current_name) {
            wait_for_period(period);
        }
    }

    exit_code = 0;

close_session:
    snmp_close(ss);

out:
    SOCK_CLEANUP;
    return (exit_code);
}
Example #2
0
static void *snmp_client_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;

        struct snmp_client_hnd *custom_handle;
        
	char *root_tuple;

	/* snmpv3 sercurity */
	char *version = NULL;
	char *security_name = NULL;
	char *security_level = NULL;
	char *authpassphrase = NULL;
	char *privpassphrase = NULL;

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if(!root_tuple) {
                dbg("ERROR: Cannot open snmp_client plugin. No entity root found in configuration.");
                return NULL;
        }
        
        handle = 
		(struct oh_handler_state *)g_malloc0(sizeof(*handle));
        custom_handle =
                (struct snmp_client_hnd *)g_malloc0(sizeof(*custom_handle));

        if(!handle || !custom_handle) {
                dbg("Could not allocate memory for handle or custom_handle.");
                return NULL;
        }
        handle->data = custom_handle;
        
        handle->config = handler_config;

        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));

        /* Initialize snmp library */
        init_snmp("oh_snmp_client");

        snmp_sess_init(&(custom_handle->session)); /* Setting up all defaults for now. */
        custom_handle->session.peername = (char *)g_hash_table_lookup(handle->config, "host");

	/* snmp version */
        version = (char *)g_hash_table_lookup(handle->config, "version");

	/* Use SNMPv3 to talk to the server */
	if (!strncmp(version, "3", 1)) {

		if(!(security_name = (char *)g_hash_table_lookup(handle->config, "security_name"))){
			dbg("MISSING security_name"); 
			return NULL;
		}
		
		if (!(security_level = (char *)g_hash_table_lookup(handle->config, "security_level"))){
			dbg("MISSING security_level");
			return NULL;
		}
		if (!(authpassphrase = (char *)g_hash_table_lookup(handle->config, "authpassphrase"))){ 
			dbg("MISSING authpassphrase");
			return NULL;
		}
	
		if (!(privpassphrase = (char *)g_hash_table_lookup(handle->config, "privpassphrase"))){
			dbg("MISSING privpassphrase");
			return NULL;
		}
	
		/* set the SNMPv3 user name */
		custom_handle->session.securityName = strdup(security_name);
		custom_handle->session.securityNameLen = strlen(custom_handle->session.securityName);
	
		/* set the SNMP version number */
		custom_handle->session.version = SNMP_VERSION_3;
		
		/* set the security level to authenticated, AND not encrypted */
		if(!strncmp(security_level, "noAuthnoPriv", sizeof("noAuthnoPriv")))
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
		else if(!strncmp(security_level, "authNoPriv", sizeof("authNoPriv"))) 
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
		else if(!strncmp(security_level, "authPriv", sizeof("suthPriv")))
		   custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
		else {
			dbg("ERROR: unsupport securtiy_level");
			return NULL;
		}
	
		/* set the authentication method to MD5 */
		if (authpassphrase) {
			custom_handle->session.securityAuthProto = usmHMACMD5AuthProtocol;
			custom_handle->session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol)/sizeof(oid);
			custom_handle->session.securityAuthKeyLen = USM_AUTH_KU_LEN;
		    
			/* set the authentication key to a MD5 hashed version of our
			passphrase "The UCD Demo Password" (which must be at least 8
			characters long) */
			if (generate_Ku(custom_handle->session.securityAuthProto,
					custom_handle->session.securityAuthProtoLen,
					(u_char *) authpassphrase, 
					strlen(authpassphrase),
					custom_handle->session.securityAuthKey,
					&custom_handle->session.securityAuthKeyLen) != SNMPERR_SUCCESS) {
				snmp_perror("ack");
				snmp_log(LOG_ERR,
					 "Error generating Ku from AUTHENTICATION pass phrase. ");
				dbg("Error generating Ku from AUTHENTICATION pass phrase.");
			}
		}
		/* set the encryption method to DES */
		if (privpassphrase) {
			custom_handle->session.securityPrivProto = usmDESPrivProtocol;
			custom_handle->session.securityPrivProtoLen = sizeof(usmDESPrivProtocol)/sizeof(oid);
			custom_handle->session.securityPrivKeyLen = USM_PRIV_KU_LEN;
			/* generate Key */
			if (generate_Ku(custom_handle->session.securityAuthProto,
					custom_handle->session.securityAuthProtoLen,
					(u_char *) privpassphrase, 
					strlen(privpassphrase),
					custom_handle->session.securityPrivKey,
					&custom_handle->session.securityPrivKeyLen) != SNMPERR_SUCCESS) {
				snmp_perror("ack");
				snmp_log(LOG_ERR,
					 "Error generating Ku from PRIVACY pass phrase. ");
				dbg("Error generating Ku from PRIVACY pass phrase.");
			}
		}
	
	}
	
	/* Use SNMPv2c to talk to the server */
	if (!strncmp(version, "2c", 2)) {

		/* set the SNMP version number */
		custom_handle->session.version = SNMP_VERSION_2c;

		/* set the SNMPv1 community name used for authentication */
		custom_handle->session.community = 
			(char *)g_hash_table_lookup(handle->config, "community");
		custom_handle->session.community_len = 
			strlen(custom_handle->session.community);
	}
	

        /* windows32 specific net-snmp initialization (is a noop on unix) */
        SOCK_STARTUP;

        custom_handle->ss = snmp_open(&(custom_handle->session));

        if(!custom_handle->ss) {
                snmp_perror("ack");
                snmp_log(LOG_ERR, "something horrible happened!!!");
                dbg("Unable to open snmp session.");
                return NULL;
        }

        return handle;

}
Example #3
0
int
main(int argc, char *argv[])
{
    char           *hostname = NULL;
    struct protoent *p;
    struct protox  *tp = NULL;  /* for printing cblocks & stats */
    int             allprotos = 1;
    char           *community = NULL;
    char           *argp;
    netsnmp_session session;
    int             timeout = SNMP_DEFAULT_TIMEOUT;
    int             version = SNMP_DEFAULT_VERSION;
    int             arg;

#ifndef DISABLE_MIB_LOADING
    init_mib();
#endif /* DISABLE_MIB_LOADING */
    /*
     * Usage: snmpnetstatwalk -v 1 [-q] hostname community ...      or:
     * Usage: snmpnetstat [-v 2 ] [-q] hostname noAuth     ...
     */
    while ((arg = getopt(argc, argv, "VhdqD:t:c:v:aionrsP:I:")) != EOF) {
        switch (arg) {
        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n",
                    netsnmp_get_version());
            exit(0);
            break;

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

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

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

        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;

        case 't':
            timeout = atoi(optarg);
            timeout *= 1000000;
            break;

        case 'c':
            community = optarg;
            break;

        case 'v':
            argp = optarg;
            version = -1;
#ifndef DISABLE_SNMPV1
            if (!strcasecmp(argp, "1"))
                version = SNMP_VERSION_1;
#endif
#ifndef DISABLE_SNMPV2C
            if (!strcasecmp(argp, "2c"))
                version = SNMP_VERSION_2c;
#endif
            if (version == -1) {
                fprintf(stderr, "Invalid version: %s\n", argp);
                usage();
                exit(1);
            }
            break;

        case 'a':
            aflag++;
            break;

        case 'i':
            iflag++;
            break;

        case 'o':
            oflag++;
            break;

        case 'n':
            nflag++;
            break;

        case 'r':
            rflag++;
            break;

        case 's':
            sflag++;
            break;

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

        case 'I':
            iflag++;
            intrface = optarg;
            break;

        default:
            exit(1);
            break;
        }
        continue;
    }

    init_snmp("snmpapp");
    snmp_enable_stderrlog();
    if (version == SNMP_DEFAULT_VERSION) {
        version = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
		                     NETSNMP_DS_LIB_SNMPVERSION);
        if (!version) {
            switch (DEFAULT_SNMP_VERSION) {
#ifndef DISABLE_SNMPV1
            case 1:
                version = SNMP_VERSION_1;
                break;
#endif
#ifndef DISABLE_SNMPV2C
            case 2:
                version = SNMP_VERSION_2c;
                break;
#endif
            case 3:
                version = SNMP_VERSION_3;
                break;
            }
#ifndef DISABLE_SNMPV1
        } else if (version == NETSNMP_DS_SNMP_VERSION_1) {
                          /* Bogus value. version1 = 0 */
            version = SNMP_VERSION_1;
#endif
        }
    }
    if (optind < argc) {
        hostname = argv[optind++];
    }
    else {
        fprintf(stderr, "Missing host name.\n");
        exit(1);
    }
    if (community == NULL) {
	community = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
		                          NETSNMP_DS_LIB_COMMUNITY);
    }
    if (optind < argc && isdigit(argv[optind][0])) {
        interval = atoi(argv[optind++]);
        if (interval <= 0) {
            usage();
            exit(1);
        }
        iflag++;
    }
    if (optind < argc) {
        usage();
        exit(1);
    }


    snmp_sess_init(&session);
    session.peername = hostname;
    session.timeout = timeout;
#if !defined(DISABLE_SNMPV1) || !defined(DISABLE_SNMPV2C)
    if (version != SNMP_VERSION_3) {
        if (!community) {
            fprintf(stderr, "Missing community name.\n");
            exit(1);
        }
        session.version = version;
        session.community = (u_char *) community;
        session.community_len = strlen(community);
    }
#endif

    SOCK_STARTUP;

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

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

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

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

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

    snmp_close(Session);

    SOCK_CLEANUP;
    return 0;
}
Example #4
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;
}
Example #5
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;
}
Example #6
0
int
main(int argc, char *argv[])
{
	netsnmp_session session;
	struct protoent *p;
        char *cp;

	af = AF_UNSPEC;
        cp = strrchr( argv[0], '/' );
        if (cp)
            progname = cp+1;
        else
            progname = argv[0];

	switch (snmp_parse_args( argc, argv, &session, "C:iRs", 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;
	}

	    /*
	     * Check argc vs optind ??
	     */
	argv += optind;
	argc -= optind;

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

	/*
	 * Omitted:
	 *     Privilege handling
	 *    "Backward Compatibility"
	 *     Kernel namelis handling
	 */

	if (mflag) {
            /*
		mbpr(nl[N_MBSTAT].n_value, nl[N_MBPOOL].n_value,
		    nl[N_MCLPOOL].n_value);
             */
		exit(0);
	}
	if (pflag) {
		printproto(tp, tp->pr_name);
		exit(0);
	}
	/*
	 * Keep file descriptors open to avoid overhead
	 * of open/close on each call to get* routines.
	 */
	sethostent(1);
	setnetent(1);
	if (iflag) {
		intpr(interval);
		exit(0);
	}
	if (rflag) {
             /*
		if (sflag)
			rt_stats();
		else
              */
		if (Lflag || routexpr(af) == 0) {
		    if (route4pr(af) == 0 && af == AF_INET) routepr();
		    route6pr(af);
		}
		exit(0);
	}
     /*
	if (gflag) {
		if (sflag) {
			if (af == AF_INET || af == AF_UNSPEC)
				mrt_stats(nl[N_MRTPROTO].n_value,
				    nl[N_MRTSTAT].n_value);
#ifdef NETSNMP_ENABLE_IPV6
			if (af == AF_INET6 || af == AF_UNSPEC)
				mrt6_stats(nl[N_MRT6PROTO].n_value,
				    nl[N_MRT6STAT].n_value);
#endif
		}
		else {
			if (af == AF_INET || af == AF_UNSPEC)
				mroutepr(nl[N_MRTPROTO].n_value,
				    nl[N_MFCHASHTBL].n_value,
				    nl[N_MFCHASH].n_value,
				    nl[N_VIFTABLE].n_value);
#ifdef NETSNMP_ENABLE_IPV6
			if (af == AF_INET6 || af == AF_UNSPEC)
				mroute6pr(nl[N_MRT6PROTO].n_value,
				    nl[N_MF6CTABLE].n_value,
				    nl[N_MIF6TABLE].n_value);
#endif
		}
		exit(0);
	}
     */
	setservent(1);
	if (af == AF_UNSPEC && Lflag) {
		setprotoent(1);
		/* ugh, this is O(MN) ... why do we do this? */
		while ((p = getprotoent())) {
			for (tp = protox; tp->pr_name; tp++)
				if (strcmp(tp->pr_name, p->p_name) == 0)
					if (tp->pr_name && tp->pr_wanted)
					    printproto(tp, p->p_name);
		}
		endprotoent();
	}
	if (af == AF_UNSPEC && !Lflag)
		for (tp = ipxprotox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
	if (af == AF_INET)
		for (tp = protox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
	if (af == AF_INET6)
		for (tp = ip6protox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
    /*
	if (af == AF_IPX || af == AF_UNSPEC)
		for (tp = ipxprotox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
	if (af == AF_NS || af == AF_UNSPEC)
		for (tp = nsprotox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
	if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag)
		unixpr(nl[N_UNIXSW].n_value);
	if (af == AF_APPLETALK || af == AF_UNSPEC)
		for (tp = atalkprotox; tp->pr_name; tp++)
			printproto(tp, tp->pr_name);
     */
	exit(0);
}
Example #7
0
void startonehost(struct req_t *req, int ipchange)
{
	struct snmp_session s;
	struct snmp_pdu *snmpreq = NULL;

	if ((dataoperation < GET_DATA) && !req->currentkey) return;

	/* Are we retrying a cluster with a new IP? Then drop the current session */
	if (req->sess && ipchange) {
		/*
		 * Apparently, we cannot close a session while in a callback.
		 * So leave this for now - it will leak some memory, but
		 * this is not a problem as long as we only run once.
		 */
		/* snmp_close(req->sess); */
		req->sess = NULL;
	}

	/* Setup the SNMP session */
	if (!req->sess) {
		snmp_sess_init(&s);

		/* 
		 * snmp_session has a "remote_port" field, but it does not work.
		 * Instead, the peername should include a port number (IP:PORT)
		 * if (req->portnumber) s.remote_port = req->portnumber;
		 */
		s.peername = req->hostip[req->hostipidx];

		/* Set the SNMP version and authentication token(s) */
		s.version = req->version;
		switch (s.version) {
		  case SNMP_VERSION_1:
		  case SNMP_VERSION_2c:
			s.community = req->community;
			s.community_len = strlen((char *)req->community);
			break;

		  case SNMP_VERSION_3:
			/* set the SNMPv3 user name */
			s.securityName = strdup(req->username);
			s.securityNameLen = strlen(s.securityName);

			/* set the security level to authenticated, but not encrypted */
			s.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;

			/* set the authentication method */
			switch (req->authmethod) {
			  case SNMP_V3AUTH_MD5:
				s.securityAuthProto = usmHMACMD5AuthProtocol;
				s.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol)/sizeof(oid);
				s.securityAuthKeyLen = USM_AUTH_KU_LEN;
				break;

			  case SNMP_V3AUTH_SHA1:
				s.securityAuthProto = usmHMACSHA1AuthProtocol;
				s.securityAuthProtoLen = sizeof(usmHMACSHA1AuthProtocol)/sizeof(oid);
				s.securityAuthKeyLen = USM_AUTH_KU_LEN;
				break;
			}

			/*
			 * set the authentication key to a hashed version of our
			 * passphrase (which must be at least 8 characters long).
			 */
			if (generate_Ku(s.securityAuthProto, s.securityAuthProtoLen,
					(u_char *)req->passphrase, strlen(req->passphrase),
					s.securityAuthKey, &s.securityAuthKeyLen) != SNMPERR_SUCCESS) {
				errprintf("Failed to generate Ku from authentication pass phrase for host %s\n",
					  req->hostname);
				snmp_perror("generate_Ku");
				return;
			}
			break;
		}

		/* Set timeouts and retries */
		if (timeout > 0) s.timeout = timeout;
		if (retries > 0) s.retries = retries;

		/* Setup the callback */
		s.callback = asynch_response;
		s.callback_magic = req;

		if (!(req->sess = snmp_open(&s))) {
			snmp_sess_perror("snmp_open", &s);
			return;
		}
	}

	switch (dataoperation) {
	  case GET_KEYS:
		snmpreq = snmp_pdu_create(SNMP_MSG_GETNEXT);
		pducount++;
		snmp_add_null_var(snmpreq, req->currentkey->indexmethod->rootoid, req->currentkey->indexmethod->rootoidlen);
		break;

	  case GET_DATA:
		/* Build the request PDU and send it */
		snmpreq = generate_datarequest(req);
		break;
	}

	if (!snmpreq) return;

	if (snmp_send(req->sess, snmpreq))
		active_requests++;
	else {
		errorcount++;
		snmp_sess_perror("snmp_send", req->sess);
		snmp_free_pdu(snmpreq);
	}
}
Example #8
0
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;
}
Example #9
0
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu = NULL, *response = NULL;

    int             arg;
    size_t          name_length = USM_OID_LEN;
    size_t          name_length2 = USM_OID_LEN;
    int             status;
    int             exitval = 1;
    int             rval;
    int             command = 0;
    long            longvar;

    size_t          oldKu_len = SNMP_MAXBUF_SMALL,
        newKu_len = SNMP_MAXBUF_SMALL,
        oldkul_len = SNMP_MAXBUF_SMALL,
        oldkulpriv_len = SNMP_MAXBUF_SMALL,
        newkulpriv_len = SNMP_MAXBUF_SMALL,
        newkul_len = SNMP_MAXBUF_SMALL,
        keychange_len = SNMP_MAXBUF_SMALL,
        keychangepriv_len = SNMP_MAXBUF_SMALL;

    char           *newpass = NULL, *oldpass = NULL;
    u_char          oldKu[SNMP_MAXBUF_SMALL],
        newKu[SNMP_MAXBUF_SMALL],
        oldkul[SNMP_MAXBUF_SMALL],
        oldkulpriv[SNMP_MAXBUF_SMALL],
        newkulpriv[SNMP_MAXBUF_SMALL],
        newkul[SNMP_MAXBUF_SMALL], keychange[SNMP_MAXBUF_SMALL],
        keychangepriv[SNMP_MAXBUF_SMALL];

    SOCK_STARTUP;

    authKeyChange = authKeyOid;
    privKeyChange = privKeyOid;

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

    if (arg >= argc) {
        fprintf(stderr, "Please specify an operation to perform.\n");
        usage();
        goto out;
    }

    /*
     * open an SNMP session 
     */
    /*
     * Note:  this needs to obtain the engineID used below 
     */
    session.flags &= ~SNMP_FLAGS_DONT_PROBE;
    ss = snmp_open(&session);
    if (ss == NULL) {
        /*
         * diagnose snmp_open errors with the input netsnmp_session pointer 
         */
        snmp_sess_perror("snmpusm", &session);
        goto out;
    }

    /*
     * set usmUserEngineID from ss->contextEngineID
     *   if not already set (via -CE)
     */
    if (usmUserEngineID == NULL) {
      usmUserEngineID    = ss->contextEngineID;
      usmUserEngineIDLen = ss->contextEngineIDLen;
    }

    /*
     * create PDU for SET request and add object names and values to request 
     */
    pdu = snmp_pdu_create(SNMP_MSG_SET);
    if (!pdu) {
        fprintf(stderr, "Failed to create request\n");
        goto close_session;
    }


    if (strcmp(argv[arg], CMD_PASSWD_NAME) == 0) {

        /*
         * passwd: change a users password.
         *
         * XXX:  Uses the auth type of the calling user, a MD5 user can't
         *       change a SHA user's key.
         */
        char *passwd_user;

        command = CMD_PASSWD;
        oldpass = argv[++arg];
        newpass = argv[++arg];
        passwd_user = argv[++arg];

        if (doprivkey == 0 && doauthkey == 0)
            doprivkey = doauthkey = 1;

        if (newpass == NULL || strlen(newpass) < USM_LENGTH_P_MIN) {
            fprintf(stderr,
                    "New passphrase must be greater than %d characters in length.\n",
                    USM_LENGTH_P_MIN);
            goto close_session;
        }

        if (oldpass == NULL || strlen(oldpass) < USM_LENGTH_P_MIN) {
            fprintf(stderr,
                    "Old passphrase must be greater than %d characters in length.\n",
                    USM_LENGTH_P_MIN);
            goto close_session;
        }

        DEBUGMSGTL(("9:usm:passwd", "oldpass len %" NETSNMP_PRIz "d, newpass len %" NETSNMP_PRIz "d\n",
                    strlen(oldpass), strlen(newpass)));

        /* 
         * Change the user supplied on command line.
         */
        if ((passwd_user != NULL) && (strlen(passwd_user) > 0)) {
            session.securityName = passwd_user;
        } else {
            /*
             * Use own key object if no user was supplied.
             */
            authKeyChange = ownAuthKeyOid;
            privKeyChange = ownPrivKeyOid;
        }

        /*
         * do we have a securityName?  If not, copy the default 
         */
        if (session.securityName == NULL) {
            session.securityName = 
	      strdup(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
					   NETSNMP_DS_LIB_SECNAME));
        }

        /*
         * the old Ku is in the session, but we need the new one 
         */
        if (session.securityAuthProto == NULL) {
            /*
             * get .conf set default 
             */
            const oid      *def =
                get_default_authtype(&session.securityAuthProtoLen);
            session.securityAuthProto =
                snmp_duplicate_objid(def, session.securityAuthProtoLen);
        }
        if (session.securityAuthProto == NULL) {
            /*
             * assume MD5 
             */
#ifndef NETSNMP_DISABLE_MD5
            session.securityAuthProtoLen =
                sizeof(usmHMACMD5AuthProtocol) / sizeof(oid);
            session.securityAuthProto =
                snmp_duplicate_objid(usmHMACMD5AuthProtocol,
                                     session.securityAuthProtoLen);
#else
            session.securityAuthProtoLen =
                sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid);
            session.securityAuthProto =
                snmp_duplicate_objid(usmHMACSHA1AuthProtocol,
                                     session.securityAuthProtoLen);
#endif

        }

	if (uselocalizedkey && (strncmp(oldpass, "0x", 2) == 0)) {
	    /*
	     * use the localized key from the command line
	     */
	    u_char *buf;
	    size_t buf_len = SNMP_MAXBUF_SMALL;
	    buf = (u_char *) malloc (buf_len * sizeof(u_char));

	    oldkul_len = 0; /* initialize the offset */
	    if (!snmp_hex_to_binary((u_char **) (&buf), &buf_len, &oldkul_len, 0, oldpass)) {
	      snmp_perror(argv[0]);
	      fprintf(stderr, "generating the old Kul from localized key failed\n");
	      goto close_session;
	    }
	    
	    memcpy(oldkul, buf, oldkul_len);
	    SNMP_FREE(buf);
	}
	else {
	    /*
	     * the old Ku is in the session, but we need the new one 
	     */
	    rval = generate_Ku(session.securityAuthProto,
			       session.securityAuthProtoLen,
			       (u_char *) oldpass, strlen(oldpass),
			       oldKu, &oldKu_len);
	    
	    if (rval != SNMPERR_SUCCESS) {
	        snmp_perror(argv[0]);
	        fprintf(stderr, "generating the old Ku failed\n");
	        goto close_session;
	    }

	    /*
	     * generate the two Kul's 
	     */
	    rval = generate_kul(session.securityAuthProto,
				session.securityAuthProtoLen,
				usmUserEngineID, usmUserEngineIDLen,
				oldKu, oldKu_len, oldkul, &oldkul_len);
	    
	    if (rval != SNMPERR_SUCCESS) {
	        snmp_perror(argv[0]);
		fprintf(stderr, "generating the old Kul failed\n");
		goto close_session;
	    }
            DEBUGMSGTL(("9:usm:passwd", "oldkul len %" NETSNMP_PRIz "d\n", oldkul_len));
	}
	if (uselocalizedkey && (strncmp(newpass, "0x", 2) == 0)) {
	    /*
	     * use the localized key from the command line
	     */
	    u_char *buf;
	    size_t buf_len = SNMP_MAXBUF_SMALL;
	    buf = (u_char *) malloc (buf_len * sizeof(u_char));

	    newkul_len = 0; /* initialize the offset */
	    if (!snmp_hex_to_binary((u_char **) (&buf), &buf_len, &newkul_len, 0, newpass)) {
	      snmp_perror(argv[0]);
	      fprintf(stderr, "generating the new Kul from localized key failed\n");
	      goto close_session;
	    }
	    
	    memcpy(newkul, buf, newkul_len);
	    SNMP_FREE(buf);
	} else {
            rval = generate_Ku(session.securityAuthProto,
                               session.securityAuthProtoLen,
                               (u_char *) newpass, strlen(newpass),
                               newKu, &newKu_len);

            if (rval != SNMPERR_SUCCESS) {
                snmp_perror(argv[0]);
                fprintf(stderr, "generating the new Ku failed\n");
                goto close_session;
            }

	    rval = generate_kul(session.securityAuthProto,
				session.securityAuthProtoLen,
				usmUserEngineID, usmUserEngineIDLen,
				newKu, newKu_len, newkul, &newkul_len);

	    if (rval != SNMPERR_SUCCESS) {
	        snmp_perror(argv[0]);
		fprintf(stderr, "generating the new Kul failed\n");
		goto close_session;
	    }
            DEBUGMSGTL(("9:usm:passwd", "newkul len %" NETSNMP_PRIz "d\n", newkul_len));
	}

        /*
         * for encryption, we may need to truncate the key to the proper length
         * so we need two copies.  For simplicity, we always just copy even if
         * they're the same lengths.
         */
        if (doprivkey) {
            int privtype, properlength;
            u_char *okp = oldkulpriv, *nkp = newkulpriv;
            if (!session.securityPrivProto) {
                snmp_log(LOG_ERR, "no encryption type specified, which I need in order to know to change the key\n");
                goto close_session;
            }

            privtype = sc_get_privtype(session.securityPrivProto,
                                       session.securityPrivProtoLen);
            properlength = sc_get_proper_priv_length_bytype(privtype);
            if (USM_CREATE_USER_PRIV_DES == privtype)
                properlength *= 2; /* ?? we store salt with key */
            DEBUGMSGTL(("9:usm:passwd", "proper len %d\n", properlength));
            oldkulpriv_len = oldkul_len;
            newkulpriv_len = newkul_len;
            memcpy(oldkulpriv, oldkul, oldkulpriv_len);
            memcpy(newkulpriv, newkul, newkulpriv_len);

            if (oldkulpriv_len > properlength) {
                oldkulpriv_len = newkulpriv_len = properlength;
            }
            else if (oldkulpriv_len < properlength) {
                rval = netsnmp_extend_kul(properlength,
                                          session.securityAuthProto,
                                          session.securityAuthProtoLen,
                                          privtype,
                                          usmUserEngineID, usmUserEngineIDLen,
                                          &okp, &oldkulpriv_len,
                                          sizeof(oldkulpriv));
                rval = netsnmp_extend_kul(properlength,
                                          session.securityAuthProto,
                                          session.securityAuthProtoLen,
                                          privtype,
                                          usmUserEngineID, usmUserEngineIDLen,
                                          &nkp, &newkulpriv_len,
                                          sizeof(newkulpriv));
            }
        }

        /*
         * create the keychange string 
         */
	if (doauthkey) {
	  rval = encode_keychange(session.securityAuthProto,
				  session.securityAuthProtoLen,
				  oldkul, oldkul_len,
				  newkul, newkul_len,
				  keychange, &keychange_len);

	  if (rval != SNMPERR_SUCCESS) {
	    snmp_perror(argv[0]);
            fprintf(stderr, "encoding the keychange failed\n");
            usage();
            goto close_session;
	  }
	}

        /* which is slightly different for encryption if lengths are
           different */
	if (doprivkey) {
            DEBUGMSGTL(("9:usm:passwd:encode", "proper len %" NETSNMP_PRIz "d, old_len %" NETSNMP_PRIz "d, new_len %" NETSNMP_PRIz "d\n",
                        oldkulpriv_len, oldkulpriv_len, newkulpriv_len));
	  rval = encode_keychange(session.securityAuthProto,
                                session.securityAuthProtoLen,
                                oldkulpriv, oldkulpriv_len,
                                newkulpriv, newkulpriv_len,
                                keychangepriv, &keychangepriv_len);

          DEBUGMSGTL(("9:usm:passwd:encode", "keychange len %" NETSNMP_PRIz "d\n",
                      keychangepriv_len));
	  if (rval != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr, "encoding the keychange failed\n");
            usage();
            goto close_session;
	  }
	}

        /*
         * add the keychange string to the outgoing packet 
         */
        if (doauthkey) {
            setup_oid(authKeyChange, &name_length,
                      usmUserEngineID, usmUserEngineIDLen,
                      session.securityName);
            snmp_pdu_add_variable(pdu, authKeyChange, name_length,
                                  ASN_OCTET_STR, keychange, keychange_len);
        }
        if (doprivkey) {
            setup_oid(privKeyChange, &name_length2,
                      usmUserEngineID, usmUserEngineIDLen,
                      session.securityName);
            snmp_pdu_add_variable(pdu, privKeyChange, name_length2,
                                  ASN_OCTET_STR,
                                  keychangepriv, keychangepriv_len);
        }

    } else if (strcmp(argv[arg], CMD_CREATE_NAME) == 0) {
        /*
         * create:  create a user
         *
         * create USER [CLONEFROM]
         */
        if (++arg >= argc) {
            fprintf(stderr, "You must specify the user name to create\n");
            usage();
            goto close_session;
        }

        command = CMD_CREATE;

        if (++arg < argc) {
            /*
             * clone the new user from an existing user
             *   (and make them active immediately)
             */
            setup_oid(usmUserStatus, &name_length,
                      usmUserEngineID, usmUserEngineIDLen, argv[arg-1]);
            if (docreateandwait) {
                longvar = RS_CREATEANDWAIT;
            } else {
                longvar = RS_CREATEANDGO;
            }
            snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                                  ASN_INTEGER, (u_char *) & longvar,
                                  sizeof(longvar));

            name_length = USM_OID_LEN;
            setup_oid(usmUserCloneFrom, &name_length,
                      usmUserEngineID, usmUserEngineIDLen,
                      argv[arg - 1]);
            setup_oid(usmUserSecurityName, &name_length2,
                      usmUserEngineID, usmUserEngineIDLen,
                      argv[arg]);
            snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length,
                                  ASN_OBJECT_ID,
                                  (u_char *) usmUserSecurityName,
                                  sizeof(oid) * name_length2);
        } else {
            /*
             * create a new (unauthenticated) user from scratch
             * The Net-SNMP agent won't allow such a user to be made active.
             */
            setup_oid(usmUserStatus, &name_length,
                      usmUserEngineID, usmUserEngineIDLen, argv[arg-1]);
            longvar = RS_CREATEANDWAIT;
            snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                                  ASN_INTEGER, (u_char *) & longvar,
                                  sizeof(longvar));
        }

    } else if (strcmp(argv[arg], CMD_CLONEFROM_NAME) == 0) {
        /*
         * create:  clone a user from another
         *
         * cloneFrom USER FROM
         */
        if (++arg >= argc) {
            fprintf(stderr,
                    "You must specify the user name to operate on\n");
            usage();
            goto close_session;
        }

        command = CMD_CLONEFROM;
        setup_oid(usmUserStatus, &name_length,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);
        longvar = RS_ACTIVE;
        snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                              ASN_INTEGER, (u_char *) & longvar,
                              sizeof(longvar));
        name_length = USM_OID_LEN;
        setup_oid(usmUserCloneFrom, &name_length,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);

        if (++arg >= argc) {
            fprintf(stderr,
                    "You must specify the user name to clone from\n");
            usage();
            goto close_session;
        }

        setup_oid(usmUserSecurityName, &name_length2,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);
        snmp_pdu_add_variable(pdu, usmUserCloneFrom, name_length,
                              ASN_OBJECT_ID,
                              (u_char *) usmUserSecurityName,
                              sizeof(oid) * name_length2);

    } else if (strcmp(argv[arg], CMD_DELETE_NAME) == 0) {
        /*
         * delete:  delete a user
         *
         * delete USER
         */
        if (++arg >= argc) {
            fprintf(stderr, "You must specify the user name to delete\n");
            goto close_session;
        }

        command = CMD_DELETE;
        setup_oid(usmUserStatus, &name_length,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);
        longvar = RS_DESTROY;
        snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                              ASN_INTEGER, (u_char *) & longvar,
                              sizeof(longvar));
    } else if (strcmp(argv[arg], CMD_ACTIVATE_NAME) == 0) {
        /*
         * activate:  activate a user
         *
         * activate USER
         */
        if (++arg >= argc) {
            fprintf(stderr, "You must specify the user name to activate\n");
            goto close_session;
        }

        command = CMD_ACTIVATE;
        setup_oid(usmUserStatus, &name_length,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);
        longvar = RS_ACTIVE;
        snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                              ASN_INTEGER, (u_char *) & longvar,
                              sizeof(longvar));
    } else if (strcmp(argv[arg], CMD_DEACTIVATE_NAME) == 0) {
        /*
         * deactivate:  deactivate a user
         *
         * deactivate USER
         */
        if (++arg >= argc) {
            fprintf(stderr, "You must specify the user name to deactivate\n");
            goto close_session;
        }

        command = CMD_DEACTIVATE;
        setup_oid(usmUserStatus, &name_length,
                  usmUserEngineID, usmUserEngineIDLen, argv[arg]);
        longvar = RS_NOTINSERVICE;
        snmp_pdu_add_variable(pdu, usmUserStatus, name_length,
                              ASN_INTEGER, (u_char *) & longvar,
                              sizeof(longvar));
#if defined(HAVE_OPENSSL_DH_H) && defined(HAVE_LIBCRYPTO)
    } else if (strcmp(argv[arg], CMD_CHANGEKEY_NAME) == 0) {
        /*
         * change the key of a user if DH is available
         */

        char *passwd_user;
        netsnmp_pdu *dhpdu, *dhresponse = NULL;
        netsnmp_variable_list *vars, *dhvar;
        
        command = CMD_CHANGEKEY;
        name_length = DH_USM_OID_LEN;
        name_length2 = DH_USM_OID_LEN;

        passwd_user = argv[++arg];

        if (doprivkey == 0 && doauthkey == 0)
            doprivkey = doauthkey = 1;

        /* 
         * Change the user supplied on command line.
         */
        if ((passwd_user != NULL) && (strlen(passwd_user) > 0)) {
            session.securityName = passwd_user;
        } else {
            /*
             * Use own key object if no user was supplied.
             */
            dhauthKeyChange = usmDHUserOwnAuthKeyChange;
            dhprivKeyChange = usmDHUserOwnPrivKeyChange;
        }

        /*
         * do we have a securityName?  If not, copy the default 
         */
        if (session.securityName == NULL) {
            session.securityName = 
	      strdup(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
					   NETSNMP_DS_LIB_SECNAME));
        }

        /* fetch the needed diffie helman parameters */
        dhpdu = snmp_pdu_create(SNMP_MSG_GET);
        if (!dhpdu) {
            fprintf(stderr, "Failed to create DH request\n");
            goto close_session;
        }

        /* get the current DH parameters */
        snmp_add_null_var(dhpdu, usmDHParameters, usmDHParameters_len);
        
        /* maybe the auth key public value */
        if (doauthkey) {
            setup_oid(dhauthKeyChange, &name_length,
                      usmUserEngineID, usmUserEngineIDLen,
                      session.securityName);
            snmp_add_null_var(dhpdu, dhauthKeyChange, name_length);
        }
            
        /* maybe the priv key public value */
        if (doprivkey) {
            setup_oid(dhprivKeyChange, &name_length2,
                      usmUserEngineID, usmUserEngineIDLen,
                      session.securityName);
            snmp_add_null_var(dhpdu, dhprivKeyChange, name_length2);
        }

        /* fetch the values */
        status = snmp_synch_response(ss, dhpdu, &dhresponse);

        if (status != SNMPERR_SUCCESS || dhresponse == NULL ||
            dhresponse->errstat != SNMP_ERR_NOERROR ||
            dhresponse->variables->type != ASN_OCTET_STR) {
            snmp_sess_perror("snmpusm", ss);
            if (dhresponse && dhresponse->variables &&
                dhresponse->variables->type != ASN_OCTET_STR) {
                fprintf(stderr,
                        "Can't get diffie-helman exchange from the agent\n");
                fprintf(stderr,
                        "  (maybe it doesn't support the SNMP-USM-DH-OBJECTS-MIB MIB)\n");
            }
            exitval = 1;
            goto begone;
        }
        
        dhvar = dhresponse->variables;
        vars = dhvar->next_variable;
        /* complete the DH equation & print resulting keys */
        if (doauthkey) {
            if (get_USM_DH_key(vars, dhvar,
                               sc_get_properlength(ss->securityAuthProto,
                                                   ss->securityAuthProtoLen),
                               pdu, "auth",
                               dhauthKeyChange, name_length) != SNMPERR_SUCCESS)
                goto begone;
            vars = vars->next_variable;
        }
        if (doprivkey) {
            size_t dhprivKeyLen = 0;
            int privtype = sc_get_privtype(ss->securityPrivProto,
                                           ss->securityPrivProtoLen);
            dhprivKeyLen = sc_get_proper_priv_length_bytype(privtype);
            if (USM_CREATE_USER_PRIV_DES == privtype)
                dhprivKeyLen *= 2; /* ?? we store salt with key */
            if (get_USM_DH_key(vars, dhvar,
                               dhprivKeyLen,
                               pdu, "priv",
                               dhprivKeyChange, name_length2)
                != SNMPERR_SUCCESS)
                goto begone;
            vars = vars->next_variable;
        }
        /* snmp_free_pdu(dhresponse); */ /* parts still in use somewhere */
#endif /* HAVE_OPENSSL_DH_H && HAVE_LIBCRYPTO */
    } else {
        fprintf(stderr, "Unknown command\n");
        usage();
        goto close_session;
    }

    /*
     * add usmUserPublic if specified (via -Cp)
     */
    if (usmUserPublic_val) {
        name_length = USM_OID_LEN;
	setup_oid(usmUserPublic, &name_length,
		  usmUserEngineID, usmUserEngineIDLen,
		  session.securityName);
	snmp_pdu_add_variable(pdu, usmUserPublic, name_length,
			      ASN_OCTET_STR, usmUserPublic_val, 
			      strlen(usmUserPublic_val));	  
    }

    /*
     * do the request 
     */
    status = snmp_synch_response(ss, pdu, &response);
    if (status == STAT_SUCCESS) {
        if (response) {
            if (response->errstat == SNMP_ERR_NOERROR) {
                fprintf(stdout, "%s\n", successNotes[command - 1]);
            } else {
                fprintf(stderr, "Error in packet.\nReason: %s\n",
                        snmp_errstring(response->errstat));
                if (response->errindex != 0) {
                    int             count;
                    netsnmp_variable_list *vars;
                    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("snmpset", ss);
        exitval = 1;
    }

    exitval = 0;
#if defined(HAVE_OPENSSL_DH_H) && defined(HAVE_LIBCRYPTO)
  begone:
#endif /* HAVE_OPENSSL_DH_H && HAVE_LIBCRYPTO */
    if (response)
        snmp_free_pdu(response);

close_session:
    snmp_close(ss);

out:
    SOCK_CLEANUP;
    return exitval;
}
Example #10
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);
}
Example #11
0
fsal_status_t SNMPFSAL_InitClientContext(snmpfsal_op_context_t * p_thr_context)
{

  int rc, i;
  netsnmp_session session;

  /* sanity check */
  if(!p_thr_context)
    Return(ERR_FSAL_FAULT, 0, INDEX_FSAL_InitClientContext);

  /* initialy set the export entry to none */
  p_thr_context->export_context = NULL;

  p_thr_context->user_credential.user = 0;
  p_thr_context->user_credential.group = 0;

  /* initialize the SNMP session  */

  snmp_sess_init(&session);
  session.version = snmp_glob_config.snmp_version;
  session.retries = snmp_glob_config.nb_retries;
  session.timeout = snmp_glob_config.microsec_timeout;
  session.peername = snmp_glob_config.snmp_server;
  if(session.version == SNMP_VERSION_3)
    {
      if(!strcasecmp(snmp_glob_config.auth_proto, "MD5"))
        {
          session.securityAuthProto = usmHMACMD5AuthProtocol;
          session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
        }
      else if(!strcasecmp(snmp_glob_config.auth_proto, "SHA"))
        {
          session.securityAuthProto = usmHMACSHA1AuthProtocol;
          session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
        }
      if(!strcasecmp(snmp_glob_config.enc_proto, "DES"))
        {
          session.securityPrivProto = usmDESPrivProtocol;
          session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
        }
      else if(!strcasecmp(snmp_glob_config.enc_proto, "AES"))
        {
          session.securityPrivProto = usmAES128PrivProtocol;
          session.securityPrivProtoLen = USM_PRIV_PROTO_AES128_LEN;
        }

      session.securityName = snmp_glob_config.username; /* securityName is not allocated */
      session.securityNameLen = strlen(snmp_glob_config.username);
      session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;

      session.securityAuthKeyLen = USM_AUTH_KU_LEN;
      if(generate_Ku(session.securityAuthProto,
                     session.securityAuthProtoLen,
                     (u_char *) snmp_glob_config.auth_phrase,
                     strlen(snmp_glob_config.auth_phrase), session.securityAuthKey,
                     &session.securityAuthKeyLen) != SNMPERR_SUCCESS)
        {
          LogCrit(COMPONENT_FSAL,
                  "FSAL INIT CONTEXT: ERROR creating SNMP passphrase for authentification");
          Return(ERR_FSAL_BAD_INIT, snmp_errno, INDEX_FSAL_InitClientContext);
        }

      session.securityPrivKeyLen = USM_PRIV_KU_LEN;
      if(generate_Ku(session.securityAuthProto,
                     session.securityAuthProtoLen,
                     (u_char *) snmp_glob_config.enc_phrase,
                     strlen(snmp_glob_config.enc_phrase), session.securityPrivKey,
                     &session.securityPrivKeyLen) != SNMPERR_SUCCESS)
        {
          LogCrit(COMPONENT_FSAL, "FSAL INIT CONTEXT: ERROR creating SNMP passphrase for encryption");
          Return(ERR_FSAL_BAD_INIT, snmp_errno, INDEX_FSAL_InitClientContext);
        }
    }
  else                          /* v1 or v2c */
    {
      session.community = snmp_glob_config.community;
      session.community_len = strlen(snmp_glob_config.community);
    }
  p_thr_context->snmp_session = snmp_open(&session);

  if(p_thr_context->snmp_session == NULL)
    {
      char *err_msg;
      snmp_error(&session, &errno, &snmp_errno, &err_msg);

      LogCrit(COMPONENT_FSAL, "FSAL INIT CONTEXT: ERROR creating SNMP session: %s", err_msg);
      Return(ERR_FSAL_BAD_INIT, snmp_errno, INDEX_FSAL_InitClientContext);
    }

  p_thr_context->snmp_request = NULL;
  p_thr_context->snmp_response = NULL;
  p_thr_context->current_response = NULL;

  Return(ERR_FSAL_NO_ERROR, 0, INDEX_FSAL_InitClientContext);

}
Example #12
0
int
main(int argc, char **argv)
{
    netsnmp_session        session, *ss;
    netsnmp_variable_list *var_list = NULL;
    int                    arg, rc, rs_idx;
    u_int                  hash_type;
    char                  *fingerprint, *tmp;

    /*
     * 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();
    default:
        break;
    }

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

    if (strcmp(argv[arg], "certToSecName") == 0) {

        oid           map_type[MAX_OID_LEN];
        u_int         pri;
        size_t        map_type_len;

        if (strcmp(argv[++arg], "add") != 0) {
            fprintf(stderr, "only add is supported at this time\n");
            exit(1);
        }

        pri = atoi(argv[++arg]);
        tmp = argv[++arg];
        hash_type = atoi(tmp);
        fingerprint = argv[++arg];

        DEBUGMSGT(("snmptls",
                   "create pri %d, hash type %d, fp %s",
                   pri, hash_type, fingerprint));
        if (_map_type_str) {
            map_type_len = MAX_OID_LEN;
            if (snmp_parse_oid(_map_type_str, map_type, &map_type_len) 
                == NULL) {
                snmp_perror(_map_type_str);
                exit(1);
            }
            DEBUGMSG(("snmptls", ", map type "));
            DEBUGMSGOID(("snmptls", map_type, map_type_len));
        }
        if (_data)
            DEBUGMSG(("snmptls", ", data %s", _data));

        _parse_storage_type(_storage_type_str);

        DEBUGMSG(("snmptls", "\n"));
        var_list = cert_row_create(pri, hash_type, fingerprint, map_type,
                                   map_type_len, (u_char*)_data, _data_len,
                                   _storage_type, &rs_idx);
    }
    else if (strcmp(argv[arg], "targetParamsFingerprint") == 0) {

        char * params_name;

        if (strcmp(argv[++arg], "add") != 0) {
            fprintf(stderr, "only add is supported at this time\n");
            exit(1);
        }

        params_name = argv[++arg];
        hash_type = atoi(argv[++arg]);
        fingerprint = argv[++arg];
        
        _parse_storage_type(_storage_type_str);

        DEBUGMSGT(("snmptls",
                   "create %s param fp, hash type %d, fp %s\n",
                   params_name, hash_type, fingerprint));

        var_list = params_row_create(params_name, hash_type, fingerprint,
                                     _storage_type, &rs_idx);
    }

    else if (strcmp(argv[arg], "targetAddr") == 0) {

        char * addr_name;

        if (strcmp(argv[++arg], "add") != 0) {
            fprintf(stderr, "only add is supported at this time\n");
            exit(1);
        }

        addr_name = argv[++arg];
        
        _parse_storage_type(_storage_type_str);

        DEBUGMSGT(("snmptls",
                   "create %s addr fp, hash type %d, fp %s, id %s\n",
                   addr_name, _hash_type, _fp_str, _id_str));

        var_list = addr_row_create(addr_name, _hash_type, _fp_str, _id_str,
                                     _storage_type, &rs_idx);
    }

    if (! var_list) {
        fprintf(stderr, "no command specified\n");
        usage();
    }

    rc = netsnmp_row_create(ss, var_list, rs_idx);

    SOCK_CLEANUP;
    return 0;
}
Example #13
0
int sendtrap(struct opts opts, char *community, 
	     int status, char *message)
{
  int return_stat = 0;

#ifdef HAVE_SNMPTRAP
  struct snmp_session session, *ss;
  struct snmp_pdu *pdu;    
  char statusmsg[12];
  oid enterprise[] = {1,3,6,1,4,1,300};
  oid statusoid[] = {1,3,6,1,4,1,300,1};
  oid messageoid[] = {1,3,6,1,4,1,300,2};
  int counter;
  char *messagebuf;
  in_addr_t *pdu_in_addr_t;

  
  for (counter=0; counter < opts.nr_traphosts; counter++) {
    
    snmp_sess_init( &session );
    
    /* strlen() doesn't count the terminating \0, so we do +1 in malloc. */
    session.peername = (char *)malloc(strlen(opts.traphosts[counter])+1);
    strcpy (session.peername, opts.traphosts[counter]);
    session.community = (char *)malloc(strlen(community)+1);
    strcpy (session.community, community);
    session.community_len = strlen(session.community);
    session.version = SNMP_VERSION_1;
    session.retries = 5; 
    session.timeout = 500;
    session.remote_port = 162;
    session.authenticator = NULL;
    
    ss = snmp_open(&session);   
    if (!ss) {
      snmp_sess_perror( "Error: sendtrap/snmp_open", &session );
      return_stat++;
    }
    
    pdu = snmp_pdu_create(SNMP_MSG_TRAP);
    pdu_in_addr_t = (struct in_addr_t *)&pdu->agent_addr;
    pdu->enterprise = malloc(sizeof(enterprise));
    memcpy (pdu->enterprise, enterprise, sizeof(enterprise));
    pdu->enterprise_length = sizeof(enterprise) / sizeof (oid);
    pdu->trap_type = 6;
    pdu->specific_type = 1; 
    pdu->time = 0;
    pdu->contextEngineID = 0x0;
    *pdu_in_addr_t = get_myaddr();

    sprintf(statusmsg, "%d", status);

    snmp_add_var (pdu, statusoid, sizeof(statusoid) / sizeof (oid), 'i', 
		  statusmsg);
    messagebuf = (char *)malloc(strlen(message)+1);
    strcpy(messagebuf,message);
    snmp_add_var (pdu, messageoid, sizeof(messageoid) / sizeof (oid), 's', 
		  message);
    
    if (!snmp_send(ss, pdu)) {
      snmp_sess_perror("Error: sendtrap/snmp_send", &ss );
      return_stat++;
    }
    snmp_close(ss);
  }
#endif
  return return_stat;
}
Example #14
0
int main (int argc, char **argv) {
    oid             objid_enterprise[] = { 1, 3, 6, 1, 4, 1, 3, 1, 1 };
    oid             objid_sysdescr[] = { 1, 3, 6, 1, 2, 1, 1, 1, 0 };
    oid             objid_sysuptime[] = { 1, 3, 6, 1, 2, 1, 1, 3, 0 };
    oid             objid_snmptrap[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 };
    oid             objid_mytrap[] = { 1, 3, 6, 1, 6, 3, 1, 1, 34, 0 };
    int             inform = 0;

    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;

    snmp_sess_init(&session);

    session.version       = SNMP_VERSION_1;
    session.retries       = 2;
    char address[]        = "localhost:162";
    //char address[]        = "192.168.1.174:161";
    char *ptrAddress      = address;
    session.peername      = ptrAddress;
    u_char comm[]         = "public";
    const u_char *community = comm;

    session.community     = community;
    session.community_len = strlen(session.community);

    // set debug tokens
    //debug_register_tokens("transport,tdomain,snmp_sess");
    debug_register_tokens("all");
    snmp_set_do_debugging(1);
    /* windows32 specific initialization (is a noop on unix) */
    SOCK_STARTUP;
    // open snmp session
    ss = snmp_open(&session);
    /*
    ss = snmp_add(&session,
      netsnmp_transport_open_client("snmptrap", session.peername),
      NULL, NULL);
    */
    if (!ss) {
        //snmp_perror("ack");
        snmp_sess_perror("snmptrap", &session);
        //snmp_log(LOG_DEBUG, "Session did not open\n");
        exit(2);
    }
    //snmp_log(LOG_DEBUG, "DEBUG OUTPUT");
    // create the PDU
    //pdu = snmp_pdu_create(1);
    pdu = snmp_pdu_create(SNMP_MSG_TRAP);
    if ( !pdu ) {
        fprintf(stderr, "Failed to create trap PDU\n");
        snmp_perror("pdu error");
        SOCK_CLEANUP;
        exit(1);
    }

    pdu->enterprise = (oid *) malloc(sizeof(objid_enterprise));
    memcpy(pdu->enterprise, objid_enterprise, sizeof(objid_enterprise));
    pdu->enterprise_length = sizeof(objid_enterprise) / sizeof(oid);

    /*
    pdu->specific_type = (oid *) malloc(sizeof(objid_snmptrap));
    memcpy(pdu->specific_type, objid_snmptrap, sizeof(objid_snmptrap));
    */
    pdu->specific_type = 8;

    /*
    pdu->trap_type = (oid *) malloc(sizeof(objid_snmptrap));
    memcpy(pdu->trap_type, objid_snmptrap, sizeof(objid_snmptrap));
    //pdu->enterprise_length = sizeof(objid_enterprise) / sizeof(oid);
    */
    pdu->trap_type = 124;

    // add variables to the PDU
    // int snmp_add_var (netsnmp_pdu *pdu, const oid *name,
    // size_t name_length, char type, const char *value)
    if(snmp_add_var(pdu, objid_mytrap, OID_LENGTH(objid_mytrap), 'i', "100")) {
        snmp_perror("add variable");
        SOCK_CLEANUP;
        exit(1);
    };

    status = snmp_send(ss, pdu) == 0;
    if (status) {
        snmp_sess_perror(inform ? "snmpinform" : "snmptrap", ss);
    }
    snmp_close(ss);
    return 0;
}
Example #15
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() */
Example #16
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);
}
Example #17
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;	
}
Example #18
0
int main(int argc, char **argv) {
    if ( argc < 2) {
        ip = fgets(cm,sizeof cm,stdin);
        // remove \n
        cm[strlen(cm)-1] = '\0';
        //fprintf(stdout, "IP length: %li\n", strlen(cm) );
        if(strlen(cm)< 2) {
        printf("Missing CM IP\nUSAGE: %s <CM_IP>\n", argv[0]);
        exit(1);
        } else {
          printf("Using %s IP\n",ip);
}
    } else {
        strncpy(cm,argv[1],sizeof cm);
    }
    init_snmp("snmpapp");
    snmp_sess_init( &session );
    session.peername = cm;
    session.version=SNMP_VERSION_2c;
    session.community=(unsigned char *) "public";
    session.community_len = strlen((const char *) session.community);
    ss = snmp_open(&session);
    if (!ss) {
       snmp_perror("ack");
       snmp_log(LOG_ERR, "Unable to open snmp session!!\n");
       exit(2);
   }

    pdu = snmp_pdu_create(SNMP_MSG_GET);
    read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len);
    snmp_add_null_var(pdu, anOID, anOID_len);
    status = snmp_synch_response(ss, pdu, &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);
      /* manipulate the information ourselves */
     for(vars = response->variables; vars; vars = vars->next_variable) {
       int count=1;
       if (vars->type == ASN_OCTET_STR) {
         char *sp = malloc(1 + vars->val_len);
         memcpy(sp, vars->val.string, vars->val_len);
         sp[vars->val_len] = '\0';
         //printf("%d: %s\n", count++, sp);
         printf("%s\n", 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
       snmp_sess_perror("snmpget", ss);

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

   /* windows32 specific cleanup (is a noop on unix) */
   SOCK_CLEANUP;

   return EXIT_SUCCESS;

}
int main(int argc, char * argv[]){
    returncode = 0;
    int status;
    struct tree * mib_tree;

    if(argv[1] != NULL && strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0){
        PrintHelp();
        return 0;
    }
    if(argv[1] == NULL || argv[2] == NULL || argv[3] == NULL || argv[4]== NULL) {
        printf("Argument invalide (hostname, variable, warning, critical)\n");
    }

    snmp_sess_init(&session);
    session.version = SNMP_VERSION_1;
    session.community = "public";
    session.community_len = strlen(session.community);
    session.peername = argv[1];

    session_handle = snmp_open(&session);
    add_mibdir("/usr/share/snmp/mibs/");

    pdu = snmp_pdu_create(SNMP_MSG_GET);

    char variable[50];
    snprintf(variable, 50, argv[2]);

    if(strcmp("CPULOAD", variable) == 0){
		processSnmpGet("NETWORK-APPLIANCE-MIB::cpuBusyTimePerCent.0");
		int result = atoi(resultString + 2);
        if(result >= atoi(argv[4])){
            returncode = 2;
        }
        else if (result >= atoi(argv[3])){
            returncode = 1;
        }
        printf("CPU Load : %d %% | cpu_load=%d %%\n", result, result);
    }
    else if(strcmp("PS", variable) == 0){
        processSnmpGet("NETWORK-APPLIANCE-MIB::envFailedPowerSupplyCount.0");
        int result = atoi(resultString);
        if(result >= atoi(argv[4])){
            returncode = 2;
        }
        else if (result >= atoi(argv[3])){
            returncode = 1;
        }
        printf("Failed Power Supply : %d\n", result);

    }
    else if(strcmp("FAN", variable) == 0){
        processSnmpGet("NETWORK-APPLIANCE-MIB::envFailedFanCount.0");
        int result = atoi(resultString);
        if(result >= atoi(argv[4])){
            returncode = 2;
        }
        else if (result >= atoi(argv[3])){
            returncode = 1;
        }
        printf("Failed FAN : %d\n", result);
    }
	else if(strcmp("TEMP", variable) == 0){
		processSnmpGet("NETWORK-APPLIANCE-MIB::envOverTemperature.0");
        int result = atoi(resultString);
        if(result == 2){
            returncode = 2;
			printf("Over Temperatur : YES");
        }
        else{
            printf("Over Temperatur : NO");
        }
	}
	else if(strcmp("NVRAM", variable) == 0){
		processSnmpGet("NETWORK-APPLIANCE-MIB::nvramBatteryStatus.0");
        int result = atoi(resultString);
		if(result > 1){
		    returncode = 2;
		}
		printf("NVRAM battery status: %d\n", result);
	}
    else{
        printf("Invalid argument");
        freeSession();
        return 3;
    }
    freeSession();
    return returncode;
}
Example #20
0
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu;
    netsnmp_pdu    *response;
    int             arg;
    oid             base[MAX_OID_LEN];
    size_t          base_length;
    int             status;
    netsnmp_variable_list *saved = NULL, *vlp = saved, *vlp2;
    int             count = 0;

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

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

    SOCK_STARTUP;

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

    printf("%-18s %15s %15s %15s %5s\n", "Description", "size (kB)",
           "Used", "Available", "Used%");
    if (ucd_mib == 0) {
        /*
         * * Begin by finding all the storage pieces that are of
         * * type hrStorageFixedDisk, which is a standard disk.
         */
        pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
        base_length =
            add(pdu, "HOST-RESOURCES-MIB:hrStorageIndex", NULL, 0);
        memcpy(base, pdu->variables->name, base_length * sizeof(oid));

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

        while (vlp) {
            size_t          units;
            unsigned long   hssize, hsused;
            char            descr[SPRINT_MAX_LEN];
	    int             len;

            pdu = snmp_pdu_create(SNMP_MSG_GET);

            add(pdu, "HOST-RESOURCES-MIB:hrStorageDescr",
                &(vlp->name[base_length]), vlp->name_length - base_length);
            add(pdu, "HOST-RESOURCES-MIB:hrStorageAllocationUnits",
                &(vlp->name[base_length]), vlp->name_length - base_length);
            add(pdu, "HOST-RESOURCES-MIB:hrStorageSize",
                &(vlp->name[base_length]), vlp->name_length - base_length);
            add(pdu, "HOST-RESOURCES-MIB:hrStorageUsed",
                &(vlp->name[base_length]), vlp->name_length - base_length);

            status = snmp_synch_response(ss, pdu, &response);
            if (status != STAT_SUCCESS || !response) {
                snmp_sess_perror("snmpdf", ss);
                exit(1);
            }

            vlp2 = response->variables;
	    len = vlp2->val_len;
	    if (len >= SPRINT_MAX_LEN) len = SPRINT_MAX_LEN-1;
            memcpy(descr, vlp2->val.string, len);
            descr[len] = '\0';

            vlp2 = vlp2->next_variable;
            units = vlp2->val.integer ? *(vlp2->val.integer) : 0;

            vlp2 = vlp2->next_variable;
            hssize = vlp2->val.integer ? *(vlp2->val.integer) : 0;

            vlp2 = vlp2->next_variable;
            hsused = vlp2->val.integer ? *(vlp2->val.integer) : 0;

            printf("%-18s %15lu %15lu %15lu %4lu%%\n", descr,
                   units ? convert_units(hssize, units, 1024) : hssize,
                   units ? convert_units(hsused, units, 1024) : hsused,
                   units ? convert_units(hssize-hsused, units, 1024) : hssize -
                   hsused, hssize ? convert_units(hsused, 100, hssize) :
                   hsused);

            vlp = vlp->next_variable;
            snmp_free_pdu(response);
            count++;
        }
    }

    if (count == 0) {
        size_t          units = 0;
        /*
         * the host resources mib must not be supported.  Lets try the
         * UCD-SNMP-MIB and its dskTable 
         */

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

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

        while (vlp) {
            unsigned long   hssize, hsused;
            char            descr[SPRINT_MAX_LEN];

            pdu = snmp_pdu_create(SNMP_MSG_GET);

            add(pdu, "UCD-SNMP-MIB:dskPath",
                &(vlp->name[base_length]), vlp->name_length - base_length);
            add(pdu, "UCD-SNMP-MIB:dskTotal",
                &(vlp->name[base_length]), vlp->name_length - base_length);
            add(pdu, "UCD-SNMP-MIB:dskUsed",
                &(vlp->name[base_length]), vlp->name_length - base_length);

            status = snmp_synch_response(ss, pdu, &response);
            if (status != STAT_SUCCESS || !response) {
                snmp_sess_perror("snmpdf", ss);
                exit(1);
            }

            vlp2 = response->variables;
            memcpy(descr, vlp2->val.string, vlp2->val_len);
            descr[vlp2->val_len] = '\0';

            vlp2 = vlp2->next_variable;
            hssize = *(vlp2->val.integer);

            vlp2 = vlp2->next_variable;
            hsused = *(vlp2->val.integer);

            printf("%-18s %15lu %15lu %15lu %4lu%%\n", descr,
                   units ? convert_units(hssize, units, 1024) : hssize,
                   units ? convert_units(hsused, units, 1024) : hsused,
                   units ? convert_units(hssize-hsused, units, 1024) : hssize -
                   hsused, hssize ? convert_units(hsused, 100, hssize) :
                   hsused);

            vlp = vlp->next_variable;
            snmp_free_pdu(response);
            count++;
        }
    }

    if (count == 0) {
        fprintf(stderr, "Failed to locate any partitions.\n");
        exit(1);
    }

    snmp_close(ss);
    SOCK_CLEANUP;
    return 0;

}                               /* end main() */
Example #21
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;
}
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;
}
Example #23
0
/*
  Check the CPU load percentage on Linux Devices.
*/
char *checkCPU(struct snmp_session* session) {
	struct snmp_session *s_handle = NULL;
	struct snmp_pdu *pdu = NULL;
	struct snmp_pdu *reply = NULL;
	struct variable_list *vars;
	int status ;
	//char CPU;
	
	oid mib_CPU[] = { 1, 3, 6, 1, 4, 1, 2021, 10, 1, 3, 2};
	
	/* Open snmp session, print error if one occurs */
	s_handle = snmp_open( session );
	if (!s_handle) {
		printf("ERROR - Problem opening session!\n");
		exit(RESULT_CRITICAL);
	}
	
	/* Build PDU and add desired OID's */
	pdu = snmp_pdu_create(SNMP_MSG_GET);

	snmp_add_null_var(pdu, mib_CPU, OID_LENGTH(mib_CPU));
	
	/* Check if snmp synchs correctly, if not exit the program */
	status = snmp_synch_response(s_handle, pdu, &reply);
	if (status == STAT_ERROR) {
		printf("ERROR - Problem while querying device!\n");
		exit(RESULT_CRITICAL);
	}
	else if (status == STAT_TIMEOUT) {
		printf("ERROR - Connection timed out!\n");
		exit(RESULT_CRITICAL);
	}
	else if (reply->errstat != SNMP_ERR_NOERROR) {
		switch (reply->errstat) {
			case SNMP_ERR_NOSUCHNAME:
				printf("ERROR - Device does not support that feature!\n");
				break;
			case SNMP_ERR_TOOBIG:
				printf("ERROR - Result generated too much data!\n");
				break;
			case SNMP_ERR_READONLY:
				printf("ERROR - Value is read only!\n");
				break;
			case SNMP_ERR_BADVALUE:
			case SNMP_ERR_GENERR:
			case SNMP_ERR_NOACCESS:
			case SNMP_ERR_WRONGTYPE:
			case SNMP_ERR_WRONGLENGTH:
			case SNMP_ERR_WRONGENCODING:
			case SNMP_ERR_WRONGVALUE:
			case SNMP_ERR_NOCREATION:
			case SNMP_ERR_INCONSISTENTVALUE:
			case SNMP_ERR_RESOURCEUNAVAILABLE:
			case SNMP_ERR_COMMITFAILED:
			case SNMP_ERR_UNDOFAILED:
			case SNMP_ERR_AUTHORIZATIONERROR:
			case SNMP_ERR_NOTWRITABLE:
			case SNMP_ERR_INCONSISTENTNAME:
			default:
				printf("ERROR - Unknown error!\n");
		}
		exit(RESULT_CRITICAL);
	}
		
	vars = reply->variables;
	if ((vars == NULL) || (vars->type == ASN_NULL)) {
		printf("ERROR - No data recieved from device\n");
		exit(RESULT_UNKNOWN);
	}
	
    for(vars = reply->variables; vars; vars = vars->next_variable) {
    	char *sp = (char *)malloc(1 + vars->val_len);
		memcpy(sp, vars->val.string, vars->val_len);
		sp[vars->val_len] = '\0';
        float CPU;
     	CPU = atof(sp);
    	free(sp);
        if (CPU > crit) {
			exitVal = RESULT_CRITICAL;
			sprintf(retstr, "CRITICAL - CPU Load: %.2f%% | load=%.2f%%\n", CPU, CPU);
		}
	
		else if (CPU > warn) {
			exitVal = RESULT_WARNING;
			sprintf(retstr, "WARNING - CPU Load: %.2f%% | load=%.2f%%\n", CPU, CPU);
		}
		else {
			exitVal = RESULT_OK;
			sprintf(retstr, "OK - CPU Load: %.2f%% | load=%.2f%%\n", CPU , CPU);
		}
	}
	
	snmp_free_pdu(reply);
	snmp_close(s_handle);
	return retstr;
}
Example #24
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() */
Example #25
0
/*
* Generic SNMP object fetcher
*
* st=1   snmpget() - query an agent and return a single value.
* st=2   snmpwalk() - walk the mib and return a single dimensional array 
*          containing the values.
* st=3 snmprealwalk() and snmpwalkoid() - walk the mib and return an 
*          array of oid,value pairs.
* st=5-8 ** Reserved **
* st=11  snmpset() - query an agent and set a single value
*
*/
void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st) {
	zval **a1, **a2, **a3, **a4, **a5, **a6, **a7;
	struct snmp_session session, *ss;
	struct snmp_pdu *pdu=NULL, *response;
	struct variable_list *vars;
    char *objid;
    oid name[MAX_NAME_LEN];
    int name_length;
    int status, count,rootlen=0,gotroot=0;
	oid root[MAX_NAME_LEN];
	char buf[2048];
	char buf2[2048];
	int keepwalking=1;
	long timeout=SNMP_DEFAULT_TIMEOUT;
	long retries=SNMP_DEFAULT_RETRIES;
	int myargc = ZEND_NUM_ARGS();
    char type = (char) 0;
    char *value = (char *) 0;
	
	if (myargc < 3 || myargc > 7 ||
		zend_get_parameters_ex(myargc, &a1, &a2, &a3, &a4, &a5, &a6, &a7) == FAILURE) {
		WRONG_PARAM_COUNT;
	}

	convert_to_string_ex(a1);
	convert_to_string_ex(a2);
	convert_to_string_ex(a3);
	
	if (st == 11) {
		if (myargc < 5) {
			WRONG_PARAM_COUNT;
		}

		convert_to_string_ex(a4);
		convert_to_string_ex(a5);
	
		if(myargc > 5) {
			convert_to_long_ex(a6);
			timeout = (*a6)->value.lval;
		}

		if(myargc > 6) {
			convert_to_long_ex(a7);
			retries = (*a7)->value.lval;
		}

		type = (*a4)->value.str.val[0];
		value = (*a5)->value.str.val;
	} else {
		if(myargc > 3) {
			convert_to_long_ex(a4);
			timeout = (*a4)->value.lval;
		}

		if(myargc > 4) {
			convert_to_long_ex(a5);
			retries = (*a5)->value.lval;
		}
	}

	objid = (*a3)->value.str.val;
	
	if (st >= 2) { /* walk */
		rootlen = MAX_NAME_LEN;
		if ( strlen(objid) ) { /* on a walk, an empty string means top of tree - no error */
			if ( read_objid(objid, root, &rootlen) ) {
				gotroot = 1;
			} else {
				php_error(E_WARNING,"Invalid object identifier: %s\n", objid);
			}
		}
		if (gotroot == 0) {
			memmove((char *)root, (char *)objid_mib, sizeof(objid_mib));
			rootlen = sizeof(objid_mib) / sizeof(oid);
			gotroot = 1;
		}
	}
	
	memset(&session, 0, sizeof(struct snmp_session));

	session.peername = (*a1)->value.str.val;
	session.version = SNMP_VERSION_1;
	/*
	* FIXME: potential memory leak
	* This is a workaround for an "artifact" (Mike Slifcak)
	* in (at least) ucd-snmp 3.6.1 which frees
	* memory it did not allocate
	*/
#ifdef UCD_SNMP_HACK
	session.community = (u_char *)strdup((*a2)->value.str.val); /* memory freed by SNMP library, strdup NOT estrdup */
#else
	session.community = (u_char *)(*a2)->value.str.val;
#endif
	session.community_len = (*a2)->value.str.len;
	session.retries = retries;
	session.timeout = timeout;
	
	session.authenticator = NULL;
	snmp_synch_setup(&session);

	if ((ss = snmp_open(&session)) == NULL) {
		php_error(E_WARNING,"Could not open snmp\n");
		RETURN_FALSE;
	}

	if (st >= 2) {
		memmove((char *)name, (char *)root, rootlen * sizeof(oid));
		name_length = rootlen;
		if (array_init(return_value) == FAILURE) {
			php_error(E_WARNING, "Cannot prepare result array");
			RETURN_FALSE;
		}
	}

	while(keepwalking) {
		keepwalking=0;
		if (st == 1) {
			pdu = snmp_pdu_create(SNMP_MSG_GET);
			name_length = MAX_NAME_LEN;
			if ( !read_objid(objid, name, &name_length) ) {
				php_error(E_WARNING,"Invalid object identifier: %s\n", objid);
				RETURN_FALSE;
			}
			snmp_add_null_var(pdu, name, name_length);
		} else if (st == 11) {
			pdu = snmp_pdu_create(SNMP_MSG_SET);
			if (snmp_add_var(pdu, name, name_length, type, value)) {
				php_error(E_WARNING,"Could not add variable: %s\n", name);
				RETURN_FALSE;
			}
		} else if (st >= 2) {
			pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
			snmp_add_null_var(pdu, name, name_length);
		}
		
retry:
		status = snmp_synch_response(ss, pdu, &response);
		if (status == STAT_SUCCESS) {
			if (response->errstat == SNMP_ERR_NOERROR) {
				for (vars = response->variables; vars; vars = vars->next_variable) {
					if (st >= 2 && st != 11 && 
						(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) {
						continue;       /* not part of this subtree */
					}

					if (st != 11) {
						sprint_value(buf,vars->name, vars->name_length, vars);
					}
#if 0
					Debug("snmp response is: %s\n",buf);
#endif
					if (st == 1) {
						RETVAL_STRING(buf,1);
					} else if (st == 2) {
						add_next_index_string(return_value,buf,1); /* Add to returned array */
					} else if (st == 3)  {
						sprint_objid(buf2, vars->name, vars->name_length);
						add_assoc_string(return_value,buf2,buf,1);
					}
					if (st >= 2 && st != 11) {
						if (vars->type != SNMP_ENDOFMIBVIEW && 
							vars->type != SNMP_NOSUCHOBJECT && vars->type != SNMP_NOSUCHINSTANCE) {
							memmove((char *)name, (char *)vars->name,vars->name_length * sizeof(oid));
							name_length = vars->name_length;
							keepwalking = 1;
						}
					}
				}	
			} else {
				if (st != 2 || response->errstat != SNMP_ERR_NOSUCHNAME) {
					php_error(E_WARNING,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat));
					if (response->errstat == SNMP_ERR_NOSUCHNAME) {
						for (count=1, vars = response->variables; vars && count != response->errindex;
						vars = vars->next_variable, count++);
						if (vars) {
							sprint_objid(buf,vars->name, vars->name_length);
						}
						php_error(E_WARNING,"This name does not exist: %s\n",buf);
					}
					if (st == 1) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GET)) != NULL) {
							goto retry;
						}
					} else if (st == 11) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_SET)) != NULL) {
							goto retry;
						}
					} else if (st >= 2) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETNEXT)) != NULL) {
							goto retry;
						}
					}
					RETURN_FALSE;
				}
			}
		} else if (status == STAT_TIMEOUT) {
			php_error(E_WARNING,"No Response from %s\n", (*a1)->value.str.val);
			RETURN_FALSE;
		} else {    /* status == STAT_ERROR */
			php_error(E_WARNING,"An error occurred, Quitting...\n");
			RETURN_FALSE;
		}
		if (response) {
			snmp_free_pdu(response);
		}
	} /* keepwalking */
	snmp_close(ss);
}
Example #26
0
unsigned long
Evaluate_Expression(struct expValueTable_data *vtable_data)
{

    struct header_complex_index *hcindex;
    struct expObjectTable_data *objstorage, *objfound;
    struct expValueTable_data *valstorage;
    valstorage = vtable_data;

    char           *expression;
    char           *result, *resultbak;
    char           *temp, *tempbak;
    char            intchar[10];
    int             i = 0, j, k, l;
    long            value;
    unsigned long   result_u_long;
    temp = malloc(100);
    result = malloc(100);
    tempbak = temp;
    memset(result, 0, 100);
    *result = '\0';
    resultbak = result;

    expression = vtable_data->expression_data->expExpression;

    while (*expression != '\0') {
        if (*expression == '$') {
            objfound = NULL;
            i++;
            for (j = 1; j < 100; j++) {
                if ((*(expression + j) == '+') ||
                    (*(expression + j) == '-') ||
                    (*(expression + j) == '*') ||
                    (*(expression + j) == '/') ||
                    (*(expression + j) == '(') ||
                    (*(expression + j) == ')') ||
                    *(expression + j) == '\0') {
                    break;
                }
            }
            strncpy(temp, expression + 1, j - 1);
            *(temp + j - 1) = '\0';
            l = atoi(temp);
            expression = expression + j;
            /*
             *   here use snmpget to get value
             */
            for (hcindex = expObjectTableStorage; hcindex != NULL;
                 hcindex = hcindex->next) {
                objstorage = (struct expObjectTable_data *) hcindex->data;
                if (!strcmp
                    (objstorage->expExpressionOwner,
                     valstorage->expExpressionOwner)
                    && (objstorage->expExpressionOwnerLen ==
                        valstorage->expExpressionOwnerLen)
                    && !strcmp(objstorage->expExpressionName,
                               valstorage->expExpressionName)
                    && (objstorage->expExpressionNameLen ==
                        valstorage->expExpressionNameLen)
                    && (l == objstorage->expObjectIndex)) {
                    objfound = objstorage;
                    break;
                }
            }


            if (!objfound) {
                /* have err */
                return 0;
            }
            struct snmp_session *ss;
            struct snmp_pdu *pdu;
            struct snmp_pdu *response;

            oid             anOID[MAX_OID_LEN];
            size_t          anOID_len;

            memcpy(anOID, objfound->expObjectID,
                   objfound->expObjectIDLen * sizeof(oid));
            anOID_len = objfound->expObjectIDLen;
            if (objfound->expObjectIDWildcard == EXPOBJCETIDWILDCARD_TRUE) {
                anOID_len =
                    anOID_len + valstorage->expValueInstanceLen - 2;
                memcpy(anOID + objfound->expObjectIDLen,
                       valstorage->expValueInstance + 2,
                       (valstorage->expValueInstanceLen -
                        2) * sizeof(oid));
            }
            struct variable_list *vars;
            int             status;

            /*
             * Initialize the SNMP library
             */

            /*
             * Initialize a "session" that defines who we're going to talk to
             */
            session.version = vtable_data->expression_data->pdu_version;

            /*
             * set the SNMPv1 community name used for authentication 
             */
            session.community =
                vtable_data->expression_data->pdu_community;
            session.community_len =
                vtable_data->expression_data->pdu_community_len;
            /*
             * Open the session
             */
            SOCK_STARTUP;
            ss = snmp_open(&session);   /* establish the session */

            if (!ss) {
                /* err */
                exit(2);
            }
            pdu = snmp_pdu_create(SNMP_MSG_GET);
            snmp_add_null_var(pdu, anOID, anOID_len);

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

            /*
             * Process the response.
             */
            if (status == STAT_SUCCESS
                && response->errstat == SNMP_ERR_NOERROR) {
                /*
                 * SUCCESS: Print the result variables
                 */

                vars = response->variables;
                value = *(vars->val.integer);
                sprintf(intchar, "%lu", value);
                for (k = 1; k <= strlen(intchar); k++) {
                    *result = intchar[k - 1];
                    result++;
                }

            } else {
                /*
                 * FAILURE: print what went wrong!
                 */

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

            }

            /*
             * Clean up:
             *  1) free the response.
             *  2) close the session.
             */
            if (response)
                snmp_free_pdu(response);
            snmp_close(ss);

            SOCK_CLEANUP;

        } else {
            *result = *expression;
            result++;
            expression++;
        }
    }
    result_u_long = get_result(resultbak);
    free(tempbak);
    free(resultbak);
    return result_u_long;
}
Example #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;
}
Example #28
0
void
build_valuetable(void)
{
    struct expExpressionTable_data *expstorage, *expfound;
    struct expObjectTable_data *objstorage, *objfound = NULL;
    struct header_complex_index *hcindex, *object_hcindex;
    char           *expression;
    size_t          expression_len;
    oid            *index;


    char           *result, *resultbak;
    char           *temp, *tempbak;
    int             i = 0, j, l;
    temp = malloc(100);
    result = malloc(100);
    tempbak = temp;
    memset(result, 0, 100);
    *result = '\0';
    resultbak = result;


    DEBUGMSGTL(("expValueTable", "building valuetable...  \n"));

    for (hcindex = expExpressionTableStorage; hcindex != NULL;
         hcindex = hcindex->next) {
        expstorage = (struct expExpressionTable_data *) hcindex->data;
        if (expstorage->expExpressionEntryStatus == RS_ACTIVE) {
            expression = expstorage->expExpression;
            expression_len = expstorage->expExpressionLen;
            while (*expression != '\0') {
                if (*expression == '$') {
                    i++;
                    for (j = 1; j < 100; j++) {
                        if ((*(expression + j) == '+') ||
                            (*(expression + j) == '-') ||
                            (*(expression + j) == '*') ||
                            (*(expression + j) == '/') ||
                            (*(expression + j) == '(') ||
                            (*(expression + j) == ')') ||
                            *(expression + j) == '\0') {
                            break;
                        }
                    }
                    strncpy(temp, expression + 1, j - 1);
                    *(temp + j - 1) = '\0';
                    l = atoi(temp);
                    for (object_hcindex = expObjectTableStorage;
                         object_hcindex != NULL;
                         object_hcindex = object_hcindex->next) {
                        objstorage =
                            (struct expObjectTable_data *) object_hcindex->
                            data;
                        if (!strcmp
                            (objstorage->expExpressionOwner,
                             expstorage->expExpressionOwner)
                            && (objstorage->expExpressionOwnerLen ==
                                expstorage->expExpressionOwnerLen)
                            && !strcmp(objstorage->expExpressionName,
                                       expstorage->expExpressionName)
                            && (objstorage->expExpressionNameLen ==
                                expstorage->expExpressionNameLen)
                            && (l == objstorage->expObjectIndex)) {
                            if (objfound == NULL) {
                                expfound = expstorage;
                                objfound = objstorage;
                            }
                            if (objstorage->expObjectIDWildcard ==
                                EXPOBJCETIDWILDCARD_TRUE)
                                objfound = objstorage;
                        }
                    }
                    expression = expression + j;
                } else {
                    expression++;
                }
            };
        }

        if (!objfound) {
            continue;
        }
        if (objfound->expObjectIDWildcard == EXPOBJCETIDWILDCARD_FALSE) {
            index = calloc(1, MAX_OID_LEN);
            *index = 0;
            *(index + 1) = 0;
            *(index + 2) = 0;
            expValueTable_add(expstorage, objfound->expExpressionOwner,
                              objfound->expExpressionOwnerLen,
                              objfound->expExpressionName,
                              objfound->expExpressionNameLen, index, 3);
        } else {
            oid            *targetOID;
            size_t          taggetOID_len;
            targetOID = objfound->expObjectID;
            struct snmp_pdu *pdu;
            struct snmp_pdu *response;
            oid            *next_OID;
            size_t          next_OID_len;
            taggetOID_len = objfound->expObjectIDLen;
            int             status;
            struct snmp_session *ss;
            /*
             * Initialize the SNMP library
             */


            /*
             * set the SNMP version number 
             */
            session.version = expstorage->pdu_version;

            /*
             * set the SNMPv1 community name used for authentication 
             */
            session.community = expstorage->pdu_community;
            session.community_len = expstorage->pdu_community_len;

            /*
             * Open the session
             */
            SOCK_STARTUP;
            ss = snmp_open(&session);   /* establish the session */
            if (!ss) {
                snmp_perror("ack");
                snmp_log(LOG_ERR, "something horrible happened!!!\n");
                exit(2);
            }

            next_OID = targetOID;
            next_OID_len = taggetOID_len;
            do {
                index = calloc(1, MAX_OID_LEN);
                pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);

                snmp_add_null_var(pdu, next_OID, next_OID_len);

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

                /*
                 * Process the response.
                 */
                if (status == STAT_SUCCESS
                    && response->errstat == SNMP_ERR_NOERROR) {
                    /*
                     * SUCCESS: Print the result variables
                     */

                    if (((response->variables->type >= SNMP_NOSUCHOBJECT &&
                          response->variables->type <= SNMP_ENDOFMIBVIEW)
                         || snmp_oid_compare(targetOID, taggetOID_len,
                                             response->variables->name,
                                             taggetOID_len) != 0)) {
                        break;
                    }
                    /* add to expValueTable */

                    *index = 0;
                    *(index + 1) = 0;
                    memcpy(index + 2,
                           response->variables->name + taggetOID_len,
                           (response->variables->name_length -
                            taggetOID_len) * sizeof(oid));
                    expValueTable_add(expstorage,
                                      objfound->expExpressionOwner,
                                      objfound->expExpressionOwnerLen,
                                      objfound->expExpressionName,
                                      objfound->expExpressionNameLen,
                                      index,
                                      response->variables->name_length -
                                      taggetOID_len + 2);

                    next_OID = response->variables->name;

                    next_OID_len = response->variables->name_length;




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

        }

    }

}
netsnmp_session *mp_snmp_init(void) {

    netsnmp_session session, *ss;
    int status;

    init_snmp(progname);

    snmp_sess_init( &session );

    if (mp_snmp_community == NULL)
        mp_snmp_community = mp_strdup("public");

    mp_asprintf(&(session.peername), "%s:%d", hostname, port);

    switch(mp_snmp_version) {
        case SNMP_VERSION_1:
            session.version = SNMP_VERSION_1;
            session.community = (u_char *)mp_snmp_community;
            session.community_len = strlen((char *)session.community);
            break;
        case SNMP_VERSION_2c:
            session.version = SNMP_VERSION_2c;
            session.community = (u_char *)mp_snmp_community;
            session.community_len = strlen((char *)session.community);
            break;
        case SNMP_VERSION_3:
            session.version = SNMP_VERSION_3;

            session.securityName = mp_strdup(mp_snmp_secname);
            session.securityNameLen = strlen(session.securityName);

            /* set the security level */
            session.securityLevel = mp_snmp_seclevel;
            session.contextName = mp_strdup(mp_snmp_context);

            session.contextNameLen = strlen(session.contextName);

            /* set the authentication method */
            session.securityAuthProto = mp_snmp_authproto;
            session.securityAuthProtoLen = 10;
            session.securityAuthKeyLen = USM_AUTH_KU_LEN;

            status = generate_Ku(session.securityAuthProto,
                    session.securityAuthProtoLen,
                    (u_char *) mp_snmp_authpass, strlen(mp_snmp_authpass),
                    session.securityAuthKey,
                    &session.securityAuthKeyLen);
            if (status != SNMPERR_SUCCESS) {
                snmp_perror(progname);
                snmp_log(LOG_ERR,
                        "Error generating Ku from authentication pass phrase. \n%s\n",snmp_api_errstring(status));
                exit(1);
            }

            break;
    }

    netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
                           NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);

    SOCK_STARTUP;
    ss = snmp_open(&session);

    if (!ss) {
      snmp_sess_perror("ack", &session);
      SOCK_CLEANUP;
      exit(1);
    }

    free(session.peername);

    if (mp_snmp_retries > 0)
        ss->retries = mp_snmp_retries;
    if (mp_snmp_timeout > 0)
        ss->timeout = (long)(mp_snmp_timeout * 1000000L);

    return ss;

}
Example #30
0
void *snmp_bc_open(GHashTable *handler_config)
{
    struct oh_handler_state *handle;
    struct snmp_bc_hnd *custom_handle;
    char *root_tuple;

    root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
    if(!root_tuple) {
        dbg("ERROR: Cannot open snmp_bc plugin. No entity root found in configuration.");
        return NULL;
    }

    handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
    custom_handle =
        (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
    if(!handle || !custom_handle) {
        dbg("Could not allocate memory for handle or custom_handle.");
        return NULL;
    }
    handle->data = custom_handle;

    handle->config = handler_config;

    /* Initialize RPT cache */
    handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));

    /* Initialize SEL cache */
    handle->selcache =  oh_sel_create(OH_SEL_MAX_SIZE);

    /* Initialize String-to-Event hash table */
    if (str2event_hash_init()) {
        dbg("Couldn't initialize str2event hash table.");
        return NULL;
    }

    /* Initialize BC_Event_Number-to-HPI_Event hash table */
    if (event2hpi_hash_init()) {
        dbg("Couldn't initialize event2hpi hash table.");
        return NULL;
    }

    /* Initialize snmp library */
    init_snmp("oh_snmp_bc");

    snmp_sess_init(&(custom_handle->session)); /* Setting up all defaults for now. */
    custom_handle->session.peername = (char *)g_hash_table_lookup(handle->config, "host");

    /* set the SNMP version number */
    custom_handle->session.version = SNMP_VERSION_1;

    /* set the SNMPv1 community name used for authentication */
    custom_handle->session.community = (char *)g_hash_table_lookup(handle->config, "community");
    custom_handle->session.community_len = strlen(custom_handle->session.community);

    /* windows32 specific net-snmp initialization (is a noop on unix) */
    SOCK_STARTUP;

    custom_handle->ss = snmp_open(&(custom_handle->session));

    if(!custom_handle->ss) {
        snmp_perror("ack");
        snmp_log(LOG_ERR, "something horrible happened!!!\n");
        dbg("Unable to open snmp session.");
        return NULL;
    }

    /* Set BladeCenter Type */
    {
        struct snmp_value  get_value;

        if ((snmp_get(custom_handle->ss, SNMP_BC_BLADECENTER_TYPE, &get_value) != 0) ||
                (get_value.type != ASN_OCTET_STR)) {
            dbg("SNMP could not read %s; Type=%d.\n",
                SNMP_BC_BLADECENTER_TYPE, get_value.type);
            return NULL;
        }

        if (!strcmp(get_value.string, SNMP_BC_BCE_MODEL)) {
            strcpy(bc_type, SNMP_BC_PLATFORM_BCE);
        }
        else if (!strcmp(get_value.string, SNMP_BC_BCT_MODEL_AC)) {
            strcpy(bc_type, SNMP_BC_PLATFORM_BCT);
        }
        else if (!strcmp(get_value.string, SNMP_BC_BCT_MODEL_DC)) {
            strcpy(bc_type, SNMP_BC_PLATFORM_BCT);
        }
        else {
            dbg("Unrecognized BladeCenter Type=%s.\n", get_value.string);
            return NULL;
        }
    }

    return handle;
}