void test_lazy_load_failed()
 {
     Engine engine(Engine::READ_ONLY);
     setup_log(engine);
     Session session(Yb::theSchema(), &engine);
     OrmTest dobj(session, ORM_XML_ID2);
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Ghost, (int)dobj.get_data_object()->status());
     String x = dobj.a;
 }
 void tearDown()
 {
     SqlConnection conn(Engine::sql_source_from_env());
     setup_log(conn);
     conn.begin_trans_if_necessary();
     conn.exec_direct(_T("DELETE FROM T_ORM_XML"));
     conn.exec_direct(_T("DELETE FROM T_ORM_TEST"));
     conn.grant_insert_id(_T("T_ORM_TEST"), false, true);
     conn.grant_insert_id(_T("T_ORM_XML"), false, true);
     conn.commit();
 }
void dolog(FILE *output, ...)
{
  va_list args;
  va_start(args, output);
  if (setjmp(buf) != 0)
  {
    vfprintf(output, "%i %i %n\n", args);
    va_end(args);
  }
  else
    setup_log(output);
}
 void test_lazy_load()
 {
     Engine engine(Engine::READ_ONLY);
     setup_log(engine);
     Session session(Yb::theSchema(), &engine);
     OrmTest dobj(session, ORM_TEST_ID1);
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Ghost, (int)dobj.get_data_object()->status());
     CPPUNIT_ASSERT_EQUAL(string("item"), NARROW(dobj.a.value()));
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Sync, (int)dobj.get_data_object()->status());
     dobj.a = _T("new_item");
     CPPUNIT_ASSERT_EQUAL(string("new_item"), NARROW(dobj.a.value()));
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Dirty, (int)dobj.get_data_object()->status());
 }
    void setUp()
    {
        SqlConnection conn(Engine::sql_source_from_env());
        conn.set_convert_params(true);
        setup_log(conn);
        conn.begin_trans_if_necessary();
        conn.grant_insert_id(_T("T_ORM_TEST"), true, true);
        {
            String sql_str =
                _T("INSERT INTO T_ORM_TEST(ID, A, B, C, D) VALUES(?, ?, ?, ?, ?)");
            conn.prepare(sql_str);
            Values params(5);
            params[0] = Value(ORM_TEST_ID1);
            params[1] = Value(_T("item"));
            params[2] = Value(now());
            params[3] = Value(Decimal(_T("1.2")));
            params[4] = Value(4.56);
            conn.exec(params);
        }
        conn.grant_insert_id(_T("T_ORM_TEST"), false, true);
        conn.grant_insert_id(_T("T_ORM_XML"), true, true);
        {
            String sql_str =
                _T("INSERT INTO T_ORM_XML(ID, ORM_TEST_ID, B) VALUES (?, ?, ?)");
            conn.prepare(sql_str);
            Values params(3);
            params[0] = Value(ORM_XML_ID2);
            params[1] = Value(ORM_TEST_ID1);
            params[2] = Value(Decimal(_T("3.14")));
            conn.exec(params);
            params[0] = Value(ORM_XML_ID3);
            params[1] = Value(ORM_TEST_ID1);
            params[2] = Value(Decimal(_T("2.7")));
            conn.exec(params);
        }
        {
            String sql_str =
                _T("INSERT INTO T_ORM_XML(ID, ORM_TEST_ID, B) VALUES (?, ?, ?)");
            conn.prepare(sql_str);
            Values params(3);
            params[0] = Value(ORM_XML_ID4);
            params[1] = Value();
            params[2] = Value(Decimal(_T("42")));
            conn.exec(params);
        }
        conn.grant_insert_id(_T("T_ORM_XML"), false, true);
        conn.commit();

        Yb::init_schema();
    }
 void test_null_fk_relation()
 {
     Engine engine(Engine::READ_ONLY);
     setup_log(engine);
     Session session(Yb::theSchema(), &engine);
     OrmXml dobj(session, ORM_XML_ID4);
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Ghost, (int)dobj.get_data_object()->status());
     Decimal x = dobj.b;
     CPPUNIT_ASSERT_EQUAL((int)DataObject::Sync, (int)dobj.get_data_object()->status());
     // Holder is always not empty!
     CPPUNIT_ASSERT(dobj.orm_test._get_p() != NULL);
     // but:
     // DomainObject does not contain link to DataObject
     CPPUNIT_ASSERT(dobj.orm_test->is_empty());
     // Referencing DataObject does not have FK field set
     CPPUNIT_ASSERT(dobj.get(_T("ORM_TEST_ID")).is_null());
 }
 void test_explicit_join2()
 {
     Engine engine(Engine::READ_ONLY);
     setup_log(engine);
     Session session(Yb::theSchema(), &engine);
     DomainResultSet<OrmXml> rs = Yb::query<OrmXml>(session)
         .select_from<OrmTest>()
         .join<OrmXml>()
         .filter_by(OrmTest::c.id == ORM_TEST_ID1)
         .all();
     vector<OrmXml> out;
     copy(rs.begin(), rs.end(), back_inserter(out));
     CPPUNIT_ASSERT_EQUAL(2, (int)out.size());
     ///
     CPPUNIT_ASSERT_EQUAL(3, (int)session.objects_.size());
     CPPUNIT_ASSERT_EQUAL(3, (int)session.identity_map_.size());
     CPPUNIT_ASSERT(out[0] != out[1]);
 }
 void test_join()
 {
     Engine engine(Engine::READ_ONLY);
     setup_log(engine);
     Session session(Yb::theSchema(), &engine);
     QueryObj<boost::tuple<OrmTest, OrmXml> > q1 =
         Yb::query<boost::tuple<OrmTest, OrmXml> >(session)
                 .select_from<OrmTest>()
                 .join<OrmXml>(OrmTest::c.id == OrmXml::c.orm_test_id);
     CPPUNIT_ASSERT_EQUAL(2, (int)q1.count());
     QueryObj<boost::tuple<OrmTest, OrmXml> > q2 =
         Yb::query<boost::tuple<OrmTest, OrmXml> >(session)
                 .select_from<OrmTest>()
                 .join<OrmXml>();
     CPPUNIT_ASSERT_EQUAL(2, (int)q2.count());
     // and the old style:
     QueryObj<boost::tuple<OrmTest, OrmXml> > q3 =
         Yb::query<boost::tuple<OrmTest, OrmXml> >(session);
     CPPUNIT_ASSERT_EQUAL(2, (int)q3.count());
 }
    void test_holder()
    {
        // a new DomainObject with a new DataObject object are created
        OrmXml::Holder dh0;
        CPPUNIT_ASSERT(dh0._get_p() != NULL);
        CPPUNIT_ASSERT(!dh0->is_empty());
        // a new DomainObject with an empty DataObject are created
        OrmXml::Holder dh1(EMPTY_DATAOBJ);
        CPPUNIT_ASSERT(dh1._get_p() != NULL);
        CPPUNIT_ASSERT(dh1->is_empty());

        Engine engine(Engine::READ_ONLY);
        setup_log(engine);
        Session session(Yb::theSchema(), &engine);
        OrmXml dobj(session, ORM_XML_ID4);
        OrmXml::Holder dh2(dobj);
        CPPUNIT_ASSERT(dh2._get_p() != NULL);
        CPPUNIT_ASSERT_EQUAL(shptr_get(dobj.get_data_object()),
                shptr_get(dh2->get_data_object()));
    }
