コード例 #1
0
ファイル: tunnel.c プロジェクト: michalklempa/net-snmp
/*
 * update a struct tunnel. its index and ifname elements have to be set.
 */
static struct tunnel *
updateTunnel(struct tunnel *tunnel)
{
    struct ip_tunnel_parm *parm;
    int             fd;
    struct ifreq    ifrq;

    /*
     * NOTE: getTunnelParm() may adjust the passed ifname. 
     */
    parm = getTunnelParm(tunnel->ifname);
    if (!parm) {
	DEBUGMSGTL(("tunnel",
		    "updateTunnel(): getTunnelParm(\"%s\") returned NULL\n",
		    tunnel->ifname));
        tunnel->active = 0;
        return NULL;
    }

    tunnel->active = 1;

    tunnel->local = parm->iph.saddr;
    tunnel->remote = parm->iph.daddr;

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        DEBUGMSGTL(("snmpd", "socket open failure in updateTunnels()\n"));
        return NULL;
    } else {
        /*
         * NOTE: this ioctl does not guarantee 6 bytes of a physaddr.
         * In particular, a 'sit0' interface only appears to get back
         * 4 bytes of sa_data. We don't use sa_data here, or we'd
         * need to memset it to 0 before the ioct.
         */
        strlcpy(ifrq.ifr_name, tunnel->ifname, sizeof(ifrq.ifr_name));
        if (ioctl(fd, SIOCGIFHWADDR, &ifrq) == 0)
            switch (ifrq.ifr_hwaddr.sa_family) {
            case ARPHRD_TUNNEL:
                tunnel->encaps = 2;
                break;;         /* direct */
            case ARPHRD_TUNNEL6:
                tunnel->encaps = 2;
                break;;         /* direct */
            case ARPHRD_IPGRE:
                tunnel->encaps = 3;
                break;;         /* gre */
            case ARPHRD_SIT:
                tunnel->encaps = 2;
                break;;         /* direct */
            default:
                tunnel->encaps = 1;     /* other */
            }
        close(fd);
    }

    tunnel->hoplimit = parm->iph.ttl;
    tunnel->security = 1;
    tunnel->tos = (parm->iph.tos & 1) ? -1 : parm->iph.tos;
    /*
     * XXX: adjust tos mapping (kernel <-> TUNNEL-MIB::tunnelIfTOS) 
     */

    return tunnel;
}
コード例 #2
0
ファイル: ide_linux.c プロジェクト: vejta66/hp-ams
int netsnmp_arch_idedisk_container_load(netsnmp_container* container)
{
    cpqIdeControllerTable_entry *cntlr;
    cpqIdeAtaDiskTable_entry *disk;
    cpqIdeAtaDiskTable_entry *old;
    netsnmp_container *cntlr_container;
    netsnmp_iterator  *it;
    netsnmp_cache *cntlr_cache;
    netsnmp_container *fw_container = NULL;
    netsnmp_cache *fw_cache = NULL;

    char buffer[256];
    char attribute[256];
    char *value;
    long long size;
    char *scsi;
    char *generic;

    int Cntlr, Bus, Index, Target;
    char * OS_name;
    char *serialnum = NULL;
    int j;
    long  rc = 0;
    int disk_fd;
    int Health = 0, Temp = -1, Mcot = -1, Wear = -1;
    unsigned char *Temperature;

    netsnmp_index tmp;
    oid oid_index[2];

    DEBUGMSGTL(("idedisk:container:load", "loading\n"));
    /*
     * find  the HBa container.
     */
    SataDiskCondition = CPQ_REG_OK;

    cntlr_cache = netsnmp_cache_find_by_oid(cpqIdeControllerTable_oid, 
                                            cpqIdeControllerTable_oid_len);
    if (cntlr_cache == NULL) {
        return -1;
    }
    cntlr_container = cntlr_cache->magic;
    DEBUGMSGTL(("idedisk:container:load", "Container=%p\n",cntlr_container));
    DEBUGMSGTL(("idedisk:container:load", 
                "ContainerSize=%ld\n", CONTAINER_SIZE(cntlr_container)));
    it = CONTAINER_ITERATOR( cntlr_container );
    cntlr = ITERATOR_FIRST( it );
    DEBUGMSGTL(("idedisk:container:load", "cntlr=%p\n",cntlr));
    while ( cntlr != NULL ) {
        current_Cntlr = cntlr->host;
        DEBUGMSGTL(("idedisk:container:load", 
                    "Starting Loop %s\n", current_Cntlr));
        cntlr->cpqIdeControllerOverallCondition =
                  MAKE_CONDITION(cntlr->cpqIdeControllerOverallCondition,
                                 cntlr->cpqIdeControllerCondition);
        /* Now chack for those HBA's in  the SCSI diskss */
        if ((NumScsiDisk = scandir(ScsiDiskDir, &ScsiDisklist, 
                                   disk_select, alphasort)) <= 0) {
            free(ScsiDisklist);
            cntlr = ITERATOR_NEXT( it );
            continue;
        }	

        for (j= 0; j< NumScsiDisk; j++) {
            memset(&buffer, 0, sizeof(buffer));
            strncpy(buffer, ScsiDiskDir, sizeof(buffer) - 1);
            strncat(buffer, ScsiDisklist[j]->d_name, 
                    sizeof(buffer) - strlen(buffer) - 1);
            DEBUGMSGTL(("idedisk:container:load", "Working on disk %s\n", 
                        ScsiDisklist[j]->d_name));

            sscanf(ScsiDisklist[j]->d_name,"%d:%d:%d:%d",
                        &Cntlr, &Bus, &Index, &Target);

            DEBUGMSGTL(("idedisk:container:load",
                        "looking for cntlr=%ld, Disk = %d\n", 
                        cntlr->cpqIdeControllerIndex, Index));
            oid_index[0] = cntlr->cpqIdeControllerIndex;
            oid_index[1] = Index;
            tmp.len = 2;
            tmp.oids = &oid_index[0];

            old = CONTAINER_FIND(container, &tmp);
            DEBUGMSGTL(("idedisk:container:load", "Old disk=%p\n",old));
            if (old != NULL ) {
                DEBUGMSGTL(("idedisk:container:load", "Re-Use old entry\n"));
                old->OldStatus = old->cpqIdeAtaDiskStatus;
                disk = old;
            } else {
                disk = cpqIdeAtaDiskTable_createEntry(container,
                            (oid)cntlr->cpqIdeControllerIndex, 
                            Index);
                if (disk == NULL) 
                    continue;

                DEBUGMSGTL(("idedisk:container:load", "Entry created\n"));

		scsi = ScsiDisklist[j]->d_name;

                if ((value = get_DiskModel(scsi)) != NULL) {
                    strncpy(disk->cpqIdeAtaDiskModel, value,
                            sizeof(disk->cpqIdeAtaDiskModel) - 1);
                    disk->cpqIdeAtaDiskModel_len = 
                                               strlen(disk->cpqIdeAtaDiskModel);
                    free(value);
                }

                if ((value = get_DiskState(scsi)) != NULL) {
                    if (strcmp(value, "running") == 0)
                        disk->cpqIdeAtaDiskStatus = SAS_PHYS_STATUS_OK;
                    free(value);
                }

                disk->cpqIdeAtaDiskCapacity = get_BlockSize(scsi) >> 11;

                generic = get_ScsiGeneric(scsi);
                if (generic != NULL) {
                    memset(disk->cpqIdeAtaDiskOsName, 0, 256);
                    disk->cpqIdeAtaDiskOsName_len =
                                        sprintf(disk->cpqIdeAtaDiskOsName,
                                                "/dev/%s",
                                                generic);
                    free(generic);
                }
                DEBUGMSGTL(("idedisk:container:load", "generic dev is %s\n",
                                disk->cpqIdeAtaDiskOsName));

            }
            if ((disk_fd = open(disk->cpqIdeAtaDiskOsName, 
                                O_RDWR | O_NONBLOCK)) >= 0) {
                if ((serialnum = get_unit_sn(disk_fd)) != NULL  ) {
                    strncpy(disk->cpqIdeAtaDiskSerialNumber, serialnum, 40);
                    disk->cpqIdeAtaDiskSerialNumber_len = strlen(serialnum);
                    free(serialnum);
                }

                if ((value = get_sata_DiskRev(disk_fd)) != NULL) {
                    strncpy(disk->cpqIdeAtaDiskFwRev, value,
                            sizeof(disk->cpqIdeAtaDiskFwRev) - 1);
                    disk->cpqIdeAtaDiskFwRev_len = 
                                               strlen(disk->cpqIdeAtaDiskFwRev);
                    free(value);
                }

                disk->cpqIdeAtaDiskPowerOnHours = get_sata_pwron(disk_fd);

                disk->cpqIdeAtaDiskSSDEstTimeRemainingHours = -1;

                if ((Temperature = get_sata_temp(disk_fd)) != NULL ) {
                    Temp = sata_parse_current(Temperature);
                    Mcot = sata_parse_mcot(Temperature);
                    disk->cpqIdeAtaDiskCurrTemperature = Temp;
                    disk->cpqIdeAtaDiskTemperatureThreshold = Mcot;
                    free(Temperature);
                }

                if (is_unit_ssd(disk_fd)) {
                    disk->cpqIdeAtaDiskMediaType = PHYS_DRV_SOLID_STATE;
                    Wear = get_sata_ssd_wear(disk_fd);
                    disk->cpqIdeAtaDiskSSDPercntEndrnceUsed = Wear;
                    disk->cpqIdeAtaDiskSSDWearStatus = SSD_WEAR_OK;
                    if (disk->cpqIdeAtaDiskSSDPercntEndrnceUsed >= 95)
                        disk->cpqIdeAtaDiskSSDWearStatus = 
                                                        SSD_WEAR_5PERCENT_LEFT;
                    if (disk->cpqIdeAtaDiskSSDPercntEndrnceUsed >= 98)
                        disk->cpqIdeAtaDiskSSDWearStatus = 
                                                        SSD_WEAR_2PERCENT_LEFT;
                    if (disk->cpqIdeAtaDiskSSDPercntEndrnceUsed >= 100)
                        disk->cpqIdeAtaDiskSSDWearStatus = SSD_WEAR_OUT;
                } else {
                    disk->cpqIdeAtaDiskMediaType = PHYS_DRV_ROTATING_PLATTERS;
                    disk->cpqIdeAtaDiskSSDPercntEndrnceUsed = 
                                                    get_sata_ssd_wear(disk_fd);
                    disk->cpqIdeAtaDiskSSDWearStatus = SSD_WEAR_OTHER;
                } 

                if ((Health = get_sata_health(disk_fd)) >= 0) {
                    disk->cpqIdeAtaDiskSmartEnabled = 2;
                    if (Health == 0) {
                        disk->cpqIdeAtaDiskStatus = 2; /* OK */
                        disk->cpqIdeAtaDiskCondition = 2; /* OK */
                    } else {
                        disk->cpqIdeAtaDiskStatus = 3; /* predictive failure */
                        disk->cpqIdeAtaDiskCondition = 3; /*  Degraded*/
                    }
                } else {
                    disk->cpqIdeAtaDiskSmartEnabled = 1;
                    disk->cpqIdeAtaDiskStatus = 1; /* Other */
                    disk->cpqIdeAtaDiskCondition = 1; /* Other */
                }
                close(disk_fd);
            }
            disk->cpqIdeAtaDiskChannel = 4; /* Serial */
            disk->cpqIdeAtaDiskTransferMode = 1;
            disk->cpqIdeAtaDiskLogicalDriveMember = 1;
            disk->cpqIdeAtaDiskIsSpare = 1;
            disk->cpqIdeAtaDiskType = 3;  /* Only SATA drives */
            disk->cpqIdeAtaDiskSataVersion = 3; /*assume version 2 */
            disk->cpqIdeAtaDiskNumber = 4 + Index;

            disk->cpqIdeAtaDiskCondition = 
                            MAKE_CONDITION(disk->cpqIdeAtaDiskCondition, 
                                           disk->cpqIdeAtaDiskStatus);
            cntlr->cpqIdeControllerOverallCondition =
                MAKE_CONDITION(cntlr->cpqIdeControllerOverallCondition,
                               disk->cpqIdeAtaDiskStatus);
            if (old == NULL) {
                rc = CONTAINER_INSERT(container, disk);
                DEBUGMSGTL(("idedisk:container:load", "entry inserted\n"));
            }
            if (((old == NULL) || (disk->OldStatus == 2)) &&
                    (disk->cpqIdeAtaDiskStatus == 3)){
                SendIdeTrap(IDE_TRAP_DISK_STATUS_CHANGE, disk);
                DEBUGMSGTL(("idedisk:container:load", "Sending Trap\n"));
            }
            free(ScsiDisklist[j]);
            SataDiskCondition |=  (1 < (disk->cpqIdeAtaDiskCondition -1));
        }
        free(ScsiDisklist);
        cntlr = ITERATOR_NEXT( it );
    }
    ITERATOR_RELEASE( it );

    if ((SataDiskCondition & (1 < (CPQ_REG_DEGRADED -1))) != 0)
        cpqHoMibHealthStatusArray[CPQMIBHEALTHINDEX] = CPQ_REG_DEGRADED;

    DEBUGMSGTL(("idedisk:container", "init\n"));
    return 1;
}
コード例 #3
0
ファイル: cpqNicIfLogMapTable.c プロジェクト: marker55/hp-ams
/** handles requests for the cpqNicIfLogMapTable table */
int
cpqNicIfLogMapTable_handler(netsnmp_mib_handler *handler,
                            netsnmp_handler_registration *reginfo,
                            netsnmp_agent_request_info *reqinfo,
                            netsnmp_request_info *requests)
{

    netsnmp_request_info *request;
    netsnmp_table_request_info *table_info;
    cpqNicIfLogMapTable_entry *table_entry;

    DEBUGMSGTL(("cpqNicIfLogMapTable:handler", "Processing request (%d)\n",
                reqinfo->mode));

    switch (reqinfo->mode) {
        /*
         * Read-support (also covers GetNext requests)
         */
    case MODE_GET:
        for (request = requests; request; request = request->next) {
            if (request->processed)
                continue;
            table_entry = (cpqNicIfLogMapTable_entry *)
                netsnmp_container_table_extract_context(request);
            table_info = netsnmp_extract_table_info(request);
            if ((NULL == table_entry) || (NULL == table_info)) {
                snmp_log(LOG_ERR,
                         "could not extract table entry or info for cpqNicIfLogMapTable\n");
                snmp_set_var_typed_value(request->requestvb,
                                         SNMP_ERR_GENERR, NULL, 0);
                continue;
            }

            switch (table_info->colnum) {
            case COLUMN_CPQNICIFLOGMAPINDEX:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapIndex);
                break;
            case COLUMN_CPQNICIFLOGMAPIFNUMBER:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapIfNumber,
                                         table_entry->
                                         cpqNicIfLogMapIfNumber_len);
                break;
            case COLUMN_CPQNICIFLOGMAPDESCRIPTION:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapDescription,
                                         table_entry->
                                         cpqNicIfLogMapDescription_len);
                break;
            case COLUMN_CPQNICIFLOGMAPGROUPTYPE:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapGroupType);
                break;
            case COLUMN_CPQNICIFLOGMAPADAPTERCOUNT:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapAdapterCount);
                break;
            case COLUMN_CPQNICIFLOGMAPADAPTEROKCOUNT:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapAdapterOKCount);
                break;
            case COLUMN_CPQNICIFLOGMAPPHYSICALADAPTERS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                             cpqNicIfLogMapPhysicalAdapters,
                                         table_entry->
                                             cpqNicIfLogMapPhysicalAdapters_len);
                break;
            case COLUMN_CPQNICIFLOGMAPMACADDRESS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapMACAddress,
                                         table_entry->
                                         cpqNicIfLogMapMACAddress_len);
                break;
            case COLUMN_CPQNICIFLOGMAPSWITCHOVERMODE:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapSwitchoverMode);
                break;
            case COLUMN_CPQNICIFLOGMAPCONDITION:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapCondition);
                break;
            case COLUMN_CPQNICIFLOGMAPSTATUS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapStatus);
                break;
            case COLUMN_CPQNICIFLOGMAPNUMSWITCHOVERS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_COUNTER,
                                           table_entry->
                                           cpqNicIfLogMapNumSwitchovers);
                break;
            case COLUMN_CPQNICIFLOGMAPHWLOCATION:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapHwLocation,
                                         table_entry->
                                         cpqNicIfLogMapHwLocation_len);
                break;
            case COLUMN_CPQNICIFLOGMAPSPEED:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_GAUGE,
                                           table_entry->
                                           cpqNicIfLogMapSpeed);
                break;
            case COLUMN_CPQNICIFLOGMAPVLANCOUNT:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapVlanCount);
                break;
            case COLUMN_CPQNICIFLOGMAPVLANS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->cpqNicIfLogMapVlans,
                                         table_entry->
                                         cpqNicIfLogMapVlans_len);
                break;
            case COLUMN_CPQNICIFLOGMAPLASTCHANGE:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb,
                                           ASN_TIMETICKS,
                                           table_entry->
                                           cpqNicIfLogMapLastChange);
                break;
            case COLUMN_CPQNICIFLOGMAPADVANCEDTEAMING:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_INTEGER,
                                           table_entry->
                                           cpqNicIfLogMapAdvancedTeaming);
                break;
            case COLUMN_CPQNICIFLOGMAPSPEEDMBPS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb, ASN_GAUGE,
                                           table_entry->
                                           cpqNicIfLogMapSpeedMbps);
                break;
            case COLUMN_CPQNICIFLOGMAPIPV6ADDRESS:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapIPV6Address,
                                         table_entry->
                                         cpqNicIfLogMapIPV6Address_len);
                break;
            case COLUMN_CPQNICIFLOGMAPLACNUMBER:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapLACNumber,
                                         table_entry->
                                         cpqNicIfLogMapLACNumber_len);
                break;
            case COLUMN_CPQNICIFLOGMAPPCILOCATION:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR,
                                         table_entry->
                                         cpqNicIfLogMapPciLocation,
                                         table_entry->
                                         cpqNicIfLogMapPciLocation_len);
                break;
            default:
                netsnmp_set_request_error(reqinfo, request,
                                          SNMP_NOSUCHOBJECT);
                break;
            }
        }
        break;

    }
    return SNMP_ERR_NOERROR;
}
コード例 #4
0
/************************************************************
 *
 * Initialize the saHpiSensorReadingNormalMinTable table by defining its contents and how it's structured
 */
