Example #1
0
/* parse_cli_params */
int parse_module_args(int argc, char *argv[]) {
    int i = 0;

    /* Set default values */
    arg_options = (arg_options_t) {
        .prefix            = NULL,
        .before            = NULL,
        .after             = NULL,
        .mainsrc          = NULL,
    };

    if (((0 >= my_module_globals.threshold) || 
            (1 < my_module_globals.threshold))) {
        OUTPUT(("%s", _ERROR("invalid threshold")));
        return PERFEXPERT_ERROR;
    }

    /* If some environment variable is defined, use it! */
    if (PERFEXPERT_SUCCESS != parse_env_vars()) {
        OUTPUT(("%s", _ERROR("parsing environment variables")));
        return PERFEXPERT_ERROR;
    }

    /* Parse arguments */
    argp_parse(&argp, argc, argv, 0, 0, NULL);

    /* Expand AFTERs, BEFOREs, and PREFIXs arguments */
    // TODO: right now we only use the before, after and
    // prefix from globals. We should also consider values coming
    // throught args_options.* (that have been set in the previous
    // instruction
    if (NULL != arg_options.after) {
        perfexpert_string_split(perfexpert_string_remove_spaces(
            arg_options.after), my_module_globals.after, ' ');
    }
    if (NULL != arg_options.before) {
        perfexpert_string_split(perfexpert_string_remove_spaces(
            arg_options.before), my_module_globals.before, ' ');
    }
    if (NULL != arg_options.prefix) {
        perfexpert_string_split(perfexpert_string_remove_spaces(
            arg_options.prefix), my_module_globals.prefix, ' ');
    }
    if (NULL != arg_options.mainsrc) {
        my_module_globals.mainsrc = arg_options.mainsrc;
    }

    OUTPUT_VERBOSE((7, "%s", _BLUE("Summary of options")));

    if (7 <= globals.verbose) {
        printf("%s    Threshold:           %f", PROGRAM_PREFIX, my_module_globals.threshold); 
        printf("\n%s    Prefix:             ", PROGRAM_PREFIX);
        if (NULL == my_module_globals.prefix[0]) {
            printf(" (null)");
        } else {
            i = 0;
            while (NULL != my_module_globals.prefix[i]) {
                printf(" [%s]", (char *)my_module_globals.prefix[i]);
                i++;
            }
        }

        printf("\n%s    Before each run:    ", PROGRAM_PREFIX);
        if (NULL == my_module_globals.before[0]) {
            printf(" (null)");
        } else {
            i = 0;
            while (NULL != my_module_globals.before[i]) {
                printf(" [%s]", (char *)my_module_globals.before[i]);
                i++;
            }
        }

        printf("\n%s    After each run:     ", PROGRAM_PREFIX);
        if (NULL == my_module_globals.after[0]) {
            printf(" (null)");
        } else {
            i = 0;
            while (NULL != my_module_globals.after[i]) {
                printf(" [%s]", (char *)my_module_globals.after[i]);
                i++;
            }
        }

        printf("\n%s    Main src file:      ", PROGRAM_PREFIX);
        if (NULL == my_module_globals.mainsrc) {
            printf(" (null)");
        } else {
            printf(" [%s]", (char *)my_module_globals.mainsrc);
        }
        printf("\n");
        fflush(stdout);
    }

    /* Not using OUTPUT_VERBOSE because I want only one line */
    if (8 <= globals.verbose) {
        i = 0;
        printf("%s %s", PROGRAM_PREFIX, _YELLOW("options:"));
        for (i = 0; i < argc; i++) {
            printf(" [%s]", argv[i]);
        }
        printf("\n");
        fflush(stdout);
    }

    return PERFEXPERT_SUCCESS;
}
Example #2
0
int parse_args(int argc, char** argv, struct arguments* parguments) {
	return argp_parse(&argp, argc, argv, 0, 0, parguments);
}
Example #3
0
int main(int argc, char *argv[])
{
	int dev_from_class = 0, write_cnt;
	int fd;
	static struct sysfs_names *names;
	struct rc_device	  rc_dev;

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

	/* Just list all devices */
	if (!clear && !readtable && !keys.next && !ch_proto && !cfg.next && !test && !delay && !period) {
		if (devicename) {
			fd = open(devicename, O_RDONLY);
			if (fd < 0) {
				perror("Can't open device");
				return -1;
			}
			device_info(fd, "");
			close(fd);
			return 0;
		}
		if (show_sysfs_attribs(&rc_dev))
			return -1;

		return 0;
	}

	if (cfg.next && (clear || keys.next || ch_proto || devicename)) {
		fprintf (stderr, "Auto-mode can be used only with --read, --debug and --sysdev options\n");
		return -1;
	}
	if (!devicename) {
		names = find_device(devclass);
		if (!names)
			return -1;
		rc_dev.sysfs_name = names->name;
		if (get_attribs(&rc_dev, names->name)) {
			free_names(names);
			return -1;
		}
		names->name = NULL;
		free_names(names);

		devicename = rc_dev.input_name;
		dev_from_class++;
	}

	if (cfg.next) {
		struct cfgfile *cur;
		char *fname, *name;
		int rc;

		for (cur = &cfg; cur->next; cur = cur->next) {
			if ((!rc_dev.drv_name || strcasecmp(cur->driver, rc_dev.drv_name)) && strcasecmp(cur->driver, "*"))
				continue;
			if ((!rc_dev.keytable_name || strcasecmp(cur->table, rc_dev.keytable_name)) && strcasecmp(cur->table, "*"))
				continue;
			break;
		}

		if (!cur->next) {
			if (debug)
				fprintf(stderr, "Table for %s, %s not found. Keep as-is\n",
				       rc_dev.drv_name, rc_dev.keytable_name);
			return 0;
		}
		if (debug)
			fprintf(stderr, "Table for %s, %s is on %s file.\n",
				rc_dev.drv_name, rc_dev.keytable_name,
				cur->fname);
		if (cur->fname[0] == '/' || ((cur->fname[0] == '.') && strchr(cur->fname, '/'))) {
			fname = cur->fname;
			rc = parse_keyfile(fname, &name);
			if (rc < 0) {
				fprintf(stderr, "Can't load %s table\n", fname);
				return -1;
			}
		} else {
			fname = malloc(strlen(cur->fname) + strlen(IR_KEYTABLE_USER_DIR) + 2);
			strcpy(fname, IR_KEYTABLE_USER_DIR);
			strcat(fname, "/");
			strcat(fname, cur->fname);
			rc = parse_keyfile(fname, &name);
			if (rc != 0) {
				fname = malloc(strlen(cur->fname) + strlen(IR_KEYTABLE_SYSTEM_DIR) + 2);
				strcpy(fname, IR_KEYTABLE_SYSTEM_DIR);
				strcat(fname, "/");
				strcat(fname, cur->fname);
				rc = parse_keyfile(fname, &name);
			}
			if (rc != 0) {
				fprintf(stderr, "Can't load %s table from %s or %s\n", cur->fname, IR_KEYTABLE_USER_DIR, IR_KEYTABLE_SYSTEM_DIR);
				return -1;
			}
		}
		if (!keys.next) {
			fprintf(stderr, "Empty table %s\n", fname);
			return -1;
		}
		clear = 1;
	}

	if (debug)
		fprintf(stderr, "Opening %s\n", devicename);
	fd = open(devicename, O_RDONLY);
	if (fd < 0) {
		perror(devicename);
		return -1;
	}
	if (dev_from_class)
		free(devicename);
	if (get_input_protocol_version(fd))
		return -1;

	/*
	 * First step: clear, if --clear is specified
	 */
	if (clear) {
		clear_table(fd);
		fprintf(stderr, "Old keytable cleared\n");
	}

	/*
	 * Second step: stores key tables from file or from commandline
	 */
	write_cnt = add_keys(fd);
	if (write_cnt)
		fprintf(stderr, "Wrote %d keycode(s) to driver\n", write_cnt);

	/*
	 * Third step: change protocol
	 */
	if (ch_proto) {
		rc_dev.current = ch_proto;
		if (set_proto(&rc_dev))
			fprintf(stderr, "Couldn't change the IR protocols\n");
		else {
			fprintf(stderr, "Protocols changed to ");
			show_proto(rc_dev.current);
			fprintf(stderr, "\n");
		}
	}

	/*
	 * Fourth step: display current keytable
	 */
	if (readtable)
		display_table(&rc_dev, fd);

	/*
	 * Fiveth step: change repeat rate/delay
	 */
	if (delay || period) {
		unsigned int new_delay, new_period;
		get_rate(fd, &new_delay, &new_period);
		if (delay)
			new_delay = delay;
		if (period)
			new_period = period;
		set_rate(fd, new_delay, new_period);
	}

	if (test)
		test_event(fd);

	return 0;
}
Example #4
0
int main(int argc, char **argv)
{
	struct arguments args;
	int lnb = -1,idx = -1;
	const struct argp argp = {
		.options = options,
		.parser = parse_opt,
		.doc = "scan DVB services using the channel file",
		.args_doc = "<initial file>",
	};

	memset(&args, 0, sizeof(args));
	args.sat_number = -1;
	args.output = DEFAULT_OUTPUT;
	args.input_format = FILE_DVBV5;
	args.output_format = FILE_DVBV5;
	args.timeout_multiply = 1;

	argp_parse(&argp, argc, argv, 0, &idx, &args);
	if (args.timeout_multiply == 0)
		args.timeout_multiply = 1;

	if (args.lnb_name) {
		lnb = dvb_sat_search_lnb(args.lnb_name);
		if (lnb < 0) {
			printf("Please select one of the LNBf's below:\n");
			print_all_lnb();
			exit(1);
		} else {
			printf("Using LNBf ");
			print_lnb(lnb);
		}
	}

	if (idx < argc)
		args.confname = argv[idx];

	if (!args.confname || idx < 0) {
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}
	if ((args.input_format == FILE_ZAP) ||
		   (args.input_format == FILE_UNKNOWN) ||
		   (args.output_format == FILE_UNKNOWN)) {
		fprintf(stderr, "ERROR: Please specify a valid format\n");
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	asprintf(&args.demux_dev,
		 "/dev/dvb/adapter%i/demux%i", args.adapter, args.demux);

	if (verbose)
		fprintf(stderr, "using demux '%s'\n", args.demux_dev);

	struct dvb_v5_fe_parms *parms = dvb_fe_open(args.adapter,
						    args.frontend,
						    verbose, args.force_dvbv3);
	if (!parms)
		return -1;
	if (lnb >= 0)
		parms->lnb = dvb_sat_get_lnb(lnb);
	if (args.sat_number >= 0)
		parms->sat_number = args.sat_number % 3;
	parms->diseqc_wait = args.diseqc_wait;
	parms->freq_bpf = args.freq_bpf;

	if (run_scan(&args, parms))
		return -1;

	dvb_fe_close(parms);

	free(args.demux_dev);

	return 0;
}
int main(int argc, char *argv[])
{
  int i, j, entriesPrinted, totalPrinted, remainingCount;
  int rc;
  char client_name[] = "ofdpa flowtable_dump client";
  char docBuffer[1000];
  char argsDocBuffer[300];

  /* Our argp parser. */
  struct argp argp =
  {
    .args_doc = argsDocBuffer,
    .doc      = docBuffer,
    .options  = options,
    .parser   = parse_opt,
  };

  count = DEFAULT_COUNT;

  strcpy(argsDocBuffer, "[table_ID]");

  strcpy(docBuffer, "Prints entries in the OF-DPA flow tables. Specify table ID to print content of a single table. "
         "If no argument given, content of all tables are printed.\vDefault values:\n");
  i = strlen(docBuffer);
  i += sprintf(&docBuffer[i], "COUNT     = %d\n", DEFAULT_COUNT);
  i += sprintf(&docBuffer[i], "\n");

  rc = ofdpaClientInitialize(client_name);
  if (rc != OFDPA_E_NONE)
  {
    return rc;
  }

  /* Parse our arguments; every option seen by `parse_opt' will be reflected in
     `arguments'. */
  argp_parse(&argp, argc, argv, 0, 0, 0);

  if (showValidTableIds)
  {
    printf("Valid flow table IDs:\r\n");
    for (j = 0; j < 256; j++)
    {
      if (ofdpaFlowTableSupported(j) == OFDPA_E_NONE)
      {
        printf("  %d - %s\r\n", j, ofdpaFlowTableNameGet(j));
      }
    }
    printf("\r\n");
    return 0;
  }

  totalPrinted = 0;

  if (tableIdSpecified)
  {
    dumpFlowTable(tableId, count, &totalPrinted);
  }
  else
  {
    remainingCount = count;

    for (j = 0; j < 256; j++)
    {
      if (ofdpaFlowTableSupported(j) == OFDPA_E_NONE)
      {
        entriesPrinted = 0;

        dumpFlowTable(j, remainingCount, &entriesPrinted);

        totalPrinted += entriesPrinted;

        if (count != 0)
        {
          if (remainingCount > entriesPrinted)
          {
            remainingCount -= entriesPrinted;
          }
          else
          {
            /* printed the requested number of total entries */
            break;
          }
        }
      }
    }
  }

  /* 
   * if not printing empty table stats and no flow entries found, we haven't printed anything at all
   * so print a message letting the user know we are responsive
   */
  if ((showEmptyTables == 0) && (totalPrinted == 0))
  {
    printf("No flow entries found.\r\n");
  }
  return 0;
}
Example #6
0
int
main(int argc, char *argv[])
{
  error_t err;

  /* The filesystem node we're putting a translator on.  */
  char *node_name = 0;
  file_t node;

  /* The translator's arg vector, in '\0' separated format.  */
  char *argz = 0;
  size_t argz_len = 0;

  /* The control port for any active translator we start up.  */
  fsys_t active_control = MACH_PORT_NULL;

  /* Flags to pass to file_set_translator.  */
  int active_flags = 0;
  int passive_flags = 0;
  int lookup_flags = O_NOTRANS;
  int goaway_flags = 0;

  /* Various option flags.  */
  int passive = 0, active = 0, keep_active = 0, pause = 0, kill_active = 0,
      orphan = 0;
  int start = 0;
  int stack = 0;
  char *pid_file = NULL;
  int excl = 0;
  int timeout = DEFAULT_TIMEOUT * 1000; /* ms */
  char *underlying_node_name = NULL;
  int underlying_lookup_flags;
  char **chroot_command = 0;
  char *chroot_chdir = "/";

  /* Parse our options...  */
  error_t parse_opt (int key, char *arg, struct argp_state *state)
    {
      switch (key)
	{
	case ARGP_KEY_ARG:
	  if (state->arg_num == 0)
	    node_name = arg;
	  else			/* command */
	    {
	      if (start)
		argp_error (state, "both --start and TRANSLATOR given");

	      error_t err =
		argz_create (state->argv + state->next - 1, &argz, &argz_len);
	      if (err)
		error(3, err, "Can't create options vector");
	      state->next = state->argc; /* stop parsing */
	    }
	  break;

	case ARGP_KEY_NO_ARGS:
	  argp_usage (state);
	  return EINVAL;

	case 'a': active = 1; break;
	case 's':
	  start = 1;
	  active = 1;	/* start implies active */
	  break;
	case OPT_STACK:
	  stack = 1;
	  active = 1;	/* stack implies active */
	  orphan = 1;	/* stack implies orphan */
	  break;
	case 'p': passive = 1; break;
	case 'k': keep_active = 1; break;
	case 'g': kill_active = 1; break;
	case 'x': excl = 1; break;
	case 'P': pause = 1; break;
	case 'F':
	  pid_file = strdup (arg);
	  if (pid_file == NULL)
	    error(3, ENOMEM, "Failed to duplicate argument");
	  break;

	case 'o': orphan = 1; break;
	case 'U':
	  underlying_node_name = strdup (arg);
	  if (underlying_node_name == NULL)
	    error(3, ENOMEM, "Failed to duplicate argument");
	  break;

	case 'C':
	  if (chroot_command)
	    {
	      argp_error (state, "--chroot given twice");
	      return EINVAL;
	    }
	  chroot_command = &state->argv[state->next];
	  while (state->next < state->argc)
	    {
	      if (!strcmp (state->argv[state->next], "--"))
		{
		  state->argv[state->next++] = 0;
		  if (chroot_command[0] == 0)
		    {
		      argp_error (state,
				  "--chroot must be followed by a command");
		      return EINVAL;
		    }
		  return 0;
		}
	      ++state->next;
	    }
	  argp_error (state, "--chroot command must be terminated with `--'");
	  return EINVAL;

	case OPT_CHROOT_CHDIR:
	  if (arg[0] != '/')
	    argp_error (state, "--chroot-chdir must be absolute");
	  chroot_chdir = arg;
	  break;

	case 'c': lookup_flags |= O_CREAT; break;
	case 'L': lookup_flags &= ~O_NOTRANS; break;

	case 'R': goaway_flags |= FSYS_GOAWAY_RECURSE; break;
	case 'S': goaway_flags |= FSYS_GOAWAY_NOSYNC; break;
	case 'f': goaway_flags |= FSYS_GOAWAY_FORCE; break;

	  /* Use atof so the user can specifiy fractional timeouts.  */
	case 't': timeout = atof (arg) * 1000.0; break;

	default:
	  return ARGP_ERR_UNKNOWN;
	}
      return 0;
    }
  struct argp argp = {options, parse_opt, args_doc, doc};

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

  if (stack)
    {
      underlying_node_name = node_name;
      underlying_lookup_flags = lookup_flags && ~O_NOTRANS;
    }
  else
    underlying_lookup_flags = lookup_flags;

  if (!active && !passive && !chroot_command)
    passive = 1;		/* By default, set the passive translator.  */

  if (passive)
    passive_flags = FS_TRANS_SET | (excl ? FS_TRANS_EXCL : 0);
  if (active)
    active_flags = FS_TRANS_SET | (excl ? FS_TRANS_EXCL : 0)
		   | (orphan ? FS_TRANS_ORPHAN : 0);

  if (passive && !active)
    {
      /* When setting just the passive, decide what to do with any active.  */
      if (kill_active)
	/* Make it go away.  */
	active_flags = FS_TRANS_SET;
      else if (! keep_active)
	/* Ensure that there isn't one.  */
	active_flags = FS_TRANS_SET | FS_TRANS_EXCL;
    }

  if (start)
    {
      /* Retrieve the passive translator record in argz.  */
      mach_port_t node = file_name_lookup (node_name, lookup_flags, 0);
      if (node == MACH_PORT_NULL)
	error (4, errno, "%s", node_name);

      char buf[1024];
      argz = buf;
      argz_len = sizeof (buf);

      err = file_get_translator (node, &argz, &argz_len);
      if (err == EINVAL)
	error (4, 0, "%s: no passive translator record found", node_name);
      if (err)
	error (4, err, "%s", node_name);

      mach_port_deallocate (mach_task_self (), node);
    }

  if ((active || chroot_command) && argz_len > 0)
    {
      /* Error during file lookup; we use this to avoid duplicating error
	 messages.  */
      error_t open_err = 0;

      /* The callback to start_translator opens NODE as a side effect.  */
      error_t open_node (int flags,
			 mach_port_t *underlying,
			 mach_msg_type_name_t *underlying_type,
			 task_t task, void *cookie)
	{
	  if (pause)
	    {
	      fprintf (stderr, "Translator pid: %d\nPausing...",
	               task2pid (task));
	      getchar ();
	    }

	  if (pid_file != NULL)
	    {
	      FILE *h;
	      h = fopen (pid_file, "w");
	      if (h == NULL)
		error (4, errno, "Failed to open pid file");

	      fprintf (h, "%i\n", task2pid (task));
	      fclose (h);
	    }

	  node = file_name_lookup (node_name, flags | lookup_flags, 0666);
	  if (node == MACH_PORT_NULL)
	    {
	      open_err = errno;
	      return open_err;
	    }

	  if (underlying_node_name)
	    {
	      *underlying = file_name_lookup (underlying_node_name,
					      flags | underlying_lookup_flags,
					      0666);
	      if (! MACH_PORT_VALID (*underlying))
		{
		  /* For the error message.  */
		  node_name = underlying_node_name;
		  open_err = errno;
		  return open_err;
		}
	    }
	  else
	    *underlying = node;
	  *underlying_type = MACH_MSG_TYPE_COPY_SEND;

	  return 0;
	}
      err = fshelp_start_translator (open_node, NULL, argz, argz, argz_len,
				     timeout, &active_control);
      if (err)
	/* If ERR is due to a problem opening the translated node, we print
	   that name, otherwise, the name of the translator.  */
	error(4, err, "%s", (err == open_err) ? node_name : argz);
    }
Example #7
0
int main(int argc, char **argv)
{
    struct arguments arguments;

    // Default values
    arguments.cmd = NULL;
    arguments.cmdargs[0] = NULL;
    arguments.cmdargs[1] = NULL;
    arguments.cmdargs[2] = NULL;
    arguments.bit_num = -1;

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

    // printf("cmd = %s\ncmdargs[0] = %s\ncmdargs[1] = %s\n"
    //        "cmdargs[2] = %s\nbit_num = %d\n",
    //        arguments.cmd,
    //        arguments.cmdargs[0],
    //        arguments.cmdargs[1],
    //        arguments.cmdargs[2],
    //        arguments.bit_num);

    if (arguments.bit_num > 7) {
        fprintf(stderr, "pifacecad: bit num must in range 0-7.\n");
        exit(1);
    }

    pifacecad_open_noinit();

    if (strcmp(arguments.cmd, "open") == 0) {
        pifacecad_open();
        int i;
        for (i = 0; i <= 2; i++) {
            if (arguments.cmdargs[i] == NULL) {
                continue;
            }
            if (strcmp(arguments.cmdargs[i], "displayoff") == 0) {
                pifacecad_lcd_display_off();
            }
            if (strcmp(arguments.cmdargs[i], "blinkoff") == 0) {
                pifacecad_lcd_blink_off();
            }
            if (strcmp(arguments.cmdargs[i], "cursoroff") == 0) {
                pifacecad_lcd_cursor_off();
            }
        }

    } else if (strcmp(arguments.cmd, "read") == 0) {
        pfc_read_switch(arguments.bit_num, str2reg(arguments.cmdargs[0]));

    } else if (strcmp(arguments.cmd, "write") == 0) {
        pifacecad_lcd_write(arguments.cmdargs[0]);

    } else if (strcmp(arguments.cmd, "backlight") == 0) {
        if (strcmp(arguments.cmdargs[0], "on") == 0) {
            pifacecad_lcd_backlight_on();
        } else {
            pifacecad_lcd_backlight_off();
        }

    } else if (strcmp(arguments.cmd, "home") == 0) {
        pifacecad_lcd_home();

    } else if (strcmp(arguments.cmd, "clear") == 0) {
        pifacecad_lcd_clear();

    } else if (strcmp(arguments.cmd, "setcursor") == 0) {
        const uint8_t col = atoi(arguments.cmdargs[0]);
        const uint8_t row = atoi(arguments.cmdargs[1]);
        pifacecad_lcd_set_cursor(col, row);
    }

    pifacecad_close();

    exit(0);
}
Example #8
0
int main (int argc, char **argv)
{
    struct arguments arguments;

    /* Default values. */
    arguments.verbose = 0;
    arguments.grd = 0;
    arguments.region = NULL;
    arguments.type = NULL;
    static const int NUM_DAYS = 365;

    /* Parse our arguments; every option seen by parse_opt will
     be reflected in arguments. */
    argp_parse (&argp, argc, argv, 0, 0, &arguments);

    /* Set up variables */
    int num_columns;
    int num_rows;
    char* region = arguments.region;
    char* type = arguments.type;
    int grd = arguments.grd;
    int i,j,k;

    /* Initialize NETCDF Variables */
    int ncid, row_dimid, col_dimid;
    int varid, wet_varid, dry_varid, slope_varid;
    int retval;
    char FILE_NAME[100];
    int dimids[NDIMS];

    /* multithread args */
    thread_args t_args[NUM_THREADS];
    pthread_t thread_id[NUM_THREADS];
    int ind_per_thread;
    int start_index;
    int stop_index;

    printf ("GEN_C0\n---------------\nBeginning processing with options:\n");

    printf ("Region = %s\nVERBOSE = %s\nTYPE = %s\n---------------\n",
      arguments.region,
      arguments.verbose ? "yes" : "no",
      arguments.type);

    /* define image areas based on region */
    if (!grd) {
        if (strcmp(region,"Ama") == 0) {
            num_columns = 1128;
            num_rows = 744;
        } else if (strcmp(region,"Ber") == 0) {
            num_columns = 1350;
            num_rows = 750;
        } else if (strcmp(region,"CAm") == 0) {
              num_columns = 1440;
              num_rows = 700;
        } else if (strcmp(region,"ChJ") == 0) {
              num_columns = 1980;
              num_rows = 950;
        } else if (strcmp(region,"Eur") == 0) {
              num_columns = 1530;
              num_rows = 1040;
        } else if (strcmp(region,"Ind") == 0) {
              num_columns = 1800;
              num_rows = 680;
        } else if (strcmp(region,"NAf") == 0) {
              num_columns = 2120;
              num_rows = 1130;
        } else if (strcmp(region,"NAm") == 0) {
              num_columns = 1890;
              num_rows = 1150;
        } else if (strcmp(region,"SAf") == 0) {
              num_columns = 1220;
              num_rows = 1260;
        } else if (strcmp(region,"SAm") == 0) {
              num_columns = 1310;
              num_rows = 1850;
        }  else if (strcmp(region,"SAs") == 0) {
              num_columns = 1760;
              num_rows = 720;
        } else {
            printf("ERROR SETTING REGION SIZES!");
            exit(-1);
        }
    } else {
        if (strcmp(region,"NAm") == 0) {
            num_columns = 672;
            num_rows = 410;
        } else {
            printf("ERROR SETTING REGION SIZES!");
            exit(-1);
        }
    }

    /* allocate memory for 2d arrays */
    printf("Allocating Memory...");
    float **c0_dry = (float**)malloc(sizeof(float *)*num_rows);
    float **c0_wet = (float**)malloc(sizeof(float *)*num_rows);
    float **dry_slope = (float**)malloc(sizeof(float *)*num_rows);
    c0_dry[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    c0_wet[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    dry_slope[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    for (i = 1; i < num_rows; i++) {
        c0_dry[i] = c0_dry[0] + i * num_columns;
        c0_wet[i] = c0_wet[0] + i * num_columns;
        dry_slope[i] = dry_slope[0] + i * num_columns;
    }
    memset(c0_dry[0],0,num_rows*num_columns*sizeof(float));
    memset(c0_wet[0],0,num_rows*num_columns*sizeof(float));
    memset(dry_slope[0],0,num_rows*num_columns*sizeof(float));

    /* allocate memory for NetCDF File */
    float ****row_ptr = (float****)malloc(sizeof(float ***)*num_rows);
    float ***column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns);
    float **year_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_YEARS);
    float *day_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS);
    float ****tseries = row_ptr;

    for (i = 0; i < num_rows; i++, column_ptr += num_columns) {
        tseries[i] = column_ptr;
        for (j = 0; j < num_columns; j++, year_ptr += NUM_YEARS) {
            tseries[i][j] = year_ptr;
            for (k = 0; k < NUM_YEARS; k++, day_ptr += NUM_DAYS) {
                tseries[i][j][k] = day_ptr;
            }
        }
    }

    row_ptr = (float****)malloc(sizeof(float ***)*num_rows);
    column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns);
    year_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_YEARS);
    day_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS);
    float ****tseriesb = row_ptr;

    for (i = 0; i < num_rows; i++, column_ptr += num_columns) {
        tseriesb[i] = column_ptr;
        for (j = 0; j < num_columns; j++, year_ptr += NUM_YEARS) {
            tseriesb[i][j] = year_ptr;
            for (k = 0; k < NUM_YEARS; k++, day_ptr += NUM_DAYS) {
                tseriesb[i][j][k] = day_ptr;
            }
        }
    }

    printf("done\n");

    setvbuf (stdout, NULL, _IONBF, 0);
    printf("Reading NetCDF Files...");
    /* Open the netCDF time series a file*/
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/ts/ts_%s_%s.nc",region,"a");
    if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
        ERR(retval);

    /* Get the varid of the data variable, based on its name. */
    if ((retval = nc_inq_varid(ncid, "data", &varid)))
        ERR(retval);

    /* read values from netCDF variable */
    if ((retval = nc_get_var_float(ncid, varid, &tseries[0][0][0][0])))
       ERR(retval);

    /* Open the netCDF time series b file*/
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/ts/ts_%s_%s.nc",region,"b");
    if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
        ERR(retval);

    /* Get the varid of the data variable, based on its name. */
    if ((retval = nc_inq_varid(ncid, "data", &varid)))
        ERR(retval);

    /* read values from netCDF variable */
    if ((retval = nc_get_var_float(ncid, varid, &tseriesb[0][0][0][0])))
       ERR(retval);

    printf("done\n");

    /* get threads ready */
    /* split up column processing based on number of threads/rows */
    ind_per_thread = num_rows / NUM_THREADS - 1;
    start_index = 0;
    stop_index = 0;
    for (i = 0; i < NUM_THREADS; i++) {
        if (i == NUM_THREADS - 1) {
            stop_index = num_rows-1;
        } else {
            stop_index = start_index + ind_per_thread;
        }
        t_args[i].tseries = tseries;
        t_args[i].tseriesb = tseriesb;
        t_args[i].c0_wet = c0_wet;
        t_args[i].c0_dry = c0_dry;
        t_args[i].dry_slope = dry_slope;
        t_args[i].start_i = start_index;
        t_args[i].stop_i = stop_index;
        t_args[i].num_columns = num_columns;
        t_args[i].region = region;
        t_args[i].type = type;
        start_index = stop_index + 1;
    }

    /* call multithreaded function */
    /* submit threads */
    printf("Starting Processing\n");
    for (i = 0; i < NUM_THREADS; i++) {
        pthread_create(&thread_id[i], NULL, mthreadGenC0, &t_args[i]);
    }

    /* join threads */
    for (i = 0; i < NUM_THREADS; i++) {
        pthread_join(thread_id[i], NULL);
    }

    /* save min/max 2d arrays to netcdf file */
    /* Create the file. */
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/c0/c0_%s.nc",region);
    if ((retval = nc_create(FILE_NAME, NC_NETCDF4, &ncid)))
        ERR(retval);

    /* Define the dimensions. */
    if ((retval = nc_def_dim(ncid, "row", num_rows, &row_dimid)))
        ERR(retval);
    if ((retval = nc_def_dim(ncid, "column", num_columns, &col_dimid)))
        ERR(retval);

    /* Define the netCDF variables. The dimids array is used to pass
        the dimids of the dimensions of the variables.*/
    dimids[0] = row_dimid;
    dimids[1] = col_dimid;

    /* define the variable */
    if ((retval = nc_def_var(ncid, "dry", NC_FLOAT, NDIMS, dimids, &dry_varid)))
        ERR(retval);

    if ((retval = nc_def_var(ncid, "wet", NC_FLOAT, NDIMS, dimids, &wet_varid)))
        ERR(retval);

    if ((retval = nc_def_var(ncid, "dry_slope", NC_FLOAT, NDIMS, dimids, &slope_varid)))
        ERR(retval);

    /* End define mode. */
    if ((retval = nc_enddef(ncid)))
        ERR(retval);

    /* Write the data. */
    if ((retval = nc_put_var_float(ncid, dry_varid, &c0_dry[0][0])))
        ERR(retval);
    if ((retval = nc_put_var_float(ncid, wet_varid, &c0_wet[0][0])))
        ERR(retval);
    if ((retval = nc_put_var_float(ncid, slope_varid, &dry_slope[0][0])))
        ERR(retval);

    /* Close the file. */
    if ((retval = nc_close(ncid)))
        ERR(retval);

    /* Free memory for 3D image timeseries array */
    printf("Finishing up...");
    free(tseries[0][0][0]);
    free(tseries[0][0]);
    free(tseries[0]);
    free(tseries);

    free(c0_wet[0]);
    free(c0_dry[0]);
    free(dry_slope[0]);
    free(c0_wet);
    free(c0_dry);
    free(dry_slope);

    printf("done\n");

    exit (0);
}
Example #9
0
int
main (int argc, char **argv)
{
  argp_parse (0, argc, argv, 0, 0, 0);
  exit (0);
}
Example #10
0
File: main.c Project: Larhard/hurd
int
main (int argc, char **argv, char **envp)
{
  mach_port_t boot;
  error_t err;
  void *genport;
  process_t startup_port;
  mach_port_t startup;
  struct argp argp = { 0, 0, 0, "Hurd process server" };

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

  initialize_version_info ();

  err = task_get_bootstrap_port (mach_task_self (), &boot);
  assert_perror (err);
  if (boot == MACH_PORT_NULL)
    error (2, 0, "proc server can only be run by init during boot");

  proc_bucket = ports_create_bucket ();
  proc_class = ports_create_class (0, 0);
  generic_port_class = ports_create_class (0, 0);
  exc_class = ports_create_class (exc_clean, 0);
  ports_create_port (generic_port_class, proc_bucket,
		     sizeof (struct port_info), &genport);
  generic_port = ports_get_right (genport);

  /* Create the initial proc object for init (PID 1).  */
  init_proc = create_init_proc ();

  /* Create the startup proc object for /hurd/init (PID 2).  */
  startup_proc = allocate_proc (MACH_PORT_NULL);
  startup_proc->p_deadmsg = 1;
  complete_proc (startup_proc, HURD_PID_STARTUP);

  /* Create our own proc object.  */
  self_proc = allocate_proc (mach_task_self ());
  assert (self_proc);

  complete_proc (self_proc, HURD_PID_PROC);

  startup_port = ports_get_send_right (startup_proc);
  err = startup_procinit (boot, startup_port, &startup_proc->p_task,
			  &authserver, &_hurd_host_priv, &_hurd_device_master);
  assert_perror (err);
  mach_port_deallocate (mach_task_self (), startup_port);

  mach_port_mod_refs (mach_task_self (), authserver, MACH_PORT_RIGHT_SEND, 1);
  _hurd_port_set (&_hurd_ports[INIT_PORT_AUTH], authserver);
  mach_port_deallocate (mach_task_self (), boot);

  proc_death_notify (startup_proc);
  add_proc_to_hash (startup_proc); /* Now that we have the task port.  */

  /* Set our own argv and envp locations.  */
  self_proc->p_argv = (vm_address_t) argv;
  self_proc->p_envp = (vm_address_t) envp;

  /* Give ourselves good scheduling performance, because we are so
     important. */
  err = increase_priority ();
  if (err)
    error (0, err, "Increasing priority failed");

#if 0
  err = register_new_task_notification (_hurd_host_priv,
					generic_port,
					MACH_MSG_TYPE_MAKE_SEND);
  if (err)
    error (0, err, "Registering task notifications failed");
#endif

  {
    /* Get our stderr set up to print on the console, in case we have
       to panic or something.  */
    mach_port_t cons;
    error_t err;
    err = device_open (_hurd_device_master, D_READ|D_WRITE, "console", &cons);
    assert_perror (err);
    stdin = mach_open_devstream (cons, "r");
    stdout = stderr = mach_open_devstream (cons, "w");
    mach_port_deallocate (mach_task_self (), cons);
  }

  startup = file_name_lookup (_SERVERS_STARTUP, 0, 0);
  if (MACH_PORT_VALID (startup))
    {
      err = startup_essential_task (startup, mach_task_self (),
				    MACH_PORT_NULL, "proc", _hurd_host_priv);
      if (err)
	/* Due to the single-threaded nature of /hurd/startup, it can
	   only handle requests once the core server bootstrap has
	   completed.  Therefore, it does not bind itself to
	   /servers/startup until it is ready.	*/
	/* Fall back to abusing the message port lookup.  */
	startup_fallback = 1;

      err = mach_port_deallocate (mach_task_self (), startup);
      assert_perror (err);
    }
  else
    /* Fall back to abusing the message port lookup.	*/
    startup_fallback = 1;

  while (1)
    ports_manage_port_operations_multithread (proc_bucket,
					      message_demuxer,
					      0, 0, 0);
}
Example #11
0
int main (int argc, char *argv[])
{
#ifdef HAVE_ICONV
	char *locale_charset;
#endif
	int status = OK;

	program_name = base_name (argv[0]);
	if (STREQ (program_name, APROPOS_NAME)) {
		am_apropos = 1;
		argp_program_version = "apropos " PACKAGE_VERSION;
	} else {
		struct argp_option *optionp;
		am_apropos = 0;
		argp_program_version = "whatis " PACKAGE_VERSION;
		for (optionp = (struct argp_option *) whatis_argp.options;
		     optionp->name || optionp->key || optionp->arg ||
		     optionp->flags || optionp->doc || optionp->group;
		     ++optionp) {
			if (!optionp->name)
				continue;
			if (STREQ (optionp->name, "exact") ||
			    STREQ (optionp->name, "and"))
				optionp->flags |= OPTION_HIDDEN;
		}
	}

	init_debug ();
	pipeline_install_post_fork (pop_all_cleanups);
	init_locale ();

	internal_locale = setlocale (LC_MESSAGES, NULL);
	/* Use LANGUAGE only when LC_MESSAGES locale category is
	 * neither "C" nor "POSIX". */
	if (internal_locale && strcmp (internal_locale, "C") &&
	    strcmp (internal_locale, "POSIX"))
		multiple_locale = getenv ("LANGUAGE");
	internal_locale = xstrdup (internal_locale ? internal_locale : "C");

	if (argp_parse (am_apropos ? &apropos_argp : &whatis_argp, argc, argv,
			0, 0, 0))
		exit (FAIL);

	read_config_file (user_config_file != NULL);

	/* close this locale and reinitialise if a new locale was 
	   issued as an argument or in $MANOPT */
	if (locale) {
		free (internal_locale);
		internal_locale = setlocale (LC_ALL, locale);
		if (internal_locale)
			internal_locale = xstrdup (internal_locale);
		else
			internal_locale = xstrdup (locale);

		debug ("main(): locale = %s, internal_locale = %s\n",
		       locale, internal_locale);
		if (internal_locale) {
			setenv ("LANGUAGE", internal_locale, 1);
			locale_changed ();
			multiple_locale = NULL;
		}
	}

	/* sort out the internal manpath */
	if (manp == NULL)
		manp = locale_manpath (get_manpath (alt_systems));
	else
		free (get_manpath (NULL));

	create_pathlist (manp, manpathlist);

	display_seen = hashtable_create (&null_hashtable_free);

#ifdef HAVE_ICONV
	locale_charset = xasprintf ("%s//IGNORE", get_locale_charset ());
	conv_to_locale = iconv_open (locale_charset, "UTF-8");
	free (locale_charset);
#endif /* HAVE_ICONV */

	if (regex_opt) {
		int i;
		preg = XNMALLOC (num_keywords, regex_t);
		for (i = 0; i < num_keywords; ++i)
			xregcomp (&preg[i], keywords[i],
				  REG_EXTENDED | REG_NOSUB | REG_ICASE);
	}

	if (!search ((const char **) keywords, num_keywords))
		status = NOT_FOUND;

	if (regex_opt) {
		int i;
		for (i = 0; i < num_keywords; ++i)
			regfree (&preg[i]);
		free (preg);
	}

#ifdef HAVE_ICONV
	if (conv_to_locale != (iconv_t) -1)
		iconv_close (conv_to_locale);
#endif /* HAVE_ICONV */
	hashtable_free (display_seen);
	free_pathlist (manpathlist);
	free (manp);
	free (internal_locale);
	free (program_name);
	exit (status);
}
Example #12
0
int main(int argc, char *argv[])
{
	char errbuf[PCAP_ERRBUF_SIZE];
	char *dev;
	struct iface_config *ifc;
	int optind;
	int i;


	bzero(&cfg, sizeof(cfg));

	/* Default configuration */
//	cfg.ratelimit = 0;
	cfg.hashsize = 1;
//	cfg.quiet = 0;
	cfg.promisc_flag = 1;
//	cfg.ratelimit = 0;
//	cfg.sqlite_file = NULL;
//	cfg.uname = NULL;
	cfg.shm_data.size = DEFAULT_SHM_LOG_SIZE;
	cfg.shm_data.name = DEFAULT_SHM_LOG_NAME;
#if HAVE_LIBSQLITE3
	cfg.sqlite_table = PACKAGE;
#endif
	log_open(PACKAGE_NAME);
	argp_parse(&argp, argc, argv, 0, &optind, 0);

	if (!cfg.hostname) {
		cfg.hostname_len = sysconf(_SC_HOST_NAME_MAX);
		cfg.hostname = (char *)calloc(cfg.hostname_len, sizeof(char));
		gethostname(cfg.hostname, cfg.hostname_len);
	}

	daemonize();
	save_pid();

	libevent_init();


	if (cfg.ratelimit > 0)
		log_msg(LOG_DEBUG, "Ratelimiting duplicate entries to 1 per %d seconds", cfg.ratelimit);
	else if (cfg.ratelimit == -1)
		log_msg(LOG_DEBUG, "Duplicate entries supressed indefinitely");
	else
		log_msg(LOG_DEBUG, "Duplicate entries ratelimiting disabled");

	if (cfg.promisc_flag)
		log_msg(LOG_DEBUG, "PROMISC mode enabled");
	else
		log_msg(LOG_DEBUG, "PROMISC mode disabled");

	if (argc > optind) {
		for (i = optind; i < argc; i++)
			add_iface(argv[i]);
	} else {
		dev = pcap_lookupdev(errbuf);
		if (dev != NULL)
			add_iface(dev);
	}

	if (!cfg.interfaces)
		log_msg(LOG_ERR, "No suitable interfaces found!");

	if (cfg.uname)
		drop_root(cfg.uname);

	output_flatfile_init();
	output_sqlite_init();
	output_shm_init();

	/* main loop */
#if HAVE_LIBEVENT2
	event_base_dispatch(cfg.eb);
#else
	event_dispatch();
#endif

	output_shm_close();
	output_sqlite_close();
	output_flatfile_close();

	for (ifc = cfg.interfaces; ifc != NULL; ifc = del_iface(ifc));


	libevent_close();
	log_close();

	del_pid();
	blacklist_free();

	free(cfg.hostname);

	return 0;
}
Example #13
0
int
main (int argc, char *argv[])
{
  int fd;
  int remaining;
  int must_swap;
  uint32_t word;

  /* Parse and process arguments.  */
  argp_parse (&argp, argc, argv, 0, &remaining, NULL);

  if (remaining == argc)
    fd = STDIN_FILENO;
  else if (remaining + 1 != argc)
    {
      argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
		 program_invocation_short_name);
      exit (1);
    }
  else
    {
      /* Open the given file.  */
      fd = open (argv[remaining], O_RDONLY);

      if (fd == -1)
	error (EXIT_FAILURE, errno, _("cannot open input file"));
    }

  /* Read the first 4-byte word.  It contains the information about
     the word size and the endianess.  */
  if (TEMP_FAILURE_RETRY (read (fd, &word, 4)) != 4)
    error (EXIT_FAILURE, errno, _("cannot read header"));

  /* Check whether we have to swap the byte order.  */
  must_swap = (word & 0xfffffff0) == bswap_32 (0xdeb00000);
  if (must_swap)
    word = bswap_32 (word);

  /* We have two loops, one for 32 bit pointers, one for 64 bit pointers.  */
  if (word == 0xdeb00004)
    {
      union
      {
	uint32_t ptrs[2];
	char bytes[8];
      } pair;

      while (1)
	{
	  size_t len = sizeof (pair);
	  size_t n;

	  while (len > 0
		 && (n = TEMP_FAILURE_RETRY (read (fd, &pair.bytes[8 - len],
						   len))) != 0)
	    len -= n;

	  if (len != 0)
	    /* Nothing to read.  */
	    break;

	  printf ("this = %#010" PRIx32 ", caller = %#010" PRIx32 "\n",
		  must_swap ? bswap_32 (pair.ptrs[0]) : pair.ptrs[0],
		  must_swap ? bswap_32 (pair.ptrs[1]) : pair.ptrs[1]);
	}
    }
  else if (word == 0xdeb00008)
    {
      union
      {
	uint64_t ptrs[2];
	char bytes[16];
      } pair;

      while (1)
	{
	  size_t len = sizeof (pair);
	  size_t n;

	  while (len > 0
		 && (n = TEMP_FAILURE_RETRY (read (fd, &pair.bytes[8 - len],
						   len))) != 0)
	    len -= n;

	  if (len != 0)
	    /* Nothing to read.  */
	    break;

	  printf ("this = %#018" PRIx64 ", caller = %#018" PRIx64 "\n",
		  must_swap ? bswap_64 (pair.ptrs[0]) : pair.ptrs[0],
		  must_swap ? bswap_64 (pair.ptrs[1]) : pair.ptrs[1]);
	}
    }
  else
    /* This should not happen.  */
    error (EXIT_FAILURE, 0, _("invalid pointer size"));

  /* Clean up.  */
  close (fd);

  return 0;
}
Example #14
0
static void handle_session(ssh_event event, ssh_session session) {
    int n;
    int rc = 0;

    /* Structure for storing the pty size. */
    struct winsize wsize = {
        .ws_row = 0,
        .ws_col = 0,
        .ws_xpixel = 0,
        .ws_ypixel = 0
    };

    /* Our struct holding information about the channel. */
    struct channel_data_struct cdata = {
        .pid = 0,
        .pty_master = -1,
        .pty_slave = -1,
        .child_stdin = -1,
        .child_stdout = -1,
        .child_stderr = -1,
        .event = NULL,
        .winsize = &wsize
    };

    /* Our struct holding information about the session. */
    struct session_data_struct sdata = {
        .channel = NULL,
        .auth_attempts = 0,
        .authenticated = 0
    };

    struct ssh_channel_callbacks_struct channel_cb = {
        .userdata = &cdata,
        .channel_pty_request_function = pty_request,
        .channel_pty_window_change_function = pty_resize,
        .channel_shell_request_function = shell_request,
        .channel_exec_request_function = exec_request,
        .channel_data_function = data_function,
        .channel_subsystem_request_function = subsystem_request
    };

    struct ssh_server_callbacks_struct server_cb = {
        .userdata = &sdata,
        .auth_password_function = auth_password,
        .channel_open_request_session_function = channel_open,
    };

    if (authorizedkeys[0]) {
        server_cb.auth_pubkey_function = auth_publickey;
        ssh_set_auth_methods(session, SSH_AUTH_METHOD_PASSWORD | SSH_AUTH_METHOD_PUBLICKEY);
    } else
        ssh_set_auth_methods(session, SSH_AUTH_METHOD_PASSWORD);

    ssh_callbacks_init(&server_cb);
    ssh_callbacks_init(&channel_cb);

    ssh_set_server_callbacks(session, &server_cb);

    if (ssh_handle_key_exchange(session) != SSH_OK) {
        fprintf(stderr, "%s\n", ssh_get_error(session));
        return;
    }

    ssh_event_add_session(event, session);

    n = 0;
    while (sdata.authenticated == 0 || sdata.channel == NULL) {
        /* If the user has used up all attempts, or if he hasn't been able to
         * authenticate in 10 seconds (n * 100ms), disconnect. */
        if (sdata.auth_attempts >= 3 || n >= 100) {
            return;
        }

        if (ssh_event_dopoll(event, 100) == SSH_ERROR) {
            fprintf(stderr, "%s\n", ssh_get_error(session));
            return;
        }
        n++;
    }

    ssh_set_channel_callbacks(sdata.channel, &channel_cb);

    do {
        /* Poll the main event which takes care of the session, the channel and
         * even our child process's stdout/stderr (once it's started). */
        if (ssh_event_dopoll(event, -1) == SSH_ERROR) {
          ssh_channel_close(sdata.channel);
        }

        /* If child process's stdout/stderr has been registered with the event,
         * or the child process hasn't started yet, continue. */
        if (cdata.event != NULL || cdata.pid == 0) {
            continue;
        }
        /* Executed only once, once the child process starts. */
        cdata.event = event;
        /* If stdout valid, add stdout to be monitored by the poll event. */
        if (cdata.child_stdout != -1) {
            if (ssh_event_add_fd(event, cdata.child_stdout, POLLIN, process_stdout,
                                 sdata.channel) != SSH_OK) {
                fprintf(stderr, "Failed to register stdout to poll context\n");
                ssh_channel_close(sdata.channel);
            }
        }

        /* If stderr valid, add stderr to be monitored by the poll event. */
        if (cdata.child_stderr != -1){
            if (ssh_event_add_fd(event, cdata.child_stderr, POLLIN, process_stderr,
                                 sdata.channel) != SSH_OK) {
                fprintf(stderr, "Failed to register stderr to poll context\n");
                ssh_channel_close(sdata.channel);
            }
        }
    } while(ssh_channel_is_open(sdata.channel) &&
            (cdata.pid == 0 || waitpid(cdata.pid, &rc, WNOHANG) == 0));

    close(cdata.pty_master);
    close(cdata.child_stdin);
    close(cdata.child_stdout);
    close(cdata.child_stderr);

    /* Remove the descriptors from the polling context, since they are now
     * closed, they will always trigger during the poll calls. */
    ssh_event_remove_fd(event, cdata.child_stdout);
    ssh_event_remove_fd(event, cdata.child_stderr);

    /* If the child process exited. */
    if (kill(cdata.pid, 0) < 0 && WIFEXITED(rc)) {
        rc = WEXITSTATUS(rc);
        ssh_channel_request_send_exit_status(sdata.channel, rc);
    /* If client terminated the channel or the process did not exit nicely,
     * but only if something has been forked. */
    } else if (cdata.pid > 0) {
        kill(cdata.pid, SIGKILL);
    }

    ssh_channel_send_eof(sdata.channel);
    ssh_channel_close(sdata.channel);

    /* Wait up to 5 seconds for the client to terminate the session. */
    for (n = 0; n < 50 && (ssh_get_status(session) & SESSION_END) == 0; n++) {
        ssh_event_dopoll(event, 100);
    }
}