Beispiel #10
0
main(int argc, char *argv[])
#endif
{
    char            options[128] = "aAc:CdD::fhHI:l:LP:qrsS:UvV-:";
    int             arg, i, ret;
    int             dont_fork = 0;
    int             dont_zero_log = 0;
    int             stderr_log = 0, syslog_log = 0;
    int             uid = 0, gid = 0;
    int             agent_mode = -1;
    char            logfile[PATH_MAX + 1] = { 0 };
    char           *cptr, **argvptr;
    char           *pid_file = NULL;
#if HAVE_GETPID
    int fd;
    FILE           *PID;
#endif

#ifdef LOGFILE
    strncpy(logfile, LOGFILE, PATH_MAX);
#endif

#ifdef NO_ROOT_ACCESS
    /*
     * Default to no.  
     */
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			   NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1);
#endif
    /*
     * Default to NOT running an AgentX master.  
     */
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			   NETSNMP_DS_AGENT_AGENTX_MASTER, 0);
    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_TIMEOUT, -1);
    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_RETRIES, -1);

    /*
     * Add some options if they are available.  
     */
#if HAVE_UNISTD_H
    strcat(options, "g:u:");
#endif
#if defined(USING_AGENTX_SUBAGENT_MODULE)|| defined(USING_AGENTX_MASTER_MODULE)
    strcat(options, "x:");
#endif
#ifdef USING_AGENTX_SUBAGENT_MODULE
    strcat(options, "X");
#endif

    /*
     * Now process options normally.  
     */

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

            handle_long_opt(optarg);
            break;

        case 'a':
            log_addresses++;
            break;

        case 'A':
            dont_zero_log = 1;
            break;

        case 'c':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
				      NETSNMP_DS_LIB_OPTIONALCONFIG, optarg);
            } else {
                usage(argv[0]);
            }
            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(++snmp_dump_packet);
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_VERBOSE, 1);
            break;

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

        case 'f':
            dont_fork = 1;
            break;

#if HAVE_UNISTD_H
        case 'g':
            if (optarg != NULL) {
                netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_GROUPID, atoi(optarg));
            } else {
                usage(argv[0]);
            }
            break;
#endif

        case 'h':
            usage(argv[0]);
            break;

        case 'H':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1);
            init_agent("snmpd");        /* register our .conf handlers */
            init_mib_modules();
            init_snmp("snmpd");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            exit(0);

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

        case 'l':
            if (optarg != NULL) {
                if (strlen(optarg) > PATH_MAX) {
                    fprintf(stderr,
                            "%s: logfile path too long (limit %d chars)\n",
                            argv[0], PATH_MAX);
                    exit(1);
                }
                strncpy(logfile, optarg, PATH_MAX);
            } else {
                usage(argv[0]);
            }
            break;

        case 'L':
            stderr_log = 1;
            break;

        case 'P':
            if (optarg != NULL) {
                pid_file = optarg;
            } else {
                usage(argv[0]);
            }
            break;

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

        case 'r':
            netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_NO_ROOT_ACCESS);
            break;

        case 's':
            syslog_log = 1;
            break;

        case 'S':
            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(argv[0]);
                }
            } else {
                fprintf(stderr, "no syslog facility specified\n");
                usage(argv[0]);
            }
            break;

        case 'U':
            netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_LEAVE_PIDFILE);
            break;

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

                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(argv[0]);
            }
            break;
#endif

        case 'v':
            version();

        case 'V':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_VERBOSE, 1);
            break;

#if defined(USING_AGENTX_SUBAGENT_MODULE)|| defined(USING_AGENTX_MASTER_MODULE)
        case 'x':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_X_SOCKET, optarg);
            } else {
                usage(argv[0]);
            }
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_AGENTX_MASTER, 1);
            break;
#endif

        case 'X':
#if defined(USING_AGENTX_SUBAGENT_MODULE)
            agent_mode = SUB_AGENT;
#else
            fprintf(stderr, "%s: Illegal argument -X:"
		            "AgentX support not compiled in.\n", argv[0]);
            usage(argv[0]);
            exit(1);
#endif
            break;

        default:
            usage(argv[0]);
            break;
        }
    }

    if (optind < argc) {
        /*
         * 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);
                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)));
    }

    setup_log(0, dont_zero_log, stderr_log, syslog_log, logfile);

    /*
     * Initialize a argv set to the current for restarting the agent.   
     */
    argvrestartp = (char **)malloc((argc + 2) * sizeof(char *));
    argvptr = argvrestartp;
    for (i = 0, ret = 1; i < argc; i++) {
        ret += strlen(argv[i]) + 1;
    }
    argvrestart = (char *) malloc(ret);
    argvrestartname = (char *) malloc(strlen(argv[0]) + 1);
    if (!argvrestartp || !argvrestart || !argvrestartname) {
        fprintf(stderr, "malloc failure processing argvrestart\n");
        exit(1);
    }
    strcpy(argvrestartname, argv[0]);
    if (agent_mode == -1) {
        if (strstr(argvrestartname, "agentxd") != NULL) {
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_ROLE, SUB_AGENT);
        } else {
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_ROLE, MASTER_AGENT);
        }
    } else {
        netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_ROLE, agent_mode);
    }

    for (cptr = argvrestart, i = 0; i < argc; i++) {
        strcpy(cptr, argv[i]);
        *(argvptr++) = cptr;
        cptr += strlen(argv[i]) + 1;
    }
    *cptr = 0;
    *argvptr = NULL;

#ifdef BUFSIZ
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
#endif
    /*
     * Initialize the world.  Detach from the shell.  Create initial user.  
     */
#if HAVE_FORK
    if (!dont_fork) {
        /*
         * Fork to return control to the invoking process and to
         * guarantee that we aren't a process group leader.
         */
        if (fork() != 0) {
            /* Parent. */
            if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                                        NETSNMP_DS_AGENT_QUIT_IMMEDIATELY)) {
                exit(0);
            }
        } else {
            /* Child. */
#ifdef HAVE_SETSID
            /* Become a process/session group leader. */
            setsid();
#endif
            /*
             * Fork to let the process/session group leader exit.
             */
            if (fork() != 0) {
                /* Parent. */
                exit(0);
            }
#ifndef WIN32
            else {
                /* Child. */

                /* Avoid keeping any directory in use. */
                chdir("/");

                if (!stderr_log) {
                    /*
                     * Close inherited file descriptors to avoid
                     * keeping unnecessary references.
                     */
                    close(0);
                    close(1);
                    close(2);

                    /*
                     * Redirect std{in,out,err} to /dev/null, just in
                     * case.
                     */
                    open("/dev/null", O_RDWR);
                    dup(0);
                    dup(0);
                }
            }
#endif /* !WIN32 */
        }
    }
#endif /* HAVE_FORK */

    SOCK_STARTUP;
    init_agent("snmpd");        /* do what we need to do first. */
    init_mib_modules();

    /*
     * start library 
     */
    init_snmp("snmpd");

    if ((ret = init_master_agent()) != 0) {
        /*
         * Some error opening one of the specified agent transports.  
         */
        Exit(1);                /*  Exit logs exit val for us  */
    }
#ifdef SIGTERM
    DEBUGMSGTL(("signal", "registering SIGTERM signal handler\n"));
    signal(SIGTERM, SnmpdShutDown);
#endif
#ifdef SIGINT
    DEBUGMSGTL(("signal", "registering SIGINT signal handler\n"));
    signal(SIGINT, SnmpdShutDown);
