hyperdbbackend (size_t keybytes, parameters const& keyvalues,
        scheduler& scheduler, beast::journal journal)
        : m_deletepath (false)
        , m_journal (journal)
        , m_keybytes (keybytes)
        , m_scheduler (scheduler)
        , m_batch (*this, scheduler)
        , m_name (keyvalues ["path"].tostdstring ())
    {
        if (m_name.empty ())
            throw std::runtime_error ("missing path in leveldbfactory backend");

        hyperleveldb::options options;
        options.create_if_missing = true;

        if (keyvalues ["cache_mb"].isempty ())
        {
            options.block_cache = hyperleveldb::newlrucache (getconfig ().getsize (sihashnodedbcache) * 1024 * 1024);
        }
        else
        {
            options.block_cache = hyperleveldb::newlrucache (keyvalues["cache_mb"].getintvalue() * 1024l * 1024l);
        }

        if (keyvalues ["filter_bits"].isempty())
        {
            if (getconfig ().node_size >= 2)
                m_filter_policy.reset  (hyperleveldb::newbloomfilterpolicy (10));
        }
        else if (keyvalues ["filter_bits"].getintvalue() != 0)
        {
            m_filter_policy.reset (hyperleveldb::newbloomfilterpolicy (keyvalues ["filter_bits"].getintvalue ()));
        }
        options.filter_policy = m_filter_policy.get();

        if (! keyvalues["open_files"].isempty ())
        {
            options.max_open_files = keyvalues ["open_files"].getintvalue();
        }

        hyperleveldb::db* db = nullptr;
        hyperleveldb::status status = hyperleveldb::db::open (options, m_name, &db);
        if (!status.ok () || !db)
            throw std::runtime_error (std::string (
                "unable to open/create hyperleveldb: ") + status.tostring());

        m_db.reset (db);
    }
示例#2
0
/* $begin parse_uri */
int parse_uri(char *uri, char *filename, char *cgiargs) 
{
    char *ptr;
    char tmpcwd[MAXLINE];
    strcpy(tmpcwd,cwd);
    strcat(tmpcwd,"/");

    if (!strstr(uri, "cgi-bin")) 
    {  /* Static content */
	strcpy(cgiargs, "");
	strcpy(filename, strcat(tmpcwd,getconfig("root")));
	strcat(filename, uri);
	if (uri[strlen(uri)-1] == '/')
	    strcat(filename, "home.html");
	return 1;
    }
    else 
    {  /* Dynamic content */
	ptr = index(uri, '?');
	if (ptr) 
	{
	    strcpy(cgiargs, ptr+1);
	    *ptr = '\0';
	}
	else 
	    strcpy(cgiargs, "");
	strcpy(filename, cwd);
	strcat(filename, uri);
	return 0;
    }
}
示例#3
0
bool courier::auth::config_file::config(const char *name,
                                        std::string &value,
                                        bool required,
                                        const char *default_value) const
{
    return getconfig(name, value, required, default_value);
}
示例#4
0
bool vibration::load(const char *file) {
	//setfile(file); // FIXME: to allow loading/reloading filename
	loaddefaults();
	if(getconfig(m_configfile) == false) {
		setconfig(m_configfile);
		return false;
	}
	return true;
}
示例#5
0
bool configurator::loadconf() {

    LOG4CXX_DEBUG("loading config");
    // FIXME: loaddefaults first then load config, which should place val@key
    if(getconfig("harmonics.conf") == false) { // FIXME:  warning: deprecated conversion from string constant to ‘char*’
        // TODO: if config file not found create one with defaults
        //dumper("harmonics.conf", " ", 1);
        loaddefaults();
        LOG4CXX_DEBUG("defaults loaded for config");
    } else {
        LOG4CXX_DEBUG("using config from file");

    }
    return true;
}
// {
//   secret: <string>
// }
json::value dovalidationseed (rpc::context& context)
{
    auto lock = getapp().masterlock();
    json::value obj (json::objectvalue);

    if (!context.params.ismember ("secret"))
    {
        std::cerr << "unset validation seed." << std::endl;

        getconfig ().validation_seed.clear ();
        getconfig ().validation_pub.clear ();
        getconfig ().validation_priv.clear ();
    }
    else if (!getconfig ().validation_seed.setseedgeneric (
                 context.params["secret"].asstring ()))
    {
        getconfig ().validation_pub.clear ();
        getconfig ().validation_priv.clear ();

        return rpcerror (rpcbad_seed);
    }
    else
    {
        auto& seed = getconfig ().validation_seed;
        auto& pub = getconfig ().validation_pub;

        pub = rippleaddress::createnodepublic (seed);
        getconfig ().validation_priv = rippleaddress::createnodeprivate (seed);

        obj["validation_public_key"] = pub.humannodepublic ();
        obj["validation_seed"] = seed.humanseed ();
        obj["validation_key"] = seed.humanseed1751 ();
    }

    return obj;
}
json::value doledgeraccept (rpc::context& context)
{
    auto lock = getapp().masterlock();
    json::value jvresult;

    if (!getconfig ().run_standalone)
    {
        jvresult["error"] = "notstandalone";
    }
    else
    {
        context.netops.acceptledger ();

        jvresult["ledger_current_index"]
                = context.netops.getcurrentledgerid ();
    }

    return jvresult;
}
示例#8
0
static int tapi2p_callback(struct libwebsocket_context *ctx,
						   struct libwebsocket *wsi,
						   enum libwebsocket_callback_reasons reason,
						   void* user,
						   void* in,
						   size_t len)
{
	switch(reason)
	{
		case LWS_CALLBACK_ESTABLISHED:
			lwsl_notice("Handshaked with client.\n");
			libwebsocket_callback_on_writable(ctx, wsi);
			break;
		case LWS_CALLBACK_SERVER_WRITEABLE:
		{
			if(corefd==-1)
			{
				char* conn_reply="Could not connect to tapi2p. Is tapi2p core running?";
				websocket_send(wsi, conn_reply, strlen(conn_reply));
			}
			else if(!welcome_message_sent)
			{
				struct config* conf=getconfig();
				if(conf)
				{
					struct configitem* ci=config_find_item(conf, "Nick", "Account");
					if(ci && ci->val)
					{
						json_t *root=json_object();
						json_object_set_new(root, "cmd", json_integer(Message));
						json_object_set_new(root, "data", json_string("Welcome to tapi2p, "));
						json_object_set_new(root, "own_nick", json_string(ci->val));
						char *jsonstr=json_dumps(root, 0);
						welcome_message_sent=1;
						websocket_send(wsi, jsonstr, strlen(jsonstr));
						free(jsonstr);
						json_decref(root);
						lwsl_notice("Sent welcome message.\n");
					}
				}
			}
			else if(unsent_data>0)
			{
				pthread_mutex_lock(&datalock);
				while(unsent_data)
				{
					char* data=data_to_send[--unsent_data];
					printf("Sent: %s\n", data);
					websocket_send(wsi, data, strlen(data));
					free(data);
				}
				pthread_mutex_unlock(&datalock);
			}
			usleep(10000);
			libwebsocket_callback_on_writable(ctx, wsi);
			break;
		}
		case LWS_CALLBACK_CLOSED:
			lwsl_notice("Connection to client closed.\n");
			break;
		case LWS_CALLBACK_RECEIVE:
			lwsl_notice("Message from client\n");
			printf("Json: %s %d\n", (char*)in, len);
			send_json((char*) in, len);
			break;

	}
	return 0;
}
示例#9
0
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp		now;
	struct recvbuf *rbuf;
	const char *	logfilename;
# ifdef HAVE_UMASK
	mode_t		uv;
# endif
# if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	uid_t		uid;
# endif
# if defined(HAVE_WORKING_FORK)
	long		wait_sync = 0;
	int		pipe_fds[2];
	int		rc;
	int		exit_code;
#  ifdef _AIX
	struct sigaction sa;
#  endif
#  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
	int		fid;
#  endif
# endif	/* HAVE_WORKING_FORK*/
# ifdef SCO5_CLOCK
	int		fd;
	int		zero;
# endif

# ifdef NEED_PTHREAD_WARMUP
	my_pthread_warmup();
# endif
	
# ifdef HAVE_UMASK
	uv = umask(0);
	if (uv)
		umask(uv);
	else
		umask(022);
# endif
	saved_argc = argc;
	saved_argv = argv;
	progname = argv[0];
	initializing = TRUE;		/* mark that we are initializing */
	parse_cmdline_opts(&argc, &argv);
# ifdef DEBUG
	debug = OPT_VALUE_SET_DEBUG_LEVEL;
#  ifdef HAVE_SETLINEBUF
	setlinebuf(stdout);
#  endif
# endif

	if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
# ifdef DEBUG
	    || debug
# endif
	    || HAVE_OPT(SAVECONFIGQUIT))
		nofork = TRUE;

	init_logging(progname, NLOG_SYNCMASK, TRUE);
	/* honor -l/--logfile option to log to a file */
	if (HAVE_OPT(LOGFILE)) {
		logfilename = OPT_ARG(LOGFILE);
		syslogit = FALSE;
		change_logfile(logfilename, FALSE);
	} else {
		logfilename = NULL;
		if (nofork)
			msyslog_term = TRUE;
		if (HAVE_OPT(SAVECONFIGQUIT))
			syslogit = FALSE;
	}
	msyslog(LOG_NOTICE, "%s: Starting", Version);

	{
		int i;
		char buf[1024];	/* Secret knowledge of msyslog buf length */
		char *cp = buf;

		/* Note that every arg has an initial space character */
		snprintf(cp, sizeof(buf), "Command line:");
		cp += strlen(cp);

		for (i = 0; i < saved_argc ; ++i) {
			snprintf(cp, sizeof(buf) - (cp - buf),
				" %s", saved_argv[i]);
			cp += strlen(cp);
		}
		msyslog(LOG_INFO, "%s", buf);
	}

	/*
	 * Install trap handlers to log errors and assertion failures.
	 * Default handlers print to stderr which doesn't work if detached.
	 */
	isc_assertion_setcallback(assertion_failed);
	isc_error_setfatal(library_fatal_error);
	isc_error_setunexpected(library_unexpected_error);

	/* MPE lacks the concept of root */
# if defined(HAVE_GETUID) && !defined(MPE)
	uid = getuid();
	if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
		msyslog_term = TRUE;
		msyslog(LOG_ERR,
			"must be run as root, not uid %ld", (long)uid);
		exit(1);
	}
# endif

/*
 * Enable the Multi-Media Timer for Windows?
 */
# ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
# endif

#ifdef HAVE_DNSREGISTRATION
/*
 * Enable mDNS registrations?
 */
	if (HAVE_OPT( MDNS )) {
		mdnsreg = TRUE;
	}
#endif  /* HAVE_DNSREGISTRATION */

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int		ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		sockaddr_u	addr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, AF_UNSPEC, &addr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

# ifdef HAVE_SCHED_SETSCHEDULER
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
# endif

# ifdef HAVE_WORKING_FORK
	/* make sure the FDs are initialised */
	pipe_fds[0] = -1;
	pipe_fds[1] = -1;
	do {					/* 'loop' once */
		if (!HAVE_OPT( WAIT_SYNC ))
			break;
		wait_sync = OPT_VALUE_WAIT_SYNC;
		if (wait_sync <= 0) {
			wait_sync = 0;
			break;
		}
		/* -w requires a fork() even with debug > 0 */
		nofork = FALSE;
		if (pipe(pipe_fds)) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"Pipe creation failed for --wait-sync: %m");
			exit(exit_code);
		}
		waitsync_fd_to_close = pipe_fds[1];
	} while (0);				/* 'loop' once */
# endif	/* HAVE_WORKING_FORK */

	init_lib();
# ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
# endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

# ifdef HAVE_WORKING_FORK
		rc = fork();
		if (-1 == rc) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR, "fork: %m");
			exit(exit_code);
		}
		if (rc > 0) {	
			/* parent */
			exit_code = wait_child_sync_if(pipe_fds[0],
						       wait_sync);
			exit(exit_code);
		}
		
		/*
		 * child/daemon 
		 * close all open files excepting waitsync_fd_to_close.
		 * msyslog() unreliable until after init_logging().
		 */
		closelog();
		if (syslog_file != NULL) {
			fclose(syslog_file);
			syslog_file = NULL;
			syslogit = TRUE;
		}
		close_all_except(waitsync_fd_to_close);
		INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
			&& 2 == dup2(0, 2));

		init_logging(progname, 0, TRUE);
		/* we lost our logfile (if any) daemonizing */
		setup_logfile(logfilename);

#  ifdef SYS_DOMAINOS
		{
			uid_$t puid;
			status_$t st;

			proc2_$who_am_i(&puid);
			proc2_$make_server(&puid, &st);
		}
#  endif	/* SYS_DOMAINOS */
#  ifdef HAVE_SETSID
		if (setsid() == (pid_t)-1)
			msyslog(LOG_ERR, "setsid(): %m");
#  elif defined(HAVE_SETPGID)
		if (setpgid(0, 0) == -1)
			msyslog(LOG_ERR, "setpgid(): %m");
#  else		/* !HAVE_SETSID && !HAVE_SETPGID follows */
#   ifdef TIOCNOTTY
		fid = open("/dev/tty", 2);
		if (fid >= 0) {
			ioctl(fid, (u_long)TIOCNOTTY, NULL);
			close(fid);
		}
#   endif	/* TIOCNOTTY */
		ntp_setpgrp(0, getpid());
#  endif	/* !HAVE_SETSID && !HAVE_SETPGID */
#  ifdef _AIX
		/* Don't get killed by low-on-memory signal. */
		sa.sa_handler = catch_danger;
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_RESTART;
		sigaction(SIGDANGER, &sa, NULL);
#  endif	/* _AIX */
# endif		/* HAVE_WORKING_FORK */
	}

# ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	fd = open("/dev/at1", O_RDONLY);		
	if (fd >= 0) {
		zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
			msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close(fd);
	}
# endif

	/* Setup stack size in preparation for locking pages in memory. */
# if defined(HAVE_MLOCKALL)
#  ifdef HAVE_SETRLIMIT
	ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