/* SIGCHLD handler for cleaning up dead children. */
static void sigchld_handler(int signo) {
    (void) signo;
    while (waitpid(-1, NULL, WNOHANG) > 0);
}

int main(int argc, char **argv) {
    ssh_bind sshbind;
    ssh_session session;
    ssh_event event;
    struct sigaction sa;
    int rc;

    /* Set up SIGCHLD handler. */
    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
    if (sigaction(SIGCHLD, &sa, NULL) != 0) {
        fprintf(stderr, "Failed to register SIGCHLD handler\n");
        return 1;
    }

    rc = ssh_init();
    if (rc < 0) {
        fprintf(stderr, "ssh_init failed\n");
        return 1;
    }

    sshbind = ssh_bind_new();
    if (sshbind == NULL) {
        fprintf(stderr, "ssh_bind_new failed\n");
        return 1;
    }

#ifdef HAVE_ARGP_H
    argp_parse(&argp, argc, argv, 0, 0, sshbind);
#else
    (void) argc;
    (void) argv;

    set_default_keys(sshbind, 0, 0, 0);
#endif /* HAVE_ARGP_H */

    if(ssh_bind_listen(sshbind) < 0) {
        fprintf(stderr, "%s\n", ssh_get_error(sshbind));
        return 1;
    }

    while (1) {
        session = ssh_new();
        if (session == NULL) {
            fprintf(stderr, "Failed to allocate session\n");
            continue;
        }

        /* Blocks until there is a new incoming connection. */
        if(ssh_bind_accept(sshbind, session) != SSH_ERROR) {
            switch(fork()) {
                case 0:
                    /* Remove the SIGCHLD handler inherited from parent. */
                    sa.sa_handler = SIG_DFL;
                    sigaction(SIGCHLD, &sa, NULL);
                    /* Remove socket binding, which allows us to restart the
                     * parent process, without terminating existing sessions. */
                    ssh_bind_free(sshbind);

                    event = ssh_event_new();
                    if (event != NULL) {
                        /* Blocks until the SSH session ends by either
                         * child process exiting, or client disconnecting. */
                        handle_session(event, session);
                        ssh_event_free(event);
                    } else {
                        fprintf(stderr, "Could not create polling context\n");
                    }
                    ssh_disconnect(session);
                    ssh_free(session);

                    exit(0);
                case -1:
                    fprintf(stderr, "Failed to fork\n");
            }
        } else {
            fprintf(stderr, "%s\n", ssh_get_error(sshbind));
        }
        /* Since the session has been passed to a child fork, do some cleaning
         * up at the parent process. */
        ssh_disconnect(session);
        ssh_free(session);
    }

    ssh_bind_free(sshbind);
    ssh_finalize();
    return 0;
}
Example #15
0
int main(int argc, char **argv)
{
	unsigned i;
	conf_t *conf;
	dict_t *repositories;
	dict_t *ports_dict;
	dict_t *not_founds;
	list_t *ports_list;
	list_t *packages;
	list_t *list;
	list_t *drivers;
	struct arguments arguments;

	arguments.action = 0;
	arguments.no_favourite_repositories = 0;
	arguments.no_locked_versions = 0;
	arguments.no_aliases = 0;
	arguments.no_colors = 0;
	arguments.no_deps = 1;
	arguments.all = 0;
	arguments.fetch_only = 0;
	arguments.no_repositories_hierarchy = 0;
	arguments.tree = 0;
	arguments.verbose = 0;
	arguments.rebuild_cache = 0;
	arguments.args = list_new();

	if (argc < 2) {
		char *fake_arg[2];
		fake_arg[0] = "ilenia";
		fake_arg[1] = "--help";
		argp_parse(&argp, 2, fake_arg, 0, 0, &arguments);
	}

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

	conf = conf_init();

	if (arguments.no_repositories_hierarchy) {
		list_free(conf->repositories_hierarchy, free);
		conf->repositories_hierarchy = list_new();
	}

	if (arguments.no_favourite_repositories) {
		dict_free(conf->favourite_repositories, NULL);
		conf->favourite_repositories = dict_new();
	}

	if (arguments.no_locked_versions) {
		dict_free(conf->locked_versions, free);
		conf->locked_versions = dict_new();
	}

	if (arguments.no_aliases) {
		aliases_free(conf->aliases);
		conf->aliases = dict_new();
	}

	drivers = drivers_list_init();
	repositories = repositories_dict_init(drivers,
					      conf->repositories_hierarchy);
	if (!conf->enable_colors || arguments.no_colors)
		cprintf = uncoloredprintf;
	else
		cprintf = coloredprintf;

	if (arguments.rebuild_cache)
		cache_build(repositories);
	packages = packages_list_init();
	if ((ports_list = ports_list_init(repositories)) == NULL) {
		list_free(arguments.args, NULL);
		dict_free(repositories, repository_free);
		list_free(packages, port_free);
		list_free(drivers, free);
		dict_free(conf->favourite_repositories, free);
		conf->favourite_repositories = dict_new();
		conf_free(conf);
		return 1;
	}

	conf_reparse(conf, ports_list);
	ports_dict = ports_dict_init(ports_list, packages, conf);
	not_founds = dict_new();

	if (!arguments.verbose)
		arguments.verbose = conf->verbose;

	switch (arguments.action) {
	case ACT_LIST:
		if (!arguments.args->length) {
			list_dump(ports_list, port_dump);
			break;
		}
		for (i = 0; i < arguments.args->length; i++) {
			if (dict_get(repositories, list_get(arguments.args, i))
			    == NULL) {
				warning("repository %s not found!",
					list_get(arguments.args, i));
				continue;
			}
			list = list_query(ports_list,
					  port_query_by_repository,
					  list_get(arguments.args, i));
			list_dump(list, port_dump);
			list_free(list, NULL);
		}
		break;
	case ACT_SEARCH:
		if (!arguments.args->length) {
			warning("action --search (-s) requires at least an "
				"argument!");
			break;
		}
		for (i = 0; i < arguments.args->length; i++) {
			list = list_query(ports_list, port_query_by_name,
					  list_get(arguments.args, i));
			if (arguments.verbose)
				list_dump(list, port_info_dump);
			else
				list_dump(list, port_dump);
			if (list->length == 0)
				printf("%s not found!\n",
				       (char *)list_get(arguments.args, i));
			list_free(list, NULL);
		}
		break;
	case ACT_SEARCHDESC:
		if (!arguments.args->length) {
			warning("action --search-desc requires at least an "
				"argument!");
			break;
		}
		for (i = 0; i < arguments.args->length; i++) {
			char *key = xstrdup(list_get(arguments.args, i));
			if (isalpha(*key) && isalpha(*(key + strlen(key) - 1))) {
				strprepend(&key, "*");
				strappend(&key, "*");
			}
			list = list_query(ports_list, port_query_by_description,
					  key);
			if (arguments.verbose)
				list_dump(list, port_info_dump);
			else
				list_dump(list, port_dump);
			list_free(list, NULL);
			free(key);
		}
		break;
	case ACT_DIFF:
		port_show_diffs(ports_dict, packages);
		break;
	case ACT_UPDATED:
		port_show_outdated(ports_dict, packages);
		break;
	case ACT_DEPENDENCIES:
		if (!arguments.args->length) {
			warning("action --dependencies (-D) requires at "
				"least an argument!");
			break;
		}
		//for (i = 0; i < arguments.args->length; i++)
		dependencies_dump(arguments.args,
				  ports_dict, conf->aliases,
				  not_founds,
				  arguments.tree, arguments.verbose);
		break;
	case ACT_DEPENDENTS:
		if (!arguments.args->length) {
			warning("action --dependents (-T) requires at "
				"least an argument!");
			break;
		}
		for (i = 0; i < arguments.args->length; i++)
			dependents_dump(list_get(arguments.args, i),
					ports_dict, conf->aliases,
					arguments.tree, arguments.verbose,
					arguments.all);
		break;
	case ACT_INFO:
		if (!arguments.args->length) {
			warning("action --info requires at "
				"least an argument!");
			break;
		}
		for (i = 0; i < arguments.args->length; i++)
			info_dump(list_get(arguments.args, i), ports_dict);
		break;
	case ACT_README:
		if (!arguments.args->length) {
			warning("action --show-readme requires at "
				"least an argument!");
			break;
		}
		for (i = 0; i < arguments.args->length; i++)
			readme_dump(list_get(arguments.args, i), ports_dict);
		break;
	case ACT_REPOSITORY_LIST:
		repositories_dict_dump(repositories);
		break;
	case ACT_UPDATE:
		if (arguments.args->length)
			repositories_dict_update(repositories, arguments.args);
		else
			repositories_dict_update_all(repositories);
		break;
	case ACT_REMOVE:
		if (!arguments.args->length) {
			warning("action --remove (-R) requires at "
				"least an argument!");
			break;
		}
		remove_packages(arguments.args, packages, ports_dict, conf,
				arguments.all);
		break;
	case ACT_UPDATE_PKG:
		if (!arguments.args->length) {
			update_system(ports_dict,
				      conf->aliases, arguments.fetch_only,
				      conf->ask_for_update,
				      conf->not_found_policy);
			break;
		}
		update_package(arguments.args, ports_dict, conf,
			       arguments.fetch_only);
		break;
	default:
		if (!arguments.rebuild_cache)
			warning("What can I do for you?");
	}

	list_free(arguments.args, NULL);
	dict_free(repositories, repository_free);
	list_free(ports_list, port_free);
	list_free(packages, port_free);
	dict_free(ports_dict, NULL);
	list_free(drivers, free);
	conf_free(conf);
	dict_free(not_founds, port_free);

	return 0;
}
Example #16
0
File: main.c Project: f4exb/tnc1101
// ------------------------------------------------------------------------------------------------
int main (int argc, char **argv)
// ------------------------------------------------------------------------------------------------
{
    int i, nbytes;

    // unsolicited termination handling
    struct sigaction sa;
    // Catch all signals possible on process exit!
    for (i = 1; i < 64; i++) 
    {
        // skip SIGUSR2 for Wiring Pi
        if (i == 17)
            continue; 

        // These are uncatchable or harmless or we want a core dump (SEGV) 
        if (i != SIGKILL
            && i != SIGSEGV
            && i != SIGSTOP
            && i != SIGVTALRM
            && i != SIGWINCH
            && i != SIGPROF) 
        {
            memset(&sa, 0, sizeof(sa));
            sa.sa_handler = terminate;
            sigaction(i, &sa, NULL);
        }
    }

    // Set argument defaults
    init_args(&arguments); 

    // Parse arguments 
    argp_parse (&argp, argc, argv, 0, 0, &arguments);

    if (arguments.print_long_help)
    {
        print_long_help();
        return 0;
    }
    
    if (!arguments.usbacm_device)
    {
        arguments.usbacm_device = strdup("/dev/ttyACM2");
    }
    
    if (!arguments.serial_device)
    {
        arguments.serial_device = strdup("/var/ax25/axp2");
    }
    
    if (!arguments.bulk_filename)
    {
        arguments.bulk_filename = strdup("-");
    }

    set_serial_parameters(&serial_parms_ax25, arguments.serial_device, get_serial_speed(arguments.serial_speed, &arguments.serial_speed_n));
    set_serial_parameters(&serial_parms_usb,  arguments.usbacm_device, get_serial_speed(115200, &arguments.usb_speed_n));
    init_radio_parms(&radio_parms, &arguments);

    if (arguments.verbose_level > 0)
    {
        print_args(&arguments);
        print_radio_parms(&radio_parms);
        fprintf(stderr, "\n");
    }

    if (arguments.tnc_mode == TNC_KISS)
    {
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_SLIP)
    {
        arguments.slip = 1;
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_USB_ECHO) // This one does not need any access to the radio
    {
        usb_test_echo(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_STATUS) 
    {
        print_radio_status(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_INIT)
    {
        init_radio(&serial_parms_usb, &radio_parms, &arguments);

        if (nbytes < 0)
        {
            fprintf(stderr, "Error\n");
        }
    }
    else if (arguments.tnc_mode == TNC_TEST_TX)
    {
        radio_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX)
    {
        radio_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_ECHO_TX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 1);
    } 
    else if (arguments.tnc_mode == TNC_TEST_ECHO_RX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 0);
    }
    else if (arguments.tnc_mode == TNC_TEST_TX_PACKET)
    {
        radio_packet_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET)
    {
        radio_packet_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET_NON_BLOCKING)
    {
        radio_packet_receive_nb_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_TX)
    {
        file_bulk_transmit(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_RX)
    {
        file_bulk_receive(&serial_parms_usb, &radio_parms, &arguments);
    }

    close_serial(&serial_parms_usb);
    close_serial(&serial_parms_ax25);
    delete_args(&arguments);
    return 0;
}
Example #17
0
int main( int argc, char *argv[] )
{
    struct structArgs cmdArgs;
	unsigned int val, val2;
	int dir;
    int errNum;
	cmdArgs.card = 0;		// Default card.
	cmdArgs.control = 1;	// Default control.


    // ************************************************************************
    //  ALSA control elements.
    // ************************************************************************
    snd_pcm_t *pcmp;
    snd_pcm_hw_params_t *params;
//	snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
	snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
    snd_pcm_uframes_t frames;


    // ************************************************************************
    //  Get command line parameters.
    // ************************************************************************
    argp_parse( &argp, argc, argv, 0, 0, &cmdArgs );

    printf( "Card = %i\n", cmdArgs.card );
    printf( "Control = %i\n", cmdArgs.control );
    sprintf( cmdArgs.deviceID, "hw:%i,%i", cmdArgs.card, cmdArgs.control );
	printf( "Using device %s :", cmdArgs.deviceID );

    /* Allocate a hardware parameters object. */
    if ( snd_pcm_hw_params_alloca( &params ) < 0 )
    {
    	fprintf( stderr, "Unable to allocate.\n" );
    	return -1;
   	}
    /* Open PCM device for playback. */
//    if ( snd_pcm_open( &pcmp, cmdArgs.deviceID, stream, 0 ) < 0 )
//    {
//        fprintf( stderr, "Unable to open pcm device.\n" );
//    	return -1;
//    }
    /* Fill it in with default values. */
//    if ( snd_pcm_hw_params_any( pcmp, params ) < 0
//    {
//    	fprintf( stderr, "Unable to set default values.\n" );
//    	return -1;
//    }
    /* Interleaved mode */
//    snd_pcm_hw_params_set_access( pcmp, params,
//    		SND_PCM_ACCESS_RW_INTERLEAVED );

    /* Signed 16-bit little-endian format */
    snd_pcm_hw_params_set_format( pcmp, params,
        	SND_PCM_FORMAT_S16_LE );

    /* Two channels (stereo) */
    snd_pcm_hw_params_set_channels( pcmp, params, 2 );

    /* 44100 bits/second sampling rate (CD quality) */
    val = 44100;
    snd_pcm_hw_params_set_rate_near( pcmp, params, &val, &dir );

    /* Write the parameters to the driver */
    errNum = snd_pcm_hw_params( pcmp, params );
    if ( errNum < 0 )
    {
        fprintf(stderr, "unable to set hw parameters: %s\n",
            snd_strerror( errNum ));
        exit( 1 );
    }

    /* Display information about the PCM interface */

    printf( "PCM handle name = '%s'\n", snd_pcm_name( pcmp ));

    printf("PCM state = %s\n", snd_pcm_state_name( snd_pcm_state( pcmp )));

    snd_pcm_hw_params_get_access( params, ( snd_pcm_access_t * ) &val );
    printf( "access type = %s\n",
        snd_pcm_access_name(( snd_pcm_access_t ) val ));

    snd_pcm_hw_params_get_format( params, ( snd_pcm_format_t * ) &val );
    printf( "format = '%s' (%s)\n",
        snd_pcm_format_name(( snd_pcm_format_t ) val ),
        snd_pcm_format_description(( snd_pcm_format_t ) val ));

    snd_pcm_hw_params_get_subformat( params,
        ( snd_pcm_subformat_t * ) &val );
    printf( "subformat = '%s' (%s)\n",
        snd_pcm_subformat_name(( snd_pcm_subformat_t ) val ),
        snd_pcm_subformat_description((
        snd_pcm_subformat_t ) val ));

    snd_pcm_hw_params_get_channels( params, &val );
    printf( "channels = %d\n", val );

    snd_pcm_hw_params_get_rate( params, &val, &dir );
    printf( "rate = %d bps\n", val );

    snd_pcm_hw_params_get_period_time( params, &val, &dir );
    printf( "period time = %d us\n", val );

    snd_pcm_hw_params_get_period_size( params, &frames, &dir );
    printf( "period size = %d frames\n", ( int ) frames );

    snd_pcm_hw_params_get_buffer_time( params, &val, &dir );
    printf( "buffer time = %d us\n", val );

    snd_pcm_hw_params_get_buffer_size( params,
        ( snd_pcm_uframes_t * ) &val );
    printf( "buffer size = %d frames\n", val );

    snd_pcm_hw_params_get_periods( params, &val, &dir );
    printf( "periods per buffer = %d frames\n", val );

    snd_pcm_hw_params_get_rate_numden( params, &val, &val2 );
    printf( "exact rate = %d/%d bps\n", val, val2 );

    val = snd_pcm_hw_params_get_sbits( params );
    printf( "significant bits = %d\n", val );

//    snd_pcm_hw_params_get_tick_time( params, &val, &dir );
//    printf( "tick time = %d us\n", val );

    val = snd_pcm_hw_params_is_batch( params );
    printf( "is batch = %d\n", val );

    val = snd_pcm_hw_params_is_block_transfer( params );
    printf( "is block transfer = %d\n", val );

    val = snd_pcm_hw_params_is_double( params );
    printf( "is double = %d\n", val );

    val = snd_pcm_hw_params_is_half_duplex( params );
    printf( "is half duplex = %d\n", val );

    val = snd_pcm_hw_params_is_joint_duplex( params );
    printf( "is joint duplex = %d\n", val );

    val = snd_pcm_hw_params_can_overrange( params );
    printf( "can overrange = %d\n", val );

    val = snd_pcm_hw_params_can_mmap_sample_resolution( params );
    printf( "can mmap = %d\n", val );

    val = snd_pcm_hw_params_can_pause( params );
    printf( "can pause = %d\n", val );

    val = snd_pcm_hw_params_can_resume( params );
    printf( "can resume = %d\n", val );

    val = snd_pcm_hw_params_can_sync_start( params );
    printf( "can sync start = %d\n", val );
    snd_pcm_close( pcmp );

    return 0;
}
Example #18
0
int main (int argc, char* argv[])
{
  // Create our single-loop for this single-thread application
  EV_P;
  pthread_attr_t attr;
  int thread_status;
  struct evn_server* server;
  char socket_address[256];
  EV_A = ev_default_loop(0);


  // Set default options, then parse new arguments to update the settings
  dummy_settings_set_presets(&dummy_settings);
  argp_parse (&argp, argc, argv, 0, 0, &dummy_settings);
  // TODO separate worker settings from daemon settings
  // (i.e. redirect)

  if (true == redirect)
  {
    redirect_output();
  }

  if (0)
  {
    struct ev_periodic every_few_seconds;

    // To be sure that we aren't actually blocking
    ev_periodic_init(&every_few_seconds, test_process_is_not_blocked, 0, 1, 0);
    ev_periodic_start(EV_A_ &every_few_seconds);
  }

  // Set the priority of this whole process higher (requires root)
  setpriority(PRIO_PROCESS, 0, -13); // -15

  // initialize the values of the struct that we will be giving to the new thread
  thread_control.dummy_settings = &dummy_settings;
  thread_control.buffer_head = 0;
  thread_control.buffer_count = 0;
  thread_control.EV_A = ev_loop_new(EVFLAG_AUTO);

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  // Initialize the thread that will manage the DUMMY_WORKER
  thread_status = pthread_create(&dummy_worker_pthread, &attr, dummy_worker_thread, (void *)(&thread_control));
  if (0 != thread_status)
  {
    fprintf(stderr, "thread creation failed with errno %d (%s)\n", thread_status, strerror(thread_status));
    exit(EXIT_FAILURE);
  }
  pthread_attr_destroy(&attr);


  // Create unix socket in non-blocking fashion
  snprintf(socket_address, sizeof(socket_address), DUMMYD_SOCK, (int)getuid());
  unlink(socket_address);
  server = evn_server_create(EV_A_ server_on_connection);
  server->on_connection = server_on_connection;
  evn_server_listen(server, 0, socket_address);

  // Run our loop, until we recieve the QUIT, TERM or INT signals, or an 'x' over the socket.
  puts("[Daemon] Looping.\n");
  ev_loop(EV_A_ 0);

  // Cleanup if `unloop` is ever called
  clean_shutdown(EV_A_ 0);
  return 0;
}
int main(int argc, char **argv)
{
  struct arguments arguments;
  int sockfd, n;

  struct sockaddr_in serv_addr;
  struct hostent *server;

  char buffer[1028];
  int result_size = 1028;
  char* result;
  char* command;
// Default values.
  arguments.verbose = 0;
  arguments.port_number = 5002;
  arguments.addr = "localhost";

// Parse our arguments; every option seen by parse_opt will be reflected in arguments.
  argp_parse (&argp, argc, argv, 0, 0, &arguments);
  sockfd = socket(AF_INET, SOCK_STREAM, 0);

  if (sockfd < 0) {
    error("ERROR opening socket");
  }

  server = gethostbyname(arguments.addr);

  if (server == NULL) {
    error("ERROR, no such host");
  }

  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;

  bcopy((char *)server->h_addr, 
       (char *)&serv_addr.sin_addr.s_addr,
       server->h_length);

  serv_addr.sin_port = htons(arguments.port_number);
  if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
    error("ERROR connecting");
  }

  command = build_command(arguments.args);

  if (write(sockfd, command, strlen(command)) < 0) {
    error("ERROR writing to socket");
  }

  result = "";

  while ((n = read(sockfd, buffer, 1027))) {
    buffer[n] = '\0';
    result = concat(result, "", buffer);
  }

  printf("%s\n", result);

  if (command) {
    free(command);
  }

  if (result) {
    free(result);
  }
  return 0;
}
Example #20
0
int main(int argc, char** argv){
	
	int seed = getpid();
	int c;
	int option_index = 0;
	int league_id;
	int num_players;
	
	struct argp_option options[] = {
		{"seed",'s', "int", 0, 0},
		{"league-id", 'l', "int", 0, 0},
		{"players", 'n', "int", 0, 0},
		{"hitter-mean",'h', "double", 0, 0},
		{"hitter-sd", 'i', "double", 0, 0},
		{"pitcher-mean", 'p', "double", 0, 0},
		{"pitcher-sd", 'r', "double", 0, 0},
		{0}
	};

	struct arguments args = {&seed, &league_id, &num_players, &HITTER_MEAN,
					&HITTER_SD, &PITCHER_MEAN, &PITCHER_SD};
	struct argp argp = {options, arg_parser, 0, 0, global_child}; 
	argp_parse(&argp, argc, argv, 0, 0, &args);

#ifdef _USEGSL_
	gsl_rng_env_setup();
	const gsl_rng_type *type = gsl_rng_default;
	rng = gsl_rng_alloc(type);
	gsl_rng_set(rng,seed);
#else
	srand(seed);
#endif
	Db_Object db = db_connect(CONFIG_FILE);
	db->begin_transaction(db->conn);
	fprintf(stderr,"Seed: %d\n",seed);

	Array_List first_names = Array_List_create(sizeof(char*));
	Array_List last_names = Array_List_create(sizeof(char*));

	select_names(db,first_names,last_names);
	int i;

	struct player new_player;
	struct hitter_skill hitter_skill;
	struct pitcher_skill pitcher_skill;
	struct fielder_skill fielder_skill;

	for(i=0;i<num_players;i++){
		
		int power= random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL);
		int contact = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL);
		int fielding = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL);
		int speed = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL);
		int intelligence = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL);
		int control = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL);
		int movement = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL);
		int velocity = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL);
		int endurance = 0;
		int bats = (rand()%100)+1;
		int throws = (rand()%100)+1;
		int position = rand()%18;