#endif
#ifdef SIGHUP
    DEBUGMSGTL(("signal", "registering SIGHUP signal handler\n"));
    signal(SIGHUP, SnmpdReconfig);
#endif
#ifdef SIGUSR1
    DEBUGMSGTL(("signal", "registering SIGUSR1 signal handler\n"));
    signal(SIGUSR1, SnmpdDump);
#endif
#ifdef SIGPIPE
    DEBUGMSGTL(("signal", "registering SIGPIPE signal handler\n"));
    signal(SIGPIPE, SIG_IGN);   /* 'Inline' failure of wayward readers */
#endif

    /*
     * Store persistent data immediately in case we crash later.  
     */
    snmp_store("snmpd");

    /*
     * Send coldstart trap if possible.  
     */
    send_easy_trap(0, 0);

#if HAVE_GETPID
    if (pid_file != NULL) {
	    /*
	     * unlink the pid_file, if it exists, prior to open.  Without
	     * doing this the open will fail if the user specified pid_file
	     * already exists.
	     */
	    unlink(pid_file);
	    fd = open(pid_file, O_CREAT | O_EXCL | O_WRONLY, 0600);
	    if (fd == -1) {
		    snmp_log_perror(pid_file);
		    if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			NETSNMP_DS_AGENT_NO_ROOT_ACCESS)) {
			    exit(1);
		    }
	    } else {
		    if ((PID = fdopen(fd, "w")) == NULL) {
			    snmp_log_perror(pid_file);
			    exit(1);
		    } else {
			    fprintf(PID, "%d\n", (int) getpid());
			    fclose(PID);
		    }
		    close(fd);
	    }
    }
#endif

