Esempio n. 1
0
main(int argc, char *argv[])
#endif
{
    char            options[128] = "aAc:CdD::efF:g:hHI:L:m:M:no:O:PqsS:tu:vx:-:";
    netsnmp_session *sess_list = NULL, *ss = NULL;
    netsnmp_transport *transport = NULL;
    int             arg, i = 0, depmsg = 0;
    int             uid = 0, gid = 0;
    int             count, numfds, block;
    fd_set          readfds,writefds,exceptfds;
    struct timeval  timeout, *tvp;
    char           *cp, *listen_ports = NULL;
#if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
    int             agentx_subagent = 1;
#endif
    netsnmp_trapd_handler *traph;
#ifdef NETSNMP_EMBEDDED_PERL
    extern void init_perl(void);
#endif

#ifndef WIN32
    /*
     * close all non-standard file descriptors we may have
     * inherited from the shell.
     */
    for (i = getdtablesize() - 1; i > 2; --i) {
        (void) close(i);
    }
#endif /* #WIN32 */
    
#ifdef SIGTERM
    signal(SIGTERM, term_handler);
#endif
#ifdef SIGHUP
    signal(SIGHUP, SIG_IGN);   /* do not terminate on early SIGHUP */
#endif
#ifdef SIGINT
    signal(SIGINT, term_handler);
#endif
#ifdef SIGPIPE
    signal(SIGPIPE, SIG_IGN);   /* 'Inline' failure of wayward readers */
#endif

#ifdef SIGHUP
    signal(SIGHUP, SIG_IGN);   /* do not terminate on early SIGHUP */
#endif

    /*
     * register our configuration handlers now so -H properly displays them 
     */
    snmptrapd_register_configs( );
    init_usm_conf( "snmptrapd" );
    register_config_handler("snmptrapd", "snmpTrapdAddr",
                            parse_trapd_address, free_trapd_address, "string");

    register_config_handler("snmptrapd", "doNotLogTraps",
                            parse_config_doNotLogTraps, NULL, "(1|yes|true|0|no|false)");
#if HAVE_GETPID
    register_config_handler("snmptrapd", "pidFile",
                            parse_config_pidFile, NULL, "string");
#endif
#ifdef HAVE_UNISTD_H
    register_config_handler("snmptrapd", "agentuser",
                            parse_config_agentuser, NULL, "userid");
    register_config_handler("snmptrapd", "agentgroup",
                            parse_config_agentgroup, NULL, "groupid");
#endif
    
    register_config_handler("snmptrapd", "logOption",
                            parse_config_logOption, NULL, "string");

    register_config_handler("snmptrapd", "doNotFork",
                            parse_config_doNotFork, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "printEventNumbers",
                            parse_config_printEventNumbers, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "ignoreAuthFailure",
                            parse_config_ignoreAuthFailure, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "outputOption",
                            parse_config_outputOption, NULL, "string");

#ifdef WIN32
    setvbuf(stdout, NULL, _IONBF, BUFSIZ);
#else
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
#endif

    /*
     * Add some options if they are available.  
     */
#if HAVE_GETPID
    strcat(options, "p:");
#endif

#ifdef WIN32
    snmp_log_syslogname(app_name_long);
#else
    snmp_log_syslogname(app_name);
#endif

    /*
     * Now process options normally.  
     */

    while ((arg = getopt(argc, argv, options)) != EOF) {
        switch (arg) {
        case '-':
            if (strcasecmp(optarg, "help") == 0) {
                usage();
                exit(0);
            }
            if (strcasecmp(optarg, "version") == 0) {
                version();
                exit(0);
            }

            handle_long_opt(optarg);
            break;

        case 'a':
            dropauth = 1;
            break;

        case 'A':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_LIB_APPEND_LOGFILES, 1);
            break;

        case 'c':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
				      NETSNMP_DS_LIB_OPTIONALCONFIG, optarg);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'C':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
				   NETSNMP_DS_LIB_DONT_READ_CONFIGS, 1);
            break;

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

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

        case 'e':
            Event++;
            break;

        case 'f':
            dofork = 0;
            break;

        case 'F':
            if (optarg != NULL) {
                trap1_fmt_str_remember = optarg;
            } else {
                usage();
                exit(1);
            }
            break;

#if HAVE_UNISTD_H
        case 'g':
            if (optarg != NULL) {
                netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_GROUPID, gid = atoi(optarg));
            } else {
                usage();
                exit(1);
            }
            break;
#endif

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

        case 'H':
            init_agent("snmptrapd");
#ifdef USING_NOTIFICATION_LOG_MIB_NOTIFICATION_LOG_MODULE
            init_notification_log();
#endif
#ifdef NETSNMP_EMBEDDED_PERL
            init_perl();
#endif
            init_snmp("snmptrapd");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            exit(0);

        case 'I':
            if (optarg != NULL) {
                add_to_init_list(optarg);
            } else {
                usage();
            }
            break;

	case 'S':
            fprintf(stderr,
                    "Warning: -S option is deprecated; use -Ls <facility> instead\n");
            depmsg = 1;
            if (optarg != NULL) {
                switch (*optarg) {
                case 'd':
                case 'D':
                    Facility = LOG_DAEMON;
                    break;
                case 'i':
                case 'I':
                    Facility = LOG_INFO;
                    break;
                case '0':
                    Facility = LOG_LOCAL0;
                    break;
                case '1':
                    Facility = LOG_LOCAL1;
                    break;
                case '2':
                    Facility = LOG_LOCAL2;
                    break;
                case '3':
                    Facility = LOG_LOCAL3;
                    break;
                case '4':
                    Facility = LOG_LOCAL4;
                    break;
                case '5':
                    Facility = LOG_LOCAL5;
                    break;
                case '6':
                    Facility = LOG_LOCAL6;
                    break;
                case '7':
                    Facility = LOG_LOCAL7;
                    break;
                default:
                    fprintf(stderr, "invalid syslog facility: -S%c\n",*optarg);
                    usage();
                    exit(1);
                }
            } else {
                fprintf(stderr, "no syslog facility specified\n");
                usage();
                exit(1);
            }
            break;

        case 'm':
            if (optarg != NULL) {
                setenv("MIBS", optarg, 1);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'M':
            if (optarg != NULL) {
                setenv("MIBDIRS", optarg, 1);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'n':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_APP_NUMERIC_IP, 1);
            break;

        case 'o':
            fprintf(stderr,
                    "Warning: -o option is deprecated; use -Lf <file> instead\n");
            if (optarg != NULL) {
                logfile = optarg;
                snmp_enable_filelog(optarg, 
                                    netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
                                                           NETSNMP_DS_LIB_APPEND_LOGFILES));
            } else {
                usage();
                exit(1);
            }
            break;

        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown output option passed to -O: %c\n",
			*cp);
                usage();
                exit(1);
            }
            break;

        case 'L':
	    if  (snmp_log_options( optarg, argc, argv ) < 0 ) {
                usage();
                exit(1);
            }
            break;

#if HAVE_GETPID
        case 'p':
            if (optarg != NULL) {
                parse_config_pidFile(NULL, optarg);
            } else {
                usage();
                exit(1);
            }
            break;
#endif

        case 'P':
            fprintf(stderr,
                    "Warning: -P option is deprecated; use -f -Le instead\n");
            dofork = 0;
            snmp_enable_stderrlog();
            break;

        case 's':
            fprintf(stderr,
                    "Warning: -s option is deprecated; use -Lsd instead\n");
            depmsg = 1;
#ifdef WIN32
            snmp_enable_syslog_ident(app_name_long, Facility);
#else
            snmp_enable_syslog_ident(app_name, Facility);
#endif
            break;

        case 't':
            SyslogTrap++;
            break;

#if HAVE_UNISTD_H
        case 'u':
            if (optarg != NULL) {
                char           *ecp;

                uid = strtoul(optarg, &ecp, 10);
                if (*ecp) {
#if HAVE_GETPWNAM && HAVE_PWD_H
                    struct passwd  *info;
                    info = getpwnam(optarg);
                    if (info) {
                        uid = info->pw_uid;
                    } else {
#endif
                        fprintf(stderr, "Bad user id: %s\n", optarg);
                        exit(1);
#if HAVE_GETPWNAM && HAVE_PWD_H
                    }
#endif
                }
                netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_USERID, uid);
            } else {
                usage();
                exit(1);
            }
            break;
#endif

        case 'v':
            version();
            exit(0);
            break;

        case 'x':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                      NETSNMP_DS_AGENT_X_SOCKET, optarg);
            } else {
                usage();
                exit(1);
            }
            break;

        default:
            fprintf(stderr, "invalid option: -%c\n", arg);
            usage();
            exit(1);
            break;
        }
    }

    if (optind < argc) {
        /*
         * There are optional transport addresses on the command line.  
         */
        for (i = optind; i < argc; i++) {
            char *astring;
            if (listen_ports != NULL) {
                astring = malloc(strlen(listen_ports) + 2 + strlen(argv[i]));
                if (astring == NULL) {
                    fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                    exit(1);
                }
                sprintf(astring, "%s,%s", listen_ports, argv[i]);
                free(listen_ports);
                listen_ports = astring;
            } else {
                listen_ports = strdup(argv[i]);
                if (listen_ports == NULL) {
                    fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                    exit(1);
                }
            }
        }
    }

    SOCK_STARTUP;

    /*
     * I'm being lazy here, and not checking the
     * return value from these registration calls.
     * Don't try this at home, children!
     */
    if (0 == snmp_get_do_logging()) {
        traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER,
                                               syslog_handler);
        traph->authtypes = TRAP_AUTH_LOG;
        snmp_enable_syslog();
    } else {
        traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER,
                                               print_handler);
        traph->authtypes = TRAP_AUTH_LOG;
    }

    if (Event) {
        traph = netsnmp_add_traphandler(event_handler, risingAlarm,
                                        OID_LENGTH(risingAlarm));
        traph->authtypes = TRAP_AUTH_LOG;

        traph = netsnmp_add_traphandler(event_handler, fallingAlarm,
                                        OID_LENGTH(fallingAlarm));
        traph->authtypes = TRAP_AUTH_LOG;

        traph = netsnmp_add_traphandler(event_handler, unavailableAlarm,
                                        OID_LENGTH(unavailableAlarm));
        traph->authtypes = TRAP_AUTH_LOG;
	/* XXX - might be worth setting some "magic data"
	 * in the traphandler structure that 'event_handler'
	 * can use to avoid checking the trap OID values.
	 */
    }

#if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
    /*
     * we're an agentx subagent? 
     */
    if (agentx_subagent) {
        /*
         * make us a agentx client. 
         */
        netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
			       NETSNMP_DS_AGENT_ROLE, 1);
    }
#endif

    /*
     * don't fail if we can't do agentx (ie, socket not there, or not root) 
     */
    netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
			      NETSNMP_DS_AGENT_NO_ROOT_ACCESS);
    /*
     * ignore any warning messages.
     */
    netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
			      NETSNMP_DS_AGENT_NO_CONNECTION_WARNINGS);

    /*
     * initialize the agent library 
     */
    init_agent("snmptrapd");

#if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
    /*
     * initialize local modules 
     */
    if (agentx_subagent) {
#ifdef USING_SNMPV3_SNMPENGINE_MODULE
        extern void register_snmpEngine_scalars_context(const char *);
#endif
        subagent_init();
#ifdef USING_NOTIFICATION_LOG_MIB_NOTIFICATION_LOG_MODULE
        /* register the notification log table */
        if (should_init("notificationLogMib")) {
            netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                              NETSNMP_DS_NOTIF_LOG_CTX,
                              "snmptrapd");
            traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_POST_HANDLER,
                                                   notification_handler);
            traph->authtypes = TRAP_AUTH_LOG;
            init_notification_log();
        }
#endif
#ifdef USING_SNMPV3_SNMPENGINE_MODULE
        /*
         * register scalars from SNMP-FRAMEWORK-MIB::snmpEngineID group;
         * allows engineID probes via the master agent under the
         * snmptrapd context
         */
        register_snmpEngine_scalars_context("snmptrapd");
#endif
    }
#endif /* USING_AGENTX_SUBAGENT_MODULE && !NETSNMP_SNMPTRAPD_DISABLE_AGENTX */

    /* register our authorization handler */
    init_netsnmp_trapd_auth();

#if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
    if (agentx_subagent) {
#ifdef USING_AGENT_NSVACMACCESSTABLE_MODULE
        extern void init_register_nsVacm_context(const char *);
#endif
#ifdef USING_SNMPV3_USMUSER_MODULE
        extern void init_register_usmUser_context(const char *);
        /* register ourselves as having a USM user database */
        init_register_usmUser_context("snmptrapd");
#endif
#ifdef USING_AGENT_NSVACMACCESSTABLE_MODULE
        /* register net-snmp vacm extensions */
        init_register_nsVacm_context("snmptrapd");
#endif
    }
#endif

#ifdef NETSNMP_EMBEDDED_PERL
    init_perl();
    {
        /* set the default path to load */
        char            init_file[SNMP_MAXBUF];
        snprintf(init_file, sizeof(init_file) - 1,
                 "%s/%s", SNMPSHAREPATH, "snmp_perl_trapd.pl");
        netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                              NETSNMP_DS_AGENT_PERL_INIT_FILE,
                              init_file);
    }
#endif

    /*
     * Initialize the world.
     */
    init_snmp("snmptrapd");

#ifdef SIGHUP
    signal(SIGHUP, hup_handler);
#endif

    if (trap1_fmt_str_remember) {
        free_trap1_fmt();
        free_trap2_fmt();
        print_format1 = strdup(trap1_fmt_str_remember);
        print_format2 = strdup(trap1_fmt_str_remember);
    }

    if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_QUIT_IMMEDIATELY)) {
        /*
         * just starting up to process specific configuration and then
         * shutting down immediately. 
         */
        netsnmp_running = 0;
    }

    /*
     * if no logging options on command line or in conf files, use syslog
     */
    if (0 == snmp_get_do_logging()) {
#ifdef WIN32
        snmp_enable_syslog_ident(app_name_long, Facility);
#else
        snmp_enable_syslog_ident(app_name, Facility);
#endif        
    }

#ifndef WIN32
    /*
     * fork the process to the background if we are not printing to stderr 
     */
    if (dofork && netsnmp_running) {
        int             fd;

        switch (fork()) {
        case -1:
            fprintf(stderr, "bad fork - %s\n", strerror(errno));
            _exit(1);

        case 0:
            /*
             * become process group leader 
             */
            if (setsid() == -1) {
                fprintf(stderr, "bad setsid - %s\n", strerror(errno));
                _exit(1);
            }

            /*
             * if we are forked, we don't want to print out to stdout or stderr 
             */
            fd = open("/dev/null", O_RDWR);
            dup2(fd, STDIN_FILENO);
            dup2(fd, STDOUT_FILENO);
            dup2(fd, STDERR_FILENO);
            close(fd);
            break;

        default:
            _exit(0);
        }
    }
#endif                          /* WIN32 */
#if HAVE_GETPID
    if (pid_file != NULL) {
        if ((PID = fopen(pid_file, "w")) == NULL) {
            snmp_log_perror("fopen");
            exit(1);
        }
        fprintf(PID, "%d\n", (int) getpid());
        fclose(PID);
        free_config_pidFile();
    }
#endif

    snmp_log(LOG_INFO, "NET-SNMP version %s\n", netsnmp_get_version());
    if (depmsg) {
        snmp_log(LOG_WARNING, "-s and -S options are deprecated; use -Ls <facility> instead\n");
    }
    
    if (listen_ports)
        cp = listen_ports;
    else
        cp = default_port;

    while (cp != NULL) {
        char *sep = strchr(cp, ',');

        if (sep != NULL) {
            *sep = 0;
        }

        transport = netsnmp_transport_open_server("snmptrap", cp);
        if (transport == NULL) {
            snmp_log(LOG_ERR, "couldn't open %s -- errno %d (\"%s\")\n",
                     cp, errno, strerror(errno));
            snmptrapd_close_sessions(sess_list);
            SOCK_CLEANUP;
            exit(1);
        } else {
            ss = snmptrapd_add_session(transport);
            if (ss == NULL) {
                /*
                 * Shouldn't happen?  We have already opened the transport
                 * successfully so what could have gone wrong?  
                 */
                snmptrapd_close_sessions(sess_list);
                netsnmp_transport_free(transport);
                snmp_log(LOG_ERR, "couldn't open snmp - %s", strerror(errno));
                SOCK_CLEANUP;
                exit(1);
            } else {
                ss->next = sess_list;
                sess_list = ss;
            }
        }

        /*
         * Process next listen address, if there is one.  
         */

        if (sep != NULL) {
            *sep = ',';
            cp = sep + 1;
        } else {
            cp = NULL;
        }
    }

    /*
     * ignore early sighup during startup
     */
    reconfig = 0;

#if HAVE_UNISTD_H
#ifdef HAVE_SETGID
    if ((gid = netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID, 
				  NETSNMP_DS_AGENT_GROUPID)) != 0) {
        DEBUGMSGTL(("snmptrapd/main", "Changing gid to %d.\n", gid));
        if (setgid(gid) == -1
#ifdef HAVE_SETGROUPS
            || setgroups(1, (gid_t *)&gid) == -1
#endif
            ) {
            snmp_log_perror("setgid failed");
            if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
					NETSNMP_DS_AGENT_NO_ROOT_ACCESS)) {
                exit(1);
            }
        }
    }
#endif
#ifdef HAVE_SETUID
    if ((uid = netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID, 
				  NETSNMP_DS_AGENT_USERID)) != 0) {
        DEBUGMSGTL(("snmptrapd/main", "Changing uid to %d.\n", uid));
        if (setuid(uid) == -1) {
            snmp_log_perror("setuid failed");
            if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
					NETSNMP_DS_AGENT_NO_ROOT_ACCESS)) {
                exit(1);
            }
        }
    }
#endif
#endif

#ifdef WIN32SERVICE
    trapd_status = SNMPTRAPD_RUNNING;
#endif
    while (netsnmp_running) {
        if (reconfig) {
                /*
                 * If we are logging to a file, receipt of SIGHUP also
                 * indicates the the log file should be closed and
                 * re-opened.  This is useful for users that want to
                 * rotate logs in a more predictable manner.
                 */
                netsnmp_logging_restart();
                snmp_log(LOG_INFO, "NET-SNMP version %s restarted\n",
                         netsnmp_get_version());
            trapd_update_config();
            if (trap1_fmt_str_remember) {
                free_trap1_fmt();
                free_trap2_fmt();
                print_format1 = strdup(trap1_fmt_str_remember);
                print_format2 = strdup(trap1_fmt_str_remember);
            }
            reconfig = 0;
        }
        numfds = 0;
        FD_ZERO(&readfds);
        FD_ZERO(&writefds);
        FD_ZERO(&exceptfds);
        block = 0;
        tvp = &timeout;
        timerclear(tvp);
        tvp->tv_sec = 5;
        snmp_select_info(&numfds, &readfds, tvp, &block);
        if (block == 1)
            tvp = NULL;         /* block without timeout */
        netsnmp_external_event_info(&numfds, &readfds, &writefds, &exceptfds);
        count = select(numfds, &readfds, &writefds, &exceptfds, tvp);
        gettimeofday(&Now, 0);
        if (count > 0) {
            netsnmp_dispatch_external_events(&count, &readfds, &writefds,
                                             &exceptfds);
            /* If there are any more events after external events, then
             * try SNMP events. */
            if (count > 0) {
                snmp_read(&readfds);
            }
        } else
            switch (count) {
            case 0:
                snmp_timeout();
                break;
            case -1:
                if (errno == EINTR)
                    continue;
                snmp_log_perror("select");
                netsnmp_running = 0;
                break;
            default:
                fprintf(stderr, "select returned %d\n", count);
                netsnmp_running = 0;
            }
	run_alarms();
    }

    if (snmp_get_do_logging()) {
        struct tm      *tm;
        time_t          timer;
        time(&timer);
        tm = localtime(&timer);
        snmp_log(LOG_INFO,
                "%.4d-%.2d-%.2d %.2d:%.2d:%.2d NET-SNMP version %s Stopped.\n",
                 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
                 tm->tm_min, tm->tm_sec, netsnmp_get_version());
    }
    snmp_log(LOG_INFO, "Stopping snmptrapd");
    
    snmptrapd_close_sessions(sess_list);
    snmp_shutdown("snmptrapd");