#   ifdef RLIMIT_MEMLOCK
	/*
	 * The default RLIMIT_MEMLOCK is very low on Linux systems.
	 * Unless we increase this limit malloc calls are likely to
	 * fail if we drop root privilege.  To be useful the value
	 * has to be larger than the largest ntpd resident set size.
	 */
	ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
#   endif	/* RLIMIT_MEMLOCK */
#  endif	/* HAVE_SETRLIMIT */
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
#    ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
		msyslog(LOG_ERR,
			"Cannot adjust stack limit for plock: %m");
#    endif	/* _AIX */
#   endif	/* PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */

	/*
	 * Set up signals we pay attention to locally.
	 */
# ifdef SIGDIE1
	signal_no_reset(SIGDIE1, finish);
	signal_no_reset(SIGDIE2, finish);
	signal_no_reset(SIGDIE3, finish);
	signal_no_reset(SIGDIE4, finish);
# endif
# ifdef SIGBUS
	signal_no_reset(SIGBUS, finish);
# endif

# if !defined(SYS_WINNT) && !defined(VMS)
#  ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
#  else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
#  endif	/* DEBUG */
# endif	/* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
# ifdef SIGPIPE
	signal_no_reset(SIGPIPE, SIG_IGN);
# endif

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	INIT_SSL();
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_request();
	init_control();
	init_peer();
# ifdef REFCLOCK
	init_refclock();
# endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);

	if (-1 == cur_memlock) {
# if defined(HAVE_MLOCKALL)
		/*
		 * lock the process into memory
		 */
		if (   !HAVE_OPT(SAVECONFIGQUIT)
#  ifdef RLIMIT_MEMLOCK
		    && -1 != DFLT_RLIMIT_MEMLOCK
#  endif
		    && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
			msyslog(LOG_ERR, "mlockall(): %m");
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
		/*
		 * lock the process into memory
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
			msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#   else	/* !PROCLOCK follows  */
#    ifdef TXTLOCK
		/*
		 * Lock text into ram
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
			msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#    else	/* !TXTLOCK follows */
		msyslog(LOG_ERR, "plock() - don't know what to lock!");
#    endif	/* !TXTLOCK */
#   endif	/* !PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */
	}

	loop_config(LOOP_DRIFTINIT, 0);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	initializing = FALSE;

# ifdef HAVE_DROPROOT
	if (droproot) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#  ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#  elif HAVE_SOLARIS_PRIVS
		/* Nothing to do here */
#  else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					free(user);
					user = estrdup(pw->pw_name);
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
						msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
						msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
#  ifdef HAVE_SOLARIS_PRIVS
		if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
			msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
			exit(-1);
		}
		if ((highprivs = priv_allocset()) == NULL) {
			msyslog(LOG_ERR, "priv_allocset() failed:%m");
			exit(-1);
		}
		(void) getppriv(PRIV_PERMITTED, highprivs);
		(void) priv_intersect(highprivs, lowprivs);
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
#  endif /* HAVE_SOLARIS_PRIVS */
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (group) {
			if (0 != setgroups(1, &sw_gid)) {
				msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
				exit (-1);
			}
		}
		else if (pw)
			if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
				msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
				exit (-1);
			}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#  if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
		}

#  ifdef HAVE_LINUX_CAPABILITIES
		{
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext;
			
			captext = (0 != interface_interval)
				      ? "cap_sys_time,cap_net_bind_service=pe"
				      : "cap_sys_time=pe";
			caps = cap_from_text(captext);
			if (!caps) {
				msyslog(LOG_ERR,
					"cap_from_text(%s) failed: %m",
					captext);
				exit(-1);
			}
			if (-1 == cap_set_proc(caps)) {
				msyslog(LOG_ERR,
					"cap_set_proc() failed to drop root privs: %m");
				exit(-1);
			}
			cap_free(caps);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES */
#  ifdef HAVE_SOLARIS_PRIVS
		if (priv_delset(lowprivs, "proc_setid") == -1) {
			msyslog(LOG_ERR, "priv_delset() failed:%m");
			exit(-1);
		}
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
		priv_freeset(lowprivs);
		priv_freeset(highprivs);
#  endif /* HAVE_SOLARIS_PRIVS */
		root_dropped = TRUE;
		fork_deferred_worker();
	}	/* if (droproot) */
# endif	/* HAVE_DROPROOT */

/* libssecomp sandboxing */
#if defined (LIBSECCOMP) && (KERN_SECCOMP)
	scmp_filter_ctx ctx;

	if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
		msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
	}