void
initialize_table_saHpiSensorReadingNormalMinTable(void)
{
	netsnmp_table_registration_info *table_info;

	DEBUGMSGTL ((AGENT, "initialize_table_saHpiSensorReadingNormalMinTable, called\n"));

	if (my_handler) {
		snmp_log(LOG_ERR, "initialize_table_saHpiSensorReadingNormalMinTable_handler called again\n");
		return;
	}

	memset(&cb, 0x00, sizeof(cb));

	/** create the table structure itself */
	table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);

	/* if your table is read only, it's easiest to change the
	   HANDLER_CAN_RWRITE definition below to HANDLER_CAN_RONLY */
	my_handler = netsnmp_create_handler_registration("saHpiSensorReadingNormalMinTable",
							 netsnmp_table_array_helper_handler,
							 saHpiSensorReadingNormalMinTable_oid,
							 saHpiSensorReadingNormalMinTable_oid_len,
							 HANDLER_CAN_RWRITE);

	if (!my_handler || !table_info) {
		snmp_log(LOG_ERR, "malloc failed in "
			 "initialize_table_saHpiSensorReadingNormalMinTable_handler\n");
		return;	/** mallocs failed */
	}

	/***************************************************
	 * Setting up the table's definition
	 */
	/*
	 * TODO: add any external indexes here.
	 */
	/** TODO: add code for external index(s)! */

	/*
	 * internal indexes
	 */
	/** index: saHpiDomainId */
	netsnmp_table_helper_add_index(table_info, ASN_UNSIGNED);
	/** index: saHpiResourceId */
	netsnmp_table_helper_add_index(table_info, ASN_UNSIGNED);
	/** index: saHpiResourceIsHistorical */
	netsnmp_table_helper_add_index(table_info, ASN_INTEGER);
	/** index: saHpiSensorNum */
	netsnmp_table_helper_add_index(table_info, ASN_UNSIGNED);

	table_info->min_column = saHpiSensorReadingNormalMinTable_COL_MIN;
	table_info->max_column = saHpiSensorReadingNormalMinTable_COL_MAX;

	/***************************************************
	 * registering the table with the master agent
	 */
	cb.get_value = saHpiSensorReadingNormalMinTable_get_value;
	cb.container = netsnmp_container_find("saHpiSensorReadingNormalMinTable_primary:"
					      "saHpiSensorReadingNormalMinTable:"
					      "table_container");

	netsnmp_container_add_index(cb.container,
				    netsnmp_container_find("saHpiSensorReadingNormalMinTable_secondary:"
							   "saHpiSensorReadingNormalMinTable:"
							   "table_container"));
	cb.container->next->compare = saHpiSensorReadingNormalMinTable_cmp;


	cb.can_set = 1;

	cb.create_row = (UserRowMethod*)saHpiSensorReadingNormalMinTable_create_row;

	cb.duplicate_row = (UserRowMethod*)saHpiSensorReadingNormalMinTable_duplicate_row;
	cb.delete_row = (UserRowMethod*)saHpiSensorReadingNormalMinTable_delete_row;
	cb.row_copy = (Netsnmp_User_Row_Operation *)saHpiSensorReadingNormalMinTable_row_copy;

	cb.can_activate = (Netsnmp_User_Row_Action *)saHpiSensorReadingNormalMinTable_can_activate;
	cb.can_deactivate = (Netsnmp_User_Row_Action *)saHpiSensorReadingNormalMinTable_can_deactivate;
	cb.can_delete = (Netsnmp_User_Row_Action *)saHpiSensorReadingNormalMinTable_can_delete;

	cb.set_reserve1 = saHpiSensorReadingNormalMinTable_set_reserve1;
	cb.set_reserve2 = saHpiSensorReadingNormalMinTable_set_reserve2;
	cb.set_action = saHpiSensorReadingNormalMinTable_set_action;
	cb.set_commit = saHpiSensorReadingNormalMinTable_set_commit;
	cb.set_free = saHpiSensorReadingNormalMinTable_set_free;
	cb.set_undo = saHpiSensorReadingNormalMinTable_set_undo;

	DEBUGMSGTL(("initialize_table_saHpiSensorReadingNormalMinTable",
		    "Registering table saHpiSensorReadingNormalMinTable "
		    "as a table array\n"));
	netsnmp_table_container_register(my_handler, table_info, &cb,
					 cb.container, 1);
}
コード例 #5
0
ファイル: snmpv3.c プロジェクト: Undrizzle/yolanda
/*******************************************************************-o-******
 * engineBoots_conf
 *
 * Parameters:
 *	*word
 *	*cptr
 *
 * Line syntax:
 *	engineBoots <num_boots>
 */
void
engineBoots_conf(const char *word, char *cptr)
{
  engineBoots = atoi(cptr)+1;
  DEBUGMSGTL(("snmpv3","engineBoots: %d\n",engineBoots));
}
コード例 #6
0
/**
 * load initial data
 *
 * TODO:350:M: Implement dot11PermitSSIDTable data load
 * This function will also be called by the cache helper to load
 * the container again (after the container free function has been
 * called to free the previous contents).
 *
 * @param container container to which items should be inserted
 *
 * @retval MFD_SUCCESS              : success.
 * @retval MFD_RESOURCE_UNAVAILABLE : Can't access data source
 * @retval MFD_ERROR                : other error.
 *
 *  This function is called to load the index(es) (and data, optionally)
 *  for the every row in the data set.
 *
 * @remark
 *  While loading the data, the only important thing is the indexes.
 *  If access to your data is cheap/fast (e.g. you have a pointer to a
 *  structure in memory), it would make sense to update the data here.
 *  If, however, the accessing the data invovles more work (e.g. parsing
 *  some other existing data, or peforming calculations to derive the data),
 *  then you can limit yourself to setting the indexes and saving any
 *  information you will need later. Then use the saved information in
 *  dot11PermitSSIDTable_row_prep() for populating data.
 *
 * @note
 *  If you need consistency between rows (like you want statistics
 *  for each row to be from the same time frame), you should set all
 *  data here.
 *
 */
int
dot11PermitSSIDTable_container_load(netsnmp_container *container)
{
	snmp_log(LOG_DEBUG, "enter dot11PermitSSIDTable_container_load\n");
	
    dot11PermitSSIDTable_rowreq_ctx *rowreq_ctx;
    size_t                 count = 0;

    /*
     * temporary storage for index values
     */
        /*
         * permitSSIDID(1)/INTEGER/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
         */
   long   permitSSIDID;

    
    /*
     * this example code is based on a data source that is a
     * text file to be read and parsed.
     */
    //FILE *filep;
    //char line[MAX_LINE_SIZE];

    DEBUGMSGTL(("verbose:dot11PermitSSIDTable:dot11PermitSSIDTable_container_load","called\n"));

    /*
    ***************************************************
    ***             START EXAMPLE CODE              ***
    ***---------------------------------------------***/
    /*
     * open our data file.
     */
    //filep = fopen("/etc/dummy.conf", "r");
    //if(NULL ==  filep) {
      //  return MFD_RESOURCE_UNAVAILABLE;
    //}

    /*
    ***---------------------------------------------***
    ***              END  EXAMPLE CODE              ***
    ***************************************************/
    /*
     * TODO:351:M: |-> Load/update data in the dot11PermitSSIDTable container.
     * loop over your dot11PermitSSIDTable data, allocate a rowreq context,
     * set the index(es) [and data, optionally] and insert into
     * the container.
     */
    snmpd_dbus_message *messageHead = NULL, *messageNode = NULL;
    snmp_log(LOG_DEBUG, "enter list_connection_call_dbus_method:show_legal_essid_list_cmd\n");
    messageHead = list_connection_call_dbus_method(show_legal_essid_list_cmd, SHOW_ALL_WTP_TABLE_METHOD);
	snmp_log(LOG_DEBUG, "exit list_connection_call_dbus_method:show_legal_essid_list_cmd,messageHead=%p\n", messageHead);

	if(messageHead)
	{
		for(messageNode = messageHead; NULL != messageNode; messageNode = messageNode->next)
		{
            DCLI_AC_API_GROUP_ONE *LIST = messageNode->message;
            if((LIST) && (LIST->dcli_essid_list)) 
			{
                struct essid_node *head = NULL;
                unsigned int len = LIST->dcli_essid_list->list_len;
                int i = 0;				
				char essid[255] = { 0 };
				for(i=0,head = LIST->dcli_essid_list->essid_list;
					((i<len)&&(NULL != head));
					i++,head = head->next)
			    {
                    permitSSIDID = local_to_global_ID(messageNode->parameter, i + 1, WIRELESS_MAX_NUM);
					
					memset(essid,0,sizeof(essid));
					if(head->essid)
					{
						strncpy(essid,head->essid,sizeof(essid)-1);
					}
		    /*
		    ***************************************************
		    ***             START EXAMPLE CODE              ***
		    ***---------------------------------------------***/
		    /*
		     * get a line (skip blank lines)
		     */
		    //do {
		      //  if (!fgets(line, sizeof(line), filep)) {
		            /* we're done */
		        //    fclose(filep);
		          //  filep = NULL;
		        //}
		    //} while (filep && (line[0] == '\n'));

		    /*
		     * check for end of data
		     */
		    //if(NULL == filep)
		      //  break;

		    /*
		     * parse line into variables
		     */
		    /*
		    ***---------------------------------------------***
		    ***              END  EXAMPLE CODE              ***
		    ***************************************************/

		        /*
		         * TODO:352:M: |   |-> set indexes in new dot11PermitSSIDTable rowreq context.
		         * data context will be set from the param (unless NULL,
		         *      in which case a new data context will be allocated)
		         */
		        rowreq_ctx = dot11PermitSSIDTable_allocate_rowreq_ctx(NULL);
		        if (NULL == rowreq_ctx) {
		            snmp_log(LOG_ERR, "memory allocation failed\n");
					free_dbus_message_list(&messageHead, Free_legal_essid_list_head);
		            return MFD_RESOURCE_UNAVAILABLE;
		        }
		        if(MFD_SUCCESS != dot11PermitSSIDTable_indexes_set(rowreq_ctx
		                               , permitSSIDID
		               )) {
		            snmp_log(LOG_ERR,"error setting index while loading "
		                     "dot11PermitSSIDTable data.\n");
		            dot11PermitSSIDTable_release_rowreq_ctx(rowreq_ctx);
		            continue;
		        }

				memcpy(&(rowreq_ctx->data.parameter), &(messageNode->parameter), sizeof(rowreq_ctx->data.parameter));

				rowreq_ctx->data.is_modify = 1;

				/*
		         * TODO:352:r: |   |-> populate dot11PermitSSIDTable data context.
		         * Populate data context here. (optionally, delay until row prep)
		         */
		    /*
		     * TRANSIENT or semi-TRANSIENT data:
		     * copy data or save any info needed to do it in row_prep.
		     */
		    /*
		     * setup/save data for permitSSID
		     * permitSSID(2)/DisplayString/ASN_OCTET_STR/char(char)//L/A/W/e/R/d/H
		     */
		    /** no mapping */
		    /*
		     * make sure there is enough space for permitSSID data
		     */
		    /*if ((NULL == rowreq_ctx->data.permitSSID) ||
		        (rowreq_ctx->data.permitSSID_len <
		         (permitSSID_len* sizeof(permitSSID[0])))) {
		        snmp_log(LOG_ERR,"not enough space for value\n");
		        return MFD_ERROR;
		    }*/
		    rowreq_ctx->data.permitSSID_len = MIN(sizeof(rowreq_ctx->data.permitSSID) - 1, strlen(essid));
		    memcpy( rowreq_ctx->data.permitSSID, essid, rowreq_ctx->data.permitSSID_len );
		    
		    /*
		     * setup/save data for permitSSIDRowStatus
		     * permitSSIDRowStatus(3)/RowStatus/ASN_INTEGER/long(u_long)//l/A/W/E/r/d/h
		     */
		    /** no mapping */
		    rowreq_ctx->data.permitSSIDRowStatus = RS_ACTIVE;
		    
		        
		        /*
		         * insert into table container
		         */
		        if(CONTAINER_INSERT(container, rowreq_ctx))
		        {
		        	dot11PermitSSIDTable_release_rowreq_ctx(rowreq_ctx);
		        }
		        ++count;
		    }		}
        }
        free_dbus_message_list(&messageHead, Free_legal_essid_list_head);
    }  


    /*
    ***************************************************
    ***             START EXAMPLE CODE              ***
    ***---------------------------------------------***/
    //if(NULL != filep)
      //  fclose(filep);
    /*
    ***---------------------------------------------***
    ***              END  EXAMPLE CODE              ***
    ***************************************************/

    DEBUGMSGT(("verbose:dot11PermitSSIDTable:dot11PermitSSIDTable_container_load",
               "inserted %d records\n", count));

	snmp_log(LOG_DEBUG, "exit dot11PermitSSIDTable_container_load\n");
	
    return MFD_SUCCESS;
} /* dot11PermitSSIDTable_container_load */
コード例 #7
0
/**
 * the *_extract_index routine
 *
 * This routine is called when a set request is received for an index
 * that was not found in the table container. Here, we parse the oid
 * in the the individual index components and copy those indexes to the
 * context. Then we make sure the indexes for the new row are valid.
 */