#ifdef WIN32SERVICE
    trapd_status = SNMPTRAPD_STOPPED;
#endif
    snmp_disable_log();
    SOCK_CLEANUP;
    return 0;
}
int main(int argc, char** argv) {
    int agentx_subagent =
        1; /* change this if you want to be a SNMP master agent */
    /* Defs for arg-handling code: handles setting of policy-related variables
     */
    int ch;
    extern char* optarg;
    int dont_fork = 0, use_syslog = 0;
    char const* agentx_socket = NULL;
    char const* app_name = "moninor-agent";
    char const* directory = "/home/";

    while ((ch = getopt(argc, argv, "a:p:hdD:fHLMx:")) != EOF) {
        switch (ch) {
        case 'a':
            app_name = optarg;
            break;
        case 'p':
            directory = optarg;
            break;
        case 'h':
            print_usage();
            exit(0);
        case 'd':
            print_tokens();
            exit(0);
            break;
        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;
        case 'f':
            dont_fork = 1;
            break;
        case 'M':
            agentx_subagent = 0;
            break;
        case 'L':
            use_syslog = 0; /* use stderr */
            break;
        case 'x':
            agentx_socket = optarg;
            break;
        default:
            fprintf(stderr, "unknown option %c\n", ch);
            print_usage();
        }
    }

    if (optind < argc) {
        int i;
        /*
            * There are optional transport addresses on the command line.
            */
        DEBUGMSGTL(("snmpd/main", "optind %d, argc %d\n", optind, argc));
        for (i = optind; i < argc; i++) {
            char* c, *astring;
            if ((c = netsnmp_ds_get_string(NETSNMP_DS_APPLICATION_ID,
                                           NETSNMP_DS_AGENT_PORTS))) {
                astring = malloc(strlen(c) + 2 + strlen(argv[i]));
                if (astring == NULL) {
                    fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                    exit(1);
                }
                sprintf(astring, "%s,%s", c, argv[i]);
                netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                      NETSNMP_DS_AGENT_PORTS, astring);
                SNMP_FREE(astring);
            } else {
                netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                      NETSNMP_DS_AGENT_PORTS, argv[i]);
            }
        }
        DEBUGMSGTL(("snmpd/main", "port spec: %s\n",
                    netsnmp_ds_get_string(NETSNMP_DS_APPLICATION_ID,
                                          NETSNMP_DS_AGENT_PORTS)));
    }

    /* check directory existence */
    DIR* dir = opendir(directory);
    if (dir) {
        closedir(dir);
    } else if (ENOENT == errno) {
        puts("Directory doesn't not exist.");
        exit(-1);
    } else {
        puts("Cannot open direcory.");
        exit(-1);
    }

    /* we're an agentx subagent? */
    if (agentx_subagent) {
        /* make us a agentx client. */
        netsnmp_enable_subagent();
        if (NULL != agentx_socket) {
            netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                  NETSNMP_DS_AGENT_X_SOCKET, agentx_socket);
        }
    }

    snmp_disable_log();
    if (use_syslog)
        snmp_enable_calllog();
    else
        snmp_enable_stderrlog();

    /* daemonize */
    if (!dont_fork) {
        int rc = netsnmp_daemonize(1, !use_syslog);
        if (rc) exit(-1);
    }

    /* initialize tcp/ip if necessary */
    SOCK_STARTUP;

    /* initialize the agent library */
    init_agent(app_name);

    /* init mib code */
    global_settings_t* settings = get_mutable_global_settings();
    strcpy(settings->path, directory);

    void* data[4] = {NULL, NULL, NULL, NULL};
    init_Directory(data + 0);
    init_DirectoryStateNotification(data + 1);
    init_NumDirectories(data + 2);
    init_NumFiles(data + 3);
    init_DirectoryContentTable();

    /* read app_name.conf files. */
    init_snmp(app_name);

    /* If we're going to be a snmp master agent, initial the ports */
    if (!agentx_subagent)
        init_master_agent(); /* open the port to listen on (defaults to udp:161)
                                */

    /* In case we recevie a request to stop (kill -TERM or kill -INT) */
    g_keep_running = 1;
    signal(SIGTERM, stop_server);
    signal(SIGINT, stop_server);

    /* you're main loop here... */
    while (g_keep_running) {
        agent_check_and_process(1); /* 0 == don't block */
    }

    shutdown_DirectoryContentTable();
    shutdown_NumFiles(data[3]);
    shutdown_NumDirectories(data[2]);
    shutdown_DirectoryStateNotification(data[1]);
    shutdown_Directory(data[0]);

    /* at shutdown time */
    snmp_shutdown(app_name);
    SOCK_CLEANUP;
    exit(0);
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
	int		agentx_subagent;	/* change this if you want to be a SNMP master agent */
	int		background;			/* change this if you want to run in the background */
	int		syslog;				/* change this if you want to use syslog */
	int		dRet, dOldThreadCount;
	time_t	tOldThreadCheck, tThreadCheck;

	agentx_subagent	= 1;
	background		= 0;
	syslog			= 1;

	// Initialize Log
	dRet = log_init(S_SSHM_LOG_LEVEL, getpid(), SEQ_PROC_SNMPIF, LOG_PATH"/SNMPIF", "SNMPIF");
	if(dRet < 0)
	{
		log_print(LOGN_WARN, LH"MAIN : Failed in Initialize LOGLIB Info [%d]", LT,  dRet);
		return -1;
	}

#if 0	
	if( (dRet = Init_shm_common()) < 0)
	{
		log_print(LOGN_CRI, LH"ERROR IN Init_shm_common() [errno:%d-%s]", LT, -dRet, strerror(-dRet));
		return -2;
	}
#endif

	// Set version
	if((dRet = set_version(S_SSHM_VERSION, SEQ_PROC_SNMPIF, szVersion)) < 0)
	{
        log_print(LOGN_WARN, LH"ERROR IN set_version() dRet[%d]", LT, dRet);
		return -3;
    }

    if( (dRet = dGetBlocks(FILE_MC_INIT_M_PRI, SWLST_TAM_APP)) < 0)
    {
        log_print(LOGN_CRI, LH"ERROR IN dGetBlocks(%s) dRet[%d]", LT, FILE_MC_INIT_M_PRI, dRet);
		return -4;
    }

    if( (dRet = dGetBlocks(FILE_MC_INIT_F_PRI, SWLST_TAF_RP)) < 0)
    {
        log_print(LOGN_CRI, LH"ERROR IN dGetBlocks(%s) dRet[%d]", LT, FILE_MC_INIT_F_PRI, dRet);
		return -5;
    }

    if( (dRet = dGetBlocks(FILE_MC_INIT_F_SEC, SWLST_TAF_PI)) < 0)
    {
        log_print(LOGN_CRI, LH"ERROR IN dGetBlocks(%s) dRet[%d]", LT, FILE_MC_INIT_F_SEC, dRet);
		return -6;
    }

	if( (dRet = dReadSubSysListFromFile(&stSubSysList)) < 0)
	{
		log_print(LOGN_CRI, LH"ERROR IN dReadSubSysListFromFile() dRet[%d]", LT, dRet);
		return -7;
	}

	putenv("MIBS=ALL");

	/* print log errors to syslog or stderr */
	if(syslog)
		snmp_enable_calllog();
	else
		snmp_enable_stderrlog();

	/* we're an agentx subagent? */
	if(agentx_subagent)
	{
		/* make us a agentx client. */
		netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 1);
	}

	/* run in background, if requested */
	if(background && netsnmp_daemonize(1, !syslog))
		exit(-1);

	/* initialize tcpip, if necessary */
	SOCK_STARTUP;

	/* initialize the agent library */
	init_agent(TARGET);

	/* initialize mib code here */

	/* mib code: init_hardware from hardware.C */
	init_chnTable();
	init_dskTable();
	init_edTable();
	init_ethTable();
	init_fanTable();
	init_memTable();
	init_ntpTable();
	init_prTable();
	init_pwrTable();
	init_queTable();
	init_cpuTable();
	init_nifoTable();


	/* initialize vacm/usm access control  */
	if(!agentx_subagent)
	{
		init_vacm_vars();
		init_usmUser();
	}

	/* Initialize fidb */
	if((dRet = dInitFidb()) < 0)
	{
		log_print(LOGN_CRI, LH"ERROR IN dInitFidb() dRet=%d", LT, dRet);
		exit(-4);
	}

	/* Initialize sfdb */
	if( (dRet = init_sfdb()) < 0)
	{
		log_print(LOGN_CRI, LH"ERROR IN init_sfdb() dRet[%d]", LT, dRet);
		exit(-5);
	}

	if( (dRet = pthread_create(&t_agntx, NULL, p_agntx, NULL)) != 0)
	{
		log_print(LOGN_CRI, LH"FAILED IN pthread_create(t_agntx[%lu]) dRet[%d] errno[%d-%s]", LT,
			t_agntx, dRet, errno, strerror(errno));
		exit(-6);
	}
	else if( (dRet = pthread_detach(t_agntx)) != 0)
	{
		log_print(LOGN_CRI, LH"FAILED IN pthread_detach(t_agntx[%lu]) dRet[%d] errno[%d-%s]", LT,
			t_agntx, dRet, errno, strerror(errno));
		exit(-7);
	}

	tOldThreadCheck = time(NULL);
	dOldThreadCount	= dThreadStop;

	/* In case we recevie a request to stop (kill -TERM or kill -INT) */
	gJiSTOPFlag = 1;
	SetUpSignal();
	send_start_trap();

	log_print(LOGN_CRI, "SNMPIF[%s] START", szVersion);
	while(gJiSTOPFlag)
	{
		if( ((tThreadCheck = time(NULL)) - tOldThreadCheck) > THREAD_CHECK_INTERVAL)
		{
			tOldThreadCheck = tThreadCheck;
			if(dThreadStop == dOldThreadCount)
			{
				log_print(LOGN_CRI, LH"STOPED thread(p_agntx) dThreadStop[%d] dOldThreadCount[%d]", LT,
					dThreadStop, dOldThreadCount);
				if( (dRet = pthread_create(&t_agntx, NULL, p_agntx, NULL)) != 0)
				{
					log_print(LOGN_CRI, LH"FAILED IN pthread_create(t_agntx[%lu]) dRet[%d] errno[%d-%s]", LT,
						t_agntx, dRet, errno, strerror(errno));
					exit(-7);
				}
				else
				{
					log_print(LOGN_CRI, LH"SUCCESS IN pthread_create(t_agntx[%lu])", LT, t_agntx);
					dThreadStop		= 0;
				}
			}
			log_print(LOGN_DEBUG, LH"dThreadStop[%d] dOldThreadCount[%d]", LT, dThreadStop, dOldThreadCount);
			dOldThreadCount = dThreadStop;
		}

		/* if you use select(), see snmp_select_info() in snmp_api(3) */
		/*     --- OR ---  */
		alarm(1);
		agent_check_and_process(1); /* 0 == don't block */
		alarm(0);
	}

	/* at shutdown time */
	send_stop_trap();
	snmp_shutdown("SNMPIF");
	SOCK_CLEANUP;
	log_print(LOGN_CRI, "SNMPIF[%s] END", szVersion);

	return 0;
}
Esempio n. 4
0
int
main (int argc, char **argv) {
  int agentx_subagent=1; /* change this if you want to be a SNMP master agent */
  /* Defs for arg-handling code: handles setting of policy-related variables */
  int          ch;
  extern char *optarg;
  int dont_fork = 0, use_stderr = 0;
  char *agentx_socket = NULL;

  while ((ch = getopt(argc, argv, "D:fHLMx:")) != EOF)
    switch(ch) {
    case 'D':
      debug_register_tokens(optarg);
      snmp_set_do_debugging(1);
      break;
    case 'f':
      dont_fork = 1;
      break;
    case 'H':
      netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
	                     NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1);
      init_agent("libvirtGuestTable");        /* register our .conf handlers */
      init_libvirtGuestTable();
      init_snmp("libvirtGuestTable");
      fprintf(stderr, "Configuration directives understood:\n");
      read_config_print_usage("  ");
      snmp_shutdown("libvirtGuestTable");
      shutdown_libvirtGuestTable();
      exit(0);
    case 'M':
      agentx_subagent = 0;
      break;
    case 'L':
      use_stderr = 1;
      break;
    case 'x':
      agentx_socket = optarg;
      break;
    default:
      fprintf(stderr,"unknown option %c\n", ch);
      usage();
  }

  if (optind < argc) {
      int i;
      /*
       * There are optional transport addresses on the command line.
       */
      DEBUGMSGTL(("snmpd/main", "optind %d, argc %d\n", optind, argc));
      for (i = optind; i < argc; i++) {
          char *c, *astring;
          if ((c = netsnmp_ds_get_string(NETSNMP_DS_APPLICATION_ID,
                                         NETSNMP_DS_AGENT_PORTS))) {
              astring = malloc(strlen(c) + 2 + strlen(argv[i]));
              if (astring == NULL) {
                  fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                  exit(1);
              }
              sprintf(astring, "%s,%s", c, argv[i]);
              netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                    NETSNMP_DS_AGENT_PORTS, astring);
              SNMP_FREE(astring);
          } else {
              netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                    NETSNMP_DS_AGENT_PORTS, argv[i]);
          }
      }
      DEBUGMSGTL(("snmpd/main", "port spec: %s\n",
                  netsnmp_ds_get_string(NETSNMP_DS_APPLICATION_ID,
                                        NETSNMP_DS_AGENT_PORTS)));
  }

  /* we're an agentx subagent? */
  if (agentx_subagent) {
    /* make us a agentx client. */
    netsnmp_enable_subagent();
    if (NULL != agentx_socket)
        netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                              NETSNMP_DS_AGENT_X_SOCKET, agentx_socket);
  }

  snmp_disable_log();
  if (use_stderr)
      snmp_enable_stderrlog();
  else
      snmp_enable_calllog();

  /* daemonize */
  if(!dont_fork) {
    int rc = netsnmp_daemonize(1, use_stderr);
    if(rc)
       exit(-1);
  }

  /* initialize tcp/ip if necessary */
  SOCK_STARTUP;

  /* initialize the agent library */
  init_agent("libvirtGuestTable");

  /* init libvirtGuestTable mib code */
  init_libvirtGuestTable();

  /* read libvirtGuestTable.conf files. */
  init_snmp("libvirtGuestTable");

  /* If we're going to be a snmp master agent, initial the ports */
  if (!agentx_subagent)
    init_master_agent();  /* open the port to listen on (defaults to udp:161) */

  /* In case we recevie a request to stop (kill -TERM or kill -INT) */
  keep_running = 1;
  signal(SIGTERM, stop_server);
  signal(SIGINT, stop_server);

  /* you're main loop here... */
  while(keep_running) {
    /* if you use select(), see snmp_select_info() in snmp_api(3) */
    /*     --- OR ---  */
    agent_check_and_process(1); /* 0 == don't block */
  }

  /* at shutdown time */
  snmp_shutdown("libvirtGuestTable");
  shutdown_libvirtGuestTable();
  SOCK_CLEANUP;
  exit(0);
}
Esempio n. 5
0
static int send_snmp_inform_or_trap(const GpErrorData * errorData, const char * subject, const char * severity)
{

	netsnmp_session session, *ss = NULL;
	netsnmp_pdu    *pdu, *response;
	int				status;
	char            csysuptime[20];
	static bool 	snmp_initialized = false;
	static char myhostname[255];	/* gethostname usually is limited to 65 chars out, but make this big to be safe */
	char	   *rawstring = NULL;
	List	   *elemlist = NIL;
	ListCell   *l = NULL;

	/*
	 * "inform" messages get a positive acknowledgement response from the SNMP manager.
	 * If it doesn't come, the message might be resent.
	 *
	 * "trap" messages are one-way, and we have no idea if the manager received it.
	 * But, it's faster and cheaper, and no need to retry.  So some people might prefer it.
	 */
	bool inform = strcmp(gp_snmp_use_inform_or_trap,"inform") == 0;


	if (gp_snmp_monitor_address == NULL || gp_snmp_monitor_address[0] == '\0')
	{
		static bool firsttime = 1;

		ereport(firsttime ? LOG : DEBUG1,(errmsg("SNMP inform/trap alerts are disabled"),errOmitLocation(true)));
		firsttime = false;

		return -1;
	}


	/*
	 * SNMP managers are required to handle messages up to at least 484 bytes long, but I believe most existing
	 * managers support messages up to one packet (ethernet frame) in size, 1472 bytes.
	 *
	 * But, should we take that chance?  Or play it safe and limit the message to 484 bytes?
	 */

	elog(DEBUG2,"send_snmp_inform_or_trap");

	if (!snmp_initialized)
	{
		snmp_enable_stderrlog();

		if (gp_snmp_debug_log != NULL && gp_snmp_debug_log[0] != '\0')
		{
			snmp_enable_filelog(gp_snmp_debug_log, 1);

			//debug_register_tokens("ALL");
			snmp_set_do_debugging(1);
		}

		/*
		 * Initialize the SNMP library.  This also reads the MIB database.
		 */
		/* Add GPDB-MIB to the list to be loaded */
		putenv("MIBS=+GPDB-MIB:SNMP-FRAMEWORK-MIB:SNMPv2-CONF:SNMPv2-TC:SNMPv2-TC");

		init_snmp("sendalert");

		snmp_initialized = true;

		{
			char portnum[16];
			myhostname[0] = '\0';

			if (gethostname(myhostname, sizeof(myhostname)) == 0)
			{
				strcat(myhostname,":");
				pg_ltoa(PostPortNumber,portnum);
				strcat(myhostname,portnum);
			}
		}
	}

	/*
	 * Trap/Inform messages always start with the system up time. (SysUpTime.0)
	 *
	 * This presumably would be the uptime of GPDB, not the machine it is running on, I think.
	 *
	 * Use Postmaster's "MyStartTime" as a way to get that.
	 */

	sprintf(csysuptime, "%ld", (long)(time(NULL) - MyStartTime));


	/*
	// ERRCODE_DISK_FULL could be reported vi rbmsMIB rdbmsTraps rdbmsOutOfSpace trap.
	// But it appears we never generate that error?

	// ERRCODE_ADMIN_SHUTDOWN means SysAdmin aborted somebody's request.  Not interesting?

	// ERRCODE_CRASH_SHUTDOWN sounds interesting, but I don't see that we ever generate it.

	// ERRCODE_CANNOT_CONNECT_NOW means we are starting up, shutting down, in recovery, or Too many users are logged on.

	// abnormal database system shutdown
	*/



	/*
	 * The gpdbAlertSeverity is a crude attempt to classify some of these messages based on severity,
	 * where OK means everything is running normal, Down means everything is shut down, degraded would be
	 * for times when some segments are down, but the system is up, The others are maybe useful in the future
	 *
	 *  gpdbSevUnknown(0),
	 *	gpdbSevOk(1),
	 *	gpdbSevWarning(2),
	 *	gpdbSevError(3),
	 *	gpdbSevFatal(4),
	 *	gpdbSevPanic(5),
	 *	gpdbSevSystemDegraded(6),
	 *	gpdbSevSystemDown(7)
	 */


	char detail[MAX_ALERT_STRING+1];
	snprintf(detail, MAX_ALERT_STRING, "%s", errorData->error_detail);
	detail[127] = '\0';

	char sqlstmt[MAX_ALERT_STRING+1];
	char * sqlstmtp = errorData->debug_query_string;
	if (sqlstmtp == NULL || sqlstmtp[0] == '\0')
		sqlstmtp = errorData->internal_query;
	if (sqlstmtp == NULL)
		sqlstmtp = "";


	snprintf(sqlstmt, MAX_ALERT_STRING, "%s", sqlstmtp);
	sqlstmt[MAX_ALERT_STRING] = '\0';


	/* Need a modifiable copy of To list */
	rawstring = pstrdup(gp_snmp_monitor_address);

	/* Parse string into list of identifiers */
	if (!SplitMailString(rawstring, ',', &elemlist))
	{
		/* syntax error in list */
		ereport(LOG,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid list syntax for \"gp_snmp_monitor_address\"")));
		return -1;
	}


	/*
	 * This session is just a template, and doesn't need to be connected.
	 * It is used by snmp_add(), which copies this info, opens the new session, and assigns the transport.
	 */
	snmp_sess_init( &session );	/* Initialize session to default values */
	session.version = SNMP_VERSION_2c;
	session.timeout = SNMP_DEFAULT_TIMEOUT;
	session.retries = SNMP_DEFAULT_RETRIES;
	session.remote_port = 162; 							// I think this isn't used by net-snmp any more.

	/*if (strchr(session.peername,':')==NULL)
		strcat(session.peername,":162");*/
	session.community = (u_char *)gp_snmp_community;
	session.community_len = strlen((const char *)session.community);  // SNMP_DEFAULT_COMMUNITY_LEN means "public"
	session.callback_magic = NULL;

	foreach(l, elemlist)
	{
		char	   *cur_gp_snmp_monitor_address = (char *) lfirst(l);

		if (cur_gp_snmp_monitor_address == NULL || cur_gp_snmp_monitor_address[0] == '\0')
			continue;

		session.peername = cur_gp_snmp_monitor_address;
		/*
		 * If we try to "snmp_open( &session )", net-snmp will set up a connection to that
		 * endpoint on port 161, assuming we are the network monitor, and the other side is an agent.
		 *
		 * But we are pretending to be an agent, sending traps to the NM, so we don't need this.
		 */

		/*if (!snmp_open( &session ))   	// Don't open the session here!
		{
			const char     *str;
			int             xerr;
			xerr = snmp_errno;
			str = snmp_api_errstring(xerr);
			elog(LOG, "snmp_open: %s", str);
			return -1;
		}*/

		/*
		 * This call copies the info from "session" to "ss", assigns the transport, and opens the session.
		 * We must specify "snmptrap" so the transport will know we want port 162 by default.
		 */
		ss = snmp_add(&session,
					  netsnmp_transport_open_client("snmptrap", cur_gp_snmp_monitor_address),
					  NULL, NULL);
		if (ss == NULL) {
			/*
			 * diagnose netsnmp_transport_open_client and snmp_add errors with
			 * the input netsnmp_session pointer
			 */
			{
				char           *err;
				snmp_error(&session, NULL, NULL, &err);
				elog(LOG, "send_alert snmp_add of %s failed: %s", cur_gp_snmp_monitor_address, err);
				free(err);
			}
			return -1;
		}

		/*
		 * We need to create the pdu each time, as it gets freed when we send a trap.
		 */
		pdu = snmp_pdu_create(inform ? SNMP_MSG_INFORM : SNMP_MSG_TRAP2);
		if (!pdu)
		{
			const char     *str;
			int             xerr;
			xerr = snmp_errno;
			str = snmp_api_errstring(xerr);
			elog(LOG, "Failed to create notification PDU: %s", str);
			return -1;
		}

		/*
		 * Trap/Inform messages always start with the system up time. (SysUpTime.0)
		 * We use Postmaster's "MyStartTime" as a way to get that.
		 */

		snmp_add_var(pdu, objid_sysuptime,
							sizeof(objid_sysuptime) / sizeof(oid),
							't', (const char *)csysuptime);

	#if 0
		/*
		 * In the future, we might want to send RDBMS-MIB::rdbmsStateChange when the system becomes unavailable or
		 * partially unavailable.  This code, which is not currently used, shows how to build the pdu for
		 * that trap.
		 */
		/* {iso(1) identified-organization(3) dod(6) internet(1) mgmt(2) mib-2(1) rdbmsMIB(39) rdbmsTraps(2) rdbmsStateChange(1)} */
		snmp_add_var(pdu, objid_snmptrap,
							sizeof(objid_snmptrap) / sizeof(oid),
							'o', "1.3.6.1.2.1.39.2.1");  // rdbmsStateChange


		snmp_add_var(pdu, objid_rdbmsrelstate,
							sizeof(objid_rdbmsrelstate) / sizeof(oid),
							'i', "5");  // 4 = restricted, 5 = unavailable
	#endif

		/* {iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprises(1) gpdbMIB(31327) gpdbTraps(5) gpdbTrapsList(0) gpdbAlert(1)} */

		/*
		 * We could specify this trap oid by name, rather than numeric oid, but then if the GPDB-MIB wasn't
		 * found, we'd get an error.  Using the numeric oid means we can still work without the MIB loaded.
		 */
		snmp_add_var(pdu, objid_snmptrap,
							sizeof(objid_snmptrap) / sizeof(oid),
							'o', "1.3.6.1.4.1.31327.5.0.1");  // gpdbAlert


		snmp_add_var(pdu, objid_gpdbAlertMsg,
							sizeof(objid_gpdbAlertMsg) / sizeof(oid),
							's', subject);  // SnmpAdminString = UTF-8 text
		snmp_add_var(pdu, objid_gpdbAlertSeverity,
							sizeof(objid_gpdbAlertSeverity) / sizeof(oid),
							'i', (char *)severity);

		snmp_add_var(pdu, objid_gpdbAlertSqlstate,
							sizeof(objid_gpdbAlertSqlstate) / sizeof(oid),
							's', errorData->sql_state);

		snmp_add_var(pdu, objid_gpdbAlertDetail,
							sizeof(objid_gpdbAlertDetail) / sizeof(oid),
							's', detail); // SnmpAdminString = UTF-8 text

		snmp_add_var(pdu, objid_gpdbAlertSqlStmt,
							sizeof(objid_gpdbAlertSqlStmt) / sizeof(oid),
							's', sqlstmt); // SnmpAdminString = UTF-8 text

		snmp_add_var(pdu, objid_gpdbAlertSystemName,
							sizeof(objid_gpdbAlertSystemName) / sizeof(oid),
							's', myhostname); // SnmpAdminString = UTF-8 text



		elog(DEBUG2,"ready to send to %s",cur_gp_snmp_monitor_address);
		if (inform)
			status = snmp_synch_response(ss, pdu, &response);
		else
			status = snmp_send(ss, pdu) == 0;

		elog(DEBUG2,"send, status %d",status);
		if (status != STAT_SUCCESS)
		{
			/* Something went wrong */
			if (ss)
			{
				char           *err;
				snmp_error(ss, NULL, NULL, &err);
				elog(LOG, "sendalert failed to send %s: %s", inform ? "inform" : "trap", err);
				free(err);
			}
			else
			{
				elog(LOG, "sendalert failed to send %s: %s", inform ? "inform" : "trap", "Something went wrong");
			}
			if (!inform)
				snmp_free_pdu(pdu);
		}
		else if (inform)
			snmp_free_pdu(response);

		snmp_close(ss);
		ss = NULL;

	}