/*TODO: Make the choosing of names random.*/
		int first_name = 8 * (power + contact + fielding + speed + bats) % first_names->length;
		int last_name = 8 * (first_name + speed + intelligence + control + movement + velocity + bats + throws + control + movement + position) % last_names->length;
		
		if(throws <= PERCENT_THROW_RIGHT){
			new_player.throws = RIGHT;
		}
		else{
			new_player.throws = LEFT;
		}
		
		if(bats<= PERCENT_HIT_SAME){
			new_player.bats = new_player.throws;
		}
		else if(bats<PERCENT_HIT_SAME+PERCENT_HIT_DIFFERENT){
			if(new_player.throws == RIGHT){
				new_player.bats = LEFT;
			}
			else{
				new_player.bats = RIGHT;
			}
		}
		else{
			new_player.bats = SWITCH;
		}
		if(position <= 9 && position > 1){
			new_player. position = position;
			pitcher_skill.end = random_normal(30.0,PITCHER_SD*SD_TWEAK,0,49);
		}
		else if(position>=15 || position == 1){
			new_player.position =1;
			pitcher_skill.end = random_normal(80.0,PITCHER_SD*SD_TWEAK,50,100);
		}
		else{
			new_player.position = 0;
			pitcher_skill.end = random_normal(30.0,PITCHER_SD*SD_TWEAK,0,49);
		}
		int vs_right_mod = 5;
		int vs_left_mod = 5;
		if(new_player.bats == RIGHT){
			vs_right_mod = -5;
		}
		if(new_player.bats ==LEFT){
			vs_left_mod = -5;
		}
		
		new_player.first_name = gget(first_names,first_name);
		new_player.last_name = gget(last_names,last_name);
		
		hitter_skill.cvr = calc_skill(contact+vs_right_mod,HITTER_SD);
		hitter_skill.pvr = calc_skill(power+vs_right_mod,HITTER_SD);
		hitter_skill.cvl = calc_skill(contact+vs_left_mod,HITTER_SD);
		hitter_skill.pvl = calc_skill(power+vs_left_mod,HITTER_SD);
		hitter_skill.spd = speed;	
		
		fielder_skill.range = calc_skill(fielding,HITTER_SD);
		fielder_skill.arm = calc_skill(fielding,HITTER_SD);
		fielder_skill.field = calc_skill(fielding,HITTER_SD);
		
		new_player.intelligence = intelligence;
		
		pitcher_skill.mov = calc_skill(movement,PITCHER_SD);
		pitcher_skill.vel = calc_skill(velocity,PITCHER_SD);
		pitcher_skill.ctrl = calc_skill(control,PITCHER_SD);
		
		insert_player(db,&new_player,&hitter_skill,&pitcher_skill,&fielder_skill,league_id);
		
	}
	db->commit(db->conn);
	db->close_connection(db->conn);	
