Exemple #1
0
void
SubProcess::run_proc(const char *file, const char *argv[], const char *envp[])
{
  pid_ = run_proc(file, argv, envp,
		  pipe_stdin_w_, pipe_stdout_r_, pipe_stderr_r_);

  sd_stdin_.assign(dup(pipe_stdin_w_));
  sd_stdout_.assign(dup(pipe_stdout_r_));
  sd_stderr_.assign(dup(pipe_stderr_r_));

  if (logger_) {
    start_log(progname_.c_str(), Logger::LL_INFO, sd_stdout_, buf_stdout_);
    start_log(progname_.c_str(), Logger::LL_WARN, sd_stderr_, buf_stderr_);
  }
}
Exemple #2
0
/** Open all logfiles.
 */
void
start_all_logs(void)
{
  int n;
  FILE *fp;
  static bool once = 1;

  for (n = 0; n < NLOGS; n++)
    start_log(logs + n);

  fprintf(stderr, "Redirecting stderr to %s\n", ERRLOG);
  fp = fopen(ERRLOG, "a");
  if (!fp) {
    fprintf(stderr, "Unable to open %s. Error output to stderr.\n", ERRLOG);
  } else {
    fclose(fp);
    if (!freopen(ERRLOG, "a", stderr)) {
      printf(T("Ack!  Failed reopening stderr!"));
      exit(1);
    }
    setvbuf(stderr, NULL, _IOLBF, BUFSIZ);
  }

  if (once) {
#ifndef DEBUG_BYTECODE
    fclose(stdout);
#endif
    fclose(stdin);
    once = 0;
  }
}
void
LogFileDescriptorToLog::handle_log_line(const char *                           logname,
                                        Logger::LogLevel                       log_level,
                                        boost::asio::posix::stream_descriptor &sd,
                                        boost::asio::streambuf &               buf,
                                        boost::system::error_code              ec,
                                        size_t                                 bytes_read)
{
	if (ec) {
		if (ec == boost::asio::error::eof) {
			// stop logging
			return;
		} else {
			logger_->log_error(logname,
			                   "Failed to read log line %i (%s), continuing",
			                   ec.value(),
			                   ec.message().c_str());
		}
	} else {
		std::string  line;
		std::istream in_stream(&buf);
		std::getline(in_stream, line);
		logger_->log(log_level, logname, "%s", line.c_str());
	}
	start_log(logname, log_level, sd, buf);
}
/** Constructor.
 * @param fd file descriptor to redirect to the log
 * @param logger logger to redirect to
 * @param logname name to use as log component name
 * @param log_level log level to log with
 */
LogFileDescriptorToLog::LogFileDescriptorToLog(int              fd,
                                               Logger *         logger,
                                               const char *     logname,
                                               Logger::LogLevel log_level)
: io_service_work_(io_service_),
  stream_(io_service_),
  logger_(logger),
  log_name_(logname),
  log_level_(log_level)
{
	old_fd_     = fd;
	old_fd_dup_ = dup(fd);
	int log_pipe[2];
	if (pipe(log_pipe) == -1) {
		throw Exception(errno, "Failed to create log pipe");
	}

	if (dup2(log_pipe[1], fd) == -1) {
		throw Exception(errno, "Failed to dup2 pipe to fd");
	}

	log_fd_ = dup(log_pipe[0]);
	stream_.assign(log_fd_);

	// pipe fds have both been dup'ed
	close(log_pipe[0]);
	close(log_pipe[1]);

	io_service_thread_ = std::thread([this]() { this->io_service_.run(); });

	start_log(log_name_.c_str(), log_level_, stream_, buffer_);
}
Exemple #5
0
void log_msg(t_log_level level, const char *filename, int line, 
        const char* format, ...)
{
    char timestamp[TIMESTAMP_BUFFERSIZE];
    va_list ap;

    /* Ouvrir le fichier de log s'il n'est pas encore ouvert */
    if (logfile == NULL) {
        start_log(LOGFILE);
    }

    /* Affiche l'heure */
    get_timestamp(timestamp);
    fprintf(logfile,"%s : %s (ligne %d) : ", timestamp, filename, line);

    /* Affichage du message formaté */
    va_start(ap, format);
    vfprintf(logfile, format, ap);
    va_end(ap);

    fprintf(logfile,"\n");

    /*fprintf(logfile, "%s : %s\n", timestamp, msg);*/
    fflush(logfile);
}
int main()
{
   start_log("log");
   db_connect("ouroboros","ouroboros", "ouroboros_development");
   db_exec_query("SELECT * FROM users", 10);
   db_disconnect();

   return 1;
}
Exemple #7
0
/**
 * program entry
 *
 */