#ifdef __x86_64__
int scmp_sc[] = {
	SCMP_SYS(adjtimex),
	SCMP_SYS(bind),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(connect),
	SCMP_SYS(exit_group),
	SCMP_SYS(fstat),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(getsockname),
	SCMP_SYS(ioctl),
	SCMP_SYS(lseek),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(recvmsg),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(rt_sigreturn),
	SCMP_SYS(select),
	SCMP_SYS(sendto),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(socket),
	SCMP_SYS(stat),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
#ifdef __i386__
int scmp_sc[] = {
	SCMP_SYS(_newselect),
	SCMP_SYS(adjtimex),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(exit_group),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(mmap2),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(select),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(sigprocmask),
	SCMP_SYS(sigreturn),
	SCMP_SYS(socketcall),
	SCMP_SYS(stat64),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
	{
		int i;

		for (i = 0; i < COUNTOF(scmp_sc); i++) {
			if (seccomp_rule_add(ctx,
			    SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
				msyslog(LOG_ERR,
				    "%s: seccomp_rule_add() failed: %m",
				    __func__);
			}
		}
	}

	if (seccomp_load(ctx) < 0)
		msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
		    __func__);	
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
	}
#endif /* LIBSECCOMP and KERN_SECCOMP */

# ifdef HAVE_IO_COMPLETION_PORT

	for (;;) {
		GetReceivedBuffers();
# else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = FALSE;

	for (;;) {
		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (!was_alarmed && !has_full_recv_buffer()) {
			/*
			 * Nothing to do.  Wait for something.
			 */
			io_handler();
		}

		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (was_alarmed) {
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = FALSE;
			BLOCK_IO_AND_ALARM();
		}

# endif		/* !HAVE_IO_COMPLETION_PORT */

# ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
# endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL) {
				if (alarm_flag) {
					was_alarmed = TRUE;
					alarm_flag = FALSE;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed) {
					/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = FALSE;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL) {
# ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
# endif
					(*rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
# ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
# endif

		/*
		 * Go around again
		 */

# ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attempting to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = FALSE;
			}
		}
# endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}
#endif	/* !SIM */


#if !defined(SIM) && defined(SIGDIE1)
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	const char *sig_desc;

	sig_desc = NULL;
#ifdef HAVE_STRSIGNAL
	sig_desc = strsignal(sig);
#endif
	if (sig_desc == NULL)
		sig_desc = "";
	msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
		sig, sig_desc);
	/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
# ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
# endif
	peer_cleanup();
	exit(0);
}
#endif	/* !SIM && SIGDIE1 */


#ifndef SIM
/*
 * wait_child_sync_if - implements parent side of -w/--wait-sync
 */
# ifdef HAVE_WORKING_FORK
static int
wait_child_sync_if(
	int	pipe_read_fd,
	long	wait_sync
	)
{
	int	rc;
	int	exit_code;
	time_t	wait_end_time;
	time_t	cur_time;
	time_t	wait_rem;
	fd_set	readset;
	struct timeval wtimeout;

	if (0 == wait_sync) 
		return 0;

	/* waitsync_fd_to_close used solely by child */
	close(waitsync_fd_to_close);
	wait_end_time = time(NULL) + wait_sync;
	do {
		cur_time = time(NULL);
		wait_rem = (wait_end_time > cur_time)
				? (wait_end_time - cur_time)
				: 0;
		wtimeout.tv_sec = wait_rem;
		wtimeout.tv_usec = 0;
		FD_ZERO(&readset);
		FD_SET(pipe_read_fd, &readset);
		rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
			    &wtimeout);
		if (-1 == rc) {
			if (EINTR == errno)
				continue;
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"--wait-sync select failed: %m");
			return exit_code;
		}
		if (0 == rc) {
			/*
			 * select() indicated a timeout, but in case
			 * its timeouts are affected by a step of the
			 * system clock, select() again with a zero 
			 * timeout to confirm.
			 */
			FD_ZERO(&readset);
			FD_SET(pipe_read_fd, &readset);
			wtimeout.tv_sec = 0;
			wtimeout.tv_usec = 0;
			rc = select(pipe_read_fd + 1, &readset, NULL,
				    NULL, &wtimeout);
			if (0 == rc)	/* select() timeout */
				break;
			else		/* readable */
				return 0;
		} else			/* readable */
			return 0;
	} while (wait_rem > 0);

	fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
		progname, wait_sync);
	return ETIMEDOUT;
}
示例#10
0
ter
createoffer::doapply()
{
    if (m_journal.debug) m_journal.debug <<
        "offercreate> " << mtxn.getjson (0);

    std::uint32_t const utxflags = mtxn.getflags ();

    bool const bpassive (utxflags & tfpassive);
    bool const bimmediateorcancel (utxflags & tfimmediateorcancel);
    bool const bfillorkill (utxflags & tffillorkill);
    bool const bsell  (utxflags & tfsell);

    stamount satakerpays = mtxn.getfieldamount (sftakerpays);
    stamount satakergets = mtxn.getfieldamount (sftakergets);

    if (!islegalnet (satakerpays) || !islegalnet (satakergets))
        return tembad_amount;

    auto const& upaysissuerid = satakerpays.getissuer ();
    auto const& upayscurrency = satakerpays.getcurrency ();

    auto const& ugetsissuerid = satakergets.getissuer ();
    auto const& ugetscurrency = satakergets.getcurrency ();

    bool const bhaveexpiration (mtxn.isfieldpresent (sfexpiration));
    bool const bhavecancel (mtxn.isfieldpresent (sfoffersequence));

    std::uint32_t const uexpiration = mtxn.getfieldu32 (sfexpiration);
    std::uint32_t const ucancelsequence = mtxn.getfieldu32 (sfoffersequence);

    // fixme understand why we use sequencenext instead of current transaction
    //       sequence to determine the transaction. why is the offer seuqnce
    //       number insufficient?

    std::uint32_t const uaccountsequencenext = mtxnaccount->getfieldu32 (sfsequence);
    std::uint32_t const usequence = mtxn.getsequence ();

    const uint256 uledgerindex = getofferindex (mtxnaccountid, usequence);

    if (m_journal.debug)
    {
        m_journal.debug <<
            "creating offer node: " << to_string (uledgerindex) <<
            " usequence=" << usequence;

        if (bimmediateorcancel)
            m_journal.debug << "transaction: ioc set.";

        if (bfillorkill)
            m_journal.debug << "transaction: fok set.";
    }

    // this is the original rate of this offer, and is the rate at which it will
    // be placed, even if crossing offers change the amounts.
    std::uint64_t const urate = getrate (satakergets, satakerpays);

    ter terresult (tessuccess);

    // this is the ledger view that we work against. transactions are applied
    // as we go on processing transactions.
    core::ledgerview& view (mengine->view ());

    // this is a checkpoint with just the fees paid. if something goes wrong
    // with this transaction, we roll back to this ledger.
    core::ledgerview view_checkpoint (view);

    view.bumpseq (); // begin ledger variance.

    sle::pointer slecreator = mengine->entrycache (
        ltaccount_root, getaccountrootindex (mtxnaccountid));

    // additional checking for currency asset.
    // buy asset
    if (assetcurrency() == upayscurrency) {
        if (assetcurrency() == ugetscurrency || // asset for asset
            bsell)                              // tfsell set while buying asset
            return temdisabled;

        if (satakerpays < stamount(satakerpays.issue(), getconfig().asset_tx_min) || !satakerpays.ismathematicalinteger())
            return tembad_offer;

        if (upaysissuerid == mtxnaccountid || ugetsissuerid == mtxnaccountid) {
            m_journal.trace << "creating asset offer is not allowed for issuer";
            return temdisabled;
        }
    }
    // sell asset
    if (assetcurrency() == ugetscurrency) {
        if (!bsell) // tfsell not set while selling asset
            return temdisabled;

        if (satakergets < stamount(satakergets.issue(), getconfig().asset_tx_min) || !satakergets.ismathematicalinteger())
            return tembad_offer;
    }

    if (utxflags & tfoffercreatemask)
    {
        if (m_journal.debug) m_journal.debug <<
            "malformed transaction: invalid flags set.";

        terresult = teminvalid_flag;
    }
    else if (bimmediateorcancel && bfillorkill)
    {
        if (m_journal.debug) m_journal.debug <<
            "malformed transaction: both ioc and fok set.";

        terresult = teminvalid_flag;
    }
    else if (bhaveexpiration && !uexpiration)
    {
        m_journal.warning <<
            "malformed offer: bad expiration";

        terresult = tembad_expiration;
    }
    else if (satakerpays.isnative () && satakergets.isnative ())
    {
        m_journal.warning <<
            "malformed offer: xrp for xrp";

        terresult = tembad_offer;
    }
    else if (satakerpays <= zero || satakergets <= zero)
    {
        m_journal.warning <<
            "malformed offer: bad amount";

        terresult = tembad_offer;
    }
    else if (upayscurrency == ugetscurrency && upaysissuerid == ugetsissuerid)
    {
        m_journal.warning <<
            "malformed offer: redundant offer";

        terresult = temredundant;
    }
    // we don't allow a non-native currency to use the currency code vrp.
    else if (badcurrency() == upayscurrency || badcurrency() == ugetscurrency)
    {
        m_journal.warning <<
            "malformed offer: bad currency.";

        terresult = tembad_currency;
    }
    else if (satakerpays.isnative () != isnative(upaysissuerid) ||
             satakergets.isnative () != isnative(ugetsissuerid))
    {
        m_journal.warning <<
            "malformed offer: bad issuer";

        terresult = tembad_issuer;
    }
    else if (view.isglobalfrozen (upaysissuerid) || view.isglobalfrozen (ugetsissuerid))
    {
        m_journal.warning <<
            "offer involves frozen asset";

        terresult = tecfrozen;
    }
    else if (view.accountfunds (
        mtxnaccountid, satakergets, fhzero_if_frozen) <= zero)
    {
        m_journal.warning <<
            "delay: offers must be at least partially funded.";

        terresult = tecunfunded_offer;
    }
    // this can probably be simplified to make sure that you cancel sequences
    // before the transaction sequence number.
    else if (bhavecancel && (!ucancelsequence || uaccountsequencenext - 1 <= ucancelsequence))
    {
        if (m_journal.debug) m_journal.debug <<
            "uaccountsequencenext=" << uaccountsequencenext <<
            " uoffersequence=" << ucancelsequence;

        terresult = tembad_sequence;
    }

    if (terresult != tessuccess)
    {
        if (m_journal.debug) m_journal.debug <<
            "final terresult=" << transtoken (terresult);

        return terresult;
    }

    // process a cancellation request that's passed along with an offer.
    if ((terresult == tessuccess) && bhavecancel)
    {
        uint256 const ucancelindex (
            getofferindex (mtxnaccountid, ucancelsequence));
        sle::pointer slecancel = mengine->entrycache (ltoffer, ucancelindex);

        // it's not an error to not find the offer to cancel: it might have
        // been consumed or removed as we are processing.
        if (slecancel)
        {
            m_journal.warning <<
                "cancelling order with sequence " << ucancelsequence;

            terresult = view.offerdelete (slecancel);
        }
    }

    // expiration is defined in terms of the close time of the parent ledger,
    // because we definitively know the time that it closed but we do not
    // know the closing time of the ledger that is under construction.
    if (bhaveexpiration &&
        (mengine->getledger ()->getparentclosetimenc () >= uexpiration))
    {
        return tessuccess;
    }

    // make sure that we are authorized to hold what the taker will pay us.
    if (terresult == tessuccess && !satakerpays.isnative ())
        terresult = checkacceptasset (issue (upayscurrency, upaysissuerid));

    bool crossed = false;
    bool const bopenledger (mparams & tapopen_ledger);

    if (terresult == tessuccess)
    {
        // we reverse gets and pays because during offer crossing we are taking.
        core::amounts const taker_amount (satakergets, satakerpays);

        // the amount of the offer that we will need to place, after we finish
        // offer crossing processing. it may be equal to the original amount,
        // empty (fully crossed), or something in-between.
        core::amounts place_offer;

        std::tie(terresult, place_offer) = crossoffers (view, taker_amount);

        if (terresult == tecfailed_processing && bopenledger)
            terresult = telfailed_processing;

        if (terresult == tessuccess)
        {
            // we now need to reduce the offer by the cross flow. we reverse
            // in and out here, since during crossing we were takers.
            assert (satakerpays.getcurrency () == place_offer.out.getcurrency ());
            assert (satakerpays.getissuer () == place_offer.out.getissuer ());
            assert (satakergets.getcurrency () == place_offer.in.getcurrency ());
            assert (satakergets.getissuer () == place_offer.in.getissuer ());

            if (taker_amount != place_offer)
                crossed = true;

            if (m_journal.debug)
            {
                m_journal.debug << "offer crossing: " << transtoken (terresult);

                if (terresult == tessuccess)
                {
                    m_journal.debug <<
                        "    takerpays: " << satakerpays.getfulltext () <<
                        " -> " << place_offer.out.getfulltext ();
                    m_journal.debug <<
                        "    takergets: " << satakergets.getfulltext () <<
                        " -> " << place_offer.in.getfulltext ();
                }
            }

            satakerpays = place_offer.out;
            satakergets = place_offer.in;
        }
    }

    if (terresult != tessuccess)
    {
        m_journal.debug <<
            "final terresult=" << transtoken (terresult);

        return terresult;
    }

    if (m_journal.debug)
    {
        m_journal.debug <<
            "takeoffers: satakerpays=" <<satakerpays.getfulltext ();
        m_journal.debug <<
            "takeoffers: satakergets=" << satakergets.getfulltext ();
        m_journal.debug <<
            "takeoffers: mtxnaccountid=" <<
            to_string (mtxnaccountid);
        m_journal.debug <<
            "takeoffers:         funds=" << view.accountfunds (
            mtxnaccountid, satakergets, fhzero_if_frozen).getfulltext ();
    }

    if (satakerpays < zero || satakergets < zero)
    {
        // earlier, we verified that the amounts, as specified in the offer,
        // were not negative. that they are now suggests that something went
        // very wrong with offer crossing.
        m_journal.fatal << (crossed ? "partially consumed" : "full") <<
            " offer has negative component:" <<
            " pays=" << satakerpays.getfulltext () <<
            " gets=" << satakergets.getfulltext ();

        assert (satakerpays >= zero);
        assert (satakergets >= zero);
        return tefinternal;
    }

    if (bfillorkill && (satakerpays != zero || satakergets != zero))
    {
        // fill or kill and have leftovers.
        view.swapwith (view_checkpoint); // restore with just fees paid.
        return tessuccess;
    }

    // what the reserve would be if this offer was placed.
    auto const accountreserve (mengine->getledger ()->getreserve (
        slecreator->getfieldu32 (sfownercount) + 1));

    if (satakerpays == zero ||                // wants nothing more.
        satakergets == zero ||                // offering nothing more.
        bimmediateorcancel)                   // do not persist.
    {
        // complete as is.
    }
    else if (mpriorbalance.getnvalue () < accountreserve)
    {
        // if we are here, the signing account had an insufficient reserve
        // *prior* to our processing. we use the prior balance to simplify
        // client writing and make the user experience better.

        if (bopenledger) // ledger is not final, can vote no.
        {
            // hope for more reserve to come in or more offers to consume. if we
            // specified a local error this transaction will not be retried, so
            // specify a tec to distribute the transaction and allow it to be
            // retried. in particular, it may have been successful to a
            // degree (partially filled) and if it hasn't, it might succeed.
            terresult = tecinsuf_reserve_offer;
        }
        else if (!crossed)
        {
            // ledger is final, insufficent reserve to create offer, processed
            // nothing.
            terresult = tecinsuf_reserve_offer;
        }
        else
        {
            // ledger is final, insufficent reserve to create offer, processed
            // something.
            // consider the offer unfunded. treat as tessuccess.
        }
    }
    else
    {
        assert (satakerpays > zero);
        assert (satakergets > zero);

        // we need to place the remainder of the offer into its order book.
        if (m_journal.debug) m_journal.debug <<
            "offer not fully consumed:" <<
            " satakerpays=" << satakerpays.getfulltext () <<
            " satakergets=" << satakergets.getfulltext ();

        std::uint64_t uownernode;
        std::uint64_t ubooknode;
        uint256 udirectory;

        // add offer to owner's directory.
        terresult = view.diradd (uownernode,
            getownerdirindex (mtxnaccountid), uledgerindex,
            std::bind (
                &ledger::ownerdirdescriber, std::placeholders::_1,
                std::placeholders::_2, mtxnaccountid));

        if (tessuccess == terresult)
        {
            // update owner count.
            view.incrementownercount (slecreator);

            uint256 const ubookbase (getbookbase (
                {{upayscurrency, upaysissuerid},
                    {ugetscurrency, ugetsissuerid}}));

            if (m_journal.debug) m_journal.debug <<
                "adding to book: " << to_string (ubookbase) <<
                " : " << satakerpays.gethumancurrency () <<
                "/" << to_string (satakerpays.getissuer ()) <<
                " -> " << satakergets.gethumancurrency () <<
                "/" << to_string (satakergets.getissuer ());

            // we use the original rate to place the offer.
            udirectory = getqualityindex (ubookbase, urate);

            // add offer to order book.
            terresult = view.diradd (ubooknode, udirectory, uledgerindex,
                std::bind (
                    &ledger::qualitydirdescriber, std::placeholders::_1,
                    std::placeholders::_2, satakerpays.getcurrency (),
                    upaysissuerid, satakergets.getcurrency (),
                    ugetsissuerid, urate));
        }

        if (tessuccess == terresult)
        {
            if (m_journal.debug)
            {
                m_journal.debug <<
                    "sfaccount=" <<
                    to_string (mtxnaccountid);
                m_journal.debug <<
                    "upaysissuerid=" <<
                    to_string (upaysissuerid);
                m_journal.debug <<
                    "ugetsissuerid=" <<
                    to_string (ugetsissuerid);
                m_journal.debug <<
                    "satakerpays.isnative()=" <<
                    satakerpays.isnative ();
                m_journal.debug <<
                    "satakergets.isnative()=" <<
                    satakergets.isnative ();
                m_journal.debug <<
                    "upayscurrency=" <<
                    satakerpays.gethumancurrency ();
                m_journal.debug <<
                    "ugetscurrency=" <<
                    satakergets.gethumancurrency ();
            }

            sle::pointer sleoffer (mengine->entrycreate (ltoffer, uledgerindex));

            sleoffer->setfieldaccount (sfaccount, mtxnaccountid);
            sleoffer->setfieldu32 (sfsequence, usequence);
            sleoffer->setfieldh256 (sfbookdirectory, udirectory);
            sleoffer->setfieldamount (sftakerpays, satakerpays);
            sleoffer->setfieldamount (sftakergets, satakergets);
            sleoffer->setfieldu64 (sfownernode, uownernode);
            sleoffer->setfieldu64 (sfbooknode, ubooknode);

            if (uexpiration)
                sleoffer->setfieldu32 (sfexpiration, uexpiration);

            if (bpassive)
                sleoffer->setflag (lsfpassive);

            if (bsell)
                sleoffer->setflag (lsfsell);

            if (m_journal.debug) m_journal.debug <<
                "final terresult=" << transtoken (terresult) <<
                " sleoffer=" << sleoffer->getjson (0);
        }
    }

    if (terresult != tessuccess)
    {
        m_journal.debug <<
            "final terresult=" << transtoken (terresult);
    }

    return terresult;
}
示例#11
0
int main(int argc, char *argv[])
{
    int n, i, argp;
    int lstn = -1, lmax = 0, lunix = -1, lweb = -1;
    unsigned int u;
    fd_set fds, lfds;
    struct sockaddr_in sin;
    struct sockaddr_un sun;
    char buf[512], *c, *d;
    FILE *kmlinf;
    struct timeval tv;
    int pid, pipefrom[2];
    int fastfwd = 1;
    unsigned int ll, llprev = 0, llpvpv[3] = { 0, 0, 0 };

    if (!geteuid()) {
        fprintf(stderr, "Don't run as root!\n");
        exit(-2);
    }

    if (argc < 2) {
        fprintf(stderr, "Usage: gpsreplay [-f <speed multiplier>] <kmz or kml files>\n");
        return -1;
    }

    memset(&gpst, 0, sizeof(gpst));
    gpst.gpsfd = 7;
    gpst.obdfd = 8;

    fprintf(stderr, "Startup\n");
    fflush(stderr);

    getconfig();

    for (n = 0; n < MAXCONN; n++)
        acpt[n] = -1;

    memset((char *) &sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;

    dobindlstn(&lstn, gpsdport);
    dobindlstn(&lweb, httpport);

    lunix = socket(AF_UNIX, SOCK_STREAM, 0);
    sun.sun_family = AF_UNIX;
    strcpy(sun.sun_path, unixsock);
    unlink(unixsock);
    if (bind(lunix, (struct sockaddr *) &sun, (int) sizeof(sun)))
        fprintf(stderr, "bind on unix sock failed\n");
    else if (listen(lunix, 3))
        fprintf(stderr, "listen on unix sock failed\n");

    xbuf = malloc(BUFLEN);

    listen(lstn, 3);
    listen(lweb, 3);
    lmax = lstn;

    if (lunix > lmax)
        lmax = lunix;
    if (lweb > lmax)
        lmax = lweb;

    FD_ZERO(&lfds);
    FD_SET(lstn, &lfds);
    FD_SET(lunix, &lfds);
    FD_SET(lweb, &lfds);

    getms();

    int vfd = open("/tmp/v1state", O_RDWR | O_CREAT, 0666);
    if (vfd < 0)
        return -1;
    memset(&u, 0, sizeof(u));
    write(vfd, &u, sizeof(u));
    unsigned int *v1img = mmap(0, sizeof(u), PROT_READ | PROT_WRITE, MAP_SHARED, vfd, 0);

    int mfd = open("/tmp/obd2state", O_RDWR | O_CREAT, 0666);
    if (mfd < 0)
        return -1;
    memset(buf, 0xa5, 512);
    write(mfd, buf, 512);
    unsigned int *memimg = mmap(0, 512, PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0);

    stafd = open("/tmp/mgpstate", O_RDWR | O_CREAT, 0644);
    write(stafd, &gpst, sizeof(gpst));
    write(stafd, &hstat, sizeof(hstat));
    write(stafd, &more, sizeof(more));

    for (argp = 1; argp < argc; argp++) {
        kmlinf = NULL;
        if (strstr(argv[argp], ".kml"))
            kmlinf = fopen(argv[argp], "r");
        else if (strstr(argv[argp], ".kmz")) {
            pipe(pipefrom);
            pid = fork();
            if (!pid) {
                dup2(pipefrom[1], STDOUT_FILENO);
                close(pipefrom[0]);
                close(pipefrom[1]);
                execlp("/usr/bin/unzip", "unzip", "-p", argv[argp], NULL);
                fprintf(stderr, "KMZ support requires unzip to be installed\n");
                exit(-1);
            }
            close(pipefrom[1]);
            kmlinf = fdopen(pipefrom[0], "r");
        } else if (strstr(argv[argp], "-f")) {
            fastfwd = atoi(argv[++argp]);
            continue;
        } else {
            fprintf(stderr, "Unknown arg %s is not kml/kmz file nor \"-f speed\"\n", argv[argp]);
            continue;
        }

        if (kmlinf == NULL)
            continue;

        for (;;) {
            waitpid(-1, &i, WNOHANG);
            if (feof(kmlinf))
                break;

            buf[0] = 0;
            fgets(buf, 512, kmlinf);

            if (strstr(buf, "TimeStamp")) {
                if (fastfwd > 1) {
                    i = fastfwd - 1;
                    while (i) {
                        buf[0] = 0;
                        fgets(buf, 512, kmlinf);
                        if (feof(kmlinf))
                            break;
                        if (strstr(buf, "TimeStamp"))
                            i--;
                    }
                    if (feof(kmlinf))
                        break;
                }
                getms();
                //                usleep( 1000 * (1001 - thisms % 1000) ); 
                continue;
            }

            if ((c = strstr(buf, "g( V"))) {
                c += 4;
                if (1 == sscanf(c, "%08x", &ll)) {
                    more.v1flash = ll & ~llprev & ~llpvpv[0] & llpvpv[1] & llpvpv[2];
                    more.v1img = ll;
                    llpvpv[2] = llpvpv[1];
                    llpvpv[1] = llpvpv[0];
                    llpvpv[0] = llprev;
                    llprev = ll;
                }
                continue;
            }
            if ((c = strstr(buf, "g( K,"))) {
                unsigned int ax, ay, az;
                char *dot;
                strcpy(xbuf, &buf[5]);
                // zap decimal points
                while ((dot = strstr(xbuf, ".")))
                    strcpy(dot, &dot[1]);
                if (3 == sscanf(xbuf, "%d,%d,%d", &ax, &ay, &az)) {
                    more.xa = ax;
                    more.ya = ay;
                    more.za = az;
                }
                continue;
            }

            if (!(c = strchr(buf, '$')))
                continue;

            d = strchr(c, '*');
            if (!d)
                continue;
            d += 3;
            *d++ = '\r';
            *d++ = '\n';
            *d = 0;
            doraw(c);
            if (c[1] == 'G')
                getgpsinfo(c);  // expects single null terminated strings (line ends dont matter)

            // add PLL code later
            //            usleep(100);

            if (c[1] == 'P') {
                c += 3;
                // thisms from PLL or buf tag
                if (strstr(c, "OBD")) {
                    if ((d = strstr(c, ",41,"))) {
                        unsigned int t[4], pid;
                        unsigned int ll;
                        int k;

                        d += 4;
                        sscanf(d, "%02x,%02x,%02x,%02x,%02x", &pid, &t[0], &t[1], &t[2], &t[3]);
                        ll = 0;
                        i = resplen[pid];
                        for (k = 0; k < i && k < 4; k++)
                            ll = (ll << 8) | t[k];
                        memimg[pid] = ll;
                    }
                } else {
                    if (strstr(c, "FUL") || strstr(c, "ODO")) {
                        c = strchr(c, ',');
                        if (!c)
                            continue;
                        c++;
                    }
                    c = strchr(c, ',');
                    if (!c)
                        continue;
                    c++;
                    c = strchr(c, ',');
                    if (!c)
                        continue;
                    c++;
                    d = strchr(c, '*');
                    if (d)
                        *d = 0;

                    calcobd(c, thisms);
                }
            }

            lseek(stafd, 0, SEEK_SET);
            write(stafd, &gpst, sizeof(gpst));
            write(stafd, &hstat, sizeof(hstat));
            write(stafd, &more, sizeof(more));

            fds = lfds;
            n = lmax;
#define MAXFD(fd) if (fd >= 0) { FD_SET(fd, &fds); if (fd > n) n = fd; }
            for (i = 0; i < amax; i++)
                MAXFD(acpt[i]);

            tv.tv_sec = 0;
            tv.tv_usec = 0;

            i = select(++n, &fds, NULL, NULL, &tv);
            if (i < 0)
                continue;       // if BT device detaches...
            // timeout added to reconnect
            if (i == 0)
                continue;

            /* read commands from remote */
            for (i = 0; i < amax; i++) {
                if (acpt[i] == -1)
                    continue;
                if (FD_ISSET(acpt[i], &fds)) {
                    n = read(acpt[i], buf, 500);
                    if (n <= 0) {
                        /* read error */
                        close(acpt[i]);
                        acpt[i] = -1;
                        continue;
                    }
                    buf[n] = 0;
                    prtgpsinfo(i, buf);
                }
            }

            /* accept new connections */
            if (FD_ISSET(lweb, &fds)) {
                char *c;
                u = sizeof(sin);
                n = accept(lweb, (struct sockaddr *) &sin, &u);
                i = read(n, xbuf, BUFLEN);
                /* for the GET / HTTP1.X, etc. */
                if (i < 0)
                    break;
                xbuf[i] = 0;
                if (strstr(xbuf, "kml"))
                    dokml(xbuf);
                else if (strstr(xbuf, "gpsdata.xml"))
                    doxml();
                else if (strstr(xbuf, "dogmap.html"))
                    dogmap();
                else if ((c = strstr(xbuf, "radar"))) {
                    c += 5;
                    i = atoi(c);
                    if (!i)
                        i = 20;
                    dorad(i);
                } else
                    doweb();
                write(n, xbuf, strlen(xbuf));
                close(n);
            }

            /* accept new connections */
            if (FD_ISSET(lstn, &fds)) {
                for (n = 0; n < amax; n++)
                    if (acpt[n] == -1)
                        break;
                if (n < MAXCONN) {
                    if (n >= amax)
                        amax++;
                    u = sizeof(sin);
                    raw[n] = 0;
                    acpt[n] = accept(lstn, (struct sockaddr *) &sin, &u);
                    i = fcntl(acpt[n], F_GETFL, 0);
                    fcntl(acpt[n], F_SETFL, i | O_NONBLOCK);
                    fprintf(stderr, "acpt %d %d\n", n, acpt[n]);
                    fflush(stderr);
                }
            }

            /* accept new connections */
            if (FD_ISSET(lunix, &fds)) {
                for (n = 0; n < amax; n++)
                    if (acpt[n] == -1)
                        break;
                if (n < MAXCONN) {
                    if (n >= amax)
                        amax++;
                    u = sizeof(sun);
                    raw[n] = 0;
                    acpt[n] = accept(lunix, (struct sockaddr *) &sun, &u);
                    i = fcntl(acpt[n], F_GETFL, 0);
                    fcntl(acpt[n], F_SETFL, i | O_NONBLOCK);
                    fprintf(stderr, "acpt %d %d\n", n, acpt[n]);
                    fflush(stderr);
                }
            }

        }
        fclose(kmlinf);
    }
    return 0;                   // quiet compiler
}
示例#12
0
/*
 * Main program.  Initialize us, disconnect us from the tty if necessary,
 * and loop waiting for I/O and/or timer expiries.
 */
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp now;
	struct recvbuf *rbuf;
#ifdef _AIX			/* HMS: ifdef SIGDANGER? */
	struct sigaction sa;
#endif

	progname = argv[0];
	initializing = 1;		/* mark that we are initializing */
	process_commandline_opts(&argc, &argv);
	init_logging(progname, 1);	/* Open the log file */

	char *error = NULL;
	if (sandbox_init("ntpd", SANDBOX_NAMED, &error) == -1) {
		msyslog(LOG_ERR, "sandbox_init(ntpd, SANDBOX_NAMED) failed: %s", error);
		sandbox_free_error(error);
	}
#ifdef HAVE_UMASK
	{
		mode_t uv;

		uv = umask(0);
		if(uv)
			(void) umask(uv);
		else
			(void) umask(022);
	}
#endif

#if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	{
		uid_t uid;

		uid = getuid();
		if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
			msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid);
			printf("must be run as root, not uid %ld\n", (long)uid);
			exit(1);
		}
	}