#ifdef _USEGSL_
	gsl_rng_free(rng);
#endif

	return 0;	
}
Example #21
0
int
mutool_acl (int argc, char **argv)
{
  int rc, index;
  mu_acl_result_t result;
  mu_cfg_tree_t *tree = NULL, *temp_tree = NULL;
  mu_cfg_node_t *node;
  
  if (argp_parse (&acl_argp, argc, argv, ARGP_IN_ORDER, &index, NULL))
    return 1;

  argc -= index;
  argv += index;

  if (argc == 0)
    {
      mu_error (_("not enough arguments"));
      return 1;
    }

  if (input_file_name)
    {
      mu_load_site_rcfile = 0;
      mu_load_user_rcfile = 0;
      mu_load_rcfile = input_file_name;
    }

  mu_acl_cfg_init ();
  if (mu_libcfg_parse_config (&tree))
    return 1;
  if (!tree)
    return 0;
  
  if (mu_cfg_find_node (tree, path, &node))
    {
      mu_error (_("cannot find node: %s"), path);
      return 1;
    }

  mu_cfg_tree_create (&temp_tree);
  mu_cfg_tree_add_node (temp_tree, node);
  rc = mu_cfg_tree_reduce (temp_tree, NULL, acl_cfg_param, NULL);
  if (rc)
    return 1;
  if (!acl)
    {
      mu_error (_("No ACL found in config"));
      return 1;
    }
  
  while (argc--)
    {
      const char *ap = *argv++;

      rc = mu_sockaddr_from_node (&target_sa, ap, NULL, NULL);
      if (rc)
	{
	  mu_error ("mu_sockaddr_from_node: %s", mu_strerror (rc));
	  exit (1);
	}

      mu_printf ("Testing %s:\n", ap);
      rc = mu_acl_check_sockaddr (acl, target_sa->addr, target_sa->addrlen,
				  &result);
      mu_sockaddr_free_list (target_sa);
      if (rc)
	{
	  mu_error ("mu_acl_check_sockaddr failed: %s", mu_strerror (rc));
	  return 1;
	}

      switch (result)
	{
	case mu_acl_result_undefined:
	  mu_printf ("%s: undefined\n", ap);
	  break;
      
	case mu_acl_result_accept:
	  mu_printf ("%s: accept\n", ap);
	  break;

	case mu_acl_result_deny:
	  mu_printf ("%s: deny\n", ap);
	  break;
	}
    }

  mu_cfg_destroy_tree (&tree);
  mu_cfg_destroy_tree (&temp_tree);

  return 0;
}
Example #22
0
int
main (int ac, char *ag[])
{
  int index;
  pth_init ();

  argp_parse (&argp, ac, ag, ARGP_IN_ORDER, &index, &arg);

  // if you ever want this to be fatal, doing it here would be too late
  if (getuid () == 0)
    ERRORPRINTF (arg.tracer(), E_WARNING | 20, 0, "EIBD should not run as root");

  signal (SIGPIPE, SIG_IGN);

  if (arg.daemon)
    {
      int fd = open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
      if (fd == -1)
	die ("Can not open file %s", arg.daemon);
      int i = fork ();
      if (i < 0)
	die ("fork failed");
      if (i > 0)
	exit (0);
      close (1);
      close (2);
      close (0);
      dup2 (fd, 1);
      dup2 (fd, 2);
      close (fd);
      setsid ();
    }

  FILE *pidf;
  if (arg.pidfile)
    if ((pidf = fopen (arg.pidfile, "w")) != NULL)
      {
	fprintf (pidf, "%d", getpid ());
	fclose (pidf);
      }


  signal (SIGINT, SIG_IGN);
  signal (SIGTERM, SIG_IGN);

  // main loop
#ifdef HAVE_SYSTEMD
  sd_notify(0,"READY=1");
#endif
  int sig;
  if (! arg.stop_now)
    do {
      sigset_t t1;
      sigemptyset (&t1);
      sigaddset (&t1, SIGINT);
      sigaddset (&t1, SIGHUP);
      sigaddset (&t1, SIGTERM);

      pth_sigwait (&t1, &sig);

      if (sig == SIGHUP && arg.daemon)
	{
	  int fd =
	    open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
	  if (fd == -1)
	    {
	      ERRORPRINTF (arg.tracer(), E_ERROR | 21, 0, "can't open log file %s",
			   arg.daemon);
	      continue;
	    }
	  close (1);
	  close (2);
	  dup2 (fd, 1);
	  dup2 (fd, 2);
	  close (fd);
	}

    } while (sig == SIGHUP);
#ifdef HAVE_SYSTEMD
  sd_notify(0,"STOPPING=1");
#endif

  signal (SIGINT, SIG_DFL);
  signal (SIGTERM, SIG_DFL);

#ifdef HAVE_GROUPCACHE
  DeleteGroupCache ();
#endif

  arg.free_l3();

  if (arg.pidfile)
    unlink (arg.pidfile);

  pth_yield (0);
  pth_yield (0);
  pth_yield (0);
  pth_yield (0);
  pth_exit (0);
  return 0;
}
Example #23
0
static int do_exec_cmd_ent(struct cmdctx *cmdctx, int argc, char **argv) 
{
    int                  rc = 1;
    unsigned             parse_flags;
    struct poclidek_cmd  *cmd = cmdctx->cmd;
    struct argp          cmd_argp = { cmd->argp_opts, cmd->parse_opt_fn,
                                      cmd->arg,
                                      cmd->doc, 0, 0, 0};
    
    struct argp_child cmd_argp_child[2] = { { &cmd_argp, 0, NULL, 0 },
                                            { NULL, 0, NULL, 0 },   };
    
    struct argp argp = { common_options, parse_opt, 0, 0,
                         cmd_argp_child, 0, 0 };

    
    if (argv == NULL)
        return 0;

    cmd = cmdctx->cmd;
    if (poclidek_argv_is_help(argc, (const char**)argv)) {
        cmdctx->rtflags |= CMDCTX_ISHELP;
        DBGF("is_help!\n");
    }
    
    if (poldek_verbose() < 0)
        cmdctx->rtflags |= CMDCTX_NOCTRLMSGS;
    
    cmdctx->_data = NULL;
    if (cmd->init_cmd_arg_d)
        cmdctx->_data = cmd->init_cmd_arg_d();

    if (cmd->cmd_fn) { /* option parses its args itself */
        DBGF("run cmd_fn(arc, argv)\n");
        rc = cmd->cmd_fn(cmdctx, argc, (const char**)argv, &argp);
        goto l_end;
    }
    
    
    if ((cmd->flags & COMMAND_NOHELP) && (cmd->flags & COMMAND_NOARGS) &&
        (cmd->flags & COMMAND_NOOPTS)) {
        rc = cmd->do_cmd_fn(cmdctx);
        goto l_end;
    }

    argp.help_filter = help_filter;
    parse_flags = argp_parse_flags;
    argp_parse(&argp, argc, (char**)argv, parse_flags, 0, cmdctx);

    if (cmdctx->rtflags & CMDCTX_ERR) {
        rc = 0;
        goto l_end;
    }
    
    if (cmdctx->rtflags & CMDCTX_ISHELP) {
        rc = 1;
        goto l_end;
    }
    
    rc = cmd->do_cmd_fn(cmdctx);

 l_end:
    if (cmd->destroy_cmd_arg_d && cmdctx->_data)
        cmd->destroy_cmd_arg_d(cmdctx->_data);

    return rc;
}
Example #24
0
int main (int argc, char **argv)
{
    struct arguments arguments;

    /* Parse our arguments; every option seen by parse_opt will
       be reflected in arguments. */
    argp_parse (&argp, argc, argv, 0, 0, &arguments); 

    // number of nearest neighbors
    int k;
    k = 1; //default is 1
    if (sscanf (arguments.args[0], "%i", &k)!=1) {}

    //omp vars
    int num_threads;
    num_threads = 4;
    if (sscanf(arguments.args[1], "%i", &num_threads)!=1) {}

    //verbose?
    int verbose;
    verbose = arguments.verbose;
    if (verbose>0 && verbose<130){
        verbose = 1;
    }
    else{
        verbose = 0;
    }


    //define a bunch of counters!
    int i, j, m, n, ii, jj, kk;

    //number of examples to read in
    int total_examples = 10000;
    // int total_examples = 19;

    //max words per question
    int num_words = 300;

    //max word length
    int max_word_len = 20;
    //max vocab count
    // int max_vocab = 200000;

    //data read in poorly
    int bad_iter = 0;

    //Used to split into training and testing data (will train on example_num%train)
    int train = 10;

    //Debug
    int debug = 0;


    printf("k, Verbose, num_threads = %i, %i, %i\n",
                          k, verbose, num_threads);
    

     //Allocate space for data being read in with fgets
    char *csv_line = malloc(sizeof(char)*1500);

    //store all data
    //array of structs
    //struct.question->array of char*
    //struct.cat->char*
    //struct.example_num->int
    struct data *all_data;
    all_data = malloc(sizeof(struct data)*total_examples);
    for (ii=0; ii<total_examples; ii++){
    	all_data[ii].question = malloc(sizeof(char*)*num_words);
    	for (jj=0; jj<num_words; jj++){
    		// all_data[ii].question[jj] = malloc(sizeof(char)*max_word_len);
    		all_data[ii].question[jj] = calloc(max_word_len, sizeof(char));
    	}
    	all_data[ii].cat = malloc(sizeof(char)*max_word_len);
    }

    //store numeric version of data for algorithms
    struct numeric_data *num_data;
    num_data = malloc(sizeof(struct numeric_data)*total_examples);
    for (ii=0; ii<total_examples; ii++){
    	num_data[ii].array_of_features = malloc(sizeof(struct feature_count)*num_words);
    	for (jj=0; jj<num_words; jj++){
    		num_data[ii].array_of_features[jj].feature_num = 0;
    		num_data[ii].array_of_features[jj].count = 0;
    	}
    }

    //store struct which keep track of the k nearest neighbors
    // struct distance_results results;
    // results.example_num = 0;
    // results.distances = calloc(k, sizeof(double));
    // results.cat = calloc(k, sizeof(int));
    // results.example_nums = calloc(k, sizeof(int));

    // //struct used to calculate the mode of the k nearest neighbors
    // struct mode mod;
    // mod.count = calloc(k, sizeof(int));
    // mod.cat = calloc(k, sizeof(int));
 
    // //store vocabulary list (char** points to array of char* of length 20)
    // char **word_list;
    // word_list = malloc(sizeof(char*)*max_vocab); //assumes max_vocab total vocab
    // for (ii=0; ii<max_vocab; ii++){
    // 	// word_list[ii] = malloc(sizeof(char)*max_word_len);  //assumes max word length of 20
    // 	word_list[ii] = calloc(max_word_len, sizeof(char));  //assumes max word length of 20
    // }

    //alternate vocab store tree
    feature_tree *vocab;
    vocab = NULL;

    //store category list
    char **cat_list;
    cat_list = malloc(sizeof(char*)*40);  //assumes 20 max categories
    for (ii=0; ii<40; ii++){
    	cat_list[ii] = malloc(sizeof(char)*max_word_len);
		strncpy(cat_list[ii], "\0", 1);	
    }

    //Read in csv file
    FILE *f = fopen("train_pruned2.csv", "r");
    if (f == NULL){
    	printf("Failed to open file \n");
    	return -1;
    }

    //parse question into individual words, create vocabulary list
    int vocab_count = 0;
    int category_count = 1;

    for (i=0; i<total_examples; i++){
    	// printf("Iteration = %i\n", i);

    	//line in csv to buffer
    	if (fgets(csv_line, 1500, f) == NULL){
            printf("Fgets error!\n");
            exit(0);
        }

    	//csv line to 3 individual parts
    	if (i>0)
    	{

			char *tok;
			char *tok_copy; //problem with tok getting overwritten in parse_question
			// char **parsed_question = malloc(sizeof(char*)*num_words);

			// printf("CSV_LINE = %s\n", csv_line);

			tok = strtok(csv_line, "|");
			if (tok == NULL){
				// all_data[i-bad_iter-1].example_num = -1;
				bad_iter++;
				// i--;
				continue;
			}
			sscanf(tok, "%i", &all_data[i-bad_iter-1].example_num);

			

			tok = strtok(NULL, "|");
			if (tok == NULL){
				// all_data[i-bad_iter-1].example_num = -1;
				bad_iter++;
				// i--;
				continue;
			}
			tok_copy = (char *)tok;

			

			tok = strtok(NULL, "|");
			if (tok == NULL){
				// all_data[i-bad_iter-1].example_num = -1;
				bad_iter++;
				// i--;
				continue;
			}
			strncpy(all_data[i-bad_iter-1].cat, tok, 19);
			all_data[i-bad_iter-1].cat[max_word_len-1] = 0;


			char *tok2;
			tok2 = strtok(tok_copy, " \t");

			j = 0;
			if ((tok2 != NULL) && (strlen(tok2)>3)){
				strncpy(all_data[i-bad_iter-1].question[0], tok2, 19);
		    	all_data[i-bad_iter-1].question[0][max_word_len-1] = 0;

		    	//add to tree if not test data
		    	// if (all_data[i-bad_iter-1].example_num % train != 0){
		    	insert_word(&vocab, all_data[i-bad_iter-1].question[0]);
    			j += 1;
		    	// }
    			
			}

			while (tok2 != NULL){
				if (j>=num_words){
					break;
				}
				tok2 = strtok(NULL, " \t");
		        if ((tok2 != NULL) && (strlen(tok2)>3)){
		            strncpy(all_data[i-bad_iter-1].question[j], tok2, 19);
		            all_data[i-bad_iter-1].question[j][max_word_len-1] = 0;

		            //add to tree if not test data
		            // if (all_data[i-bad_iter-1].example_num % train != 0){
					insert_word(&vocab, all_data[i-bad_iter-1].question[j]);
					j++;
    				// }
		        }
				
			} //end while

    		// all_data[i-bad_iter-1] = instance;
    		// print_data(&all_data[i-bad_iter-1]);

    		////add to vocabulary (using array, VERY slow with lots of data)
    		// add_to_word_list(all_data[i-bad_iter-1].question, word_list, &vocab_count);
    		
    		//add to category list
    		add_to_cat_list(all_data[i-bad_iter-1].cat, cat_list, &category_count);

    	} //end if
    } //end for

    //close file
    fclose(f);

    //assign unique number to each feature
    //first feature is feature 1, feature 0 is for errors etc.
    unsigned int mm = 1;
    number_features(vocab, &mm);

    //Some of the csv rows aren't read in properly with fgets
    printf("Bad iterations = %i/%i\n", bad_iter, i);
    printf("Feature count = %i\n", count_features(vocab));
    // print_inorder(vocab);

    // for (ii=0; ii<40; ii++){
    // 	printf("%s", cat_list[ii]);
    // }

    ////turn data into numeric features////
    for (i=0; i<total_examples; i++){
    	num_data[i].example_num = all_data[i].example_num;
    	num_data[i].cat = get_cat_index(cat_list, all_data[i].cat);
    	words_to_num(&num_data[i], &all_data[i], &vocab, num_words);
        // count_features2(&num_data[i]);
    }

    // num_data->array_of_features[0].feature_num = 44;

    // print_num_data(&num_data[0]);
    // print_num_data(&num_data[1]);
    total_examples = total_examples-bad_iter-1;

    int sadfjh;
    double av_feature_count = 0;
    for (ii=0; ii<total_examples; ii++){
        sadfjh = count_features2(&num_data[ii]);
        av_feature_count += sadfjh;
        // printf("%i ", sadfjh);
    }
    // printf("\n av_feature_count %f\n", av_feature_count/(total_examples-bad_iter-1));
    
    
    // print_num_data(&num_data[4464]);

    // printf("vocab->right = %s \n", vocab->feature);
    // print_data(&all_data[0]);
    // print_data(&all_data[29000]);
    // printf("%s, %u\n", "1829", get_feature_number(&vocab, "1829"));



    //find the distance between first example and rest
    double distance;

    //range each process will cover
    int range;

    // printf("%i, %i\n", range, total_examples);
    // printf("R, Min, Max = %i, %i, %i\n", rank, rank*range, (rank+1)*range);

    //     struct distance_results results;
    // results.example_num = 0;
    // results.distances = calloc(k, sizeof(double));
    // results.cat = calloc(k, sizeof(int));
    // results.example_nums = calloc(k, sizeof(int));

    // //struct used to calculate the mode of the k nearest neighbors
    // struct mode mod;
    // mod.count = calloc(k, sizeof(int));
    // mod.cat = calloc(k, sizeof(int));


   	//correct/total/answer
   	int c = 0;
    int total = 0;
    int answer;

    omp_set_dynamic(0); //Explicitly disable dynamic teams
    omp_set_num_threads(num_threads); //Specify thread count

    #pragma omp parallel \
            private(kk, ii, distance, answer) \
            reduction(+:c,total) \
            shared(num_data)
    {
        //store struct which keep track of the k nearest neighbors
        struct distance_results results;
        results.example_num = 0;
        results.distances = calloc(k, sizeof(double));
        results.cat = calloc(k, sizeof(int));
        results.example_nums = calloc(k, sizeof(int));

        //struct used to calculate the mode of the k nearest neighbors
        struct mode mod;
        mod.count = calloc(k, sizeof(int));
        mod.cat = calloc(k, sizeof(int));
    
        #pragma omp for
        for (kk=0; kk<total_examples; kk++){
            // printf("Thread = %i, Iter = %i, c = %i, total=%i\n", omp_get_thread_num(), kk, c, total);

        	//only test on test data
        	if (num_data[kk].example_num%train != 0){
        		continue;
        	}

        	if (num_data[kk].cat == 0){
        		continue;
        	}

        	results.correct_answer = num_data[kk].cat;
        	results.example_num = num_data[kk].example_num;
        	for (ii=0; ii<k; ii++){
        		results.distances[ii] = 0;
        		results.cat[ii] = 0;
        		mod.count[ii] = 0;
        		mod.cat[ii] = 0;
        	}

        	// print_num_data(&num_data[kk]);

        	//calc distance to neighbors
        	for (ii=0; ii<total_examples-1; ii++){
        		//don't calc distance to self
        		if (kk != ii){
                    //Eliminate bad data (examples with few words tend to have low distances
                    //reguardless of whether they are more similar...
                    if (num_data[ii].total_features >= 40){
                        distance = get_distance(&num_data[kk], &num_data[ii], num_words);
                        // if (distance < 2){
                        //  continue;
                        // }
                        // printf("%f ", distance);
                        if (num_data[ii].example_num > 0){
                            add_distance_to_results(&results, distance, k, 
                                                    num_data[ii].cat, num_data[ii].example_num);
                        }
    		    	}
        		}
    	    	
    	    }

    	    answer = calc_nearest_neighbor(&results, &mod, k);
    	    if (answer == results.correct_answer){
    	    	c += 1;
    	    }
    	    // printf("\n");
    	    // for (ii=0; ii<k; ii++){
    	    // 	printf("Distance, cat, example_num1, example_num2 = %2.2f, %i, %i, %i\n", 
    	    // 		results.distances[ii], results.cat[ii], results.example_num, results.example_nums[ii]);
    	    // }
    	    // else{
    	    	
    	    // }
    	    total += 1;

            if (verbose>0 && debug>0){
                printf("Thread = %i, Correct/Total = %i/%i  Answer/Correct = %i/%i\n", 
                    omp_get_thread_num(), c, total, answer, results.correct_answer);
            }
    	    
        }

        //Thread results
        #pragma omp barrier
        if (omp_get_thread_num() == 0){
            printf("/// Thread Results ///\n");
        }
        #pragma omp barrier
        printf("Thread = %i, Correct/Total = %i/%i\n", 
                omp_get_thread_num(), c, total);

        //free distance result
        free(results.distances);
        free(results.cat); 

        //free mode struct
        free(mod.count);
        free(mod.cat);
    }

    printf("/// Final Results ///\n");
    printf("Correct/Total = %i/%i\n", c, total);
    // printf("verbose = %i", verbose);


    

    ////free malloc calls////
    //free feature tree
    free_feature_tree(vocab);

    //free numeric data
    for (ii=0; ii<total_examples; ii++){
    	free(num_data[ii].array_of_features);
    }
    free(num_data);

    // //free vocab list
    // for (ii=0; ii<max_vocab; ii++){
    //     free(word_list[ii]);  
    // }
    // free(word_list);

    //free category list
    for (ii=0; ii<40; ii++){
        free(cat_list[ii]);  
    }
    free(cat_list);

    //free all_data list
    for (ii=0; ii<total_examples; ii++){
        
        for (jj=0; jj<num_words; jj++){
            free(all_data[ii].question[jj]);
        }
        free(all_data[ii].question);
        free(all_data[ii].cat);
    }
    free(all_data);

    //free var used to rean in csv
    free(csv_line);

    
}
Example #25
0
int main(int argc, char **argv)
{
  struct lsh_decode_key_options *options = make_lsh_decode_key_options();
  struct lsh_string *input;
  struct lsh_string *output;
  
  int out = STDOUT_FILENO;
  
  argp_parse(&main_argp, argc, argv, 0, NULL, options);

  if (options->file)
    {
      out = open(lsh_get_cstring(options->file),
                 O_WRONLY | O_CREAT, 0666);
      if (out < 0)
        {
          werror("Failed to open file `%S' for writing: %e.\n",
                 options->file, errno);
          return EXIT_FAILURE;
        }
    }

  input = io_read_file_raw(STDIN_FILENO, 3000);
  if (!input)
    {
      werror("Failed to read stdin: %e.\n", errno);
      return EXIT_FAILURE;
    }

  if (options->base64)
    {
      if (!lsh_string_base64_decode(input))
	{
          werror("Invalid base64 encoding.\n");

	  lsh_string_free(input);

          return EXIT_FAILURE;
        }
    }
  
  output = lsh_decode_key(input);
  lsh_string_free(input);

  if (!output)
    {
      werror("Invalid ssh2 key.\n");
      return EXIT_FAILURE;
    }
    
  if (!write_raw(out, STRING_LD(output)))
    {
      werror("Write failed: %e.\n", errno);
      return EXIT_FAILURE;
    }
  lsh_string_free(output);
  
  gc_final();
  
  return EXIT_SUCCESS;
}
Example #26
0
void
parse_commandline (int argc, char **argv)
{
  char next_arg, i, arg_error = 0;

  Log ("--[ PARSING COMMAND LINE ]--------------------------\n");

#if 0 // !defined(WIN32) && !defined(SOLARIS) && !defined(NGC) && !defined(PSP)
  argp_parse (&argp, argc, argv, 0, 0, &option);
#else
  next_arg = 0;
  for (i = 1; i < argc; i++)
    if (!next_arg)
      {
	if (argv[i][0] == '-')
	  {
	    if (strlen (argv[i]) == 2)
	      {
		switch (argv[i][1])
		  {
		  default:
		    next_arg = argv[i][1];
		    break;
		  }
	      }
	    else
	      arg_error |= set_arg (argv[i][1], (char *) &argv[i][2]);
	  }
	else
	  {
	    if (!cart_name[0])
	      {
		strcpy (cart_name, argv[i]);
		Log ("Setting card name to %s\n", cart_name);
		{
		  int x;
		  for (x = 0; x < strlen (cart_name); x++)
		    if (cart_name[x] == '\\')
		      cart_name[x] = '/';
		}
	      }
	    else if (!bmdefault)
	      {
		Log ("Setting backup mem file name to %s\n", argv[i]);
		bmdefault = argv[i];
	      }
	    else
	      {
		Log ("Unrecognized option : %s\n", argv[i]);
		arg_error = 1;
	      };
	  }
      }
    else
      {
	arg_error |= set_arg (next_arg, argv[i]);
	next_arg = 0;
      }

  if (next_arg)
    {
      Log ("No value for last arg : %c\n", next_arg);
      next_arg = 0;
      arg_error = 1;
    };

#endif

  Log ("End of parsing command line\n");

  video_driver = 0;

  if (use_eagle)
    video_driver = 1;
  else if (use_scanline)
    video_driver = 2;
}
Example #27
0
int main(int argc, char **argv)
{
	argp_parse(&argp, argc, argv, 0, 0, 0);

	return capture(dev_name, x_res, y_res, n_frames, out_dir);
}
Example #28
0
int main(int argc, char **argv)
{
	struct arguments args;
	int err, lnb = -1,idx = -1;
	int r;
	const struct argp argp = {
		.options = options,
		.parser = parse_opt,
		.doc = N_("scan DVB services using the channel file"),
		.args_doc = N_("<initial file>"),
	};

#ifdef ENABLE_NLS
	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);