int
saHpiSensorReadingNormalMinTable_extract_index( saHpiSensorReadingNormalMinTable_context * ctx, netsnmp_index * hdr )
{
	/*
	 * temporary local storage for extracting oid index
	 *
	 * extract index uses varbinds (netsnmp_variable_list) to parse
	 * the index OID into the individual components for each index part.
	 */
	/** TODO: add storage for external index(s)! */
	netsnmp_variable_list var_saHpiDomainId;
	netsnmp_variable_list var_saHpiResourceId;
	netsnmp_variable_list var_saHpiResourceIsHistorical;
	netsnmp_variable_list var_saHpiSensorNum;
	int err;

	DEBUGMSGTL ((AGENT, "saHpiSensorReadingNormalMinTable_extract_index, called\n"));

	/*
	 * copy index, if provided
	 */
	if (hdr) {
		netsnmp_assert(ctx->index.oids == NULL);
		if (snmp_clone_mem( (void*)&ctx->index.oids, hdr->oids,
				    hdr->len * sizeof(oid) )) {
			return -1;
		}
		ctx->index.len = hdr->len;
	}

	/*
	 * initialize variable that will hold each component of the index.
	 * If there are multiple indexes for the table, the variable_lists
	 * need to be linked together, in order.
	 */
	/** TODO: add code for external index(s)! */
	memset( &var_saHpiDomainId, 0x00, sizeof(var_saHpiDomainId) );
	var_saHpiDomainId.type = ASN_UNSIGNED; /* type hint for parse_oid_indexes */
	/** TODO: link this index to the next, or NULL for the last one */
	var_saHpiDomainId.next_variable = &var_saHpiResourceId;

	memset( &var_saHpiResourceId, 0x00, sizeof(var_saHpiResourceId) );
	var_saHpiResourceId.type = ASN_UNSIGNED; /* type hint for parse_oid_indexes */
	/** TODO: link this index to the next, or NULL for the last one */
	var_saHpiResourceId.next_variable = &var_saHpiResourceIsHistorical;

	memset( &var_saHpiResourceIsHistorical, 0x00, sizeof(var_saHpiResourceIsHistorical) );
	var_saHpiResourceIsHistorical.type = ASN_INTEGER; /* type hint for parse_oid_indexes */
	/** TODO: link this index to the next, or NULL for the last one */
	var_saHpiResourceIsHistorical.next_variable = &var_saHpiSensorNum;

	memset( &var_saHpiSensorNum, 0x00, sizeof(var_saHpiSensorNum) );
	var_saHpiSensorNum.type = ASN_UNSIGNED;	/* type hint for parse_oid_indexes */
	/** TODO: link this index to the next, or NULL for the last one */
	var_saHpiSensorNum.next_variable = NULL;


	/*
	 * parse the oid into the individual index components
	 */
	err = parse_oid_indexes( hdr->oids, hdr->len, &var_saHpiDomainId );
	if (err == SNMP_ERR_NOERROR) {
		/*
		 * copy index components into the context structure
		 */
		/** skipping external index saHpiDomainId */

		/** skipping external index saHpiResourceId */

		/** skipping external index saHpiResourceIsHistorical */

		/** skipping external index saHpiSensorNum */


		err = saHpiDomainId_check_index(
					       *var_saHpiDomainId.val.integer);
		err = saHpiResourceEntryId_check_index(
						      *var_saHpiResourceId.val.integer);  
		err = saHpiResourceIsHistorical_check_index(
							   *var_saHpiResourceIsHistorical.val.integer);
		err = saHpiSensorNum_check_index(
						*var_saHpiSensorNum.val.integer);
	}

	/*
	 * parsing may have allocated memory. free it.
	 */
	snmp_reset_var_buffers( &var_saHpiDomainId );

	return err;
}
コード例 #8
0
ファイル: vacm_conf.c プロジェクト: prak5192/C_Project
void
vacm_parse_authaccess(const char *token, char *confline)
{
    char *group, *view, *tmp;
    const char *context;
    int  model = SNMP_SEC_MODEL_ANY;
    int  level, prefix;
    int  i;
    char   *st;
    struct vacm_accessEntry *ap;
    int  viewtypes = vacm_parse_authtokens(token, &confline);

    if (viewtypes == -1)
        return;

    group = strtok_r(confline, " \t\n", &st);
    if (!group) {
        config_perror("missing GROUP parameter");
        return;
    }
    view = strtok_r(NULL, " \t\n", &st);
    if (!view) {
        config_perror("missing VIEW parameter");
        return;
    }

    /*
     * Check for security model option
     */
    if ( strcasecmp(view, "-s") == 0 ) {
        tmp = strtok_r(NULL, " \t\n", &st);
        if (tmp) {
            if (strcasecmp(tmp, "any") == 0)
                model = SNMP_SEC_MODEL_ANY;
            else if (strcasecmp(tmp, "v1") == 0)
                model = SNMP_SEC_MODEL_SNMPv1;
            else if (strcasecmp(tmp, "v2c") == 0)
                model = SNMP_SEC_MODEL_SNMPv2c;
            else {
                model = se_find_value_in_slist("snmp_secmods", tmp);
                if (model == SE_DNE) {
                    config_perror
                        ("bad security model, should be: v1, v2c or usm or a registered security plugin name");
                    return;
                }
            }
        } else {
            config_perror("missing SECMODEL parameter");
            return;
        }
        view = strtok_r(NULL, " \t\n", &st);
        if (!view) {
            config_perror("missing VIEW parameter");
            return;
        }
    }
    if (strlen(view) >= VACMSTRINGLEN ) {
        config_perror("View value too long");
        return;
    }

    /*
     * Now parse optional fields, or provide default values
     */
    
    tmp = strtok_r(NULL, " \t\n", &st);
    if (tmp) {
        if (strcasecmp(tmp, "noauth") == 0)
            level = SNMP_SEC_LEVEL_NOAUTH;
        else if (strcasecmp(tmp, "noauthnopriv") == 0)
            level = SNMP_SEC_LEVEL_NOAUTH;
        else if (strcasecmp(tmp, "auth") == 0)
            level = SNMP_SEC_LEVEL_AUTHNOPRIV;
        else if (strcasecmp(tmp, "authnopriv") == 0)
            level = SNMP_SEC_LEVEL_AUTHNOPRIV;
        else if (strcasecmp(tmp, "priv") == 0)
            level = SNMP_SEC_LEVEL_AUTHPRIV;
        else if (strcasecmp(tmp, "authpriv") == 0)
            level = SNMP_SEC_LEVEL_AUTHPRIV;
        else {
            config_perror
                ("bad security level (noauthnopriv, authnopriv, authpriv)");
                return;
        }
    } else {
        /*  What about  SNMP_SEC_MODEL_ANY ?? */
        if ( model == SNMP_SEC_MODEL_SNMPv1 ||
             model == SNMP_SEC_MODEL_SNMPv2c )
            level = SNMP_SEC_LEVEL_NOAUTH;
        else
            level = SNMP_SEC_LEVEL_AUTHNOPRIV;
    }
    

    context = tmp = strtok_r(NULL, " \t\n", &st);
    if (tmp) {
        tmp = (tmp + strlen(tmp)-1);
        if (tmp && *tmp == '*') {
            *tmp = '\0';
            prefix = 2;
        } else {
            prefix = 1;
        }
    } else {
        context = "";
        prefix  = 1;   /* Or prefix(2) ?? */
    }

    /*
     * Now we can create the access entry
     */
    ap = vacm_getAccessEntry(group, context, model, level);
    if (!ap) {
        ap = vacm_createAccessEntry(group, context, model, level);
        DEBUGMSGTL(("vacm:conf:authaccess",
                    "no existing access found; creating a new one\n"));
    } else {
        DEBUGMSGTL(("vacm:conf:authaccess",
                    "existing access found, using it\n"));
    }
    if (!ap) {
        config_perror("failed to create access entry");
        return;
    }

    for (i = 0; i <= VACM_MAX_VIEWS; i++) {
        if (viewtypes & (1 << i)) {
            strcpy(ap->views[i], view);
        }
    }
    ap->contextMatch = prefix;
    ap->storageType  = SNMP_STORAGE_PERMANENT;
    ap->status       = SNMP_ROW_ACTIVE;
    if (ap->reserved)
        free(ap->reserved);
    ap->reserved = NULL;
}
コード例 #9
0
ファイル: vacm_conf.c プロジェクト: prak5192/C_Project
void
vacm_create_simple(const char *token, char *confline,
                   int parsetype, int viewtypes)
{
    char            line[SPRINT_MAX_LEN];
    char            community[COMMUNITY_MAX_LEN];
    char            theoid[SPRINT_MAX_LEN];
    char            viewname[SPRINT_MAX_LEN];
    char           *view_ptr = viewname;
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
    char            addressname[SPRINT_MAX_LEN];
#endif
    const char     *rw = "none";
    char            model[SPRINT_MAX_LEN];
    char           *cp, *tmp;
    char            secname[SPRINT_MAX_LEN];
    char            grpname[SPRINT_MAX_LEN];
    char            authlevel[SPRINT_MAX_LEN];
    char            context[SPRINT_MAX_LEN];
    int             ctxprefix = 1;  /* Default to matching all contexts */
    static int      commcount = 0;
    /* Conveniently, the community-based security
       model values can also be used as bit flags */
    int             commversion = SNMP_SEC_MODEL_SNMPv1 |
                                  SNMP_SEC_MODEL_SNMPv2c;

    /*
     * init 
     */
    strcpy(model, "any");
    memset(context, 0, sizeof(context));
    memset(secname, 0, sizeof(secname));
    memset(grpname, 0, sizeof(grpname));

    /*
     * community name or user name 
     */
    cp = copy_nword(confline, community, sizeof(community));

    if (parsetype == VACM_CREATE_SIMPLE_V3) {
        /*
         * maybe security model type 
         */
        if (strcmp(community, "-s") == 0) {
            /*
             * -s model ... 
             */
            if (cp)
                cp = copy_nword(cp, model, sizeof(model));
            if (!cp) {
                config_perror("illegal line");
                return;
            }
            if (cp)
                cp = copy_nword(cp, community, sizeof(community));
        } else {
            strcpy(model, "usm");
        }
        /*
         * authentication level 
         */
        if (cp && *cp)
            cp = copy_nword(cp, authlevel, sizeof(authlevel));
        else
            strcpy(authlevel, "auth");
        DEBUGMSGTL((token, "setting auth level: \"%s\"\n", authlevel));
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
    } else {
        if (strcmp(community, "-v") == 0) {
            /*
             * -v version ... 
             */
            if (cp)
                cp = copy_nword(cp, model, sizeof(model));
            if (!cp) {
                config_perror("illegal line");
                return;
            }
            if ( strcasecmp( model,  "1" ) == 0 )
                strcpy(model, "v1");
            if ( strcasecmp( model, "v1" ) == 0 )
                commversion = SNMP_SEC_MODEL_SNMPv1;
            if ( strcasecmp( model,  "2c" ) == 0 )
                strcpy(model, "v2c");
            if ( strcasecmp( model, "v2c" ) == 0 )
                commversion = SNMP_SEC_MODEL_SNMPv2c;
            if (cp)
                cp = copy_nword(cp, community, sizeof(community));
        }
        /*
         * source address 
         */
        if (cp && *cp) {
            cp = copy_nword(cp, addressname, sizeof(addressname));
        } else {
            strcpy(addressname, "default");
        }
        /*
         * authlevel has to be noauth 
         */
        strcpy(authlevel, "noauth");
#endif /* support for community based SNMP */
    }

    /*
     * oid they can touch 
     */
    if (cp && *cp) {
        if (strncmp(cp, "-V ", 3) == 0) {
             cp = skip_token(cp);
             cp = copy_nword(cp, viewname, sizeof(viewname));
             view_ptr = NULL;
        } else {
             cp = copy_nword(cp, theoid, sizeof(theoid));
        }
    } else {
        strcpy(theoid, ".1");
        strcpy(viewname, "_all_");
        view_ptr = NULL;
    }
    /*
     * optional, non-default context
     */
    if (cp && *cp) {
        cp = copy_nword(cp, context, sizeof(context));
        tmp = (context + strlen(context)-1);
        if (tmp && *tmp == '*') {
            *tmp = '\0';
            ctxprefix = 1;
        } else {
            /*
             * If no context field is given, then we default to matching
             *   all contexts (for compatability with previous releases).
             * But if a field context is specified (not ending with '*')
             *   then this should be taken as an exact match.
             * Specifying a context field of "" will match the default
             *   context (and *only* the default context).
             */
            ctxprefix = 0;
        }
    }

    if (viewtypes & VACM_VIEW_WRITE_BIT)
        rw = viewname;

    commcount++;

#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#ifdef NETSNMP_TRANSPORT_UDP_DOMAIN
    if (parsetype == VACM_CREATE_SIMPLE_COMIPV4 ||
        parsetype == VACM_CREATE_SIMPLE_COM) {
        vacm_gen_com2sec(commcount, community, addressname,
                         "com2sec", &netsnmp_udp_parse_security,
                         secname, sizeof(secname),
                         view_ptr, sizeof(viewname), commversion, context);
    }
#endif

#ifdef NETSNMP_TRANSPORT_UNIX_DOMAIN
    if (parsetype == VACM_CREATE_SIMPLE_COMUNIX ||
        parsetype == VACM_CREATE_SIMPLE_COM) {
        if ( *context )
           snprintf(line, sizeof(line), "-Cn %s %s %s '%s'",
             context, secname, addressname, community);
        else
            snprintf(line, sizeof(line), "%s %s '%s'",
                 secname, addressname, community);
        line[ sizeof(line)-1 ] = 0;
        DEBUGMSGTL((token, "passing: %s %s\n", "com2secunix", line));
        netsnmp_unix_parse_security("com2secunix", line);
    }
#endif

#ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
    if (parsetype == VACM_CREATE_SIMPLE_COMIPV6 ||
        parsetype == VACM_CREATE_SIMPLE_COM) {
        vacm_gen_com2sec(commcount, community, addressname,
                         "com2sec6", &netsnmp_udp6_parse_security,
                         secname, sizeof(secname),
                         view_ptr, sizeof(viewname), commversion, context);
    }
#endif
#endif /* support for community based SNMP */

    if (parsetype == VACM_CREATE_SIMPLE_V3) {
        /* support for SNMPv3 user names */
        if (view_ptr) {
            sprintf(viewname,"viewUSM%d",commcount);
        }
        if ( strcmp( token, "authgroup" ) == 0 ) {
            strlcpy(grpname, community, sizeof(grpname));
        } else {
            strlcpy(secname, community, sizeof(secname));

            /*
             * sec->group mapping 
             */
            /*
             * group   anonymousGroupNameNUM  any      anonymousSecNameNUM 
             */
            snprintf(grpname, sizeof(grpname), "grp%.28s", secname);
            for (tmp=grpname; *tmp; tmp++)
                if (!isalnum((unsigned char)(*tmp)))
                    *tmp = '_';
            snprintf(line, sizeof(line),
                     "%s %s \"%s\"", grpname, model, secname);
            line[ sizeof(line)-1 ] = 0;
            DEBUGMSGTL((token, "passing: %s %s\n", "group", line));
            vacm_parse_group("group", line);
        }
    } else {
        snprintf(grpname, sizeof(grpname), "grp%.28s", secname);
        for (tmp=grpname; *tmp; tmp++)
            if (!isalnum((unsigned char)(*tmp)))
                *tmp = '_';
    }

    /*
     * view definition 
     */
    /*
     * view    anonymousViewNUM       included OID 
     */
    if (view_ptr) {
        snprintf(line, sizeof(line), "%s included %s", viewname, theoid);
        line[ sizeof(line)-1 ] = 0;
        DEBUGMSGTL((token, "passing: %s %s\n", "view", line));
        vacm_parse_view("view", line);
    }

    /*
     * map everything together 
     */
    if ((viewtypes == VACM_VIEW_READ_BIT) ||
        (viewtypes == (VACM_VIEW_READ_BIT | VACM_VIEW_WRITE_BIT))) {
        /* Use the simple line access command */
        /*
         * access  anonymousGroupNameNUM  "" MODEL AUTHTYPE prefix anonymousViewNUM [none/anonymousViewNUM] [none/anonymousViewNUM] 
         */
        snprintf(line, sizeof(line),
                 "%s %s %s %s %s %s %s %s",
                 grpname, context[0] ? context : "\"\"",
                 model, authlevel,
                (ctxprefix ? "prefix" : "exact"),
                 viewname, rw, rw);
        line[ sizeof(line)-1 ] = 0;
        DEBUGMSGTL((token, "passing: %s %s\n", "access", line));
        vacm_parse_access("access", line);
    } else {
        /* Use one setaccess line per access type */
        /*
         * setaccess  anonymousGroupNameNUM  "" MODEL AUTHTYPE prefix viewname viewval
         */
        int i;
        DEBUGMSGTL((token, " checking view levels for %x\n", viewtypes));
        for(i = 0; i <= VACM_MAX_VIEWS; i++) {
            if (viewtypes & (1 << i)) {
                snprintf(line, sizeof(line),
                         "%s %s %s %s %s %s %s",
                         grpname, context[0] ? context : "\"\"",
                         model, authlevel,
                        (ctxprefix ? "prefix" : "exact"),
                         se_find_label_in_slist(VACM_VIEW_ENUM_NAME, i),
                         viewname);
                line[ sizeof(line)-1 ] = 0;
                DEBUGMSGTL((token, "passing: %s %s\n", "setaccess", line));
                vacm_parse_setaccess("setaccess", line);
            }
        }
    }
}
コード例 #10
0
ファイル: vmstat_solaris2.c プロジェクト: Undrizzle/apps
/*
 * This gets called every POLL_INTERVAL seconds to update the snapshots.  It takes a new snapshot and 
 * drops the oldest one.  This way we move the time window so we always take the values over 
 * POLL_INTERVAL * POLL_VALUES seconds and update the data used every POLL_INTERVAL seconds 
 * The alarm timer is in the init function of this module (snmp_alarm_register) 
 * ARGSUSED0 
 */