#endif

	/* getstartup(argc, argv); / * startup configuration, may set debug */

#ifdef DEBUG
	debug = DESC(DEBUG_LEVEL).optOccCt;
	DPRINTF(1, ("%s\n", Version));
#endif

	/* honor -l/--logfile option to log to a file */
	setup_logfile();

/*
 * Enable the Multi-Media Timer for Windows?
 */
#ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
#endif

	if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT )
#ifdef DEBUG
	    || debug
#endif
	    || HAVE_OPT( SAVECONFIGQUIT ))
		nofork = 1;

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int	ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		isc_netaddr_t	netaddr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, &netaddr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

#if defined(HAVE_SCHED_SETSCHEDULER)
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
#endif

#ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
#endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

#if !defined(VMS)
# ifndef NODETACH
	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

		/*
		 * Install trap handlers to log errors and assertion
		 * failures.  Default handlers print to stderr which 
		 * doesn't work if detached.
		 */
		isc_assertion_setcallback(assertion_failed);
		isc_error_setfatal(library_fatal_error);
		isc_error_setunexpected(library_unexpected_error);

#  ifndef SYS_WINNT
#   ifdef HAVE_DAEMON
		daemon(0, 0);
#   else /* not HAVE_DAEMON */
		if (fork())	/* HMS: What about a -1? */
			exit(0);

		{
#if !defined(F_CLOSEM)
			u_long s;
			int max_fd;
#endif /* !FCLOSEM */
			if (syslog_file != NULL) {
				fclose(syslog_file);
				syslog_file = NULL;
			}
#if defined(F_CLOSEM)
			/*
			 * From 'Writing Reliable AIX Daemons,' SG24-4946-00,
			 * by Eric Agar (saves us from doing 32767 system
			 * calls)
			 */
			if (fcntl(0, F_CLOSEM, 0) == -1)
			    msyslog(LOG_ERR, "ntpd: failed to close open files(): %m");
#else  /* not F_CLOSEM */

# if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
			max_fd = sysconf(_SC_OPEN_MAX);
# else /* HAVE_SYSCONF && _SC_OPEN_MAX */
			max_fd = getdtablesize();
# endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
			for (s = 0; s < max_fd; s++)
				(void) close((int)s);
#endif /* not F_CLOSEM */
			(void) open("/", 0);
			(void) dup2(0, 1);
			(void) dup2(0, 2);

			init_logging(progname, 0);
			/* we lost our logfile (if any) daemonizing */
			setup_logfile();

#ifdef SYS_DOMAINOS
			{
				uid_$t puid;
				status_$t st;

				proc2_$who_am_i(&puid);
				proc2_$make_server(&puid, &st);
			}
#endif /* SYS_DOMAINOS */
#if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
# ifdef HAVE_SETSID
			if (setsid() == (pid_t)-1)
				msyslog(LOG_ERR, "ntpd: setsid(): %m");
# else
			if (setpgid(0, 0) == -1)
				msyslog(LOG_ERR, "ntpd: setpgid(): %m");
# endif
#else /* HAVE_SETPGID || HAVE_SETSID */
			{
# if defined(TIOCNOTTY)
				int fid;

				fid = open("/dev/tty", 2);
				if (fid >= 0)
				{
					(void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
					(void) close(fid);
				}
# endif /* defined(TIOCNOTTY) */
# ifdef HAVE_SETPGRP_0
				(void) setpgrp();
# else /* HAVE_SETPGRP_0 */
				(void) setpgrp(0, getpid());
# endif /* HAVE_SETPGRP_0 */
			}
#endif /* HAVE_SETPGID || HAVE_SETSID */
#ifdef _AIX
			/* Don't get killed by low-on-memory signal. */
			sa.sa_handler = catch_danger;
			sigemptyset(&sa.sa_mask);
			sa.sa_flags = SA_RESTART;

			(void) sigaction(SIGDANGER, &sa, NULL);
#endif /* _AIX */
		}
#   endif /* not HAVE_DAEMON */
#  endif /* SYS_WINNT */
	}
# endif /* NODETACH */
#endif /* VMS */

#ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	{
	    int fd = open("/dev/at1", O_RDONLY);
	    if (fd >= 0) {
		int zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
		    msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close( fd );
	    } /* else ...
	       *   If we can't open the device, this probably just isn't
	       *   a multiprocessor system, so we're A-OK.
	       */
	}
#endif

#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE)
# ifdef HAVE_SETRLIMIT
	/*
	 * Set the stack limit to something smaller, so that we don't lock a lot
	 * of unused stack memory.
	 */
	{
	    struct rlimit rl;

	    /* HMS: must make the rlim_cur amount configurable */
	    if (getrlimit(RLIMIT_STACK, &rl) != -1
		&& (rl.rlim_cur = 50 * 4096) < rl.rlim_max)
	    {
		    if (setrlimit(RLIMIT_STACK, &rl) == -1)
		    {
			    msyslog(LOG_ERR,
				"Cannot adjust stack limit for mlockall: %m");
		    }
	    }
#  ifdef RLIMIT_MEMLOCK
	    /*
	     * The default RLIMIT_MEMLOCK is very low on Linux systems.
	     * Unless we increase this limit malloc calls are likely to
	     * fail if we drop root privlege.  To be useful the value
	     * has to be larger than the largest ntpd resident set size.
	     */
	    rl.rlim_cur = rl.rlim_max = 32*1024*1024;
	    if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) {
		msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m");
	    }
#  endif /* RLIMIT_MEMLOCK */
	}
# endif /* HAVE_SETRLIMIT */
	/*
	 * lock the process into memory
	 */
	if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0)
		msyslog(LOG_ERR, "mlockall(): %m");
#else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */
# ifdef HAVE_PLOCK
#  ifdef PROCLOCK
#   ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8*4096)) < 0)
	{
		msyslog(LOG_ERR,"Cannot adjust stack limit for plock on AIX: %m");
	}
#   endif /* _AIX */
	/*
	 * lock the process into memory
	 */
	if (plock(PROCLOCK) < 0)
		msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#  else /* not PROCLOCK */
#   ifdef TXTLOCK
	/*
	 * Lock text into ram
	 */
	if (plock(TXTLOCK) < 0)
		msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#   else /* not TXTLOCK */
	msyslog(LOG_ERR, "plock() - don't know what to lock!");
#   endif /* not TXTLOCK */
#  endif /* not PROCLOCK */
# endif /* HAVE_PLOCK */
#endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */

	/*
	 * Set up signals we pay attention to locally.
	 */
#ifdef SIGDIE1
	(void) signal_no_reset(SIGDIE1, finish);
#endif	/* SIGDIE1 */
#ifdef SIGDIE2
	(void) signal_no_reset(SIGDIE2, finish);
#endif	/* SIGDIE2 */
#ifdef SIGDIE3
	(void) signal_no_reset(SIGDIE3, finish);
#endif	/* SIGDIE3 */
#ifdef SIGDIE4
	(void) signal_no_reset(SIGDIE4, finish);
#endif	/* SIGDIE4 */