Esempio n. 6
0
void *poller(void *thread_args)
{
    worker_t *worker = (worker_t *) thread_args;
    crew_t *crew = worker->crew;
    target_t *entry = NULL;
    void *sessp = NULL;
    struct snmp_session session;
    struct snmp_pdu *pdu = NULL;
    struct snmp_pdu *response = NULL;
    oid anOID[MAX_OID_LEN];
    size_t anOID_len = MAX_OID_LEN;
    struct variable_list *vars = NULL;
    unsigned long long result = 0;
    unsigned long long last_value = 0;
    unsigned long long insert_val = 0;
    int poll_status = 0, db_status = 0, bits = 0, init = 0;
    char query[BUFSIZE];
    char storedoid[BUFSIZE];
    char result_string[BUFSIZE];
    int cur_work = 0;
    int prev_work = 99999999;
    int loop_count = 0;


#ifdef FEATURES
	/* Per thread SQL connection testing */
  #if HAVE_MYSQL
	MYSQL mysql;
  #elif HAVE_PGSQL
	PGconn *pgsql;
  #endif
	double rate = 0;
	struct timezone tzp;
	struct timeval current_time;
	struct timeval last_time;

	/* for thread settings */
	int oldstate, oldtype;
#endif

	debug(HIGH, "Thread [%d] starting.\n", worker->index);

    pthread_cleanup_push(cleanup_db, NULL);



    /* Attempt to connect to the MySQL Database */
#ifdef FEATURES
	/* Per thread MySQL connection testing */
    if (!(set->dboff)) {
	/* load the database driver */
	if (!(db_init(set))) {
		fatal("** Database error - check configuration.\n");
	}
	/* connect to the database */
	if (!(db_connect(set))) {
		fatal("server not responding.\n");
	}
		/* set up cancel function for exit */
		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
		pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
    }
#endif /* FEATURES */

    while (1) {

/*        if(loop_count >= POLLS_PER_TRANSACTION) {
            debug(HIGH, "Thread [%d] doing commit on %d\n", worker->index, POLLS_PER_TRANSACTION);
            db_status = db_commit(); 
            loop_count = 0;
        }
*/

#ifdef FEATURES
	/* see if we've been cancelled before we start another loop */
	pthread_testcancel();
#endif
	debug(DEVELOP, "Thread [%d] locking (wait on work)\n", worker->index);

	PT_MUTEX_LOCK(&crew->mutex);
#ifdef FEATURES
	/* add an unlock to the cancel stack */
	pthread_cleanup_push(cancel_lock, &crew->mutex);	
#endif

	while (current == NULL) {
		PT_COND_WAIT(&crew->go, &crew->mutex);
	}
	debug(DEVELOP, "Thread [%d] done waiting, received go (work cnt: %d)\n",
		worker->index, crew->work_count);
        cur_work = crew->work_count;
/*         if(cur_work > prev_work) {
            debug(HIGH, "Thread [%d] doing commit at %d\n", worker->index,time(NULL));
            db_status = db_commit(); 
            loop_count = 0;
        }
*/
        prev_work = cur_work;

	if (current != NULL) {
		debug(DEVELOP, "Thread [%d] processing %s %s (%d work units remain in queue)\n",
			worker->index, current->host->host, current->objoid, crew->work_count);
	    snmp_enable_stderrlog(); 
            snmp_sess_init(&session);
		if (current->host->snmp_ver == 2)
			session.version = SNMP_VERSION_2c;
		else
			session.version = SNMP_VERSION_1;
	    session.peername = current->host->host;
	    session.community = current->host->community;
		session.remote_port = set->snmp_port;
	    session.community_len = strlen(session.community);

	    sessp = snmp_sess_open(&session);
	    anOID_len = MAX_OID_LEN;
	    pdu = snmp_pdu_create(SNMP_MSG_GET);
	    read_objid(current->objoid, anOID, &anOID_len);
	    entry = current;
	    last_value = current->last_value;
#ifdef FEATURES
		/* save the time so we can calculate rate */
		last_time = current->last_time;
#endif
	    init = current->init;
	    insert_val = 0;
	    bits = current->bits;
	    strncpy(storedoid, current->objoid, sizeof(storedoid));
		current = getNext();
	}
	debug(DEVELOP, "Thread [%d] unlocking (done grabbing current)\n", worker->index);
	PT_MUTEX_UNLOCK(&crew->mutex);
#ifdef FEATURES
	/* take the unlock off the cancel stack */
	pthread_cleanup_pop(FALSE);
#endif

	snmp_add_null_var(pdu, anOID, anOID_len);
	if (sessp != NULL) 
	   poll_status = snmp_sess_synch_response(sessp, pdu, &response);
	else
	   poll_status = STAT_DESCRIP_ERROR;

	/* Collect response and process stats */
	PT_MUTEX_LOCK(&stats.mutex);
	if (poll_status == STAT_DESCRIP_ERROR) {
	    stats.errors++;
            printf("*** SNMP Error: (%s) Bad descriptor.\n", session.peername);
	} else if (poll_status == STAT_TIMEOUT) {
	    stats.no_resp++;
	    printf("*** SNMP No response: (%s@%s).\n", session.peername,
	       storedoid);
	} else if (poll_status != STAT_SUCCESS) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) Unsuccessuful (%d).\n", session.peername,
	       storedoid, poll_status);
	} else if (poll_status == STAT_SUCCESS && response->errstat != SNMP_ERR_NOERROR) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) %s\n", session.peername,
	       storedoid, snmp_errstring(response->errstat));
	} else if (poll_status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR && response->variables->type == SNMP_NOSUCHINSTANCE) {
	    stats.errors++;
	    printf("*** SNMP Error: No Such Instance Exists (%s@%s)\n", session.peername, storedoid);
	} else if (poll_status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	    stats.polls++;
	} 
	PT_MUTEX_UNLOCK(&stats.mutex);

	/* Liftoff, successful poll, process it */
#ifdef FEATURES
	/* Get the current time */
	gettimeofday(&current_time, &tzp);
#endif

	if (poll_status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR && response->variables->type != SNMP_NOSUCHINSTANCE) {
	    vars = response->variables;
#ifdef OLD_UCD_SNMP
            sprint_value(result_string, anOID, anOID_len, vars);
#else
	    snprint_value(result_string, BUFSIZE, anOID, anOID_len, vars);
#endif
	    switch (vars->type) {
		/*
		 * Switch over vars->type and modify/assign result accordingly.
		 */
		case ASN_COUNTER64:
		    debug(DEBUG, "64-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = vars->val.counter64->high;
		    result = result << 32;
		    result = result + vars->val.counter64->low;
		    break;
		case ASN_COUNTER:
		    debug(DEBUG, "32-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_INTEGER:
		    debug(DEBUG, "Integer result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_GAUGE:
		    debug(DEBUG, "32-bit gauge: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_TIMETICKS:
		    debug(DEBUG, "Timeticks result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_OPAQUE:
		    debug(DEBUG, "Opaque result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_OCTET_STR:
		    debug(DEBUG, "String Result: (%s@%s) %s\n", session.peername, storedoid, result_string);
#ifdef HAVE_STRTOLL
		    result = strtoll(vars->val.string, NULL, 0);
#else
		    result = strtol(vars->val.string, NULL, 0);
#endif
		    break;
		default:
		    debug(LOW, "Unknown result type: (%s@%s) %s\n", session.peername, storedoid, result_string);
	    }

		/* Gauge Type */
		if (bits == 0) {
			if (result != last_value) {
				insert_val = result;
				debug(DEVELOP, "Thread [%d]: Gauge change from %lld to %lld\n", worker->index, last_value, insert_val);
			} else {
				if (set->withzeros) 
					insert_val = result;
				debug(DEVELOP, "Thread [%d]: Gauge steady at %lld\n", worker->index, insert_val);
			}
	    /* Counter Wrap Condition */
	    } else if (result < last_value) {
			PT_MUTEX_LOCK(&stats.mutex);
              stats.wraps++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	      if (bits == 32) insert_val = (THIRTYTWO - last_value) + result;
	      else if (bits == 64) insert_val = (SIXTYFOUR - last_value) + result;

#ifdef FEATURES
			rate = insert_val / timediff(current_time, last_time);
#endif

	      debug(LOW, "*** Counter Wrap (%s@%s) [poll: %llu][last: %llu][insert: %llu]\n",
	         session.peername, storedoid, result, last_value, insert_val);
	    /* Not a counter wrap and this is not the first poll */
	    } else if ((last_value >= 0) && (init != NEW)) {
		insert_val = result - last_value;

#ifdef FEATURES
			rate = insert_val / timediff(current_time, last_time);
#endif
		
	        /* Print out SNMP result if verbose */
	        if (set->verbose == DEBUG)
		  printf("Thread [%d]: (%lld-%lld -- %llu) = %llu\n", worker->index, result, last_value, insert_val,rate);
	        if (set->verbose == HIGH)
		  printf("Thread [%d]: %llu\n", worker->index, insert_val);
            /* last_value < 0, so this must be the first poll */
	    } else {
#ifdef FEATURES
			/* set up this result for the next poll */
			entry->last_value = result;
#endif
			debug(HIGH, "Thread [%d]: First Poll, Normalizing\n", worker->index);
	    }

		/* Check for bogus data, either negative or unrealistic */
	    if (insert_val > entry->maxspeed || result < 0) {
			debug(LOW, "*** Out of Range (%s@%s) [insert_val: %llu] [oor: %lld]\n",
				session.peername, storedoid, insert_val, entry->maxspeed);
			insert_val = 0;
#ifdef FEATURES
			rate = 0;
#endif
			PT_MUTEX_LOCK(&stats.mutex);
			stats.out_of_range++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	    }

		if (!(set->dboff)) {
			if ( (insert_val > 0) || (set->withzeros) ) {
#ifndef FEATURES
				/* MP - since we have our own database connection we don't need to lock it anymore */
				PT_MUTEX_LOCK(&crew->mutex);
#endif

                                debug(DEVELOP, "db_insert sent: %s %d %d %e\n",entry->table,entry->iid,insert_val,rate);
				/* insert into the database */
				db_status = db_insert(entry->table, entry->iid, insert_val, rate);

#ifndef FEATURES
				/* MP - since we have our own database connection we don't need to lock it anymore */
				PT_MUTEX_UNLOCK(&crew->mutex);
#endif

				if (db_status) {
					PT_MUTEX_LOCK(&stats.mutex);
					stats.db_inserts++;
					PT_MUTEX_UNLOCK(&stats.mutex);
				} else {
					fatal("Fatal database error.\n");
				}
			} /* insert_val > 0 or withzeros */	
		} /* !dboff */

	} /* STAT_SUCCESS */

/*	debug(HIGH, "Thread [%d] doing commit\n", worker->index);
        db_status = db_commit(); */

        if (sessp != NULL) {
           snmp_sess_close(sessp);
           if (response != NULL) snmp_free_pdu(response);
        }

	debug(DEVELOP, "Thread [%d] locking (update work_count)\n", worker->index);
	PT_MUTEX_LOCK(&crew->mutex);
	crew->work_count--;
	/* Only if we received a positive result back do we update the
	   last_value object */
	if (poll_status == STAT_SUCCESS) {
		entry->last_value = result;
		if (init == NEW) entry->init = LIVE;
	}

#ifdef FEATURES
	/* always update the time */
	entry->last_time = current_time;	
#endif

	if (crew->work_count <= 0) {
	    debug(HIGH, "Queue processed. Broadcasting thread done condition.\n");
		PT_COND_BROAD(&crew->done);
	}
	debug(DEVELOP, "Thread [%d] unlocking (update work_count)\n", worker->index);

		PT_MUTEX_UNLOCK(&crew->mutex);

        loop_count++;
    }				/* while(1) */
    pthread_cleanup_pop(FALSE);

/* Not reached */
}
Esempio n. 7
0
int
main(int argc, char **argv)
{
    /*
     * Defs for arg-handling code: handles setting of policy-related variables 
     */
    int             ch;
    int             dont_fork = 0, use_syslog = 0, kdump_only = 0;
    int             ilo_gen = 0;
    char            *transport = "hpilo:";
    int             i;

    int            do_ahs = 1;
    int            do_ide = 1;
    int            do_host = 1;
    int            do_nic = 1;
    int            do_scsi = 1;
    int            do_pmp = 0;
    int            do_se = 1;
    int            do_fca = 1;
    int            do_mibII = 1;
    int scale = 1;
    char *argarg;
    int             prepared_sockets = 0;
    struct stat     st;
    struct timeval the_time[2];

    init_etime(&the_time[0]);

    if (stat("/sys/module/hpilo", &st) != 0 ) {
       printf("hp-ams requires that the hpilo kernel module is loaded");
       exit(1);
    } 
        
#ifndef NETSNMP_NO_SYSTEMD
    /* check if systemd has sockets for us and don't close them */
    prepared_sockets = netsnmp_sd_listen_fds(0);
#endif /* NETSNMP_NO_SYSTEMD */

    /*
     * close all non-standard file descriptors we may have
     * inherited from the shell.
     */
    if (!prepared_sockets) {
        for (i = getdtablesize() - 1; i > 2; --i) {
            (void) close(i);
        }
    }

    snmp_disable_log();

    while ((ch = getopt(argc, argv, "D:fG:kLM::OI:P:t:T::x:V:")) != EOF)
        switch (ch) {
        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;
        case 'f':
            dont_fork = 1;
            break;
        case 'k':
            kdump_only = 1;
            break;
        case 'h':
            usage();
            exit(0);
            break;
        case 'G':
            GenericData = optarg;
            break;
        case 'I':
            log_interval = atoi(optarg);
            if ((log_interval <0) || (log_interval > 3)) {
                usage();
                exit(0);
            }
            break;
        case 'P':
            interval2ping = atoi(optarg);
            if (interval2ping <0)  {
                usage();
                exit(0);
            }
            break;
        case 'L':
            use_syslog = 0;     /* use stderr */
            break;
        case 'M':
            argarg = optarg;
            do_ahs = 0;
            
            do_ide = 0;
            do_nic = 0;
            do_scsi = 0;
            do_host = 0;
            do_pmp = 0;
            do_se = 0;
            do_fca = 0;
            do_mibII = 1;
            while (argarg != 0) {
                char * mibnum;
                int mibitem;

                do_mibII = 0;
                mibnum = argarg;
                argarg = index(mibnum, ',');
                if (argarg != 0) {
                    *argarg = 0;
                    argarg++;
                }
                mibitem = atoi(mibnum);
                switch (mibitem) {
                    case 0:
                        do_ahs = 1;
                        break; 
                    case 1:
                        do_se = 1;
                        break; 
                    case 5:
                        do_scsi = 1;
                        break; 
                    case 11:
                        do_host = 1;
                        break; 
                    case 14:
                        do_ide = 1;
                        break; 
                    case 16:
                        do_fca = 1;
                        break; 
                    case 18:
                        do_nic = 1;
                        break; 
                    case 23:
                        do_pmp = 1;
                        break; 
                    case 99:
                        do_mibII = 1;
                        break; 
                    default:
                        break; 
                }
            }
            break;
        case 'O':
            gen8_only = 0;     /* allow to run on non supported */
            break;
        case 't':
             if (optarg != (char *) 0) 
                trap_fire = atoi(optarg);
            else
                trap_fire = 1;

            break;
        case 'T':
            if (optarg != (char *) 0) {
                switch (optarg[strlen(optarg)-1]) {
                    case 'd':
                    case 'D':
                        optarg[strlen(optarg)-1] = (char )0;
                        scale = 60*60*24;
                        break;
                    case 'h':
                    case 'H':
                        optarg[strlen(optarg)-1] = (char )0;
                        scale = 60*60;
                        break;
                    case 'm':
                    case 'M':
                        optarg[strlen(optarg)-1] = (char )0;
                        scale = 60;
                        break;
                    case 'S':
                    case 's':
                        optarg[strlen(optarg)-1] = (char )0;
                    default:
                        break;
                }
                testtrap_interval = atoi(optarg) * scale;
                if ((testtrap_interval < 10) || (testtrap_interval > (7*24*60*60))) {
                    usage();
                    exit(0);
                }
            }
            break;
        case 'x':
            if (optarg != NULL) {
                transport = optarg;
            } else {
                usage();
            }
            break;
        case 'V':
            if (optarg != NULL) {
                vendor_tag = optarg;
            } else {
                usage();
            }
            break;
        default:
            fprintf(stderr, "unknown option %c\n", ch);
            usage();
            exit(1);
        }

    /* if the -k option was provided, then also set the dont_fork flag. */
    if (kdump_only) {
        dont_fork = 1;
    }

    if (dont_fork) {
        snmp_enable_stderrlog();
    }

    netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                                      NETSNMP_DS_AGENT_X_SOCKET, transport);
    /*
     * make us a agentx client. 
     */
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
                                    NETSNMP_DS_AGENT_ROLE, 1);

    if (InitSMBIOS() == 0 ) {
        if (gen8_only == 0) {
            fprintf(stderr,"SM BIOS initialization failed,"
                       " some functionality may not exist\n");
        } else {
            fprintf(stderr,"SM BIOS initialization failed,"
                       " unable to determine system type\n");
            exit(1);
        }
    } else {
        ilo_gen = GetiLOGen();
        if ((gen8_only) && (ilo_gen < 4)) {
            fprintf(stderr,"This program requires the host to have a HP Integrated Lights Out 4 (iLO 4)"
                       " BMC\n");
            exit(1);
        }
    }

    /*
     * daemonize 
     */
    snmp_disable_log();

    if (!dont_fork) {
        snmp_enable_calllog();
        int             rc = netsnmp_daemonize(1, use_syslog);
        if (rc)
            exit(-1);
    } else
        snmp_enable_stderrlog();


    /* Clear out Status array */
    memset(cpqHostMibStatusArray,0,sizeof(cpqHostMibStatusArray));
    memset(cpqHoMibHealthStatusArray, 0, sizeof(cpqHoMibHealthStatusArray));

    DEBUGMSG(("amsHelper:timer", "interval for StartUp %dms\n", get_etime(&the_time[0])));

    if (do_ahs) {
        LOG_PROCESS_CRASHES();

        DEBUGMSG(("amsHelper:timer", "interval for Log Crashes %dms\n", get_etime(&the_time[0])));

        if (kdump_only) {
            return 0;
        }

        LOG_OS_BOOT();

        DEBUGMSG(("amsHelper:timer", "interval for Log Boot %dms\n", get_etime(&the_time[0])));

    }
    openlog("hp-ams",  LOG_CONS | LOG_PID, LOG_DAEMON);
    /*
     * initialize the agent library 
     */
    init_agent("amsHelper");

    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID,
                       NETSNMP_DS_HPILODOMAIN_IML, 4);

    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_TIMEOUT, 120 * ONE_SEC);

    /* set ping inetrval to interval2pimn - default is 0 */
    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_PING_INTERVAL, interval2ping);

    /* sometime iLO4 can be slow so double the default to 2 sec if necessary*/
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TIMEOUT, 3); 

    /* if the ilo starts dropping packets retry a couple of times */
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES, 5);

    init_snmp("amsHelper");

    DEBUGMSG(("amsHelper:timer", "interval for SNMP startup %dms\n", get_etime(&the_time[0])));

    if (do_mibII) {
        init_mib_modules();
        DEBUGMSG(("amsHelper:timer", "interval for init MIB-2 %dms\n", get_etime(&the_time[0])));
    }

    if (do_host) {
        init_cpqHost();
        DEBUGMSG(("amsHelper:timer", "interval for cpqHost %dms\n", get_etime(&the_time[0])));
    }

    if (do_ahs) {
        LOG_OS_INFORMATION();
        DEBUGMSG(("amsHelper:timer", "interval for LOG OS %dms\n", get_etime(&the_time[0])));

        LOG_DRIVERS();
        DEBUGMSG(("amsHelper:timer", "interval for Log drivers %dms\n", get_etime(&the_time[0])));

        LOG_SERVICE();
        DEBUGMSG(("amsHelper:timer", "interval for Log services %dms\n", get_etime(&the_time[0])));

        LOG_PACKAGE();
        DEBUGMSG(("amsHelper:timer", "interval for Log packages %dms\n", get_etime(&the_time[0])));
    }

    if (do_se) {
        init_cpqStdPciTable();
        DEBUGMSG(("amsHelper:timer", "interval for cpqSe %dms\n", get_etime(&the_time[0])));
    }

    if (do_scsi) {
        init_cpqScsi();
        DEBUGMSG(("amsHelper:timer", "interval for cpqScsi %dms\n", get_etime(&the_time[0])));
    }

    if (do_ide) {
        init_cpqIde();
        DEBUGMSG(("amsHelper:timer", "interval for cpqIde %dms\n", get_etime(&the_time[0])));
    }

    if (do_fca) {
        init_cpqFibreArray();
        DEBUGMSG(("amsHelper:timer", "interval for cpqFca %dms\n", get_etime(&the_time[0])));
    }

    if (do_nic) {
        init_cpqNic();
        DEBUGMSG(("amsHelper:timer", "interval for cpqNic %dms\n", get_etime(&the_time[0])));
    }

    if (do_pmp) {
        init_cpqLinOsMgmt();
        DEBUGMSG(("amsHelper:timer", "interval for cpqLinOsMgmt %dms\n", get_etime(&the_time[0])));
    }

    /*
     * Send coldstart trap if possible.
     */
    send_easy_trap(0, 0);
    syslog(LOG_NOTICE, "amsHelper Started . . "); 
    /*
     * Let systemd know we're up.
     */