static void
update_stats(unsigned int registrationNumber, void *clientarg)
{
    /*
     * The time between the samples we compare 
     */
    hrtime_t        time_diff;

    /*
     * Easier to use these than the snapshots, short hand pointers 
     */
    struct cpu_stat_snapshot *css_old, *css_new;

    /*
     * The usual stuff to count on, err, by 
     */
    int             i;

    /*
     * Kstat chain id, to check whether kstat chain changed 
     */
    kid_t           kid;

    /*
     * The sum of the CPU ticks that have passed on the different CPU states, so we can calculate 
     * the percentages of each state 
     */
    unsigned long long cpu_sum = 0;

    DEBUGMSGTL(("ucd-snmp/vmstat_solaris2.c:update_stats",
                "updating stats\n"));

    /*
     * Just in case someone added (or removed) some CPUs during operation (or other kstat chain changes) 
     */
    kid = kstat_chain_update(kstat_fd);
    if (kid != 0) {
        if (kid == -1) {
            snmp_log(LOG_WARNING,
                     "vmstat_solaris2 (update_stats): Could not update kstat chain.\n");
        } else {
            /*
             * On some machines this floods the logfile, thus commented out 
             * snmp_log(LOG_INFO, "vmstat_solaris2 (update_stats): Kstat chain changed."); 
             */
        }
    }

    /*
     * Take the current snapshot 
     */
    if (take_snapshot(&snapshot[0]) == -1) {
        snmp_log(LOG_WARNING,
                 "vmstat_solaris2 (update_stats): Something went wrong with take_snapshot.\n");
        return;
    }

    /*
     * Do we have some data we can use ?  An issue right after the start of the agent 
     */
    if (number_of_snapshots > 0) {
        /*
         * Huh, the number of CPUs changed during run time.  That is indeed s.th. worth noting, we 
         * output a humorous (more or less) syslog message and need to retake the snapshots 
         */
        if (snapshot[0].css_cpus != snapshot[1].css_cpus) {
            if (snapshot[0].css_cpus > snapshot[1].css_cpus) {
                snmp_log(LOG_NOTICE,
                         "vmstat_solaris2 (update_stats): Cool ! Number of CPUs increased, must be hot-pluggable.\n");
            } else {
                snmp_log(LOG_NOTICE,
                         "vmstat_solaris2 (update_stats): Lost at least one CPU, RIP.\n");
            }
            /*
             * Make all snapshots but the current one invalid 
             */
            number_of_snapshots = 1;
            /*
             * Move the current one in the "first" [1] slot 
             */
            memmove(&snapshot[1], &snapshot[0], sizeof snapshot[0]);
            /*
             * Erase the current one 
             */
            memset(&snapshot[0], 0, sizeof snapshot[0]);
            /*
             * Try to get a new snapshot in five seconds so we can return s.th. useful 
             */
            if (snmp_alarm_register(5, NULL, update_stats, NULL) == 0) {
                snmp_log(LOG_WARNING,
                         "vmstat_solaris2 (update_stats): snmp_alarm_register failed.\n");
            }
            return;
        }

        /*
         * Short hand pointers 
         */
        css_new = &snapshot[0];
        css_old = &snapshot[number_of_snapshots];

        /*
         * How much time has passed between the snapshots we get the values from ? 
         * Time is in nanoseconds so a few zeros here to juggle with 
         * But the hrtime is not subject to change (s.b. setting the clock), unlike the normal time 
         */
        time_diff =
            (snapshot[0].css_time -
             snapshot[number_of_snapshots].css_time) / 1000000;
        if ( time_diff == 0 ) { time_diff = 1; }  /* Protect against division-by-zero */

        DEBUGMSGTL(("ucd-snmp/vmstat_solaris2.c:update_stats",
                    "time_diff: %lld\n", time_diff));

        /*
         * swapin and swapout are in pages, MIB wants kB/s,so we just need to get kB and seconds 
         * For the others we need to get value per second 
         * getpagesize() returns pagesize in bytes 
         * decided to use sysconf(_SC_PAGESIZE) instead to get around an #ifndef (I don't like those) 
         * that was needed b/c some old Solaris versions don't have getpagesize() 
         */
        /*
         * LINTED cast needed, really 
         */
        swapin =
            (uint_t) ((css_new->css_swapin -
                       css_old->css_swapin) * (hrtime_t) 1000 *
                      sysconf(_SC_PAGESIZE) / 1024 / time_diff);
        /*
         * LINTED cast needed, really 
         */
        swapout =
            (uint_t) ((css_new->css_swapout -
                       css_old->css_swapout) * (hrtime_t) 1000 *
                      sysconf(_SC_PAGESIZE) / 1024 / time_diff);
        /*
         * LINTED cast needed, really 
         */
        blocks_read =
            (uint_t) ((css_new->css_blocks_read -
                       css_old->css_blocks_read) * (hrtime_t) 1000 /
                      time_diff);
        /*
         * LINTED cast needed, really 
         */
        blocks_write =
            (uint_t) ((css_new->css_blocks_write -
                       css_old->css_blocks_write) * (hrtime_t) 1000 /
                      time_diff);
        /*
         * LINTED cast needed, really 
         */
        interrupts =
            (uint_t) ((css_new->css_interrupts -
                       css_old->css_interrupts) * (hrtime_t) 1000 /
                      time_diff);
        /*
         * LINTED cast needed, really 
         */
        context_sw =
            (uint_t) ((css_new->css_context_sw -
                       css_old->css_context_sw) * (hrtime_t) 1000 /
                      time_diff);

        /*
         * Loop thru all the CPU_STATES and get the differences 
         */
        for (i = 0; i < CPU_STATES; i++) {
            cpu_sum += (css_new->css_cpu[i] - css_old->css_cpu[i]);
        }

        /*
         * Now calculate the absolute percentage values 
         * Looks somewhat complicated sometimes but tries to get around using floats to increase speed 
         */
        for (i = 0; i < CPU_STATES; i++) {
            /*
             * Since we don't return fractions we use + 0.5 to get between 99 and 101 percent adding the values 
             * together, otherwise we would get less than 100 most of the time 
             */
            /*
             * LINTED has to be 'long' 
             */
            cpu_perc[i] =
                (long) (((css_new->css_cpu[i] -
                          css_old->css_cpu[i]) * 100 +
                         (cpu_sum / 2)) / cpu_sum);
        }

        /*
         * As said before, MIB wants CPU_SYSTEM which is CPU_KERNEL + CPU_WAIT 
         */
        /*
         * LINTED has to be 'long' 
         */
        cpu_perc[CPU_SYSTEM] =
            (long) ((((css_new->css_cpu[CPU_KERNEL] -
                       css_old->css_cpu[CPU_KERNEL])
                      + (css_new->css_cpu[CPU_WAIT] -
                         css_old->css_cpu[CPU_WAIT]))
                     * 100 + (cpu_sum / 2)) / cpu_sum);
    }

    /*
     * Make the current one the first one and move the whole thing one place down 
     */
    memmove(&snapshot[1], &snapshot[0],
            (size_t) (((char *) &snapshot[POLL_VALUES]) -
                      ((char *) &snapshot[0])));

    /*
     * Erase the current one 
     */
    memset(&snapshot[0], 0, sizeof snapshot[0]);

    /*
     * Only important on start up, we keep track of how many snapshots we have taken so far 
     */
    if (number_of_snapshots < POLL_VALUES) {
        number_of_snapshots++;
    }
}                               /* update_stats ends here */
コード例 #11
0
ファイル: vacm_conf.c プロジェクト: prak5192/C_Project
int
vacm_check_view_contents(netsnmp_pdu *pdu, oid * name, size_t namelen,
                         int check_subtree, int viewtype, int flags)
{
    struct vacm_accessEntry *ap;
    struct vacm_groupEntry *gp;
    struct vacm_viewEntry *vp;
    char            vacm_default_context[1] = "";
    const char     *contextName = vacm_default_context;
    const char     *sn = NULL;
    char           *vn;
    const char     *pdu_community;

    /*
     * len defined by the vacmContextName object 
     */
#define CONTEXTNAMEINDEXLEN 32
    char            contextNameIndex[CONTEXTNAMEINDEXLEN + 1];

#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#if defined(NETSNMP_DISABLE_SNMPV1)
    if (pdu->version == SNMP_VERSION_2c)
#else
#if defined(NETSNMP_DISABLE_SNMPV2C)
    if (pdu->version == SNMP_VERSION_1)
#else
    if (pdu->version == SNMP_VERSION_1 || pdu->version == SNMP_VERSION_2c)
#endif
#endif
    {
        pdu_community = (const char *) pdu->community;
        if (!pdu_community)
            pdu_community = "";
        if (snmp_get_do_debugging()) {
            char           *buf;
            if (pdu->community) {
                buf = (char *) malloc(1 + pdu->community_len);
                memcpy(buf, pdu->community, pdu->community_len);
                buf[pdu->community_len] = '\0';
            } else {
                DEBUGMSGTL(("mibII/vacm_vars", "NULL community"));
                buf = strdup("NULL");
            }

            DEBUGMSGTL(("mibII/vacm_vars",
                        "vacm_in_view: ver=%ld, community=%s\n",
                        pdu->version, buf));
            free(buf);
        }

        /*
         * Okay, if this PDU was received from a UDP or a TCP transport then
         * ask the transport abstraction layer to map its source address and
         * community string to a security name for us.  
         */

        if (0) {
#ifdef NETSNMP_TRANSPORT_UDP_DOMAIN
        } else if (pdu->tDomain == netsnmpUDPDomain
#ifdef NETSNMP_TRANSPORT_TCP_DOMAIN
            || pdu->tDomain == netsnmp_snmpTCPDomain
#endif
            ) {
            if (!netsnmp_udp_getSecName(pdu->transport_data,
                                        pdu->transport_data_length,
                                        pdu_community,
                                        pdu->community_len, &sn,
                                        &contextName)) {
                /*
                 * There are no com2sec entries.  
                 */
                sn = NULL;
            }
            /* force the community -> context name mapping here */
            SNMP_FREE(pdu->contextName);
            pdu->contextName = strdup(contextName);
            pdu->contextNameLen = strlen(contextName);
#endif
#ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
        } else if (pdu->tDomain == netsnmp_UDPIPv6Domain
#ifdef NETSNMP_TRANSPORT_TCPIPV6_DOMAIN
                   || pdu->tDomain == netsnmp_TCPIPv6Domain
#endif
            ) {
            if (!netsnmp_udp6_getSecName(pdu->transport_data,
                                         pdu->transport_data_length,
                                         pdu_community,
                                         pdu->community_len, &sn,
                                         &contextName)) {
                /*
                 * There are no com2sec entries.  
                 */
                sn = NULL;
            }
            /* force the community -> context name mapping here */
            SNMP_FREE(pdu->contextName);
            pdu->contextName = strdup(contextName);
            pdu->contextNameLen = strlen(contextName);
#endif
#ifdef NETSNMP_TRANSPORT_UNIX_DOMAIN
        } else if (pdu->tDomain == netsnmp_UnixDomain){
            if (!netsnmp_unix_getSecName(pdu->transport_data,
                                         pdu->transport_data_length,
                                         pdu_community,
                                         pdu->community_len, &sn,
                                         &contextName)) {
					sn = NULL;
            }
            /* force the community -> context name mapping here */
            SNMP_FREE(pdu->contextName);
            pdu->contextName = strdup(contextName);
            pdu->contextNameLen = strlen(contextName);
#endif	
        } else {
            /*
             * Map other <community, transport-address> pairs to security names
             * here.  For now just let non-IPv4 transport always succeed.
             * 
             * WHAAAATTTT.  No, we don't let non-IPv4 transports
             * succeed!  You must fix this to make it usable, sorry.
             * From a security standpoint this is insane. -- Wes
             */
            /** @todo alternate com2sec mappings for non v4 transports.
                Should be implemented via registration */
            sn = NULL;
        }

    } else
#endif /* support for community based SNMP */
      if (find_sec_mod(pdu->securityModel)) {
        /*
         * any legal defined v3 security model 
         */
        DEBUGMSG(("mibII/vacm_vars",
                  "vacm_in_view: ver=%ld, model=%d, secName=%s\n",
                  pdu->version, pdu->securityModel, pdu->securityName));
        sn = pdu->securityName;
        contextName = pdu->contextName;
    } else {
        sn = NULL;
    }

    if (sn == NULL) {
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
        snmp_increment_statistic(STAT_SNMPINBADCOMMUNITYNAMES);
#endif
        DEBUGMSGTL(("mibII/vacm_vars",
                    "vacm_in_view: No security name found\n"));
        return VACM_NOSECNAME;
    }

    if (pdu->contextNameLen > CONTEXTNAMEINDEXLEN) {
        DEBUGMSGTL(("mibII/vacm_vars",
                    "vacm_in_view: bad ctxt length %d\n",
                    (int)pdu->contextNameLen));
        return VACM_NOSUCHCONTEXT;
    }
    /*
     * NULL termination of the pdu field is ugly here.  Do in PDU parsing? 
     */
    if (pdu->contextName)
        memcpy(contextNameIndex, pdu->contextName, pdu->contextNameLen);
    else
        contextNameIndex[0] = '\0';

    contextNameIndex[pdu->contextNameLen] = '\0';
    if (!(flags & VACM_CHECK_VIEW_CONTENTS_DNE_CONTEXT_OK) &&
        !netsnmp_subtree_find_first(contextNameIndex)) {
        /*
         * rfc 3415 section 3.2, step 1
         * no such context here; return no such context error 
         */
        DEBUGMSGTL(("mibII/vacm_vars", "vacm_in_view: no such ctxt \"%s\"\n",
                    contextNameIndex));
        return VACM_NOSUCHCONTEXT;
    }

    DEBUGMSGTL(("mibII/vacm_vars", "vacm_in_view: sn=%s", sn));

    gp = vacm_getGroupEntry(pdu->securityModel, sn);
    if (gp == NULL) {
        DEBUGMSG(("mibII/vacm_vars", "\n"));
        return VACM_NOGROUP;
    }
    DEBUGMSG(("mibII/vacm_vars", ", gn=%s", gp->groupName));

    ap = vacm_getAccessEntry(gp->groupName, contextNameIndex,
                             pdu->securityModel, pdu->securityLevel);
    if (ap == NULL) {
        DEBUGMSG(("mibII/vacm_vars", "\n"));
        return VACM_NOACCESS;
    }

    if (name == NULL) { /* only check the setup of the vacm for the request */
        DEBUGMSG(("mibII/vacm_vars", ", Done checking setup\n"));
        return VACM_SUCCESS;
    }

    if (viewtype < 0 || viewtype >= VACM_MAX_VIEWS) {
        DEBUGMSG(("mibII/vacm_vars", " illegal view type\n"));
        return VACM_NOACCESS;
    }
    vn = ap->views[viewtype];
    DEBUGMSG(("mibII/vacm_vars", ", vn=%s", vn));

    if (check_subtree) {
        DEBUGMSG(("mibII/vacm_vars", "\n"));
        return vacm_checkSubtree(vn, name, namelen);
    }

    vp = vacm_getViewEntry(vn, name, namelen, VACM_MODE_FIND);

    if (vp == NULL) {
        DEBUGMSG(("mibII/vacm_vars", "\n"));
        return VACM_NOVIEW;
    }
    DEBUGMSG(("mibII/vacm_vars", ", vt=%d\n", vp->viewType));

    if (vp->viewType == SNMP_VIEW_EXCLUDED) {
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#if defined(NETSNMP_DISABLE_SNMPV1)
        if (pdu->version == SNMP_VERSION_2c)
#else
#if defined(NETSNMP_DISABLE_SNMPV2C)
        if (pdu->version == SNMP_VERSION_1)
#else
        if (pdu->version == SNMP_VERSION_1 || pdu->version == SNMP_VERSION_2c)
#endif
#endif
        {
            snmp_increment_statistic(STAT_SNMPINBADCOMMUNITYUSES);
        }
#endif
        return VACM_NOTINVIEW;
    }

    return VACM_SUCCESS;

}                               /* end vacm_in_view() */
コード例 #12
0
ファイル: snmpv3.c プロジェクト: DYFeng/infinidb
void
usm_parse_create_usmUser(const char *token, char *line)
{
    char           *cp;
    char            buf[SNMP_MAXBUF_MEDIUM];
    struct usmUser *newuser;
    u_char          userKey[SNMP_MAXBUF_SMALL], *tmpp;
    size_t          userKeyLen = SNMP_MAXBUF_SMALL;
    size_t          privKeyLen = 0;
    size_t          ret;
    int             testcase;

    newuser = usm_create_user();

    /*
     * READ: Security Name 
     */
    cp = copy_nword(line, buf, sizeof(buf));

    /*
     * might be a -e ENGINEID argument 
     */
    if (strcmp(buf, "-e") == 0) {
        size_t          ebuf_len = 32, eout_len = 0;
        u_char         *ebuf = (u_char *) malloc(ebuf_len);

        if (ebuf == NULL) {
            config_perror("malloc failure processing -e flag");
            usm_free_user(newuser);
            return;
        }

        /*
         * Get the specified engineid from the line.  
         */
        cp = copy_nword(cp, buf, sizeof(buf));
        if (!snmp_hex_to_binary(&ebuf, &ebuf_len, &eout_len, 1, buf)) {
            config_perror("invalid EngineID argument to -e");
            usm_free_user(newuser);
            SNMP_FREE(ebuf);
            return;
        }

        newuser->engineID = ebuf;
        newuser->engineIDLen = eout_len;
        cp = copy_nword(cp, buf, sizeof(buf));
    } else {
        newuser->engineID = snmpv3_generate_engineID(&ret);
        if (ret == 0) {
            usm_free_user(newuser);
            return;
        }
        newuser->engineIDLen = ret;
    }

    newuser->secName = strdup(buf);
    newuser->name = strdup(buf);

    if (!cp)
        goto add;               /* no authentication or privacy type */

    /*
     * READ: Authentication Type 
     */
#ifndef DISABLE_MD5
    if (strncmp(cp, "MD5", 3) == 0) {
        memcpy(newuser->authProtocol, usmHMACMD5AuthProtocol,
               sizeof(usmHMACMD5AuthProtocol));
    } else
#endif
        if (strncmp(cp, "SHA", 3) == 0) {
        memcpy(newuser->authProtocol, usmHMACSHA1AuthProtocol,
               sizeof(usmHMACSHA1AuthProtocol));
    } else {
        config_perror("Unknown authentication protocol");
        usm_free_user(newuser);
        return;
    }

    cp = skip_token(cp);

    /*
     * READ: Authentication Pass Phrase or key
     */
    if (!cp) {
        config_perror("no authentication pass phrase");
        usm_free_user(newuser);
        return;
    }
    cp = copy_nword(cp, buf, sizeof(buf));
    if (strcmp(buf,"-m") == 0) {
        /* a master key is specified */
        cp = copy_nword(cp, buf, sizeof(buf));
        ret = sizeof(userKey);
        tmpp = userKey;
        userKeyLen = 0;
        if (!snmp_hex_to_binary(&tmpp, &ret, &userKeyLen, 0, buf)) {
            config_perror("invalid key value argument to -m");
            usm_free_user(newuser);
            return;
        }
    } else if (strcmp(buf,"-l") != 0) {
        /* a password is specified */
        userKeyLen = sizeof(userKey);
        ret = generate_Ku(newuser->authProtocol, newuser->authProtocolLen,
                          (u_char *) buf, strlen(buf), userKey, &userKeyLen);
        if (ret != SNMPERR_SUCCESS) {
            config_perror("could not generate the authentication key from the "
                          "suppiled pass phrase.");
            usm_free_user(newuser);
            return;
        }
    }        
        
    /*
     * And turn it into a localized key 
     */
    ret =
        sc_get_properlength(newuser->authProtocol,
                            newuser->authProtocolLen);
    if (ret <= 0) {
        config_perror("Could not get proper authentication protocol key length");
        return;
    }
    newuser->authKey = (u_char *) malloc(ret);

    if (strcmp(buf,"-l") == 0) {
        /* a local key is directly specified */
        cp = copy_nword(cp, buf, sizeof(buf));
        newuser->authKeyLen = 0;
        if (!snmp_hex_to_binary(&newuser->authKey, &ret,
                                &newuser->authKeyLen, 0, buf)) {
            config_perror("invalid key value argument to -l");
            usm_free_user(newuser);
            return;
        }
        if (ret != newuser->authKeyLen) {
            config_perror("improper key length to -l");
            usm_free_user(newuser);
            return;
        }
    } else {
        newuser->authKeyLen = ret;
        ret = generate_kul(newuser->authProtocol, newuser->authProtocolLen,
                           newuser->engineID, newuser->engineIDLen,
                           userKey, userKeyLen,
                           newuser->authKey, &newuser->authKeyLen);
        if (ret != SNMPERR_SUCCESS) {
            config_perror("could not generate localized authentication key "
                          "(Kul) from the master key (Ku).");
            usm_free_user(newuser);
            return;
        }
    }

    if (!cp)
        goto add;               /* no privacy type (which is legal) */

    /*
     * READ: Privacy Type 
     */
    testcase = 0;
#ifndef DISABLE_DES
    if (strncmp(cp, "DES", 3) == 0) {
        memcpy(newuser->privProtocol, usmDESPrivProtocol,
               sizeof(usmDESPrivProtocol));
        testcase = 1;
	/* DES uses a 128 bit key, 64 bits of which is a salt */
	privKeyLen = 16;
    }
#endif
#ifdef HAVE_AES
    if (strncmp(cp, "AES128", 6) == 0 ||
               strncmp(cp, "AES", 3) == 0) {
        memcpy(newuser->privProtocol, usmAESPrivProtocol,
               sizeof(usmAESPrivProtocol));
        testcase = 1;
	privKeyLen = 16;
    }
#endif
    if (testcase == 0) {
        config_perror("Unknown privacy protocol");
        usm_free_user(newuser);
        return;
    }

    cp = skip_token(cp);
    /*
     * READ: Encryption Pass Phrase or key
     */
    if (!cp) {
        /*
         * assume the same as the authentication key 
         */
        memdup(&newuser->privKey, newuser->authKey, newuser->authKeyLen);
        newuser->privKeyLen = newuser->authKeyLen;
    } else {
        cp = copy_nword(cp, buf, sizeof(buf));
        
        if (strcmp(buf,"-m") == 0) {
            /* a master key is specified */
            cp = copy_nword(cp, buf, sizeof(buf));
            ret = sizeof(userKey);
            tmpp = userKey;
            userKeyLen = 0;
            if (!snmp_hex_to_binary(&tmpp, &ret, &userKeyLen, 0, buf)) {
                config_perror("invalid key value argument to -m");
                usm_free_user(newuser);
                return;
            }
        } else if (strcmp(buf,"-l") != 0) {
            /* a password is specified */
            userKeyLen = sizeof(userKey);
            ret = generate_Ku(newuser->authProtocol, newuser->authProtocolLen,
                              (u_char *) buf, strlen(buf), userKey, &userKeyLen);
            if (ret != SNMPERR_SUCCESS) {
                config_perror("could not generate the privacy key from the "
                              "suppiled pass phrase.");
                usm_free_user(newuser);
                return;
            }
        }        
        
        /*
         * And turn it into a localized key 
         */
        ret =
            sc_get_properlength(newuser->authProtocol,
                                newuser->authProtocolLen);
        if (ret < 0) {
            config_perror("could not get proper key length to use for the "
                          "privacy algorithm.");
            usm_free_user(newuser);
            return;
        }
        newuser->privKey = (u_char *) malloc(ret);

        if (strcmp(buf,"-l") == 0) {
            /* a local key is directly specified */
            cp = copy_nword(cp, buf, sizeof(buf));
            newuser->privKeyLen = 0;
            if (!snmp_hex_to_binary(&newuser->privKey, &ret,
                                    &newuser->privKeyLen, 0, buf)) {
                config_perror("invalid key value argument to -l");
                usm_free_user(newuser);
                return;
            }
        } else {
            newuser->privKeyLen = ret;
            ret = generate_kul(newuser->authProtocol, newuser->authProtocolLen,
                               newuser->engineID, newuser->engineIDLen,
                               userKey, userKeyLen,
                               newuser->privKey, &newuser->privKeyLen);
            if (ret != SNMPERR_SUCCESS) {
                config_perror("could not generate localized privacy key "
                              "(Kul) from the master key (Ku).");
                usm_free_user(newuser);
                return;
            }
        }
    }

    if ((newuser->privKeyLen >= privKeyLen) || (privKeyLen == 0)){
      newuser->privKeyLen = privKeyLen;
    }
    else {
      /* The privKey length is smaller than required by privProtocol */
      usm_free_user(newuser);
      return;
    }

  add:
    usm_add_user(newuser);
    DEBUGMSGTL(("usmUser", "created a new user %s at ", newuser->secName));
    DEBUGMSGHEX(("usmUser", newuser->engineID, newuser->engineIDLen));
    DEBUGMSG(("usmUser", "\n"));
}
コード例 #13
0
ファイル: tunnel.c プロジェクト: michalklempa/net-snmp
unsigned char  *
var_tunnelConfigEntry(struct variable *vp,
                      oid * name, size_t * length,
                      int exact, size_t * var_len,
                      WriteMethod ** write_method)
{
    static long     ret_int;
    struct tunnel  *tunnel;
    int             i;

    DEBUGMSGTL(("tunnel", "var_tunnelConfigEntry: "));
    DEBUGMSGOID(("tunnel", name, *length));
    DEBUGMSG(("tunnel", " %d\n", exact));

    updateTunnels();

    if (exact) {
        if (*length != tunnel_len + 3 + 4 + 4 + 1 + 1) {
            return NULL;
        }
        tunnel = getTunnelByConfigOid(name, length);
    } else {
        if (snmp_oid_compare(name, *length,
                             tunnel_configEntry_oid,
                             tunnel_configEntry_len) < 0) {
            *length = 0;
        }
        if ((*length) < tunnel_len) {
            memcpy((char *) name, (char *) tunnel_variables_oid,
                   tunnel_len * sizeof(oid));
        }
        if ((*length) < tunnel_len + 1) {
            name[tunnel_len] = 2;
        }
        if ((*length) < tunnel_len + 2) {
            name[tunnel_len + 1] = 1;
        }
        if ((*length) < tunnel_len + 3) {
            name[tunnel_len + 2] = 5;
        }
        for (i = MAX(*length, tunnel_len + 3);
             i < tunnel_len + 3 + 4 + 4 + 1 + 1; i++) {
            name[i] = 0;
        }
        *length = tunnel_len + 3 + 4 + 4 + 1 + 1;
        tunnel = getNextTunnelByConfigOid(name, length);
        if (!tunnel) {
            /*
             * end of column, continue with first row of next column 
             */
            tunnel = tunnels;
            name[tunnel_len + 2]++;
            if (name[tunnel_len + 2] > 6) {
                /*
                 * there is no next column 
                 */
                return NULL;
            }
            if (!tunnel) {
                /*
                 * there is no (next) row 
                 */
                return NULL;
            }
        }
    }

    if (!tunnel) {
        return NULL;
    }

    fillConfigOid(&name[tunnel_len + 3], tunnel);

    DEBUGMSGTL(("tunnel", "var_tunnelConfigEntry: using "));
    DEBUGMSGOID(("tunnel", name, *length));
    DEBUGMSG(("tunnel", "\n"));

    switch (name[tunnel_len + 2]) {
    case 5:                    /* tunnelConfigIfIndex */
        ret_int = tunnel->ifindex;
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        return (u_char *) & ret_int;
    case 6:                    /* tunnelConfigStatus */
        ret_int = 1;            /* active */
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        return (u_char *) & ret_int;
    default:
        return 0;
    }

    return NULL;
}
コード例 #14
0
ファイル: tunnel.c プロジェクト: michalklempa/net-snmp
unsigned char  *
var_tunnelIfEntry(struct variable *vp,
                  oid * name, size_t * length,
                  int exact, size_t * var_len, WriteMethod ** write_method)
{
    static unsigned long ret_addr;
    static long     ret_int;
    struct tunnel  *tunnel;

    DEBUGMSGTL(("tunnel", "var_tunnelIfEntry: "));
    DEBUGMSGOID(("tunnel", name, *length));
    DEBUGMSG(("tunnel", " %d\n", exact));

    updateTunnels();

    if (exact) {
        if (*length != tunnel_len + 3 + 1) {
            return NULL;
        }
        tunnel = getTunnelByIfIndex((int) name[*length - 1]);
    } else {
        if ((*length) < tunnel_len) {
            memcpy((char *) name, (char *) tunnel_variables_oid,
                   tunnel_len * sizeof(oid));
        }
        if ((*length) < tunnel_len + 1) {
            name[tunnel_len] = 1;
        }
        if ((*length) < tunnel_len + 2) {
            name[tunnel_len + 1] = 1;
        }
        if ((*length) < tunnel_len + 3) {
            name[tunnel_len + 2] = 1;
        }
        if ((*length) < tunnel_len + 4) {
            name[tunnel_len + 3] = 0;
        }
        *length = tunnel_len + 4;

        tunnel = getNextTunnelByIfIndex(name[*length - 1]);
        if (!tunnel) {
            /*
             * end of column, continue with first row of next column 
             */
            tunnel = tunnels;
            name[tunnel_len + 2]++;
            if (name[tunnel_len + 2] > 6) {
                /*
                 * there is no next column 
                 */
                return NULL;
            }
            if (!tunnel) {
                /*
                 * there is no (next) row 
                 */
                return NULL;
            }
        }
    }

    if (!tunnel) {
        return NULL;
    }

    name[*length - 1] = tunnel->ifindex;

    DEBUGMSGTL(("tunnel", "var_tunnelIfEntry: using"));
    DEBUGMSGOID(("tunnel", name, *length));
    DEBUGMSG(("tunnel", "\n"));

    switch (name[tunnel_len + 2]) {
    case 1:                    /* tunnelIfLocalAddress */
        ret_addr = tunnel->local;
        *var_len = 4;
        vp->type = ASN_IPADDRESS;
        *write_method = writeLocalAddress;
        return (u_char *) & ret_addr;
    case 2:                    /* tunnelIfRemoteAddress */
        ret_addr = tunnel->remote;
        *var_len = 4;
        vp->type = ASN_IPADDRESS;
        *write_method = writeRemoteAddress;
        return (u_char *) & ret_addr;
    case 3:                    /* tunnelIfEncapsMethod */
        ret_int = tunnel->encaps;
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        return (u_char *) & ret_int;
    case 4:                    /* tunnelIfHopLimit */
        ret_int = tunnel->hoplimit;
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        *write_method = writeHopLimit;
        return (u_char *) & ret_int;
    case 5:                    /* tunnelIfSecurity */
        ret_int = tunnel->security;
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        return (u_char *) & ret_int;
    case 6:                    /* tunnelIfTOS */
        ret_int = tunnel->tos;
        *var_len = sizeof(ret_int);
        vp->type = ASN_INTEGER;
        *write_method = writeTOS;
        return (u_char *) & ret_int;
    default:
        return 0;
    }

    return NULL;
}
コード例 #15
0
/*
 * Initialize the openserSIPStatusCodesTable table by defining how it is
 * structured.
 *
 * This function is mostly auto-generated.
 */
