Example #1
0
int
main(int argc, char *argv[])
{
  int result;
  struct fuse_args args = FUSE_ARGS_INIT(argc, argv);

  memset(&stormfs, 0, sizeof(struct stormfs));
  stormfs.progname = argv[0];
  stormfs.service = AMAZON;
  set_defaults();

  if(fuse_opt_parse(&args, &stormfs, stormfs_opts, stormfs_opt_proc) == -1) {
    fprintf(stderr, "%s: error parsing command-line options\n", stormfs.progname);
    exit(EXIT_FAILURE);
  }

  parse_config(stormfs.config);
  validate_config();
  if(stormfs.rrs)
    stormfs.storage_class = "REDUCED_REDUNDANCY";

  stormfs.virtual_url = stormfs_virtual_url(stormfs.url, stormfs.bucket);

  g_thread_init(NULL);
  result = stormfs_fuse_main(&args);

  fuse_opt_free_args(&args);

  return result;
}
Example #2
0
END_TEST

START_TEST(test_validate_default_config)
{
    statsite_config config;
    int res = config_from_filename(NULL, &config);
    fail_unless(res == 0);

    res = validate_config(&config);
    fail_unless(res == 0);
}
Example #3
0
END_TEST

START_TEST(test_validate_bad_config)
{
    statsite_config config;
    int res = config_from_filename(NULL, &config);
    fail_unless(res == 0);

    // Set an absurd eps, should fail
    config.timer_eps = 1.0;

    res = validate_config(&config);
    fail_unless(res == 1);
}
Example #4
0
int main(int ac, char *av[]) {
  int rv = 0;

  int sfd = setup_signalfd();

  struct config *config = parse_config("amtredird.ini");
  if (config && validate_config(config)) {
    if (init_amt(config)) {
      if (sfd != -1) {
        rv = (run_server(config, sfd) == 0);
      } else {
        rv = 1;
      }
      teardown_amt(config);
    }
  } else {
    rv = 1;
  }
  close(sfd);
  free_config(config);
  return rv;
}
Example #5
0
void parse_args(int argc, const char * argv[]) {
    int opt;
    
    while ((opt = getopt_long(argc, (char *const *)argv, short_opts, long_options, NULL)) != -1) {
        switch (opt) {
            case 'h':
                print_usage();
                break;
                
            case 'u':
                strcpy((char *)user_config.username, optarg);
                break;
                
            case 'i':
                strcpy((char *)user_config.ipaddress, optarg);
                break;
                
            case 't':
                strcpy((char *)user_config.target, optarg);
                break;
                
            case 'P':
                user_config.port = atoi(optarg);
                break;
                
            case 'I':
                user_config.interval = atoi(optarg);
                break;
                
            default:
                print_usage();
                break;
        }
    }
    validate_config();
}
/*===========================================================================
FUNCTION      isp_tintless_config

DESCRIPTION
===========================================================================*/
static tintless_return_t
isp_tintless_config(tintless_lib_t * const tintless_lib, const tintless_update_request_t type, tintless_cfg_t c)
{
    tintless_stats_config_t * stats_cfg;
    tintless_mesh_config_t * mesh_cfg;
    chromatix_color_tint_correction_type * chromatix_param;
    dmlroc_config_t * const cfg = &tintless_lib->cfg;

    switch (type)
    {
    case UPDATES_STAT_CONFIG:
        stats_cfg = c.stats;

        // check if the new cfg is valid
        if (stats_cfg == NULL || stats_cfg->camif_win_w == 0 ||
            stats_cfg->stat_elem_w == 0 || stats_cfg->stat_elem_h == 0 ||
            stats_cfg->camif_win_h == 0) {
            return TINTLESS_INVALID_STATS;
        }

        // check if the new cfg is different from current cfg
        if (cfg->camif_win_w        != stats_cfg->camif_win_w ||
            cfg->camif_win_h        != stats_cfg->camif_win_h ||
            cfg->stat_elem_w        != stats_cfg->stat_elem_w ||
            cfg->stat_elem_h        != stats_cfg->stat_elem_h
            )
        {
            cfg->camif_win_w        = stats_cfg->camif_win_w;
            cfg->camif_win_h        = stats_cfg->camif_win_h;
            cfg->stat_elem_w        = stats_cfg->stat_elem_w;
            cfg->stat_elem_h        = stats_cfg->stat_elem_h;
            CDBG_ERROR("%s: cfg: camif %dx%d, elem sz %dx%d,", __func__,stats_cfg->camif_win_w, stats_cfg->camif_win_h, stats_cfg->stat_elem_w, stats_cfg->stat_elem_h);
        } else {
            printf("same cfg as current\n");
            return TINTLESS_SUCCESS;
        }
        break;

    case UPDATES_CHROMATIX_PARAMS:
        chromatix_param = c.chromatix;

        if (chromatix_param == NULL)
            return TINTLESS_INVALID_STATS;

        // check if the new cfg is different from current cfg
        if (cfg->tint_correction_strength != chromatix_param->tint_correction_strength)
        {
            cfg->tint_correction_strength = chromatix_param->tint_correction_strength;
            CDBG_ERROR("%s: tint_correction_strength updated to %d", __func__, cfg->tint_correction_strength);
        } else {
            CDBG_ERROR("%s: same cfg as current", __func__);
            return TINTLESS_SUCCESS;
        }
        break;
    default:
        return TINTLESS_UPDATES_NOT_SUPPORTED;
        break;
    } // end switch

    // validate config struct. If complete, init tintless lib
    if (validate_config(tintless_lib, cfg))
        return translate_return_code(tintless_lib->init_func(cfg));
    else
        return TINTLESS_SUCCESS;


} /* isp_tintless_config */
int main(int argc, char **argv) {
    // Initialize syslog
    setup_syslog();

    // Parse the command line
    char *config_file = NULL;
    int parse_res = parse_cmd_line_args(argc, argv, &config_file);
    if (parse_res) return 1;

    // Parse the config file
    statsite_proxy_config *config = calloc(1, sizeof(statsite_proxy_config));
    int config_res = config_from_filename(config_file, config);
    if (config_res != 0) {
        syslog(LOG_ERR, "Failed to read the configuration file!");
        return 1;
    }

    // Validate the config file
    int validate_res = validate_config(config);
    if (validate_res != 0) {
        syslog(LOG_ERR, "Invalid configuration!");
        return 1;
    }

    // Set the syslog mask
    setlogmask(config->syslog_log_level);

    // Daemonize
    if (config->daemonize) {
        pid_t pid, sid;
        syslog(LOG_INFO, "Daemonizing.");
        pid = fork();

        // Exit if we failed to fork
        if (pid < 0) {
            syslog(LOG_ERR, "Failed to fork() daemon!");
            return 1;
        }

        // Parent process returns
        if (pid) return 0;

        // Create a new session
        sid = setsid();
        if (sid < 0) {
            syslog(LOG_ERR, "Failed to set daemon SID!");
            return 1;
        }

        int write_pidfile_res = write_pidfile(config->pid_file, sid);
        if (write_pidfile_res) {
            syslog(LOG_ERR, "Failed to write pidfile. Terminating.");
            return 1;
        }

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

    // Log that we are starting up
    syslog(LOG_INFO, "Starting statsite-proxy.");
    syslog(LOG_INFO, "Loaded Servers config: %s", config->servers);

    // Initialize proxy
    proxy *proxy = NULL;
    int proxy_res = proxy_init(&proxy, config->servers);

    if (proxy_res != 0) {
    	syslog(LOG_ERR, "Failed to initialize proxy!");
    	return 1;
    }

    // Initialize the networking
    statsite_proxy_networking *netconf = NULL;
    int net_res = init_networking(config, &netconf, proxy);
    if (net_res != 0) {
        syslog(LOG_ERR, "Failed to initialize networking!");
        return 1;
    }

    // Start the network workers
    pthread_t thread;
    pthread_create(&thread, NULL, (void*(*)(void*))start_networking_worker, netconf);

    /**
     * Loop forever, until we get a signal that
     * indicates we should shutdown.
     */

    signal(SIGPIPE, SIG_IGN);       // Ignore SIG_IGN
    signal(SIGHUP, SIG_IGN);        // Ignore SIG_IGN
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    while (SHOULD_RUN) {
        sleep(1);
    }

    // Begin the shutdown/cleanup
    shutdown_networking(netconf);

    // If daemonized, remove the pid file

    if (config->daemonize && unlink(config->pid_file)) {
        syslog(LOG_ERR, "Failed to delete pid file!");
    }

    // Free our memory
    proxy_destroy(proxy);
    free(config);



    // Done
    return 0;
}
Example #8
0
int cmd_rxtx(struct cli_state *s, int argc, char **argv)
{
    int ret = CMD_RET_OK;
    int fpga_loaded;
    enum rxtx_cmd cmd;
    struct common_cfg *common;
    bool is_tx;
    int (*start_init)(struct cli_state *s);
    int (*stop_cleanup)(struct cli_state *s);

        if (!strcasecmp("tx", argv[0])) {
            is_tx = true;
            common = &s->rxtx_data->tx.common;
            start_init = tx_start_init;
            stop_cleanup = tx_stop_cleanup;
        } else if (!strcasecmp("rx", argv[0])) {
            is_tx = false;
            common = &s->rxtx_data->rx.common;
            start_init = rx_start_init;
            stop_cleanup = rx_stop_cleanup;
        } else {
            /* Bug */
            assert(0);
            return CMD_RET_UNKNOWN;
        }

    /* Just <rx|tx> is supported shorthand for <rx|tx> config */
    if (argc == 1) {
        cmd = RXTX_CMD_CFG;
    } else {
        cmd = get_cmd(argv[1]);
    }

    switch (cmd) {
        case RXTX_CMD_START:
            if (!cli_device_is_opened(s)) {
                ret = CMD_RET_NODEV;
            } else if (get_state(common) == RXTX_STATE_RUNNING) {
                ret = CMD_RET_STATE;
            } else {
                fpga_loaded = bladerf_is_fpga_configured(s->dev);
                if (fpga_loaded < 0) {
                    s->last_lib_error = fpga_loaded;
                    ret = CMD_RET_LIBBLADERF;
                } else if (!fpga_loaded) {
                    cli_err(s, argv[0], "FPGA is not configured");
                    ret = CMD_RET_INVPARAM;
                } else {
                    ret = validate_config(s, argv[0], s->rxtx_data, is_tx);
                    if (!ret) {
                        ret = open_samples_file(common, NULL, is_tx ? "r" : "w");
                        if (!ret) {
                            ret = start_init(s);
                        }
                    }
                }
            }
            break;

        case RXTX_CMD_STOP:
            if (!cli_device_is_opened(s)) {
                ret = CMD_RET_NODEV;
            } else if (get_state(common) != RXTX_STATE_RUNNING) {
                ret = CMD_RET_STATE;
            } else {
                ret = stop_cleanup(s);
            }
            break;

        case RXTX_CMD_CFG:
            if (argc > 2) {
                if (get_state(common) != RXTX_STATE_RUNNING) {
                    ret = handle_params(s, argc, argv, is_tx);
                } else {
                    ret = CMD_RET_STATE;
                }
            } else {
                print_config(s->rxtx_data, is_tx);
            }
            break;

        default:
            cli_err(s, argv[0], "Invalid command (%s)", argv[1]);
            ret = CMD_RET_INVPARAM;
    }


    return ret;
}
Example #9
0
File: main.c Project: l3ib/fsniper
int main(int argc, char** argv)
{
    int ifd, len = 0, i = 0, selectret = 0, maxfd, retryselect, pid;
    char buf[BUF_LEN]; 
    char *configdir;
    char *pidfilename;
    char *statusfilename;
    char *statusbin;
    char *error_str;
    char *version_str = PACKAGE_STRING;
    char *pbuf;
    char *filename;
    FILE *pidfile;
    FILE *statusfile;
    fd_set set;
    struct inotify_event *event;
    struct argument *argument = argument_new();
    struct pipe_list *pipe_list_cur;
    struct stat file_stat;
    struct watchnode *node;

    /* alloc pipe list */
    pipe_list_head = malloc(sizeof(struct pipe_list));
    pipe_list_head->next = NULL;

    /* set up signals for exiting/reaping */ 
    signal(SIGINT, &handle_quit_signal); 
    signal(SIGTERM, &handle_quit_signal);
    signal(SIGCHLD, &handle_child_signal);
    signal(SIGHUP, &handle_hup_signal);


    /* add command line arguments */
    argument_register(argument, "help", "Prints this help text.", 0);
    argument_register(argument, "version", "Prints version information.", 0);
    argument_register(argument, "daemon", "Run as a daemon.", 0);
    argument_register(argument, "verbose", "Turns on debug text.", 0);
    argument_register(argument, "sync", "Sync mode (for debugging).", 0);
    argument_register(argument, "log-to-stdout", "Deprecated, use \"--log-to=stdout\" instead", 0);
    argument_register(argument, "log-to", "Log messages with specified way. "
#ifdef USE_SYSLOG
                                "Can be: stdout, file, syslog. \"file\" by default.", 1);
#else
                                "Can be: stdout, file. \"file\" by default.", 1);
#endif

    if ((error_str = argument_parse(argument, argc, argv))) {
	fprintf(stderr, "Error in arguments: %s", error_str);
	free(error_str);
	return -1;
    }

    if (argument_exists(argument, "help")) {
	char *help_txt = argument_get_help_text(argument);
	printf("%s", help_txt);
	free(help_txt);
	return 0;
    }

    if (argument_exists(argument, "version")) {
	printf("%s\n", version_str);
	return 0;
    }

    if (argument_exists(argument, "verbose")) {
	verbose = 1;
    }

    if (argument_exists(argument, "daemon") && fork())
	return 0;

    if (argument_exists(argument, "sync"))
	syncmode = 1;


    if (argument_exists(argument, "log-to-stdout"))
        fprintf(stderr, "Warning, this option is deprecated, " \
                        "please use new syntax: \"--log-to=stdout\".\n");

    logtype = LOG_FILE;
    if (argument_exists(argument, "log-to") && \
        (log_arg = argument_get_value(argument, "log-to")) != NULL)
    {
        if      (strcmp(log_arg, "stdout") == 0)
            logtype = LOG_STDOUT;
#ifdef USE_SYSLOG
        else if (strcmp(log_arg, "syslog") == 0)
            logtype = LOG_SYS;
#endif
        else /* logtype already set to 'file' above */
            fprintf(stderr, "Warning, selected unknown logging type. " \
                            "Will use \"--log-to=file\" instead.\n");
    }

    /* get config dir (must free this) */
    configdir = get_config_dir();	

    /* if a config file has not been specified, use default */
    if (argument_get_extra(argument))
    {
	configfile = strdup(argument_get_extra(argument));
    }
    else
    {
	configfile = malloc (strlen(configdir) + strlen ("/config") + 1);
	sprintf(configfile, "%s/config", configdir);
    }

    argument_free(argument);
    free(configdir);

    if (access(configfile, R_OK) != 0)
    {
	fprintf(stderr, "error: could not open config file: %s\n", configfile);
	return -1;
    }

    /* create a pid file */
    pidfilename = get_pid_filename();
	
    if (stat(pidfilename, &file_stat) == 0) /* pidfile exists */
    {
	pidfile = fopen(pidfilename, "r");
		
	if (fscanf(pidfile, "%d", &pid) == 1) /* pidfile has a pid inside */
	{
	    char *binaryname;
	    char *scanformat; 
	    if ((binaryname = strrchr(argv[0], '/')) != NULL)
	    {
		binaryname++;
	    }
	    else
	    {
		binaryname = argv[0];
	    }

	    scanformat = malloc(strlen("Name:   %") + strlen(binaryname) + strlen("s") + 1);
	    statusfilename = malloc(strlen("/proc/") + 6 + strlen("/status") + 1);
	    sprintf(statusfilename, "/proc/%d/status", pid);

	    if (stat(statusfilename, &file_stat) != 0) /* write pid file if the process no longer exists */
	    {
		write_pid_file(pidfilename);
	    }
	    else /* process exists, so check owner and binary name */
	    {
		statusfile = fopen(statusfilename, "r");
		statusbin = malloc(strlen(binaryname) + 2); /* the binary name may start with "fsniper" but be longer */
		sprintf(scanformat, "Name:   %%%ds", strlen(binaryname) + 1);
		fscanf(statusfile, scanformat, statusbin);
		free(statusfilename);
		fclose(statusfile);
		fclose(pidfile);
				
		if (strcmp(binaryname, statusbin) == 0 && file_stat.st_uid == getuid())
		    /* exit if the process is fsniper and is owned by the current user */
		{
		    printf("%s: already running instance found with pid %d. exiting.\n", binaryname, pid);
		    exit(1);
		}
		else /* the pid file contains an old pid, one that isn't fsniper, or one not owned by the current user */
		{
		    write_pid_file(pidfilename);
		}
	    }
	}
	else /* pidfile is invalid */
	{
	    fclose(pidfile);
	    write_pid_file(pidfilename);
	}
    }
    else /* the pidfile doesn't exist */
    {
	write_pid_file(pidfilename);
    }
    free(pidfilename);

    /* start up log */
    if (!log_open())
    {
	fprintf(stderr, "Error: could not start log.\n");
	return -1;
    }

    ifd = inotify_init();
    if (ifd < 0)
    {
	perror("inotify_init");
	return -1;
    }

    if (verbose) log_write("Parsing config file: %s\n", configfile);
    config = keyval_parse_file(configfile);

    if ((error_str = keyval_get_error())) {
        fprintf(stderr, "%s", error_str);
        free(error_str);
        exit(1);
    }

    validate_config(config);

    /* add nodes to the inotify descriptor */
    g_watchnode = add_watches(ifd);

    /* wait for events and then handle them */
    while (1)
    {		
	/* set up fds and max */
	FD_ZERO(&set);
	FD_SET(ifd, &set);
	maxfd = ifd;
	for (pipe_list_cur = pipe_list_head->next; pipe_list_cur; pipe_list_cur = pipe_list_cur->next)
	{
	    FD_SET(pipe_list_cur->pfd[0], &set);
	    if (pipe_list_cur->pfd[0] > maxfd)
		maxfd = pipe_list_cur->pfd[0];
	}

	retryselect = 1;
	while (retryselect)
	{
	    /* use select to get activity on any of the fds */
	    selectret = select(maxfd + 1, &set, NULL, NULL, NULL);

	    if (selectret == -1)
	    {
		if (errno == EINTR)
		    retryselect = 1;
		else
		    handle_quit_signal(-2);
	    } else
		retryselect = 0;
	}
		
	/* handle any events on the inotify fd */
	if (FD_ISSET(ifd, &set))
	{
	    len = read(ifd, buf, BUF_LEN);
	    while (i < len)
	    {
		event = (struct inotify_event *) &buf[i];
		if (event->len && (event->mask & IN_CLOSE_WRITE || event->mask & IN_MOVED_TO))
		{
		    /* if sync mode, just call handle_exec */
		    if (syncmode == 1)
		    {
			handle_event(event, fileno(_logfd));
		    }
		    else
		    {
			/* create new pipe_list entry */
			for (pipe_list_cur = pipe_list_head; pipe_list_cur->next != NULL; pipe_list_cur = pipe_list_cur->next) {}

			pipe_list_cur->next = malloc(sizeof(struct pipe_list));
			pipe_list_cur->next->next = NULL;

			/* create pipe */
			pipe(pipe_list_cur->next->pfd);

			if (fork() == 0) 
			{
			    /* child, close 0 */
			    close(pipe_list_cur->next->pfd[0]);					
			    log_close();
			    signal(SIGINT, &handle_child_quit_signal);
			    signal(SIGTERM, &handle_child_quit_signal);
			    handle_event(event, pipe_list_cur->next->pfd[1]);
			} else {
			    /* parent, close 1 */
			    close(pipe_list_cur->next->pfd[1]);
			}
		    }
		}
                else if (event->len && (event->mask & IN_CREATE && event->mask & IN_ISDIR))
                {
                    for (node = g_watchnode->next; node; node = node->next)
                        if (node->wd == event->wd)
                            break;

                    if (node)
                    {
                        /* combine the name inotify gives with the full path to the file */
                        filename = malloc(strlen(node->path) + strlen("/") + strlen(event->name) + 1);
                        sprintf(filename, "%s/%s", node->path, event->name);
                        watch_dir(node, ifd, strdup(filename), node->section);
                        free(filename);
                    }
                }
		else if (event->len && (event->mask & IN_DELETE && event->mask & IN_ISDIR))
                {
                    for (node = g_watchnode->next; node; node = node->next)
                        if (node->wd == event->wd)
                            break;

                    if (node)
                    {
                        /* combine the name inotify gives with the full path to the file */
                        filename = malloc(strlen(node->path) + strlen("/") + strlen(event->name) + 1);
                        sprintf(filename, "%s/%s", node->path, event->name);
                        unwatch_dir(filename, ifd);
                        free(filename);
                    }
                }
                i += EVENT_SIZE + event->len;
            }
	    i = 0;
	}
		
	/* now lets see if we have any pipe activity */
	pipe_list_cur = pipe_list_head->next;
	while (pipe_list_cur)
	{
	    if (FD_ISSET(pipe_list_cur->pfd[0], &set))
	    {
		len = read(pipe_list_cur->pfd[0], buf, BUF_LEN);
		if (len == 0)
		{
		    close(pipe_list_cur->pfd[0]);
		    /* remove this item from the list */
		    pipe_list_cur = pipe_list_remove(pipe_list_head, pipe_list_cur);
					
		} else {
		    /* print it somewhere */
		    pbuf = malloc(len + 1);
		    snprintf(pbuf, len, "%s", buf);
		    log_write("%s\n", pbuf);
		    free(pbuf);
		    pipe_list_cur = pipe_list_cur->next;
		}
	    } else {
		pipe_list_cur = pipe_list_cur->next;

	    }


	}
    }
}
Example #10
0
int main(int argc, char **argv) {
    // Initialize syslog
    setup_syslog();

    // Parse the command line
    char *config_file = NULL;
    int parse_res = parse_cmd_line_args(argc, argv, &config_file);
    if (parse_res) return 1;

    // Parse the config file
    statsite_config *config = calloc(1, sizeof(statsite_config));
    int config_res = config_from_filename(config_file, config);
    if (config_res != 0) {
        syslog(LOG_ERR, "Failed to read the configuration file!");
        return 1;
    }

    // Validate the config file
    if (validate_config(config)) {
        syslog(LOG_ERR, "Invalid configuration!");
        return 1;
    }

    // Set prefixes for each message type
    if (prepare_prefixes(config)) {
        syslog(LOG_ERR, "Failed to get prefixes!");
        return 1;
    }

    // Build the prefix tree
    if (build_prefix_tree(config)) {
        syslog(LOG_ERR, "Failed to build prefix tree!");
        return 1;
    }

    // Set the syslog mask
    setlogmask(config->syslog_log_level);

    // Daemonize
    if (config->daemonize) {
        pid_t pid, sid;
        int fd;
        syslog(LOG_INFO, "Daemonizing.");
        pid = fork();

        // Exit if we failed to fork
        if (pid < 0) {
            syslog(LOG_ERR, "Failed to fork() daemon!");
            return 1;
        }

        // Parent process returns
        if (pid) return 0;

        // Create a new session
        sid = setsid();
        if (sid < 0) {
            syslog(LOG_ERR, "Failed to set daemon SID!");
            return 1;
        }

        int write_pidfile_res = write_pidfile(config->pid_file, sid);
        if (write_pidfile_res) {
            syslog(LOG_ERR, "Failed to write pidfile. Terminating.");
            return 1;
        }

        if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
          dup2(fd, STDIN_FILENO);
          dup2(fd, STDOUT_FILENO);
          dup2(fd, STDERR_FILENO);
          if (fd > STDERR_FILENO) close(fd);
        }
    }

    // Log that we are starting up
    syslog(LOG_INFO, "Starting statsite.");

    // Initialize the networking
    statsite_networking *netconf = NULL;
    int net_res = init_networking(config, &netconf);
    if (net_res != 0) {
        syslog(LOG_ERR, "Failed to initialize networking!");
        return 1;
    }

    // Setup signal handlers
    signal(SIGPIPE, SIG_IGN);       // Ignore SIG_IGN
    signal(SIGHUP, SIG_IGN);        // Ignore SIG_IGN
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    // Join the networking loop, blocks until exit
    enter_networking_loop(netconf, &SHOULD_RUN);

    // Begin the shutdown/cleanup
    shutdown_networking(netconf);

    // Do the final flush
    final_flush();

    // If daemonized, remove the pid file
    if (config->daemonize && unlink(config->pid_file)) {
        syslog(LOG_ERR, "Failed to delete pid file!");
    }

    // Free our memory
    free(config);

    // Done
    return 0;
}
Example #11
0
void load_config(char configPath[255], char supportedInput[255], void* params)
{

struct config_params *p = (struct config_params *)params;
FILE *fp;
	
//config: creating path to default config file
if (configPath[0] == '\0') {
	char *configFile = "config";
	char *configHome = getenv("XDG_CONFIG_HOME");
	if (configHome != NULL) {
		sprintf(configPath,"%s/%s/", configHome, PACKAGE);
	} else {
		configHome = getenv("HOME");
		if (configHome != NULL) {
			sprintf(configPath,"%s/%s/%s/", configHome, ".config", PACKAGE);
		} else {
			printf("No HOME found (ERR_HOMELESS), exiting...");
			exit(EXIT_FAILURE);
		}
	}

	// config: create directory
	mkdir(configPath, 0777);

	// config: adding default filename file
	strcat(configPath, configFile);
	
	fp = fopen(configPath, "ab+");
	if (fp) {
		fclose(fp);
	} else {
		printf("Unable to access config '%s', exiting...\n", configPath);
		exit(EXIT_FAILURE);
	}


} else { //opening specified file

	fp = fopen(configPath, "rb+");	
	if (fp) {
		fclose(fp);
	} else {
		printf("Unable to open file '%s', exiting...\n", configPath);
		exit(EXIT_FAILURE);
	}
}

// config: parse ini
dictionary* ini;
ini = iniparser_load(configPath);

//setting fifo to defaualt if no other input modes supported
inputMethod = (char *)iniparser_getstring(ini, "input:method", "fifo"); 

//setting alsa to defaualt if supported
#ifdef ALSA
	inputMethod = (char *)iniparser_getstring(ini, "input:method", "alsa"); 
#endif

//setting pulse to defaualt if supported
#ifdef PULSE
	inputMethod = (char *)iniparser_getstring(ini, "input:method", "pulse");
#endif


#ifdef NCURSES
	outputMethod = (char *)iniparser_getstring(ini, "output:method", "ncurses");
#endif
#ifndef NCURSES
	outputMethod = (char *)iniparser_getstring(ini, "output:method", "noncurses");
#endif

p->monstercat = 1.5 * iniparser_getdouble(ini, "smoothing:monstercat", 1);
p->waves = iniparser_getint(ini, "smoothing:waves", 0);
p->integral = iniparser_getdouble(ini, "smoothing:integral", 90);
p->gravity = iniparser_getdouble(ini, "smoothing:gravity", 100);
p->ignore = iniparser_getdouble(ini, "smoothing:ignore", 0);

p->color = (char *)iniparser_getstring(ini, "color:foreground", "default");
p->bcolor = (char *)iniparser_getstring(ini, "color:background", "default");

p->gradient = iniparser_getint(ini, "color:gradient", 0);
if (p->gradient) {
	p->gradient_color_1 = (char *)iniparser_getstring(ini, "color:gradient_color_1", "#0099ff");
	p->gradient_color_2 = (char *)iniparser_getstring(ini, "color:gradient_color_2", "#ff3399");
}

p->fixedbars = iniparser_getint(ini, "general:bars", 0);
p->bw = iniparser_getint(ini, "general:bar_width", 2);
p->bs = iniparser_getint(ini, "general:bar_spacing", 1);
p->framerate = iniparser_getint(ini, "general:framerate", 60);
p->sens = iniparser_getint(ini, "general:sensitivity", 100);
p->autosens = iniparser_getint(ini, "general:autosens", 1);
p->overshoot = iniparser_getint(ini, "general:overshoot", 20);
p->lowcf = iniparser_getint(ini, "general:lower_cutoff_freq", 50);
p->highcf = iniparser_getint(ini, "general:higher_cutoff_freq", 10000);

// config: output
channels =  (char *)iniparser_getstring(ini, "output:channels", "stereo");
p->raw_target = (char *)iniparser_getstring(ini, "output:raw_target", "/dev/stdout");
data_format = (char *)iniparser_getstring(ini, "output:data_format", "binary");
p->bar_delim = (char)iniparser_getint(ini, "output:bar_delimiter", 59);
p->frame_delim = (char)iniparser_getint(ini, "output:frame_delimiter", 10);
p->ascii_range = iniparser_getint(ini, "output:ascii_max_range", 1000);
p->bit_format = iniparser_getint(ini, "output:bit_format", 16);

// read & validate: eq
p->smooth = smoothDef;
p->smcount = iniparser_getsecnkeys(ini, "eq");
if (p->smcount > 0) {
	p->customEQ = 1;
	p->smooth = malloc(p->smcount*sizeof(p->smooth));
	#ifndef LEGACYINIPARSER
	const char *keys[p->smcount];
	iniparser_getseckeys(ini, "eq", keys);
	#endif
	#ifdef LEGACYINIPARSER
	char **keys = iniparser_getseckeys(ini, "eq");
	#endif
	for (int sk = 0; sk < p->smcount; sk++) {
		p->smooth[sk] = iniparser_getdouble(ini, keys[sk], 1);
	}
} else {
	p->customEQ = 0;
	p->smcount = 64; //back to the default one
}

// config: input
p->im = 0;
if (strcmp(inputMethod, "alsa") == 0) {
	p->im = 1;
	p->audio_source = (char *)iniparser_getstring(ini, "input:source", "hw:Loopback,1");
}
if (strcmp(inputMethod, "fifo") == 0) {
	p->im = 2;
	p->audio_source = (char *)iniparser_getstring(ini, "input:source", "/tmp/mpd.fifo");
}
if (strcmp(inputMethod, "pulse") == 0) {
	p->im = 3;
	p->audio_source = (char *)iniparser_getstring(ini, "input:source", "auto");
}

validate_config(supportedInput, params);
//iniparser_freedict(ini);

}
Example #12
0
int main(int argc, char **argv) {

    // temporarily set the syslog facilty to main and init it
    setup_syslog(LOG_USER, 0);

    // Parse the command line
    char *config_file = NULL;
    int parse_res = parse_cmd_line_args(argc, argv, &config_file);
    if (parse_res) return 1;

    // Parse the config file
    statsite_config *config = alloc_config();
    int config_res = config_from_filename(config_file, config);
    if (config_res != 0) {
        syslog(LOG_ERR, "Failed to read the configuration file!");
        return 1;
    }

    // Validate the config file
    if (validate_config(config)) {
        syslog(LOG_ERR, "Invalid configuration!");
        return 1;
    }

    // close the initial syslog
    closelog();

    // Initialize syslog with configured facility
    setup_syslog(config->syslog_log_facility, config->daemonize);

    // Set prefixes for each message type
    if (prepare_prefixes(config)) {
        syslog(LOG_ERR, "Failed to get prefixes!");
        return 1;
    }

    // Build the prefix tree
    if (build_prefix_tree(config)) {
        syslog(LOG_ERR, "Failed to build prefix tree!");
        return 1;
    }

    // Set the syslog mask
    setlogmask(config->syslog_log_level);

    // Initialize libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Daemonize
    if (config->daemonize) {
        pid_t pid, sid;
        int fd;
        syslog(LOG_INFO, "Daemonizing.");
        pid = fork();

        // Exit if we failed to fork
        if (pid < 0) {
            syslog(LOG_ERR, "Failed to fork() daemon!");
            return 1;
        }

        // Parent process returns
        if (pid) return 0;

        // Create a new session
        sid = setsid();
        if (sid < 0) {
            syslog(LOG_ERR, "Failed to set daemon SID!");
            return 1;
        }

        int write_pidfile_res = write_pidfile(config->pid_file, sid);
        if (write_pidfile_res) {
            syslog(LOG_ERR, "Failed to write pidfile. Terminating.");
            return 1;
        }

        if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
          dup2(fd, STDIN_FILENO);
          dup2(fd, STDOUT_FILENO);
          dup2(fd, STDERR_FILENO);
          if (fd > STDERR_FILENO) close(fd);
        }
    }

    // Log that we are starting up
    syslog(LOG_INFO, "Starting statsite.");

    // Build the sinks
    sink* sinks = NULL;
    init_sinks(&sinks, config);

    // Initialize the networking
    statsite_networking *netconf = NULL;
    int net_res = init_networking(config, &netconf, sinks);
    if (net_res != 0) {
        syslog(LOG_ERR, "Failed to initialize networking!");
        return 1;
    }

    // Setup signal handlers
    signal(SIGPIPE, SIG_IGN);       // Ignore SIG_IGN
    signal(SIGHUP, SIG_IGN);        // Ignore SIG_IGN
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    // Join the networking loop, blocks until exit
    enter_networking_loop(netconf, &SIGNUM);

    if (SIGNUM != 0) {
        syslog(LOG_WARNING, "Received signal [%s]! Exiting...", strsignal(SIGNUM));
    }

    // Begin the shutdown/cleanup
    shutdown_networking(netconf);

    // Do the final flush
    final_flush(sinks);

    // If daemonized, remove the pid file
    if (config->daemonize && unlink(config->pid_file)) {
        syslog(LOG_ERR, "Failed to delete pid file!");
    }

    // Free our memory
    free_config(config);

    // Tear down libcurl
    curl_global_cleanup();

    // Done
    return 0;
}
Example #13
0
/* Main loop for processing the configuration file */
int
schd_get_config(char *filename)
  {
  char   *id = "schd_get_config";

  char    line[MAX_LINE_SIZE];
  char    cfg_option[MAX_LINE_SIZE];
  char    cfg_arg[MAX_LINE_SIZE];
  FILE   *cfgfd = NULL;

  char   *comment;
  int     linenum = 0, error = 0;
  size_t  linelen;

  cfgfd = fopen(filename, "r");

  if (cfgfd == NULL)
    {
    (void)sprintf(log_buffer,
                  "Opening '%s': %s", filename, strerror(errno));

    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
    DBPRT(("%s: %s\n", id, log_buffer));

    return (-1);
    }

  /* Walk through the configuration file line by line. */
  while (fgets(line, sizeof(line), cfgfd))
    {
    linenum++;

    linelen = strlen(line);

    if (linelen == (sizeof(line) - 1))
      {
      (void)sprintf(log_buffer,
                    "Error in config file %s, line %d: Line too long",
                    filename, linenum);
      log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
      DBPRT(("%s\n", log_buffer));

      error = -1;
      break;
      }
    else
      {
      linelen--;   /* Move back to newline. */
      line[linelen] = '\0'; /* And remove it. */
      }

    /* If there is a comment on this line, remove it from view. */
    if ((comment = strchr(line, '#')) != NULL)
      * comment = '\0';

    if (strlen(line) < 2)
      continue;  /* skip blank lines */

    /* Split the option and the argument. */
    if (sscanf(line, "%s %s", cfg_option, cfg_arg) != 2)
      {
      /* Unable to read a cfg_option and cfg_arg */
      (void)sprintf(log_buffer, "Error in config file %s, line %d",
                    filename, linenum);
      log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
      DBPRT(("%s\n", log_buffer));

      error = -1;
      break;
      }

    /* Set the configurable options */
    if (set_cfg_opt(cfg_option, cfg_arg))
      {
      /* Unable to parse the option. */
      (void)sprintf(log_buffer,
                    "Error parsing option '%s' in config file %s, line %d",
                    cfg_option, filename, linenum);
      log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
      DBPRT(("%s\n", log_buffer));

      error = -1;
      break;
      }
    }

  /* Close the config file */

  fclose(cfgfd);

  if (error)
    return (error);

  /* Do any post-configuration necessary. */
  if (!post_config())
    return (-1);

  if (!validate_config())
    return (-1);

  print_config();

  return (0);
  }