#ifndef NETSNMP_NO_SYSTEMD
    netsnmp_sd_notify(1, "READY=1\n");
    if (prepared_sockets)
        /*
         * Clear the environment variable, we already processed all the sockets
         * by now.
         */
        netsnmp_sd_listen_fds(1);
#endif

    if (do_ahs) {
        LOG_OS_USAGE();
        DEBUGMSG(("amsHelper:timer", "interval for LOG OS Usage%dms\n", get_etime(&the_time[0])));

        LOG_PROCESSOR_USAGE();
        DEBUGMSG(("amsHelper:timer", "interval for LOG Processor Usage %dms\n", get_etime(&the_time[0])));

        LOG_MEMORY_USAGE();
        DEBUGMSG(("amsHelper:timer", "interval for LOG Memory Usage %dms\n", get_etime(&the_time[0])));
    }

    /*
     * In case we recevie a request to stop (kill -TERM or kill -INT) 
     */
    ams_running = 1;
    signal(SIGTERM, stop_server);
    signal(SIGINT, stop_server);

    DEBUGMSGTL(("snmpd/main", "We're up.  Starting to process data.\n"));
    if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                NETSNMP_DS_AGENT_QUIT_IMMEDIATELY))
        receive();

    snmp_shutdown("amsHelper");

    LOG_OS_SHUTDOWN();

    syslog(LOG_NOTICE, "amsHelper Stopped . . "); 
    exit(0);
}
Esempio n. 8
0
int
main (int argc, char **argv)
{
	
	  	int agentx_subagent = AGENT_TRUE;
	  	int c;
	  	int rc = 0;
	  
	  	SaErrorT 	rv = SA_OK;
		SaHpiVersionT	hpiVer;
		SaHpiSessionIdT sessionid;
                SaHpiDomainInfoT        domain_info;  		
		SaHpiBoolT      run_threaded = TRUE;
		
	  	pid_t child;
		
		char * env;
	  		  	
	  	/* change this if you want to be a SNMP master agent */
	  	
	  	debug_register_tokens (AGENT);
                snmp_enable_stderrlog ();
                snmp_set_do_debugging (1);

	  	while ((c = getopt (argc, argv, "fdsCx:h?")) != EOF) {
	    switch (c) {
	   	case 'f':
			do_fork = AGENT_TRUE;
		   	break;
	
	    case 'd':
			debug_register_tokens (AGENT);
			snmp_enable_stderrlog ();
			snmp_set_do_debugging (1);
	      	break;
	
	  	case 's':
			do_syslog = AGENT_FALSE;
	      	break;
	
	   	case 'C':
			netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
				       NETSNMP_DS_LIB_DONT_READ_CONFIGS,
				       1);
	     	break;
	
	  	case 'x':
			netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
				      NETSNMP_DS_AGENT_X_SOCKET,
				      optarg);
	      	break;
	
	 	case 'h':
	    default:
			usage(argv[0]);
			exit(1);
	      	break;
	    }
	  }
	
	  if (do_syslog == AGENT_TRUE) {
	      snmp_enable_calllog ();
	      snmp_enable_syslog_ident (AGENT, LOG_DAEMON);
	  }
	  snmp_log (LOG_INFO, "Starting %s\n", version);
	  /* we're an agentx subagent? */
	  if (agentx_subagent) {
	      /* make us a agentx client. */
	      rc = netsnmp_ds_set_boolean (NETSNMP_DS_APPLICATION_ID,
					   NETSNMP_DS_AGENT_ROLE, 1);
	  }
	
	  /* initialize the agent library */
	  rc = init_agent (AGENT);
	  if (rc != 0) {
	      snmp_log (LOG_ERR, "Could not initialize connection to SNMP daemon. \n"
			"Perhaps you are running %s as non-root?\n", argv[0]);
	      exit (rc);
	  }

	  /* Read configuration information here, before we initialize */
	
	  snmpd_register_config_handler (TRAPS_TOKEN,
					 hpiSubagent_parse_config_traps,
					 NULL,
					 "hpiSubagent on/off switch for sending events upon startup");
	
	  snmpd_register_config_handler (MAX_EVENT_TOKEN,
					 hpiSubagent_parse_config_max_event,
					 NULL,
					 "hpiSubagent MAX number of rows for Events.");
					 
	init_snmp (AGENT); 	
	
	/* 
	 * Initialize HPI library
	 */
	hpiVer = saHpiVersionGet();
	DEBUGMSGTL ((AGENT, "Hpi Version %d Implemented.\n", hpiVer));   	 

	rv = saHpiSessionOpen( SAHPI_UNSPECIFIED_DOMAIN_ID, &sessionid, NULL );
	if (rv != SA_OK) {
		DEBUGMSGTL ((AGENT, "saHpiSessionOpen Error: returns %s\n",
			oh_lookup_error(rv)));
		exit(-1);
	}
   	DEBUGMSGTL ((AGENT, "saHpiSessionOpen returns with SessionId %d\n", 
   		sessionid)); 

        /* Get the DomainInfo structur,  This is how we get theDomainId for this Session */
	rv = saHpiDomainInfoGet(sessionid, &domain_info);
	if (rv != SA_OK) {
                DEBUGMSGTL ((AGENT, "saHpiSessionOpen Error: returns %s\n",
                        oh_lookup_error(rv)));
                exit(-1);
	}

        /* store session numbers */
   	store_session_info(sessionid, domain_info.DomainId);	
   				
	/* subscribe all sessions/events */
        subcsribe_all_sessions();

	/* Resource discovery */
	rv = saHpiDiscover(sessionid);
	
	if (rv != SA_OK) {
		DEBUGMSGTL ((AGENT, "saHpiDiscover Error: returns %s\n",oh_lookup_error(rv)));
		exit(-1);
	}
	DEBUGMSGTL ((AGENT, "saHpiDiscover Success!\n"));	

	/* Initialize subagent tables */		
	init_saHpiDomainInfoTable(); 
	init_saHpiDomainAlarmTable();
	init_saHpiDomainReferenceTable();
	
	init_saHpiResourceTable();
	init_saHpiRdrTable();
	init_saHpiCtrlDigitalTable();
	init_saHpiCtrlDiscreteTable();
	init_saHpiCtrlAnalogTable();
	init_saHpiCtrlStreamTable();
	init_saHpiCtrlTextTable();
	init_saHpiCtrlOemTable();
	init_saHpiSensorTable();
	init_saHpiCurrentSensorStateTable();
	init_saHpiSensorReadingMaxTable();
	init_saHpiSensorReadingMinTable();
	init_saHpiSensorReadingNominalTable();
	init_saHpiSensorReadingNormalMaxTable();
	init_saHpiSensorReadingNormalMinTable();
	init_saHpiSensorThdLowCriticalTable();
	init_saHpiSensorThdLowMajorTable();
	init_saHpiSensorThdLowMinorTable();
	init_saHpiSensorThdUpCriticalTable();
	init_saHpiSensorThdUpMajorTable();
	init_saHpiSensorThdUpMinorTable();
	init_saHpiSensorThdPosHysteresisTable();
	init_saHpiSensorThdNegHysteresisTable();
	init_saHpiInventoryTable();
	init_saHpiWatchdogTable();
	init_saHpiAnnunciatorTable();
	init_saHpiAreaTable();
	init_saHpiFieldTable();

	init_saHpiEventTable();
	init_saHpiResourceEventTable();
	init_saHpiDomainEventTable();
	init_saHpiSensorEventTable();
	init_saHpiOEMEventTable();
	init_saHpiHotSwapEventTable();
	init_saHpiWatchdogEventTable();		
	init_saHpiSoftwareEventTable();
	init_saHpiSensorEnableChangeEventTable();
	init_saHpiUserEventTable();

	init_saHpiEventLogInfoTable();
	init_saHpiEventLogTable();
	init_saHpiResourceEventLogTable();
	init_saHpiSensorEventLogTable();
	
	init_saHpiHotSwapEventLogTable();
	init_saHpiWatchdogEventLogTable();
	init_saHpiSoftwareEventLogTable();
	init_saHpiOEMEventLogTable();
	init_saHpiUserEventLogTable();
	init_saHpiSensorEnableChangeEventLogTable();
	init_saHpiDomainEventLogTable();
	
	init_saHpiHotSwapTable();
        init_saHpiAutoInsertTimeoutTable();
	init_saHpiAutoInsertTimeoutTable();
	init_saHpiAnnouncementTable();
	init_saHpiAnnouncementEventLogTable();


	if (send_traps_on_startup == AGENT_TRUE)
		send_traps = AGENT_TRUE;
	/* after initialization populate tables */
	populate_saHpiDomainInfoTable(sessionid);

	populate_saHpiDomainAlarmTable(sessionid);

	poplulate_saHpiDomainReferenceTable(sessionid);	

	populate_saHpiResourceTable(sessionid);
	    /* populate_saHpiResourceTable() calls:
	     *     populate_saHpiRdrTable(); calls:
	     *         populate_saHpiCtrlDigitalTable();		
	     *	       populate_saHpiCtrlDiscreteTable();		
	     *	       populate_saHpiCtrlAnalogTable();		
	     *	       populate_saHpiCtrlStreamTable();		
	     *	       populate_saHpiCtrlTextTable();		
	     *	       populate_saHpiCtrlOemTable();		
	     *	       populate_saHpiSensorTable();		
	     *	           populate_saHpiSesnorReadingMaxTable();		
	     *	           populate_saHpiSesnorReadingMinTable();		
	     *	           populate_saHpiSesnorReadingNominalTable();		
	     *	           populate_saHpiSesnorReadingNormalMaxTable();		
	     *	           populate_saHpiSesnorReadingNormalMinTable();		
	     *	           populate_saHpiSensorThdLowCriticalTable();		
	     *	           populate_saHpiSensorThdLowMajorTable();		
	     *	           populate_saHpiSensorThdLowMinorTable();		
	     *	           populate_saHpiSensorThdUpCriticalTable();		
	     *	           populate_saHpiSensorThdUpMajorTable();		
	     *	           populate_saHpiSensorThdUpMinorTable();		
	     *	           populate_saHpiSensorThdPosHysteresisTable();		
	     *	           populate_saHpiSensorThdNegHysteresisTable();		
	     *	       populate_saHpiCurrentSensorStateTable();		
	     *	       populate_saHpiInventoyTable();		
	     *	       populate_saHpiWatchdogTable();		
	     *	       populate_saHpiAnnunciatorTable();		
	     *	       populate_saHpiAreaTable();		
	     *	           populate_saHpiFieldTable(); 
             *         populate_saHpiHotSwapTable();
             *             populate_saHpiAutoInsertTimeoutTable();             
  	     *         populate_saHpiAnnouncementTable();
	     */
            
	populate_saHpiEventTable(sessionid);
            /* populate_saHpiResourceEventTable();
	     * populate_saHpiDomainEventTable();
	     * populate_saHpiSensorEventTable();
	     * populate_saHpiOemEventTable();
	     * populate_saHpiHotSwapEventTable();
	     * populate_saHpiWatchdogEventTable();
	     * populate_saHpiSoftwareEventTable();
	     * populate_saHpiSensorEnableChangeEventTable();
	     * populate_saHpiUserEventTable();
	     */
        populate_saHpiEventLogInfo(sessionid);
        populate_saHpiEventLog (sessionid);
            /*
             * populate_saHpiResourceEventLogTable();
             * populate_saHpiSensorEventLogTable();
	     * populate_saHpiHotSwapEventLogTable();
	     * populate_saHpiWatchdogEventLogTable();
	     * populate_saHpiSoftwareEventLogTable();
	     * populate_saHpiOemEventLogTable();
	     * populate_saHpiUserEventLogTable();
	     * populate_saHpiSensorEnableChangeEventLogTable();
	     * populate_saHpiDomainEventLogTable();	     
             */

        /* Determine whether or not we're in threaded mode */
	env = getenv("OPENHPI_THREADED");
	if ((env == (char *)NULL) || (strcmp(env, "NO") == 0)) {
                DEBUGMSGTL ((AGENT, "Running in nonthreaded mode.  Configuring polling mechanism\n"));  
                run_threaded = SAHPI_FALSE;
		if (init_alarm() != AGENT_ERR_NOERROR) {
                    snmp_log (LOG_ERR, "Could not initialize polling mechanism. Exiting\n.");
                    rc = -1;
                    goto stop;
                }
	}	
	else {
                DEBUGMSGTL ((AGENT, "Running in threaded mode.  Spawing thread\n"));
		/* start event thread */
                set_run_threaded(TRUE);
                if (start_event_thread(&sessionid) != AGENT_ERR_NOERROR) {
                        snmp_log (LOG_ERR, "Could not start our internal loop . Exiting\n.");
                        rc = -1;
                        goto stop;
                }
	}	

        send_traps = AGENT_TRUE;
        /* If we're going to be a snmp master agent, initial the ports */

        if (!agentx_subagent)
                init_master_agent ();	/* open the port to listen on (defaults to udp:161) */
                
        if (do_fork == AGENT_TRUE) {
                if ((child = fork ()) < 0) {
                        snmp_log (LOG_ERR, "Could not fork!\n");
                        exit (-1);
                }
                if (child != 0)
                        exit (0);
        }

        /* In case we recevie a request to stop (kill -TERM or kill -INT) */
        keep_running = 1;
        signal (SIGTERM, stop_server);
        signal (SIGINT, stop_server);

                /* you're main loop here... */
        while (keep_running) {
                /* if you use select(), see snmp_select_info() in snmp_api(3) */
                /*     --- OR ---  */		
                rc = agent_check_and_process (1);
		
        }
