Exemple #1
0
int main(int argc, char* argv[])
{
    printf("[i] Start...\n");

    register_signal_handlers();

    // init
    Teleoperation teleop;

    if( teleop.init() ) {
        fprintf(stderr, "[!] Error: teleop init!\n");
        return -1;
    }

#if defined(USE_KEYBOARD_INPUT) && defined(LINUX)
    // Use termios to turn off line buffering
    termios term, cooked;
    tcgetattr(STDIN_FILENO, &term);
    memcpy(&cooked, &term, sizeof(term));
    term.c_lflag &= ~(ICANON | ECHO);
    term.c_cc[VEOL] = 1;
    term.c_cc[VEOF] = 2;
    tcsetattr(STDIN_FILENO, TCSANOW, &term);
    setbuf(stdin, NULL);
#endif

    while( !terminated ) {

#if defined(USE_KEYBOARD_INPUT)
        int key = console::waitKey(30);
        if(key != 0 ) printf( "[i] Key: %c (%d)\n", key ,key );
        if(key == 27) { //ESC
            break;
        }
#endif //#if defined(USE_KEYBOARD_INPUT)

        // process
        teleop.make();

    } //while( !terminated ) {

    printf("[i] End.\n");

    return 0;
}
void prepare_and_run_sampler(const unsigned long max_iterations, int append) {
	unsigned int n_beta = N_BETA;
	unsigned int i = 0;
	int n_swap = N_SWAP;

	mcmc ** chains = setup_chains();

	debug("reading calibrations file")
	read_calibration_file(chains, n_beta);

	debug("opening dump files")
	mcmc_open_dump_files(chains[i], "-chain", i, (append == 1 ? "a" : "w"));

#ifdef DUMP_ALL_CHAINS
	for (i = 1; i < n_beta; i++) {
		mcmc_open_dump_files(chains[i], "-chain", i, (append == 1 ? "a" : "w"));
	}
#endif

	if (n_swap < 0) {
		n_swap = 2000 / n_beta;
		printf("automatic n_swap: %d\n", n_swap);
	}

	debug("running sampler")
	register_signal_handlers();
	run_sampler(chains, n_beta, n_swap, max_iterations, (append == 1 ? "a" : "w"));

	debug("reporting")
	report((const mcmc **) chains, n_beta);

	for (i = 0; i < n_beta; i++) {
		mem_free(chains[i]->additional_data);
		if (i != 0) {
			/* this was reused, thus avoid double free */
			set_data(chains[i], NULL);
		}
		chains[i] = mcmc_free(chains[i]);
		mem_free(chains[i]);
	}
	mem_free(chains);
}
Exemple #3
0
void basic_server_buffer<Document, Selector>::open(unsigned int port)
{
	if(basic_buffer<Document, Selector>::is_open() )
	{
		throw std::logic_error(
			"obby::basic_server_buffer::open:\n"
			"Server is already open"
		);
	}

	basic_buffer<Document, Selector>::m_net.reset(new_net());
	register_signal_handlers();

	reopen_impl(port);

	// Clear previous documents and users
	basic_buffer<Document, Selector>::document_clear();
	basic_buffer<Document, Selector>::m_user_table.clear();

	basic_buffer<Document, Selector>::m_signal_sync_init.emit(0);
	basic_buffer<Document, Selector>::m_signal_sync_final.emit();
}
Exemple #4
0
void basic_server_buffer<Document, Selector>::open(const std::string& session,
                                                   unsigned int port)
{
	// TODO: Close server when session deserialisation failed
	if(basic_buffer<Document, Selector>::is_open() )
	{
		throw std::logic_error(
			"obby::basic_server_buffer::open:\n"
			"Server is already open"
		);
	}

	// Open server
	basic_buffer<Document, Selector>::m_net.reset(new_net());
	register_signal_handlers();

	reopen_impl(port);

	// Deserialise file
	serialise::parser parser;
	parser.deserialise(session);

	// Clear previous documents and users
	basic_buffer<Document, Selector>::document_clear();
	basic_buffer<Document, Selector>::m_user_table.clear();

	basic_buffer<Document, Selector>::m_signal_sync_init.emit(0);

	if(parser.get_type() != "obby")
		throw serialise::error(_("File is not an obby document"), 1);

	// Get root object, verify that it is an obby session
	serialise::object& root = parser.get_root();
	if(root.get_name() != "session")
	{
		throw serialise::error(
			_("File is not a stored obby session"),
			root.get_line()
		);
	}

	serialise::attribute& version_attr =
		root.get_required_attribute("version");

	// TODO: Check version for incompatibilites
	// TODO: Block higher version files
	// Check children
	for(serialise::object::child_iterator iter = root.children_begin();
	    iter != root.children_end();
	    ++ iter)
	{
		if(iter->get_name() == "user_table")
		{
			// Stored user table
			basic_buffer<Document, Selector>::
				m_user_table.deserialise(
					*iter
				);
		}
		else if(iter->get_name() == "chat")
		{
			// Stored chat history
			basic_buffer<Document, Selector>::m_chat.deserialise(
				*iter,
				basic_buffer<Document, Selector>::m_user_table
			);
		}
		else if(iter->get_name() == "document")
		{
			// Stored document, load it
			base_document_info_type* info =
				new_document_info(*iter);
			// Add to list
			basic_buffer<Document, Selector>::document_add(*info);
		}
		else
		{
			// Unexpected child
			// TODO: unexpected_child_error
			format_string str(_("Unexpected child node: '%0%'") );
			str << iter->get_name();
			throw serialise::error(str.str(), iter->get_line() );
		}
	}

	basic_buffer<Document, Selector>::m_signal_sync_final.emit();
}
Exemple #5
0
static int cmd_save(const char *tuner_str, const char *filename)
{
	if (hdhomerun_device_set_tuner_from_str(hd, tuner_str) <= 0) {
		fprintf(stderr, "invalid tuner number\n");
		return -1;
	}

	FILE *fp;
	if (strcmp(filename, "null") == 0) {
		fp = NULL;
	} else if (strcmp(filename, "-") == 0) {
		fp = stdout;
	} else {
		fp = fopen(filename, "wb");
		if (!fp) {
			fprintf(stderr, "unable to create file %s\n", filename);
			return -1;
		}
	}

	int ret = hdhomerun_device_stream_start(hd);
	if (ret <= 0) {
		fprintf(stderr, "unable to start stream\n");
		if (fp && fp != stdout) {
			fclose(fp);
		}
		return ret;
	}

	register_signal_handlers(sigabort_handler, sigabort_handler, siginfo_handler);

	struct hdhomerun_video_stats_t stats_old, stats_cur;
	hdhomerun_device_get_video_stats(hd, &stats_old);

	uint64_t next_progress = getcurrenttime() + 1000;

	while (!sigabort_flag) {
		uint64_t loop_start_time = getcurrenttime();

		if (siginfo_flag) {
			fprintf(stderr, "\n");
			cmd_save_print_stats();
			siginfo_flag = FALSE;
		}

		size_t actual_size;
		uint8_t *ptr = hdhomerun_device_stream_recv(hd, VIDEO_DATA_BUFFER_SIZE_1S, &actual_size);
		if (!ptr) {
			msleep_approx(64);
			continue;
		}

		if (fp) {
			if (fwrite(ptr, 1, actual_size, fp) != actual_size) {
				fprintf(stderr, "error writing output\n");
				return -1;
			}
		}

		if (loop_start_time >= next_progress) {
			next_progress += 1000;
			if (loop_start_time >= next_progress) {
				next_progress = loop_start_time + 1000;
			}

			/* Windows - indicate activity to suppress auto sleep mode. */
			#if defined(__WINDOWS__)
			SetThreadExecutionState(ES_SYSTEM_REQUIRED);
			#endif

			/* Video stats. */
			hdhomerun_device_get_video_stats(hd, &stats_cur);

			if (stats_cur.overflow_error_count > stats_old.overflow_error_count) {
				fprintf(stderr, "o");
			} else if (stats_cur.network_error_count > stats_old.network_error_count) {
				fprintf(stderr, "n");
			} else if (stats_cur.transport_error_count > stats_old.transport_error_count) {
				fprintf(stderr, "t");
			} else if (stats_cur.sequence_error_count > stats_old.sequence_error_count) {
				fprintf(stderr, "s");
			} else {
				fprintf(stderr, ".");
			}

			stats_old = stats_cur;
			fflush(stderr);
		}

		int32_t delay = 64 - (int32_t)(getcurrenttime() - loop_start_time);
		if (delay <= 0) {
			continue;
		}

		msleep_approx(delay);
	}

	if (fp) {
		fclose(fp);
	}

	hdhomerun_device_stream_stop(hd);

	fprintf(stderr, "\n");
	fprintf(stderr, "-- Video statistics --\n");
	cmd_save_print_stats();

	return 0;
}
Exemple #6
0
static int cmd_scan(const char *tuner_str, const char *filename)
{
	if (hdhomerun_device_set_tuner_from_str(hd, tuner_str) <= 0) {
		fprintf(stderr, "invalid tuner number\n");
		return -1;
	}

	char *ret_error;
	if (hdhomerun_device_tuner_lockkey_request(hd, &ret_error) <= 0) {
		fprintf(stderr, "failed to lock tuner\n");
		if (ret_error) {
			fprintf(stderr, "%s\n", ret_error);
		}
		return -1;
	}

	hdhomerun_device_set_tuner_target(hd, "none");

	char *channelmap;
	if (hdhomerun_device_get_tuner_channelmap(hd, &channelmap) <= 0) {
		fprintf(stderr, "failed to query channelmap from device\n");
		return -1;
	}

	const char *channelmap_scan_group = hdhomerun_channelmap_get_channelmap_scan_group(channelmap);
	if (!channelmap_scan_group) {
		fprintf(stderr, "unknown channelmap '%s'\n", channelmap);
		return -1;
	}

	if (hdhomerun_device_channelscan_init(hd, channelmap_scan_group) <= 0) {
		fprintf(stderr, "failed to initialize channel scan\n");
		return -1;
	}

	FILE *fp = NULL;
	if (filename) {
		fp = fopen(filename, "w");
		if (!fp) {
			fprintf(stderr, "unable to create file: %s\n", filename);
			return -1;
		}
	}

	register_signal_handlers(sigabort_handler, sigabort_handler, siginfo_handler);

	int ret = 0;
	while (!sigabort_flag) {
		struct hdhomerun_channelscan_result_t result;
		ret = hdhomerun_device_channelscan_advance(hd, &result);
		if (ret <= 0) {
			break;
		}

		cmd_scan_printf(fp, "SCANNING: %lu (%s)\n",
			(unsigned long)result.frequency, result.channel_str
		);

		ret = hdhomerun_device_channelscan_detect(hd, &result);
		if (ret <= 0) {
			break;
		}

		cmd_scan_printf(fp, "LOCK: %s (ss=%u snq=%u seq=%u)\n",
			result.status.lock_str, result.status.signal_strength,
			result.status.signal_to_noise_quality, result.status.symbol_error_quality
		);

		if (result.transport_stream_id_detected) {
			cmd_scan_printf(fp, "TSID: 0x%04X\n", result.transport_stream_id);
		}

		int i;
		for (i = 0; i < result.program_count; i++) {
			struct hdhomerun_channelscan_program_t *program = &result.programs[i];
			cmd_scan_printf(fp, "PROGRAM %s\n", program->program_str);
		}
	}

	hdhomerun_device_tuner_lockkey_release(hd);

	if (fp) {
		fclose(fp);
	}
	if (ret < 0) {
		fprintf(stderr, "communication error sending request to hdhomerun device\n");
	}
	return ret;
}
Exemple #7
0
int main(int argc, char* argv[])
{
    printf("[i] Start...\n");

    register_signal_handlers();

    roboipc::CommunicatorServer communicator;
    roboipc::CommunicatorClient client;

    if( communicator.init(SPEECHER_SOCKET_NAME) ) {
        fprintf(stderr, "[!] Error: cant create communication: %s!\n", SPEECHER_SOCKET_NAME);
        return -1;
    }

    communicator.is_auto_close = false;
    client.is_auto_close = false;

    int res = 0;

#if defined(USE_KEYBOARD_INPUT) && defined(LINUX)
    // Use termios to turn off line buffering
    termios term;
    tcgetattr(STDIN_FILENO, &term);
    term.c_lflag &= ~ICANON;
    tcsetattr(STDIN_FILENO, TCSANOW, &term);
    setbuf(stdin, NULL);
#endif

    CmdSpeech cmd_speech;
    CmdAcknowledgment cmd_ack;

    memset(&cmd_speech, 0, sizeof(cmd_speech));
    memset(&cmd_ack, 0, sizeof(cmd_ack));

    char cmd_buf[128]={0};
    int cmd_buf_size = 0;

    int return_value;
    int child_status = -1;
    pid_t child_pid;

    while( !terminated ) {

#if defined(USE_KEYBOARD_INPUT)
        int key = console::waitKey(30);
        if(key != 0 ) printf( "[i] Key: %c (%d)\n", key ,key );
        if(key == 27) { //ESC
            break;
        }
#endif //#if defined(USE_KEYBOARD_INPUT)

#if 1
        SOCKET sockfd = SOCKET_ERROR;
        if( (sockfd = communicator.connected(200)) != SOCKET_ERROR ) {
            printf("[i] Client connected...\n");
            client.close();
            client.sockfd = sockfd;
        }

        if(client.available(50) > 0) {
            printf("[i] Client action...\n");
            if( (cmd_buf_size = client.read(cmd_buf, sizeof(cmd_buf)))>0 ) {
                printf("[i] Data size: %d\n", cmd_buf_size);
                if(cmd_buf_size > CMD_SIG_SIZE) {
                    if( !strncmp(cmd_buf, "speech", CMD_SIG_SIZE) && cmd_buf_size >= sizeof(cmd_speech) ) {
                        memcpy(&cmd_speech, cmd_buf, sizeof(cmd_speech));
                        printf("[i] Clinet command speech: %d %s\n", cmd_speech.code, cmd_speech.name);

                        child_pid = fork();
                        if(child_pid == 0) {
                            // child

                            char filename[sizeof(cmd_speech.name)] = {0};
                            if(get_filename_for_speak(cmd_speech)) {
                                strncpy(filename, get_filename_for_speak(cmd_speech), sizeof(filename));
                            }
                            printf("[i] play file: %s\n", filename);

                            //return_value = execl("/usr/bin/aplay", "aplay", "./snd/dog_woof.wav");
                            return_value = execl("/usr/bin/aplay", "aplay", filename, "-D", "default:CARD=ALSA", 0); //return_value = execl("/usr/bin/aplay", "aplay", filename, 0);
                            return return_value;
                        }
                        else {
                            // parent
                            printf("[i] parent process, with id %d\n", (int) getpid());
                            printf("[i] childs process ID is %d\n", (int) child_pid);
                        }

#if 1
                        wait( &child_status );
                        printf("[i] status: %d\n", child_status);

                        if (WIFEXITED (child_status)) {
                            printf ("[i] the child process exited normally, with exit code %d\n", WEXITSTATUS (child_status));
                        }
                        else {
                            printf ("[i] the child process exited abnormally\n");
                        }

                        printf( "[i] Send ACK...\n");

                        if(client.sockfd != SOCKET_ERROR) {
                            strncpy(cmd_ack.sig, "ackmnt", CMD_SIG_SIZE);
                            cmd_ack.code = 0;

                            res = client.write(&cmd_ack, sizeof(cmd_ack));
                            printf( "[i] Send ACK (%d)...\n", res);
                        }
#endif
                    }
                }
            }
            else {
                printf("[i] Connection closed...\n");
                client.close();
            }
        }

#endif
    }  // while( !terminated ) {

    communicator.close();

    printf("[i] End.\n");

    return 0;
}
Exemple #8
0
int main(int argc, char **argv) {
  struct sockaddr_un addr;
  pid_t pid, sid;
  int pipefd[2];
  int clfd;
  char deamonize;
  
  if(argc==2 && !strncmp(argv[1], "-f", 3)) {
    deamonize=0;
  } else {
    deamonize=1;
  }
  
  if(deamonize) {
    if(pipe2(pipefd, O_CLOEXEC)) {
      print( FATAL, "pipe2: %s", strerror(errno) );
      return EXIT_FAILURE;
    }
    
    pid = fork();
    
    if(pid<0) {
      print( FATAL, "fork: %s", strerror(errno) );
      return EXIT_FAILURE;
    } else if(pid) {
      close(pipefd[1]);
      if(!read(pipefd[0], &clfd, 1))
        return EXIT_FAILURE;
      return EXIT_SUCCESS;
    }
    close(pipefd[0]);
  
    umask(0);

    if(open_logfile(LOG_PATH)) {
      print( FATAL, "cannot open logfile");
      return EXIT_FAILURE;
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    set_logger(file_logger);

    sid = setsid();
    if(sid<0) {
      print( FATAL, "setsid: %s", strerror(errno) );
      return EXIT_FAILURE;
    }
  }
  
  if(init_structs())
    return EXIT_FAILURE;
  
  if(load_handlers())
    return EXIT_FAILURE;
  
  if(load_users())
    return EXIT_FAILURE;
  
  if(remove_old_socket())
    return EXIT_FAILURE;
  
  sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
  
  if(sockfd < 0) {
    print( FATAL, "socket: %s", strerror(errno) );
    return EXIT_FAILURE;
  }
  
  if(register_signal_handlers()) {
    close(sockfd);
    return EXIT_FAILURE;
  }
  
  memset(&addr, 0, sizeof(struct sockaddr_un));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path)-1);
  if(bind(sockfd, (struct sockaddr*)&addr, sizeof(addr))) {
    print( FATAL, "bind: %s", strerror(errno) );
    close(sockfd);
    unlink(SOCKET_PATH);
    return EXIT_FAILURE;
  }
  
  if(listen(sockfd, 5)) {
    print( FATAL, "listen: %s", strerror(errno) );
    close(sockfd);
    unlink(SOCKET_PATH);
    return EXIT_FAILURE;
  }
  
  if(start_reaper()) {
    close(sockfd);
    unlink(SOCKET_PATH);
    return EXIT_FAILURE;
  }
  