/*===========================================================================
FUNCTION      isp_tintless_config

DESCRIPTION
===========================================================================*/
static tintless_return_t
isp_tintless_config(tintless_lib_t * const tintless_lib, const tintless_update_request_t type, tintless_cfg_t c)
{
    tintless_stats_config_t * stats_cfg;
    tintless_mesh_config_t * mesh_cfg;
    chromatix_color_tint_correction_type * chromatix_param;
    dmlroc_config_t * const cfg = &tintless_lib->cfg;

    switch (type)
    {
    case UPDATES_STAT_CONFIG:
        stats_cfg = c.stats;

        // check if the new cfg is valid
        if (stats_cfg == NULL || stats_cfg->camif_win_w == 0 ||
            stats_cfg->stat_elem_w == 0 || stats_cfg->stat_elem_h == 0 ||
            stats_cfg->camif_win_h == 0 || stats_cfg->num_stat_elem_rows ==0 ||
            stats_cfg->num_stat_elem_cols == 0) {
            return TINTLESS_INVALID_STATS;
        }

        // check if the new cfg is different from current cfg
        if (cfg->camif_win_w        != stats_cfg->camif_win_w ||
            cfg->camif_win_h        != stats_cfg->camif_win_h ||
            cfg->stat_elem_w        != stats_cfg->stat_elem_w ||
            cfg->stat_elem_h        != stats_cfg->stat_elem_h ||
            cfg->num_stat_elem_rows != stats_cfg->num_stat_elem_rows ||
            cfg->num_stat_elem_cols != stats_cfg->num_stat_elem_cols ||
            cfg->b_post_stats       != stats_cfg->stats_type
            )
        {
            cfg->camif_win_w        = stats_cfg->camif_win_w;
            cfg->camif_win_h        = stats_cfg->camif_win_h;
            cfg->stat_elem_w        = stats_cfg->stat_elem_w;
            cfg->stat_elem_h        = stats_cfg->stat_elem_h;
            cfg->num_stat_elem_rows = stats_cfg->num_stat_elem_rows;
            cfg->num_stat_elem_cols = stats_cfg->num_stat_elem_cols;
            cfg->b_post_stats       = (stats_cfg->stats_type == STATS_TYPE_BG) ? 1 : 0;
            CDBG_ERROR("%s: cfg: camif %dx%d, elem sz %dx%d, elems %dx%d", __func__,stats_cfg->camif_win_w, stats_cfg->camif_win_h, stats_cfg->stat_elem_w, stats_cfg->stat_elem_h, stats_cfg->num_stat_elem_rows, stats_cfg->num_stat_elem_cols);
        } else {
            printf("same cfg as current\n");
            return TINTLESS_SUCCESS;
        }
        break;

    case UPDATES_MESH_CONFIG:
        mesh_cfg = c.mesh;

        // check if the new cfg is valid
        if (mesh_cfg == NULL || mesh_cfg->subgrids == 0 ||
            mesh_cfg->subgrid_height == 0 || mesh_cfg->subgrid_width == 0 ||
            mesh_cfg->num_mesh_elem_rows == 0 || mesh_cfg->num_mesh_elem_cols == 0)
        {
            return TINTLESS_INVALID_STATS;
        }

        // check if the new cfg is different from current cfg
        if (cfg->mesh_subgrid_width     != mesh_cfg->subgrid_width ||
            cfg->mesh_subgrid_height    != mesh_cfg->subgrid_height ||
            cfg->num_mesh_elem_rows     != mesh_cfg->num_mesh_elem_rows ||
            cfg->num_mesh_elem_cols     != mesh_cfg->num_mesh_elem_cols ||
            cfg->mesh_offset_horizontal != mesh_cfg->offset_horizontal ||
            cfg->mesh_offset_vertical   != mesh_cfg->offset_vertical ||
            cfg->num_mesh_subgrids      != (uint32_t)mesh_cfg->subgrids)
        {
            cfg->mesh_subgrid_width     = mesh_cfg->subgrid_width;
            cfg->mesh_subgrid_height    = mesh_cfg->subgrid_height;
            cfg->num_mesh_elem_rows     = mesh_cfg->num_mesh_elem_rows;
            cfg->num_mesh_elem_cols     = mesh_cfg->num_mesh_elem_cols;
            cfg->mesh_offset_horizontal = mesh_cfg->offset_horizontal;
            cfg->mesh_offset_vertical   = mesh_cfg->offset_vertical;
            cfg->num_mesh_subgrids      = (uint32_t)mesh_cfg->subgrids;

            CDBG_ERROR("%s: cfg: %dx%d mesh, %dx%d subgrid, subgrid sz %dx%d\n", __func__,
                       mesh_cfg->num_mesh_elem_rows, mesh_cfg->num_mesh_elem_cols,
                       cfg->num_mesh_subgrids, cfg->num_mesh_subgrids,
                       mesh_cfg->subgrid_width, mesh_cfg->subgrid_height);
        } else {
            CDBG_ERROR("%s: same cfg as current", __func__);
            return TINTLESS_SUCCESS;
        }
        break;

    case UPDATES_CHROMATIX_PARAMS:
        chromatix_param = c.chromatix;

        if (chromatix_param == NULL)
            return TINTLESS_INVALID_STATS;

        // check if the new cfg is different from current cfg
        if (cfg->tint_correction_strength != chromatix_param->tint_correction_strength)
        {
            cfg->tint_correction_strength = chromatix_param->tint_correction_strength;
            CDBG_ERROR("%s: tint_correction_strength updated to %d", __func__, cfg->tint_correction_strength);
        } else {
            CDBG_ERROR("%s: same cfg as current", __func__);
            return TINTLESS_SUCCESS;
        }
        break;
    default:
        return TINTLESS_UPDATES_NOT_SUPPORTED;
        break;
    } // end switch

    // validate config struct. If complete, init tintless lib
    if (validate_config(tintless_lib, cfg))
        return translate_return_code(tintless_lib->init_func(&tintless_lib->dmlroc_res, cfg));
    else
        return TINTLESS_SUCCESS;


} /* isp_tintless_config */
int main(int argc, char **argv)
{
    if (1 == argc) {
        utlog(LOG_ERR, "No configuration file was specified\n\n");
        print_help(EXIT_FAILURE);
    }

    int c;
    int foreground = 0;
    char *config_file = "";

    while (1) {

        static struct option long_options[] = {
            {"help",       no_argument,       0, 'h'},
            {"version",    no_argument,       0, 'v'},
            {"config",     required_argument, 0, 'c'},
            {"foreground", no_argument,       0, 'f'},
            {0, 0, 0, 0}
        };

        // getopt_long stores the option index here.
        int option_index = 0;

        c = getopt_long(argc, argv, "hvfc:",
                long_options, &option_index);

        // Detect the end of the options.
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                print_help(EXIT_SUCCESS);
                break;

            case 'v':
                print_version(EXIT_SUCCESS);
                break;

            case 'c':
                config_file = optarg;
                break;

            case 'f':
                foreground = 1;
                break;

            case '?':
                // getopt_long already printed an error message.
                utlog(LOG_INFO, "\n");
                print_help(EXIT_FAILURE);
                break;

            default:
                break;
        }
    }

    pid_t pid;

    if (0 != (pid = pidfile_check(pidfile))) {
        utlog(LOG_ERR, "A instance of avm-motion-triggerd (%d) is already running\n",
                pid);
        exit(EXIT_FAILURE);
    }

    conf = get_config(config_file);
    validate_config(&conf);

    // Run as daemon if we should
    if (0 == foreground) {
        daemonize();
        utlog_mode(LOG_BACKGROUND);
        utlog_pri_mode(LOG_PRI_DISABLE);
    } else {
        utlog_mode(LOG_FOREGROUND);
        utlog_pri_mode(LOG_PRI_ENABLE);
    }

    // Write a pidfile for the current daemon process
    if (0 == pidfile_write(pidfile)) {
        exit(EXIT_FAILURE);
    }

    // Bind the signal handler
    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);

    // Initialize the sensors
    init_sensors(&conf);

    // Call the business logic loop
    detect_motions(&conf);

    return EXIT_SUCCESS;
}