#endif

	memset(&args, 0, sizeof(args));
	args.sat_number = -1;
	args.output = DEFAULT_OUTPUT;
	args.input_format = FILE_DVBV5;
	args.output_format = FILE_DVBV5;
	args.timeout_multiply = 1;
	args.adapter = (unsigned)-1;
	args.lna = LNA_AUTO;

	if (argp_parse(&argp, argc, argv, ARGP_NO_HELP | ARGP_NO_EXIT, &idx, &args)) {
		argp_help(&argp, stderr, ARGP_HELP_SHORT_USAGE, PROGRAM_NAME);
		return -1;
	}

	if (args.timeout_multiply == 0)
		args.timeout_multiply = 1;

	if (args.n_adapter == 1) {
		args.adapter_fe = args.adapter;
		args.adapter_dmx = args.adapter;
	}

	if (args.lnb_name) {
		lnb = dvb_sat_search_lnb(args.lnb_name);
		if (lnb < 0) {
			printf(_("Please select one of the LNBf's below:\n"));
			dvb_print_all_lnb();
			exit(1);
		} else {
			printf(_("Using LNBf "));
			dvb_print_lnb(lnb);
		}
	}

	if (idx < argc)
		args.confname = argv[idx];

	if (!args.confname || idx < 0) {
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}
	if ((args.input_format == FILE_ZAP) ||
		   (args.input_format == FILE_UNKNOWN) ||
		   (args.output_format == FILE_UNKNOWN)) {
		fprintf(stderr, _("ERROR: Please specify a valid format\n"));
		argp_help(&argp, stderr, ARGP_HELP_STD_HELP, PROGRAM_NAME);
		return -1;
	}

	r = asprintf(&args.demux_dev,
		 "/dev/dvb/adapter%i/demux%i", args.adapter_dmx, args.demux);
	if (r < 0) {
		fprintf(stderr, _("asprintf error\n") );
		return -1;
	}

	if (verbose)
		fprintf(stderr, _("using demux '%s'\n"), args.demux_dev);

	struct dvb_v5_fe_parms *parms = dvb_fe_open(args.adapter_fe,
						    args.frontend,
						    verbose, args.force_dvbv3);
	if (!parms) {
		free(args.demux_dev);
		return -1;
	}
	if (lnb >= 0)
		parms->lnb = dvb_sat_get_lnb(lnb);
	if (args.sat_number >= 0)
		parms->sat_number = args.sat_number % 3;
	parms->diseqc_wait = args.diseqc_wait;
	parms->freq_bpf = args.freq_bpf;
	parms->lna = args.lna;
	r = dvb_fe_set_default_country(parms, args.cc);
	if (r < 0)
		fprintf(stderr, _("Failed to set the country code:%s\n"), args.cc);

	timeout_flag = &parms->abort;
	signal(SIGTERM, do_timeout);
	signal(SIGINT, do_timeout);

	err = run_scan(&args, parms);

	dvb_fe_close(parms);
	free(args.demux_dev);

	return err;
}
int main(int argc, char **argv){
    ssh_session session;
    ssh_bind sshbind;
    ssh_message message;
    ssh_channel chan=0;
    char buf[2048];
    int auth=0;
    int shell=0;
    int i;
    int r;

    sshbind=ssh_bind_new();
    session=ssh_new();

    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY,
                                            KEYS_FOLDER "ssh_host_dsa_key");
    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY,
                                            KEYS_FOLDER "ssh_host_rsa_key");