#ifdef SIGBUS
	(void) signal_no_reset(SIGBUS, finish);
#endif /* SIGBUS */

#if !defined(SYS_WINNT) && !defined(VMS)
# ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
# else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
# endif /* DEBUG */
#endif /* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
#if defined SIGPIPE
	(void) signal_no_reset(SIGPIPE, SIG_IGN);
#endif	/* SIGPIPE */

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_lib();
	init_request();
	init_control();
	init_peer();
#ifdef REFCLOCK
	init_refclock();
#endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);
	NLOG(NLOG_SYSINFO) /* 'if' clause for syslog */
	msyslog(LOG_NOTICE, "%s", Version);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	loop_config(LOOP_DRIFTCOMP, old_drift);
	initializing = 0;

#ifdef HAVE_DROPROOT
	if( droproot ) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#endif /* HAVE_LINUX_CAPABILITIES */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					user = strdup(pw->pw_name);
					if (NULL == user) {
						msyslog(LOG_ERR, "strdup() failed: %m");
						exit (-1);
					}
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
					    msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
					    msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#ifndef HAVE_LINUX_CAPABILITIES
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#endif

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking");
		}

#ifdef HAVE_LINUX_CAPABILITIES
		do {
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext = (interface_interval)
				? "cap_sys_time,cap_net_bind_service=ipe"
				: "cap_sys_time=ipe";
			if( ! ( caps = cap_from_text( captext ) ) ) {
				msyslog( LOG_ERR, "cap_from_text() failed: %m" );
				exit(-1);
			}
			if( cap_set_proc( caps ) == -1 ) {
				msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" );
				exit(-1);
			}
			cap_free( caps );
		} while(0);
#endif /* HAVE_LINUX_CAPABILITIES */

	}    /* if( droproot ) */
#endif /* HAVE_DROPROOT */

	/*
	 * Use select() on all on all input fd's for unlimited
	 * time.  select() will terminate on SIGALARM or on the
	 * reception of input.	Using select() means we can't do
	 * robust signal handling and we get a potential race
	 * between checking for alarms and doing the select().
	 * Mostly harmless, I think.
	 */
	/* On VMS, I suspect that select() can't be interrupted
	 * by a "signal" either, so I take the easy way out and
	 * have select() time out after one second.
	 * System clock updates really aren't time-critical,
	 * and - lacking a hardware reference clock - I have
	 * yet to learn about anything else that is.
	 */
#if defined(HAVE_IO_COMPLETION_PORT)

	for (;;) {
		GetReceivedBuffers();
#else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = 0;
	for (;;)
	{
# if !defined(HAVE_SIGNALED_IO)
		extern fd_set activefds;
		extern int maxactivefd;

		fd_set rdfdes;
		int nfound;
# endif

		if (alarm_flag)		/* alarmed? */
		{
			was_alarmed = 1;
			alarm_flag = 0;
		}

		if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE)
		{
			/*
			 * Nothing to do.  Wait for something.
			 */
# ifndef HAVE_SIGNALED_IO
			rdfdes = activefds;
#  if defined(VMS) || defined(SYS_VXWORKS)
			/* make select() wake up after one second */
			{
				struct timeval t1;

				t1.tv_sec = 1; t1.tv_usec = 0;
				nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
						(fd_set *)0, &t1);
			}
#  else
			nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
					(fd_set *)0, (struct timeval *)0);
#  endif /* VMS */
			if (nfound > 0)
			{
				l_fp ts;

				get_systime(&ts);

				(void)input_handler(&ts);
			}
			else if (nfound == -1 && errno != EINTR)
				msyslog(LOG_ERR, "select() error: %m");
#  ifdef DEBUG
			else if (debug > 5)
				msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
#  endif /* DEBUG */
# else /* HAVE_SIGNALED_IO */

			wait_for_signal();
# endif /* HAVE_SIGNALED_IO */
			if (alarm_flag)		/* alarmed? */
			{
				was_alarmed = 1;
				alarm_flag = 0;
			}
		}

		if (was_alarmed)
		{
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = 0;
			BLOCK_IO_AND_ALARM();
		}

#endif /* ! HAVE_IO_COMPLETION_PORT */

#ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
#endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL)
			{
				if (alarm_flag)
				{
					was_alarmed = 1;
					alarm_flag = 0;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed)
				{	/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = 0;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL)	/* This should always be true */
				{
#ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
#endif
					(rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "receive buffer corruption - receiver found to be NULL - ABORTING");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
#ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
#endif

		/*
		 * Go around again
		 */

#ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attemping to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = 0;
			}
		}
#endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}


#ifdef SIGDIE2
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig);
#ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
#endif
	switch (sig) {
# ifdef SIGBUS
	case SIGBUS:
		printf("\nfinish(SIGBUS)\n");
		exit(0);
# endif
	case 0:			/* Should never happen... */
		return;

	default:
		exit(0);
	}
}
MOTOBOX_CONFIG_ERR_T setconfig_main(int argc, char *argv[])
{

    char *confid = NULL;
    int value = MOTOBOX_CONFIG_ID_INVALID;
    MOTOBOX_CONFIG_ERR_T status = MOTOBOX_CONFIG_ERR_NONE;
    char buf[255];
    char *old_confid = NULL;
    int leadZeros = 0;

    /** Set to recovery mode or not flag */
    short isSetRecovery = 1; // TRUE by default
    short dont_erase = 0;

    struct stat s;

    /* validate argument format*/
    if(argc == 3 || argc == 2){
        /* check if multiconfig build */
        if(lstat( MULTICONFIG_FOLDER, &s ) < 0 ) {
            LOGE("This is not a multiconfig build, exiting %s\n", argv[0]);
            printf("%d\n", MOTOBOX_CONFIG_ERR_NOT_MULTICONFIG);
            return MOTOBOX_CONFIG_ERR_NOT_MULTICONFIG;
        }

        if(argc == 3) {
            if (strcmp(NO_RECOVERY_PARAM, argv[1]) == 0) {
                isSetRecovery = 0; //FALSE
                confid = argv[2];
            } else if (strcmp("-no_erase_data", argv[1]) == 0) {
                dont_erase = 1; //TRUE
                confid = argv[2];
            } else {
                LOGE("use: %s [-norecovery | -no_erase_data] config-id\n", argv[0]);

                printf("%d\n", MOTOBOX_CONFIG_ERR_INVALID_PARAM);
                return MOTOBOX_CONFIG_ERR_INVALID_PARAM;
            }
        } else if(argc == 2) {
            confid = argv[1];
        }
    } else {
        LOGE("use: %s [-norecovery | -no_erase_data] config-id\n", argv[0]);

        printf("%d\n", MOTOBOX_CONFIG_ERR_INVALID_PARAM);
        return MOTOBOX_CONFIG_ERR_INVALID_PARAM;
    }

    /* validate conf-id */
    value = atoi(confid);
    memset(buf, 0 , sizeof(buf));
    sprintf(buf, "%d", value);

    /* config-id can have leading zeros ex: 0001, ignore them for comparing */
    if(strlen(confid) > 1) { // Ignore confid="0"
        while(confid[leadZeros] == '0') leadZeros++;
    }

    /* atoi does not detect trailing chars ex: 12abc, so compare */
    if (strcmp(buf, (confid + leadZeros)) != 0){
        LOGE("Invalid config-id :%s \n",confid);

        printf("%d\n", MOTOBOX_CONFIG_ERR_INVALID_FORMAT);
        return MOTOBOX_CONFIG_ERR_INVALID_FORMAT;
    }

    if(value < MOTOBOX_CONFIG_ID_UNCONFIGURED || value > MOTOBOX_CONFIG_ID_MAX) {
        LOGE("Invalid config-id limit :%d \n", value);

        printf("%d\n", MOTOBOX_CONFIG_ERR_INVALID_FORMAT);
        return MOTOBOX_CONFIG_ERR_INVALID_FORMAT;
    }


    /** Compare with previous config-id if present */
    if (getconfig(buf,sizeof(buf)) == MOTOBOX_CONFIG_ERR_NONE) {
        old_confid = buf;
    }

    //Copying the BOTA Package to Cache partition
    status = copy_bota_package_to_cache();

    if ( status != MOTOBOX_CONFIG_ERR_NONE) {
         printf("%d\n",status);
         return status;
    }

    /* Write to config file */
    status = set_config(confid);
    if (status == MOTOBOX_CONFIG_ERR_NONE) {

        /* set into recovery mode */
        if (isSetRecovery) {
            status = set_recovery();
        } else {
            /* Caller will set into recovery mode, so just update cache command file */
            status = set_cache_command();
        }
        if(status == MOTOBOX_CONFIG_ERR_NONE) {
            if (dont_erase) {
               set_no_erase_data_flag();
            }
            sync();
        } else {
            /* Set to recovery mode failed, so revert back to older config-id */
            if(old_confid != NULL) {
              if(set_config(old_confid) != MOTOBOX_CONFIG_ERR_NONE) {
                LOGE("setconfig altered to %s but not complete.Please reconfigure.\n",confid);
                status = MOTOBOX_CONFIG_ERR_NEEDS_RECONFIG;
              }
            }
        }

    }

    if ( status != MOTOBOX_CONFIG_ERR_NONE) {
         LOGE("Remove bota package from cache partition since setconfig failed ..%d\n",status);
         remove_bota_package_from_cache();
    }

    printf("%d\n",status);
    return status;
}
示例#14
0
int main(int argc, char *argv[])
{
	uint8_t *tab_rp_bits;
	uint16_t *tab_rp_registers;
	uint16_t *rd_position_registers;
    uint16_t *tab_rp_registers_bad;
    modbus_t *ctx;

/***********************************************************************
* feedback is used to store the return value of every called function
* rc is used to store the return value of the modbus command 
* resend is used to define the resend times if the command is failed
* i is used for the loop parameter
* insert_bit is used to indicate the calibarate function if there is value to set
* num is used to store the number of data blocks in database 
* use_backend is used to indicate the modbus mode is rtu
* next_option is used to take the command options
* pre_step, curr_step are used to indicate the previous step number and current position step number
* pre_length and value indicate the latest posiotion in database and current position
* SLEN is a kind of struct used to store the database blocks
************************************************************************/
    int feedback,i; 
	int insert_bit, nb_points,num =0;
	int next_option;
	long curr_step;
	long pystep = -1;
	double value;
	double pdepth,pspacing,pdwell,pinterval;
	double profiled,stopped;
	double depth,dwell,spacing,interval;
	double last_position;
	int profilebit =0,feedback1,feedback2;
	int modbus=0;
	int motor_stop = 0;
	char * command_arg = "";
	char * return_value;
	double in_position = 0;
	SLEN *examp;
	ARF  *config, *profile,*off_set;
	modbus_mapping_t *mb_mapping;
	int   ShmID;      
	int *ShmPTR;
	int stop_indicator = 0;

	key_t MyKey;
	MyKey   = ftok(".", 's');    
    ShmID   = shmget(MyKey, sizeof(int), IPC_CREAT | 0666);
    ShmPTR  = (int *) shmat(ShmID, NULL, 0);

	tab_rp_registers = (uint16_t *) malloc(4 * sizeof(uint16_t));
	rd_position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
	tab_rp_registers_bad = (uint16_t *) malloc(2 * sizeof(uint16_t));

	config = (ARF*)malloc( 10 * sizeof(ARF) );
	if ( config == NULL ) 
	{
		printf("Error: Out of Memory, use ./master reset to reset memory\n"); 
		exit(1);
	}
	const char *const short_options = "hd::u::l:p::cD::w::s::i::gSmt::";
	const struct option long_options[] = {
        { "help",              0,NULL, 'h'},
        { "down",              2,NULL, 'd'},
		{ "up",                2,NULL, 'u'},
		{ "length",            1,NULL, 'l'},
		{ "position",          2,NULL, 'p'},
		{ "count",             0,NULL, 'c'},
		{ "Depth",             2,NULL, 'D'},
		{ "well",              2,NULL, 'w'},
		{ "spacing",           2,NULL, 's'},
		{ "interval",          2,NULL, 'i'},
		{ "go",                0,NULL, 'g'},
		{ "System",            0,NULL, 'S'},
		{ "motor",             0,NULL, 'm'},
		{ "time",              2,NULL, 't'},
        { NULL, 0, NULL, 0  },

    };

	if (argc < 2) 
	{
		print_comusage (stderr, 1);
		return_value = json_option("status:",-1);
		return return_value;
	}
	program_name = argv[0];
	/*Get the first argument that passed through main function but does not contain*/
	command_name = argv[1];
	if(argc > 2)
	{
		command_arg  = argv[2];
	}
/*******************************************************************************************
* The next three command_name are used to control the motor through modbus	(need modbus)  *
********************************************************************************************/

	if ( strcmp(command_name, "go") == 0 ) {
		double curr_position;
		char *recd = (char*)malloc(10*sizeof(char));
		double offset;
		int re_send = 0;
		*ShmPTR = 0;
		modbus = 0;
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		
		if (next_option == -1) print_comusage (stderr, 1);
		while (next_option != -1) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);
				case 'd':  
				godown:
						enable(0);
						initbus(1);
				/*		sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = godown(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto godown;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
				*/
						feedback = process_go_down(1);
						if((feedback == 0) && (re_send < 1))
						{
							printf("get false recycle power\n");
							enable(0);
							initbus(0);
							re_send++;
							goto godown;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'u':
				goup: 
						enable(0);
						initbus(1);
				/*
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = goup(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto goup;
						}
				*/
						feedback = process_go_up(1);
						if((feedback == 0) && (re_send < 1))
						{
							printf("Get false recycle power\n");
							enable(0);
							initbus(0);
							re_send++;
							goto goup;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'p':
						enable(0);
						initbus(1);
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						in_position = atof(optarg);		
						off_set = (ARF*)malloc(15*sizeof(ARF));
	    				off_set = getconfig(&num,off_set);
						offset = off_set[10].value;
						in_position = in_position - offset;
						//printf("inposition is %f offset is %f\n",in_position,offset);
						free(off_set);
						//system("/home/sampler/kingkong.sh");
				gotoposition:
						if (in_position <= 0)
						{
							if( process_read_home_switch(1) == 0)
							{
								feedback = process_go_home(1);
							}
							else
								feedback = 1;
						}
						else 
						{
							pystep = process_read_step(1);
							curr_position = process_position(pystep);
							if ( !(( (in_position -0.1) <= curr_position ) && ( curr_position <= (in_position + 0.1) )) ) 
							{
								feedback = process_go_position(1,in_position);
								return_value = json_option("status",feedback);
							}
						}
						if((feedback == 0)&&(re_send <1))
						{
							printf("get false recycle power");
							enable(0);
							initbus(0);
							enable(0);
							initbus(1);
							re_send++;
							goto gotoposition;
						}
						break;	
					case '?':
						print_comusage (stderr, 1);
					default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		//If the go command is failed, then exit the current process and power off the controller 	
		if(feedback == 0)
		{
			printf("1\n");
			//*ShmPTR = 1;
			enable(0);
			initbus(0);
			return_value = json_option("status",-1);
			return return_value;
		}
		do{
			usleep(5000);
			stop_indicator = process_check(1);
		}while(stop_indicator != 0);
		//printf("stop\n");
		sleep(1);
		pystep = process_read_step(1);
		curr_position = process_position(pystep);
		//printf("cur position is %f\n",curr_position);
		if(curr_position != -1)
		{
			login("Go to command set last position");
			curr_position = curr_position + offset;
			setconfig(9,curr_position);
			// In order to avoid "Read status command shutdown the power by accident
			enable(0);
			initbus(0);		
			return_value = json_option("status",1);
		}
		else return_value = json_option("status",-1);
	}

	if ( strcmp(command_name, "stop") == 0 ) 
	{ 		
		if(check_power() == 1)
		{
			/*sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = stop(ctx);
			if(feedback == -1)stop(ctx);
			*/
			process_stop(1);
		}
	}

    if ( strcmp(command_name, "position") == 0 ) 
	{ 
		login("Check position command");
		int resend = 0;
		double temp_position,offset;
		char *rec = (char*)malloc(10*sizeof(char));
		stop_indicator = *ShmPTR;
		uint16_t * position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
checkposition:
		if (check_power()== 1) 
		{
			ctx = modbusconnection(ctx);
			modbus = 1;
			temp_position = checkposition(ctx,position_registers);
			sprintf(rec,"The position read is %f",temp_position);
			login(rec);
			if(temp_position != -1)
			{
				login("Check position set last position");
				//This sentence is used to show the position with offset 
				temp_position = temp_position + offset;
				feedback = setconfig(9,temp_position);
			}
			else 
			{
				if(resend < 2)
				{
					resend++;					
					goto checkposition;
				}
				else return -100;
			}
		}
		else 
		{
			config = getconfig(&num,config);
			temp_position = config[8].value;
		}
		return_value = json_float_option("status",temp_position);
		printf("%s\n",return_value);
	}
/***********************************************************************
*         0: motor is stopped                                          *
*         1: motor is going down                                       *
*         2: motor is going up                                         *
*         3: motor is ramp up                                          *
*         4: motor is ramp down   									   *
*		   (need modbus)             						           *
*                                               	                   *
************************************************************************/
	if(strcmp(command_name, "status") == 0) 
	{
		stop_indicator = *ShmPTR;
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			if(next_option == -1) print_comusage (stderr, 1);
			while(next_option != -1) 
			{
				switch (next_option) 
				{
					case 'h':
							print_comusage(stdout, 0);	
					case 'S':
							feedback = checksystemstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;	
					case 'm':
							feedback = checkmotorstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;
					case '?':
							print_comusage (stderr, 1);
					default:
							abort ();
				}
				next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			}	
			if(feedback == -1)
			{
				return_value = json_option("status",0);
			}
		}
		else 
		{
			return_value = json_option("status",0);
			//login("Check status from database");
		}
		printf("%s\n",return_value);
	}

/****************************************************************************************
*      The next three command_name are used to control the database through sqlite3	    *
*****************************************************************************************/
	if ( strcmp(command_name, "factory_default") == 0 ) 
	{
		feedback1 = reset(0);
		feedback2 = dbinit(0);
		if ( (feedback1 == 1) && (feedback2 == 1)) 
		{
			return_value = json_float_option("status",1);
			printf("%s\n",return_value);
		}
		else 
		{
			return_value = json_float_option("status",-1);
			printf("%s\n",return_value);		
		}
	}

	if ( strcmp(command_name, "reset") == 0 ) 
	{
		feedback = reset(0);
		if(feedback == 1)
		{
			feedback = expected_time_reset();
		}
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "init") == 0 ) 
	{
		feedback = -1;
		if ( strcmp(command_arg, "all") == 0 ) 
		{
			feedback = dbinit(0);
			if(feedback == 1)
			{
				feedback = expected_time_init();
			}
		}
		if ( strcmp(command_arg, "calibrate" ) == 0 ) 
		{ 
			setconfig(6,0);
			feedback = dbinit(1); 
		}
		if ( strcmp(command_arg, "configure" ) == 0 ) 
		{
			feedback = dbinit(2);
		}
		if ( feedback == -1 ) 
		{
			return_value = json_float_option("status",-1);
			print_comusage (stderr, 1);
		}
		else return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name,"get") == 0 ) 
	{
		examp = getall(&num,examp);
		return_value = json_array_option(num,examp);
		free(examp);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"set_offset") == 0 ) 
	{
		double offset;		
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)offset = strtod(optarg,NULL);
						insert_bit = 1;
						break;	
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		feedback = setconfig(11,offset);
		return_value = json_option("status",feedback);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"get_offset") == 0 ) 
	{
		double offset;		
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
		return_value = json_float_option("status",offset);
		printf("%s",return_value);	
		free(off_set);
	}