stop:
        DEBUGMSGTL ((AGENT,
        "WARNING: closeSaHpiSession: hpiSubagent.c: nolong implemented!"));
        //closeSaHpiSession();
        /* at shutdown time */
        snmp_log (LOG_INFO, "Stopping %s\n", version);
        snmp_shutdown (AGENT);
  
  return rc;
}
Esempio n. 9
0
/*
 * This method does the real work for snmp_parse_args.  It takes an
 * extra argument, proxy, and uses this to decide how to handle the lack of
 * of a community string.
 */
int
snmp_parse_args(int argc,
                char **argv,
                netsnmp_session * session, const char *localOpts,
                void (*proc) (int, char *const *, int))
{
    static char	   *sensitive[4] = { NULL, NULL, NULL, NULL };
    int             arg, sp = 0, zero_sensitive = 1, testcase = 0;
    char           *cp;
    char           *Apsz = NULL;
    char           *Xpsz = NULL;
    char           *Cpsz = NULL;
    char            Opts[BUF_SIZE];
    int             logopt = 0;

    /*
     * initialize session to default values 
     */
    snmp_sess_init(session);
    strcpy(Opts, "Y:VhHm:M:O:I:P:D:dv:r:t:c:Z:e:E:n:u:l:x:X:a:A:p:T:-:3:s:S:L:");
    if (localOpts)
        strcat(Opts, localOpts);

    if (strcmp(argv[0], "snmpd-trapsess") == 0 ||
	strcmp(argv[0], "snmpd-proxy")    == 0) {
	/*  Don't worry about zeroing sensitive parameters as they are not
	    on the command line anyway (called from internal config-line
	    handler).  */
	zero_sensitive = 0;
    }

    /*
     * get the options 
     */
    DEBUGMSGTL(("snmp_parse_args", "starting: %d/%d\n", optind, argc));
    for (arg = 0; arg < argc; arg++) {
        DEBUGMSGTL(("snmp_parse_args", " arg %d = %s\n", arg, argv[arg]));
    }

    optind = 1;
    while ((arg = getopt(argc, argv, Opts)) != EOF) {
        DEBUGMSGTL(("snmp_parse_args", "handling (#%d): %c\n", optind, arg));
        switch (arg) {
        case '-':
            if (strcasecmp(optarg, "help") == 0) {
                return (-1);
            }
            if (strcasecmp(optarg, "version") == 0) {
                fprintf(stderr,"NET-SNMP version: %s\n",netsnmp_get_version());
                return (-2);
            }

            handle_long_opt(optarg);
            break;

        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n", netsnmp_get_version());
            return (-2);

        case 'h':
            return (-1);
            break;

        case 'H':
            init_snmp("snmpapp");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            return (-2);

        case 'Y':
            netsnmp_config_remember(optarg);
            break;

#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 'm':
            setenv("MIBS", optarg, 1);
            break;

        case 'M':
            netsnmp_get_mib_directory(); /* prepare the default directories */
            netsnmp_set_mib_directory(optarg);
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */

        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown output option passed to -O: %c.\n", 
			*cp);
                return (-1);
            }
            break;

        case 'I':
            cp = snmp_in_options(optarg, argc, argv);
            if (cp != NULL) {
                fprintf(stderr, "Unknown input option passed to -I: %c.\n",
			*cp);
                return (-1);
            }
            break;

#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 'P':
            cp = snmp_mib_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr,
                        "Unknown parsing option passed to -P: %c.\n", *cp);
                return (-1);
            }
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */

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

        case 'd':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
				   NETSNMP_DS_LIB_DUMP_PACKET, 1);
            break;

        case 'v':
            session->version = -1;
#ifndef NETSNMP_DISABLE_SNMPV1
            if (!strcmp(optarg, "1")) {
                session->version = SNMP_VERSION_1;
            }
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
            if (!strcasecmp(optarg, "2c")) {
                session->version = SNMP_VERSION_2c;
            }
#endif
            if (!strcasecmp(optarg, "3")) {
                session->version = SNMP_VERSION_3;
            }
            if (session->version == -1) {
                fprintf(stderr,
                        "Invalid version specified after -v flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'p':
            fprintf(stderr, "Warning: -p option is no longer used - ");
            fprintf(stderr, "specify the remote host as HOST:PORT\n");
            return (-1);
            break;

        case 'T':
            fprintf(stderr, "Warning: -T option is no longer used - ");
            fprintf(stderr, "specify the remote host as TRANSPORT:HOST\n");
            return (-1);
            break;

        case 't':
            session->timeout = (long)(atof(optarg) * 1000000L);
            if (session->timeout <= 0) {
                fprintf(stderr, "Invalid timeout in seconds after -t flag.\n");
                return (-1);
            }
            break;

        case 'r':
            session->retries = atoi(optarg);
            if (session->retries < 0 || !isdigit(optarg[0])) {
                fprintf(stderr, "Invalid number of retries after -r flag.\n");
                return (-1);
            }
            break;

        case 'c':
	    if (zero_sensitive) {
		if ((sensitive[sp] = strdup(optarg)) != NULL) {
		    Cpsz = sensitive[sp];
		    memset(optarg, '\0', strlen(optarg));
		    sp++;
		} else {
		    fprintf(stderr, "malloc failure processing -c flag.\n");
		    return -1;
		}
	    } else {
		Cpsz = optarg;
	    }
            break;

        case '3':
	    /*  TODO: This needs to zero things too.  */
            if (snmpv3_options(optarg, session, &Apsz, &Xpsz, argc, argv) < 0){
                return (-1);
            }
            break;

        case 'L':
            if (snmp_log_options(optarg, argc, argv) < 0) {
                return (-1);
            }
	    logopt = 1;
            break;

#define SNMPV3_CMD_OPTIONS
#ifdef  SNMPV3_CMD_OPTIONS
        case 'Z':
            errno = 0;
            session->engineBoots = strtoul(optarg, &cp, 10);
            if (errno || cp == optarg) {
                fprintf(stderr, "Need engine boots value after -Z flag.\n");
                return (-1);
            }
            if (*cp == ',') {
                char *endptr;
                cp++;
                session->engineTime = strtoul(cp, &endptr, 10);
                if (errno || cp == endptr) {
                    fprintf(stderr, "Need engine time after \"-Z engineBoot,\".\n");
                    return (-1);
                }
            }
            /*
             * Handle previous '-Z boot time' syntax 
             */
            else if (optind < argc) {
                session->engineTime = strtoul(argv[optind], &cp, 10);
                if (errno || cp == argv[optind]) {
                    fprintf(stderr, "Need engine time after \"-Z engineBoot\".\n");
                    return (-1);
                }
            } else {
                fprintf(stderr, "Need engine time after \"-Z engineBoot\".\n");
                return (-1);
            }
            break;

        case 'e':{
                size_t ebuf_len = 32, eout_len = 0;
                u_char *ebuf = (u_char *)malloc(ebuf_len);

                if (ebuf == NULL) {
                    fprintf(stderr, "malloc failure processing -e flag.\n");
                    return (-1);
                }
                if (!snmp_hex_to_binary
                    (&ebuf, &ebuf_len, &eout_len, 1, optarg)) {
                    fprintf(stderr, "Bad engine ID value after -e flag.\n");
                    free(ebuf);
                    return (-1);
                }
                if ((eout_len < 5) || (eout_len > 32)) {
                    fprintf(stderr, "Invalid engine ID value after -e flag.\n");
                    free(ebuf);
                    return (-1);
                }
                session->securityEngineID = ebuf;
                session->securityEngineIDLen = eout_len;
                break;
            }

        case 'E':{
                size_t ebuf_len = 32, eout_len = 0;
                u_char *ebuf = (u_char *)malloc(ebuf_len);

                if (ebuf == NULL) {
                    fprintf(stderr, "malloc failure processing -E flag.\n");
                    return (-1);
                }
                if (!snmp_hex_to_binary(&ebuf, &ebuf_len,
					&eout_len, 1, optarg)) {
                    fprintf(stderr, "Bad engine ID value after -E flag.\n");
                    free(ebuf);
                    return (-1);
                }
                if ((eout_len < 5) || (eout_len > 32)) {
                    fprintf(stderr, "Invalid engine ID value after -E flag.\n");
                    free(ebuf);
                    return (-1);
                }
                session->contextEngineID = ebuf;
                session->contextEngineIDLen = eout_len;
                break;
            }

        case 'n':
            session->contextName = optarg;
            session->contextNameLen = strlen(optarg);
            break;

        case 'u':
	    if (zero_sensitive) {
		if ((sensitive[sp] = strdup(optarg)) != NULL) {
		    session->securityName = sensitive[sp];
		    session->securityNameLen = strlen(sensitive[sp]);
		    memset(optarg, '\0', strlen(optarg));
		    sp++;
		} else {
		    fprintf(stderr, "malloc failure processing -u flag.\n");
		    return -1;
		}
	    } else {
		session->securityName = optarg;
		session->securityNameLen = strlen(optarg);
	    }
            break;

        case 'l':
            if (!strcasecmp(optarg, "noAuthNoPriv") || !strcmp(optarg, "1")
                || !strcasecmp(optarg, "noauth")
                || !strcasecmp(optarg, "nanp")) {
                session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
            } else if (!strcasecmp(optarg, "authNoPriv")
                       || !strcmp(optarg, "2")
                       || !strcasecmp(optarg, "auth")
                       || !strcasecmp(optarg, "anp")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
            } else if (!strcasecmp(optarg, "authPriv")
                       || !strcmp(optarg, "3")
                       || !strcasecmp(optarg, "priv")
                       || !strcasecmp(optarg, "ap")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
            } else {
                fprintf(stderr,
                        "Invalid security level specified after -l flag: %s\n",
                        optarg);
                return (-1);
            }

            break;

        case 'a':
#ifndef NETSNMP_DISABLE_MD5
            if (!strcasecmp(optarg, "MD5")) {
                session->securityAuthProto = usmHMACMD5AuthProtocol;
                session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
            } else
#endif
                if (!strcasecmp(optarg, "SHA")) {
                session->securityAuthProto = usmHMACSHA1AuthProtocol;
                session->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
            } else {
                fprintf(stderr,
                        "Invalid authentication protocol specified after -a flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'x':
            testcase = 0;
#ifndef NETSNMP_DISABLE_DES
            if (!strcasecmp(optarg, "DES")) {
                testcase = 1;
                session->securityPrivProto = usmDESPrivProtocol;
                session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
            }
#endif
#ifdef HAVE_AES
            if (!strcasecmp(optarg, "AES128") ||
                !strcasecmp(optarg, "AES")) {
                testcase = 1;
                session->securityPrivProto = usmAESPrivProtocol;
                session->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
            }
#endif
            if (testcase == 0) {
                fprintf(stderr,
                      "Invalid privacy protocol specified after -x flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'A':
	    if (zero_sensitive) {
		if ((sensitive[sp] = strdup(optarg)) != NULL) {
		    Apsz = sensitive[sp];
		    memset(optarg, '\0', strlen(optarg));
		    sp++;
		} else {
		    fprintf(stderr, "malloc failure processing -A flag.\n");
		    return -1;
		}
	    } else {
		Apsz = optarg;
	    }
            break;

        case 'X':
	    if (zero_sensitive) {
		if ((sensitive[sp] = strdup(optarg)) != NULL) {
		    Xpsz = sensitive[sp];
		    memset(optarg, '\0', strlen(optarg));
		    sp++;
		} else {
		    fprintf(stderr, "malloc failure processing -X flag.\n");
		    return -1;
		}
	    } else {
		Xpsz = optarg;
	    }
            break;
#endif                          /* SNMPV3_CMD_OPTIONS */

        case '?':
            return (-1);
            break;

        default:
            proc(argc, argv, arg);
            break;
        }
    }
    DEBUGMSGTL(("snmp_parse_args", "finished: %d/%d\n", optind, argc));
    
    if (!logopt)
	snmp_enable_stderrlog();

    /*
     * read in MIB database and initialize the snmp library
     */
    init_snmp("snmpapp");

    /*
     * session default version 
     */
    if (session->version == SNMP_DEFAULT_VERSION) {
        /*
         * run time default version 
         */
        session->version = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, 
					      NETSNMP_DS_LIB_SNMPVERSION);

        /*
         * compile time default version 
         */
        if (!session->version) {
            switch (NETSNMP_DEFAULT_SNMP_VERSION) {
#ifndef NETSNMP_DISABLE_SNMPV1
            case 1:
                session->version = SNMP_VERSION_1;
                break;
#endif

#ifndef NETSNMP_DISABLE_SNMPV2C
            case 2:
                session->version = SNMP_VERSION_2c;
                break;
#endif

            case 3:
                session->version = SNMP_VERSION_3;
                break;

            default:
                snmp_log(LOG_ERR, "Can't determine a valid SNMP version for the session\n");
                return(-2);
            }
        } else {
#ifndef NETSNMP_DISABLE_SNMPV1
            if (session->version == NETSNMP_DS_SNMP_VERSION_1)  /* bogus value.  version 1 actually = 0 */
                session->version = SNMP_VERSION_1;
#endif
        }
    }

    /*
     * make master key from pass phrases 
     */
    if (Apsz) {
        session->securityAuthKeyLen = USM_AUTH_KU_LEN;
        if (session->securityAuthProto == NULL) {
            /*
             * get .conf set default 
             */
            const oid      *def =
                get_default_authtype(&session->securityAuthProtoLen);
            session->securityAuthProto =
                snmp_duplicate_objid(def, session->securityAuthProtoLen);
        }
        if (session->securityAuthProto == NULL) {
#ifndef NETSNMP_DISABLE_MD5
            /*
             * assume MD5
             */
            session->securityAuthProto =
                snmp_duplicate_objid(usmHMACMD5AuthProtocol,
                                     USM_AUTH_PROTO_MD5_LEN);
            session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
#else
            session->securityAuthProto =
                snmp_duplicate_objid(usmHMACSHA1AuthProtocol,
                                     USM_AUTH_PROTO_SHA_LEN);
            session->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
#endif
        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Apsz, strlen(Apsz),
                        session->securityAuthKey,
                        &session->securityAuthKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied authentication pass phrase. \n");
            return (-2);
        }
    }
    if (Xpsz) {
        session->securityPrivKeyLen = USM_PRIV_KU_LEN;
        if (session->securityPrivProto == NULL) {
            /*
             * get .conf set default 
             */
            const oid      *def =
                get_default_privtype(&session->securityPrivProtoLen);
            session->securityPrivProto =
                snmp_duplicate_objid(def, session->securityPrivProtoLen);
        }
        if (session->securityPrivProto == NULL) {
            /*
             * assume DES 
             */
#ifndef NETSNMP_DISABLE_DES
            session->securityPrivProto =
                snmp_duplicate_objid(usmDESPrivProtocol,
                                     USM_PRIV_PROTO_DES_LEN);
            session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
#else
            session->securityPrivProto =
                snmp_duplicate_objid(usmAESPrivProtocol,
                                     USM_PRIV_PROTO_AES_LEN);
            session->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
#endif

        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Xpsz, strlen(Xpsz),
                        session->securityPrivKey,
                        &session->securityPrivKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied privacy pass phrase. \n");
            return (-2);
        }
    }
    /*
     * get the hostname 
     */
    if (optind == argc) {
        fprintf(stderr, "No hostname specified.\n");
        return (-1);
    }
    session->peername = argv[optind++]; /* hostname */

#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
    /*
     * If v1 or v2c, check community has been set, either by a -c option above,
     * or via a default token somewhere.  
     * If neither, it will be taken from the incoming request PDU.
     */

#if defined(NETSNMP_DISABLE_SNMPV1)
    if (session->version == SNMP_VERSION_2c)
#else 
#if defined(NETSNMP_DISABLE_SNMPV2C)
    if (session->version == SNMP_VERSION_1)
#else
    if (session->version == SNMP_VERSION_1 ||
	session->version == SNMP_VERSION_2c)
#endif
#endif
    {
        if (Cpsz == NULL) {
            Cpsz = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, 
					 NETSNMP_DS_LIB_COMMUNITY);
	    if (Cpsz == NULL) {
                if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
                                           NETSNMP_DS_LIB_IGNORE_NO_COMMUNITY)){
                    DEBUGMSGTL(("snmp_parse_args",
                                "ignoring that the community string is not present\n"));
                    session->community = NULL;
                    session->community_len = 0;
                } else {
                    fprintf(stderr, "No community name specified.\n");
                    return (-1);
                }
	    }
	} else {
            session->community = (unsigned char *)Cpsz;
            session->community_len = strlen(Cpsz);
        }
    }