#if HAVE_UNISTD_H
#ifdef HAVE_SETGID
    if ((gid = netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID, 
				  NETSNMP_DS_AGENT_GROUPID)) != 0) {
        DEBUGMSGTL(("snmpd/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(("snmpd/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

    /*
     * We're up, log our version number.  
     */
    snmp_log(LOG_INFO, "NET-SNMP version %s\n", netsnmp_get_version());
#ifdef WIN32
    agent_status = AGENT_RUNNING;
#endif
    netsnmp_addrcache_initialise();

    /*
     * Forever monitor the dest_port for incoming PDUs.  
     */
    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();
#include "mib_module_shutdown.h"
    DEBUGMSGTL(("snmpd/main", "sending shutdown trap\n"));
    SnmpTrapNodeDown();
    DEBUGMSGTL(("snmpd/main", "Bye...\n"));
    snmp_shutdown("snmpd");
    if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
				NETSNMP_DS_AGENT_LEAVE_PIDFILE) &&
	(pid_file != NULL)) {
        unlink(pid_file);
    }
#ifdef WIN32
    agent_status = AGENT_STOPPED;
#endif
    return 0;
}                               /* End main() -- snmpd */
Beispiel #11
0
int runsvdir_main(int argc, char **argv)
{
	struct stat s;
	dev_t last_dev = last_dev; /* for gcc */
	ino_t last_ino = last_ino; /* for gcc */
	time_t last_mtime = 0;
	int wstat;
	int curdir;
	int pid;
	unsigned deadline;
	unsigned now;
	unsigned stampcheck;
	char ch;
	int i;

	argv++;
	if (!*argv)
		bb_show_usage();
	if (argv[0][0] == '-') {
		switch (argv[0][1]) {
		case 'P': set_pgrp = 1;
		case '-': ++argv;
		}
		if (!*argv)
			bb_show_usage();
	}

	sig_catch(SIGTERM, s_term);
	sig_catch(SIGHUP, s_hangup);
	svdir = *argv++;
	if (argv && *argv) {
		rplog = *argv;
		if (setup_log() != 1) {
			rplog = 0;
			warnx("log service disabled");
		}
	}
	curdir = open_read(".");
	if (curdir == -1)
		fatal2_cannot("open current directory", "");
	coe(curdir);

	stampcheck = monotonic_sec();

	for (;;) {
		/* collect children */
		for (;;) {
			pid = wait_nohang(&wstat);
			if (pid <= 0)
				break;
			for (i = 0; i < svnum; i++) {
				if (pid == sv[i].pid) {
					/* runsv has gone */
					sv[i].pid = 0;
					check = 1;
					break;
				}
			}
		}

		now = monotonic_sec();
		if ((int)(now - stampcheck) >= 0) {
			/* wait at least a second */
			stampcheck = now + 1;

			if (stat(svdir, &s) != -1) {
				if (check || s.st_mtime != last_mtime
				 || s.st_ino != last_ino || s.st_dev != last_dev
				) {
					/* svdir modified */
					if (chdir(svdir) != -1) {
						last_mtime = s.st_mtime;
						last_dev = s.st_dev;
						last_ino = s.st_ino;
						check = 0;
						//if (now <= mtime)
						//	sleep(1);
						runsvdir();
						while (fchdir(curdir) == -1) {
							warn2_cannot("change directory, pausing", "");
							sleep(5);
						}
					} else
						warn2_cannot("change directory to ", svdir);
				}
			} else
				warn2_cannot("stat ", svdir);
		}

		if (rplog) {
			if ((int)(now - stamplog) >= 0) {
				write(logpipe[1], ".", 1);
				stamplog = now + 900;
			}
		}

		pfd[0].revents = 0;
		sig_block(SIGCHLD);
		deadline = (check ? 1 : 5);
		if (rplog)
			poll(pfd, 1, deadline*1000);
		else
			sleep(deadline);
		sig_unblock(SIGCHLD);

		if (pfd[0].revents & POLLIN) {
			while (read(logpipe[0], &ch, 1) > 0) {
				if (ch) {
					for (i = 6; i < rploglen; i++)
						rplog[i-1] = rplog[i];
					rplog[rploglen-1] = ch;
				}
			}
		}

		switch (exitsoon) {
		case 1:
			_exit(0);
		case 2:
			for (i = 0; i < svnum; i++)
				if (sv[i].pid)
					kill(sv[i].pid, SIGTERM);
			_exit(111);
		}
	}
	/* not reached */
	return 0;
}
Beispiel #12
0
int main(int argc, char **argv)
{
    struct stat s;
    time_t mtime =0;
    int wstat;
    int curdir;
    int pid;
    struct taia deadline;
    struct taia now;
    struct taia stampcheck;
    char ch;
    int i;

    progname =*argv++;
    if (! argv || ! *argv) usage();
    if (**argv == '-')
    {
        switch (*(*argv +1))
        {
        case 'P':
            pgrp =1;
        case '-':
            ++argv;
        }
        if (! argv || ! *argv) usage();
    }

    sig_catch(sig_term, s_term);
    sig_catch(sig_hangup, s_hangup);
    svdir =*argv++;
    if (argv && *argv)
    {
        rplog =*argv;
        if (setup_log() != 1)
        {
            rplog =0;
            warn3x("log service disabled.", 0, 0);
        }
    }
    if ((curdir =open_read(".")) == -1)
        fatal("unable to open current directory", 0);
    coe(curdir);

    taia_now(&stampcheck);

    for (;;)
    {
        /* collect children */
        for (;;)
        {
            if ((pid =wait_nohang(&wstat)) <= 0) break;
            for (i =0; i < svnum; i++)
            {
                if (pid == sv[i].pid)
                {
                    /* runsv has gone */
                    sv[i].pid =0;
                    check =1;
                    break;
                }
            }
        }

        taia_now(&now);
        if (now.sec.x < (stampcheck.sec.x -3))
        {
            /* time warp */
            warn3x("time warp: resetting time stamp.", 0, 0);
            taia_now(&stampcheck);
            taia_now(&now);
            if (rplog) taia_now(&stamplog);
        }
        if (taia_less(&now, &stampcheck) == 0)
        {
            /* wait at least a second */
            taia_uint(&deadline, 1);
            taia_add(&stampcheck, &now, &deadline);

            if (stat(svdir, &s) != -1)
            {
                if (check || \
                        s.st_mtime != mtime || s.st_ino != ino || s.st_dev != dev)
                {
                    /* svdir modified */
                    if (chdir(svdir) != -1)
                    {
                        mtime =s.st_mtime;
                        dev =s.st_dev;
                        ino =s.st_ino;
                        check =0;
                        if (now.sec.x <= (4611686018427387914ULL +(uint64)mtime))
                            sleep(1);
                        runsvdir();
                        while (fchdir(curdir) == -1)
                        {
                            warn("unable to change directory, pausing", 0);
                            sleep(5);
                        }
                    }
                    else
                        warn("unable to change directory to ", svdir);
                }
            }
            else
                warn("unable to stat ", svdir);
        }

        if (rplog)
            if (taia_less(&now, &stamplog) == 0)
            {
                write(logpipe[1], ".", 1);
                taia_uint(&deadline, 900);
                taia_add(&stamplog, &now, &deadline);
            }
        /* half a second */
        deadline.sec.x =0;
        deadline.nano =500000000UL;
        deadline.atto =0;
        taia_add(&deadline, &now, &deadline);

        sig_block(sig_child);
        if (rplog)
            iopause(io, 1, &deadline, &now);
        else
            iopause(0, 0, &deadline, &now);
        sig_unblock(sig_child);

        if (rplog && (io[0].revents | IOPAUSE_READ))
            while (read(logpipe[0], &ch, 1) > 0)
                if (ch)
                {
                    for (i =6; i < rploglen; i++)
                        rplog[i -1] =rplog[i];
                    rplog[rploglen -1] =ch;
                }

        switch(exitsoon)
        {
        case 1:
            _exit(0);
        case 2:
            for (i =0; i < svnum; i++) if (sv[i].pid) kill(sv[i].pid, SIGTERM);
            _exit(111);
        }
    } /* for (;;) */
    /* not reached */
    _exit(0);
}
Beispiel #13
0
int main(int argc, const char * argv[]) {
	
	setup_log();
	
	double destination[3] = {0, 5, 3} ;
	
	double vitesse[3] = {0} ;
	double position[3] = {0} ;
	
	double propulsion_verticale = 0, propulsion_horizontale = 0 ;
	
	int  i = 1;
	
	do {
		double delta_t = get_delta_t(); ;
		
		double acceleration[3];
		double deplacement[3] = { 0 };
		
		acquerir_acceleration(acceleration);
		
		double v0[3];
		matrix_col_copy(vitesse, v0);
		
		// vitesse = acceleration * ∆t + v0
			matrix_k(acceleration, delta_t, acceleration);
			matrix_col_sum(acceleration, v0, vitesse);
		
		// vitesse = 1/2 . acceleration * ∆t^2 + v0 . ∆t
			matrix_k(acceleration, delta_t, acceleration);
			matrix_k(acceleration, 0.5, acceleration);
		
			matrix_k(v0, delta_t, v0);
		
			matrix_col_sum(deplacement, acceleration, deplacement);
			matrix_col_sum(deplacement, v0, deplacement);
		
		//On calcul la nouvelle position du dirigeable
			double θ = acquerir_angle_nord() / (2 * PI) ; //conversion degré/radians
		
			double matrice_passage[3][3] = {
				{ cos(θ), sin(θ),  0 },
				{ -sin(θ), cos(θ), 0 },
				{	0	 ,	0	 , 1 }
			};
		
			matrix_product(deplacement, matrice_passage, deplacement); //on calcul les coordonées de d dans (i,j)
			matrix_col_sum(deplacement, position, position); // on ajoute le déplacement à la position du dirigeable
		
		// et on agit en fonction
		
			//on inverse la matrice de passage afin d'aller de (i, j) vers (k, l)
			matrice_passage[0][1] *= -1 ;
			matrice_passage[1][0] *= -1 ;
		
			//les coordonées de la destination, dans le référentiel du ballon
			double dest[3] ;
			matrix_col_copy(destination, dest) ;
			matrix_col_diff(dest, position, dest);
			matrix_product(dest, matrice_passage, dest);
		
			char tourner = 0 ;
			double angle_destination = atan(dest[0]/dest[1]);
			double distance_destination = sqrt(pow(dest[0], 2) + pow(dest[1], 2));
		
			// Dans le plan (x, y)
			if(distance_destination > 0.1){
				if(dest[1] > 0 && isClose(angle_destination, 0, PI/16)){
					if(vitesse[1] > .1 && acceleration[1] > 0){
						propulsion_horizontale -= .1 ;
					}
						
					if(vitesse[1] < .1){
						propulsion_horizontale += .1 ;
					}
				}
				else {
					propulsion_horizontale = .2 ;
					
					if(dest[0] < 0){
						tourner = -1 ;
					}
					else if(dest[0] > 0){
						tourner = 1 ;
					}
				}
			}
			else {
				if (vitesse[1] > 0.01) { //on ralenti à l'approche de l'objectif
					propulsion_horizontale = -7 ;
				}
				else {
					propulsion_horizontale = 0 ;
				}
			}
		
		
			// on adapte la propulsion verticale
			if(vitesse[2] > 0.1){
				propulsion_verticale-- ;
				if(vitesse[2] > 1){
					propulsion_verticale -= 10;
				}
			}
			else if(vitesse[2] < - 0.1){
				propulsion_verticale++ ;
			
				if(vitesse[2] < -1){
					propulsion_verticale += 10;
				}
			}
			else if(position[2] < destination[2]){
				propulsion_verticale++;
			}
			else if (position[2] > destination[2]){
				propulsion_verticale-- ;
			}
	
		
			//On réajuste ensuite les demandes moteur
				if(propulsion_verticale > 100){
					propulsion_verticale = 100 ;
				}
				else if(propulsion_verticale < 1){
					propulsion_verticale = 1 ;
				}
		
				if(propulsion_horizontale > 100){
					propulsion_horizontale = 100 ;
				}
				else if(propulsion_horizontale < -100){
					propulsion_horizontale = -100 ;
				}
		
			double norme = sqrt(pow(propulsion_verticale,2) + pow(propulsion_horizontale,2)) ;
		
			// si on demande une trop forte poussée aux moteurs, on réajuste la demande
			// en donnant la priorité à la poussée verticale
			if(norme > 100){
				norme = 100 ;
				int signe = propulsion_horizontale < 0 ? -1 : 1 ;
				propulsion_horizontale = signe * sqrt(pow(norme, 2) - pow(propulsion_verticale,2)) ;
				
			}
		
			double angle_moteur_gauche = atan(propulsion_horizontale / propulsion_verticale) ;
			double angle_moteur_droit = angle_moteur_gauche ;
		
			if(tourner != 0){
				angle_moteur_gauche *= tourner ;
				angle_moteur_droit *= -tourner ;
			}
		
			adapter_propulsion(norme, angle_moteur_gauche, angle_moteur_droit);
		
		if(i % 5 == 0){ //On complète le log toutes les 5 périodes
			add_log(acceleration, vitesse, position, dest, propulsion_verticale, propulsion_horizontale, angle_moteur_gauche, angle_moteur_droit, θ);
		}
		
	} while(i++ < 1200) ;
		
	matrix_col_print(position);
	close_log();
	
    return 0;
}
Beispiel #14
0
main(int argc, char *argv[])
#endif
{
    char            options[128] = "aAc:CdD::fhHI:l:L:m:M:p:P:qrsS:UvV-:";
    int             arg, i, ret;
    int             dont_fork = 0;
    int             dont_zero_log = 0;
    int             syslog_log = 0;
    int             uid = 0, gid = 0;
    int             agent_mode = -1;
    char            logfile[PATH_MAX + 1] = { 0 };
    char           *cptr, **argvptr;
    char           *pid_file = NULL;
    char            option_compatability[] = "-Le";
#if HAVE_GETPID
    int fd;
    FILE           *PID;
#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 */
    
    /*
     * register signals ASAP to prevent default action (usually core)
     * for signals during startup...
     */
#ifdef SIGTERM
    DEBUGMSGTL(("signal", "registering SIGTERM signal handler\n"));
    signal(SIGTERM, SnmpdShutDown);
#endif
#ifdef SIGINT
    DEBUGMSGTL(("signal", "registering SIGINT signal handler\n"));
    signal(SIGINT, SnmpdShutDown);
#endif
#ifdef SIGHUP
    DEBUGMSGTL(("signal", "registering SIGHUP signal handler\n"));
    signal(SIGHUP, SnmpdReconfig);
#endif
#ifdef SIGUSR1
    DEBUGMSGTL(("signal", "registering SIGUSR1 signal handler\n"));
    signal(SIGUSR1, SnmpdDump);
#endif
#ifdef SIGPIPE
    DEBUGMSGTL(("signal", "registering SIGPIPE signal handler\n"));
    signal(SIGPIPE, SIG_IGN);   /* 'Inline' failure of wayward readers */
#endif
#ifdef SIGXFSZ
    signal(SIGXFSZ, SnmpdCatchRandomSignal);
#endif

#ifdef LOGFILE
    strncpy(logfile, LOGFILE, PATH_MAX);
#endif

#ifdef NO_ROOT_ACCESS
    /*
     * Default to no.  
     */
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			   NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1);
#endif
    /*
     * Default to NOT running an AgentX master.  
     */
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			   NETSNMP_DS_AGENT_AGENTX_MASTER, 0);
    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_TIMEOUT, -1);
    netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID,
                       NETSNMP_DS_AGENT_AGENTX_RETRIES, -1);

    /*
     * Add some options if they are available.  
     */