/**************************************************************************
*      The next three command_name are used to calibrate (need modbus)     *                     
***************************************************************************/
	if ( strcmp(command_name, "calibrate") == 0 ) 
	{	
		double calibrate;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);	
		modbus = 1;	
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);

		if ( next_option == -1 ) print_comusage (stderr, 1);
		config = getconfig(&num,config);
		calibrate = config[5].value;
		if ( calibrate == 0 ) 
		{
			reset(1);
			setconfig(6,1.0);
			set(num,0,0);
		}
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)value = atof(optarg);
						insert_bit = 1;
						break;	
				case 'c':
						getall(&num,examp);
						return_value = json_option("status",num);
						printf("%s\n",return_value);
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		if ( insert_bit == 1 ) 
		{
			curr_step = checksteps(ctx,rd_position_registers);
			if ( curr_step < 0 ) curr_step =0;//do not need
			feedback = checkvalue(curr_step,value);
			if ( feedback == 1 ) 
			{
				feedback = set(num,curr_step,value);
				return_value = json_option("status",feedback);
			} 
			else 
			{
				return_value = json_option("status",-1);
			}	
		}
		/*if ( checkmotorstatus(ctx,tab_rp_registers) == 0 ) 
		{	
			enable(0);
			initbus(0);
		}*/
		printf("%s\n",return_value);
	}


/***********************************************************************
*         The following functions are used for profile				   *
*                                               	                   *
************************************************************************/
	if ( strcmp(command_name, "profile") == 0 ) 
	{
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while ( next_option != -1 ) 
		{
			switch (next_option) {
				case 'h':
						print_comusage(stdout, 0);	
				case 'd':
						if(optarg!=0)depth = atof(optarg);
						profilebit = 1;
						break;	
				case 's':
						if(optarg!=0)spacing = atof(optarg);
						profilebit = 1;
						break;
				case 'w':
						if(optarg!=0)dwell = atof(optarg);
						profilebit = 1;
						break;
				case 'i':
						//if(optarg!=0)interval = atof(optarg);
						if(optarg!=0)interval = strtod(optarg,NULL);
						profilebit = 1;
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	

		if ( profilebit == 1 ) 
		{
			feedback = set_profile(depth,spacing,dwell,interval);
		}
		//Want to get the expected profile time and save it in database
		profile_time_check(interval);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profileget" ) == 0) 
	{
		profile = getconfig(&num,config);
		return_value = json_profile_option(num-2,profile);
		free(profile);
		printf("%s",return_value);	
	}
	if ( strcmp(command_name, "profile_check" ) == 0) 
	{
		int *expected_profile_time;
		long remain_profile_time;
		config = getconfig(&num,config);
		pinterval = config[3].value;
		if(pinterval == 0)	
		{
			printf("-999\n");
			return -999;
		}
		expected_profile_time = (int*)malloc(10*sizeof(int));
		if(expected_profile_time == NULL){printf("error\n");exit(1);}
		expected_time_get(expected_profile_time);
		remain_profile_time = auto_run(0,expected_profile_time);
		if(remain_profile_time <=0 )remain_profile_time = 0;
		printf("%d\n",remain_profile_time);
		free(expected_profile_time);
		return remain_profile_time;
	}
	if ( strcmp(command_name, "profile_reset") == 0 ) 
	{
		//feedback = dbinit(2);
		//reading_hourly();
		system("ps aux | grep -e 'master profilego' | grep -v grep | awk '{print $2}' | xargs -i kill {}");
		feedback = set_profile(0,0,0,0);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profilego") == 0 ) 
	{	
		double stayposition, curr_position,tmp,cal_position;
		double sdl_read,offset;
		long wait_time,motor_status;
		int year;
		time_t fail_time;
		int stop_check = -1;
		int count,fini_count,re_try1 = 0,re_power1 =0,re_try = 0,re_send=0;
		int i=1,sample = 0,profile_times,sample_indicator;
		int * expected_tm, *curr_time,inter_val;
		setconfig(10,0);
	profile:
		/* The following eight lines are used to get profile arguments from database */
		config = getconfig(&num,config);
		pdepth = config[0].value;
		pspacing = config[1].value;
		pdwell = config[2].value;
		pinterval = config[3].value;	
		profiled = config[4].value;
		sample = config[9].value;
		offset = config[10].value;
		profile_times = 1+(pdepth - offset)/pspacing;		// Caculate the profile times
		inter_val = (int)pinterval;
		if(pinterval == 0){schedule_reading();goto profile;}
	   	if(profiled == 0 )
		{
			config = getconfig(&num,config);
			pdepth = config[0].value;
			pspacing = config[1].value;
			pdwell = config[2].value;
			pinterval = config[3].value;	
			profiled = config[4].value;
			sample = config[9].value;
			/* 
				The following part are used to get the expected profile time and 
				compare with current time
			*/
			expected_tm = (int*)malloc(10*sizeof(int));
			curr_time = (int*)malloc(10*sizeof(int));
			if(curr_time == NULL){printf("error\n");exit(1);}
			if(expected_tm == NULL){printf("error\n");exit(1);}
			do{
				config = getconfig(&num,config);
				sample = config[9].value;
				expected_time_get(expected_tm);
				wait_time= auto_run(0,expected_tm);
				curr_time = check_time(curr_time);
				sample_indicator = curr_time[3]%inter_val;
				printf("Wait for next profile\n");
				//because the board will boot up 3 minutes after clock time
				if(wait_time < -600)
				{
					profile_time_check(pinterval);
					goto profile;
				}					
				sleep(1);
			}while(wait_time>0);
			free(expected_tm);	
		four_minute_delay:
			sleep(1);
			curr_time = check_time(curr_time);
			if((curr_time[4]>=4) &&(curr_time[4]<=10))goto start_profile;
			if(curr_time[4]<4)goto four_minute_delay;
			if(curr_time[4]>10)goto profile;
		}
	start_profile:
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		if(ctx == NULL)goto profile;
		modbus = 1;
		sleep(9);
		if ( profiled == 0 ) 
		{
			if (process_syncclock() == 0) 
			{
				login("Failed in connectting with SDL");
				return;
			}
			if (process_expression(3,1,profile_times,0) == 0)
			{	
				login("Failed in send profile to SDL");
				return;
			}		
			login("Start Profiling");
			if( process_read_home_switch(1) == 0)
			{
				gotoposition(ctx, 0,rd_position_registers);   //Do not need to check if it is home because we want it home anyway
				do{
					usleep(5000);
					stop_check = process_check(1);
				}while(stop_check != 0);
				if(process_pass_through_check() == 0)initbus(0); 
				setconfig(5,1);		//Set the profile flag 
				sleep(pdwell);
			}
			else
			{
				setconfig(5,1);
				sleep(pdwell);
			}
		}	
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		/* This following part is used to determine where is destination  */
		curr_position = checkposition(ctx,tab_rp_registers) + offset;
		cal_position = i*pspacing + offset;
		if ( cal_position < pdepth )
		{
			stayposition = cal_position;
		}
		else 
			stayposition = pdepth;
		i++;
		stayposition = stayposition - offset;
		gotoposition(ctx,stayposition,tab_rp_registers);
position1:
			sleep(1);		
			ctx = modbusconnection(ctx);
			curr_position = checkposition(ctx,tab_rp_registers) + offset;
			if(curr_position == -1)
			{
				if(re_power1 < 3)
				{		
					if(re_try1 < 2)
					{
						sleep(3);
						re_try1++;
						goto position1;
					}
					else
					{
						re_try1 = 0;
						enable(0);
						initbus(0);
						sleep(3);
						initbus(1);
						sleep(1);
						re_power1++;
						goto position1;
					}
				}
				else
				{
					enable(0);
					initbus(0);
					enable(1);
					re_power1 = 0;
					return -1;
				}
			}
			if (!((stayposition -0.1) <= curr_position ) && (curr_position <= (stayposition + 0.1)))goto position1;
		wait_for_stop(ctx, tab_rp_registers);
		//Here check position in order to determine if it is destination now 
		curr_position = checkposition(ctx,tab_rp_registers)+offset;
		setconfig(9,curr_position);
		printf("Go to sleep for dwell time\n");
		if(process_pass_through_check() == 0)initbus(0);	// Add this part to check if it is passing command
		sleep(pdwell);
		if (((pdepth -0.1) <= curr_position) && (curr_position <= (pdepth + 0.1))) 
		{ 
			setconfig(5,0);	//Set profile flag here to avoid reprofile if something wrong happens during following
			profile_time_check(pinterval);		// Set next profile time
			enable(0);
			initbus(1);
			ctx = modbusconnection(ctx);
			gotoposition(ctx,0,rd_position_registers);		// After finish profile, go home
			wait_for_stop(ctx, tab_rp_registers);
			sleep(1);
			enable(0);
			if(process_pass_through_check() == 0) initbus(0);	//Check is pass through
			enable(1);
			setconfig(9,offset); //Save the position 0
			sleep(40);
			goto profile;
		}
		goto profile;

	}
/***********************************************************************
*          The next three command_name are used                        *
*             to control the date and time         	                   *
************************************************************************/
	if ( strcmp(command_name, "checktime") == 0 ) 
	{
	/*
		char *sdate;
		if ( (sdate = malloc( 80 * sizeof(char) ) )== NULL)return NULL; 
		sdate = current_time(sdate);
		return_value = json_option_string("status",sdate);
		printf("%s\n",return_value);
		free(sdate);
	*/
		//long pystep = process_read_step(1);
		//process_position(pystep);
		//process_expression(3,1,3,1);
		//process_pass_through_check();
		//process_syncclock();
		process_expression(3,1,3,0);
		process_read_home_switch(1);
    }
	if ( strcmp(command_name, "settime") == 0 ) 
	{
    	if ( argc < 4 ) 
		{ 
			print_comusage (stderr, 1); 
		}
        char *date = argv[2];
        char *time = argv[3];
        int *buf = (int*)malloc(6*sizeof(int)); 
		parse(buf,date,time);
        int i,m_buf[6];
        for(i=0;i<=5;i++) 
		{ 
			m_buf[i]=*(buf+i); 
		}
		feedback = set_time(&m_buf);
        return_value = json_option("status:",feedback);
        printf("%s\n",return_value);
		login("Set local time");
		login(return_value);
		sleep(5);
	}
	if ( strcmp(command_name, "voltage") == 0 ) 
	{
		double voltage;	
		voltage = voltage_read();
		return_value = json_float_option("status",voltage);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "temp") == 0 ) 
	{
		double temp;
		temp = temp_read();
		return_value = json_float_option("status",temp);
		printf("%s\n",return_value);
	}
	if(strcmp(command_name, "enable_power") == 0)
	{
		enable(0);
		initbus(1);
		return_value = json_option("status:",1);
	}

	if(strcmp(command_name, "disable_power") == 0)
	{
		enable(0);
		initbus(0);
		return_value = json_option("status:",1);
	}
	if ( strcmp(command_name, "backup") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr.sl3   /home/sampler/lr_default.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "restore") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr_default.sl3  /home/sampler/lr.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "debug") == 0 ) 
	{
		long return_steps;
		char *debug_result;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		uint16_t *debug_position_registers = (uint16_t*)malloc(2*sizeof(uint16_t));
		debug_result = (char*)malloc(50*sizeof(char));
		return_steps = checksteps(ctx,debug_position_registers);
		sprintf(debug_result,"%x,%x,%x\n",debug_position_registers[0],debug_position_registers[1],return_steps);
		json_option_string("status",debug_result);
		printf("%s\n",debug_result);
		initbus(0);
		
	}
	if ( strcmp(command_name, "power_check") == 0 ) 
	{
		int power_status = check_power();
		printf("Power is %d\n",power_status);
	}
	if ( strcmp(command_name, "sdl") == 0 ) 
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl != NULL)
		{
			double vol = sdltest(sdl);
			return_value = json_float_option("status",vol);
			printf("%s\n",return_value);
			setsdl(30000,vol);
			login("Read SDL");
			login(return_value);
		}
		else setsdl(30000,-100000);
		modbus_close(sdl);
  		modbus_free(sdl);
	}
	if ( strcmp(command_name, "sdl_reset") == 0 ) 
	{
		resetsdl();
	}
	if ( strcmp(command_name, "sdl_get") == 0 ) 
	{
		int num_records;		
		SLEN * sdl_records;
		sdl_records = (SLEN*)malloc(100*sizeof(SLEN));
		sdl_records = getsdl(&num_records, sdl_records);
		return_value = json_sdl_option(num_records,sdl_records);
		printf("%s\n",return_value);
		free(sdl_records);
	}
	if ( strcmp(command_name, "sdl_uploadtime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_setuploadtime(sdl,12,5,21,12,50,0);
	}
	if ( strcmp(command_name, "sdl_settime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else  sdl_rtc_time(sdl,12,5,25,7,58,0);
	}
	if ( strcmp(command_name, "sdl_readsize") == 0 )
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_readbuffsize(sdl);
	} 
	if ( strcmp(command_name, "sdl_readsensor") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_read_sensor(sdl,1,1);
	}
	if ( strcmp(command_name, "sdl_upload") == 0 ) 
	{
		//sdl_read_log_data(16);
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			profile_save_data(sdl);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "sdl_sample") == 0 ) 
	{
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			sdl_read_sensor(sdl,1,1);
			sleep(60);
			sample_save_data(sdl);
			//sdl_start_profile(sdl,2);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "shutdown") == 0 ) 
	{
		feedback = system("/sbin/shutdown now");
	}
	if ( strcmp(command_name, "maxstep") == 0 ) 
	{
		enable(0);
		initbus(1);		
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		feedback = set_max_step(ctx,rd_position_registers);
		return_value = json_option("status",feedback);
		initbus(0);
	}
	if(strcmp(command_name, "slave") == 0)
	{
		slave();
	} 
	if(strcmp(command_name, "motor_status") == 0) 
	{
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = checkmotorstatus(ctx,tab_rp_registers);
			if(feedback == -1)
			{
				printf("0\n");				
				return 0;
			}
			else 
			{
				printf("%d\n",feedback);
				return feedback;
			}
		}
		else
		{
			printf("0\n");
			return 0;
		}		
	}