#ifndef NDEBUG
  chmod(SOCKET_PATH, 0666);
#endif
  
  if(deamonize) {
    if(write(pipefd[1], "!", 1) != 1) {
      print( FATAL, "cannot notify that daemon started" );
      return EXIT_FAILURE;
    }
    close(pipefd[1]);
  }
  
  while(1) {
    if((clfd=accept(sockfd, NULL, NULL)) < 0) {
      if(errno == EINVAL) {
#ifndef NDEBUG
        print( DEBUG, "socket closed" );
#endif
      }
      print( ERROR, "accept: %s", strerror(errno) );
      break;
    }
    
    if(serve_new_client(clfd)) {
      print( WARNING, "cannot serve new connection" );
      close(clfd);
    }
  }
  
  unlink(SOCKET_PATH);
  
  close_connections();
  
  stop_reaper();
  
  destroy_structs();
  
  unload_users();
  unload_handlers();
  
  return EXIT_SUCCESS;
}
Exemple #9
0
int main(int argc, char **argv)
{
    const char *sopt = "hVvdm:p:l:f:b:s:t:";
    const char *method = NULL, *path = NULL;
    const char *log_filepath = NULL;
    const char *pid_filepath = QGA_PIDFILE_DEFAULT;
    const char *state_dir = QGA_STATEDIR_DEFAULT;
#ifdef _WIN32
    const char *service = NULL;
#endif
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "logfile", 1, NULL, 'l' },
        { "pidfile", 1, NULL, 'f' },
        { "verbose", 0, NULL, 'v' },
        { "method", 1, NULL, 'm' },
        { "path", 1, NULL, 'p' },
        { "daemonize", 0, NULL, 'd' },
        { "blacklist", 1, NULL, 'b' },