#if HAVE_UNISTD_H
    strcat(options, "g:u:");
#endif
#if defined(USING_AGENTX_SUBAGENT_MODULE)|| defined(USING_AGENTX_MASTER_MODULE)
    strcat(options, "x:");
#endif
#ifdef USING_AGENTX_SUBAGENT_MODULE
    strcat(options, "X");
#endif

    /*
     * This is incredibly ugly, but it's probably the simplest way
     *  to handle the old '-L' option as well as the new '-Lx' style
     */
    for (i=0; i<argc; i++) {
        if (!strcmp(argv[i], "-L"))
            argv[i] = option_compatability;            
    }

    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(argv[0]);
            }
            if (strcasecmp(optarg, "version") == 0) {
                version();
            }

            handle_long_opt(optarg);
            break;

        case 'a':
            log_addresses++;
            break;

        case 'A':
            dont_zero_log = 1;
            break;

        case 'c':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, 
				      NETSNMP_DS_LIB_OPTIONALCONFIG, optarg);
            } else {
                usage(argv[0]);
            }
            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(++snmp_dump_packet);
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_VERBOSE, 1);
            break;

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

        case 'f':
            dont_fork = 1;
            break;

#if HAVE_UNISTD_H
        case 'g':
            if (optarg != NULL) {
                netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_GROUPID, atoi(optarg));
            } else {
                usage(argv[0]);
            }
            break;
#endif

        case 'h':
            usage(argv[0]);
            break;

        case 'H':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1);
            init_agent("snmpd");        /* register our .conf handlers */
            init_mib_modules();
            init_snmp("snmpd");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            exit(0);

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

        case 'l':
            printf("Warning: -l option is deprecated, use -Lf <file> instead\n");
            if (optarg != NULL) {
                if (strlen(optarg) > PATH_MAX) {
                    fprintf(stderr,
                            "%s: logfile path too long (limit %d chars)\n",
                            argv[0], PATH_MAX);
                    exit(1);
                }
                strncpy(logfile, optarg, PATH_MAX);
            } else {
                usage(argv[0]);
            }
            break;

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

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

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

        case 'P':
            printf("Warning: -P option is deprecated, use -p instead\n");
        case 'p':
            if (optarg != NULL) {
                pid_file = optarg;
            } else {
                usage(argv[0]);
            }
            break;

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

        case 'r':
            netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_NO_ROOT_ACCESS);
            break;

        case 's':
            printf("Warning: -s option is deprecated, use -Lsd instead\n");
            syslog_log = 1;
            break;

        case 'S':
            printf("Warning: -S option is deprecated, use -Ls <facility> instead\n");
            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(argv[0]);
                }
            } else {
                fprintf(stderr, "no syslog facility specified\n");
                usage(argv[0]);
            }
            break;

        case 'U':
            netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_LEAVE_PIDFILE);
            break;

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

                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(argv[0]);
            }
            break;
#endif

        case 'v':
            version();

        case 'V':
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_VERBOSE, 1);
            break;

#if defined(USING_AGENTX_SUBAGENT_MODULE)|| defined(USING_AGENTX_MASTER_MODULE)
        case 'x':
            if (optarg != NULL) {
                netsnmp_ds_set_string(NETSNMP_DS_APPLICATION_ID, 
				      NETSNMP_DS_AGENT_X_SOCKET, optarg);
            } else {
                usage(argv[0]);
            }
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_AGENTX_MASTER, 1);
            break;
#endif

        case 'X':
#if defined(USING_AGENTX_SUBAGENT_MODULE)
            agent_mode = SUB_AGENT;
#else
            fprintf(stderr, "%s: Illegal argument -X:"
		            "AgentX support not compiled in.\n", argv[0]);
            usage(argv[0]);
            exit(1);
#endif
            break;

        default:
            usage(argv[0]);
            break;
        }
    }

    if (optind < argc) {
        /*
         * 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 = (char*)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)));
    }

    setup_log(0, dont_zero_log, 0, syslog_log, logfile);

    /*
     * Initialize a argv set to the current for restarting the agent.   
     */
    argvrestartp = (char **)malloc((argc + 2) * sizeof(char *));
    argvptr = argvrestartp;
    for (i = 0, ret = 1; i < argc; i++) {
        ret += strlen(argv[i]) + 1;
    }
    argvrestart = (char *) malloc(ret);
    argvrestartname = (char *) malloc(strlen(argv[0]) + 1);
    if (!argvrestartp || !argvrestart || !argvrestartname) {
        fprintf(stderr, "malloc failure processing argvrestart\n");
        exit(1);
    }
    strcpy(argvrestartname, argv[0]);
    if (agent_mode == -1) {
        if (strstr(argvrestartname, "agentxd") != NULL) {
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_ROLE, SUB_AGENT);
        } else {
            netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_ROLE, MASTER_AGENT);
        }
    } else {
        netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_ROLE, agent_mode);
    }

    for (cptr = argvrestart, i = 0; i < argc; i++) {
        strcpy(cptr, argv[i]);
        *(argvptr++) = cptr;
        cptr += strlen(argv[i]) + 1;
    }
    *cptr = 0;
    *argvptr = NULL;