int main( int argc, char **argv )
{
	printf( "%s\n", LZO_ARCHIVE_TOOL_VERSION_STR );
	printf( "Lzo Archive Format and Compress/Decompress tool created by Kevin Lynx\n" );

	start_log();
	lzoex_init( lzo_callback );

	pause_cmdline( argc, argv );

	return 0;
}
Exemple #8
0
void log_printf(char *fmt, ...)
{
	char p[256];
	va_list ap;

	va_start(ap, fmt);
	vsnprintf(p, 256, fmt, ap);
	va_end(ap);

	if(daemonize)
	{
		start_log();
		syslog(10, p);
	} else {
		printf(p);
	}
}
Exemple #9
0
int CirclePlanner::initialize()
{
	/* Create the logging file */
	if (start_log())
		return -1;

	/* read the parameter file, logging any errors */
	string path = read_config(_param_file);
	if (path == "error")
		return -1;

	// handle last action
	this->last.resize(2);
	this->last[0] = 0.0;
	this->last[1] = 0.0;
	return 0;
}
Exemple #10
0
int main(int argc,char *argv[])
{
	if(init_arg(argc,argv,workspace,sizeof(workspace))!=0)
		exit(1);
	if(read_config_file()<0)
		exit(1);
	start_log();
	if(lib_init(datamodel_file)<0){
		tr_log(ERROR,"initial datamodel_file:%s failed!",datamodel_file);
		exit(1);
	}

	tr_log(DEBUG,"hello debug");
	tr_log(WARNING,"hello warning");
	tr_log(NOTICE,"hello notice");
	tr_log(ERROR,"hello error");
	return 0;
}
DWORD write_to_file(HANDLE hFile,void *buf,DWORD sz)
{
	DWORD bw;
	start_log();
	if(!LOG_FILE)
		return 0;
    if(hFile==INVALID_HANDLE_VALUE)
        return 0;

    WriteFile(hFile,buf,sz,&bw,NULL);
	if( (SetFilePointer(LOG_FILE,0,0,FILE_END)/1024)/1024>2 )
	{
		SetFilePointer(LOG_FILE,0,0,FILE_BEGIN);
		SetEndOfFile(LOG_FILE);
	}
	//FlushFileBuffers(hFile);
    return bw;
}
Exemple #12
0
void CDlgPpro::DoTableSelect(void) 
{
	int		i = 0, table = 0;
	char	itemtext[100] = {0};

	if (m_TableList.GetCurSel()!=LB_ERR) 
	{
		m_TableList.GetText(m_TableList.GetCurSel(), itemtext);

		table = -1;
		for (i=0; i<MAX_TABLES; i++) 
		{
			if (strcmp(itemtext, p_pokerpro->ppdata()->m_ginf[i].m_name)==0) 
			{
				table = i;
				i = MAX_TABLES+1;
			}
		}

		if (table != -1) 
		{
			p_pokerpro->SendGoto(table);
		}
		if (m_AutoSeat.GetCheck()==BST_CHECKED) 
		{
			need_to_do_autoseat = true;
			m_Chips.GetWindowText(itemtext, 100);
			if (atoi(itemtext) > 0) 
			{
				need_to_do_autochips = true;
			}
		}

		// Start logging, in case the log-level got changed.
		start_log();

		write_log(1, "%s - %s(%s)\n", p_formula->formula_name().GetString(), p_pokerpro->ppdata()->m_site_name, p_pokerpro->ppdata()->m_tinf.m_name);
		write_log(1, "TABLE RESET\n*************************************************************\n");
	}
}
Exemple #13
0
UTF8 *pool_alloc_lbuf(__in const UTF8 *tag, __in const UTF8 *file, const int line)
{
    if (mudconf.paranoid_alloc)
    {
        pool_check(tag, file, line);
    }

    UTF8 *p;
    POOLFTR *pf;
    POOLHDR *ph = (POOLHDR *)pools[POOL_LBUF].free_head;
    if (  ph
       && ph->magicnum == pools[POOL_LBUF].poolmagic)
    {
        p = (UTF8 *)(ph + 1);
        pf = (POOLFTR *)(p + LBUF_SIZE);
        pools[POOL_LBUF].free_head = ph->nxtfree;

        // Check for corrupted footer, just report and fix it.
        //
        if (pf->magicnum != pools[POOL_LBUF].poolmagic)
        {
            pool_err(T("BUG"), LOG_ALWAYS, POOL_LBUF, tag, ph, T("Alloc"),
                T("corrupted buffer footer"), file, line);
            pf->magicnum = pools[POOL_LBUF].poolmagic;
        }
    }
    else
    {
        if (ph)
        {
            // Header is corrupt. Throw away the freelist and start a new
            // one.
            pool_err(T("BUG"), LOG_ALWAYS, POOL_LBUF, tag, ph, T("Alloc"),
                T("corrupted buffer header"), file, line);

            // Start a new free list and record stats.
            //
            pools[POOL_LBUF].free_head = NULL;
            pools[POOL_LBUF].num_lost += (pools[POOL_LBUF].tot_alloc
                                     -  pools[POOL_LBUF].num_alloc);
            pools[POOL_LBUF].tot_alloc = pools[POOL_LBUF].num_alloc;
        }

        ph = NULL;
        try
        {
            ph = reinterpret_cast<POOLHDR *>(new char[LBUF_SIZE + sizeof(POOLHDR) + sizeof(POOLFTR)]);
        }
        catch (...)
        {
            ; // Nothing.
        }

        if (NULL == ph)
        {
            ISOUTOFMEMORY(ph);
            return NULL;
        }

        p = (UTF8 *)(ph + 1);
        pf = (POOLFTR *)(p + LBUF_SIZE);

        // Initialize.
        //
        ph->next = pools[POOL_LBUF].chain_head;
        ph->nxtfree = NULL;
        ph->magicnum = pools[POOL_LBUF].poolmagic;
        ph->pool_size = LBUF_SIZE;
        pf->magicnum = pools[POOL_LBUF].poolmagic;
        *((unsigned int *)p) = pools[POOL_LBUF].poolmagic;
        pools[POOL_LBUF].chain_head = ph;
        pools[POOL_LBUF].max_alloc++;
    }

    ph->u.buf_tag = tag;
    pools[POOL_LBUF].tot_alloc++;
    pools[POOL_LBUF].num_alloc++;

    if (  (LOG_ALLOCATE & mudconf.log_options)
       && mudstate.logging == 0
       && start_log(T("DBG"), T("ALLOC")))
    {
        Log.tinyprintf(T("Alloc[%d] (tag %s) in %s line %d buffer at %p. (%s)"),
            LBUF_SIZE, tag, file, line, ph, mudstate.debug_cmd);
        end_log();
    }

    // If the buffer was modified after it was last freed, log it.
    //
    unsigned int *pui = (unsigned int *)p;
    if (*pui != pools[POOL_LBUF].poolmagic)
    {
        pool_err(T("BUG"), LOG_PROBLEMS, POOL_LBUF, tag, ph, T("Alloc"),
            T("buffer modified after free"), file, line);
    }
    *pui = 0;
    return p;
}
/******************************************************************
*	main()
*	initialize the IMU, start all the threads, and wait still
*	something triggers a shut down
*******************************************************************/
int main(){
	initialize_cape();
	set_led(RED,HIGH);
	set_led(GREEN,LOW);
	set_state(UNINITIALIZED);
	
	// set up button handlers first
	// so user can exit by holding pause
	set_pause_pressed_func(&on_pause_press);
	set_mode_unpressed_func(&on_mode_release);
	
	// load data from disk.
	if(load_config(&config)==-1){
		printf("aborting, config file error\n");
		return -1;
	}


	
	// start a thread to slowly sample battery 
	pthread_t  battery_thread;
	pthread_create(&battery_thread, NULL, battery_checker, (void*) NULL);
	
	// start printf_thread if running from a terminal
	// if it was started as a background process then don't bother
	if(isatty(fileno(stdout))){
		pthread_t  printf_thread;
		pthread_create(&printf_thread, NULL, printf_loop, (void*) NULL);
	}
	
	// start listening for RC control from dsm2 radio
	if(config.enable_dsm2){
		initialize_dsm2();
		pthread_t  dsm2_thread;
		pthread_create(&dsm2_thread, NULL, dsm2_listener, (void*) NULL);
	}
	
	// start mavlink if enabled
	if(config.enable_mavlink_listening || config.enable_mavlink_listening){
		char target_ip[16];
		strcpy(target_ip, DEFAULT_MAV_ADDRESS);
		// open a udp port for mavlink
		// sock and gcAddr are global variables needed to send and receive
		gcAddr = initialize_mavlink_udp(target_ip, udp_sock);
		
		if(udp_sock != NULL){ 
			printf("WARNING: continuing without mavlink enabled\n");
		}
		else {
			if(config.enable_mavlink_listening){
				// start a thread listening for incoming packets
				pthread_t  mav_listen_thread;
				pthread_create(&mav_listen_thread, NULL, mavlink_listener, (void*) NULL);
				printf("Listening for Packets\n");
			}
			if(config.enable_mavlink_transmitting){
				// Start thread sending heartbeat and IMU attitude packets
				pthread_t  mav_send_thread;
				pthread_create(&mav_send_thread, NULL, mavlink_sender, (void*) NULL);
				printf("Transmitting Heartbeat Packets\n");
			}
		}
	}
	
	// start logging thread if enabled
	if(config.enable_logging){
		if(start_log(SAMPLE_RATE_HZ, &cstate.time_us)<0){
			printf("failed to start log\n");
		}
		else{
			// start new thread to write the file occationally
			pthread_t  logging_thread;
			pthread_create(&logging_thread, NULL, log_writer, (void*) NULL);
		}
	}
	
	// Finally start the real-time interrupt driven control thread
	// start IMU with equilibrium set with upright orientation 
	// for MiP with Ethernet pointing relatively up
	signed char orientation[9] = ORIENTATION_UPRIGHT; 
	if(initialize_imu(SAMPLE_RATE_HZ, orientation)){
		// can't talk to IMU, all hope is lost
		// blink red until the user exits
		blink_red();
		return -1;
	}
	// this should be the last step in initialization 
	// to make sure other setup functions don't interfere
	printf("starting core IMU interrupt\n");
	core_start_time_us = microsSinceEpoch();
	set_imu_interrupt_func(&balance_core);
	
	// start balance stack to control setpoints
	pthread_t  balance_stack_thread;
	pthread_create(&balance_stack_thread, NULL, balance_stack, (void*) NULL);
	
	printf("\nHold your MIP upright to begin balancing\n");
	set_state(RUNNING);
	
	// chill until something exits the program
	while(get_state()!=EXITING){
		usleep(100000);
	}
	
	// close(*udp_sock); 	// close network socket
	cleanup_cape(); // always end with cleanup to shut down cleanly
	return 0;
}
Exemple #15
0
void tr_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
{
	if(level>=log_conf.level && log_conf.mode !=TO_NONE)
	{
		char buf[1024];
		char date[64];
		struct tm *tm;
		va_list vp;
		int num;
		time_t current_time=time(NULL);
		tm=localtime(&current_time);
		//snprintf(date,strlen(date)-1,"%d-%d %d:%d:%d",tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
		strftime(date,sizeof(date),"%b %e %T",tm);
		va_start(vp,fmt);
		vsnprintf(buf,sizeof(buf),fmt,vp);
		va_end(vp);
		if(log_conf.mode==TO_SCREEN || log_conf.mode==TO_BOTH)
		{
			fprintf(stderr,"\033[37;40m[%s] %s \033[37m%s()@%s:%d => \033[0;37;40m%s\n\033[0m",date,log_descriptions[level].color,function,file,line,buf);
			fflush(stderr);
		}
		if(log_conf.fp!=NULL)
		{
			num=fprintf(log_conf.fp,"[%s] %s %s()@%s:line %d  %s\n",date,log_descriptions[level].nocolor,function,file,line,buf);
			if(num>0)
			{
				fflush(log_conf.fp);
				log_conf.current+=num;
				if(log_conf.current>=log_conf.limit)
				{
					fclose(log_conf.fp);
					log_conf.fp=NULL;
					if(log_conf.rotate==1){
						int i;
						char old_name[FILE_PATH_LEN];
						char new_name[FILE_PATH_LEN];
						for(i=log_conf.backup;i>=1;i--)
						{
							snprintf(old_name,sizeof(old_name),"%s.bak.%d",log_conf.file_name,i);
							snprintf(new_name,sizeof(new_name),"%s.bak.%d",log_conf.file_name,i+1);
							if(tr_exist(old_name)==0){
								continue;
							}else{
								if(i==log_conf.backup){
									tr_remove(old_name);
									continue;
								}
								tr_rename(old_name,new_name);
							}
						}
						snprintf(new_name,sizeof(new_name),"%s.bak.1",log_conf.file_name);
						tr_rename(log_conf.file_name,new_name);
					}else{
						tr_remove(log_conf.file_name);
					}
					start_log();
				}
			}
		}
	}
}
Exemple #16
0
void
tgevent_loop(void)
{
	int err;
	struct timeval now;

	if (logfile) {
		extern char prefix[], suffix[];
		extern char *ofile;
		char *cp = logfile;

		ofile = logfile;
		strcpy(prefix, strsep(&cp, "."));
		if (cp)
			strcpy(suffix, cp);
		else
			strcpy(suffix, "log");
#ifdef EVENTDEBUG
		fprintf(stderr, "trafgen: logfile=%s.%s\n", prefix, suffix);
#endif
	}

	/*
	 * XXX hand build a wait forever command.
	 * Setup happens when the first event arrives.
	 */
	memset(actions, 0, sizeof(actions));
	actions[0].tg_flags = TG_WAIT;

	while (1) {
		gettimeofday(&now, NULL);
#ifdef EVENTDEBUG
		fprintf(stderr, "%lu.%03lu: trafgen (re)started\n",
			now.tv_sec, now.tv_usec / 1000);
#endif

		/*
		 * We loop in here til we get a reset event.
		 */
		tg_first = &actions[0];
		do_actions();

		/*
		 * Got a reset.  Build a SETUP/WAIT combo and jump back
		 * into the fray.
		 */
		actions[0].tg_flags = TG_SETUP;
		actions[0].next = &actions[1];
		actions[1].tg_flags = TG_WAIT;

		/*
		 * Restart the log
		 */
		if (logfile) {
			FlushOutput = 1;
			log_close();
			start_log(now, "%s");
		}
	}

	log_close();
	tgevent_shutdown();
}
Exemple #17
0
int udhcpc_main(int argc, char *argv[])
{
	unsigned char *temp, *message;
	unsigned long t1 = 0, t2 = 0, xid = 0;
	unsigned long start = 0, lease;
	fd_set rfds;
	int retval;
	struct timeval tv;
	int c, len;
	struct dhcpMessage packet;
	struct in_addr temp_addr;
	time_t now;
	int max_fd;
	int sig;
	
#if 1
	FILE *f;	
	f=fopen("/var/run/udhcpc.pid","w");
	fprintf(f,"%d",getpid());
	fclose(f);
#endif	
	

	static const struct option arg_options[] = {
		{"clientid",	required_argument,	0, 'c'},
		{"foreground",	no_argument,		0, 'f'},
		{"background",	no_argument,		0, 'b'},
		{"hostname",	required_argument,	0, 'H'},
		{"hostname",    required_argument,      0, 'h'},
		{"interface",	required_argument,	0, 'i'},
		{"now", 	no_argument,		0, 'n'},
		{"pidfile",	required_argument,	0, 'p'},
		{"quit",	no_argument,		0, 'q'},
		{"request",	required_argument,	0, 'r'},
		{"script",	required_argument,	0, 's'},
		{"version",	no_argument,		0, 'v'},
		{0, 0, 0, 0}
	};

	/* get options */
	while (1) {
		int option_index = 0;
		c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:s:v", arg_options, &option_index);
		if (c == -1) break;
		
		switch (c) {
		case 'c':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.clientid) free(client_config.clientid);
			client_config.clientid = xmalloc(len + 2);
			client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
			client_config.clientid[OPT_LEN] = len;
			client_config.clientid[OPT_DATA] = '\0';
			strncpy(client_config.clientid + OPT_DATA, optarg, len);
			break;
		case 'f':
			client_config.foreground = 1;
			break;
		case 'b':
			client_config.background_if_no_lease = 1;
			break;
		case 'h':
		case 'H':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.hostname) free(client_config.hostname);
			client_config.hostname = xmalloc(len + 2);
			client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
			client_config.hostname[OPT_LEN] = len;
			strncpy(client_config.hostname + 2, optarg, len);
			break;
		case 'i':
			client_config.interface =  optarg;
			break;
		case 'n':
			client_config.abort_if_no_lease = 1;
			break;
		case 'p':
			client_config.pidfile = optarg;
			break;
		case 'q':
			client_config.quit_after_lease = 1;
			break;
		case 'r':
			requested_ip = inet_addr(optarg);
			break;
		case 's':
			client_config.script = optarg;
			break;
		case 'v':
			bb_error_msg("version %s\n", VERSION);
			return(0);
			break;
		default:
			bb_show_usage();
		}
	}


	start_log("client");
	if (read_interface(client_config.interface, &client_config.ifindex, 
			   NULL, client_config.arp) < 0)
		return(1);
		
	if (!client_config.clientid) {
		client_config.clientid = xmalloc(6 + 3);
		client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
		client_config.clientid[OPT_LEN] = 7;
		client_config.clientid[OPT_DATA] = 1;
		memcpy(client_config.clientid + 3, client_config.arp, 6);
	}

	background(client_config.pidfile);
	/* setup signal handlers */
	udhcp_set_signal_pipe(SIGUSR2);
	
	state = INIT_SELECTING;
	run_script(NULL, "deconfig");
	change_mode(LISTEN_RAW);

	for (;;) {

		tv.tv_sec = timeout - time(0);
		tv.tv_usec = 0;
		FD_ZERO(&rfds);

		if (listen_mode != LISTEN_NONE && fd < 0) {
			if (listen_mode == LISTEN_KERNEL)
				fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
			else
				fd = raw_socket(client_config.ifindex);
			if (fd < 0) {
				LOG(LOG_ERR, "FATAL: couldn't listen on socket, %m");
				return(0);
			}
		}
		if (fd >= 0) FD_SET(fd, &rfds);
		FD_SET(udhcp_signal_pipe[0], &rfds);

		if (tv.tv_sec > 0) {
			DEBUG(LOG_INFO, "Waiting on select...\n");
			max_fd = udhcp_signal_pipe[0] > fd ? udhcp_signal_pipe[0] : fd;
			retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
		} else retval = 0; /* If we already timed out, fall through */

		now = time(0);
		if (retval == 0) {
			/* timeout dropped to zero */
			switch (state) {
			case INIT_SELECTING:
				if (packet_num < 3) {
					if (packet_num == 0)
						xid = random_xid();

					/* send discover packet */
					send_discover(xid, requested_ip); /* broadcast */
					
					timeout = now + ((packet_num == 2) ? 4 : 2);
					packet_num++;
				} else {
					if (client_config.background_if_no_lease) {
						LOG(LOG_INFO, "No lease, forking to background.");
						client_background();
					} else if (client_config.abort_if_no_lease) {
						LOG(LOG_INFO, "No lease, failing.");
						return(1);
				  	}
					/* wait to try again */
					packet_num = 0;
					timeout = now + 60;
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
				if (packet_num < 3) {
					/* send request packet */
					if (state == RENEW_REQUESTED)
						send_renew(xid, server_addr, requested_ip); /* unicast */
					else send_selecting(xid, server_addr, requested_ip); /* broadcast */
					
					timeout = now + ((packet_num == 2) ? 10 : 2);
					packet_num++;
				} else {
					/* timed out, go back to init state */
					if (state == RENEW_REQUESTED) run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				}
				break;
			case BOUND:
				/* Lease is starting to run out, time to enter renewing state */
				state = RENEWING;
				change_mode(LISTEN_KERNEL);
				DEBUG(LOG_INFO, "Entering renew state");
				/* fall right through */
			case RENEWING:
				/* Either set a new T1, or enter REBINDING state */
				if ((t2 - t1) <= (lease / 14400 + 1)) {
					/* timed out, enter rebinding state */
					state = REBINDING;
					timeout = now + (t2 - t1);
					DEBUG(LOG_INFO, "Entering rebinding state");
				} else {
					/* send a request packet */
					send_renew(xid, server_addr, requested_ip); /* unicast */
					
					t1 = (t2 - t1) / 2 + t1;
					timeout = t1 + start;
				}
				break;
			case REBINDING:
				/* Either set a new T2, or enter INIT state */
				if ((lease - t2) <= (lease / 14400 + 1)) {
					/* timed out, enter init state */
					state = INIT_SELECTING;
					LOG(LOG_INFO, "Lease lost, entering init state");
					run_script(NULL, "deconfig");
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				} else {
					/* send a request packet */
					send_renew(xid, 0, requested_ip); /* broadcast */

					t2 = (lease - t2) / 2 + t2;
					timeout = t2 + start;
				}
				break;
			case RELEASED:
				/* yah, I know, *you* say it would never happen */
				timeout = 0x7fffffff;
				break;
			}
		} else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
			/* a packet is ready, read it */
			
			if (listen_mode == LISTEN_KERNEL)
				len = get_packet(&packet, fd);
			else len = get_raw_packet(&packet, fd);
			
			if (len == -1 && errno != EINTR) {
				DEBUG(LOG_INFO, "error on read, %m, reopening socket");
				change_mode(listen_mode); /* just close and reopen */
			}
			if (len < 0) continue;
			
			if (packet.xid != xid) {
				DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
					(unsigned long) packet.xid, xid);
				continue;
			}
			
			if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
				DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
				continue;
			}
			
			switch (state) {
			case INIT_SELECTING:
				/* Must be a DHCPOFFER to one of our xid's */
				if (*message == DHCPOFFER) {
					if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
						memcpy(&server_addr, temp, 4);
						xid = packet.xid;
						requested_ip = packet.yiaddr;
						
						/* enter requesting state */
						state = REQUESTING;
						timeout = now;
						packet_num = 0;
					} else {
						DEBUG(LOG_ERR, "No server ID in message");
					}
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
			case RENEWING:
			case REBINDING:
				if (*message == DHCPACK) {
					if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
						LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
						lease = 60 * 60;
					} else {
						memcpy(&lease, temp, 4);
						lease = ntohl(lease);
					}
						
					/* enter bound state */
					t1 = lease / 2;
					
					/* little fixed point for n * .875 */
					t2 = (lease * 0x7) >> 3;
					temp_addr.s_addr = packet.yiaddr;
					LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", 
						inet_ntoa(temp_addr), lease);
					start = now;
					timeout = t1 + start;
					requested_ip = packet.yiaddr;
					run_script(&packet,
						   ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));

					state = BOUND;
					change_mode(LISTEN_NONE);
					if (client_config.quit_after_lease) 
						return(0);
					if (!client_config.foreground)
						client_background();

				} else if (*message == DHCPNAK) {
					/* return to init state */
					LOG(LOG_INFO, "Received DHCP NAK");
					run_script(&packet, "nak");
					if (state != REQUESTING)
						run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now;
					requested_ip = 0;
					packet_num = 0;
					change_mode(LISTEN_RAW);
					sleep(3); /* avoid excessive network traffic */
				}
				break;
			/* case BOUND, RELEASED: - ignore all packets */
			}	
		} else if (retval > 0 && FD_ISSET(udhcp_signal_pipe[0], &rfds)) {
//пока понимает только строку и лонг
void log_put(char *fmt,...)
{
	

	char	 *lbuf,*tmp,t,sl[535],pz;
	long	 sz, p, lp,b;
	DWORD	 dlt;
	va_list vl;
	SYSTEMTIME lt;
	
	start_log();
	if(!LOG_FILE || INVALID_HANDLE_VALUE == LOG_FILE)
		return;	
	
	if(!fmt /*|| !str_len(fmt)*/)
		return;

	
	
	GetLocalTime(&lt);
	wsprintfA(sl,"\n%0.2i.%0.2i.%0.2i %0.2i:%0.2i:%0.2i::%0.3i - %s",
						lt.wDay,lt.wMonth,lt.wYear,
						lt.wHour,lt.wMinute,lt.wSecond,lt.wMilliseconds, fmt);

	write_to_file(LOG_FILE,sl,strlen(sl) );
	lp=p=0;
	return;

	/*sz = str_len(fmt);

	va_start(vl, fmt);

	while(p<sz)
	{
		if(fmt[p]=='%')
		{
			if(p-lp)
			{
				lbuf=(char *)m_alloc(p-lp +1);
				CopyMemory(lbuf,fmt+lp,p-lp);
				lbuf[p-lp]=0;
				write_to_file(LOG_FILE,lbuf,p-lp);
				m_free(lbuf);
			}

			switch(fmt[p+1])
			{
				case 's':
					tmp = va_arg(vl,char *);
					write_to_file(LOG_FILE,tmp,str_len(tmp));
					p++;
				break;
				case 'i':
					b = va_arg(vl,long);
					if(b<0)
					{
						b=(~b)+1;
						t = '-';
						write_to_file(LOG_FILE,&t,1);
					}
					if(!b)
					{
						t='0';
						write_to_file(LOG_FILE,&t,1);
					}else
						dlt=1000000000;
						pz=0;
						while(b || dlt)
						{
							t = (b/dlt);
							b=b%dlt;
							dlt/=10;
							if(!t && !pz)
								continue;
							else
								pz=1;
							
							t+='0';
							write_to_file(LOG_FILE,&t,1);
						}
					p++;
				break;
			}

			lp=p+1;
		}
		p++;

	}
	
	if(sz-lp)
	{
		lbuf=(char *)m_alloc(sz-lp+1);
		CopyMemory(lbuf,fmt+lp,sz-lp);
		lbuf[sz-lp]=0;
		write_to_file(LOG_FILE,lbuf,sz-lp);
		m_free(lbuf);
	}
	va_end(vl);*/
}
Exemple #19
0
// COpenHoldemApp initialization
BOOL COpenHoldemApp::InitInstance()
{
	Scintilla_RegisterClasses(AfxGetInstanceHandle());

	// Initialize richedit2 library
	AfxInitRichEdit2();

	// Change class name of Dialog
	WNDCLASS wc;
	GetClassInfo(AfxGetInstanceHandle(), "#32770", &wc);

	wc.lpszClassName = "OpenHoldemFormula";
	wc.hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
	RegisterClass(&wc);

	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	bool load_from_registry = true;
	for (int i = 1; i < __argc; i++)
	{
		LPCTSTR pszParam = __targv[i];
		if (_tcsncmp(pszParam, "/ini:", 5) == 0) {
			CString path(pszParam+5);
			path.Replace("~", _startup_path);
			free((void*)m_pszProfileName);
			m_pszProfileName = _strdup(path);
			load_from_registry = false;
		}
		if (_tcscmp(pszParam, "/ini") == 0) {
			CString path;
			path.Format("%s\\openholdem.ini", _startup_path);
			free((void*)m_pszProfileName);
			m_pszProfileName = _strdup(path);
			load_from_registry = false;
		}
	}
	if (load_from_registry)
		SetRegistryKey(_T("OpenHoldem"));
	prefs.LoadPreferences(load_from_registry);
	
	// Classes
	if (!p_sessioncounter) p_sessioncounter = new CSessionCounter;
	// Start logging immediatelly after the loading the preferences
	// and initializing the sessioncounter.
	start_log();
	InstanciateAllSingletonsExceptSessionCounter(); 

	// mouse.dll - failure in load is fatal
	_mouse_dll = LoadLibrary("mouse.dll");
	if (_mouse_dll==NULL)
	{
		CString		t = "";
		t.Format("Unable to load mouse.dll, error: %d\n\nExiting.", GetLastError());
		OH_MessageBox(t, "OpenHoldem mouse.dll ERROR", MB_OK | MB_TOPMOST);
		return false;
	}
	else
	{
		_dll_mouse_process_message = (mouse_process_message_t) GetProcAddress(_mouse_dll, "ProcessMessage");
		_dll_mouse_click = (mouse_click_t) GetProcAddress(_mouse_dll, "MouseClick");
		_dll_mouse_click_drag = (mouse_clickdrag_t) GetProcAddress(_mouse_dll, "MouseClickDrag");

		if (_dll_mouse_process_message==NULL || _dll_mouse_click==NULL || _dll_mouse_click_drag==NULL)
		{
			CString		t = "";
			t.Format("Unable to find all symbols in mouse.dll");
			OH_MessageBox(t, "OpenHoldem mouse.dll ERROR", MB_OK | MB_TOPMOST);

			FreeLibrary(_mouse_dll);
			_mouse_dll = NULL;
			return false;
		}
	}

	// keyboard.dll - failure in load is fatal
	_keyboard_dll = LoadLibrary("keyboard.dll");
	if (_keyboard_dll==NULL)
	{
		CString		t = "";
		t.Format("Unable to load keyboard.dll, error: %d\n\nExiting.", GetLastError());
		OH_MessageBox(t, "OpenHoldem keyboard.dll ERROR", MB_OK | MB_TOPMOST);
		return false;
	}
	else
	{
		_dll_keyboard_process_message = (keyboard_process_message_t) GetProcAddress(_keyboard_dll, "ProcessMessage");
		_dll_keyboard_sendstring = (keyboard_sendstring_t) GetProcAddress(_keyboard_dll, "SendString");
		_dll_keyboard_sendkey = (keyboard_sendkey_t) GetProcAddress(_keyboard_dll, "SendKey");

		if (_dll_keyboard_process_message==NULL || _dll_keyboard_sendstring==NULL || _dll_keyboard_sendkey==NULL)
		{
			CString		t = "";
			t.Format("Unable to find all symbols in keyboard.dll");
			OH_MessageBox(t, "OpenHoldem keyboard.dll ERROR", MB_OK | MB_TOPMOST);

			FreeLibrary(_keyboard_dll);
			_keyboard_dll = NULL;
			return false;
		}
	}

	MyLoadStdProfileSettings(4);  // Load standard INI file options (including MRU)
	if (m_pRecentFileList == NULL)
		AfxMessageBox("Still NULL");
	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;

	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(COpenHoldemDoc),
		RUNTIME_CLASS(CMainFrame),	   // main SDI frame window
		RUNTIME_CLASS(COpenHoldemView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	// Enable DDE Execute open
	if (load_from_registry)
	{
		EnableShellOpen();
		RegisterShellFileTypes(false);
	}

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Open the most recently saved file. (First on the MRU list.) Get the last
	// file from the registry. We need not account for cmdInfo.m_bRunAutomated and
	// cmdInfo.m_bRunEmbedded as they are processed before we get here.
	if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew)
	{
		CString sLastPath(GetProfileString(_afxFileSection, "File1"));

		if (! sLastPath.IsEmpty())
		{
			CFile f;

			// If file is there, set to open!
			if (f.Open(sLastPath, CFile::modeRead | CFile::shareDenyWrite))
			{
				cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen;
				cmdInfo.m_strFileName = sLastPath;
				f.Close();
			}
		}
	}

	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	if (prefs.simple_window_title())
		m_pMainWnd->PostMessage(WMA_SETWINDOWTEXT, 0, (LPARAM)NULL);

	// The one and only window has been initialized, so show and update it
	if (prefs.gui_start_minimized())
	{
		m_pMainWnd->ShowWindow(SW_MINIMIZE);
	}
	else
	{
		m_pMainWnd->ShowWindow(SW_SHOW);
	}
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand
	// Enable drag/drop open
	m_pMainWnd->DragAcceptFiles();

	// Bring main window to front
	m_pMainWnd->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
	m_pMainWnd->SetActiveWindow();
	m_pMainWnd->SetFocus();
	m_pMainWnd->SetForegroundWindow();

	// autoconnect on start, if preferred
	if (prefs.autoconnector_when_to_connect() == k_AutoConnector_Connect_Once)
	{
		p_autoconnector->Connect(NULL);
	}
	// Start thread anyway; permanent connection might be enabled later via preferences.
	p_autoconnectorthread->StartThread();	

	return TRUE;
}
Exemple #20
0
void handle_msg_init(ikgt_event_info_t *event_info, log_message_t *msg)
{
	start_log(event_info, msg);
}
Exemple #21
0
// COpenHoldemApp initialization
BOOL COpenHoldemApp::InitInstance()
{
	Scintilla_RegisterClasses(AfxGetInstanceHandle());

	// Initialize richedit2 library
	AfxInitRichEdit2();

	// Change class name of Dialog
	WNDCLASS wc;
	GetClassInfo(AfxGetInstanceHandle(), "#32770", &wc);

	wc.lpszClassName = "OpenHoldemFormula";
	wc.hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
	RegisterClass(&wc);

	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Since OH 2.2.0 we always use an ini-files,
	// the one and only in our OH-directory,
	// no matter how it is named.
	// For the technical details please see:
	// http://msdn.microsoft.com/de-de/library/xykfyy20(v=vs.80).aspx
	InstantiateSomeSingletonsForVeryEarlyUseInInitInstance();
	free((void*)m_pszProfileName);
	m_pszProfileName = _strdup(p_filenames->IniFilePath().GetString());
	prefs.LoadPreferences();
	
	// Classes
	if (!p_sessioncounter) p_sessioncounter = new CSessionCounter;
	// Start logging immediatelly after the loading the preferences
	// and initializing the sessioncounter.
	start_log();
	InstantiateAllSingletons();

	// mouse.dll - failure in load is fatal
	_mouse_dll = LoadLibrary("mouse.dll");
	if (_mouse_dll==NULL)
	{
		CString		t = "";
		t.Format("Unable to load mouse.dll, error: %d\n\nExiting.", GetLastError());
		OH_MessageBox(t, "OpenHoldem mouse.dll ERROR", MB_OK | MB_TOPMOST);
		return false;
	}
	else
	{
		_dll_mouse_process_message = (mouse_process_message_t) GetProcAddress(_mouse_dll, "ProcessMessage");
		_dll_mouse_click = (mouse_click_t) GetProcAddress(_mouse_dll, "MouseClick");
		_dll_mouse_click_drag = (mouse_clickdrag_t) GetProcAddress(_mouse_dll, "MouseClickDrag");

		if (_dll_mouse_process_message==NULL || _dll_mouse_click==NULL || _dll_mouse_click_drag==NULL)
		{
			CString		t = "";
			t.Format("Unable to find all symbols in mouse.dll");
			OH_MessageBox(t, "OpenHoldem mouse.dll ERROR", MB_OK | MB_TOPMOST);

			FreeLibrary(_mouse_dll);
			_mouse_dll = NULL;
			return false;
		}
	}

	// keyboard.dll - failure in load is fatal
	_keyboard_dll = LoadLibrary("keyboard.dll");
	if (_keyboard_dll==NULL)
	{
		CString		t = "";
		t.Format("Unable to load keyboard.dll, error: %d\n\nExiting.", GetLastError());
		OH_MessageBox(t, "OpenHoldem keyboard.dll ERROR", MB_OK | MB_TOPMOST);
		return false;
	}
	else
	{
		_dll_keyboard_process_message = (keyboard_process_message_t) GetProcAddress(_keyboard_dll, "ProcessMessage");
		_dll_keyboard_sendstring = (keyboard_sendstring_t) GetProcAddress(_keyboard_dll, "SendString");
		_dll_keyboard_sendkey = (keyboard_sendkey_t) GetProcAddress(_keyboard_dll, "SendKey");

		if (_dll_keyboard_process_message==NULL || _dll_keyboard_sendstring==NULL || _dll_keyboard_sendkey==NULL)
		{
			CString		t = "";
			t.Format("Unable to find all symbols in keyboard.dll");
			OH_MessageBox(t, "OpenHoldem keyboard.dll ERROR", MB_OK | MB_TOPMOST);

			FreeLibrary(_keyboard_dll);
			_keyboard_dll = NULL;
			return false;
		}
	}

	MyLoadStdProfileSettings(k_number_of_last_recently_used_files_in_file_menu);
	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;

	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(COpenHoldemDoc),
		RUNTIME_CLASS(CMainFrame),	   // main SDI frame window
		RUNTIME_CLASS(COpenHoldemView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	EnableShellOpen();
	RegisterShellFileTypes(false);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Open the most recently saved file. (First on the MRU list.) Get the last
	// file from the registry. We need not account for cmdInfo.m_bRunAutomated and
	// cmdInfo.m_bRunEmbedded as they are processed before we get here.
	if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew)
	{
		CString sLastPath(GetProfileString(_afxFileSection, "File1"));

		if (! sLastPath.IsEmpty())
		{
			CFile f;

			// If file is there, set to open!
			if (f.Open(sLastPath, CFile::modeRead | CFile::shareDenyWrite))
			{
				cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen;
				cmdInfo.m_strFileName = sLastPath;
				f.Close();
			}
		}
	}

	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	if (prefs.simple_window_title())
		m_pMainWnd->PostMessage(WMA_SETWINDOWTEXT, 0, (LPARAM)NULL);

	// The one and only window has been initialized, so show and update it
	if (prefs.gui_start_minimized())
	{
		m_pMainWnd->ShowWindow(SW_MINIMIZE);
	}
	else
	{
		m_pMainWnd->ShowWindow(SW_SHOW);
	}
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand
	// Enable drag/drop open
	m_pMainWnd->DragAcceptFiles();

	// Bring main window to front
	m_pMainWnd->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
	m_pMainWnd->SetActiveWindow();
	m_pMainWnd->SetFocus();
	m_pMainWnd->SetForegroundWindow();

	// autoconnect on start, if preferred
	if (prefs.autoconnector_when_to_connect() == k_AutoConnector_Connect_Once)
	{
		p_autoconnector->Connect(NULL);
	}
	// Start thread anyway; permanent connection might be enabled later via preferences.
	p_autoconnectorthread->StartThread();	

	return TRUE;
}
Exemple #22
0
/*
 * Load calendar data into memory from callog file.
 */
extern CSA_return_code
_DtCmsLoadCalendar(char *target, _DtCmsCalendar **infoptr)
{
	CSA_return_code	stat;
	char		*calname;
	char		*log;
	_DtCmsCalendar	*cal = NULL;

	if (target == NULL || infoptr == NULL)
		return (CSA_E_FAILURE);

	*infoptr = NULL;

	if ((calname = get_calname(target)) == NULL)
		return(CSA_E_INSUFFICIENT_MEMORY);

	if ((log = _DtCmsGetLogFN(calname)) == NULL)
	{
		free(calname);
		return(CSA_E_INSUFFICIENT_MEMORY);
	}

	if ((cal = (_DtCmsCalendar *)calloc(1, sizeof(_DtCmsCalendar)))
	    == NULL) {
		stat = CSA_E_INSUFFICIENT_MEMORY;
		goto ERROR;
	}

	if (!(cal->calendar = (char *)strdup(calname))) {
		stat = CSA_E_INSUFFICIENT_MEMORY;
		goto ERROR;
	}

	/* load data from file */
	if ((stat = start_log(cal, log)) != CSA_SUCCESS) {
		goto ERROR;
	}

	/*
	 * get file owner after the file is loaded since file
	 * ownership might be fixed in start_log()
	 */
	if (cal->fversion == _DtCMS_VERSION1) {
		if ((stat = get_file_owner(calname, &cal->owner))
		    != CSA_SUCCESS)
			goto ERROR;

		cal->alist = _DtCmsCalendarAccessList(cal);
	} else {
		if (cal->attrs[CSA_CAL_ATTR_CALENDAR_OWNER_I].value)
			cal->owner = strdup(cal->\
					attrs[CSA_CAL_ATTR_CALENDAR_OWNER_I].\
					value->item.calendar_user_value);
		else {
			stat = CSA_X_DT_E_BACKING_STORE_PROBLEM;
	    		fprintf(stderr, "%s: %s\n", pgname,
				"calendar owner attribute is missing from callog file");
			goto ERROR;
		}

		if (cal->attrs[CSA_CAL_ATTR_PRODUCT_IDENTIFIER_I].value == NULL)
		{
			if ((stat = _DtCm_set_string_attrval(
			    _DtCM_PRODUCT_IDENTIFIER, &cal->\
			    attrs[CSA_CAL_ATTR_PRODUCT_IDENTIFIER_I].value,
			    CSA_VALUE_STRING)) != CSA_SUCCESS) {
				goto ERROR;
			}
		}

		if (cal->attrs[CSA_CAL_ATTR_VERSION_I].value == NULL) {
			if ((stat = _DtCm_set_string_attrval(
			    _DtCM_SPEC_VERSION_SUPPORTED,
			    &cal->attrs[CSA_CAL_ATTR_VERSION_I].value,
			    CSA_VALUE_STRING)) != CSA_SUCCESS) {
				goto ERROR;
			}
		}

		cal->num_entry_attrs = cal->entry_tbl->size;
	}

	cal->getattrfuncs = _GetAttrFuncPtrs;

	/* link with other calendar structures */
	cal->next = calendar_list;
	calendar_list = cal;

	free(log);
	free(calname);

	*infoptr = cal;
	return (CSA_SUCCESS);
ERROR:
	free(calname);
	free(log);

	_DtCmsFreeCalendar(cal);
	return (stat);
}
Exemple #23
0
static void
callback(event_handle_t handle, event_notification_t notification, void *data)
{
	char		buf[8][64];
	int		len = 64;
	static int	setupdone;
	struct timeval	now;

	buf[0][0] = buf[1][0] = buf[2][0] = buf[3][0] = 0;
	buf[4][0] = buf[5][0] = buf[6][0] = buf[7][0] = 0;
	event_notification_get_site(handle, notification, buf[0], len);
	event_notification_get_expt(handle, notification, buf[1], len);
	event_notification_get_group(handle, notification, buf[2], len);
	event_notification_get_host(handle, notification, buf[3], len);
	event_notification_get_objtype(handle, notification, buf[4], len);
	event_notification_get_objname(handle, notification, buf[5], len);
	event_notification_get_eventtype(handle, notification, buf[6], len);
	event_notification_get_arguments(handle, notification, buf[7], len);

#ifdef EVENTDEBUG
	{
		static int ecount;

		gettimeofday(&now, NULL);
		fprintf(stderr, "Event %d: %lu.%03lu %s %s %s %s %s %s %s %s\n",
			++ecount, now.tv_sec, now.tv_usec / 1000,
			buf[0], buf[1], buf[2],
			buf[3], buf[4], buf[5], buf[6], buf[7]);
	}
#endif

	if (tg_first != &actions[0])
		fatal("global action list corrupted!");

	/*
	 * Perform a setup when we get the "start of time" event.
	 */
	if (strcmp(buf[4], TBDB_OBJECTTYPE_TIME) == 0) {
		if (strcmp(buf[6], TIMESTARTS) == 0) {
			/*
			 * We may receive TIME START events for any experiment
			 * (if an experiment ID was not specified on the
			 * command line).  If we get a redundant start event,
			 * check the experiment ID.  If the start is for some
			 * other experiment, ignore it.  If it is another start
			 * for us, assume the event daemon has been restarted
			 * and just go back to WAITing.
			 */
			if (setupdone) {
				if (strcmp(buf[1], myexp) == 0)
					goto dowait;
				return;
			}

			if (logfile) {
				FlushOutput = 1;
				gettimeofday(&now, NULL);
				start_log(now, NULL);
			}

			/*
			 * Delay startup of source relative to sink
			 * by 0.5 seconds.
			 */
			if ((prot.qos & QOS_SERVER) == 0) {
				now.tv_sec = 0;
				now.tv_usec = 1000000 / 2;
				select(0, NULL, NULL, NULL, &now);
			}
#ifdef EVENTDEBUG
			gettimeofday(&now, NULL);
			fprintf(stderr, "%lu.%03lu: SETUP/WAIT exp=%s\n",
				now.tv_sec, now.tv_usec / 1000,
				myexp ? myexp : buf[1]);
#endif
			actions[0].tg_flags = TG_SETUP;
			actions[0].next = &actions[1];
			actions[1].tg_flags = TG_WAIT;
			actions[1].next = NULL;

			/*
			 * XXX if they didn't specify an experiment,
			 * use the value from the first time start we see.
			 */
			if (myexp == 0)
				myexp = strdup(buf[1]);

			setupdone = 1;
		}
	}

	/*
	 * If eventtype is STOP, execute an infinite wait
	 */
	else if (strcmp(buf[6], STOPEVENT) == 0) {
	dowait:
#ifdef EVENTDEBUG
		gettimeofday(&now, NULL);
		fprintf(stderr, "%lu.%03lu: WAIT\n",
			now.tv_sec, now.tv_usec / 1000);
#endif
		tg_first->tg_flags = TG_WAIT;
		tg_first->next = NULL;
	}

	/*
	 * If eventtype is START, parse any explicitly provided parameters
	 * and load the tg_action structure.  If there are errors, go back
	 * to the STOPed state.
	 */
	else if (strcmp(buf[6], STARTEVENT) == 0) {
		memset(tg_first, 0, sizeof(tg_action));
		if (parse_args(buf[7], tg_first) != 0) {
			fprintf(stderr, "START invalid params\n");
			goto dowait;
		}

		/*
		 * XXX if no time start event was seen, do an implied setup.
		 * This will happen if the node reboots after the scheduler
		 * has already sent the time start.
		 */
		if (!setupdone) {
#ifdef EVENTDEBUG
			gettimeofday(&now, NULL);
			fprintf(stderr, "%lu.%03lu: SETUP/START exp=%s\n",
				now.tv_sec, now.tv_usec / 1000,
				myexp ? myexp : buf[1]);
#endif
			if (logfile) {
				FlushOutput = 1;
				gettimeofday(&now, NULL);
				start_log(now, NULL);
			}
			actions[1] = actions[0];
			actions[0].tg_flags = TG_SETUP;
			actions[0].next = &actions[1];
			actions[1].next = NULL;
			if (actions[1].tg_flags != (TG_ARRIVAL|TG_LENGTH))
				fatal("START1: list corrupted!");
			if (myexp == 0)
				myexp = strdup(buf[1]);
			setupdone = 1;
		} else {
#ifdef EVENTDEBUG
			gettimeofday(&now, NULL);
			fprintf(stderr, "%lu.%03lu: START\n",
				now.tv_sec, now.tv_usec / 1000);
#endif
			if (tg_first->tg_flags != (TG_ARRIVAL|TG_LENGTH) ||
			    tg_first->next != NULL)
				fatal("START2: list corrupted!");
		}
	}

	/*
	 * If eventtype is MODIFY, update the params but remain in the
	 * current state.  Invalid params are ignored.
	 */
	else if (strcmp(buf[6], MODIFYEVENT) == 0) {
		if (parse_args(buf[7], tg_first) != 0)
			fprintf(stderr, "MODIFY invalid params, ignored\n");
#ifdef EVENTDEBUG
		else {
			int plen;
			double interval, bps;

			plen = (int)dist_const_gen(&tg_first->length);
			interval = dist_const_gen(&tg_first->arrival);
			bps = (plen * 8) * (1.0 / interval);

			gettimeofday(&now, NULL);
			fprintf(stderr, "%lu.%03lu: MODIFY length=%d bytes, "
				"interval=%.9f sec (rate=%f Kbps), iptos=%x\n",
				now.tv_sec, now.tv_usec / 1000, plen,
				interval, bps / 1000, prot.tos);
		}
#endif
		/*
		 * XXX Normally we return and reprocess the current event
		 * list after a MODIFY event, but if the head of the event
		 * list is a SETUP event (part of a SETUP/WAIT or SETUP/START
		 * combo) we can't do that.  So in that case, we change the
		 * head of the list to reflect the WAIT or START and continue
		 * with that action.
		 */
		if (tg_first->tg_flags & TG_SETUP) {
			if (tg_first->next == NULL)
				fatal("MODIFY: list corrupted!");
			if (tg_first->next->tg_flags & TG_WAIT)
				goto dowait;
			tg_first->tg_flags &= ~TG_SETUP;
			tg_first->next = NULL;
			if (tg_first->tg_flags != (TG_ARRIVAL|TG_LENGTH))
				fatal("MODIFY2: list corrupted!");
		}
	}
	/*
	 * If eventtype is RESET, zero out the event list so that TG
	 * falls out of its service loop and does a teardown.
	 * We regain control in tgevent_loop below and reissue a
	 * SETUP/WAIT combo.
	 */
	else if (strcmp(buf[6], RESETEVENT) == 0) {
#ifdef EVENTDEBUG
		gettimeofday(&now, NULL);
		fprintf(stderr, "%lu.%03lu: RESET\n",
			now.tv_sec, now.tv_usec / 1000);
#endif
		tg_first = NULL;
	}
	gotevent = 1;
}