#ifdef _WIN32
        { "service", 1, NULL, 's' },
#endif
        { "statedir", 1, NULL, 't' },
        { NULL, 0, NULL, 0 }
    };
    int opt_ind = 0, ch, daemonize = 0, i, j, len;
    GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
    GList *blacklist = NULL;
    GAState *s;

    module_call_init(MODULE_INIT_QAPI);

    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 'm':
            method = optarg;
            break;
        case 'p':
            path = optarg;
            break;
        case 'l':
            log_filepath = optarg;
            break;
        case 'f':
            pid_filepath = optarg;
            break;
        case 't':
             state_dir = optarg;
             break;
        case 'v':
            /* enable all log levels */
            log_level = G_LOG_LEVEL_MASK;
            break;
        case 'V':
            printf("QEMU Guest Agent %s\n", QEMU_VERSION);
            return 0;
        case 'd':
            daemonize = 1;
            break;
        case 'b': {
            char **list_head, **list;
            if (is_help_option(optarg)) {
                list_head = list = qmp_get_command_list();
                while (*list != NULL) {
                    printf("%s\n", *list);
                    g_free(*list);
                    list++;
                }
                g_free(list_head);
                return 0;
            }
            for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
                if (optarg[i] == ',') {
                    optarg[i] = 0;
                    blacklist = g_list_append(blacklist, &optarg[j]);
                    j = i + 1;
                }
            }
            if (j < i) {
                blacklist = g_list_append(blacklist, &optarg[j]);
            }
            break;
        }