#ifdef HAVE_ARGP_H
    /*
     * Parse our arguments; every option seen by parse_opt will
     * be reflected in arguments.
     */
    argp_parse (&argp, argc, argv, 0, 0, sshbind);
#else
    (void) argc;
    (void) argv;
#endif
#ifdef WITH_PCAP
    set_pcap(session);
#endif

    if(ssh_bind_listen(sshbind)<0){
        printf("Error listening to socket: %s\n", ssh_get_error(sshbind));
        return 1;
    }
    printf("Started sample libssh sshd on port %d\n", port);
    printf("You can login as the user %s with the password %s\n", SSHD_USER,
                                                            SSHD_PASSWORD);
    r = ssh_bind_accept(sshbind, session);
    if(r==SSH_ERROR){
      printf("Error accepting a connection: %s\n", ssh_get_error(sshbind));
      return 1;
    }
    if (ssh_handle_key_exchange(session)) {
        printf("ssh_handle_key_exchange: %s\n", ssh_get_error(session));
        return 1;
    }

    /* proceed to authentication */
    auth = authenticate(session);
    if (!auth || !authenticated) {
        printf("Authentication error: %s\n", ssh_get_error(session));
        ssh_disconnect(session);
        return 1;
    }


    /* wait for a channel session */
    do {
        message = ssh_message_get(session);
        if(message){
            if(ssh_message_type(message) == SSH_REQUEST_CHANNEL_OPEN &&
                    ssh_message_subtype(message) == SSH_CHANNEL_SESSION) {
                chan = ssh_message_channel_request_open_reply_accept(message);
                ssh_message_free(message);
                break;
            } else {
                ssh_message_reply_default(message);
                ssh_message_free(message);
            }
        } else {
            break;
        }
    } while(!chan);

    if(!chan) {
        printf("Error: cleint did not ask for a channel session (%s)\n",
                                                    ssh_get_error(session));
        ssh_finalize();
        return 1;
    }


    /* wait for a shell */
    do {
        message = ssh_message_get(session);
        if(message != NULL) {
            if(ssh_message_type(message) == SSH_REQUEST_CHANNEL &&
                    ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_SHELL) {
                shell = 1;
                ssh_message_channel_request_reply_success(message);
                ssh_message_free(message);
                break;
            }
            ssh_message_reply_default(message);
            ssh_message_free(message);
        } else {
            break;
        }
    } while(!shell);

    if(!shell) {
        printf("Error: No shell requested (%s)\n", ssh_get_error(session));
        return 1;
    }


    printf("it works !\n");
    do{
        i=ssh_channel_read(chan,buf, 2048, 0);
        if(i>0) {
            if(*buf == '' || *buf == '')
                    break;
            if(i == 1 && *buf == '\r')
                ssh_channel_write(chan, "\r\n", 2);
            else
                ssh_channel_write(chan, buf, i);
            if (write(1,buf,i) < 0) {
                printf("error writing to buffer\n");
                return 1;
            }
        }
    } while (i>0);
    ssh_channel_close(chan);
    ssh_disconnect(session);
    ssh_bind_free(sshbind);