#ifdef BUFSIZ
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
#endif
    /*
     * Initialize the world.  Detach from the shell.  Create initial user.  
     */
    if(!dont_fork) {
        int quit = ! netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                                            NETSNMP_DS_AGENT_QUIT_IMMEDIATELY);
        ret = netsnmp_daemonize(quit, snmp_stderrlog_status());
        /*
         * xxx-rks: do we care if fork fails? I think we should...
         */
        if(ret != 0)
            Exit(1);                /*  Exit logs exit val for us  */
    }

    SOCK_STARTUP;
    init_agent("snmpd");        /* do what we need to do first. */
    init_mib_modules();

    /*
     * start library 
     */
    init_snmp("snmpd");

    if ((ret = init_master_agent()) != 0) {
        /*
         * Some error opening one of the specified agent transports.  
         */
        Exit(1);                /*  Exit logs exit val for us  */
    }

    /*
     * Store persistent data immediately in case we crash later.  
     */
    snmp_store("snmpd");

    /*
     * Send coldstart trap if possible.  
     */
    send_easy_trap(0, 0);

#if HAVE_GETPID
    if (pid_file != NULL) {
        /*
         * unlink the pid_file, if it exists, prior to open.  Without
         * doing this the open will fail if the user specified pid_file
         * already exists.
         */
        unlink(pid_file);
        fd = open(pid_file, O_CREAT | O_EXCL | O_WRONLY, 0600);
        if (fd == -1) {
            snmp_log_perror(pid_file);
            if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
                                        NETSNMP_DS_AGENT_NO_ROOT_ACCESS)) {
                exit(1);
            }
        } else {
            if ((PID = fdopen(fd, "w")) == NULL) {
                snmp_log_perror(pid_file);
                exit(1);
            } else {
                fprintf(PID, "%d\n", (int) getpid());
                fclose(PID);
            }
            close(fd);
        }
    }
#endif

#if HAVE_UNISTD_H
#ifdef HAVE_SETGID
    if ((gid = netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID, 
				  NETSNMP_DS_AGENT_GROUPID)) != 0) {
        DEBUGMSGTL(("snmpd/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(("snmpd/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

    /*
     * We're up, log our version number.  
     */
    snmp_log(LOG_INFO, "NET-SNMP version %s\n", netsnmp_get_version());
#ifdef WIN32SERVICE
    agent_status = AGENT_RUNNING;
#endif
    netsnmp_addrcache_initialise();

    /*
     * Forever monitor the dest_port for incoming PDUs.  
     */
    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();
#include "mib_module_shutdown.h"
    DEBUGMSGTL(("snmpd/main", "sending shutdown trap\n"));
    SnmpTrapNodeDown();
    DEBUGMSGTL(("snmpd/main", "Bye...\n"));
    snmp_shutdown("snmpd");
#ifdef SHUTDOWN_AGENT_CLEANLY /* broken code */
    /* these attempt to free all known memory, but result in double frees */
    shutdown_master_agent();
    shutdown_agent();
#endif

    if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
				NETSNMP_DS_AGENT_LEAVE_PIDFILE) &&
	(pid_file != NULL)) {
        unlink(pid_file);
    }
#ifdef WIN32SERVICE
    agent_status = AGENT_STOPPED;
#endif

    SNMP_FREE(argvrestartname);
    SNMP_FREE(argvrestart);
    SNMP_FREE(argvrestartp);
    SOCK_CLEANUP;
    return 0;
}                               /* End main() -- snmpd */
Beispiel #15
0
/*******************************************************************-o-******
 * receive
 *
 * Parameters:
 *      
 * Returns:
 *	0	On success.
 *	-1	System error.
 *
 * Infinite while-loop which monitors incoming messges for the agent.
 * Invoke the established message handlers for incoming messages on a per
 * port basis.  Handle timeouts.
 */