#ifdef _WIN32
        case 's':
            service = optarg;
            if (strcmp(service, "install") == 0) {
                return ga_install_service(path, log_filepath);
            } else if (strcmp(service, "uninstall") == 0) {
                return ga_uninstall_service();
            } else {
                printf("Unknown service command.\n");
                return EXIT_FAILURE;
            }
            break;
#endif
        case 'h':
            usage(argv[0]);
            return 0;
        case '?':
            g_print("Unknown option, try '%s --help' for more information.\n",
                    argv[0]);
            return EXIT_FAILURE;
        }
    }

    s = g_malloc0(sizeof(GAState));
    s->log_level = log_level;
    s->log_file = stderr;
    g_log_set_default_handler(ga_log, s);
    g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
    ga_enable_logging(s);
    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
                                                 state_dir);
    s->frozen = false;
#ifndef _WIN32
    /* check if a previous instance of qemu-ga exited with filesystems' state
     * marked as frozen. this could be a stale value (a non-qemu-ga process
     * or reboot may have since unfrozen them), but better to require an
     * uneeded unfreeze than to risk hanging on start-up
     */
    struct stat st;
    if (stat(s->state_filepath_isfrozen, &st) == -1) {
        /* it's okay if the file doesn't exist, but if we can't access for
         * some other reason, such as permissions, there's a configuration
         * that needs to be addressed. so just bail now before we get into
         * more trouble later
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       s->state_filepath_isfrozen, strerror(errno));
            return EXIT_FAILURE;
        }
    } else {
        g_warning("previous instance appears to have exited with frozen"
                  " filesystems. deferring logging/pidfile creation and"
                  " disabling non-fsfreeze-safe commands until"
                  " guest-fsfreeze-thaw is issued, or filesystems are"
                  " manually unfrozen and the file %s is removed",
                  s->state_filepath_isfrozen);
        s->frozen = true;
    }
#endif

    if (ga_is_frozen(s)) {
        if (daemonize) {
            /* delay opening/locking of pidfile till filesystem are unfrozen */
            s->deferred_options.pid_filepath = pid_filepath;
            become_daemon(NULL);
        }
        if (log_filepath) {
            /* delay opening the log file till filesystems are unfrozen */
            s->deferred_options.log_filepath = log_filepath;
        }
        ga_disable_logging(s);
        ga_disable_non_whitelisted();
    } else {
        if (daemonize) {
            become_daemon(pid_filepath);
        }
        if (log_filepath) {
            FILE *log_file = fopen(log_filepath, "a");
            if (!log_file) {
                g_critical("unable to open specified log file: %s",
                           strerror(errno));
                goto out_bad;
            }
            s->log_file = log_file;
        }
    }

    if (blacklist) {
        s->blacklist = blacklist;
        do {
            g_debug("disabling command: %s", (char *)blacklist->data);
            qmp_disable_command(blacklist->data);
            blacklist = g_list_next(blacklist);
        } while (blacklist);
    }
    s->command_state = ga_command_state_new();
    ga_command_state_init(s, s->command_state);
    ga_command_state_init_all(s->command_state);
    json_message_parser_init(&s->parser, process_event);
    ga_state = s;
#ifndef _WIN32
    if (!register_signal_handlers()) {
        g_critical("failed to register signal handlers");
        goto out_bad;
    }
#endif

    s->main_loop = g_main_loop_new(NULL, false);
    if (!channel_init(ga_state, method, path)) {
        g_critical("failed to initialize guest agent channel");
        goto out_bad;
    }
#ifndef _WIN32
    g_main_loop_run(ga_state->main_loop);