#endif /* support for community based SNMP */

    return optind;
}
Esempio n. 10
0
int
main(int argc, char **argv)
{
	int agentx_subagent = 1;
	//Change to make an SNMP master agent

	/* print log errors to stderr */
		snmp_enable_stderrlog();

	/* we're an agentx subagent? */
	if (agentx_subagent) {
		/*
		 * This is an agentx client. Specify 0 for
		 * NETSNMP_DS_AGENT_ROLE if the agent is master agent.
		 * Specify 1 for NETSNMP_DS_AGENT_ROLE, if the agent is a
		 * client.
		 */
		netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
				NETSNMP_DS_AGENT_ROLE, 1);
		DEBUGMSGTL(("demo_module_8",
				"NETSNMP_DS_APPLICATION_ID = %s:\n",
				NETSNMP_DS_APPLICATION_ID));
		DEBUGMSGTL(("demo_module_8", "NETSNMP_DS_AGENT_ROLE = %s:\n",
				NETSNMP_DS_AGENT_ROLE));
	}
	/*
	 * Initializes the embedded agent.  Call this function before the
	 * init_snmp() call. The string name specifies which .conf file to
	 * read when init_snmp() is called later.
	 */
	init_agent("demo_module_8");
	DEBUGMSGTL(("demo_module_8", "CALLING init_agent\n"));

	/* initialize mib code here */

	/* mib code: init_me1LoadGroup from me1LoadGroup.c */
	init_me1LoadGroup();

	/*
	 * Initializes the SNMP library, which causes the agent to read your
	 * application's configuration files. The agent first tries to read
	 * the configuration files named by the string passed as an argument.
	 * You might use this to configure  access  control, for example.
	 */
	init_snmp("demo_module_8");

	/*
	 * Initializes the master agent and causes it to listen for SNMP
	 * requests on its default UDP port of 161. Open the port to listen
	 * (defaults to udp: 161)
	 */
	if (!agentx_subagent)
		init_master_agent();

	/* In case we get a request to stop (kill -TERM or kill -INT) */
	keep_running = 1;
	signal(SIGTERM, stop_server);
	signal(SIGINT, stop_server);

	/*
	 * The main loop. If you use select(), see snmp_select_info() in
	 * snmp_api(3). This checks for packets arriving on the SNMP port and
	 * processes them if some are found. If block is non zero, the
	 * function call blocks until a packet arrives or an alarm must be
	 * run (see snmp_alarm(3)).
	 *
	 * The return value from this function is a positive integer if packets
	 * were processed, zero if an alarm occurre, and -1 if an error
	 * occured.
	 */

	while (keep_running) {
		/* OR */
		agent_check_and_process(1);	/* 0 == don't block */
	}
	/*
	 * Shuts down the agent, saving any needed persistent storage.
	 */
	snmp_shutdown("demo_module_8");
}
Esempio n. 11
0
int
main (int argc, char **argv) {
    int agentx_subagent=1; /* change this if you want to be a SNMP master agent */
    int background = 0; /* change this if you want to run in the background */
    int syslog = 0; /* change this if you want to use syslog */

    /* print log errors to syslog or stderr */
    if (syslog)
        snmp_enable_calllog();
    else
        snmp_enable_stderrlog();

    /* we're an agentx subagent? */
    if (agentx_subagent) {
        /* make us a agentx client. */
        netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 1);
    }

    /* run in background, if requested */
    if (background && netsnmp_daemonize(1, !syslog))
        exit(1);

    /* initialize tcpip, if necessary */
    SOCK_STARTUP;

    /* initialize the agent library */
    init_agent("example-demon");

    /* initialize mib code here */

    /* mib code: init_example from example.c */
    init_example();

    /* initialize vacm/usm access control  */
    if (!agentx_subagent) {
        init_vacm_vars();
        init_usmUser();
    }

    /* example-demon will be used to read example-demon.conf files. */
    init_snmp("example-demon");

    /* If we're going to be a snmp master agent, initial the ports */
    if (!agentx_subagent)
        init_master_agent();  /* open the port to listen on (defaults to udp:161) */

    /* In case we recevie a request to stop (kill -TERM or kill -INT) */
    keep_running = 1;
    signal(SIGTERM, stop_server);
    signal(SIGINT, stop_server);

    snmp_log(LOG_INFO,"example-demon is up and running.\n");

    /* your main loop here... */
    while(keep_running) {
        /* if you use select(), see snmp_select_info() in snmp_api(3) */
        /*     --- OR ---  */
        agent_check_and_process(1); /* 0 == don't block */
    }

    /* at shutdown time */
    snmp_shutdown("example-demon");
    SOCK_CLEANUP;

    return 0;
}
Esempio n. 12
0
main(int argc, char *argv[])
#endif
{
    char            options[128] = "ac:CdD::efF:hHl:L:m:M:no:PqsS:tvO:-:";
    netsnmp_session *sess_list = NULL, *ss = NULL;
    netsnmp_transport *transport = NULL;
    int             arg, i = 0;
    int             count, numfds, block;
    fd_set          fdset;
    struct timeval  timeout, *tvp;
    char           *cp, *listen_ports = NULL;
    int             agentx_subagent = 1, depmsg = 0;

    /*
     * register our configuration handlers now so -H properly displays them 
     */
    snmptrapd_register_configs( );
    init_usm_conf( "snmptrapd" );
    register_config_handler("snmptrapd", "snmptrapdaddr",
                            parse_trapd_address, free_trapd_address, "string");

    register_config_handler("snmptrapd", "doNotLogTraps",
                            parse_config_doNotLogTraps, NULL, "(1|yes|true|0|no|false)");
#if HAVE_GETPID
    register_config_handler("snmptrapd", "pidFile",
                            parse_config_pidFile, NULL, "string");
#endif
    
    register_config_handler("snmptrapd", "logOption",
                            parse_config_logOption, NULL, "string");

    register_config_handler("snmptrapd", "doNotFork",
                            parse_config_doNotFork, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "printEventNumbers",
                            parse_config_printEventNumbers, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "ignoreAuthFailure",
                            parse_config_ignoreAuthFailure, NULL, "(1|yes|true|0|no|false)");

    register_config_handler("snmptrapd", "outputOption",
                            parse_config_outputOption, NULL, "string");
    
#ifdef WIN32
    setvbuf(stdout, NULL, _IONBF, BUFSIZ);
#else
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
#endif

    /*
     * Add some options if they are available.  
     */
#if HAVE_GETPID
    strcat(options, "p:u:");
#endif

    snmp_log_syslogname(app_name);

    /*
     * Now process options normally.  
     */

    while ((arg = getopt(argc, argv, options)) != EOF) {
        switch (arg) {
        case '-':
            if (strcasecmp(optarg, "help") == 0) {
                usage();
                exit(0);
            }
            if (strcasecmp(optarg, "version") == 0) {
                version();
                exit(0);
            }

            handle_long_opt(optarg);
            break;

        case 'a':
            dropauth = 1;
            break;

        case 'c':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
				      NETSNMP_DS_LIB_OPTIONALCONFIG, optarg);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'C':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, 
				   NETSNMP_DS_LIB_DONT_READ_CONFIGS, 1);
            break;

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

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

        case 'e':
            Event++;
            break;

        case 'f':
            dofork = 0;
            break;

        case 'F':
            if (optarg != NULL) {
                trap1_fmt_str_remember = optarg;
            } else {
                usage();
                exit(1);
            }
            break;

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

        case 'H':
            init_notification_log();
            init_snmp("snmptrapd");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            exit(0);

	case 'S':
            fprintf(stderr,
                    "Warning: -S option is deprecated; use -Ls <facility> instead\n");
            depmsg = 1;
            if (optarg != NULL) {
                switch (*optarg) {
                case 'd':
                case 'D':
                    Facility = LOG_DAEMON;
                    break;
                case 'i':
                case 'I':
                    Facility = LOG_INFO;
                    break;
                case '0':
                    Facility = LOG_LOCAL0;
                    break;
                case '1':
                    Facility = LOG_LOCAL1;
                    break;
                case '2':
                    Facility = LOG_LOCAL2;
                    break;
                case '3':
                    Facility = LOG_LOCAL3;
                    break;
                case '4':
                    Facility = LOG_LOCAL4;
                    break;
                case '5':
                    Facility = LOG_LOCAL5;
                    break;
                case '6':
                    Facility = LOG_LOCAL6;
                    break;
                case '7':
                    Facility = LOG_LOCAL7;
                    break;
                default:
                    fprintf(stderr, "invalid syslog facility: -S%c\n",*optarg);
                    usage();
                    exit(1);
                }
            } else {
                fprintf(stderr, "no syslog facility specified\n");
                usage();
                exit(1);
            }
            break;

        case 'm':
            if (optarg != NULL) {
                setenv("MIBS", optarg, 1);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'M':
            if (optarg != NULL) {
                setenv("MIBDIRS", optarg, 1);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'n':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_APP_NUMERIC_IP, 1);
            break;

        case 'o':
            fprintf(stderr,
                    "Warning: -o option is deprecated; use -Lf <file> instead\n");
            Print++;
            if (optarg != NULL) {
                logfile = optarg;
                snmp_enable_filelog(optarg, 0);
            } else {
                usage();
                exit(1);
            }
            break;

        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown output option passed to -O: %c\n",
			*cp);
                usage();
                exit(1);
            }
            break;

        case 'L':
	    if  (snmp_log_options( optarg, argc, argv ) < 0 ) {
                usage();
                exit(1);
            }
            Log++;
            break;

        case 'P':
            fprintf(stderr,
                    "Warning: -P option is deprecated; use -f -Le instead\n");
            dofork = 0;
            snmp_enable_stderrlog();
            Print++;
            break;

        case 's':
            fprintf(stderr,
                    "Warning: -s option is deprecated; use -Lsd instead\n");
            depmsg = 1;
            Syslog++;
            break;

        case 't':
            SyslogTrap++;
            break;


#if HAVE_GETPID
        case 'u':
            fprintf(stderr,
                    "Warning: -u option is deprecated; use -p instead\n");
        case 'p':
            if (optarg != NULL) {
                parse_config_pidFile(NULL, optarg);
            } else {
                usage();
                exit(1);
            }
            break;
#endif

        case 'v':
            version();
            exit(0);
            break;

        default:
            fprintf(stderr, "invalid option: -%c\n", arg);
            usage();
            exit(1);
            break;
        }
    }

    if (optind < argc) {
        /*
         * There are optional transport addresses on the command line.  
         */
        for (i = optind; i < argc; i++) {
            char *astring;
            if (listen_ports != NULL) {
                astring = malloc(strlen(listen_ports) + 2 + strlen(argv[i]));
                if (astring == NULL) {
                    fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                    exit(1);
                }
                sprintf(astring, "%s,%s", listen_ports, argv[i]);
                free(listen_ports);
                listen_ports = astring;
            } else {
                listen_ports = strdup(argv[i]);
                if (listen_ports == NULL) {
                    fprintf(stderr, "malloc failure processing argv[%d]\n", i);
                    exit(1);
                }
            }
        }
    }

    /*
     * I'm being lazy here, and not checking the
     * return value from these registration calls.
     * Don't try this at home, children!
     */
    if (!Log && !Print) {
        Syslog = 1;
        netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER, syslog_handler);
    } else {
        netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER, print_handler);
    }
    netsnmp_add_global_traphandler(NETSNMPTRAPD_POST_HANDLER, notification_handler);

    if (Event) {
        netsnmp_add_traphandler(event_handler, risingAlarm,
                                    OID_LENGTH(risingAlarm));
        netsnmp_add_traphandler(event_handler, fallingAlarm,
                                    OID_LENGTH(fallingAlarm));
        netsnmp_add_traphandler(event_handler, unavailableAlarm,
                                    OID_LENGTH(unavailableAlarm));
	/* XXX - might be worth setting some "magic data"
	 * in the traphandler structure that 'event_handler'
	 * can use to avoid checking the trap OID values.
	 */
    }

#ifdef USING_AGENTX_SUBAGENT_MODULE
    /*
     * we're an agentx subagent? 
     */
    if (agentx_subagent) {
        /*
         * make us a agentx client. 
         */
        netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
			       NETSNMP_DS_AGENT_ROLE, 1);
    }
#endif

    /*
     * don't fail if we can't do agentx (ie, socket not there, or not root) 
     */
    netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
			      NETSNMP_DS_AGENT_NO_ROOT_ACCESS);
    /*
     * ignore any warning messages.
     */
    netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
			      NETSNMP_DS_AGENT_NO_CONNECTION_WARNINGS);

    /*
     * initialize the agent library 
     */
    init_agent("snmptrapd");

    /*
     * initialize local modules 
     */
    if (agentx_subagent) {
        extern void init_register_usmUser_context(const char *);
#ifdef USING_AGENTX_SUBAGENT_MODULE
	void  init_subagent(void);
        init_subagent();
#endif
        /* register the notification log table */
        init_notification_log();

        /* register ourselves as having a USM user database */
        init_register_usmUser_context("snmptrapd");
    }

#ifdef NETSNMP_EMBEDDED_PERL
    init_perl();
    {
        /* set the default path to load */
        char            init_file[SNMP_MAXBUF];
        snprintf(init_file, sizeof(init_file) - 1,
                 "%s/%s", SNMPSHAREPATH, "snmp_perl_trapd.pl");
        netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
                              NETSNMP_DS_AGENT_PERL_INIT_FILE,
                              init_file);
    }
#endif

    /*
     * Initialize the world.
     */
    init_snmp("snmptrapd");

    if (trap1_fmt_str_remember) {
        free_trap1_fmt();
        free_trap2_fmt();
        print_format1 = strdup(trap1_fmt_str_remember);
        print_format2 = strdup(trap1_fmt_str_remember);
    }

    if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_QUIT_IMMEDIATELY)) {
        /*
         * just starting up to process specific configuration and then
         * shutting down immediately. 
         */
        running = 0;
    }
#ifndef WIN32
    /*
     * fork the process to the background if we are not printing to stderr 
     */
    if (dofork && running) {
        int             fd;

        switch (fork()) {
        case -1:
            fprintf(stderr, "bad fork - %s\n", strerror(errno));
            _exit(1);

        case 0:
            /*
             * become process group leader 
             */
            if (setsid() == -1) {
                fprintf(stderr, "bad setsid - %s\n", strerror(errno));
                _exit(1);
            }

            /*
             * if we are forked, we don't want to print out to stdout or stderr 
             */
            fd = open("/dev/null", O_RDWR);
            dup2(fd, STDIN_FILENO);
            dup2(fd, STDOUT_FILENO);
            dup2(fd, STDERR_FILENO);
            close(fd);
            break;

        default:
            _exit(0);
        }
    }
#endif                          /* WIN32 */
#if HAVE_GETPID
    if (pid_file != NULL) {
        if ((PID = fopen(pid_file, "w")) == NULL) {
            snmp_log_perror("fopen");
            exit(1);
        }
        fprintf(PID, "%d\n", (int) getpid());
        fclose(PID);
        free_config_pidFile();
    }
#endif

    if (Syslog) {
        snmp_enable_syslog_ident(app_name, Facility);
        snmp_log(LOG_INFO, "Starting snmptrapd %s\n", netsnmp_get_version());
	if (depmsg) {
	    snmp_log(LOG_WARNING, "-s and -S options are deprecated; use -Ls <facility> instead\n");
	}
    }
    if (Print || Log) {
        struct tm      *tm;
        time_t          timer;
        time(&timer);
        tm = localtime(&timer);
        snmp_log(LOG_INFO,
                "%.4d-%.2d-%.2d %.2d:%.2d:%.2d NET-SNMP version %s Started.\n",
                 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
                 tm->tm_hour, tm->tm_min, tm->tm_sec,
                 netsnmp_get_version());
    }

    SOCK_STARTUP;

    if (listen_ports)
        cp = listen_ports;
    else
        cp = default_port;

    while (cp != NULL) {
        char *sep = strchr(cp, ',');
        char  listen_name[128];
        char *cp2 = strchr(cp, ':');

        if (sep != NULL) {
            *sep = 0;
        }

           /*
            * Make sure this defaults to listening on port 162
            */
        if (!cp2) {
            snprintf(listen_name, sizeof(listen_name), "%s:162", cp);
            cp2 = listen_name;
        } else {
            cp2 = cp;
        }
        transport = netsnmp_tdomain_transport(cp2, 1, "udp");
        if (transport == NULL) {
            snmp_log(LOG_ERR, "couldn't open %s -- errno %d (\"%s\")\n",
                     cp2, errno, strerror(errno));
            snmptrapd_close_sessions(sess_list);
            SOCK_CLEANUP;
            exit(1);
        } else {
            ss = snmptrapd_add_session(transport);
            if (ss == NULL) {
                /*
                 * Shouldn't happen?  We have already opened the transport
                 * successfully so what could have gone wrong?  
                 */
                snmptrapd_close_sessions(sess_list);
                netsnmp_transport_free(transport);
                if (Syslog) {
                    snmp_log(LOG_ERR, "couldn't open snmp - %m");
                }
                SOCK_CLEANUP;
                exit(1);
            } else {
                ss->next = sess_list;
                sess_list = ss;
            }
        }

        /*
         * Process next listen address, if there is one.  
         */

        if (sep != NULL) {
            *sep = ',';
            cp = sep + 1;
        } else {
            cp = NULL;
        }
    }

    signal(SIGTERM, term_handler);
#ifdef SIGHUP
    signal(SIGHUP, hup_handler);
#endif
    signal(SIGINT, term_handler);

#ifdef WIN32SERVICE
    trapd_status = SNMPTRAPD_RUNNING;
#endif
    while (running) {
        if (reconfig) {
            if (Print || Log) {
                struct tm      *tm;
                time_t          timer;
                time(&timer);
                tm = localtime(&timer);

                /*
                 * If we are logging to a file, receipt of SIGHUP also
                 * indicates the the log file should be closed and
                 * re-opened.  This is useful for users that want to
                 * rotate logs in a more predictable manner.
                 */
                if (logfile)
                    snmp_enable_filelog(logfile, 1);

                snmp_log(LOG_INFO,
                         "%.4d-%.2d-%.2d %.2d:%.2d:%.2d NET-SNMP version %s Reconfigured.\n",
                         tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
                         tm->tm_hour, tm->tm_min, tm->tm_sec,
                         netsnmp_get_version());
            }
            if (Syslog)
                snmp_log(LOG_INFO, "Snmptrapd reconfiguring");
            trapd_update_config();
            if (trap1_fmt_str_remember) {
                free_trap1_fmt();
                print_format1 = strdup(trap1_fmt_str_remember);
            }
            reconfig = 0;
        }
        numfds = 0;
        FD_ZERO(&fdset);
        block = 0;
        tvp = &timeout;
        timerclear(tvp);
        tvp->tv_sec = 5;
        snmp_select_info(&numfds, &fdset, tvp, &block);
        if (block == 1)
            tvp = NULL;         /* block without timeout */
        count = select(numfds, &fdset, 0, 0, tvp);
        gettimeofday(&Now, 0);
        if (count > 0) {
            snmp_read(&fdset);
        } else
            switch (count) {
            case 0:
                snmp_timeout();
                break;
            case -1:
                if (errno == EINTR)
                    continue;
                snmp_log_perror("select");
                running = 0;
                break;
            default:
                fprintf(stderr, "select returned %d\n", count);
                running = 0;
            }
	run_alarms();
    }

    if (Print || Log) {
        struct tm      *tm;
        time_t          timer;
        time(&timer);
        tm = localtime(&timer);
        snmp_log(LOG_INFO,
                "%.4d-%.2d-%.2d %.2d:%.2d:%.2d NET-SNMP version %s Stopped.\n",
                 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
                 tm->tm_min, tm->tm_sec, netsnmp_get_version());
    }
    if (Syslog) {
        snmp_log(LOG_INFO, "Stopping snmptrapd");
    }

    snmptrapd_close_sessions(sess_list);
    snmp_shutdown("snmptrapd");
#ifdef WIN32SERVICE
    trapd_status = SNMPTRAPD_STOPPED;