void initialize_table_openserSIPStatusCodesTable(void)
{
	netsnmp_table_registration_info *table_info;

	if(my_handler) {
		snmp_log(LOG_ERR, "initialize_table_openserSIPStatusCodes"
				"Table_handler called again\n");
		return;
	}

	memset(&cb, 0x00, sizeof(cb));

	/** create the table structure itself */
	table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);

	my_handler = netsnmp_create_handler_registration(
			"openserSIPStatusCodesTable",
			netsnmp_table_array_helper_handler,
			openserSIPStatusCodesTable_oid,
			openserSIPStatusCodesTable_oid_len,
			HANDLER_CAN_RWRITE);

	if (!my_handler || !table_info) {
		snmp_log(LOG_ERR, "malloc failed in initialize_table_openserSIP"
				"StatusCodesTable_handler\n");
		return; /** mallocs failed */
	}

	/** index: openserSIPStatusCodeMethod */
	netsnmp_table_helper_add_index(table_info, ASN_UNSIGNED);
	/** index: openserSIPStatusCodeValue */
	netsnmp_table_helper_add_index(table_info, ASN_UNSIGNED);

	table_info->min_column = openserSIPStatusCodesTable_COL_MIN;
	table_info->max_column = openserSIPStatusCodesTable_COL_MAX;

	/***************************************************
	 * registering the table with the master agent
	 */
	cb.get_value = openserSIPStatusCodesTable_get_value;

	cb.container =
		netsnmp_container_find("openserSIPStatusCodesTable_primary:"
				"openserSIPStatusCodesTable:"
				"table_container");

#ifdef openserSIPStatusCodesTable_CUSTOM_SORT
	netsnmp_container_add_index(cb.container,
			netsnmp_container_find(
				"openserSIPStatusCodesTable_custom:"
				"openserSIPStatusCodesTable:"
				"table_container"));

	cb.container->next->compare = openserSIPStatusCodesTable_cmp;
#endif
	cb.can_set = 1;

	cb.create_row    =
		(UserRowMethod*)openserSIPStatusCodesTable_create_row;

	cb.duplicate_row =
		(UserRowMethod*)openserSIPStatusCodesTable_duplicate_row;

	cb.delete_row    =
		(UserRowMethod*)openserSIPStatusCodesTable_delete_row;

	cb.row_copy      = (Netsnmp_User_Row_Operation *)
		openserSIPStatusCodesTable_row_copy;

	cb.can_activate  = (Netsnmp_User_Row_Action *)
		openserSIPStatusCodesTable_can_activate;

	cb.can_deactivate = (Netsnmp_User_Row_Action *)
		openserSIPStatusCodesTable_can_deactivate;

	cb.can_delete     =
		(Netsnmp_User_Row_Action *)openserSIPStatusCodesTable_can_delete;

	cb.set_reserve1   = openserSIPStatusCodesTable_set_reserve1;
	cb.set_reserve2   = openserSIPStatusCodesTable_set_reserve2;

	cb.set_action = openserSIPStatusCodesTable_set_action;
	cb.set_commit = openserSIPStatusCodesTable_set_commit;

	cb.set_free = openserSIPStatusCodesTable_set_free;
	cb.set_undo = openserSIPStatusCodesTable_set_undo;

	DEBUGMSGTL(("initialize_table_openserSIPStatusCodesTable",
				"Registering table openserSIPStatusCodesTable "
				"as a table array\n"));

	netsnmp_table_container_register(my_handler, table_info, &cb,
			cb.container, 1);
}
コード例 #16
0
u_char *var_extensible_version(struct variable *vp,
				      oid *name,
				      size_t *length,
				      int exact,
				      size_t *var_len,
				      WriteMethod **write_method)
{

  static long long_ret;
  static char errmsg[300];
  char *cptr;
  time_t curtime;
#ifdef CONFIGURE_OPTIONS
  static char config_opts[] = CONFIGURE_OPTIONS;
#endif

    DEBUGMSGTL(("ucd-snmp/versioninfo", "var_extensible_version: "));
    DEBUGMSGOID(("ucd-snmp/versioninfo", name, *length));
    DEBUGMSG(("ucd-snmp/versioninfo"," %d\n", exact));

  if (header_generic(vp,name,length,exact,var_len,write_method))
    return(NULL);
  
  switch (vp->magic) {
    case MIBINDEX:
      long_ret = name[8];
      return((u_char *) (&long_ret));
    case VERTAG:
      sprintf(errmsg,VersionInfo);
      *var_len = strlen(errmsg);
      return((u_char *) errmsg); 
    case VERDATE:
      sprintf(errmsg,"$Date: 2000/10/27 00:31:39 $");
      *var_len = strlen(errmsg);
      return((u_char *) errmsg); 
    case VERCDATE:
      curtime = time(NULL);
      cptr = ctime(&curtime);
      sprintf(errmsg,cptr);
      *var_len = strlen(errmsg)-1;
      return((u_char *) errmsg);
    case VERIDENT:
      sprintf(errmsg,"$Id: versioninfo.c,v 1.1 2000/10/27 00:31:39 pauli Exp $");
      *var_len = strlen(errmsg);
      return((u_char *) errmsg);
    case VERCONFIG:
#ifdef CONFIGURE_OPTIONS
      *var_len = strlen(config_opts);
      return (u_char *) config_opts;
#else
      sprintf(errmsg,"");
      *var_len = strlen(errmsg);
      return((u_char *) errmsg);
#endif
    case VERCLEARCACHE:
      *write_method = clear_cache;
      long_ret = 0;
      return((u_char *) &long_ret);
    case VERUPDATECONFIG:
      *write_method = update_hook;
      long_ret = 0;
      return((u_char *) &long_ret);
    case VERRESTARTAGENT:
      *write_method = restart_hook;
      long_ret = 0;
      return((u_char *) &long_ret);
    case VERDEBUGGING:
      *write_method = debugging_hook;
      long_ret = snmp_get_do_debugging();
      return((u_char *) &long_ret);
  }      
  return NULL;
}
コード例 #17
0
/**
 * @internal
 * process token value index line
 */
static int
_process_line_udp_ep(netsnmp_line_info *line_info, void *mem,
                     struct netsnmp_line_process_info_s* lpi)
{
    netsnmp_udp_endpoint_entry *ep = (netsnmp_udp_endpoint_entry *)mem;
    char                 *ptr, *sep;
    u_char               *u_ptr;
    size_t                u_ptr_len, offset, len;
    unsigned long long    inode;
    size_t                count = 0;