#else
    if (daemonize) {
        SERVICE_TABLE_ENTRY service_table[] = {
            { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
        StartServiceCtrlDispatcher(service_table);
    } else {
        g_main_loop_run(ga_state->main_loop);
    }
#endif

    ga_command_state_cleanup_all(ga_state->command_state);
    ga_channel_free(ga_state->channel);

    if (daemonize) {
        unlink(pid_filepath);
    }
    return 0;

out_bad:
    if (daemonize) {
        unlink(pid_filepath);
    }
    return EXIT_FAILURE;
}
Exemple #10
0
int main(int argc, char *argv[])
{
	int r;
	pthread_t uloop_tid;

	parse_args(argc, argv);
	register_signal_handlers();
	sprintf(ubus_path, "serial.%s", basename(opts.port));

	r = pipe2(ubus_pipefd, O_CLOEXEC);
	if (r < 0) fatal("cannot create pipe to ubus: %s", strerror(errno));

	/* Seems like you cannot have multiple ubus connections in single process. */
	/* So we fork. */
	switch(fork()) {
		case 0:
			efd_signal = eventfd(0, EFD_CLOEXEC);
			if (efd_signal < 0) {
				fatal("cannot create efd_signal: %s", strerror(errno));
			}
			close(ubus_pipefd[1]);
			seriald_ubus_run(opts.socket);
			return EXIT_SUCCESS;
		case -1:
			fatal("cannot fork ubus_event_loop");
	}

	close(ubus_pipefd[0]);

	efd_notify_tty = eventfd(0, EFD_CLOEXEC);
	if (efd_notify_tty < 0) {
		fatal("cannot create efd_notify_tty: %s", strerror(errno));
	}

	r = term_lib_init();
	if (r < 0) fatal("term_init failed: %s", term_strerror(term_errno, errno));

	fd_tty = open(opts.port, O_RDWR | O_NONBLOCK | O_NOCTTY);
	if (fd_tty < 0) fatal("cannot open %s: %s", opts.port, strerror(errno));

	r = term_set(fd_tty,
			1,              /* raw mode. */
			opts.baud,      /* baud rate. */
			opts.parity,    /* parity. */
			opts.databits,  /* data bits. */
			opts.stopbits,  /* stop bits. */
			opts.flow,      /* flow control. */
			1,              /* local or modem */
			!opts.noreset); /* hup-on-close. */
	if (r < 0) {
		fatal("failed to add device %s: %s",
				opts.port, term_strerror(term_errno, errno));
	}

	r = term_apply(fd_tty, 0);
	if (r < 0) {
		fatal("failed to config device %s: %s",
				opts.port, term_strerror(term_errno, errno));
	}

	set_tty_write_sz(term_get_baudrate(fd_tty, NULL));

	r = seriald_ubus_loop_init(opts.socket);
	if (r) fatal("failed to connect to ubus");

	r = pthread_create(&uloop_tid, NULL, &seriald_ubus_loop, NULL);
	if (r) fatal("can't create thread for uloop: %s", strerror(r));

	loop();

	seriald_ubus_loop_done();
	return EXIT_SUCCESS;
}
Exemple #11
0
int main(int argc, char* argv[])
{
    printf("[i] Start...\n");

    register_signal_handlers();

    roboipc::CommunicatorServer communicator;
    roboipc::CommunicatorClient client;

    if( communicator.init(EYE_SOCKET_NAME) ) {
        fprintf(stderr, "[!] Error: cant create communication: %s!\n", EYE_SOCKET_NAME);
        return -1;
    }

    int res = 0;

#if defined(USE_KEYBOARD_INPUT) && defined(LINUX)
    // Use termios to turn off line buffering
    termios term;
    tcgetattr(STDIN_FILENO, &term);
    term.c_lflag &= ~ICANON;
    tcsetattr(STDIN_FILENO, TCSANOW, &term);
    setbuf(stdin, NULL);
#endif

    CmdEyeData cmd_eye;

    memset(&cmd_eye, 0, sizeof(cmd_eye));

    CvCapture* capture = cvCreateCameraCapture( 200 );
    if(!capture) {
        fprintf(stderr, "[!] Error: cant create camera capture!\n");
    }

    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, EYE_FRAME_WIDTH);
    cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, EYE_FRAME_HEIGHT);

    double width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
    double height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
    printf("[i] Capture: %.0f x %.0f\n", width, height );

    IplImage* frame = 0;

    printf("[i] Capture images...\n");

    // frame counter
    int counter = 0;

    double fps = 0;
    double begin = 0;
    double end = 0;

    while( !terminated ) {

#if defined(USE_KEYBOARD_INPUT)
        int key = console::waitKey(30);
        if(key != 0 ) printf( "[i] Key: %c (%d)\n", key ,key );
        if(key == 27) { //ESC
            break;
        }
#endif //#if defined(USE_KEYBOARD_INPUT)

        begin = (double)cvGetTickCount();

        frame = cvQueryFrame( capture );

        calc_hsv_colors(frame);

        end = (double)cvGetTickCount();

        // calculate current FPS
        counter++;
        fps = (end-begin) / (cvGetTickFrequency()*1000.0);

        // will print out Inf until sec is greater than 0
        printf("[i] FPS = %.2f\n", fps);

#if 1
        SOCKET sockfd = SOCKET_ERROR;
        if( (sockfd = communicator.connected(30)) != SOCKET_ERROR ) {
            printf("[i] Client connected...\n");
            client.close();
            client.sockfd = sockfd;
        }

        if(client.sockfd != SOCKET_ERROR) {
            strncpy(cmd_eye.sig, "eyedat", CMD_SIG_SIZE);



            res = client.write(&cmd_eye, sizeof(cmd_eye));
            printf( "[i] Send Eye data (%d)...\n", res);
        }

#endif
    }  // while( !terminated ) {

    cvReleaseCapture( &capture );

    printf("[i] End.\n");

    return 0;
}
Exemple #12
0
void initialize()
{
    time_t now = time(NULL);

    srand(now);

    startup_ts = now;

    if (init_log() == -1) {
        fprintf(stderr, "Failed to initialzie log module.\n");
        exit(EXIT_FAILURE);
    }

    int ver = read_version();
    if (ver < VERSION) {
        log_info("Previous version %d, current version %d", ver, VERSION); 
        // this is a version update! 
        if (need_to_delete_redis_db) {
            log_info("Deleting redis DB due to version update.");
            delete_redis_db();
        }
    }
    else
        log_info("Current version: %d", VERSION);
    write_version(VERSION);

    start_redis_server();

    if (init_socket() == -1) {
        log_error("Failed to initialize socket module.");
        exit(EXIT_FAILURE);
    }

    log_debug("Adding iptables rules.");
    if (add_iptables_rules() == -1) {
        log_error("Failed to add iptables rules.");
        exit(EXIT_FAILURE);
    }

    register_signal_handlers();

    if (setup_nfq() == -1) {
        log_error("unable to setup netfilter_queue");
        exit(EXIT_FAILURE);
    }

    log_debug("Init DNS client.");
    if (init_dns_cli() == -1) {
        log_error("Failed to initialize DNS module");
        exit(EXIT_FAILURE);
    }

    log_debug("Init ev watchers.");
    init_ev_watchers();

    // Begin to intercept packets 
    //if (setup_strategy() == -1) {
    //    log_error("Failed to setup strategy");
    //    exit(EXIT_FAILURE);
    //}
    
    log_debug("Loading TTL from file.");
    load_ttl_from_file("ttl");

    // start a debug thread
    //pthread_t thread_dbg;
    //if (pthread_create(&thread_dbg, NULL, debug_main, NULL) != 0) {
    //    log_error("Fail to create debug thread.");
    //    exit(EXIT_FAILURE);
    //}

    // start a thread to handle communications with redis
    pthread_t thread_cache;
    if (pthread_create(&thread_cache, NULL, cache_main, NULL) != 0){
        log_error("Fail to create caching thread.");
        exit(EXIT_FAILURE);
    }
    
    // start the DNS proxy thread
    pthread_t thread_dns;
    if (pthread_create(&thread_dns, NULL, dns_main, NULL) != 0){
        log_error("Fail to create DNS thread.");
        exit(EXIT_FAILURE);
    }

    // Uploading diagnostic log is disabled. (2017.4.26) 
    // start a thread to send feedback log
    //pthread_t thread_fb;
    //if (pthread_create(&thread_fb, NULL, feedback_main, NULL) != 0){
    //    log_error("Fail to create feedback thread.");
    //    exit(EXIT_FAILURE);
    //}
}
Exemple #13
0
int main(int argc, char **argv) {

    int server_fd, port_number, max_fd, file_descriptors[MAX_NUMBER_USERS], i;
    int temp_fd, select_result, timer_is_active = FALSE, status_code;

    char *validation;

    fd_set file_descriptor_set;

    check_incorrect_usage(argc, argv);
    set_log_method(argv);
    set_lock();

    port_number = extract_port_number(argv);
    server_fd = create_server(port_number, MAX_NUMBER_USERS);
    log_message("Streams server created", LOG_INFO);

    register_signal_handlers();

    for (i = 0; i < MAX_NUMBER_USERS; i++) {
        file_descriptors[i] = 0;
    }

    // -- SHARED MEMORY AND SEMAPHORES --

    shmid = create_shared_memory();
    shared_mem_ptr = attach_memory(shmid);
    init_semaphores();

    log_message("Shared memory and semaphores created", LOG_DEBUG);

    // -- SERVER LOOP --

    while (TRUE) {

        FD_ZERO(&file_descriptor_set);
        FD_SET(server_fd, &file_descriptor_set);
        max_fd = server_fd;

        for (i = 0; i < MAX_NUMBER_USERS; i++) {
            temp_fd = file_descriptors[i];

            if (temp_fd > 0) {
                FD_SET(temp_fd, &file_descriptor_set);
            }

            if (temp_fd > max_fd) {
                max_fd = temp_fd;
            }
        }

        select_result = select(max_fd + 1, &file_descriptor_set, NULL, NULL, NULL);

        if (select_result < 0 && errno != EINTR) {
            log_error("Select call error", LOG_WARNING, errno);
            continue;
        }

        if (FD_ISSET(server_fd, &file_descriptor_set)) {

            if ((temp_fd = accept(server_fd, NULL, 0)) < 0) {
                log_error("Could not accept incoming connection", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            log_client_connection(temp_fd);

            for (i = 0; i < MAX_NUMBER_USERS; i++) {
                if (file_descriptors[i] != 0)
                    continue;

                file_descriptors[i] = temp_fd;
                break;
            }
        }

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

            temp_fd = file_descriptors[i];

            if (!FD_ISSET(temp_fd, &file_descriptor_set))
                continue;

            char *message = NULL;
            if ((message = (char *) calloc(MESSAGE_LENGTH, sizeof(char))) == NULL) {
                log_error("Memory allocation error", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            if (recv(temp_fd, message, MESSAGE_LENGTH, 0) <= 0)   // Disconnected
            {
                log_message("Client disconnected", LOG_INFO);

                close(temp_fd);
                file_descriptors[i] = 0;
            }
            else    // Message sent to server
            {
                struct message_t mess=decode(message);

                if( (status_code = mess.type) == ERROR_MESSAGE) {
                    continue;
                }

                if (get_game_phase() == REGISTER_PHASE) {

                    if (status_code != 1) {
                        // TODO Send message back to user?
                        log_message("Currently register phase. User can only register", LOG_DEBUG);
                        continue;
                    }

                    if (!timer_is_active) {
                        log_message("Starting register timer", LOG_DEBUG);
                        alarm(WAIT_TIME);
                        timer_is_active = TRUE;
                    }

                    char *new_user = (char *) malloc(MAX_ARRAY_SIZE * sizeof(char));
                    sprintf(new_user, "User '%s' asks for registration. Adding user in memory.", (char *) mess.payload);
                    log_message(new_user, LOG_INFO);

                    // Add a player to the shared memory
                    semaphore_down(SEMAPHORE_ACCESS);
                    strncpy(shared_mem_ptr->players->name, (char *) mess.payload, strlen(mess.payload));
                    shared_mem_ptr->players[i].fd = temp_fd;
                    shared_mem_ptr->players[i].score = 15; // TODO A supprimer
                    semaphore_up(SEMAPHORE_ACCESS);

                    validation = encode(VALID_REGISTRATION, "1");
                    send(temp_fd, validation, strlen(validation), 0);
                }
                else    // GAME PHASE
                {
                    log_message("Game phase. Not yet implemented.", LOG_INFO);
                }

            }
        }
    }

    return 0;
}
Exemple #14
0
int main (int argc, char *argv[])
{
    short int device = 0;
    char *device_name = NULL;
    char *key = NULL;
    struct input_event ev;

    printf ("learnkeys (%s, %s)\n", PACKAGE_STRING, PACKAGE_VERSION_SVN_REV);

    if (argc < 2)
    {
        printf ("\nUsage:\n");
        printf ("%s config_file_name [input_device_name]\n\n", argv[0]);
        printf ("config_file_name  - location of esekeyd config file\n");
        printf ("input_device_name - input (event) device; if given turns off\n");
        printf ("                    of 1st keyboard device\n");
        printf ("\nExample:\n");
        printf ("%s ~/.esekeyd.conf /dev/input/event3\n", argv[0]);
        exit (1);
    }

    if (argc > 2)
    {
        device_name = argv[2];
    }
    else
    {
        switch (check_handlers ())
        {
            case -1:
                printf ("%s: cannot open %s\n", argv[0], INPUT_HANDLERS);
                return -1;
            case -2:
                printf ("%s: evdev handler not found in %s\n", argv[0],
                        INPUT_HANDLERS);
                return -2;
        }

        switch (device = find_input_dev ())
        {
            case -1:
                printf ("%s: evdev for keyboard not found in %s\n", argv[0],
                        INPUT_HANDLERS);
                return -3;
            default:
                asprintf (&device_name, "%s%hu", EVENT_DEVICE, device);
        }
    }

    if (!(funkey = fopen (device_name, "r")))
    {
        printf ("%s: can`t open %s\n", argv[0], device_name);
        return -4;
    }

    if (!(config = fopen (argv[1], "w")))
    {
        printf ("%s: can`t open %s\n", argv[0], argv[1]);
        return -5;
    }

    fprintf (config, 
"#\n"
"# %s config file\n"
"#\n"
"\n"
"#\n"
"# example 1: to run mutt in xterm we must set DISPLAY\n"
"#            so the command line will be as follows:\n"
"#MAIL:/bin/sh -c \"DISPLAY=:0 xterm -e mutt\"\n"
"#\n"
"# example 2: turn on/off GPS receiver when lid is open/closed\n"
"#RADIO(press):echo 1 >/sys/device/platform/gps/gps_power\n"
"#RADIO(release):echo 0 >/sys/device/platform/gps/gps_power\n"
"#\n"
"# example 3: run nautilus when both left meta and e keys are press\n"
"#LEFTMETA+E:nautilus\n"
"#\n"
"\n", PACKAGE_STRING);

    printf ("\nPres ANY (fun)key... or Ctrl-C to exit...\n\n");

    register_signal_handlers();

    while (fread (&ev, sizeof (struct input_event), 1, funkey))
    {

        if (ev.code == 28 && ev.type == EV_KEY && ev.value == 1)
        {

            printf ("\n");
            fclose (funkey);
            return 0;

        }

        if ((key = parse (ev)) != NULL)
        {

            printf ("key %s stored in config file\n", key);
            if (ev.value == 1)
                fprintf (config, "#%s(press):\n", key);
            else
                fprintf (config, "#%s(release):\n", key);

        }

    }

    cleanup ();

    return 0;

}
Exemple #15
0
int main()
{
	if (!register_signal_handlers())
	{
		return EXIT_FAILURE;
	}

	try
	{
		boost::asio::io_service _io_service;

		asiotap::tap_adapter tap_adapter(_io_service, asiotap::tap_adapter_layer::ip);

		stop_function = boost::bind(&close_tap_adapter, boost::ref(tap_adapter));

		tap_adapter.open();

		asiotap::tap_adapter_configuration configuration {};
		configuration.ipv4.network_address = { boost::asio::ip::address_v4::from_string("9.0.0.1"), 24 };
		configuration.ipv4.remote_address = boost::asio::ip::address_v4::from_string("9.0.0.0");
		configuration.ipv6.network_address = { boost::asio::ip::address_v6::from_string("fe80::c887:eb51:aaaa:bbbb"), 64 };

		tap_adapter.configure(configuration);

		tap_adapter.set_connected_state(true);

		tap_adapter.async_read(boost::asio::buffer(my_buf, sizeof(my_buf)), boost::bind(&read_done, boost::ref(tap_adapter), _1, _2));

		const auto addresses = tap_adapter.get_ip_addresses();

		std::cout << "Current IP addresses for the interface:" << std::endl;

		for(auto&& address : addresses)
		{
			std::cout << address << std::endl;
		}

		std::cout << "Adding routes" << std::endl;

		asiotap::route_manager rmgr(_io_service);
		rmgr.set_route_registration_success_handler([](const asiotap::route_manager::route_type& route){
			std::cout << "Added route: " << route << std::endl;
		});
		rmgr.set_route_registration_failure_handler([](const asiotap::route_manager::route_type& route, const boost::system::system_error& ex){
			std::cout << "Failure adding route (" << route << "): " << ex.what() << std::endl;
		});
		rmgr.set_route_unregistration_success_handler([](const asiotap::route_manager::route_type& route){
			std::cout << "Removed route: " << route << std::endl;
		});
		rmgr.set_route_unregistration_failure_handler([](const asiotap::route_manager::route_type& route, const boost::system::system_error& ex){
			std::cout << "Failure removing route (" << route << "): " << ex.what() << std::endl;
		});

		const auto r1 = rmgr.get_route_entry(tap_adapter.get_route(asiotap::to_ip_route(boost::asio::ip::address_v4::from_string("9.0.1.0"), 24)));
		const auto r2 = rmgr.get_route_entry(tap_adapter.get_route(asiotap::to_ip_route(boost::asio::ip::address_v4::from_string("9.0.2.0"), 24, boost::asio::ip::address_v4::from_string("9.0.1.2"))));

		_io_service.run();
	}
	catch (std::exception& ex)
	{
		std::cerr << "Exception caught: " << ex.what() << std::endl;

		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Exemple #16
0
int main(int argc, char **argv)
{
    const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
    const char *method = NULL, *path = NULL;
    const char *log_filepath = NULL;
    const char *pid_filepath;
#ifdef CONFIG_FSFREEZE
    const char *fsfreeze_hook = NULL;
#endif
    const char *state_dir;
#ifdef _WIN32
    const char *service = NULL;
#endif
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "logfile", 1, NULL, 'l' },
        { "pidfile", 1, NULL, 'f' },
#ifdef CONFIG_FSFREEZE
        { "fsfreeze-hook", 2, NULL, 'F' },
#endif
        { "verbose", 0, NULL, 'v' },
        { "method", 1, NULL, 'm' },
        { "path", 1, NULL, 'p' },
        { "daemonize", 0, NULL, 'd' },
        { "blacklist", 1, NULL, 'b' },
#ifdef _WIN32
        { "service", 1, NULL, 's' },
#endif
        { "statedir", 1, NULL, 't' },
        { NULL, 0, NULL, 0 }
    };
    int opt_ind = 0, ch, daemonize = 0, i, j, len;
    GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
    GList *blacklist = NULL;
    GAState *s;

    module_call_init(MODULE_INIT_QAPI);

    init_dfl_pathnames();
    pid_filepath = dfl_pathnames.pidfile;
    state_dir = dfl_pathnames.state_dir;

    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 'm':
            method = optarg;
            break;
        case 'p':
            path = optarg;
            break;
        case 'l':
            log_filepath = optarg;
            break;
        case 'f':
            pid_filepath = optarg;
            break;
#ifdef CONFIG_FSFREEZE
        case 'F':
            fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
            break;
#endif
        case 't':
             state_dir = optarg;
             break;
        case 'v':
            /* enable all log levels */
            log_level = G_LOG_LEVEL_MASK;
            break;
        case 'V':
            printf("QEMU Guest Agent %s\n", QEMU_VERSION);
            return 0;
        case 'd':
            daemonize = 1;
            break;
        case 'b': {
            if (is_help_option(optarg)) {
                qmp_for_each_command(ga_print_cmd, NULL);
                return 0;
            }
            for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
                if (optarg[i] == ',') {
                    optarg[i] = 0;
                    blacklist = g_list_append(blacklist, &optarg[j]);
                    j = i + 1;
                }
            }
            if (j < i) {
                blacklist = g_list_append(blacklist, &optarg[j]);
            }
            break;
        }
#ifdef _WIN32
        case 's':
            service = optarg;
            if (strcmp(service, "install") == 0) {
                const char *fixed_state_dir;

                /* If the user passed the "-t" option, we save that state dir
                 * in the service. Otherwise we let the service fetch the state
                 * dir from the environment when it starts.
                 */
                fixed_state_dir = (state_dir == dfl_pathnames.state_dir) ?
                                  NULL :
                                  state_dir;
                if (ga_install_vss_provider()) {
                    return EXIT_FAILURE;
                }
                if (ga_install_service(path, log_filepath, fixed_state_dir)) {
                    return EXIT_FAILURE;
                }
                return 0;
            } else if (strcmp(service, "uninstall") == 0) {
                ga_uninstall_vss_provider();
                return ga_uninstall_service();
            } else {
                printf("Unknown service command.\n");
                return EXIT_FAILURE;
            }
            break;
#endif
        case 'h':
            usage(argv[0]);
            return 0;
        case '?':
            g_print("Unknown option, try '%s --help' for more information.\n",
                    argv[0]);
            return EXIT_FAILURE;
        }
    }

#ifdef _WIN32
    /* On win32 the state directory is application specific (be it the default
     * or a user override). We got past the command line parsing; let's create
     * the directory (with any intermediate directories). If we run into an
     * error later on, we won't try to clean up the directory, it is considered
     * persistent.
     */
    if (g_mkdir_with_parents(state_dir, S_IRWXU) == -1) {
        g_critical("unable to create (an ancestor of) the state directory"
                   " '%s': %s", state_dir, strerror(errno));
        return EXIT_FAILURE;
    }
#endif

    s = g_malloc0(sizeof(GAState));
    s->log_level = log_level;
    s->log_file = stderr;
#ifdef CONFIG_FSFREEZE
    s->fsfreeze_hook = fsfreeze_hook;
#endif
    g_log_set_default_handler(ga_log, s);
    g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
    ga_enable_logging(s);
    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
                                                 state_dir);
    s->pstate_filepath = g_strdup_printf("%s/qga.state", state_dir);
    s->frozen = false;