#endif
    snmp_disable_log();
    SOCK_CLEANUP;
    return 0;
}
Esempio n. 13
0
int main(int argc, char **argv) {
    int c;
    struct snmp_session init_ses;
    char finame[1024];

    opterr=0;
    while ((c=getopt(argc, argv, "xdvi:k:u:c:")) != -1)
        switch(c) {
            case 'v':
                version();
            case 'x':
                extended=1;
                break;
            case 'd':
                debug=1;
                break;
            case 'c':
                if(isdigit((int)optarg[0]))
                    count=atoi(optarg);
                else
                    usage();
                break;
            case 'i':
                if(isdigit((int)optarg[0]))
                    interval=atoi(optarg);
                else
                    usage();
                break;
            case 'k':
                if(isdigit((int)optarg[0]))
                    S_KB=atoi(optarg);
                else
                    usage();
                break;
            case 'u':
                if(strlen(optarg)==2) {
                    S_Unit[0]=optarg[0];
                    S_Unit[1]=optarg[1];
                }
                else if(strlen(optarg)==1) {
                    S_Unit[0]='n';
                    S_Unit[1]=optarg[0];
                }
                else
                    usage();
                break;
            case '?':
            default:
                usage();
        }

    if(S_KB != 1024 && S_KB !=1000) 
        usage();

    if(interval<1) 
        usage();

    if(count<1)
        usage();

    if((argc-optind)!=3)
        usage();

    if(strcmp(netsnmp_get_version(), PACKAGE_VERSION)!=0) {
        fprintf(stderr,
            "ERROR: Net-SNMP version mismatch!\n"
            "Compiled with headers: %s\n"
            "Executed with library: %s\n",
            PACKAGE_VERSION, netsnmp_get_version());
        exit(1);
    }

    S_MB=S_KB*S_KB;
    S_GB=S_KB*S_KB*S_KB;

    gargv=argv;

    SOCK_STARTUP;
    init_snmp("ttg");
    snmp_sess_init(&init_ses);
    if(extended)
        init_ses.version=SNMP_VERSION_2c;
    else
        init_ses.version=SNMP_VERSION_1;
    init_ses.peername=argv[optind];
    init_ses.community=(unsigned char*)argv[optind+1];
    init_ses.community_len=strlen((char *)argv[optind+1]);
    snmp_enable_stderrlog(); 

    ses=snmp_open(&init_ses);
    if(!ses) {
        snmp_perror("error");
        exit(1);
    }

    if(strcasecmp(argv[optind+2], "list")==0 || strcasecmp(argv[optind+2], "ls")==0) 
        lsif(NULL);
    else if(isdigit((int)argv[optind+2][0]))
        thr(atoi(argv[optind+2]));
    else if(strlen(argv[optind+2])>=2) {

        if(argv[optind+2][0]=='@') 
            snprintf(finame, sizeof(finame), "%s", argv[optind+2]+1);
        else if(argv[optind+2][0]=='s' && argv[optind+2][1]=='e') 
            snprintf(finame, sizeof(finame), "Serial%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='e' && argv[optind+2][1]=='t') 
            snprintf(finame, sizeof(finame), "Ethernet%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='f' && argv[optind+2][1]=='a') 
            snprintf(finame, sizeof(finame), "FastEthernet%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='g' && argv[optind+2][1]=='i') 
            snprintf(finame, sizeof(finame), "GigabitEthernet%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='p' && argv[optind+2][1]=='i') 
            snprintf(finame, sizeof(finame), "Cisco PIX Security Appliance 'inside' interface");
        else if(argv[optind+2][0]=='p' && argv[optind+2][1]=='o') 
            snprintf(finame, sizeof(finame), "Cisco PIX Security Appliance 'outside' interface");
        else if(argv[optind+2][0]=='a' && argv[optind+2][1]=='i') 
            snprintf(finame, sizeof(finame), "Adaptive Security Appliance 'inside' interface");
        else if(argv[optind+2][0]=='a' && argv[optind+2][1]=='o') 
            snprintf(finame, sizeof(finame), "Adaptive Security Appliance 'outside' interface");
        else if(argv[optind+2][0]=='v' && argv[optind+2][1]=='l') 
            snprintf(finame, sizeof(finame), "Vlan%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='p' && argv[optind+2][1]=='c') 
            snprintf(finame, sizeof(finame), "Port-channel%s", argv[optind+2]+2);
        else if(argv[optind+2][0]=='t' && argv[optind+2][1]=='u') 
            snprintf(finame, sizeof(finame), "Tunnel%s", argv[optind+2]+2);
        else
            thr(lsif(argv[optind+2]));

        thr(lsif(finame));
    }
    else
        usage();

    snmp_close(ses);
    SOCK_CLEANUP;

    return 0;
}
Esempio n. 14
0
int
main(int argc, char *argv[])
{
    int             arg;
    char           *current_name = NULL, *cp = NULL;
    oid             name[MAX_OID_LEN];
    size_t          name_length;
    int             description = 0;
    int             print = 0;
    int             find_all = 0;
    int             width = 1000000;

    /*
     * usage: snmptranslate name
     */
    while ((arg = getopt(argc, argv, "Vhm:M:w:D:P:T:O:I:L:")) != EOF) {
        switch (arg) {
        case 'h':
            usage();
            exit(1);

        case 'm':
            setenv("MIBS", optarg, 1);
            break;
        case 'M':
            setenv("MIBDIRS", optarg, 1);
            break;
        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;
        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n",
                    netsnmp_get_version());
            exit(0);
            break;
        case 'w':
	    width = atoi(optarg);
	    if (width <= 0) {
		fprintf(stderr, "Invalid width specification: %s\n", optarg);
		exit (1);
	    }
	    break;
#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 'P':
            cp = snmp_mib_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown parser option to -P: %c.\n", *cp);
                usage();
                exit(1);
            }
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown OID option to -O: %c.\n", *cp);
                usage();
                exit(1);
            }
            break;
        case 'I':
            cp = snmp_in_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown OID option to -I: %c.\n", *cp);
                usage();
                exit(1);
            }
            break;
        case 'T':
            for (cp = optarg; *cp; cp++) {
                switch (*cp) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
                case 'l':
                    print = 3;
                    print_oid_report_enable_labeledoid();
                    break;
                case 'o':
                    print = 3;
                    print_oid_report_enable_oid();
                    break;
                case 's':
                    print = 3;
                    print_oid_report_enable_symbolic();
                    break;
                case 't':
                    print = 3;
                    print_oid_report_enable_suffix();
                    break;
                case 'z':
                    print = 3;
                    print_oid_report_enable_mibchildoid();
                    break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
                case 'd':
                    description = 1;
                    snmp_set_save_descriptions(1);
                    break;
                case 'B':
                    find_all = 1;
                    break;
                case 'p':
                    print = 1;
                    break;
                case 'a':
                    print = 2;
                    break;
                default:
                    fprintf(stderr, "Invalid -T<lostpad> character: %c\n",
                            *cp);
                    usage();
                    exit(1);
                    break;
                }
            }
            break;
        case 'L':
            if (snmp_log_options(optarg, argc, argv) < 0) {
                return (-1);
            }
            break;
        default:
            fprintf(stderr, "invalid option: -%c\n", arg);
            usage();
            exit(1);
            break;
        }
    }

    snmp_enable_stderrlog();
    init_snmp("snmpapp");
    if (optind < argc)
        current_name = argv[optind];

    if (current_name == NULL) {
        switch (print) {
        default:
            usage();
            exit(1);
#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 1:
            print_mib_tree(stdout, get_tree_head(), width);
            break;
        case 2:
            print_ascii_dump(stdout);
            break;
        case 3:
            print_oid_report(stdout);
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
        }
        exit(0);
    }

    do {
        name_length = MAX_OID_LEN;
        if (snmp_get_random_access()) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
            if (!get_node(current_name, name, &name_length)) {
#endif /* NETSNMP_DISABLE_MIB_LOADING */
                fprintf(stderr, "Unknown object identifier: %s\n",
                        current_name);
                exit(2);
#ifndef NETSNMP_DISABLE_MIB_LOADING
            }
#endif /* NETSNMP_DISABLE_MIB_LOADING */
        } else if (find_all) {
            if (0 == show_all_matched_objects(stdout, current_name,
                                              name, &name_length,
                                              description, width)) {
                fprintf(stderr,
                        "Unable to find a matching object identifier for \"%s\"\n",
                        current_name);
                exit(1);
            }
            exit(0);
        } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, 
					  NETSNMP_DS_LIB_REGEX_ACCESS)) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
            if (0 == get_wild_node(current_name, name, &name_length)) {
#endif /* NETSNMP_DISABLE_MIB_LOADING */
                fprintf(stderr,
                        "Unable to find a matching object identifier for \"%s\"\n",
                        current_name);
                exit(1);
#ifndef NETSNMP_DISABLE_MIB_LOADING
            }
#endif /* NETSNMP_DISABLE_MIB_LOADING */
        } else {
            if (!read_objid(current_name, name, &name_length)) {
                snmp_perror(current_name);
                exit(2);
            }
        }


        if (print == 1) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
            struct tree    *tp;
            tp = get_tree(name, name_length, get_tree_head());
            if (tp == NULL) {
#endif /* NETSNMP_DISABLE_MIB_LOADING */
                snmp_log(LOG_ERR,
                        "Unable to find a matching object identifier for \"%s\"\n",
                        current_name);
                exit(1);
#ifndef NETSNMP_DISABLE_MIB_LOADING
            }
            print_mib_tree(stdout, tp, width);
#endif /* NETSNMP_DISABLE_MIB_LOADING */
        } else {
            print_objid(name, name_length);
            if (description) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
                print_description(name, name_length, width);
#endif /* NETSNMP_DISABLE_MIB_LOADING */
            }
        }
        current_name = argv[++optind];
        if (current_name != NULL)
            printf("\n");
    } while (optind < argc);

    return (0);
}
Esempio n. 15
0
/* Main rated */
int main(int argc, char *argv[]) {
    crew_t crew;
    pthread_t sig_thread;
    sigset_t signal_set;
    struct timeval begin_time, end_time;
    unsigned long sleep_time;
    unsigned long poll_time;
    unsigned long long polls;
    unsigned long long last_poll;
    double rate;
    char *conf_file = NULL;
    char *table;
    char errstr[BUFSIZE];
    int ch, i, freed;
    struct timespec ts;

    dfp = stderr;

    /* Check argument count */
    if (argc < 3)
	usage(argv[0]);

    /* Set default environment */
    config_defaults(set);

    /* Parse the command-line. */
    while ((ch = getopt(argc, argv, "c:p:dhmDt:vz")) != EOF)
	switch ((char) ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	case 'd':
	    set->dbon = FALSE;
	    break;
	case 'D':
	    set->daemon = FALSE;
	    break;
	case 'h':
	    usage(argv[0]);
	    break;
	case 'm':
	    set->multiple++;
	    break;
	case 'p':
	    pid_file = optarg;
	    break;
	case 't':
	    target_file = optarg;
	    break;
	case 'v':
	    set->verbose++;
	    break;
	case 'z':
	    set->withzeros = TRUE;
	    break;
	}

    debug(LOW, "rated version %s starting.\n", VERSION);

    if (set->daemon) {
        if (daemon_init() < 0)
            fatal("Could not fork daemon!\n");
        debug(LOW, "Daemon detached\n");
    }

    pthread_mutex_init(&stats.mutex, NULL);

    /* Initialize signal handler */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGUSR1);
    sigaddset(&signal_set, SIGUSR2);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGQUIT);
    if (!set->multiple) 
        checkPID(pid_file, set);

    if (pthread_sigmask(SIG_BLOCK, &signal_set, NULL) != 0)
        fatal("pthread_sigmask error\n");

    /* start a thread to catch signals */
    if (pthread_create(&sig_thread, NULL, sig_handler, (void *) &(signal_set)) != 0)
	fatal("pthread_create error\n");

    /* Read configuration file to establish local environment */
    if (conf_file) {
        if ((read_rated_config(conf_file, set)) < 0) 
            fatal("Could not read config file: %s\n", conf_file);
    } else {
        conf_file = malloc(BUFSIZE);
        if (!conf_file) 
            fatal("Fatal malloc error!\n");
        for(i=0;i<CONFIG_PATHS;i++) {
            snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE); 
            if (read_rated_config(conf_file, set) >= 0)
                break;
            if (i == CONFIG_PATHS-1) {
                snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE); 
                if ((write_rated_config(conf_file, set)) < 0) 
                    fatal("Couldn't write config file.\n");
            }
        }
    }

    /* these probably aren't thread safe*/
    init_snmp("rated");
    /* TODO only do this if we're debugging or not daemonised? */
    snmp_enable_stderrlog();
    /* output oids numerically - this is equivalent to -On in the snmp tools */
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC);

    if (set->dbon) {
        /* load the database driver */
        /* we need a db connection before we parse the targets file so we can check and create tables */
        if (!(db_init(set) && db_connect(set)))
            fatal("** Database error - check configuration.\n");

        /* create our own internal tables */
        table = db_check_and_create_data_table(RATED);
        if (table == NULL)
            fatal("** Database error - couldn't create rated table.\n");
        else
            free(table);
        if (!db_check_and_create_oids_table(OIDS))
            fatal("** Database error - couldn't create oids table.\n");
    }

    /* build list of hosts to be polled */
    head = hash_target_file(target_file);
    if (head == NULL)
        fatal("Error updating target list.");

    if (hosts < set->threads) {
        debug(LOW, "Number of hosts is less than configured number of threads, defaulting to %i.\n", hosts);
        set->threads = hosts;
    }

    debug(LOW, "Initializing threads (%d).\n", set->threads);
    pthread_mutex_init(&(crew.mutex), NULL);
    pthread_cond_init(&(crew.done), NULL);
    pthread_cond_init(&(crew.go), NULL);
    crew.current = NULL;

    debug(HIGH, "Starting threads...");
    crew.running = set->threads;
    for (i = 0; i < set->threads; i++) {
        crew.member[i].index = i;
        crew.member[i].crew = &crew;
        if (pthread_create(&(crew.member[i].thread), NULL, poller, (void *) &(crew.member[i])) != 0)
	    fatal("pthread_create error\n");
	debug(HIGH, " %i", i);
	}
    debug(HIGH, " done\n");

    /* spin waiting for all threads to start up */
    debug(HIGH, "Waiting for thread startup.\n");
    ts.tv_sec = 0;
    ts.tv_nsec = 10000000; /* 10 ms */
    gettimeofday(&begin_time, NULL);
    while (crew.running > 0 ) {
	nanosleep(&ts, NULL);
    }
    gettimeofday(&end_time, NULL);
    debug(HIGH, "Waited %lu milliseconds for thread startup.\n", timediff(end_time, begin_time));

    debug(LOW, "rated ready.\n");

    /* Loop Forever Polling Target List */
    while (1) {
	/* check if we've been signalled */
	if (quitting) {
            debug(LOW, "Quitting: received signal %i.\n", quit_signal);
            if (set->dbon)
                db_disconnect();
            /* one final stat output */
            print_stats(stats, set);
            unlink(pid_file);
            exit(1);
	} else if (waiting) {
            debug(HIGH, "Processing pending SIGHUP.\n");
            /* this just rebuilds the target list
             * so all of the targets will reset to a first poll */
            /* none of the threads should be running at this point so we shouldn't need a lock */
            freed = free_host_list(head);
            debug(HIGH, "Freed %i hosts\n", freed);
            head = hash_target_file(target_file);
            waiting = FALSE;
	}

        last_poll = stats.polls;

	gettimeofday(&begin_time, NULL);

	PT_MUTEX_LOCK(&(crew.mutex));
        crew.current = head;

	debug(LOW, "Queue ready, broadcasting thread go condition.\n");

	PT_COND_BROAD(&(crew.go));
	PT_MUTEX_UNLOCK(&(crew.mutex));

        /*
         * wait for signals from threads finishing
         * we have to use a do loop because when this starts up the running count will be zero
         * so wait at least once until we get a signal that some thread is done before checking for zero
         */
	PT_MUTEX_LOCK(&(crew.mutex));
        do {
            PT_COND_WAIT(&(crew.done), &(crew.mutex));
        } while (crew.running > 0);
	PT_MUTEX_UNLOCK(&(crew.mutex));

        if (quitting_now)
            continue;

	gettimeofday(&end_time, NULL);
	poll_time = timediff(end_time, begin_time);
        polls = stats.polls - last_poll;
        rate = ((double) polls / poll_time) * 1000;
        /* don't underflow */
        if (poll_time < set->interval) {
	    sleep_time = set->interval - poll_time;
        } else {
            sleep_time = 0;
            stats.slow++;
        }

        /* have to call this before we increment the round counter */
        calc_stats(&stats, poll_time);

        stats.round++;
	debug(LOW, "Poll round %d completed %llu getnexts in %lu ms (%.0f/s).\n", stats.round, polls, poll_time, rate);
        /* insert the internal poll data for this round into the rated table */
        if (set->dbon)
            db_insert(RATED, 0, end_time, stats.polls - last_poll, rate);

	if (set->verbose >= LOW) {
            print_stats(stats, set);
        }

        if (sleep_time > 0) {
            sleepy(sleep_time, set);
        } else {
            debug(LOW, "Slow poll, not sleeping\n");
        }
    } /* while(1) */
    exit(0);
}
Esempio n. 16
0
int
main (int argc, char **argv)
{
  int agentx_subagent = AGENT_TRUE;
  char c;
  int rc = 0;

  pid_t child;
  /* change this if you want to be a SNMP master agent */


  while ((c = getopt (argc, argv, "fds?")) != EOF)
    switch (c)
      {
      case 'f':
	do_fork = AGENT_TRUE;
	break;
      case 'd':
	debug_register_tokens (AGENT);
	snmp_enable_stderrlog ();
	snmp_set_do_debugging (1);
	break;
	break;
      case 's':
	do_syslog = AGENT_FALSE;
	break;
      default:
	printf ("Usage %s [-dfs]\n", argv[0]);
	printf ("where -d enables debug mode\n");
	printf ("where -f enables forking\n");
	printf ("where -s disables logging via syslog facility.\n");
	exit (1);
      }
  init_snmp_logging ();

  if (do_syslog == AGENT_TRUE)
    {
      snmp_enable_calllog ();
      snmp_enable_syslog_ident (AGENT, LOG_DAEMON);
    }
  snmp_log (LOG_INFO, "Starting %s\n", version);
  /* we're an agentx subagent? */
  if (agentx_subagent)
    {
      /* make us a agentx client. */
      rc = netsnmp_ds_set_boolean (NETSNMP_DS_APPLICATION_ID,
				   NETSNMP_DS_AGENT_ROLE, 1);
    }

  /* initialize the agent library */
  rc = init_agent (AGENT);
  if (rc != 0)
    {
      snmp_log (LOG_ERR, "Could not initialize connection to SNMP daemon. \n"
		"Perhaps you are running %s as non-root?\n", argv[0]);
      exit (rc);
    }

  /* Read configuration information here, before we initialize */

  snmpd_register_config_handler (TRAPS_TOKEN,
				 hpiSubagent_parse_config_traps,
				 NULL,
				 "hpiSubagent on/off switch for sending events upon startup");

  snmpd_register_config_handler (INTERVAL_TOKEN,
				 hpiSubagent_parse_config_interval,
				 NULL,
				 "hpiSubagent time in seconds before HPI API is queried for information.");

  snmpd_register_config_handler (MAX_EVENT_TOKEN,
				 hpiSubagent_parse_config_max_event,
				 NULL,
				 "hpiSubagent MAX number of rows for Events.");

  init_snmp (AGENT);
  /* Initialize tables */
  initialize_table_saHpiTable ();
  initialize_table_saHpiRdrTable ();
  initialize_table_saHpiSensorTable ();
  initialize_table_saHpiCtrlTable ();
  initialize_table_saHpiInventoryTable ();
  initialize_table_saHpiWatchdogTable ();
  initialize_table_saHpiHotSwapTable ();

  initialize_table_saHpiSystemEventLogTable ();
  initialize_table_saHpiEventTable ();

  initialize_table_saHpiSensorReadingCurrentTable ();
  initialize_table_saHpiSensorReadingMaxTable ();
  initialize_table_saHpiSensorReadingMinTable ();
  initialize_table_saHpiSensorReadingNominalTable ();
  initialize_table_saHpiSensorReadingNormalMaxTable ();
  initialize_table_saHpiSensorReadingNormalMinTable ();

  initialize_table_saHpiSensorThdLowCriticalTable ();
  initialize_table_saHpiSensorThdLowMajorTable ();
  initialize_table_saHpiSensorThdLowMinorTable ();

  initialize_table_saHpiSensorThdUpCriticalTable ();
  initialize_table_saHpiSensorThdUpMajorTable ();
  initialize_table_saHpiSensorThdUpMinorTable ();

  initialize_table_saHpiSensorThdNegHysteresisTable ();
  initialize_table_saHpiSensorThdPosHysteresisTable ();

  if (send_traps_on_startup == AGENT_TRUE)
    send_traps = AGENT_TRUE;

  if (populate_rpt () != AGENT_ERR_NOERROR)
    {
      snmp_log (LOG_ERR, "Could not retrieve RPT entries. Exiting\n.");
      rc = -1;
      goto stop;
    }
  populate_event ();
  if (init_alarm () != AGENT_ERR_NOERROR)
    {
      snmp_log (LOG_ERR, "Could not start our internal loop . Exiting\n.");
      rc = -1;
      goto stop;
    }

  send_traps = AGENT_TRUE;
  /* If we're going to be a snmp master agent, initial the ports */

  if (!agentx_subagent)
    init_master_agent ();	/* open the port to listen on (defaults to udp:161) */

  if (do_fork == AGENT_TRUE)
    {
      if ((child = fork ()) < 0)
	{
	  snmp_log (LOG_ERR, "Could not fork!\n");
	  exit (-1);
	}
      if (child != 0)
	exit (0);
    }
  /* In case we recevie a request to stop (kill -TERM or kill -INT) */
  keep_running = 1;
  signal (SIGTERM, stop_server);
  signal (SIGINT, stop_server);

  /* you're main loop here... */
  while (keep_running)
    {
      /* if you use select(), see snmp_select_info() in snmp_api(3) */
      /*     --- OR ---  */
      rc = agent_check_and_process (1);	/* 0 == don't block */
    }
stop:
  /* at shutdown time */
  snmp_log (LOG_INFO, "Stopping %s\n", version);
  snmp_shutdown (AGENT);

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

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

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

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

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

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

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

        case 'c':
            community = optarg;
            break;

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

        case 'a':
            aflag++;
            break;

        case 'i':
            iflag++;
            break;

        case 'o':
            oflag++;
            break;

        case 'n':
            nflag++;
            break;

        case 'r':
            rflag++;
            break;

        case 's':
            sflag++;
            break;

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

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

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

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


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

    SOCK_STARTUP;

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

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

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

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

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

    snmp_close(Session);

    SOCK_CLEANUP;
    return 0;
}
Esempio n. 18
0
int
main (int argc, char **argv)
{
	
	  	int agentx_subagent = AGENT_TRUE;
	  	int c;
	  	int rc = 0;
        	  
	  	SaErrorT 	rv = SA_OK;
		SaHpiVersionT	hpiVer;
		SaHpiSessionIdT sessionid;
		
		
		
	  	pid_t child;
		
		/* for simulator */
		struct oh_handler_state *state = NULL;
		struct oh_event *event = (struct oh_event *)g_malloc0(sizeof(struct oh_event));
		struct oh_event *event2= (struct oh_event *)g_malloc0(sizeof(struct oh_event));
		struct oh_event *event3= (struct oh_event *)g_malloc0(sizeof(struct oh_event));		
		struct oh_event *event4= (struct oh_event *)g_malloc0(sizeof(struct oh_event));
		struct oh_event *event5= (struct oh_event *)g_malloc0(sizeof(struct oh_event));	
		struct oh_event *event6= (struct oh_event *)g_malloc0(sizeof(struct oh_event));	
		struct oh_event *event7= (struct oh_event *)g_malloc0(sizeof(struct oh_event));	
		struct oh_event *event8= (struct oh_event *)g_malloc0(sizeof(struct oh_event));			
							
		SaErrorT rc1;
	  	char OemString[] = "MY Oem EVENT";
	  	char SWString[] = "MY SW EVENT";			  	
	  	/* change this if you want to be a SNMP master agent */
	  	
	  	debug_register_tokens (AGENT);
                snmp_enable_stderrlog ();
                snmp_set_do_debugging (1);

	  	while ((c = getopt (argc, argv, "fdsCx:h?")) != EOF) {
	    switch (c) {
	   	case 'f':
			do_fork = AGENT_TRUE;
		   	break;
	
	    case 'd':
			debug_register_tokens (AGENT);
			snmp_enable_stderrlog ();
			snmp_set_do_debugging (1);
	      	break;
	
	  	case 's':
			do_syslog = AGENT_FALSE;
	      	break;
	
	   	case 'C':
			netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
				       NETSNMP_DS_LIB_DONT_READ_CONFIGS,
				       1);
	     	break;
	
	  	case 'x':
			netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID,
				      NETSNMP_DS_AGENT_X_SOCKET,
				      optarg);
	      	break;
	
	 	case 'h':
	    default:
			usage(argv[0]);
			exit(1);
	      	break;
	    }
	  }
	
	  if (do_syslog == AGENT_TRUE) {
	      snmp_enable_calllog ();
	      snmp_enable_syslog_ident (AGENT, LOG_DAEMON);
	  }
	  snmp_log (LOG_INFO, "Starting %s\n", version);
	  /* we're an agentx subagent? */
	  if (agentx_subagent) {
	      /* make us a agentx client. */
	      rc = netsnmp_ds_set_boolean (NETSNMP_DS_APPLICATION_ID,
					   NETSNMP_DS_AGENT_ROLE, 1);
	  }
	
	  /* initialize the agent library */
	  rc = init_agent (AGENT);
	  if (rc != 0) {
	      snmp_log (LOG_ERR, "Could not initialize connection to SNMP daemon. \n"
			"Perhaps you are running %s as non-root?\n", argv[0]);
	      exit (rc);
	  }

	  /* Read configuration information here, before we initialize */
	
	  snmpd_register_config_handler (TRAPS_TOKEN,
					 hpiSubagent_parse_config_traps,
					 NULL,
					 "hpiSubagent on/off switch for sending events upon startup");
	
	  snmpd_register_config_handler (MAX_EVENT_TOKEN,
					 hpiSubagent_parse_config_max_event,
					 NULL,
					 "hpiSubagent MAX number of rows for Events.");
					 
	init_snmp (AGENT); 	
	
	/* 
	 * Initialize HPI library
	 */
	hpiVer = saHpiVersionGet();
	DEBUGMSGTL ((AGENT, "Hpi Version %d Implemented.\n", hpiVer));   	 

	rv = saHpiSessionOpen( SAHPI_UNSPECIFIED_DOMAIN_ID, &sessionid, NULL );
	if (rv != SA_OK) {
		DEBUGMSGTL ((AGENT, "saHpiSessionOpen Error: returns %s\n",
			oh_lookup_error(rv)));
		exit(-1);
	}
   	DEBUGMSGTL ((AGENT, "saHpiSessionOpen returns with SessionId %d\n", 
   		sessionid));  

        /* store session numbers */
   	store_session_info(sessionid, SAHPI_UNSPECIFIED_DOMAIN_ID);	
   				
	/* subscribe all sessions/events */
        subcsribe_all_sessions();

	/* Resource discovery */
	rv = saHpiDiscover(sessionid);
	
	if (rv != SA_OK) {
		DEBUGMSGTL ((AGENT, "saHpiDiscover Error: returns %s\n",oh_lookup_error(rv)));
		exit(-1);
	}
	DEBUGMSGTL ((AGENT, "saHpiDiscover Success!\n"));	

	/* Initialize subagent tables */		
	init_saHpiDomainInfoTable(); 
	init_saHpiDomainAlarmTable();
	init_saHpiDomainReferenceTable();
	
	init_saHpiResourceTable();
	init_saHpiRdrTable();
	init_saHpiCtrlDigitalTable();
	init_saHpiCtrlDiscreteTable();
	init_saHpiCtrlAnalogTable();
	init_saHpiCtrlStreamTable();
	init_saHpiCtrlTextTable();
	init_saHpiCtrlOemTable();
	init_saHpiSensorTable();
	init_saHpiCurrentSensorStateTable();
	init_saHpiSensorReadingMaxTable();
	init_saHpiSensorReadingMinTable();
	init_saHpiSensorReadingNominalTable();
	init_saHpiSensorReadingNormalMaxTable();
	init_saHpiSensorReadingNormalMinTable();
	init_saHpiSensorThdLowCriticalTable();
	init_saHpiSensorThdLowMajorTable();
	init_saHpiSensorThdLowMinorTable();
	init_saHpiSensorThdUpCriticalTable();
	init_saHpiSensorThdUpMajorTable();
	init_saHpiSensorThdUpMinorTable();
	init_saHpiSensorThdPosHysteresisTable();
	init_saHpiSensorThdNegHysteresisTable();
	init_saHpiInventoryTable();
	init_saHpiWatchdogTable();
	init_saHpiAnnunciatorTable();
	init_saHpiAreaTable();
	init_saHpiFieldTable();

	init_saHpiEventTable();
	init_saHpiResourceEventTable();
	init_saHpiDomainEventTable();
	init_saHpiSensorEventTable();
	init_saHpiOemEventTable();
	init_saHpiHotSwapEventTable();
	init_saHpiWatchdogEventTable();		
	init_saHpiSoftwareEventTable();
	init_saHpiSensorEnableChangeEventTable();
	init_saHpiUserEventTable();

	init_saHpiEventLogInfoTable();
	init_saHpiEventLogTable();
	init_saHpiResourceEventLogTable();
	init_saHpiSensorEventLogTable();
	
	init_saHpiHotSwapEventLogTable();
	init_saHpiWatchdogEventLogTable();
	init_saHpiSoftwareEventLogTable();
	init_saHpiOemEventLogTable();
	init_saHpiUserEventLogTable();
	init_saHpiSensorEnableChangeEventLogTable();
	init_saHpiDomainEventLogTable();
	
	init_saHpiHotSwapTable();
	init_saHpiAutoInsertTimeoutTable();
	init_saHpiAnnouncementTable();