    /*
     * skip 'sl'
     */
    ptr = skip_not_white(line_info->start);
    if (NULL == ptr) {
        DEBUGMSGTL(("access:udp_endpoint", "no sl '%s'\n",
                       line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    ptr = skip_white(ptr);
    if (NULL == ptr) {
        DEBUGMSGTL(("text:util:tvi", "no space after sl '%s'\n",
                    line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }

    /*
     * get local address. ignore error on hex conversion, since that
     * function doesn't like the ':' between address and port. check the
     * offset to see if it worked. May need to flip string too.
     */
    u_ptr = ep->loc_addr;
    u_ptr_len = sizeof(ep->loc_addr);
    sep = strchr(ptr, ':');
    if (NULL == sep) {
        DEBUGMSGTL(("text:util:tvi", "no ':' '%s'\n",
                    line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    len = (sep - ptr);
    if (-1 == netsnmp_addrstr_hton(ptr, len)) {
        DEBUGMSGTL(("text:util:tvi", "bad length %d for loc addr '%s'\n",
                    u_ptr_len, line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    offset = 0;
    netsnmp_hex_to_binary(&u_ptr, &u_ptr_len, &offset, 0, ptr, NULL);
    if ((4 != offset) && (16 != offset)) {
        DEBUGMSGTL(("text:util:tvi", "bad offset %d for loc addr '%s'\n",
                    offset, line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    ep->loc_addr_len = offset;
    ptr += (offset * 2);
    ++ptr; /* skip ':' */

    /*
     * get local port
     */
    ep->loc_port = strtol(ptr, &ptr, 16);
    ptr = skip_white(ptr);

    /*
     * get remote address. ignore error on hex conversion, since that
     * function doesn't like the ':' between address and port. check the
     * offset to see if it worked. May need to flip string too.
     */
    u_ptr = ep->rmt_addr;
    u_ptr_len = sizeof(ep->rmt_addr);
    sep = strchr(ptr, ':');
    if (NULL == sep) {
        DEBUGMSGTL(("text:util:tvi", "no ':' '%s'\n",
                    line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    len = (sep - ptr);
    if (-1 == netsnmp_addrstr_hton(ptr, len)) {
        DEBUGMSGTL(("text:util:tvi", "bad length %d for rmt addr '%s'\n",
                    u_ptr_len, line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    offset = 0;
    netsnmp_hex_to_binary(&u_ptr, &u_ptr_len, &offset, 0, ptr, NULL);
    if ((4 != offset) && (16 != offset)) {
        DEBUGMSGTL(("text:util:tvi", "bad offset %d for rmt addr '%s'\n",
                    offset, line_info->start));
        return PMLP_RC_MEMORY_UNUSED;
    }
    ep->rmt_addr_len = offset;
    ptr += (offset * 2);
    ++ptr; /* skip ':' */

    /*
     * get remote port
     */
    ep->rmt_port = strtol(ptr, &ptr, 16);
    ptr = skip_white(ptr);

    /*
     * get state too
     */
    ep->state = strtol(ptr, &ptr, 16);

    /*
     * Use inode as instance value.
     */
    while (count != 5) {
	ptr = skip_white(ptr);
	ptr = skip_not_white(ptr);
	count++;
    }
    inode = strtoull(ptr, &ptr, 0);
    ep->instance = (u_int)inode;

    ep->index = (u_int)(lpi->user_context);
    lpi->user_context = (void*)((u_int)(lpi->user_context) + 1);

    ep->oid_index.oids = &ep->index;
    ep->oid_index.len = 1;

    return PMLP_RC_MEMORY_USED;
}
コード例 #18
0
ファイル: lcd_time.c プロジェクト: EPiCS/reconos_v2
/*******************************************************************-o-******
 * get_enginetime
 *
 * Parameters:
 *	*engineID
 *	 engineID_len
 *	*engineboot
 *	*engine_time
 *      
 * Returns:
 *	SNMPERR_SUCCESS		Success -- when a record for engineID is found.
 *	SNMPERR_GENERR		Otherwise.
 *
 *
 * Lookup engineID and return the recorded values for the
 * <engine_time, engineboot> tuple adjusted to reflect the estimated time
 * at the engine in question.
 *
 * Special case: if engineID is NULL or if engineID_len is 0 then
 * the time tuple is returned immediately as zero.
 *
 * XXX	What if timediff wraps?  >shrug<
 * XXX  Then: you need to increment the boots value.  Now.  Detecting
 *            this is another matter.
 */
int
get_enginetime_ex(	u_char	*engineID,	
		u_int	 engineID_len,
		u_int	*engineboot,
		u_int	*engine_time,
		u_int	*last_engine_time,
		u_int   authenticated)
{
	int		rval	 = SNMPERR_SUCCESS;
	time_t		timediff = 0;
	Enginetime	e	 = NULL;



	/*
	 * Sanity check.
	 */
	if ( !engine_time || !engineboot || !last_engine_time) {
		QUITFUN(SNMPERR_GENERR, get_enginetime_ex_quit);
	}


	/*
	 * Compute estimated current engine_time tuple at engineID if
	 * a record is cached for it.
	 */
	*last_engine_time = *engine_time = *engineboot = 0;

	if ( !engineID || (engineID_len<=0) ) {
		QUITFUN(SNMPERR_GENERR, get_enginetime_ex_quit);
	}

	if ( !(e = search_enginetime_list(engineID, engineID_len)) ) {
		QUITFUN(SNMPERR_GENERR, get_enginetime_ex_quit);
	}

#ifdef LCD_TIME_SYNC_OPT
        if (!authenticated || e->authenticatedFlag) {
#endif	
	*last_engine_time = *engine_time = e->engineTime;
	*engineboot = e->engineBoot;

	timediff = time(NULL) - e->lastReceivedEngineTime;
#ifdef LCD_TIME_SYNC_OPT	
        }
#endif	

	if ( timediff > (int)(ENGINETIME_MAX - *engine_time) ) {
		*engine_time = (timediff - (ENGINETIME_MAX - *engine_time));

		/* FIX -- move this check up... should not change anything
		 * if engineboot is already locked.  ???
		 */
		if (*engineboot < ENGINEBOOT_MAX) {
			*engineboot += 1;
		}

	} else {
		*engine_time += timediff;
	}

        DEBUGMSGTL(("lcd_get_enginetime_ex", "engineID "));
        DEBUGMSGHEX(("lcd_get_enginetime_ex", engineID, engineID_len));
        DEBUGMSG(("lcd_get_enginetime_ex", ": boots=%d, time=%d\n", *engineboot,
                  *engine_time));

get_enginetime_ex_quit:
	return rval;

}  /* end get_enginetime_ex() */
コード例 #19
0
/************************************************************
 * compare two context pointers here. Return -1 if lhs < rhs,
 * 0 if lhs == rhs, and 1 if lhs > rhs.
 */
static int
saHpiSensorReadingNormalMinTable_cmp( const void *lhs, const void *rhs )
{
	saHpiSensorReadingNormalMinTable_context *context_l =
	(saHpiSensorReadingNormalMinTable_context *)lhs;
	saHpiSensorReadingNormalMinTable_context *context_r =
	(saHpiSensorReadingNormalMinTable_context *)rhs;

	/*
	 * check primary key, then secondary. Add your own code if
	 * there are more than 2 indexes
	 */
	DEBUGMSGTL ((AGENT, "saHpiSensorReadingNormalMinTable_cmp, called\n"));

	/* check for NULL pointers */
	if (lhs == NULL || rhs == NULL ) {
		DEBUGMSGTL((AGENT,"saHpiSensorReadingNormalMinTable_cmp() NULL pointer ERROR\n" ));
		return 0;
	}
	/* CHECK FIRST INDEX,  saHpiDomainId */
	if ( context_l->index.oids[0] < context_r->index.oids[0])
		return -1;

	if ( context_l->index.oids[0] > context_r->index.oids[0])
		return 1;

	if ( context_l->index.oids[0] == context_r->index.oids[0]) {
		/* If saHpiDomainId index is equal sort by second index */
		/* CHECK SECOND INDEX,  saHpiResourceEntryId */
		if ( context_l->index.oids[1] < context_r->index.oids[1])
			return -1;

		if ( context_l->index.oids[1] > context_r->index.oids[1])
			return 1;

		if ( context_l->index.oids[1] == context_r->index.oids[1]) {
			/* If saHpiResourceEntryId index is equal sort by third index */
			/* CHECK THIRD INDEX,  saHpiResourceIsHistorical */
			if ( context_l->index.oids[2] < context_r->index.oids[2])
				return -1;

			if ( context_l->index.oids[2] > context_r->index.oids[2])
				return 1;

			if ( context_l->index.oids[2] == context_r->index.oids[2]) {
				/* If saHpiResourceIsHistorical index is equal sort by forth index */
				/* CHECK FORTH INDEX,  saHpiSensorNum */
				if ( context_l->index.oids[3] < context_r->index.oids[3])
					return -1;

				if ( context_l->index.oids[3] > context_r->index.oids[3])
					return 1;

				if ( context_l->index.oids[3] == context_r->index.oids[3])
					return 0;
			}
		}
	}

	return 0;
}
コード例 #20
0
ファイル: lcd_time.c プロジェクト: EPiCS/reconos_v2
/*******************************************************************-o-******
 * set_enginetime
 *
 * Parameters:
 *	*engineID
 *	 engineID_len
 *	 engineboot
 *	 engine_time
 *      
 * Returns:
 *	SNMPERR_SUCCESS		Success.
 *	SNMPERR_GENERR		Otherwise.
 *
 *
 * Lookup engineID and store the given <engine_time, engineboot> tuple
 * and then stamp the record with a consistent source of local time.
 * If the engineID record does not exist, create one.
 *
 * Special case: engineID is NULL or engineID_len is 0 defines an engineID
 * that is "always set."
 *
 * XXX	"Current time within the local engine" == time(NULL)...
 */
int
set_enginetime(	u_char	*engineID,
		u_int	 engineID_len,
		u_int	 engineboot,
		u_int  	 engine_time,
		u_int    authenticated)
{
	int		rval = SNMPERR_SUCCESS,
			iindex;
	Enginetime	e = NULL;



	/*
	 * Sanity check.
	 */
	if ( !engineID || (engineID_len <= 0) ) {
		return rval;
	}


	/*
	 * Store the given <engine_time, engineboot> tuple in the record
	 * for engineID.  Create a new record if necessary.
	 */
	if ( !(e = search_enginetime_list(engineID, engineID_len)) )
	{
		if ( (iindex = hash_engineID(engineID, engineID_len)) < 0 )
		{
			QUITFUN(SNMPERR_GENERR, set_enginetime_quit);
		}

		e = (Enginetime) calloc(1,sizeof(*e));

		e->next = etimelist[iindex];
		etimelist[iindex] = e;

		e->engineID = (u_char *) calloc(1,engineID_len);
		memcpy(e->engineID, engineID, engineID_len);

		e->engineID_len = engineID_len;
	}
#ifdef LCD_TIME_SYNC_OPT	
	if (authenticated || !e->authenticatedFlag) {
	  e->authenticatedFlag = authenticated;
#else
	if (authenticated) {
#endif
	  e->engineTime		  = engine_time;
	  e->engineBoot		  = engineboot;
	  e->lastReceivedEngineTime = time(NULL);
        }

	e = NULL;	/* Indicates a successful update. */

        DEBUGMSGTL(("lcd_set_enginetime", "engineID "));
        DEBUGMSGHEX(("lcd_set_enginetime", engineID, engineID_len));
        DEBUGMSG(("lcd_set_enginetime", ": boots=%d, time=%d\n", engineboot,
                  engine_time));

set_enginetime_quit:
	SNMP_FREE(e);

	return rval;

}  /* end set_enginetime() */




/*******************************************************************-o-******
 * search_enginetime_list
 *
 * Parameters:
 *	*engineID
 *	 engineID_len
 *      
 * Returns:
 *	Pointer to a etimelist record with engineID <engineID>  -OR-
 *	NULL if no record exists.
 *
 *
 * Search etimelist for an entry with engineID.
 *
 * ASSUMES that no engineID will have more than one record in the list.
 */
Enginetime
search_enginetime_list(u_char *engineID, u_int engineID_len)
{
	int		rval = SNMPERR_SUCCESS;
	Enginetime	e    = NULL;


	/*
	 * Sanity check.
	 */
	if ( !engineID || (engineID_len<=0) ) {
		QUITFUN(SNMPERR_GENERR, search_enginetime_list_quit);
	}


	/*
	 * Find the entry for engineID if there be one.
	 */
	rval = hash_engineID(engineID, engineID_len);
	if (rval < 0) {
		QUITFUN(SNMPERR_GENERR, search_enginetime_list_quit);
	}
	e = etimelist[rval];

	for ( /*EMPTY*/; e; e = e->next )
	{
		if ( (engineID_len == e->engineID_len)
			&& !memcmp(e->engineID, engineID, engineID_len) )
		{
			break;
		}
	}
	

search_enginetime_list_quit:
	return e;

}  /* end search_enginetime_list() */
コード例 #21
0
/*
 * SaErrorT populate_sensor_max()
 */
SaErrorT populate_sensor_normal_min(SaHpiSessionIdT sessionid, 
				    SaHpiRdrT *rdr_entry,
				    SaHpiRptEntryT *rpt_entry)
{

	DEBUGMSGTL ((AGENT, "populate_sensor_normal_min, called\n"));

	SaErrorT rv = SA_OK;
        int new_row = MIB_FALSE;

	oid sensor_normal_min_oid[SENSOR_READING_NORMAL_MIN_INDEX_NR];
	netsnmp_index sensor_normal_min_index;
	saHpiSensorReadingNormalMinTable_context *sensor_normal_min_context;

	/* check for NULL pointers */
	if (!rdr_entry) {
		DEBUGMSGTL ((AGENT, 
			     "ERROR: populate_sensor_normal_min() passed NULL rdr_entry pointer\n"));
		return AGENT_ERR_INTERNAL_ERROR;
	}
	if (!rpt_entry) {
		DEBUGMSGTL ((AGENT, 
			     "ERROR: populate_sensor_normal_min() passed NULL rdr_entry pointer\n"));
		return AGENT_ERR_INTERNAL_ERROR;
	}

	/* BUILD oid for new row */
	/* assign the number of indices */
	sensor_normal_min_index.len = SENSOR_READING_NORMAL_MIN_INDEX_NR;
	/** Index saHpiDomainId is external */
	sensor_normal_min_oid[0] = get_domain_id(sessionid);
	/** Index saHpiResourceId is external */
	sensor_normal_min_oid[1] = rpt_entry->ResourceId;
	/** Index saHpiResourceIsHistorical is external */
	sensor_normal_min_oid[2] = MIB_FALSE;
	/** Index saHpiSensorNum */
	sensor_normal_min_oid[3] = rdr_entry->RdrTypeUnion.SensorRec.Num;
	/* assign the indices to the index */
	sensor_normal_min_index.oids = (oid *) & sensor_normal_min_oid;

	/* See if Row exists. */
	sensor_normal_min_context = NULL;
	sensor_normal_min_context = CONTAINER_FIND(cb.container, &sensor_normal_min_index);

	if (!sensor_normal_min_context) {
		// New entry. Add it
		sensor_normal_min_context = 
		saHpiSensorReadingNormalMinTable_create_row(&sensor_normal_min_index);
                new_row = MIB_TRUE;
	}
	if (!sensor_normal_min_context) {
		snmp_log (LOG_ERR, "Not enough memory for a Normal Min row!");
		return AGENT_ERR_INTERNAL_ERROR;
	}

	/** TruthValue = ASN_INTEGER */
	sensor_normal_min_context->saHpiSensorReadingNormalMinIsSupported =
	(rdr_entry->RdrTypeUnion.SensorRec.DataFormat.Range.NormalMin.IsSupported
	 == SAHPI_TRUE) ? MIB_TRUE : MIB_FALSE;

	/** SaHpiSensorReadingType = ASN_INTEGER */
	sensor_normal_min_context->saHpiSensorReadingNormalMinType = 
	rdr_entry->RdrTypeUnion.SensorRec.DataFormat.Range.NormalMin.Type + 1;

	/** SaHpiSensorReadingValue = ASN_OCTET_STR */
	sensor_normal_min_context->saHpiSensorReadingNormalMinValue_len =
	set_sensor_reading_value(
				&rdr_entry->RdrTypeUnion.SensorRec.DataFormat.Range.NormalMin,
				sensor_normal_min_context->saHpiSensorReadingNormalMinValue);

	if (new_row == MIB_TRUE)
                CONTAINER_INSERT (cb.container, sensor_normal_min_context);

	return rv;
}
コード例 #22
0
ファイル: disk_linux.c プロジェクト: marker55/hp-ams
int netsnmp_arch_linosdiskio_container_load(netsnmp_container* container)
{
    cpqLinOsDiskTable_entry *entry;
    netsnmp_index tmp;
    oid oid_index[2];

    long  rc = 0;
    int i;
    struct timeval curr_time;
    struct timeval e_time;
    int interval;

    read_line_t *disklines = NULL;
    int maj, min;
    char diskname[16];

    gettimeofday(&curr_time, NULL);
    DEBUGMSGTL(("linosdiskio:container:load", "loading\n"));

    DEBUGMSGTL(("linosdiskio:container:load", "Container=%p\n",container));

    if ((disklines = ReadFileLines("/proc/diskstats")) != NULL) {

        for (i =0; i < disklines->count;i++) {
            unsigned long long reads, rmerged, read_sec, read_ms, 
                                writes, wmerged, write_sec, write_ms, 
                                io_inflight, io_ms, io_ms_weightd;

            if (sscanf(disklines->line[i],"%d %d %s ", &maj, &min, diskname) != 3)
                continue;
            if (min % 16)
                continue;
            if (!strncmp(diskname,"sd", 2) || 
                !strncmp(diskname,"hd", 2) ||
                !strncmp(diskname,"cciss", 5)) {
                sscanf(disklines->line[i],
                    "%d %d %s %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu", 
                    &maj, &min, diskname, 
                    &reads, &rmerged, &read_sec, &read_ms, 
                    &writes, &wmerged, &write_sec, &write_ms, 
                    &io_inflight, &io_ms, &io_ms_weightd);

                oid_index[0] = maj;
                oid_index[1] = min;
                tmp.len = 2;
                tmp.oids = &oid_index[0];
                entry = CONTAINER_FIND(container, &tmp);
                if (entry) {
                    entry->prev_time.tv_sec = entry->curr_time.tv_sec;
                    entry->prev_time.tv_usec = entry->curr_time.tv_usec;
    
                    entry->prev_reads = entry->curr_reads;
                    entry->prev_read_merge = entry->curr_read_merge;
                    entry->prev_read_sectors = entry->curr_read_sectors;
                    entry->prev_read_ms = entry->curr_read_ms;
                    entry->prev_writes = entry->curr_writes;
                    entry->prev_write_merge = entry->curr_write_merge;
                    entry->prev_write_sectors = entry->curr_write_sectors;
                    entry->prev_write_ms = entry->curr_write_ms;
     
                    entry->curr_reads = reads;
                    entry->curr_read_merge = rmerged;
                    entry->curr_read_sectors = read_sec;
                    entry->curr_read_ms = read_ms;
                    entry->curr_writes = writes;
                    entry->curr_write_merge = wmerged;
                    entry->curr_write_sectors = write_sec;
                    entry->curr_write_ms = write_ms;
     
                    entry->curr_time.tv_sec = curr_time.tv_sec;
                    entry->curr_time.tv_usec = curr_time.tv_usec;
                    timersub(&entry->curr_time, &entry->prev_time, &e_time);
                    /* interval between samples is in .01 sec */
                    interval = (e_time.tv_sec*1000 + e_time.tv_usec/1000)/10;
     
                    if (interval) {
                        entry->cpqLinOsDiskReadIos = 
                                (entry->curr_reads - entry->prev_reads);
                        entry->cpqLinOsDiskReadMerges =
                                (entry->curr_read_merge - entry->prev_read_merge);
                        entry->cpqLinOsDiskReadSectors = 
                                (entry->curr_read_sectors - entry->prev_read_sectors);
                        entry->cpqLinOsDiskReadDurationMs = 
                                (entry->curr_read_ms - entry->prev_read_ms);
    
                        entry->cpqLinOsDiskReadIosPerSec = 
                                entry->cpqLinOsDiskReadIos/(interval/100);
                        entry->cpqLinOsDiskReadSectorsPerSec = 
                                entry->cpqLinOsDiskReadSectors/(interval/100);
                        if (entry->cpqLinOsDiskReadIos)
                            entry->cpqLinOsDiskReadDurationMsPerIos = 
                                entry->cpqLinOsDiskReadDurationMs/entry->cpqLinOsDiskReadIos;
                        else
                            entry->cpqLinOsDiskReadDurationMsPerIos = 0;
    
                        entry->cpqLinOsDiskWriteIos = 
                                (entry->curr_writes - entry->prev_writes);
                        entry->cpqLinOsDiskWriteMerges =
                                (entry->curr_write_merge - entry->prev_write_merge);
                        entry->cpqLinOsDiskWriteSectors = 
                                (entry->curr_write_sectors - entry->prev_write_sectors);
                        entry->cpqLinOsDiskWriteDurationMs = 
                                (entry->curr_write_ms - entry->prev_write_ms);
    
                        entry->cpqLinOsDiskWriteIosPerSec = 
                                entry->cpqLinOsDiskWriteIos/(interval/100);
                        entry->cpqLinOsDiskWriteSectorsPerSec = 
                                entry->cpqLinOsDiskWriteSectors/(interval/100);
                        if (entry->cpqLinOsDiskWriteIos)
                            entry->cpqLinOsDiskWriteDurationMsPerIos = 
                                entry->cpqLinOsDiskWriteDurationMs/entry->cpqLinOsDiskWriteIos;
                        else
                            entry->cpqLinOsDiskWriteDurationMsPerIos = 0;
                    }
    
                } else {
                    entry = cpqLinOsDiskTable_createEntry(container, (oid)maj, (oid)min);
                    entry->cpqLinOsDiskScsiIndex = 0;
                    entry->cpqLinOsDiskMajorIndex = maj;
                    entry->cpqLinOsDiskMinorIndex = min;
                    entry->cpqLinOsDiskName_len = strlen(diskname);
                    strncpy(entry->cpqLinOsDiskName, diskname, strlen(diskname));
     
                    entry->prev_reads = 0;
                    entry->prev_read_merge = 0;
                    entry->prev_read_sectors = 0;
                    entry->prev_read_ms = 0;
                    entry->prev_writes = 0;
                    entry->prev_write_merge = 0;
                    entry->prev_write_sectors = 0;
                    entry->prev_write_ms = 0;
     
                    entry->curr_reads = reads;
                    entry->curr_read_merge = rmerged;
                    entry->curr_read_sectors = read_sec;
                    entry->curr_read_ms = read_ms;
                    entry->curr_writes = writes;
                    entry->curr_write_merge = wmerged;
                    entry->curr_write_sectors = write_sec;
                    entry->curr_write_ms = write_ms;
     
                    entry->cpqLinOsDiskReadIos = 0;
                    entry->cpqLinOsDiskReadMerges = 0;
                    entry->cpqLinOsDiskReadSectors = 0;
                    entry->cpqLinOsDiskReadDurationMs = 0;
    
                    entry->cpqLinOsDiskWriteIos = 0;
                    entry->cpqLinOsDiskWriteMerges =0;
                    entry->cpqLinOsDiskWriteSectors = 0;
                    entry->cpqLinOsDiskWriteDurationMs = 0;
    
                    entry->cpqLinOsDiskReadIosPerSec = 0;
                    entry->cpqLinOsDiskReadSectorsPerSec = 0;
                    entry->cpqLinOsDiskReadDurationMsPerIos = 0;
    
                    entry->cpqLinOsDiskWriteIosPerSec = 0;
                    entry->cpqLinOsDiskWriteSectorsPerSec = 0;
                    entry->cpqLinOsDiskWriteDurationMsPerIos = 0;
    
                    entry->curr_time.tv_sec = curr_time.tv_sec;
                    entry->curr_time.tv_usec = curr_time.tv_usec;
                    rc = CONTAINER_INSERT(container, entry);
                    DEBUGMSGTL(("linosdiskio:container:load", "Entry created\n"));
                }
            }
        } 
        free(disklines->read_buf);
        free(disklines);
    }    
    
    return(rc);
}
コード例 #23
0
ファイル: snmpv3.c プロジェクト: Undrizzle/yolanda
void
usm_parse_create_usmUser(const char *token, char *line) {
  char *cp;
  char buf[SNMP_MAXBUF_MEDIUM];
  struct usmUser *newuser;
  u_char	  userKey[SNMP_MAXBUF_SMALL];
  size_t	  userKeyLen = SNMP_MAXBUF_SMALL;
  int ret;

  newuser = usm_create_user();

  /* READ: Security Name */
  cp = copy_word(line, buf);
  newuser->secName = strdup(buf);
  newuser->name = strdup(buf);

  newuser->engineID = snmpv3_generate_engineID(&ret);
  if ( ret < 0 ) {
    usm_free_user(newuser);
    return;
  }
  newuser->engineIDLen = ret;

  if (!cp)
    goto add; /* no authentication or privacy type */

  /* READ: Authentication Type */
  if (strncmp(cp, "MD5", 3) == 0) {
    memcpy(newuser->authProtocol, usmHMACMD5AuthProtocol,
           sizeof(usmHMACMD5AuthProtocol));
  } else if (strncmp(cp, "SHA", 3) == 0) {
    memcpy(newuser->authProtocol, usmHMACSHA1AuthProtocol,
           sizeof(usmHMACSHA1AuthProtocol));
  } else {
    config_perror("Unknown authentication protocol");
    usm_free_user(newuser);
    return;
  }

  cp = skip_token(cp);

  /* READ: Authentication Pass Phrase */
  if (!cp) {
    config_perror("no authentication pass phrase");
    usm_free_user(newuser);
    return;
  }
  cp = copy_word(cp, buf);
  /* And turn it into a localized key */
  ret = generate_Ku(newuser->authProtocol, newuser->authProtocolLen,
		    (u_char *)buf, strlen(buf),
		    userKey, &userKeyLen );
  if (ret != SNMPERR_SUCCESS) {
    config_perror("Error generating auth key from pass phrase.");
    usm_free_user(newuser);
    return;
  }
  newuser->authKeyLen =
    sc_get_properlength(newuser->authProtocol, newuser->authProtocolLen);
  newuser->authKey = (u_char *) malloc(newuser->authKeyLen);
  ret = generate_kul(newuser->authProtocol, newuser->authProtocolLen,
		     newuser->engineID, newuser->engineIDLen,
		     userKey, userKeyLen,
		     newuser->authKey, &newuser->authKeyLen );
  if (ret != SNMPERR_SUCCESS) {
    config_perror("Error generating localized auth key (Kul) from Ku.");
    usm_free_user(newuser);
    return;
  }

  if (!cp)
    goto add; /* no privacy type (which is legal) */
  
  /* READ: Privacy Type */
  if (strncmp(cp, "DES", 3) == 0) {
    memcpy(newuser->privProtocol, usmDESPrivProtocol,
           sizeof(usmDESPrivProtocol));
  } else {
    config_perror("Unknown privacy protocol");
    usm_free_user(newuser);
    return;
  }

  cp = skip_token(cp);
  /* READ: Authentication Pass Phrase */
  if (!cp) {
    /* assume the same as the authentication key */
    memdup(&newuser->privKey, newuser->authKey, newuser->authKeyLen);
  } else {
    cp = copy_word(cp, buf);
    /* And turn it into a localized key */
    ret = generate_Ku(newuser->authProtocol, newuser->authProtocolLen,
                      (u_char *)buf, strlen(buf),
                      userKey, &userKeyLen );
    if (ret != SNMPERR_SUCCESS) {
      config_perror("Error generating priv key from pass phrase.");
      usm_free_user(newuser);
      return;
    }

    ret = sc_get_properlength(newuser->authProtocol, newuser->authProtocolLen);
    if (ret < 0) {
      config_perror("Error getting proper key length for priv algorithm.");
      usm_free_user(newuser);
      return;
    }
    newuser->privKeyLen = ret;
      
    newuser->privKey = (u_char *) malloc(newuser->privKeyLen);
    ret = generate_kul(newuser->authProtocol, newuser->authProtocolLen,
                       newuser->engineID, newuser->engineIDLen,
                       userKey, userKeyLen,
                       newuser->privKey, &newuser->privKeyLen );
    if (ret != SNMPERR_SUCCESS) {
      config_perror("Error generating localized priv key (Kul) from Ku.");
      usm_free_user(newuser);
      return;
    }
  }
add:
  usm_add_user(newuser);
  DEBUGMSGTL(("usmUser","created a new user %s\n", newuser->secName));
}
コード例 #24
0
int
modify_saHpiSensorThdLowMajorTable_row (SaHpiDomainIdT domain_id,
					   SaHpiResourceIdT resource_id,
					   SaHpiSensorNumT sensor_num,

					   SaHpiSensorThdDefnT *threshold_def,
					   SaHpiSensorReadingT * reading,
					   saHpiSensorThdLowMajorTable_context
					   * ctx)
{

  long hash = 0;
  unsigned int update_entry = MIB_FALSE;
  //  char format[SENSOR_THD_INTER_MAX];

  DEBUGMSGTL ((AGENT, "Modify saHpiSensorThdLowMajorTable_ctx: Entry.\n"));

  if (ctx)
    {
      hash = calculate_hash_value (reading, sizeof (SaHpiSensorReadingT));

      DEBUGMSGTL ((AGENT, " Hash value: %d, in ctx: %d\n", hash, ctx->hash));

      if (ctx->hash != 0)
	{
	  /* Only do the check if the hash value is something else than zero.
	   * 'zero' value is only for newly created records, and in some
	   * rare instances when the hash has rolled to zero - in which
	   * case we will just consider the worst-case scenario and update
	   * the record and not trust the hash value.
	   */
	  if (hash == ctx->hash)
	    {
	      /* The same data. No need to change. */
	      return AGENT_ENTRY_EXIST;
	    }
	  if ((ctx->domain_id == domain_id) &&
	      (ctx->resource_id == resource_id) &&
	      (ctx->sensor_id == sensor_num))
	    {
	      update_entry = MIB_TRUE;
	      DEBUGMSGTL ((AGENT,
			   "Updating ThdLowMajorTable row [%d, %d, %d]\n",
			   domain_id, resource_id, sensor_num));
	    }
	}

      if (hash == 0)		/* Might happend - roll-over */
	hash = 1;		/* Need this - we consider hash
				 * values of '0' uninitialized */
      ctx->hash = hash;
      ctx->resource_id = resource_id;
      ctx->domain_id = domain_id;
      ctx->sensor_id = sensor_num;


      build_reading_strings (reading,
			     0,
			     &ctx->saHpiSensorThdLowMajorValuesPresent,
			     &ctx->saHpiSensorThdLowMajorRaw,
			     ctx->saHpiSensorThdLowMajorInterpreted,
			     &ctx->saHpiSensorThdLowMajorInterpreted_len,
			     SENSOR_THD_INTER_MAX,
			     NULL, NULL, NULL, 0);

      ctx->saHpiSensorThdLowMajorIsReadable = 
	((threshold_def->ReadThold & SAHPI_STM_LOW_MAJOR) == SAHPI_STM_LOW_MAJOR) ?
	MIB_TRUE : MIB_FALSE;
      
      ctx->saHpiSensorThdLowMajorIsWritable = 
	((threshold_def->WriteThold & SAHPI_STM_LOW_MAJOR) == SAHPI_STM_LOW_MAJOR) ?
	MIB_TRUE : MIB_FALSE;
  ctx->saHpiSensorThdLowMajorIsFixed = 
	((threshold_def->FixedThold & SAHPI_STM_LOW_MAJOR) == SAHPI_STM_LOW_MAJOR) ?
	MIB_TRUE : MIB_FALSE;

      /* END */
      DEBUGMSGTL ((AGENT, "Modify saHpiSensorThdLowMajorTable_ctx: Exit"));
      if (update_entry == MIB_TRUE)
	return AGENT_ENTRY_EXIST;
      return AGENT_NEW_ENTRY;

    }

  DEBUGMSGTL ((AGENT,
	       "Modify saHpiSensorThdLowMajorTable_ctx: Exit (NULL DATA)"));

  return AGENT_ERR_NULL_DATA;
}
コード例 #25
0
ファイル: snmpv3.c プロジェクト: Undrizzle/yolanda
/*******************************************************************-o-******
 * engineID_conf
 *
 * Parameters:
 *	*word
 *	*cptr
 *
 * This function reads a string from the configuration file and uses that
 * string to initialize the engineID.  It's assumed to be human readable.
 */
void
engineID_conf(const char *word, char *cptr)
{
  setup_engineID(NULL, cptr);
  DEBUGMSGTL(("snmpv3","initialized engineID with: %s\n",cptr));
}
コード例 #26
0
int set_ThdLowMajor (saHpiSensorThdLowMajorTable_context *ctx) {

  SaHpiSensorThresholdsT thd;
  SaHpiSessionIdT session_id;
  SaErrorT rc;

  DEBUGMSGTL ((AGENT, "set_ThdLowMajor: Entry.\n"));
  if (ctx)
    {

      memset (&thd, 0x00, sizeof (SaHpiSensorThresholdsT));

      rc = getSaHpiSession (&session_id);
      if (rc != AGENT_ERR_NOERROR)
	{
	  DEBUGMSGTL ((AGENT, "Call to getSaHpiSession failed with rc: %d\n",
		       rc));
	  return rc;
	}
      /*
       * Get the current threshold information
       */
      DEBUGMSGTL((AGENT,"resource_id: %d, sensor_id: %d\n", ctx->resource_id, ctx->sensor_id));
      rc = saHpiSensorThresholdsGet (session_id,
				     ctx->resource_id,
				     ctx->sensor_id, &thd);

      if (rc != SA_OK)
	{
	  snmp_log (LOG_ERR,
		    "Call to saHpiSensorThresholdGet fails with return code: %s.\n",
		    get_error_string (rc));
	  DEBUGMSGTL ((AGENT,
		       "Call to saHpiSensorThresholdsGet fails with return code: %s\n",
		       get_error_string (rc)));
	  return AGENT_ERR_OPERATION;
	}

	/* Update the correct entry.	 */
      
      if (thd.LowMajor.ValuesPresent & SAHPI_SRF_INTERPRETED) {
	thd.LowMajor.Interpreted.Type = SAHPI_SENSOR_INTERPRETED_TYPE_BUFFER;
	memcpy(&thd.LowMajor.Interpreted.Value.SensorBuffer,
		&ctx->saHpiSensorThdLowMajorInterpreted,
		ctx->saHpiSensorThdLowMajorInterpreted_len);
	       
      }
      if (thd.LowMajor.ValuesPresent & SAHPI_SRF_RAW) {
	thd.LowMajor.Raw = ctx->saHpiSensorThdLowMajorRaw;
      }

      /*
       * Set the thresholds 
       */
      rc = saHpiSensorThresholdsSet (session_id,
				     ctx->resource_id,
				     ctx->sensor_id, &thd);

      if (rc != SA_OK)
	{
	  snmp_log (LOG_ERR,
		    "Call to saHpiSensorThresholdSet fails with return code: %s.\n",
		    get_error_string (rc));
	  DEBUGMSGTL ((AGENT,
		       "Call to saHpiSensorThresholdsSet fails with return code: %s\n",
		       get_error_string (rc)));
	  return AGENT_ERR_OPERATION;
	}

      /* 
       * Re-read the data. Might be different, so we will need
       * to populate the ctx.
       */

      memset (&thd, 0x00, sizeof (SaHpiSensorThresholdsT));
      rc = saHpiSensorThresholdsGet (session_id,
				     ctx->resource_id,
				     ctx->sensor_id, &thd);

      if (rc != SA_OK)
	{
	  snmp_log (LOG_ERR,
		    "Call to  SensorThresholdGet fails with return code: %s.\n",
		    get_error_string (rc));
	  DEBUGMSGTL ((AGENT,
		       "Call to  SensorThresholdGet fails with return code: %s.\n",
		       get_error_string (rc)));
	  return AGENT_ERR_OPERATION;
	}
      build_reading_strings (&thd.LowMajor,
			     0,
			     &ctx->saHpiSensorThdLowMajorValuesPresent,
			     &ctx->saHpiSensorThdLowMajorRaw,
			     ctx->saHpiSensorThdLowMajorInterpreted,
			     &ctx->saHpiSensorThdLowMajorInterpreted_len,
			     SENSOR_THD_INTER_MAX,
			     NULL, NULL, NULL, 0);


      DEBUGMSGTL ((AGENT, "set_ThdLowMajor: Exit.\n"));
      return AGENT_ERR_NOERROR;
    }
  DEBUGMSGTL ((AGENT, "set_sensor: Exit.\n"));

  return AGENT_ERR_NULL_DATA;


}
コード例 #27
0
ファイル: ide_linux.c プロジェクト: vejta66/hp-ams
int netsnmp_arch_idecntlr_container_load(netsnmp_container* container)
{

    cpqIdeControllerTable_entry *entry;

    int CntlrIndex=0, Host;
    char buffer[256];
    char attribute[256];
    char *value;
    long  rc = 0;
    int i;

    DEBUGMSGTL(("idecntlr:container:load", "loading\n"));
    DEBUGMSGTL(("idecntlr:container:load", "Container=%p\n",container));

    /* Find all SCSI Hosts */
    if ((NumScsiHost =
            scandir(ScsiHostDir, &ScsiHostlist, file_select, alphasort)) <= 0)
        /* Should not happen */
        return -1;

    for (i=0; i < NumScsiHost; i++) {

        entry = NULL;
        memset(&buffer, 0, sizeof(buffer));
        strncpy(buffer, ScsiHostDir, sizeof(buffer) - 1);
        strncat(buffer, ScsiHostlist[i]->d_name,
                    sizeof(buffer) - strlen(buffer) - 1);

        strncpy(attribute, buffer, sizeof(attribute) - 1);
        strncat(attribute, sysfs_attr[CLASS_PROC_NAME],
            sizeof(attribute) - strlen(attribute) - 1);
        if ((value = get_sysfs_str(attribute)) != NULL) {
            if ((strcmp(value, "ahci") == 0) || 
                (strcmp(value, "ata_piix") == 0)) {
               /*  We will need the host name later on */
                sscanf(ScsiHostlist[i]->d_name, "host%d", &Host);
                CntlrIndex = Host;

                entry = cpqIdeControllerTable_createEntry(container,
                                                          (oid)CntlrIndex);
            }
            free(value);
        }
        
        if (NULL != entry) {
            DEBUGMSGTL(("idecntlr:container:load", "Entry created %d\n", CntlrIndex));
            /*  We will need the host name later on */
            sprintf(entry->host, "%d:", Host);
            entry->cpqIdeControllerOverallCondition = IDE_CONTROLLER_STATUS_OK;
            entry->cpqIdeControllerStatus = CPQ_REG_OTHER;
    
            entry->cpqIdeControllerSlot =  pcislot_scsi_host(buffer);

            strncpy(attribute, buffer, sizeof(attribute) - 1);
            strncat(attribute, sysfs_attr[CLASS_STATE],
                    sizeof(attribute) - strlen(attribute) - 1);
            if ((value = get_sysfs_str(attribute)) != NULL) {
                if (strcmp(value, "running") == 0)
                    entry->cpqIdeControllerStatus = IDE_CONTROLLER_STATUS_OK;
                free(value);
            }
    
            strcpy(entry->cpqIdeControllerModel, "Standard IDE Controller");
            entry->cpqIdeControllerModel_len = 
                                        strlen(entry->cpqIdeControllerModel);

            entry->cpqIdeControllerCondition = 
                    MAKE_CONDITION(entry->cpqIdeControllerCondition, 
                                   entry->cpqIdeControllerStatus);
            rc = CONTAINER_INSERT(container, entry);
            DEBUGMSGTL(("idecntlr:container:load", "container inserted\n"));
        }
        free(ScsiHostlist[i]);
    }
    free(ScsiHostlist);

    return(rc);
}
コード例 #28
0
ファイル: snmp_transport.c プロジェクト: a5216652166/rcp100
/*
 * Locate the appropriate transport domain and call the create function for
 * it.
 */
netsnmp_transport *
netsnmp_tdomain_transport_full(const char *application,
                               const char *str, int local,
                               const char *default_domain,
                               const char *default_target)
{
    netsnmp_tdomain    *match = NULL;
    const char         *addr = NULL;
    const char * const *spec = NULL;
    int                 any_found = 0;
    char buf[SNMP_MAXPATH];
    extern const char *curfilename;		/* from read_config.c */
    const char        *prev_curfilename;

    prev_curfilename = curfilename;

    DEBUGMSGTL(("tdomain",
                "tdomain_transport_full(\"%s\", \"%s\", %d, \"%s\", \"%s\")\n",
                application, str ? str : "[NIL]", local,
                default_domain ? default_domain : "[NIL]",
                default_target ? default_target : "[NIL]"));

    /* see if we can load a host-name specific set of conf files */
    if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
                                NETSNMP_DS_LIB_DONT_LOAD_HOST_FILES) &&
        netsnmp_is_fqdn(str)) {
        static int have_added_handler = 0;
        char *newhost;
        struct config_line *config_handlers;
        struct config_files file_names;
        char *prev_hostname;

        /* register a "transport" specifier */
        if (!have_added_handler) {
            have_added_handler = 1;
            netsnmp_ds_register_config(ASN_OCTET_STR,
                                       "snmp", "transport",
                                       NETSNMP_DS_LIBRARY_ID,
                                       NETSNMP_DS_LIB_HOSTNAME);
        }

        /* we save on specific setting that we don't allow to change
           from one transport creation to the next; ie, we don't want
           the "transport" specifier to be a default.  It should be a
           single invocation use only */
        prev_hostname = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                              NETSNMP_DS_LIB_HOSTNAME);
        if (prev_hostname)
            prev_hostname = strdup(prev_hostname);

        /* read in the hosts/STRING.conf files */
        config_handlers = read_config_get_handlers("snmp");
        snprintf(buf, sizeof(buf)-1, "hosts/%s", str);
        file_names.fileHeader = buf;
        file_names.start = config_handlers;
        file_names.next = NULL;
        DEBUGMSGTL(("tdomain", "checking for host specific config %s\n",
                    buf));
        read_config_files_of_type(EITHER_CONFIG, &file_names);

        if (NULL !=
            (newhost = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                             NETSNMP_DS_LIB_HOSTNAME))) {
            strncpy(buf, newhost, sizeof(buf)-1);
            str = buf;
        }

        netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
                              NETSNMP_DS_LIB_HOSTNAME,
                              prev_hostname);
        SNMP_FREE(prev_hostname);
    }

    /* First try - assume that there is a domain in str (domain:target) */

    if (str != NULL) {
        const char *cp;
        if ((cp = strchr(str, ':')) != NULL) {
            char* mystring = (char*)malloc(cp + 1 - str);
            memcpy(mystring, str, cp - str);
            mystring[cp - str] = '\0';
            addr = cp + 1;

            match = find_tdomain(mystring);
            free(mystring);
        }
    }

    /*
     * Second try, if there is no domain in str (target), then try the
     * default domain
     */

    if (match == NULL) {
        addr = str;
        if (addr && *addr == '/') {
            DEBUGMSGTL(("tdomain",
                        "Address starts with '/', so assume \"unix\" "
                        "domain\n"));
            match = find_tdomain("unix");
        } else if (default_domain) {
            DEBUGMSGTL(("tdomain",
                        "Use user specified default domain \"%s\"\n",
                        default_domain));
            match = find_tdomain(default_domain);
        } else {
            spec = netsnmp_lookup_default_domains(application);
            if (spec == NULL) {
                DEBUGMSGTL(("tdomain",
                            "No default domain found, assume \"udp\"\n"));
                match = find_tdomain("udp");
            } else {
                const char * const * r = spec;
                DEBUGMSGTL(("tdomain",
                            "Use application default domains"));
                while(*r) {
                    DEBUGMSG(("tdomain", " \"%s\"", *r));
                    ++r;
                }
                DEBUGMSG(("tdomain", "\n"));
            }
        }
    }

    for(;;) {
        if (match) {
            netsnmp_transport *t = NULL;
            const char* addr2;

            any_found = 1;
            /*
             * Ok, we know what domain to try, lets see what default data
             * should be used with it
             */
            if (default_target != NULL)
                addr2 = default_target;
            else
                addr2 = netsnmp_lookup_default_target(application,
                                                      match->prefix[0]);
            DEBUGMSGTL(("tdomain",
                        "trying domain \"%s\" address \"%s\" "
                        "default address \"%s\"\n",
                        match->prefix[0], addr ? addr : "[NIL]",
                        addr2 ? addr2 : "[NIL]"));
            if (match->f_create_from_tstring) {
                NETSNMP_LOGONCE((LOG_WARNING,
                                 "transport domain %s uses deprecated f_create_from_tstring\n",
                                 match->prefix[0]));
                t = match->f_create_from_tstring(addr, local);
            }
            else
                t = match->f_create_from_tstring_new(addr, local, addr2);
            if (t) {
                curfilename = prev_curfilename;
                return t;
            }
        }
        addr = str;
        if (spec && *spec)
            match = find_tdomain(*spec++);
        else
            break;
    }
    if (!any_found)
        snmp_log(LOG_ERR, "No support for any checked transport domain\n");
    curfilename = prev_curfilename;
    return NULL;
}
コード例 #29
0
ファイル: cpqNicIfLogMapTable.c プロジェクト: marker55/hp-ams
/** Initialize the cpqNicIfLogMapTable table by defining its contents and how it's structured */
void
initialize_table_cpqNicIfLogMapTable(void)
{
    const oid       cpqNicIfLogMapTable_oid[] =
        { 1, 3, 6, 1, 4, 1, 232, 18, 2, 2, 1 };
    const size_t    cpqNicIfLogMapTable_oid_len =
        OID_LENGTH(cpqNicIfLogMapTable_oid);
    netsnmp_handler_registration *reg = NULL;
    netsnmp_mib_handler *handler = NULL;
    netsnmp_container *container = NULL;
    netsnmp_table_registration_info *table_info = NULL;
    netsnmp_cache  *cache = NULL;

    int reg_tbl_ret = SNMPERR_SUCCESS;

    DEBUGMSGTL(("cpqNicIfLogMapTable:init",
                "initializing table cpqNicIfLogMapTable\n"));

    reg =
        netsnmp_create_handler_registration("cpqNicIfLogMapTable",
                                            cpqNicIfLogMapTable_handler,
                                            cpqNicIfLogMapTable_oid,
                                            cpqNicIfLogMapTable_oid_len,
                                            HANDLER_CAN_RONLY);
    if (NULL == reg) {
        snmp_log(LOG_ERR,
                 "error creating handler registration for cpqNicIfLogMapTable\n");
        goto bail;
    }

    container =
        netsnmp_container_find("cpqNicIfLogMapTable:table_container");
    if (NULL == container) {
        snmp_log(LOG_ERR,
                 "error creating container for cpqNicIfLogMapTable\n");
        goto bail;
    }
    container->container_name = strdup("cpqNicIfLogMapTable container");


    table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
    if (NULL == table_info) {
        snmp_log(LOG_ERR,
                 "error allocating table registration for cpqNicIfLogMapTable\n");
        goto bail;
    }
    netsnmp_table_helper_add_indexes(table_info, ASN_INTEGER,   /* index: cpqNicIfLogMapIndex */
                                     0);
    table_info->min_column = COLUMN_CPQNICIFLOGMAPINDEX;
    table_info->max_column = COLUMN_CPQNICIFLOGMAPPCILOCATION;

    /*************************************************
     *
     * inject container_table helper
     */
    handler = netsnmp_container_table_handler_get(table_info, container,
                                                  TABLE_CONTAINER_KEY_NETSNMP_INDEX);
    if (NULL == handler) {
        snmp_log(LOG_ERR,
                 "error allocating table registration for cpqNicIfLogMapTable\n");
        goto bail;
    }
    if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
        snmp_log(LOG_ERR,
                 "error injecting container_table handler for cpqNicIfLogMapTable\n");
        goto bail;
    }
    handler = NULL;             /* reg has it, will reuse below */

    /*************************************************
     *
     * inject cache helper
     */
    cache = netsnmp_cache_create(30,    /* timeout in seconds */
                                 _cache_load, _cache_free,
                                 cpqNicIfLogMapTable_oid,
                                 cpqNicIfLogMapTable_oid_len);

    if (NULL == cache) {
        snmp_log(LOG_ERR,
                 "error creating cache for cpqNicIfLogMapTable\n");
        goto bail;
    }
    cache->flags = NETSNMP_CACHE_PRELOAD |
                   NETSNMP_CACHE_DONT_FREE_EXPIRED |
                   NETSNMP_CACHE_DONT_AUTO_RELEASE |
                   NETSNMP_CACHE_DONT_FREE_BEFORE_LOAD |
                   NETSNMP_CACHE_DONT_INVALIDATE_ON_SET;

    cache->magic = container;

    handler = netsnmp_cache_handler_get(cache);
    if (NULL == handler) {
        snmp_log(LOG_ERR,
                 "error creating cache handler for cpqNicIfLogMapTable\n");
        goto bail;
    }

    if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
        snmp_log(LOG_ERR,
                 "error injecting cache handler for cpqNicIfLogMapTable\n");
        goto bail;
    }
    handler = NULL;             /* reg has it */

    /*
     * register the table
     */
    reg_tbl_ret = netsnmp_register_table(reg, table_info);
    if (reg_tbl_ret != SNMPERR_SUCCESS) {
        snmp_log(LOG_ERR,
                 "error registering table handler for cpqNicIfLogMapTable\n");
        goto bail;
    }

    return;                     /* ok */

    /*
     * Some error occurred during registration. Clean up and bail.
     */
  bail:                        /* not ok */

    if (handler)
        netsnmp_handler_free(handler);

    if (cache)
        netsnmp_cache_free(cache);

    if (table_info)
        netsnmp_table_registration_info_free(table_info);

    if (container)
        CONTAINER_FREE(container);

    if (reg_tbl_ret == SNMPERR_SUCCESS)
        if (reg)
            netsnmp_handler_registration_free(reg);
}
コード例 #30
0
ファイル: hrSWInstalledTable.c プロジェクト: OPSF/uClinux
/** Initialize the hrSWInstalledTable table by defining its contents and how it's structured */
void
initialize_table_hrSWInstalledTable(void)
{
    static oid      hrSWInstalledTable_oid[] =
    { 1, 3, 6, 1, 2, 1, 25, 6, 3 };
    size_t          hrSWInstalledTable_oid_len =
        OID_LENGTH(hrSWInstalledTable_oid);
    netsnmp_handler_registration *reg;
    netsnmp_mib_handler *handler;
    netsnmp_container *container;
    netsnmp_cache *cache;
    netsnmp_table_registration_info *table_info;

    DEBUGMSGTL(("hrSWInstalled", "initialize\n"));

    reg =
        netsnmp_create_handler_registration("hrSWInstalledTable",
                                            hrSWInstalledTable_handler,
                                            hrSWInstalledTable_oid,
                                            hrSWInstalledTable_oid_len,
                                            HANDLER_CAN_RONLY);
    if (NULL == reg) {
        snmp_log(LOG_ERR,"error creating handler registration for "
                 MYTABLE "\n");
        goto bail;
    }

    container = netsnmp_container_find("hrSWInstalledTable:table_container");
    if (NULL == container) {
        snmp_log(LOG_ERR,"error creating container for "
                 MYTABLE "\n");
        goto bail;
    }

    table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
    if (NULL == table_info) {
        snmp_log(LOG_ERR,"error allocating table registration for "
                 MYTABLE "\n");
        goto bail;
    }

    netsnmp_table_helper_add_indexes(table_info, ASN_INTEGER,   /* index: hrSWInstalledIndex */
                                     0);
    table_info->min_column = COLUMN_HRSWINSTALLEDINDEX;
    table_info->max_column = COLUMN_HRSWINSTALLEDDATE;

    /*************************************************
     *
     * inject container_table helper
     */
    handler = netsnmp_container_table_handler_get(table_info, container,
              TABLE_CONTAINER_KEY_NETSNMP_INDEX);
    if (NULL == handler) {
        snmp_log(LOG_ERR,"error allocating table registration for "
                 MYTABLE "\n");
        goto bail;
    }
    if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
        snmp_log(LOG_ERR,"error injecting container_table handler for "
                 MYTABLE "\n");
        goto bail;
    }
    handler = NULL; /* reg has it, will reuse below */

    /*************************************************
     *
     * inject cache helper
     */
    cache = netsnmp_cache_create(30,    /* timeout in seconds */
                                 _cache_load, _cache_free,
                                 hrSWInstalledTable_oid,
                                 hrSWInstalledTable_oid_len);

    if (NULL == cache) {
        snmp_log(LOG_ERR, "error creating cache for "
                 MYTABLE "\n");
        goto bail;
    }
    cache->magic = container;

    handler = netsnmp_cache_handler_get(cache);
    if (NULL == handler) {
        snmp_log(LOG_ERR, "error creating cache handler for "
                 MYTABLE "\n");
        goto bail;
    }
    if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
        snmp_log(LOG_ERR,"error injecting cache handler for "
                 MYTABLE "\n");
        goto bail;
    }
    handler = NULL; /* reg has it*/

    if (SNMPERR_SUCCESS != netsnmp_register_table(reg, table_info)) {
        snmp_log(LOG_ERR,"error registering table handler for "
                 MYTABLE "\n");
        goto bail;
    }

    return; /* ok */


bail: /* not ok */

    if (handler)
        netsnmp_handler_free(handler);

    if (cache)
        netsnmp_cache_free(cache);

    if (table_info)
        netsnmp_table_registration_info_free(table_info);

    if (container)
        CONTAINER_FREE(container);

    if (reg)
        netsnmp_handler_registration_free(reg);

}