#ifdef WITH_PCAP
    cleanup_pcap();
#endif
    ssh_finalize();
    return 0;
}
Example #30
0
int main(int argc, char **argv)
{
	struct arguments arguments;

	arguments.action = 0;
	arguments.no_favorite_repo = 0;
	arguments.no_favorite_version = 0;
	arguments.no_deps = 1;
	arguments.all = 0;
	arguments.args = NULL;

	if (argc < 2) {
		char *fake_arg[2];
		fake_arg[0] = "ilenia";
		fake_arg[1] = "--help";
		argp_parse(&argp, 2, fake_arg, 0, 0, &arguments);
	}

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

	if (parse_ileniarc() != 0)
		return (EXIT_FAILURE);

	ilenia_repos = build_repolist();

	if (arguments.action == ACT_CACHE) {
		FILE *file;
		if ((file = fopen(CACHE, "w")))
			fclose(file);
	}

	ilenia_favoriterepo = get_favorite(FAVORITE_REPO);
	ilenia_favoriteversion = get_favorite(FAVORITE_VERSION);
	ilenia_aliases = aliaseslist_build();
	ilenia_ports = lsports();
	ilenia_pkgs = lspkgs();
	ilenia_favoritepkgmk = pkgmklist_build();

	if (arguments.action > 21 || arguments.action == 0)
		error("%s", "please perform an action at a time!");

	int confront_options =
	    arguments.no_favorite_repo + arguments.no_favorite_version;

	int update_options = arguments.no_deps;
	if (confront_options)
		update_options = confront_options * update_options;

	int status = EXIT_SUCCESS;

	if (arguments.action == ACT_UPDATE) {
		if (arguments.args == NULL) {
			status = update_all_repos();
			return (EXIT_SUCCESS);
		}
		while (arguments.args) {
			status = update_repo(arguments.args->data);
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_LIST) {
		if (arguments.args == NULL) {
			pkglist_print(ilenia_ports);
			return (EXIT_SUCCESS);
		}
		while (arguments.args) {
			if (repolist_exists(arguments.args->data,
					    ilenia_repos)) {
				warning("repository %s not found!\n",
					arguments.args->data);
				arguments.args = arguments.args->next;
				continue;
			}
			pkglist_print(pkglist_select_from_repo
				      (arguments.args->data,
				       ilenia_ports));
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_SEARCH) {
		if (arguments.args == NULL)
			error("action search requires an argument!");
		while (arguments.args) {
			pkglist_print(pkglist_find_like
				      (arguments.args->data,
				       ilenia_ports));
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_INFO) {
		if (arguments.args == NULL)
			error("action info requires an argument!");
		while (arguments.args) {
			info(arguments.args->data, confront_options);
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_DIFF)
		pkglist_confront(DIFF, confront_options, 1);

	if (arguments.action == ACT_UPDATED)
		pkglist_confront(UPDATED, confront_options, 1);

	if (arguments.action == ACT_DEPENDENCIES) {
		if (arguments.args == NULL)
			error("action dependencies requires an argument!");
		while (arguments.args) {
			print_dependencies(arguments.args->data);
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_UPDATE_PKG) {
		if (arguments.args == NULL) {
			status = update_system(update_options);
			return status;
		}
		while (arguments.args) {
			status =
			    update_pkg(update_options,
				       arguments.args->data);
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_DEPENDENTS) {
		if (arguments.args == NULL)
			error("action dependents requires an argument!");
		while (arguments.args) {
			print_dependents(arguments.args->data,
					 arguments.all);
			arguments.args = arguments.args->next;
		}
	}

	if (arguments.action == ACT_REMOVE) {
		if (arguments.args == NULL)
			error("action remove requires an argument!");
		while (arguments.args) {
			status =
			    remove_pkg(arguments.args->data,
				       arguments.no_deps, arguments.all);
			arguments.args = arguments.args->next;
		}
	}


	if (arguments.action == ACT_REPOSITORY_LIST) {
		while (ilenia_repos != NULL) {
			printf("name %s path %s\n", ilenia_repos->name,
			       ilenia_repos->path);
			ilenia_repos = ilenia_repos->next;
		}
	}

	return status;
}