close:
	/* Free the memory */
	free(config);
    free(tab_rp_registers);
	free(rd_position_registers);
	//modbus_mapping_free(mb_mapping);
    /* Close the connection */
	if (modbus == 1)	
	{
    	modbus_close(ctx);
	}
	if (motor_stop == 1) 
	{
		printf("stop setting\n");
		setconfig(9,last_position);
	}
    return return_value;
}
示例#15
0
int main(int argc, char **argv)
{
    int sock;
    struct ifreq req;
    char *action = NULL;
    prgname = argv[0];

    if (argc < 2) {
        fprintf(stderr,"%s: usage is \"%s <ifname> [<operation>]\"\n",
                prgname, prgname);
        exit(1);
    }
    strcpy(req.ifr_name, argv[1]);
    argc--; argv++; /* shift the interface out */

    /* a silly raw socket just for ioctl()ling it */
    sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    if (sock < 0) {
        fprintf(stderr, "%s: socket(): %s\n", argv[0],strerror(errno));
        exit(1);
    }

    if (getconfig(sock,&req, (argc==1) )) /* print if no commands */
        exit(1);

    /* ok, now loop through the options */
    while (argc > 1) {
        char *value;
        int ivalue = 0;

        action = argv[1];
        value = strchr(action,'=');
        if (value) {
            *value=0; /* terminate action */
            value++; /* skip the terminator */
            sscanf(value,"%i",&ivalue);
            /* fprintf(stderr,"--> %s %i\n",action,ivalue); */
        }
        if (!strcmp(action,"mem_start"))
            req.ifr_map.mem_start=ivalue;
        else if (!strcmp(action,"mem_end"))
            req.ifr_map.mem_end=ivalue;
        else if (!strcmp(action,"io"))
            req.ifr_map.base_addr=ivalue;
        else if (!strcmp(action,"irq"))
            req.ifr_map.irq=ivalue;
        else if (!strcmp(action,"dma"))
            req.ifr_map.dma=ivalue;
        else if (!strcmp(action,"port"))
            req.ifr_map.port=ivalue;
        else if (!strcmp(action,"tell"))
            getconfig(sock,&req, 1);
        else {
            fprintf(stderr,"%s: unknown argument \"%s\"\n",
                    prgname,action);
            argc--; argv++; continue;
        }
        if (strcmp(action,"tell"))
            setconfig(sock,&req);
        argc--; argv++;
    }
    exit(0);
}
示例#16
0
int ntpsim(int argc, char *argv[])
{
    Event *curr_event;
    struct timeval seed;

    /* Initialize the local Clock 
     */
    simclock.local_time = 0;
    simclock.adj = 0;
    simclock.slew = 0;

    /* Initialize the simulation 
     */
    simulation.num_of_servers = 0;
    simulation.beep_delay = BEEP_DLY;
    simulation.sim_time = 0;
    simulation.end_time = SIM_TIME;

    /*
     * Initialize ntp variables
     */
    initializing = 1;
    init_auth();
    init_util();
    init_restrict();
    init_mon();
    init_timer();
    init_lib();
    init_request();
    init_control();
    init_peer();
    init_proto();
    init_io();
    init_loopfilter();
    mon_start(MON_OFF);    

    /* Call getconfig to parse the configuration file */
    getconfig(argc, argv);
    initializing = 0;
    loop_config(LOOP_DRIFTCOMP, old_drift / 1e6);

    /*
     * Watch out here, we want the real time, not the silly stuff.
     */
    gettimeofday(&seed, NULL);
    ntp_srandom(seed.tv_usec);


    /* Initialize the event queue */
    event_queue = create_priority_queue((int(*)(void *, void*)) 
					determine_event_ordering);

    /* Initialize the receive queue */
    recv_queue = create_priority_queue((int(*)(void *, void*))
				       determine_recv_buf_ordering);

    /* Push a beep and a timer on the event queue */
    enqueue(event_queue, event(0, BEEP));
    enqueue(event_queue, event(simulation.sim_time + 1.0, TIMER));
    /* 
     * Pop the queue until nothing is left or time is exceeded
     */
    /* maxtime = simulation.sim_time + simulation.end_time;*/
    while (simulation.sim_time <= simulation.end_time &&
	   (!empty(event_queue))) {
	curr_event = dequeue(event_queue);
	/* Update all the clocks to the time on the event */
	sim_update_clocks(curr_event);

	/* Execute the function associated with the event */
	event_ptr[curr_event->function](curr_event);
	free_node(curr_event);
    }
    return (0);
}
示例#17
0
static int
loadconfig(void)
{
  FILE *fp;
  char *tok, *str, *s2;
  char *f1, *f2, *f3;
  int len;
  struct fontmap *fnew;

  fp = openconfig(CAIROCONF);
  if (fp == NULL)
    return 0;

  while ((tok = getconfig(fp, &str))) {
    s2 = str;
    if (strcmp(tok, "font") == 0) {
      f1 = getitok2(&s2, &len, ",");
      f2 = getitok2(&s2, &len, ",");
      for (; (s2[0] != '\0') && (strchr(" \x09,", s2[0])); s2++);
      f3 = getitok2(&s2, &len, "");
      if (f1 && f2) {
	fnew = create_font_map(f1, f2, f3);
	g_free(f1);
	g_free(f2);
	if (fnew == NULL) {
	  g_free(tok);
	  closeconfig(fp);
	  return 1;
	}
      } else {
	g_free(f1);
	g_free(f2);
      }
      g_free(f3);
    } else if (strcmp(tok, "font_map") == 0) { /* for backward compatibility */
      char *f4, *endptr;
      int two_byte;

      OldConfigExist = TRUE;
      f1 = getitok2(&s2, &len, " \t,");
      f3 = getitok2(&s2, &len, " \t,");
      f4 = getitok2(&s2, &len, " \t,");
      two_byte = strtol(f4, &endptr, 10);
      g_free(f3);
      g_free(f4);
      for (; (s2[0] != '\0') && (strchr(" \x09,", s2[0])); s2++);
      f2 = getitok2(&s2, &len, "");
      fnew = NULL;
      if (f1 && f2) {
	struct compatible_font_info *info;
	struct fontmap *tmp;

	info = gra2cairo_get_compatible_font_info(f1);

	if (info) {
	  if (nhash_get_ptr(Gra2cairoConf->fontmap, info->name, (void *) &tmp)) {
	    g_free(f1);
	    f1 = g_strdup(info->name);
	    if (f1) {
	      fnew = create_font_map(f1, f2, NULL);
	    }
	    if (fnew == NULL) {
	      g_free(tok);
	      g_free(f1);
	      g_free(f2);
	      closeconfig(fp);
	      return 1;
	    }
	  } else {
	    if (two_byte) {
	      gra2cairo_set_alternative_font(info->name, f2);
	    }
	  }
	}
      }
      g_free(f1);
      g_free(f2);
    } else {
      fprintf(stderr, "(%s): configuration '%s' in section %s is not used.\n", AppName,tok, CAIROCONF);
    }
    g_free(tok);
    g_free(str);
  }
  closeconfig(fp);
  return 0;
}
示例#18
0
int main(int argc, char** argv) {

    argp_parse(&argp, argc, argv, 0, 0, 0);


    char name1[30];
    char name2[30];
    printf("Welcome. Before we start, enter your names. Player 1: \n");
    scanf(" %s", name1);
    printf("Player 2: \n");
    scanf(" %s", name2);
    printf("%s begins the game. \n", name1);

    c = getconfig(); //getting configuration from config.txt via fileLoading

    char figures[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    int convert[26];
    int m;
    for (m = 0; m <= 35; m++) {
        repeat_fig[m] = 0; //filling array of repetitions with zeros
        if (m >= 10 && m <= 35) { //filling conversion array with numbers from 10 to 35
            convert[m - 10] = m;
        }

    }
    int input2;
    max_fig = c.base - 1;
    int end = 0;
    int n = 0;
    char *game = malloc(200 * sizeof (char)); //for saving created number
    while (end == 0) {
        for (m = 0; m < n; m++) {
            printf("%c", game[m]);
        }
        scanf(" %c", &input);
        input = tolower(input);
        for (m = 0; m <= 25; m++) { //converting letters to decimal numbers
            if (input == figures[m]) {
                input2 = convert[m];
                break;
            } else {
                int x = input - '0'; //changing char to integer
                input2 = x;
                break;
            }
        }

        if (checkInput(input2) == 1) {
            printf("You entered wrong number.\n");
            for (m = input2; m <= 35; m++) { //checking if a player can enter any more numbers
                if (repeat_fig[m] == c.repeat) {
                    end = 1;
                    printf("End\n");
                    free(game);
                    break;
                }
                else {
                    end = 0;
                    break;
                }
            }
        } else {
            game[n] = input;
            n++;
            repeat_fig[input2] = repeat_fig[input2] + 1;
            score++;
            prev_input = input2;
        }

    }
    if (score % 2 == 0) printf("The winner is %s.\n", name2);
    else printf("The winner is %s.\n", name1);
}
示例#19
0
int main(int argc, char **argv) 
{
    int listenfd, connfd, port, clientlen;
    pid_t pid;
    struct sockaddr_in clientaddr;
    char daemon=0,*portp=NULL,*logp=NULL,tmpcwd[MAXLINE];

    cwd=(char*)get_current_dir_name();	
    strcpy(tmpcwd,cwd);
    strcat(tmpcwd,"/");
    /* parse argv */
    parse_option(argc,argv,&daemon,&portp,&logp);
    portp==NULL ?(port=atoi(getconfig("port"))) : (port=atoi(portp));

    /* init log */
    if(logp==NULL) 
    	logp=getconfig("log");
    initlog(strcat(tmpcwd,logp));

    /* whethe show dir */
    if(strcmp(getconfig("dir"),"no")==0)
    	isShowdir=0;	
    	
    if(daemon==1||strcmp(getconfig("daemon"),"yes")==0)
	init_daemon();

    listenfd = Open_listenfd(port);


    /* $https start  */ 

    if((pid=Fork())==0)
    {
       listenfd= Open_listenfd(4444);
	ssl_init();

    	while(1)
	{
		clientlen = sizeof(clientaddr);
		connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
		if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
		{
		clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
		continue;
		}

		if((pid=Fork())>0)
		{
			close(connfd);
			continue;
		}
		else if(pid==0)
		{
			ishttps=1;	
			doit(connfd);
		}
	}
    }

    /* $end https */

    while (1)
    {
	clientlen = sizeof(clientaddr);
	connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
	if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
	{
	    clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
	    continue;
	}

	if((pid=Fork())>0)
	{
		close(connfd);
		continue;
	}
	else if(pid==0)
	{
		doit(connfd);
	}

    }
}
示例#20
0
void os_process_arguments (int argc, char *argv[])
{
    int c, i;

    char *p = NULL;
    char *blorb_ext = NULL;

    char *home;
    char configfile[FILENAME_MAX + 1];

#ifndef WIN32
    if ((getuid() == 0) || (geteuid() == 0)) {
        printf("I won't run as root!\n");
        exit(1);
    }
#endif

#ifdef WIN32
#define HOMEDIR "USERPROFILE"
#else
#define HOMEDIR "HOME"
#endif

    if ((home = getenv(HOMEDIR)) == NULL) {
        printf("Hard drive on fire!\n");
        exit(1);
    }

/*
 * It doesn't look like Frotz can reliably be resized given its current
 * screen-handling code.  While playing with Nitfol, I noticed that it
 * resized itself fairly reliably, even though the terminal looked rather
 * ugly to begin with.  Since Nitfol uses the Glk library for screen I/O,
 * I think there might be something in Glk that can make resizing easier.
 * Something to think about for later.
 *
 */

/*
    if (signal(SIGWINCH, SIG_IGN) != SIG_IGN)
	signal(SIGWINCH, sigwinch_handler);
*/

    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
	signal(SIGINT, sigint_handler);

    /* First check for a "$HOME/.frotzrc". */
    /* If not found, look for CONFIG_DIR/frotz.conf */
    /* $HOME/.frotzrc overrides CONFIG_DIR/frotz.conf */

    strncpy(configfile, home, FILENAME_MAX);
    strncat(configfile, "/", 1);

    strncat(configfile, USER_CONFIG, strlen(USER_CONFIG));
    if (!getconfig(configfile)) {
	strncpy(configfile, CONFIG_DIR, FILENAME_MAX);
	strncat(configfile, "/", 1);	/* added by DJP */
	strncat(configfile, MASTER_CONFIG, FILENAME_MAX-10);
	getconfig(configfile);  /* we're not concerned if this fails */
    }

    /* Parse the options */

    do {
	c = getopt(argc, argv, "aAb:c:def:Fh:il:oOpPqr:s:S:tu:w:xZ:");
	switch(c) {
	  case 'a': f_setup.attribute_assignment = 1; break;
	  case 'A': f_setup.attribute_testing = 1; break;

	  case 'b': u_setup.background_color = getcolor(optarg);
		u_setup.force_color = 1;
		u_setup.disable_color = 0;
		if ((u_setup.background_color < 2) ||
		    (u_setup.background_color > 9))
		  u_setup.background_color = -1;
		break;
	  case 'c': f_setup.context_lines = atoi(optarg); break;
	  case 'd': u_setup.disable_color = 1; break;
	  case 'e': f_setup.sound = 1; break;
	  case 'f': u_setup.foreground_color = getcolor(optarg);
		    u_setup.force_color = 1;
		    u_setup.disable_color = 0;
	            if ((u_setup.foreground_color < 2) ||
			(u_setup.foreground_color > 9))
			u_setup.foreground_color = -1;
		    break;
	  case 'F': u_setup.force_color = 1;
		    u_setup.disable_color = 0;
		    break;
          case 'h': u_setup.screen_height = atoi(optarg); break;
	  case 'i': f_setup.ignore_errors = 1; break;
	  case 'l': f_setup.left_margin = atoi(optarg); break;
	  case 'o': f_setup.object_movement = 1; break;
	  case 'O': f_setup.object_locating = 1; break;
	  case 'p': u_setup.plain_ascii = 1; break;
	  case 'P': f_setup.piracy = 1; break;
	  case 'q': f_setup.sound = 0; break;
	  case 'r': f_setup.right_margin = atoi(optarg); break;
	  case 's': u_setup.random_seed = atoi(optarg); break;
	  case 'S': f_setup.script_cols = atoi(optarg); break;
	  case 't': u_setup.tandy_bit = 1; break;
	  case 'u': f_setup.undo_slots = atoi(optarg); break;
	  case 'w': u_setup.screen_width = atoi(optarg); break;
	  case 'x': f_setup.expand_abbreviations = 1; break;
	  case 'Z': f_setup.err_report_mode = atoi(optarg);
		    if ((f_setup.err_report_mode < ERR_REPORT_NEVER) ||
			(f_setup.err_report_mode > ERR_REPORT_FATAL))
		      f_setup.err_report_mode = ERR_DEFAULT_REPORT_MODE;
		    break;
	}

    } while (c != EOF);

    if (optind != argc - 1) {
	printf("FROTZ V%s\t", VERSION);
#ifdef OSS_SOUND
	printf("oss sound driver, ");
#endif

#ifdef USE_NCURSES
	printf("ncurses interface.");
#else
	printf("curses interface.");
#endif
	putchar('\n');

	puts (INFORMATION);
	printf ("\t-Z # error checking mode (default = %d)\n"
	    "\t     %d = don't report errors   %d = report first error\n"
	    "\t     %d = report all errors     %d = exit after any error\n\n",
	    ERR_DEFAULT_REPORT_MODE, ERR_REPORT_NEVER,
	    ERR_REPORT_ONCE, ERR_REPORT_ALWAYS,
	    ERR_REPORT_FATAL);
	exit (1);
    }

    /* This section is exceedingly messy and really can't be fixed
       without major changes all over the place.
     */

    /* Save the story file name */

    f_setup.story_file = strdup(argv[optind]);
    f_setup.story_name = strdup(basename(argv[optind]));

    /* Now strip off the extension. */
    p = strrchr(f_setup.story_name, '.');
    if ((p != NULL) &&
        ((strcmp(p,EXT_BLORB2) == 0) ||
         (strcmp(p,EXT_BLORB3) == 0) ||
         (strcmp(p,EXT_BLORB4) == 0) ) )
    {
        blorb_ext = strdup(p);
    }
    else
    {
        blorb_ext = strdup(EXT_BLORB);
    }

    /* Get rid of extensions with 1 to 6 character extensions. */
    /* This will take care of an extension like ".zblorb". */
    /* More than that, there might be something weird going on */
    /* which is not our concern. */
    if (p != NULL) {
        if (strlen(p) >= 2 && strlen(p) <= 7) {
                *p = '\0';      /* extension removed */
        }
    }

    f_setup.story_path = strdup(dirname(argv[optind]));

    /* Create nice default file names */

    u_setup.blorb_name = malloc(FILENAME_MAX * sizeof(char));
    strncpy(u_setup.blorb_name, f_setup.story_name,
	strlen(f_setup.story_name) +1);
    strncat(u_setup.blorb_name, blorb_ext, strlen(blorb_ext));

    u_setup.blorb_file = malloc(strlen(f_setup.story_path) *
                sizeof(char) + strlen(u_setup.blorb_name) * sizeof(char) + 4);
    strncpy(u_setup.blorb_file, f_setup.story_path,
	strlen(f_setup.story_path));
    strncat(u_setup.blorb_file, "/", 1);
    strncat(u_setup.blorb_file, u_setup.blorb_name,
	strlen(u_setup.blorb_name) + 1);

    f_setup.script_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.script_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.script_name, EXT_SCRIPT, strlen(EXT_SCRIPT));

    f_setup.command_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.command_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.command_name, EXT_COMMAND, strlen(EXT_COMMAND));

    f_setup.save_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.save_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.save_name, EXT_SAVE, strlen(EXT_SAVE));

    f_setup.aux_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.aux_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.aux_name, EXT_AUX, strlen(EXT_AUX));

    switch (ux_init_blorb()) {
        case bb_err_Format:
	  printf("Blorb file loaded, but unable to build map.\n\n");
	  break;
	case bb_err_NotFound:
	  printf("Blorb file loaded, but lacks executable chunk.\n\n");
	  break;
    }

  printf("u_setup.blorb_file %s\n", u_setup.blorb_file);
  printf("u_setup.blorb_name %s\n", u_setup.blorb_name);

}/* os_process_arguments */
示例#21
0
文件: KOM.c 项目: punktniklas/NiKom
void DoExecuteCommand(struct Kommando *cmd) {
  switch(cmd->nummer) {
  case 201: Cmd_GoConf(); break; // ga(argument);
  case 210: Cmd_NextText(); break;
  case 211: Cmd_NextReply(); break;
  case 221: Cmd_NextConf(); break;
  case 222: GoConf(MAILBOX_CONFID); break;
  case 301: Cmd_Logout(); break;
  case 101: listmot(argument); break;
  case 102: Cmd_ListUsers(); break;
  case 103: listmed(); break;
  case 104: sendfile("NiKom:Texter/ListaKommandon.txt"); break;
  case 105: listratt(); break;
  case 106: listasenaste(); break;
  case 107: listnyheter(); break;
  case 108: listaarende(); break;
  case 109: listflagg(); break;
  case 111: listarea(); break;
  case 112: listnyckel(); break;
  case 113: listfiler(); break;
  case 114: listagrupper(); break;
  case 115: listgruppmed(); break;
  case 116: listabrev(); break;
  case 202: skriv(); break;
  case 203: Cmd_Reply(); break;
  case 204: personlig(); break;
  case 205: skickabrev(); break;
  case 206: igen(); break;
  case 207: atersekom(); break;
  case 208: medlem(argument); break;
  case 209: uttrad(argument); break;
  case 212: Cmd_Read(); break;
  case 213: endast(); break;
  case 214: Cmd_SkipReplies(); break;
  case 215: addratt(); break;
  case 216: subratt(); break;
  case 217: radtext(); break;
  case 218: skapmot(); break;
  case 219: radmot(); break;
  case 220: var(mote2); break;
  case 223: andmot(); break;
  case 224: radbrev(); break;
  case 225: rensatexter(); break;
  case 226: rensabrev(); break;
  case 227: gamlatexter(); break;
  case 228: gamlabrev(); break;
  case 229: dumpatext(); break;
  case 231: movetext(); break;
  case 232: motesstatus(); break;
  case 233: hoppaarende(); break;
  case 234: flyttagren(); break;
  case 235: Cmd_FootNote(); break;
  case 236: Cmd_Search(); break;
  case 237: Cmd_Like(); break;
  case 238: Cmd_Dislike(); break;
  case 302: sendfile("NiKom:Texter/Help.txt"); break;
  case 303: Cmd_ChangeUser(); break;
  case 304: slaav(); break;
  case 305: slapa(); break;
  case 306: tiden(); break;
  case 307: ropa(); break;
  case 308: Cmd_Status(); break;
  case 309: Cmd_DeleteUser(); break;
  case 310: vilka(); break;
  case 311: visainfo(); break;
  case 312: getconfig(); break;
  case 313: writeinfo(); break;
  case 314: sag(); break;
  case 315: skrivlapp(); break;
  case 316: radlapp(); break;
  case 317: grab(); break;
  case 318: skapagrupp(); break;
  case 319: andragrupp(); break;
  case 320: raderagrupp(); break;
  case 321: adderagruppmedlem(); break;
  case 322: subtraheragruppmedlem(); break;
  case 323: DisplayVersionInfo(); break;
  case 324: alias(); break;
  case 325: Cmd_ReLogin(); break;
  case 326: bytnodtyp(); break;
  case 327: bytteckenset(); break;
  case 328: SaveCurrentUser(inloggad, nodnr); break;
  case 329: Cmd_ChangeLanguage(); break;
  case 401: bytarea(); break;
  case 402: filinfo(); break;
  case 403: upload(); break;
  case 404: download(); break;
  case 405: Cmd_CreateArea(); break;
  case 406: radarea(); break;
  case 407: andraarea(); break;
  case 408: skapafil(); break;
  case 409: radfil(); break;
  case 410: andrafil(); break;
  case 411: lagrafil(); break;
  case 412: flyttafil(); break;
  case 413: sokfil(); break;
  case 414: filstatus(); break;
  case 415: typefil(); break;
  case 416: nyafiler(); break;
  case 417: validerafil(); break;
  default:
    if(cmd->nummer >= 500) {
      sendrexx(cmd->nummer);
    } else {
      LogEvent(SYSTEM_LOG, ERROR,
               "Trying to execute undefined command %d", cmd->nummer);
      DisplayInternalError();
    }
  }
}