static int
receive(void)
{
    int             numfds;
    fd_set          readfds, writefds, exceptfds;
    struct timeval  timeout, *tvp = &timeout;
    struct timeval  sched, *svp = &sched, now, *nvp = &now;
    int             count, block, i;
#ifdef	USING_SMUX_MODULE
    int             sd;
#endif                          /* USING_SMUX_MODULE */


    /*
     * Set the 'sched'uled timeout to the current time + one TIMETICK.
     */
    gettimeofday(nvp, (struct timezone *) NULL);
    svp->tv_usec = nvp->tv_usec + TIMETICK;
    svp->tv_sec = nvp->tv_sec;

    while (svp->tv_usec >= ONE_SEC) {
        svp->tv_usec -= ONE_SEC;
        svp->tv_sec++;
    }

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

    /*
     * Loop-forever: execute message handlers for sockets with data,
     * reset the 'sched'uler.
     */
    while (netsnmp_running) {
        if (reconfig) {
            reconfig = 0;
            snmp_log(LOG_INFO, "Reconfiguring daemon\n");
	    /*  Stop and restart logging.  This allows logfiles to be
		rotated etc.  */
	    snmp_disable_log();
	    setup_log(1, 0, 0, 0, NULL);
	    snmp_log(LOG_INFO, "NET-SNMP version %s restarted\n",
		     netsnmp_get_version());
            update_config();
            send_easy_trap(SNMP_TRAP_ENTERPRISESPECIFIC, 3);
        }

        for (i = 0; i < NUM_EXTERNAL_SIGS; i++) {
            if (external_signal_scheduled[i]) {
                external_signal_scheduled[i]--;
                external_signal_handler[i](i);
            }
        }

        tvp = &timeout;
        tvp->tv_sec = 0;
        tvp->tv_usec = TIMETICK;

        numfds = 0;
        FD_ZERO(&readfds);
        FD_ZERO(&writefds);
        FD_ZERO(&exceptfds);
        block = 0;
        snmp_select_info(&numfds, &readfds, tvp, &block);
        if (block == 1) {
            tvp = NULL;         /* block without timeout */
	}

#ifdef	USING_SMUX_MODULE
        if (smux_listen_sd >= 0) {
            FD_SET(smux_listen_sd, &readfds);
            numfds =
                smux_listen_sd >= numfds ? smux_listen_sd + 1 : numfds;
            for (i = 0; i < sdlen; i++) {
                FD_SET(sdlist[i], &readfds);
                numfds = sdlist[i] >= numfds ? sdlist[i] + 1 : numfds;
            }
        }
#endif                          /* USING_SMUX_MODULE */

        for (i = 0; i < external_readfdlen; i++) {
            FD_SET(external_readfd[i], &readfds);
            if (external_readfd[i] >= numfds)
                numfds = external_readfd[i] + 1;
        }
        for (i = 0; i < external_writefdlen; i++) {
            FD_SET(external_writefd[i], &writefds);
            if (external_writefd[i] >= numfds)
                numfds = external_writefd[i] + 1;
        }
        for (i = 0; i < external_exceptfdlen; i++) {
            FD_SET(external_exceptfd[i], &exceptfds);
            if (external_exceptfd[i] >= numfds)
                numfds = external_exceptfd[i] + 1;
        }

    reselect:
        DEBUGMSGTL(("snmpd/select", "select( numfds=%d, ..., tvp=%p)\n",
                    numfds, tvp));
        count = select(numfds, &readfds, &writefds, &exceptfds, tvp);
        DEBUGMSGTL(("snmpd/select", "returned, count = %d\n", count));

        if (count > 0) {

#ifdef USING_SMUX_MODULE
            /*
             * handle the SMUX sd's 
             */
            if (smux_listen_sd >= 0) {
                for (i = 0; i < sdlen; i++) {
                    if (FD_ISSET(sdlist[i], &readfds)) {
                        if (smux_process(sdlist[i]) < 0) {
                            for (; i < (sdlen - 1); i++) {
                                sdlist[i] = sdlist[i + 1];
                            }
                            sdlen--;
                        }
                    }
                }
                /*
                 * new connection 
                 */
                if (FD_ISSET(smux_listen_sd, &readfds)) {
                    if ((sd = smux_accept(smux_listen_sd)) >= 0) {
                        sdlist[sdlen++] = sd;
                    }
                }
            }
#endif                          /* USING_SMUX_MODULE */

            snmp_read(&readfds);

            for (i = 0; count && (i < external_readfdlen); i++) {
                if (FD_ISSET(external_readfd[i], &readfds)) {
                    DEBUGMSGTL(("snmpd/select", "readfd[%d] = %d\n",
                                i, external_readfd[i]));
                    external_readfdfunc[i] (external_readfd[i],
                                            external_readfd_data[i]);
                    FD_CLR(external_readfd[i], &readfds);
                    count--;
                }
            }
            for (i = 0; count && (i < external_writefdlen); i++) {
                if (FD_ISSET(external_writefd[i], &writefds)) {
                    DEBUGMSGTL(("snmpd/select", "writefd[%d] = %d\n",
                                i, external_writefd[i]));
                    external_writefdfunc[i] (external_writefd[i],
                                             external_writefd_data[i]);
                    FD_CLR(external_writefd[i], &writefds);
                    count--;
                }
            }
            for (i = 0; count && (i < external_exceptfdlen); i++) {
                if (FD_ISSET(external_exceptfd[i], &exceptfds)) {
                    DEBUGMSGTL(("snmpd/select", "exceptfd[%d] = %d\n",
                                i, external_exceptfd[i]));
                    external_exceptfdfunc[i] (external_exceptfd[i],
                                              external_exceptfd_data[i]);
                    FD_CLR(external_exceptfd[i], &exceptfds);
                    count--;
                }
            }

        } else
            switch (count) {
            case 0:
                snmp_timeout();
                break;
            case -1:
                if (errno == EINTR) {
                    /*
                     * likely that we got a signal. Check our special signal
                     * flags before retrying select.
                     */
		    if (netsnmp_running && !reconfig) {
                        goto reselect;
		    }
                    continue;
                } else {
                    snmp_log_perror("select");
                }
                return -1;
            default:
                snmp_log(LOG_ERR, "select returned %d\n", count);
                return -1;
            }                   /* endif -- count>0 */




        /*
         * If the time 'now' is greater than the 'sched'uled time, then:
         *
         *    Check alarm and event timers.
         *    Reset the 'sched'uled time to current time + one TIMETICK.
         *    Age the cache network addresses (from whom messges have
         *        been received).
         */
        gettimeofday(nvp, (struct timezone *)NULL);

        if (nvp->tv_sec > svp->tv_sec || (nvp->tv_sec == svp->tv_sec &&
					  nvp->tv_usec > svp->tv_usec)) {
            svp->tv_usec = nvp->tv_usec + TIMETICK;
            svp->tv_sec = nvp->tv_sec;

            while (svp->tv_usec >= ONE_SEC) {
                svp->tv_usec -= ONE_SEC;
                svp->tv_sec++;
            }
        }

        /*
         * endif -- now>sched 
         */
        /*
         * run requested alarms 
         */
        run_alarms();

        netsnmp_check_outstanding_agent_requests();

    }                           /* endwhile */

    snmp_log(LOG_INFO, "Received TERM or STOP signal...  shutting down...\n");
    return 0;

}                               /* end receive() */
Beispiel #16
0
int main(int argc, char **argv)
{
    int    fd                           = 0;
    pid_t  pid				= 0;	/* child pid */
    pid_t  sid				= 0;

    init();

    /*
     *	set up databases
     */
    if (!db_init()) {
        log_msg(INFO, "Couldn't create databases");
        exit(EXIT_FAILURE);
    }

    /*
     *	Parse command line options
     */
    handle_lispd_command_line(argc, argv);

    /*
     *	see if we need to daemonize, and if so, do it
     */
    if (lispd_config.daemonize) {
        log_msg(INFO, "lispd is backgrounding...");
        if ((pid = fork()) < 0) {
            exit(EXIT_FAILURE);
        }

        if (pid > 0) {
            log_msg(INFO, "done. Running as PID %d", pid);
            exit(EXIT_SUCCESS);
        }
        umask(0);
        if ((sid = setsid()) < 0)
            exit(EXIT_FAILURE);
        if ((chdir("/")) < 0)
            exit(EXIT_FAILURE);

        /*
         * Redirect standard files to /dev/null save fd in
         * case we need to get back to stdout later
         */
        fd = dup(fileno(stdout));
    }

    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);
    signal(SIGQUIT, signal_handler);

    init_timers();

    /*
     * Check if lispd is already running. Only allow one instance!
     */
    if (!get_process_lock(getpid())) {
        log_msg(FATAL, "lispd already running, please stop before restarting. If this seems wrong"
                " remove %s.", LISPD_LOCKFILE);


        printf("lispd already running, please stop before restarting.\n If this appears wrong,"
               " remove %s.\n", LISPD_LOCKFILE);
        exit(EXIT_FAILURE);
    }

    if (!setup_netlink()) {
        log_msg(FATAL, "Can't set up netlink socket (is the kernel module loaded?), exiting...");
        die(EXIT_FAILURE);
    }
    if (!setup_rtnetlink()) {
        log_msg(FATAL, "Can't setup rtnetlink socket, exiting...");
        die(EXIT_FAILURE);
    }

    if (!register_lispd_process()) {
        log_msg(FATAL, "Couldn't register lispd process, exiting...");
        die(EXIT_FAILURE);
    }

    log_msg(INFO, "Version %d.%d.%d starting up...",
            MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION);

    /*
     * now build the v4/v6 receive sockets
     */
    if (build_receive_sockets() == 0) {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }

    if (build_event_socket() == 0)
    {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }
    log_msg(INFO, "Built receive/event sockets");

    /*
     *	Now do the config file
     */
    if (handle_lispd_config_file()) {
        log_msg(FATAL, "Fatal error parsing config file.");
        dump_fatal_error();
        die(EXIT_FAILURE);
    }

    /*
     *	set up syslog now, checking to see if we're daemonizing...
     */
    setup_log();

    log_msg(INFO, "Read config file");

    if (!install_database_mappings()) {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }
#ifdef DEADCODE
    if (!install_map_cache_entries())
        log_msg(INFO, "Could not install static map-cache entries");