#ifndef _WIN32
    /* check if a previous instance of qemu-ga exited with filesystems' state
     * marked as frozen. this could be a stale value (a non-qemu-ga process
     * or reboot may have since unfrozen them), but better to require an
     * uneeded unfreeze than to risk hanging on start-up
     */
    struct stat st;
    if (stat(s->state_filepath_isfrozen, &st) == -1) {
        /* it's okay if the file doesn't exist, but if we can't access for
         * some other reason, such as permissions, there's a configuration
         * that needs to be addressed. so just bail now before we get into
         * more trouble later
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       s->state_filepath_isfrozen, strerror(errno));
            return EXIT_FAILURE;
        }
    } else {
        g_warning("previous instance appears to have exited with frozen"
                  " filesystems. deferring logging/pidfile creation and"
                  " disabling non-fsfreeze-safe commands until"
                  " guest-fsfreeze-thaw is issued, or filesystems are"
                  " manually unfrozen and the file %s is removed",
                  s->state_filepath_isfrozen);
        s->frozen = true;
    }
#endif

    if (ga_is_frozen(s)) {
        if (daemonize) {
            /* delay opening/locking of pidfile till filesystems are unfrozen */
            s->deferred_options.pid_filepath = pid_filepath;
            become_daemon(NULL);
        }
        if (log_filepath) {
            /* delay opening the log file till filesystems are unfrozen */
            s->deferred_options.log_filepath = log_filepath;
        }
        ga_disable_logging(s);
        qmp_for_each_command(ga_disable_non_whitelisted, NULL);
    } else {
        if (daemonize) {
            become_daemon(pid_filepath);
        }
        if (log_filepath) {
            FILE *log_file = ga_open_logfile(log_filepath);
            if (!log_file) {
                g_critical("unable to open specified log file: %s",
                           strerror(errno));
                goto out_bad;
            }
            s->log_file = log_file;
        }
    }

    /* load persistent state from disk */
    if (!read_persistent_state(&s->pstate,
                               s->pstate_filepath,
                               ga_is_frozen(s))) {
        g_critical("failed to load persistent state");
        goto out_bad;
    }

    blacklist = ga_command_blacklist_init(blacklist);
    if (blacklist) {
        s->blacklist = blacklist;
        do {
            g_debug("disabling command: %s", (char *)blacklist->data);
            qmp_disable_command(blacklist->data);
            blacklist = g_list_next(blacklist);
        } while (blacklist);
    }
    s->command_state = ga_command_state_new();
    ga_command_state_init(s, s->command_state);
    ga_command_state_init_all(s->command_state);
    json_message_parser_init(&s->parser, process_event);
    ga_state = s;