/*	init_saHpiAnnouncementEventLogTable();	*/


	if (send_traps_on_startup == AGENT_TRUE)
		send_traps = AGENT_TRUE;
	/* after initialization populate tables */
	populate_saHpiDomainInfoTable(sessionid);

	populate_saHpiDomainAlarmTable(sessionid);

	poplulate_saHpiDomainReferenceTable(sessionid);	

	populate_saHpiResourceTable(sessionid);
	    /* populate_saHpiResourceTable() calls:
	     *     populate_saHpiRdrTable(); calls:
	     *         populate_saHpiCtrlDigitalTable();		
	     *	       populate_saHpiCtrlDiscreteTable();		
	     *	       populate_saHpiCtrlAnalogTable();		
	     *	       populate_saHpiCtrlStreamTable();		
	     *	       populate_saHpiCtrlTextTable();		
	     *	       populate_saHpiCtrlOemTable();		
	     *	       populate_saHpiSensorTable();		
	     *	           populate_saHpiSesnorReadingMaxTable();		
	     *	           populate_saHpiSesnorReadingMinTable();		
	     *	           populate_saHpiSesnorReadingNominalTable();		
	     *	           populate_saHpiSesnorReadingNormalMaxTable();		
	     *	           populate_saHpiSesnorReadingNormalMinTable();		
	     *	           populate_saHpiSensorThdLowCriticalTable();		
	     *	           populate_saHpiSensorThdLowMajorTable();		
	     *	           populate_saHpiSensorThdLowMinorTable();		
	     *	           populate_saHpiSensorThdUpCriticalTable();		
	     *	           populate_saHpiSensorThdUpMajorTable();		
	     *	           populate_saHpiSensorThdUpMinorTable();		
	     *	           populate_saHpiSensorThdPosHysteresisTable();		
	     *	           populate_saHpiSensorThdNegHysteresisTable();		
	     *	       populate_saHpiCurrentSensorStateTable();		
	     *	       populate_saHpiInventoyTable();		
	     *	       populate_saHpiWatchdogTable();		
	     *	       populate_saHpiAnnunciatorTable();		
	     *	       populate_saHpiAreaTable();		
	     *	           populate_saHpiFieldTable();
	     *         populate_saHpiHotSwapTable();
	     */

	populate_saHpiEventTable(sessionid);
            /* populate_saHpiResourceEventTable();
	     * populate_saHpiDomainEventTable();
	     * populate_saHpiSensorEventTable();
	     * populate_saHpiOemEventTable();
	     * populate_saHpiHotSwapEventTable();
	     * populate_saHpiWatchdogEventTable();
	     * populate_saHpiSoftwareEventTable();
	     * populate_saHpiSensorEnableChangeEventTable();
	     * populate_saHpiUserEventTable();
	     */
        populate_saHpiEventLogInfo(sessionid);
        populate_saHpiEventLog (sessionid);
            /*
             * populate_saHpiResourceEventLogTable();
             * populate_saHpiSensorEventLogTable();
	     * populate_saHpiHotSwapEventLogTable();
	     * populate_saHpiWatchdogEventLogTable();
	     * populate_saHpiSoftwareEventLogTable();
	     * populate_saHpiOemEventLogTable();
	     * populate_saHpiUserEventLogTable();
	     * populate_saHpiSensorEnableChangeEventLogTable();
	     * populate_saHpiDomainEventLogTable();	     
             */


        /* Generate Event Here */
		
	DEBUGMSGTL ((AGENT,
        "%%%%%%%% Generating simultor event %%%%%%%%\n"));
	
	state = sim_get_handler_by_name("eventGenerator");
	
	if (!state) {
                DEBUGMSGTL ((AGENT, "%%%%%%%% Couldn't find handler name %%%%%%%%\n"));
	}
	else { // build an event
		
	        event->did = 1; /* domain id for the event */
                event->type = OH_ET_HPI;
                event->u.hpi_event.res = sim_rpt_array[0].rpt;
                event->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event->u.hpi_event.event.EventType = SAHPI_ET_WATCHDOG;
		event->u.hpi_event.event.Timestamp = 0;
		event->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event->u.hpi_event.event.EventDataUnion.WatchdogEvent.WatchdogNum = 1;
		event->u.hpi_event.event.EventDataUnion.WatchdogEvent.WatchdogAction = SAHPI_WAE_RESET;
		event->u.hpi_event.event.EventDataUnion.WatchdogEvent.WatchdogPreTimerAction = SAHPI_WPI_SMI;
		event->u.hpi_event.event.EventDataUnion.WatchdogEvent.WatchdogUse = SAHPI_WTU_BIOS_FRB2;
		
		
		rc1 = sim_inject_event(state, event);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 1: %d %%%%%%%%\n", rc1));
		
	        event2->did = 1; /* domain id for the event */
                event2->type = OH_ET_HPI;
                event2->u.hpi_event.res = sim_rpt_array[0].rpt;
                event2->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event2->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event2->u.hpi_event.event.EventType = SAHPI_ET_HOTSWAP;
		event2->u.hpi_event.event.Timestamp = 0;
		event2->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event2->u.hpi_event.event.EventDataUnion.HotSwapEvent.HotSwapState = SAHPI_HS_STATE_INSERTION_PENDING;
		event2->u.hpi_event.event.EventDataUnion.HotSwapEvent.PreviousHotSwapState = SAHPI_HS_STATE_NOT_PRESENT;				

		rc1 = sim_inject_event(state, event2);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 2: %d %%%%%%%%\n", rc1));
		
	        event3->did = 1; /* domain id for the event */
                event3->type = OH_ET_HPI;
                event3->u.hpi_event.res = sim_rpt_array[0].rpt;
                event3->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event3->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event3->u.hpi_event.event.EventType = SAHPI_ET_SENSOR;
		event3->u.hpi_event.event.Timestamp = 0;
		event3->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.SensorNum = SAHPI_DEFAGSENS_PWR;
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.SensorType = SAHPI_VOLTAGE;	   
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.EventCategory = SAHPI_EC_GENERIC;   
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.Assertion = 1;   
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.EventState = SAHPI_ES_STATE_00;    
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.OptionalDataPresent = SAHPI_SOD_TRIGGER_READING;
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.TriggerReading.IsSupported = 1;
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.TriggerReading.Type = SAHPI_SENSOR_READING_TYPE_UINT64;
		event3->u.hpi_event.event.EventDataUnion.SensorEvent.TriggerReading.Value.SensorUint64 = 0xFEEEEEEEEEEEEEED;
		
		rc1 = sim_inject_event(state, event3);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 3: %d %%%%%%%%\n", rc1));	
		
	        event4->did = 1; /* domain id for the event */
                event4->type = OH_ET_HPI;
                event4->u.hpi_event.res = sim_rpt_array[0].rpt;
                event4->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event4->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event4->u.hpi_event.event.EventType = SAHPI_ET_OEM;
		event4->u.hpi_event.event.Timestamp = 0;
		event4->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event4->u.hpi_event.event.EventDataUnion.OemEvent.MId = SAHPI_MANUFACTURER_ID_UNSPECIFIED;		
		event4->u.hpi_event.event.EventDataUnion.OemEvent.OemEventData.DataType = SAHPI_TL_TYPE_BCDPLUS;
		event4->u.hpi_event.event.EventDataUnion.OemEvent.OemEventData.Language = SAHPI_LANG_ENGLISH;
		event4->u.hpi_event.event.EventDataUnion.OemEvent.OemEventData.DataLength = 12;
		memcpy(event4->u.hpi_event.event.EventDataUnion.OemEvent.OemEventData.Data, &OemString[0],
		       event4->u.hpi_event.event.EventDataUnion.OemEvent.OemEventData.DataLength);
		
		rc1 = sim_inject_event(state, event4);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 4: %d %%%%%%%%\n", rc1));	
		
	        event5->did = 1; /* domain id for the event */
                event5->type = OH_ET_HPI;
                event5->u.hpi_event.res = sim_rpt_array[0].rpt;
                event5->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event5->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event5->u.hpi_event.event.EventType = SAHPI_ET_HPI_SW;
		event5->u.hpi_event.event.Timestamp = 0;
		event5->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.MId = SAHPI_MANUFACTURER_ID_UNSPECIFIED;
		event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.Type = SAHPI_HPIE_STARTUP;
		event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.EventData.DataType = SAHPI_TL_TYPE_TEXT;
		event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.EventData.Language = SAHPI_LANG_ENGLISH;
		event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.EventData.DataLength = 11;  								     
		memcpy(event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.EventData.Data, &SWString[0],
		       event5->u.hpi_event.event.EventDataUnion.HpiSwEvent.EventData.DataLength);

		rc1 = sim_inject_event(state, event5);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 5: %d %%%%%%%%\n", rc1));	
		
	        event6->did = 1; /* domain id for the event */
                event6->type = OH_ET_HPI;
                event6->u.hpi_event.res = sim_rpt_array[0].rpt;
                event6->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event6->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event6->u.hpi_event.event.EventType = SAHPI_ET_SENSOR_ENABLE_CHANGE;
		event6->u.hpi_event.event.Timestamp = 0;
		event6->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.SensorNum = SAHPI_DEFAGSENS_PWR;
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.SensorType = SAHPI_VOLTAGE;	   
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.EventCategory = SAHPI_EC_GENERIC;   
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.SensorEnable = 1;
                event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.SensorEventEnable = 1;
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.AssertEventMask = SAHPI_ES_STATE_ASSERTED;
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.DeassertEventMask = SAHPI_ES_STATE_DEASSERTED;
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.OptionalDataPresent = SAHPI_SEOD_CURRENT_STATE;  
		event6->u.hpi_event.event.EventDataUnion.SensorEnableChangeEvent.CurrentState = SAHPI_ES_LIMIT_EXCEEDED; 
		
		rc1 = sim_inject_event(state, event6);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 6: %d %%%%%%%%\n", rc1));	
		
	        event7->did = 1; /* domain id for the event */
                event7->type = OH_ET_HPI;
                event7->u.hpi_event.res = sim_rpt_array[0].rpt;
                event7->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event7->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event7->u.hpi_event.event.EventType = SAHPI_ET_DOMAIN;
		event7->u.hpi_event.event.Timestamp = 0;
		event7->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event7->u.hpi_event.event.EventDataUnion.DomainEvent.Type = SAHPI_DOMAIN_REF_ADDED;
		event7->u.hpi_event.event.EventDataUnion.DomainEvent.DomainId = SAHPI_UNSPECIFIED_DOMAIN_ID;
		
		rc1 = sim_inject_event(state, event7);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 7: %d %%%%%%%%\n", rc1));	
		
	        event8->did = 1; /* domain id for the event */
                event8->type = OH_ET_HPI;
                event8->u.hpi_event.res = sim_rpt_array[0].rpt;
                event8->u.hpi_event.rdr.RecordId = 0; // Not sure here
		event8->u.hpi_event.event.Source = sim_rpt_array[0].rpt.ResourceId;
		event8->u.hpi_event.event.EventType = SAHPI_ET_RESOURCE;
		event8->u.hpi_event.event.Timestamp = 0;
		event8->u.hpi_event.event.Severity = SAHPI_CRITICAL;
		event8->u.hpi_event.event.EventDataUnion.ResourceEvent.ResourceEventType = SAHPI_RESE_RESOURCE_FAILURE;								  				       	        	     		
		
		rc1 = sim_inject_event(state, event8);
                DEBUGMSGTL ((AGENT, "%%%%%%%% Return code from inject 8: %d %%%%%%%%\n", rc1));	

	}


        /* start event thread */
        set_run_threaded(TRUE);
        if (start_event_thread(sessionid) != AGENT_ERR_NOERROR) {
                snmp_log (LOG_ERR, "Could not start our internal loop . Exiting\n.");
                rc = -1;
                goto stop;
        }

        send_traps = AGENT_TRUE;
        /* If we're going to be a snmp master agent, initial the ports */

        if (!agentx_subagent)
                init_master_agent ();	/* open the port to listen on (defaults to udp:161) */
                
        if (do_fork == AGENT_TRUE) {
                if ((child = fork ()) < 0) {
                        snmp_log (LOG_ERR, "Could not fork!\n");
                        exit (-1);
                }
                if (child != 0)
                        exit (0);
        }

   
        /* In case we recevie a request to stop (kill -TERM or kill -INT) */
        keep_running = 1;
        signal (SIGTERM, stop_server);
        signal (SIGINT, stop_server);



        /* you're main loop here... */
        while (keep_running) {
                /* if you use select(), see snmp_select_info() in snmp_api(3) */
                /*     --- OR ---  */
                rc = agent_check_and_process (1);	/* 0 == don't block */
        }
stop:
        DEBUGMSGTL ((AGENT,
        "WARNING: closeSaHpiSession: hpiSubagent.c: nolong implemented!"));
        //closeSaHpiSession();
        /* at shutdown time */
        snmp_log (LOG_INFO, "Stopping %s\n", version);
        snmp_shutdown (AGENT);
  
  return rc;
}