#endif
    if (!map_register())
        log_msg(INFO, "Could not map register.");

    set_timer(RLOCProbeScan, RLOC_PROBE_CHECK_INTERVAL);

    clear_map_cache();

    listen_on_well_known_port();

    dump_info_file();
    event_loop();
    log_msg(INFO, "exiting...");		/* event_loop returned bad */
    remove_process_lock();
    exit(0);
}
Beispiel #17
0
Datei: init.c Projekt: rudyLi/fio
/*
 * Adds a job to the list of things todo. Sanitizes the various options
 * to make sure we don't have conflicts, and initializes various
 * members of td.
 */
static int add_job(struct thread_data *td, const char *jobname, int job_add_num)
{
	const char *ddir_str[] = { NULL, "read", "write", "rw", NULL,
				   "randread", "randwrite", "randrw" };
	unsigned int i;
	char fname[PATH_MAX];
	int numjobs, file_alloced;

	/*
	 * the def_thread is just for options, it's not a real job
	 */
	if (td == &def_thread)
		return 0;

	/*
	 * if we are just dumping the output command line, don't add the job
	 */
	if (dump_cmdline) {
		put_job(td);
		return 0;
	}

	if (profile_td_init(td))
		goto err;

	if (ioengine_load(td))
		goto err;

	if (td->o.use_thread)
		nr_thread++;
	else
		nr_process++;

	if (td->o.odirect)
		td->io_ops->flags |= FIO_RAWIO;

	file_alloced = 0;
	if (!td->o.filename && !td->files_index && !td->o.read_iolog_file) {
		file_alloced = 1;

		if (td->o.nr_files == 1 && exists_and_not_file(jobname))
			add_file(td, jobname);
		else {
			for (i = 0; i < td->o.nr_files; i++) {
				sprintf(fname, "%s.%d.%d", jobname,
							td->thread_number, i);
				add_file(td, fname);
			}
		}
	}

	if (fixup_options(td))
		goto err;

	flow_init_job(td);

	/*
	 * IO engines only need this for option callbacks, and the address may
	 * change in subprocesses.
	 */
	if (td->eo)
		*(struct thread_data **)td->eo = NULL;

	if (td->io_ops->flags & FIO_DISKLESSIO) {
		struct fio_file *f;

		for_each_file(td, f, i)
			f->real_file_size = -1ULL;
	}

	td->mutex = fio_mutex_init(0);

	td->ts.clat_percentiles = td->o.clat_percentiles;
	if (td->o.overwrite_plist)
		memcpy(td->ts.percentile_list, td->o.percentile_list, sizeof(td->o.percentile_list));
	else
		memcpy(td->ts.percentile_list, def_percentile_list, sizeof(def_percentile_list));

	td->ts.clat_stat[0].min_val = td->ts.clat_stat[1].min_val = ULONG_MAX;
	td->ts.slat_stat[0].min_val = td->ts.slat_stat[1].min_val = ULONG_MAX;
	td->ts.lat_stat[0].min_val = td->ts.lat_stat[1].min_val = ULONG_MAX;
	td->ts.bw_stat[0].min_val = td->ts.bw_stat[1].min_val = ULONG_MAX;
	td->ddir_seq_nr = td->o.ddir_seq_nr;

	if ((td->o.stonewall || td->o.new_group) && prev_group_jobs) {
		prev_group_jobs = 0;
		groupid++;
	}

	td->groupid = groupid;
	prev_group_jobs++;

	if (init_random_state(td, td->rand_seeds, sizeof(td->rand_seeds))) {
		td_verror(td, errno, "init_random_state");
		goto err;
	}

	if (setup_rate(td))
		goto err;

	if (td->o.write_lat_log) {
		setup_log(&td->lat_log, td->o.log_avg_msec);
		setup_log(&td->slat_log, td->o.log_avg_msec);
		setup_log(&td->clat_log, td->o.log_avg_msec);
	}
	if (td->o.write_bw_log)
		setup_log(&td->bw_log, td->o.log_avg_msec);
	if (td->o.write_iops_log)
		setup_log(&td->iops_log, td->o.log_avg_msec);

	if (!td->o.name)
		td->o.name = strdup(jobname);

	if (!terse_output) {
		if (!job_add_num) {
			if (!strcmp(td->io_ops->name, "cpuio")) {
				log_info("%s: ioengine=cpu, cpuload=%u,"
					 " cpucycle=%u\n", td->o.name,
							td->o.cpuload,
							td->o.cpucycle);
			} else {
				char *c1, *c2, *c3, *c4;

				c1 = to_kmg(td->o.min_bs[DDIR_READ]);
				c2 = to_kmg(td->o.max_bs[DDIR_READ]);
				c3 = to_kmg(td->o.min_bs[DDIR_WRITE]);
				c4 = to_kmg(td->o.max_bs[DDIR_WRITE]);

				log_info("%s: (g=%d): rw=%s, bs=%s-%s/%s-%s,"
					 " ioengine=%s, iodepth=%u\n",
						td->o.name, td->groupid,
						ddir_str[td->o.td_ddir],
						c1, c2, c3, c4,
						td->io_ops->name,
						td->o.iodepth);

				free(c1);
				free(c2);
				free(c3);
				free(c4);
			}
		} else if (job_add_num == 1)
			log_info("...\n");
	}

	/*
	 * recurse add identical jobs, clear numjobs and stonewall options
	 * as they don't apply to sub-jobs
	 */
	numjobs = td->o.numjobs;
	while (--numjobs) {
		struct thread_data *td_new = get_new_job(0, td, 1);

		if (!td_new)
			goto err;

		td_new->o.numjobs = 1;
		td_new->o.stonewall = 0;
		td_new->o.new_group = 0;

		if (file_alloced) {
			td_new->o.filename = NULL;
			td_new->files_index = 0;
			td_new->files_size = 0;
			td_new->files = NULL;
		}

		job_add_num = numjobs - 1;

		if (add_job(td_new, jobname, job_add_num))
			goto err;
	}

	return 0;
err:
	put_job(td);
	return -1;
}
Beispiel #18
0
int main()
{
    pcap_if_t *alldevsp , *device;
    pcap_t *handle; //Handle of the device that shall be sniffed
    char* databaseName = "database.sqlite3";
 
    char errbuf[100] , *devname , devs[100][100];
    int count = 1 , n;
     
    //First get the list of available devices
    printf("Finding available devices ... ");
    if( pcap_findalldevs( &alldevsp , errbuf) )
    {
        printf("Error finding devices : %s" , errbuf);
        exit(1);
    }
    printf("Done");
     
    //Print the available devices
    printf("\nAvailable Devices are :\n");
    for(device = alldevsp ; device != NULL ; device = device->next)
    {
        printf("%d. %s - %s\n" , count , device->name , device->description);
        if(device->name != NULL)
        {
            strncpy(devs[count] , device->name, 16);
        }
        count++;
    }
     
    //Ask user which device to sniff
    printf("Enter the number of the device you want to sniff : ");
    scanf("%d" , &n);
    devname = devs[n];
     
    //Open the device for sniffing
    printf("Opening device %s for sniffing ... " , devname);
    handle = pcap_open_live(devname , 65536 , 1 , 0 , errbuf);
     
    if (handle == NULL)
    {
        fprintf(stderr, "Couldn't open device %s : %s\n" , devname , errbuf);
        exit(1);
    }
    printf("Done\n");
     
    setup_log();

    if(setup_database(databaseName)){
        printf("Database is setup.\n");
    }
    else {
        printf("No database file exists.\n");
    }
     

    //Put the device in sniff loop
    pcap_loop(handle , -1 , process_packet , NULL);
     
    return 0;  
}