#ifndef _WIN32
    if (!register_signal_handlers()) {
        g_critical("failed to register signal handlers");
        goto out_bad;
    }
#endif

    s->main_loop = g_main_loop_new(NULL, false);
    if (!channel_init(ga_state, method, path)) {
        g_critical("failed to initialize guest agent channel");
        goto out_bad;
    }
#ifndef _WIN32
    g_main_loop_run(ga_state->main_loop);
#else
    if (daemonize) {
        SERVICE_TABLE_ENTRY service_table[] = {
            { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
        StartServiceCtrlDispatcher(service_table);
    } else {
        g_main_loop_run(ga_state->main_loop);
    }
#endif

    ga_command_state_cleanup_all(ga_state->command_state);
    ga_channel_free(ga_state->channel);

    if (daemonize) {
        unlink(pid_filepath);
    }
    return 0;

out_bad:
    if (daemonize) {
        unlink(pid_filepath);
    }
    return EXIT_FAILURE;
}
Exemple #17
0
/* daemon live here, receives command, process it, send back result */
int htxd_start_daemon(htxd *htxd_instance)
{

	int					result				= 0;
	int					socket_fd;
	struct sockaddr_in	local_address;
	struct sockaddr_in	client_address;
	socklen_t			address_length;
	int					new_fd;
	char *				command_buffer		= NULL;
	char *				command_result		= NULL;
	int					command_return_code	= 0;
	char			trace_string[256];


	HTXD_FUNCTION_TRACE(FUN_ENTRY, "htxd_start_daemon");

	init_option_list();
	htxd_autostart(htxd_instance);  /* try autostart if find the autostart flag file */

	socket_fd = htxd_create_socket();

	result = htxd_set_socket_option(socket_fd);

	local_address.sin_family = AF_INET;
	local_address.sin_port = htons (htxd_instance->port_number);
	local_address.sin_addr.s_addr = INADDR_ANY;
	memset (&(local_address.sin_zero), '\0', 8);

	result = htxd_bind_socket(socket_fd, &local_address, htxd_instance->port_number);

	result = htxd_listen_socket(socket_fd);

	HTXD_TRACE(LOG_ON, "starting daemon main loop");
	do  /* this loop make the daemon live */
	{
		do  /* this loop listens for incomming messages */
		{
			HTXD_TRACE(LOG_OFF, "daemon wating for command");
			result = htxd_select(socket_fd);
			if(htxd_shutdown_flag == TRUE) {
				break;
			}
		}while( (result == -1) && (errno == EINTR) );
		if(htxd_shutdown_flag == TRUE) {
			break;
		}

		new_fd = htxd_accept_connection(socket_fd, &client_address, &address_length);
		if(new_fd == -1)
		{
			if(htxd_shutdown_flag == TRUE) {
				break;
			}
			HTXD_TRACE(LOG_OFF, "select time out");
			continue;
		}

		HTXD_TRACE(LOG_OFF, "found a command for receiving");
	
		if(htxd_is_profile_initialized(htxd_instance) != TRUE) {
			HTXD_TRACE(LOG_ON, "initialize HTX profile details");
			htxd_init_profile(&(htxd_instance->p_profile));
			/* htxd_display_profile(htxd_instance->p_profile);  */ /* To DEBUG */
			register_signal_handlers();	
		}

		/* receive the incomming command */
		HTXD_TRACE(LOG_OFF, "daemon receiving command");
		command_buffer = htxd_receive_command(new_fd);
		if(command_buffer == NULL)
		{
			return -1;
		}

		HTXD_TRACE(LOG_OFF, "command received start<<");
		HTXD_TRACE(LOG_OFF, command_buffer);
		HTXD_TRACE(LOG_OFF, ">> command received end");

		htxd_update_command_object(command_buffer);

		if(command_buffer != NULL) {
			free(command_buffer);
			command_buffer = NULL;
		} 

		/* process the received command */
		HTXD_TRACE(LOG_OFF, "daemon start processing command");
		command_return_code = htxd_process_command(&command_result);

		/* handling if command did not generate result buffer */		
		if(command_result == NULL) {
			command_result = malloc(HTX_ERR_MESSAGE_LENGTH);
			if(command_result == NULL) {
				sprintf(trace_string, "Error : malloc(%d) failed with errno = <%d> while allocating error message", HTX_ERR_MESSAGE_LENGTH, errno);
				HTXD_TRACE(LOG_ON, trace_string); 
				exit(1);
			}
			strcpy(command_result, "No result is generated by the command");
		}

		HTXD_TRACE(LOG_OFF, "command result start<<");
		HTXD_TRACE(LOG_OFF, command_result);
		HTXD_TRACE(LOG_OFF, ">> command result end");

		/* send back command result to client */
		HTXD_TRACE(LOG_OFF, "daemon sending the result to client");
		result = htxd_send_response(new_fd, command_result, command_return_code);
		if(result == -1)
		{
			return result;
		}
		
		if(command_result != 0) {
			free(command_result);
		}
		close(new_fd);

	} while(htxd_shutdown_flag == FALSE);

	if(htxd_get_ecg_list_length(htxd_instance->p_ecg_manager) > 0)
	{
		/* shutdown all running ecgs and return */	
		// htxd_shutdown_all_running_ecgs();
	}

	htxd_shutdown_all_mdt();

	HTXD_FUNCTION_TRACE(FUN_EXIT, "htxd_start_daemon");

	return result;
}