Ejemplo n.º 1
0
int chkForInitialConfig(const gchar *cfgdir, const gchar *cfgfile) {
  if(g_file_test(cfgdir, G_FILE_TEST_IS_DIR) == FALSE) {
    if(g_mkdir_with_parents (cfgdir, S_IRWXU)) return(1);
  }

  dump_config(cfgdir, "apt-dater.xml", (gchar *)apt_dater_xml, apt_dater_xml_len);

  /* Convert legacy hosts.conf to new hosts.xml using external helper script. */
  gchar *fnold = g_strdup_printf("%s/%s", cfgdir, "hosts.conf");
  gchar *fnnew = g_strdup_printf("%s/%s", cfgdir, "hosts.xml");
  if((g_file_test(fnnew, G_FILE_TEST_IS_REGULAR|G_FILE_TEST_EXISTS) == FALSE) &&
     (g_file_test(fnold, G_FILE_TEST_IS_REGULAR|G_FILE_TEST_EXISTS) == TRUE)) {

    gchar *argv[3] = {PKGLIBDIR"/hosts2xml", "hosts2xml", NULL};
    GError *error = NULL;
    if(g_spawn_sync(g_getenv ("HOME"), argv, NULL, G_SPAWN_CHILD_INHERITS_STDIN, NULL, NULL, NULL, NULL, NULL, &error) == FALSE) {
      g_warning("%s", error->message);
      g_clear_error (&error);
    }
  }

  dump_config(cfgdir, "hosts.xml", (gchar *)hosts_xml, hosts_xml_len);
#ifdef FEAT_TMUX
  dump_config(cfgdir, "tmux.conf", (gchar *)tmux_conf, tmux_conf_len);
#else
  dump_config(cfgdir, "screenrc", (gchar *)screenrc, screenrc_len);
#endif

 return(0);
}
Ejemplo n.º 2
0
int main(int argc, char* argv[])
{
    if (ini_parse("test.ini", handler, &Config) < 0)
        printf("Can't load 'test.ini', using defaults\n");
    dump_config(&Config);
    return 0;
}
Ejemplo n.º 3
0
static int
debug_config(int ac, char **av)
{
	struct mfi_config_data *config;
	int error, fd;

	if (ac != 1) {
		warnx("debug: extra arguments");
		return (EINVAL);
	}

	fd = mfi_open(mfi_unit);
	if (fd < 0) {
		error = errno;
		warn("mfi_open");
		return (error);
	}

	/* Get the config from the controller. */
	if (mfi_config_read(fd, &config) < 0) {
		error = errno;
		warn("Failed to get config");
		close(fd);
		return (error);
	}

	/* Dump out the configuration. */
	dump_config(fd, config);
	free(config);
	close(fd);

	return (0);
}
Ejemplo n.º 4
0
int platform_init(void *ctx)
{
	extern struct platform *__start_platforms,  *__stop_platforms;
	struct platform **p;

	platform_ctx = talloc_new(ctx);

	for (p = &__start_platforms; p < &__stop_platforms; p++) {
		pb_debug("%s: Try platform %s\n", __func__, (*p)->name);
		if (!(*p)->probe(*p, platform_ctx))
			continue;
		platform = *p;
		break;
	}

	config = talloc(platform_ctx, struct config);
	config_set_defaults(config);

	if (platform) {
		pb_log("Detected platform type: %s\n", platform->name);
		if (platform->load_config)
			platform->load_config(platform, config);
	} else {
		pb_log("No platform type detected, some platform-specific "
				"functionality will be disabled\n");
	}

	dump_config(config);

	return 0;
}
Ejemplo n.º 5
0
struct nhlt_specific_cfg
*skl_get_ep_blob(struct skl *skl, u32 instance, u8 link_type,
			u8 s_fmt, u8 num_ch, u32 s_rate, u8 dirn)
{
	struct nhlt_fmt *fmt;
	struct nhlt_endpoint *epnt;
	struct hdac_bus *bus = ebus_to_hbus(&skl->ebus);
	struct device *dev = bus->dev;
	struct nhlt_specific_cfg *sp_config;
	struct nhlt_acpi_table *nhlt = (struct nhlt_acpi_table *)skl->nhlt;
	u16 bps = (s_fmt == 16) ? 16 : 32;
	u8 j;

	dump_config(dev, instance, link_type, s_fmt, num_ch, s_rate, dirn, bps);

	epnt = (struct nhlt_endpoint *)nhlt->desc;

	dev_dbg(dev, "endpoint count =%d\n", nhlt->endpoint_count);

	for (j = 0; j < nhlt->endpoint_count; j++) {
		if (skl_check_ep_match(dev, epnt, instance, link_type, dirn)) {
			fmt = (struct nhlt_fmt *)(epnt->config.caps +
						 epnt->config.size);
			sp_config = skl_get_specific_cfg(dev, fmt, num_ch,
							s_rate, bps, link_type);
			if (sp_config)
				return sp_config;
		}

		epnt = (struct nhlt_endpoint *)((u8 *)epnt + epnt->length);
	}

	return NULL;
}
Ejemplo n.º 6
0
static int test_init_default_config(void)
{
    _testembed_Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 7
0
void sig_debug(int d)
{
	fprintf(stderr, "config:\n");
	dump_config(2);
	fprintf(stderr, "ip-routes:\n");
	dump_ip_routes(2, 0);
	fprintf(stderr, "ax25-routes:\n");
	dump_ax25_routes(2, 0);
	signal(SIGUSR1, sig_debug);
}
Ejemplo n.º 8
0
int list_setups(void){ 
	putText("current selected setup: ",80);
        putHex((unsigned int)ddr_sel);
	putText("\n\nTiming\n------\n",40);
	dump_timing(ddr_timing_parameters);
	
	putText("\n\nConfiguration\n-------------\n",40);
	dump_config(ddr_config_parameters);
	return 0; 
};
Ejemplo n.º 9
0
int
main( int argc, char** argv )
    {
      /* Handle command-line arguments. */
      parse_args( argc, argv );

      dump_config(stderr);

      return 0;
    }
Ejemplo n.º 10
0
static int test_init_env(void)
{
    /* Test initialization from environment variables */
    Py_IgnoreEnvironmentFlag = 0;
    test_init_env_putenvs();
    _testembed_Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 11
0
int main(int argc, char** argv)
{
	if(argc < 2) 
		die("Bad call\n");

	inittab = argv[1];
	if(configure(STRICT))
		die("Failed to compile inittab\n");

	dump_config((struct config*)newblock.addr);

	return 0;
}
Ejemplo n.º 12
0
/**
 * icmd_set - Parse 'set' command to display config - Implements ::icommand_t
 */
static enum CommandResult icmd_set(struct Buffer *buf, struct Buffer *s,
                                   unsigned long data, struct Buffer *err)
{
  char tempfile[PATH_MAX];
  mutt_mktemp(tempfile, sizeof(tempfile));

  FILE *fp_out = mutt_file_fopen(tempfile, "w");
  if (!fp_out)
  {
    mutt_buffer_addstr(err, _("Could not create temporary file"));
    return MUTT_CMD_ERROR;
  }

  if (mutt_str_strcmp(s->data, "set all") == 0)
  {
    dump_config(Config, CS_DUMP_STYLE_NEO, 0, fp_out);
  }
  else if (mutt_str_strcmp(s->data, "set") == 0)
  {
    dump_config(Config, CS_DUMP_STYLE_NEO, CS_DUMP_ONLY_CHANGED, fp_out);
  }
  else
  {
    mutt_file_fclose(&fp_out);
    return MUTT_CMD_ERROR;
  }

  mutt_file_fclose(&fp_out);

  struct Pager info = { 0 };
  if (mutt_pager("set", tempfile, 0, &info) == -1)
  {
    mutt_buffer_addstr(err, _("Could not create temporary file"));
    return MUTT_CMD_ERROR;
  }

  return MUTT_CMD_SUCCESS;
}
Ejemplo n.º 13
0
static int
dump(int ac, char **av)
{
	struct mfi_config_data *config;
	char buf[64];
	size_t len;
	int error, fd;

	if (ac != 1) {
		warnx("dump: extra arguments");
		return (EINVAL);
	}

	fd = mfi_open(mfi_unit);
	if (fd < 0) {
		error = errno;
		warn("mfi_open");
		return (error);
	}

	/* Get the stashed copy of the last dcmd from the driver. */
	snprintf(buf, sizeof(buf), "dev.mfi.%d.debug_command", mfi_unit);
	if (sysctlbyname(buf, NULL, &len, NULL, 0) < 0) {
		error = errno;
		warn("Failed to read debug command");
		if (error == ENOENT)
			error = EOPNOTSUPP;
		close(fd);
		return (error);
	}

	config = malloc(len);
	if (config == NULL) {
		warnx("malloc failed");
		close(fd);
		return (ENOMEM);
	}
	if (sysctlbyname(buf, config, &len, NULL, 0) < 0) {
		error = errno;
		warn("Failed to read debug command");
		free(config);
		close(fd);
		return (error);
	}
	dump_config(fd, config);
	free(config);
	close(fd);

	return (0);
}
Ejemplo n.º 14
0
static int test_init_dev_mode(void)
{
    _PyCoreConfig config = _PyCoreConfig_INIT;
    putenv("PYTHONFAULTHANDLER=");
    putenv("PYTHONMALLOC=");
    config.dev_mode = 1;
    config.program_name = L"./_testembed";
    _PyInitError err = _Py_InitializeFromConfig(&config);
    if (_Py_INIT_FAILED(err)) {
        _Py_FatalInitError(err);
    }
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 15
0
static int test_init_global_config(void)
{
    /* FIXME: test Py_IgnoreEnvironmentFlag */

    putenv("PYTHONUTF8=0");
    Py_UTF8Mode = 1;

    /* Test initialization from global configuration variables (Py_xxx) */
    Py_SetProgramName(L"./globalvar");

    /* Py_IsolatedFlag is not tested */
    Py_NoSiteFlag = 1;
    Py_BytesWarningFlag = 1;

    putenv("PYTHONINSPECT=");
    Py_InspectFlag = 1;

    putenv("PYTHONOPTIMIZE=0");
    Py_InteractiveFlag = 1;

    putenv("PYTHONDEBUG=0");
    Py_OptimizeFlag = 2;

    /* Py_DebugFlag is not tested */

    putenv("PYTHONDONTWRITEBYTECODE=");
    Py_DontWriteBytecodeFlag = 1;

    putenv("PYTHONVERBOSE=0");
    Py_VerboseFlag = 1;

    Py_QuietFlag = 1;
    Py_NoUserSiteDirectory = 1;

    putenv("PYTHONUNBUFFERED=");
    Py_UnbufferedStdioFlag = 1;

    Py_FrozenFlag = 1;

    /* FIXME: test Py_LegacyWindowsFSEncodingFlag */
    /* FIXME: test Py_LegacyWindowsStdioFlag */

    Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 16
0
int
main (int argc, char *argv[])
{

  const char *const fname = "/etc/X11/xawtvrc";
  RcFile conf;
  FILE *cfg;

  if (rcfileExists ("adfs/sddr/s/df/s"))
  {
    puts ("exists");
  }

  if (rcfileCreate ("adfs/sddr/s/df/s"))
  {                             //succeed
    puts ("create");
  }
  if (rcfileCreate ("/home/klammerj/adfs/sddr/s/df/s"))
  {                             //succeed
    puts ("create2");
  }

  if (rcfileCreate ("./adf3/sddr/s/df/s"))
  {                             //want this to succeed(on the first try..)
    puts ("create3");
  }

  if (rcfileCreate ("./adf3/sddr/s/ds/"))
  {                             //want this to fail
    puts ("create4");           //this should show up(on linux, not on win...)
  }


  if (rcfileParse (fname, &conf))
  {
    fprintf (stderr, "parse\n");
    return 1;
  }
  dump_config (&conf);

  if (rcfileClear (&conf))
  {
    fprintf (stderr, "clear\n");
  }
}
Ejemplo n.º 17
0
void dump_config(monikor_config_dict_t *dict) {
  for (; dict; dict = dict->next) {
    switch (dict->type) {
      case MONIKOR_CFG_DICT:
        printf("dict %s\n", dict->key);
        dump_config(dict->value.dict);
        break;
      case MONIKOR_CFG_LIST:
        printf("list %s: ", dict->key);
        strl_apply(dict->value.list, dump_config_list_elm);
        printf("\n");
        break;
      case MONIKOR_CFG_SCALAR:
        printf("%s = %s\n", dict->key, dict->value.value);
        break;
      default:
        printf("unknown\n");
        break;
    }
  }
}
Ejemplo n.º 18
0
static void save_sample_config ( const char *name )
{
#ifdef __EMSCRIPTEN__
	DEBUGPRINT("CONFIG: no configuration is saved in case of emscripten." NL);
#else
	char path[PATH_MAX + 1];
	FILE *f = open_emu_file(name, "r", path);
	if (f) {
		fclose(f);
		DEBUGPRINT("CONFIG: sample configuration %s (%s) already exists, skipping to create." NL, name, path);
		return;
	}
	f = open_emu_file(name, "w", path);
	if (f) {
		dump_config(f);
		fclose(f);
		INFO_WINDOW("Note: created sample config file %s", path);
	} else
		INFO_WINDOW("Note: cannot create sample config file %s", path);
#endif
}
Ejemplo n.º 19
0
int config_set(struct config *newconfig)
{
	int rc;

	if (!platform || !platform->save_config)
		return -1;

	if (newconfig == config)
		return 0;

	pb_log("new configuration data received\n");
	dump_config(newconfig);

	rc = platform->save_config(platform, newconfig);

	if (!rc)
		config = talloc_steal(platform_ctx, newconfig);
	else
		pb_log("error saving new configuration; changes lost\n");

	return rc;
}
Ejemplo n.º 20
0
static int test_init_isolated(void)
{
    /* Test _PyCoreConfig.isolated=1 */
    _PyCoreConfig config = _PyCoreConfig_INIT;

    /* Set coerce_c_locale and utf8_mode to not depend on the locale */
    config.coerce_c_locale = 0;
    config.utf8_mode = 0;
    /* Use path starting with "./" avoids a search along the PATH */
    config.program_name = L"./_testembed";

    Py_IsolatedFlag = 0;
    config.isolated = 1;

    test_init_env_putenvs();
    _PyInitError err = _Py_InitializeFromConfig(&config);
    if (_Py_INIT_FAILED(err)) {
        _Py_FatalInitError(err);
    }
    dump_config();
    Py_Finalize();
    return 0;
}
Ejemplo n.º 21
0
Archivo: main.c Proyecto: CoiLock/uhub
int check_configuration(int dump)
{
	struct hub_config configuration;
	int ret = read_config(arg_config, &configuration, 0);

	if (dump)
	{
		if (ret != -1)
		{
			dump_config(&configuration, dump > 1);
		}
		return 0;
	}

	if (ret == -1)
	{
		fprintf(stderr, "ERROR\n");
        	return 1;
	}

	fprintf(stdout, "OK\n");
	return 0;
}
Ejemplo n.º 22
0
Archivo: main.c Proyecto: nats/nbdkit
int
main (int argc, char *argv[])
{
  int c;
  int option_index;
  int help = 0, version = 0;

  tls_init ();

  for (;;) {
    c = getopt_long (argc, argv, short_options, long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
    case 0:                     /* options which are long only */
      if (strcmp (long_options[option_index].name, "dump-config") == 0) {
        dump_config ();
        exit (EXIT_SUCCESS);
      }
      else if (strcmp (long_options[option_index].name, "run") == 0) {
        run = optarg;
        foreground = 1;
      }
      else {
        fprintf (stderr, "%s: unknown long option: %s (%d)\n",
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'f':
      foreground = 1;
      break;

    case 'g':
      group = optarg;
      break;

    case 'i':
      ipaddr = optarg;
      break;

    case 'n':
      newstyle = 1;
      break;

    case 'o':
      /* XXX When we add support for exportnames, we will need to
       * ensure that the user does not use -o + --export.
       */
      newstyle = 0;
      break;

    case 'P':
      pidfile = nbdkit_absolute_path (optarg);
      if (pidfile == NULL)
        exit (EXIT_FAILURE);
      break;

    case 'p':
      port = optarg;
      break;

    case 'r':
      readonly = 1;
      break;

    case 's':
      listen_stdin = 1;
      break;

    case 'U':
      if (strcmp (optarg, "-") == 0)
        unixsocket = make_random_fifo ();
      else
        unixsocket = nbdkit_absolute_path (optarg);
      if (unixsocket == NULL)
        exit (EXIT_FAILURE);
      break;

    case 'u':
      user = optarg;
      break;

    case 'v':
      verbose = 1;
      break;

    case 'V':
      version = 1;
      break;

    case HELP_OPTION:
      help = 1;
      break;

    default:
      usage ();
      exit (EXIT_FAILURE);
    }
  }

  /* No extra parameters. */
  if (optind >= argc) {
    if (help) {
      usage ();
      exit (EXIT_SUCCESS);
    }
    if (version) {
      display_version ();
      exit (EXIT_SUCCESS);
    }

    /* Otherwise this is an error. */
    fprintf (stderr,
             "%s: no plugins given on the command line.\nRead nbdkit(1) for documentation.\n",
             program_name);
    exit (EXIT_FAILURE);
  }

  /* Remaining command line arguments define the plugins and plugin
   * configuration.  If --help or --version was specified, we still
   * partially parse these in order that we can display the per-plugin
   * help/version information.  In future (when the new protocol and
   * export names are permitted) we will allow multiple plugins to be
   * given, but at the moment only one plugin is allowed.
   */
  while (optind < argc) {
    const char *filename = argv[optind];
    char *p;

    open_plugin_so (filename);

    /* Find key=value configuration parameters for this plugin. */
    ++optind;
    while (optind < argc && (p = strchr (argv[optind], '=')) != NULL) {
      if (help || version)
        continue;

      *p = '\0';
      plugin_config (argv[optind], p+1);

      ++optind;
    }

    if (help) {
      usage ();
      printf ("\n%s:\n\n", filename);
      plugin_usage ();
      exit (EXIT_SUCCESS);
    }

    if (version) {
      display_version ();
      plugin_version ();
      exit (EXIT_SUCCESS);
    }

    plugin_config_complete ();

    /* If we supported export names, then we'd continue in the loop
     * here, but at the moment only one plugin may be used per server
     * so exit if there are any more.
     */
    ++optind;
    if (optind < argc) {
      fprintf (stderr, "%s: this server only supports a single plugin\n",
               program_name);
      exit (EXIT_FAILURE);
    }
  }

  start_serving ();

  plugin_cleanup ();

  free (unixsocket);
  free (pidfile);

  if (random_fifo) {
    unlink (random_fifo);
    free (random_fifo);
  }

  if (random_fifo_dir) {
    rmdir (random_fifo_dir);
    free (random_fifo_dir);
  }

  exit (EXIT_SUCCESS);
}
Ejemplo n.º 23
0
static int
foreign_show_cfg(int fd, uint32_t opcode, uint8_t cfgidx, int diagnostic)
{
	struct mfi_config_data *config;
	char prefix[26];
	int error;
	uint8_t mbox[4];

	bzero(mbox, sizeof(mbox));
	mbox[0] = cfgidx;
	if (mfi_config_read_opcode(fd, opcode, &config, mbox, sizeof(mbox)) < 0) {
		error = errno;
		warn("Failed to get foreign config %d", error);
		close(fd);
		return (error);
	}

	if (opcode == MFI_DCMD_CFG_FOREIGN_PREVIEW)
		sprintf(prefix, "Foreign configuration preview %d", cfgidx);
	else
		sprintf(prefix, "Foreign configuration %d", cfgidx);
	/*
	 * MegaCli uses DCMD opcodes: 0x03100200 (which fails) followed by
	 * 0x1a721880 which returns what looks to be drive / volume info
	 * but we have no real information on what these are or what they do
	 * so we're currently relying solely on the config returned above
	 */
	if (diagnostic)
		dump_config(fd, config, prefix);
	else {
		char *ld_list;
		int i;

		ld_list = (char *)(config->array);

        	printf("%s: %d arrays, %d volumes, %d spares\n", prefix, 
		       config->array_count, config->log_drv_count,
		       config->spares_count);


		for (i = 0; i < config->array_count; i++)
			 ld_list += config->array_size;

		for (i = 0; i < config->log_drv_count; i++) {
        		const char *level;
        		char size[6], stripe[5];
			struct mfi_ld_config *ld;

			ld = (struct mfi_ld_config *)ld_list;

        		format_stripe(stripe, sizeof(stripe),
            			ld->params.stripe_size);
			/*
			 * foreign configs don't seem to have a secondary raid level
			 * but, we can use span depth here as if a LD spans multiple
			 * arrays of disks (2 raid 1 sets for example), we will have an
			 * indication based on the spam depth. swb
			 */ 
        		level = mfi_raid_level(ld->params.primary_raid_level,
            					(ld->params.span_depth - 1));

        		humanize_number(size, sizeof(size), ld->span[0].num_blocks * 512,
            			"", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);

			printf(" ID%d ", i);
              		printf("(%6s) %-8s |",
				size, level);
			printf("volume spans %d %s\n",	ld->params.span_depth,
							(ld->params.span_depth > 1) ? "arrays" : "array");
			for (int j = 0; j < ld->params.span_depth; j++) {
				char *ar_list;
				struct mfi_array *ar;
				uint16_t device_id;

				printf("      array %u @ ", ld->span[j].array_ref);
        			humanize_number(size, sizeof(size), ld->span[j].num_blocks * 512,
            				"", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
				
				printf("(%6s)\n",size);
				ar_list = (char *)config->array + (ld->span[j].array_ref * config->array_size);

				ar = (struct mfi_array *)ar_list;
				for (int k = 0; k < ar->num_drives; k++) {
					device_id = ar->pd[k].ref.v.device_id;
					if (device_id == 0xffff)
						printf("        drive MISSING\n");
					else {
						printf("        drive %u %s\n", device_id,
			    				mfi_pdstate(ar->pd[k].fw_state));
					}
				}

			}
			ld_list += config->log_drv_size;
		}
	}

	free(config);

	return (0);
}
Ejemplo n.º 24
0
int
util_dump(WT_SESSION *session, int argc, char *argv[])
{
	WT_CURSOR *cursor;
	WT_DECL_RET;
	size_t len;
	int ch, i;
	bool hex, json, reverse;
	char *checkpoint, *config, *name;

	hex = json = reverse = false;
	checkpoint = config = name = NULL;
	while ((ch = __wt_getopt(progname, argc, argv, "c:f:jrx")) != EOF)
		switch (ch) {
		case 'c':
			checkpoint = __wt_optarg;
			break;
		case 'f':			/* output file */
			if (freopen(__wt_optarg, "w", stdout) == NULL)
				return (util_err(
				    session, errno, "%s: reopen", __wt_optarg));
			break;
		case 'j':
			json = true;
			break;
		case 'r':
			reverse = true;
			break;
		case 'x':
			hex = true;
			break;
		case '?':
		default:
			return (usage());
		}
	argc -= __wt_optind;
	argv += __wt_optind;

	/* -j and -x are incompatible. */
	if (hex && json) {
		fprintf(stderr,
		    "%s: the -j and -x dump options are incompatible\n",
		    progname);
		goto err;
	}

	/* The remaining argument is the uri. */
	if (argc < 1 || (argc != 1 && !json))
		return (usage());

	if (json &&
	    ((ret = dump_json_begin(session)) != 0 ||
	    (ret = dump_prefix(session, hex, json)) != 0))
		goto err;

	for (i = 0; i < argc; i++) {
		if (json && i > 0)
			if ((ret = dump_json_separator(session)) != 0)
				goto err;
		free(name);
		name = NULL;

		if ((name = util_name(session, argv[i], "table")) == NULL)
			goto err;

		if (dump_config(session, name, hex, json) != 0)
			goto err;

		len =
		    checkpoint == NULL ? 0 : strlen("checkpoint=") +
		    strlen(checkpoint) + 1;
		len += strlen(json ? "dump=json" :
		    (hex ? "dump=hex" : "dump=print"));
		if ((config = malloc(len + 10)) == NULL)
			goto err;
		if (checkpoint == NULL)
			config[0] = '\0';
		else {
			(void)strcpy(config, "checkpoint=");
			(void)strcat(config, checkpoint);
			(void)strcat(config, ",");
		}
		(void)strcat(config, json ? "dump=json" :
		    (hex ? "dump=hex" : "dump=print"));
		if ((ret = session->open_cursor(
		    session, name, NULL, config, &cursor)) != 0) {
			fprintf(stderr, "%s: cursor open(%s) failed: %s\n",
			    progname, name, session->strerror(session, ret));
			goto err;
		}

		if ((ret = dump_record(cursor, reverse, json)) != 0)
			goto err;
		if (json && (ret = dump_json_table_end(session)) != 0)
			goto err;
	}
	if (json && ((ret = dump_json_end(session)) != 0))
		goto err;

	if (0) {
err:		ret = 1;
	}

	free(config);
	free(name);

	return (ret);
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
    int                 res, last_sig, rp_cache_count;
    char               *locale;
    pid_t               old_pid;

    fko_srv_options_t   opts;

    while(1)
    {
        /* Handle command line
        */
        config_init(&opts, argc, argv);

        /* Process any options that do their thing and exit. */

        /* Kill the currently running fwknopd?
        */
        if(opts.kill == 1)
        {
            old_pid = get_running_pid(&opts);

            if(old_pid > 0)
            {
                res = kill(old_pid, SIGTERM);
                if(res == 0)
                {
                    fprintf(stderr, "Killed fwknopd (pid=%i)\n", old_pid);
                    exit(EXIT_SUCCESS);
                }
                else
                {
                    perror("Unable to kill fwknop: ");
                    exit(EXIT_FAILURE);
                }
            }
            else
            {
                fprintf(stderr, "No running fwknopd detected.\n");
                exit(EXIT_FAILURE);
            }
        }

        /* Status of the currently running fwknopd?
        */
        if(opts.status == 1)
        {
            old_pid = write_pid_file(&opts);

            if(old_pid > 0)
                fprintf(stderr, "Detected fwknopd is running (pid=%i).\n", old_pid);
            else
                fprintf(stderr, "No running fwknopd detected.\n");

            exit(EXIT_SUCCESS);
        }

        /* Restart the currently running fwknopd?
        */
        if(opts.restart == 1 || opts.status == 1)
        {
            old_pid = get_running_pid(&opts);

            if(old_pid > 0)
            {
                res = kill(old_pid, SIGHUP);
                if(res == 0)
                {
                    fprintf(stderr, "Sent restart signal to fwknopd (pid=%i)\n", old_pid);
                    exit(EXIT_SUCCESS);
                }
                else
                {
                    perror("Unable to send signal to fwknop: ");
                    exit(EXIT_FAILURE);
                }
            }
            else
            {
                fprintf(stderr, "No running fwknopd detected.\n");
                exit(EXIT_FAILURE);
            }
        }

        /* Initialize logging.
        */
        init_logging(&opts);

#if HAVE_LOCALE_H 
        /* Set the locale if specified. 
        */ 
        if(opts.config[CONF_LOCALE] != NULL
          && strncasecmp(opts.config[CONF_LOCALE], "NONE", 4) != 0) 
        { 
            locale = setlocale(LC_ALL, opts.config[CONF_LOCALE]); 
 
            if(locale == NULL) 
            { 
                log_msg(LOG_ERR, 
                    "WARNING: Unable to set locale to '%s'.", 
                    opts.config[CONF_LOCALE] 
                ); 
            } 
            else 
            { 
                if(opts.verbose) 
                    log_msg(LOG_INFO, 
                        "Locale set to '%s'.", opts.config[CONF_LOCALE] 
                    ); 
            } 
        } 
#endif 

        /* Make sure we have a valid run dir and path leading to digest file
         * in case it configured to be somewhere other than the run dir.
        */
        check_dir_path((const char *)opts.config[CONF_FWKNOP_RUN_DIR], "Run", 0);
#if USE_FILE_CACHE
        check_dir_path((const char *)opts.config[CONF_DIGEST_FILE], "Run", 1);
#else
        check_dir_path((const char *)opts.config[CONF_DIGEST_DB_FILE], "Run", 1);
#endif

        /* Process the access.conf file.
        */
        parse_access_file(&opts);

        /* Show config (including access.conf vars) and exit dump config was
         * wanted.
        */
        if(opts.dump_config == 1)
        {
            dump_config(&opts);
            dump_access_list(&opts);
            exit(EXIT_SUCCESS);
        }

        /* Initialize the firewall rules handler based on the fwknopd.conf
         * file, but (for iptables firewalls) don't flush any rules or create
         * any chains yet.  This allows us to dump the current firewall rules
         * via fw_rules_dump() in --fw-list mode before changing around any rules
         * of an existing fwknopd process.
        */
        fw_config_init(&opts);

        if(opts.fw_list == 1)
        {
            fw_dump_rules(&opts);
            exit(EXIT_SUCCESS);
        }

        /* If we are a new process (just being started), proceed with normal
         * start-up.  Otherwise, we are here as a result of a signal sent to an
         * existing process and we want to restart.
        */
        if(get_running_pid(&opts) != getpid())
        {
            /* If foreground mode is not set, the fork off and become a daemon.
            * Otherwise, attempt to get the pid file lock and go on.
            */
            if(opts.foreground == 0)
            {
                daemonize_process(&opts);
            }
            else
            {
                old_pid = write_pid_file(&opts);
                if(old_pid > 0)
                {
                    fprintf(stderr,
                        "* An instance of fwknopd is already running: (PID=%i).\n", old_pid
                    );

                    exit(EXIT_FAILURE);
                }
                else if(old_pid < 0)
                {
                    fprintf(stderr, "* PID file error. The lock may not be effective.\n");
                }
            }

            log_msg(LOG_INFO, "Starting %s", MY_NAME);
        }
        else
        {
            log_msg(LOG_INFO, "Re-starting %s", MY_NAME);
        }

        if(opts.verbose > 1 && opts.foreground)
        {
            dump_config(&opts);
            dump_access_list(&opts);
        }

        /* Initialize the digest cache for replay attack detection (either
         * with dbm support or with the default simple cache file strategy)
         * if so configured.
        */
        if(strncasecmp(opts.config[CONF_ENABLE_DIGEST_PERSISTENCE], "Y", 1) == 0)
        {
            rp_cache_count = replay_cache_init(&opts);

            if(rp_cache_count < 0)
            {
                log_msg(LOG_WARNING,
                    "Error opening digest cache file. Incoming digests will not be remembered."
                );
                strlcpy(opts.config[CONF_ENABLE_DIGEST_PERSISTENCE], "N", 2);
            }

            if(opts.verbose)
                log_msg(LOG_ERR,
                    "Using Digest Cache: '%s' (entry count = %i)",
#if USE_FILE_CACHE
                    opts.config[CONF_DIGEST_FILE], rp_cache_count
#else
                    opts.config[CONF_DIGEST_DB_FILE], rp_cache_count
#endif
                );
        }

        /* Prepare the firewall - i.e. flush any old rules and (for iptables)
         * create fwknop chains.
        */
        fw_initialize(&opts);

        /* If the TCP server option was set, fire it up here.
        */
        if(strncasecmp(opts.config[CONF_ENABLE_TCP_SERVER], "Y", 1) == 0)
        {
            if(atoi(opts.config[CONF_TCPSERV_PORT]) <= 0
              || atoi(opts.config[CONF_TCPSERV_PORT]) >  65535)
            {
                log_msg(LOG_WARNING,
                    "WARNING: ENABLE_TCP_SERVER is set, but TCPSERV_PORT is not valid. TCP server not started!"
                );
            }
            else
            {
                run_tcp_server(&opts);
            }
        }

        /* Intiate pcap capture mode...
        */
        pcap_capture(&opts);

        if(got_signal) {
            last_sig   = got_signal;
            got_signal = 0;

            if(got_sighup)
            {
                log_msg(LOG_WARNING, "Got SIGHUP.  Re-reading configs.");
                free_configs(&opts);
                kill(opts.tcp_server_pid, SIGTERM);
                usleep(1000000);
                got_sighup = 0;
            }
            else if(got_sigint)
            {
                log_msg(LOG_WARNING, "Got SIGINT.  Exiting...");
                got_sigint = 0;
                break;
            }
            else if(got_sigterm)
            {
                log_msg(LOG_WARNING, "Got SIGTERM.  Exiting...");
                got_sigterm = 0;
                break;
            }
            else
            {
                log_msg(LOG_WARNING,
                    "Got signal %i. No defined action but to exit.", last_sig);
                break;
            }
        }
        else if (opts.packet_ctr_limit > 0
            && opts.packet_ctr >= opts.packet_ctr_limit)
        {
            log_msg(LOG_INFO,
                "Packet count limit (%d) reached.  Exiting...",
                opts.packet_ctr_limit);
            break;
        }
        else    /* got_signal was not set (should be if we are here) */
        {
            log_msg(LOG_WARNING,
                "Capture ended without signal.  Exiting...");
            break;
        }
    }

    log_msg(LOG_INFO, "Shutting Down fwknopd.");

    /* Kill the TCP server (if we have one running).
    */
    if(opts.tcp_server_pid > 0)
    {
        log_msg(LOG_INFO, "Killing the TCP server (pid=%i)",
            opts.tcp_server_pid);

        kill(opts.tcp_server_pid, SIGTERM);

        /* --DSS XXX: This seems to be necessary if the tcp server
         *            was restarted by this program.  We need to
         *            investigate and fix this. For now, this works
         *            (it is kludgy, but does no harm afaik).
        */
        kill(opts.tcp_server_pid, SIGKILL);
    }

    /* Other cleanup.
    */
    fw_cleanup();
    free_logging();

#if USE_FILE_CACHE
    free_replay_list(&opts);
#endif

    free_configs(&opts);

    return(0);
}
Ejemplo n.º 26
0
static int
create_volume(int ac, char **av)
{
	struct mfi_config_data *config;
	struct mfi_array *ar;
	struct mfi_ld_config *ld;
	struct config_id_state state;
	size_t config_size;
	char *p, *cfg_arrays, *cfg_volumes;
	int error, fd, i, raid_type;
	int narrays, nvolumes, arrays_per_volume;
	struct array_info *arrays;
	long stripe_size;
#ifdef DEBUG
	int dump;
#endif
	int ch, verbose;

	/*
	 * Backwards compat.  Map 'create volume' to 'create' and
	 * 'create spare' to 'add'.
	 */
	if (ac > 1) {
		if (strcmp(av[1], "volume") == 0) {
			av++;
			ac--;
		} else if (strcmp(av[1], "spare") == 0) {
			av++;
			ac--;
			return (add_spare(ac, av));
		}
	}

	if (ac < 2) {
		warnx("create volume: volume type required");
		return (EINVAL);
	}

	bzero(&state, sizeof(state));
	config = NULL;
	arrays = NULL;
	narrays = 0;
	error = 0;

	fd = mfi_open(mfi_unit);
	if (fd < 0) {
		error = errno;
		warn("mfi_open");
		return (error);
	}

	if (!mfi_reconfig_supported()) {
		warnx("The current mfi(4) driver does not support "
		    "configuration changes.");
		error = EOPNOTSUPP;
		goto error;
	}

	/* Lookup the RAID type first. */
	raid_type = -1;
	for (i = 0; raid_type_table[i].name != NULL; i++)
		if (strcasecmp(raid_type_table[i].name, av[1]) == 0) {
			raid_type = raid_type_table[i].raid_type;
			break;
		}

	if (raid_type == -1) {
		warnx("Unknown or unsupported volume type %s", av[1]);
		error = EINVAL;
		goto error;
	}

	/* Parse any options. */
	optind = 2;
#ifdef DEBUG
	dump = 0;
#endif
	verbose = 0;
	stripe_size = 64 * 1024;

	while ((ch = getopt(ac, av, "ds:v")) != -1) {
		switch (ch) {
#ifdef DEBUG
		case 'd':
			dump = 1;
			break;
#endif
		case 's':
			stripe_size = dehumanize(optarg);
			if ((stripe_size < 512) || (!powerof2(stripe_size)))
				stripe_size = 64 * 1024;
			break;
		case 'v':
			verbose = 1;
			break;
		case '?':
		default:
			error = EINVAL;
			goto error;
		}
	}
	ac -= optind;
	av += optind;

	/* Parse all the arrays. */
	narrays = ac;
	if (narrays == 0) {
		warnx("At least one drive list is required");
		error = EINVAL;
		goto error;
	}
	switch (raid_type) {
	case RT_RAID0:
	case RT_RAID1:
	case RT_RAID5:
	case RT_RAID6:
	case RT_CONCAT:
		if (narrays != 1) {
			warnx("Only one drive list can be specified");
			error = EINVAL;
			goto error;
		}
		break;
	case RT_RAID10:
	case RT_RAID50:
	case RT_RAID60:
		if (narrays < 1) {
			warnx("RAID10, RAID50, and RAID60 require at least "
			    "two drive lists");
			error = EINVAL;
			goto error;
		}
		if (narrays > MFI_MAX_SPAN_DEPTH) {
			warnx("Volume spans more than %d arrays",
			    MFI_MAX_SPAN_DEPTH);
			error = EINVAL;
			goto error;
		}
		break;
	}
	arrays = calloc(narrays, sizeof(*arrays));
	if (arrays == NULL) {
		warnx("malloc failed");
		error = ENOMEM;
		goto error;
	}
	for (i = 0; i < narrays; i++) {
		error = parse_array(fd, raid_type, av[i], &arrays[i]);
		if (error)
			goto error;
	}

	switch (raid_type) {
	case RT_RAID10:
	case RT_RAID50:
	case RT_RAID60:
		for (i = 1; i < narrays; i++) {
			if (arrays[i].drive_count != arrays[0].drive_count) {
				warnx("All arrays must contain the same "
				    "number of drives");
				error = EINVAL;
				goto error;
			}
		}
		break;
	}

	/*
	 * Fetch the current config and build sorted lists of existing
	 * array and volume identifiers.
	 */
	if (mfi_config_read(fd, &config) < 0) {
		error = errno;
		warn("Failed to read configuration");
		goto error;
	}
	p = (char *)config->array;
	state.array_ref = 0xffff;
	state.target_id = 0xff;
	state.array_count = config->array_count;
	if (config->array_count > 0) {
		state.arrays = calloc(config->array_count, sizeof(int));
		if (state.arrays == NULL) {
			warnx("malloc failed");
			error = ENOMEM;
			goto error;
		}
		for (i = 0; i < config->array_count; i++) {
			ar = (struct mfi_array *)p;
			state.arrays[i] = ar->array_ref;
			p += config->array_size;
		}
		qsort(state.arrays, config->array_count, sizeof(int),
		    compare_int);
	} else
		state.arrays = NULL;
	state.log_drv_count = config->log_drv_count;
	if (config->log_drv_count) {
		state.volumes = calloc(config->log_drv_count, sizeof(int));
		if (state.volumes == NULL) {
			warnx("malloc failed");
			error = ENOMEM;
			goto error;
		}
		for (i = 0; i < config->log_drv_count; i++) {
			ld = (struct mfi_ld_config *)p;
			state.volumes[i] = ld->properties.ld.v.target_id;
			p += config->log_drv_size;
		}
		qsort(state.volumes, config->log_drv_count, sizeof(int),
		    compare_int);
	} else
		state.volumes = NULL;
	free(config);

	/* Determine the size of the configuration we will build. */
	switch (raid_type) {
	case RT_RAID0:
	case RT_RAID1:
	case RT_RAID5:
	case RT_RAID6:
	case RT_CONCAT:
	case RT_JBOD:
		/* Each volume spans a single array. */
		nvolumes = narrays;
		break;
	case RT_RAID10:
	case RT_RAID50:
	case RT_RAID60:
		/* A single volume spans multiple arrays. */
		nvolumes = 1;
		break;
	default:
		/* Pacify gcc. */
		abort();
	}

	config_size = sizeof(struct mfi_config_data) +
	    sizeof(struct mfi_ld_config) * nvolumes + MFI_ARRAY_SIZE * narrays;
	config = calloc(1, config_size);
	if (config == NULL) {
		warnx("malloc failed");
		error = ENOMEM;
		goto error;
	}
	config->size = config_size;
	config->array_count = narrays;
	config->array_size = MFI_ARRAY_SIZE;	/* XXX: Firmware hardcode */
	config->log_drv_count = nvolumes;
	config->log_drv_size = sizeof(struct mfi_ld_config);
	config->spares_count = 0;
	config->spares_size = 40;		/* XXX: Firmware hardcode */
	cfg_arrays = (char *)config->array;
	cfg_volumes = cfg_arrays + config->array_size * narrays;

	/* Build the arrays. */
	for (i = 0; i < narrays; i++) {
		build_array(fd, cfg_arrays, &arrays[i], &state, verbose);
		cfg_arrays += config->array_size;
	}

	/* Now build the volume(s). */
	arrays_per_volume = narrays / nvolumes;
	for (i = 0; i < nvolumes; i++) {
		build_volume(cfg_volumes, arrays_per_volume,
		    &arrays[i * arrays_per_volume], raid_type, stripe_size,
		    &state, verbose);
		cfg_volumes += config->log_drv_size;
	}

#ifdef DEBUG
	if (dump)
		dump_config(fd, config);
#endif

	/* Send the new config to the controller. */
	if (mfi_dcmd_command(fd, MFI_DCMD_CFG_ADD, config, config_size,
	    NULL, 0, NULL) < 0) {
		error = errno;
		warn("Failed to add volume");
		/* FALLTHROUGH */
	}

error:
	/* Clean up. */
	free(config);
	free(state.volumes);
	free(state.arrays);
	for (i = 0; i < narrays; i++)
		free(arrays[i].drives);
	free(arrays);
	close(fd);

	return (error);
}
Ejemplo n.º 27
0
int 
main(int argc, char *argv[]) {

    int argn;
    int got_in=0, got_out=0, do_continue=1;
    FILE *in=stdin, *out=stdout;
    struct stat tmpstat;

    pbm_init(&argc, argv);

    printer.version       = DEFAULT_PRINTER;
    printer.x_offset      = DEFAULT_X_OFFSET;
    printer.y_offset      = DEFAULT_Y_OFFSET;
    printer.top_margin    = DEFAULT_TOP_MARGIN;
    printer.left_margin   = DEFAULT_LEFT_MARGIN;
    printer.right_margin  = DEFAULT_RIGHT_MARGIN;
    printer.bottom_margin = DEFAULT_BOTTOM_MARGIN;
    printer.DPI           = DEFAULT_DPI;
    Width = USWIDTH;
    Height = USHEIGHT;
    set_printer_specific_defaults();

    if(!stat(defaultcfgfile,&tmpstat))
        read_config_file(defaultcfgfile);

    for(argn=1; argn<argc; argn++)
    {
        if(!strcmp(argv[argn],"-h"))
        {
            show_usage(*argv);
            return 0;
        }
        else if(!strcmp(argv[argn],"-d"))
            dump_config();
        else if(argn+1<argc)
        {
            do_continue=1;
            if(!strcmp(argv[argn],"-v"))
                parm_version(argv[++argn]);
            else if(!strcmp(argv[argn],"-x"))
                printer.x_offset+=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-y"))
                printer.y_offset+=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-t"))
                printer.top_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-l"))
                printer.left_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-r"))
                printer.right_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-b"))
                printer.bottom_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-d"))
                printer.DPI=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-s"))
            {
                argn++;
                if(!strcmp(argv[argn],"us"))
                {
                    Width = USWIDTH;
                    Height = USHEIGHT;
                }
                else if(!strcmp(argv[argn],"a4"))
                {
                    Width = A4WIDTH;
                    Height = A4HEIGHT;
                }
                else
                    pm_error("unknown paper size %s",argv[argn]);
            }
            else if(!strcmp(argv[argn],"-f"))
                read_config_file(argv[++argn]);
            else do_continue=0;
            if(do_continue) continue;
        }

        if(!got_in)
        {
            if (strcmp (argv[argn], "-") == 0)
                in = stdin;
            else if ((in = fopen (argv[argn], "rb")) == NULL)
                pm_error("main(): couldn't open file '%s'", 
                         argv[argn]);
            got_in=1;
        }
        else if(!got_out)
        {
            if (strcmp (argv[argn], "-") == 0)
                out = stdout;
            else if ((out = fopen (argv[argn], "wb")) == NULL)
                pm_error("main(): couldn't open file '%s'", 
                         argv[argn]);
            got_out=1;
        }
        else
            pm_error("main(): unrecognized parameter '%s'", argv[argn]);
    }

    Pwidth=(Width+7)/8;
    printer.fptr=out;

    return print_pbm (in);
}
Ejemplo n.º 28
0
int config_init ( int argc, char **argv )
{
	const char *config_name = DEFAULT_CONFIG_FILE;	// name of the used config file, can be overwritten via CLI
	const struct configOption_st *opt;
	const char *exe = argv[0];
	int default_config = 1;
	int testparsing = 0;
	argc--; argv++;
#ifdef __EMSCRIPTEN__
	exe = strdup("/files/emscripten-virtual-executable");
#endif
#ifdef _WIN32
	console_open_window();
#endif
	SDL_VERSION(&sdlver_compiled);
	SDL_GetVersion(&sdlver_linked);
	if (sdlver_linked.major < 2 || (sdlver_linked.minor == 0 && sdlver_linked.patch < 4)) {
		ERROR_WINDOW("Too old SDL library linked, at least version 2.0.4 is required.");
		return 1;
	}
	/* SDL info on paths */
	if (get_path_info())
		return 1;
	/* ugly hack: pre-parse comand line to find debug statement (to be worse, it does not handle single argument options too well ... */
#ifdef DISABLE_DEBUG
	printf("DEBUG: disabled at compilation time." NL);
#else
	while (testparsing < argc) {
		if (!strcmp(argv[testparsing], "-" DEBUGFILE_OPT) && testparsing != argc - 1 && strcmp(argv[testparsing + 1], "none")) {
			debug_fp = fopen(argv[testparsing + 1], "w");
			DEBUGPRINT("DEBUG: enable logging into file: %s" NL, argv[testparsing + 1]);
			if (debug_fp == NULL)
				fprintf(stderr, "Cannot open debug logging file: %s" NL, argv[testparsing + 1]);
			break;
		}
		testparsing++;
	}
	testparsing = 0;
#endif
	/* end of ugly hack */
	/* let's continue with the info block ... */
	DEBUGPRINT("%s %s v%s %s %s" NL
		"GIT %s compiled by (%s) at (%s) with (%s)-(%s)" NL
		"Platform: (%s) (%d-bit), video: (%s), audio: (%s), "
		"SDL version compiled: (%d.%d.%d) and linked: (%d.%d.%d) rev (%s)" NL NL,
		WINDOW_TITLE, DESCRIPTION, VERSION, COPYRIGHT, PROJECT_PAGE,
		XEMU_BUILDINFO_GIT, XEMU_BUILDINFO_ON, XEMU_BUILDINFO_AT, CC_TYPE, XEMU_BUILDINFO_CC,
		SDL_GetPlatform(), ARCH_BITS, SDL_GetCurrentVideoDriver(), SDL_GetCurrentAudioDriver(),
		sdlver_compiled.major, sdlver_compiled.minor, sdlver_compiled.patch,
		sdlver_linked.major, sdlver_linked.minor, sdlver_linked.patch, SDL_GetRevision()
	);
	DEBUGPRINT("PATH: executable: %s" NL, exe);
	/* SDL path info block printout */
	DEBUGPRINT("PATH: SDL base path: %s" NL, app_base_path);
	DEBUGPRINT("PATH: SDL pref path: %s" NL, app_pref_path);
#ifndef _WIN32
	DEBUGPRINT("PATH: data directory: %s/" NL, DATADIR);
#endif
	DEBUGPRINT("PATH: Current directory: %s" NL NL, current_directory);
	/* Look the very basic command line switches first */
	if (argc && is_help_request_option(argv[0])) {
		opt = configOptions;
		printf("USAGE:" NL NL
			"\t%s -optname optval -optname2 optval2 ..." NL NL "OPTIONS:" NL NL
			"-config" NL "\tUse config file (or do not use the default one, if \"none\" is specified). This must be the first option if used! [default: @config]" NL,
			exe
		);
		while (opt->name) {
			printf("-%s" NL "\t%s [default: %s]" NL, opt->name, opt->help, opt->defval ? opt->defval : "-");
			opt++;
		}
		printf(NL "%s" NL, disclaimer);
#ifdef _WIN32
		if (!console_is_open)
			ERROR_WINDOW("Could not dump help, since console couldn't be allocated.");
#endif
		XEMUEXIT(0);
	}
	DEBUGPRINT("%s" NL NL, disclaimer);
	if (argc && !strcasecmp(argv[0], "-testparsing")) {
		testparsing = 1;
		argc--; argv++;
	}
	if (argc & 1) {
		fprintf(stderr, "FATAL: Bad command line: should be even number of parameters (two for an option as key and its value)" NL);
		return 1;
	}
	if (argc > 1 && !strcmp(argv[0], "-config")) {
		default_config = 0;
		config_name = argv[1];
		argc -= 2;
		argv += 2;
	}
	/* Set default (built-in) values */
	opt = configOptions;
	while (opt->name) {
		if (opt->defval)
			config_set_internal(opt->name, -1, opt->defval);
		opt++;
	}
	config_set_internal("rom", 0, COMBINED_ROM_FN);	// set default "combined" ROM image set (from segment 0, starting with EXOS)
	/* Default values for the keyboard follows ... */
	keymap_preinit_config_internal();
	/* check if we have written sample config file, if there is not, let's create one */
	save_sample_config(DEFAULT_CONFIG_SAMPLE_FILE);
	/* now parse config file (not the sample one!) if there is any */
	if (strcasecmp(config_name, "none")) {
		char path[PATH_MAX + 1];
		FILE *f = open_emu_file(config_name, "r", path);
		DEBUGPRINT("CONFIG: config file: %s (%s)" NL, config_name, f ? path : "*** CANNOT OPEN, NOT USING CONFIG FILE ***");
		if (f) {
			if (load_config_file_stream(f, path)) {
				fclose(f);
				return 1;
			}
			fclose(f);
		} else if (!default_config) {
			fprintf(stderr, "FATAL: Cannot open requested config file: %s" NL, config_name);
			return 1;
		} else
			DEBUGPRINT("CONFIG: Skipping default config file (cannot open), using built-in defaults." NL);
	} else
		DEBUGPRINT("CONFIG: Using config file: DISABLED in command line" NL);
	/* parse command line ... */
	if (parse_command_line(argc, argv))
		return -1;
	/* open debug file, if it was not requested via command line at the beginning ... */
	if (!debug_fp && strcmp(config_getopt_str(DEBUGFILE_OPT), "none")) {
		debug_fp = fopen(config_getopt_str(DEBUGFILE_OPT), "w");
		DEBUGPRINT("DEBUG: enable logging into file: %s" NL, config_getopt_str(DEBUGFILE_OPT));
		if (!debug_fp)
                	ERROR_WINDOW("Cannot open debug messages log file requested: %s", config_getopt_str(DEBUGFILE_OPT));
	}
	if (debug_fp)
		INFO_WINDOW("DEBUG: Debug messages logging is active");
	else
		printf("DEBUG: No debug messages logging is active." NL);
	/* test parsing mode? */
	if (testparsing) {
		printf(NL "--- TEST DUMP OF *PARSED* CONFIGURATION (requested)" NL NL);
		dump_config(stdout);
		printf(NL "--- END OF TEST PARSING MODE (requested)" NL);
		XEMUEXIT(0);
	}
	DEBUG("CONFIG: End of configuration step." NL NL);
	/* Close console, unless user requested it with the -console option */
#ifdef _WIN32
	if (!config_getopt_int("console"))
		console_close_window();
#else
	if (config_getopt_int("console"))
		console_open_window();	// on non-windows, it only will mark console as open for monitor to be used ..
#endif
	return 0;
}
Ejemplo n.º 29
0
int main(int argc, char **argv)
{
    int i, use_stdin, use_mbox;
    char *configfile = NULL;
    char **tlang, *locale_code;
    int cmd_show_variables;
    int print_usage;

    int amount_old = 0;		/* number of old mails */
    int amount_new = 0;		/* number of new mails */

#ifdef HAVE_LOCALE_H
    setlocale(LC_ALL, "");
#endif

    lockfile[0] = '\0';
    use_stdin = 0;
    print_usage = 0;
    use_mbox = 0;

    firstdatenum = lastdatenum = 0;

    configfile = strsav(CONFIGFILE);

    cmd_show_variables = 0;

    opterr = 0;

#define GETOPT_OPTSTRING ("a:Ab:c:d:gil:L:m:n:o:ps:tTuvVxX0:1M?")

    /* get pre config options here */
	while ((i = getopt(argc, argv, GETOPT_OPTSTRING)) != -1) {
		switch ((char)i) {
	case 'c':
	    configfile = strreplace(configfile, optarg);
	    break;
	case 'v':
	    cmd_show_variables = TRUE;
	    break;
	case 'V':
	    version();
		 /*NOTREACHED*/ case 'a':
	case 'A':
	case 'b':
	case 'd':
	case 'g':
	case 'i':
	case 'l':
	case 'L':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 's':
	case 't':
	case 'T':
	case 'u':
	case 'x':
	case 'X':
	case '0':
	case '1':
	case 'M':
	    break;
	case '?':
	default:
	    /* 
	     * Because we need to setup the language support, 
	     * printing of the usage message must be deferred 
	     * until the proper language is determined.
	     */
	    print_usage = 1;
	    break;
	}
    }

    /* 
     * ...then read the configuration file.
     */

    readconfigs(configfile, cmd_show_variables);

    /* reset the getopt() index variable */
    optind = 1;

    /* now get the post-config options! */

	while ((i = getopt(argc, argv, GETOPT_OPTSTRING)) != -1) {
		switch ((char)i) {
	case 'A':
	    set_append = 1;
	    break;
	case 'a':
	    set_archives = strreplace(set_archives, optarg);
	    break;
	case 'b':
	    set_about = strreplace(set_about, optarg);
	    break;
	case 'c':
	    /* config file from pre-config options */
	    break;
	case 'd':
	    set_dir = strreplace(set_dir, optarg);
	    break;
	case 'g':
	    set_usegdbm = 1;
	    break;
	case 'i':
	    use_stdin = TRUE;
	    break;
	case 'l':
	    set_label = strreplace(set_label, optarg);
	    break;
	case 'L':
	    set_language = strreplace(set_language, optarg);
	    break;
	case 'm':
	    set_mbox = strreplace(set_mbox, optarg);
	    break;
	case 'n':
	    set_hmail = strreplace(set_hmail, optarg);
	    break;
	case 'o':
	    ConfigAddItem(optarg);
	    break;
	case 'p':
	    set_showprogress = TRUE;
	    break;
	case 's':
	    set_htmlsuffix = strreplace(set_htmlsuffix, optarg);
	    break;
	case 't':
	    set_usetable = TRUE;
	    break;
	case 'T':
	    set_indextable = TRUE;
	    break;
	case 'u':
	    set_increment = TRUE;
	    break;
	case 'v':
	    cmd_show_variables = TRUE;
	    break;
	case 'x':
	    set_overwrite = TRUE;
	    break;
	case 'X':
	    set_writehaof = TRUE;
	    break;
	case '0':
	    set_delete_msgnum = add_list(set_delete_msgnum, optarg);
	    break;
	case '1':
	    set_readone = TRUE;
	    break;
	case 'M':
	    set_usemeta = TRUE;
	    break;
	case 'N':
 	    set_nonsequential = TRUE;
	    break;
	case '?':
	default:
	    break;
	}
    }

#ifdef DEBUG
    dump_config();
    exit(0);
#endif

    /*
     * Now override the configuration file variables with any explicitly
     * passed on the command line. This way you need not change the
     * configuration file settings for a minor change in a single run.
     */

    /* 
     * Check and make sure that the supplied language is a
     * valid language. Otherwise strange things happen quickly.
     */

    if (strlen(set_language) > 2) {
	locale_code = strsav(set_language);
	set_language[2] = 0;	/* shorten to 2-letter code */
    }
    else
	locale_code = NULL;

    if ((tlang = valid_language(set_language, &locale_code)) == NULL) {
	snprintf(errmsg, sizeof(errmsg), "\"%s\" %s.", set_language, lang[MSG_LANGUAGE_NOT_SUPPORTED]);
	cmderr(errmsg);
    }

#ifdef HAVE_LOCALE_H
	if (!setlocale(LC_ALL, locale_code)) {
	    snprintf(errmsg, sizeof(errmsg), "WARNING: locale \"%s\", not supported.\n", locale_code);
	    fprintf(stderr, "%s", errmsg);/* AUDIT biege: avoid format-bug warning */
    }
#endif
	
    lang = tlang;		/* A good language, make it so. */

    if (print_usage)		/* Print the usage message and terminate */
	usage();

#ifndef GDBM
    if (set_usegdbm) {
    fprintf(stderr, "%s: %s\n", PROGNAME, lang[MSG_OPTION_G_NOT_BUILD_IN]);
    usage();
    }
#endif

#ifndef HAVE_LIBFNV
    if (set_nonsequential)
      progerr("Hypermail isn't built with the libfnv hash library.\n"
	     "You cannot use the nonsequential option.\n");
#endif /* HAVE_LIBFNV */

    if (set_mbox && !strcasecmp(set_mbox, "NONE")) {
	use_stdin = TRUE;
    }

    /* the list of headers that we always show and that we want to avoid
       showing twice when printing the body */
    set_skip_headers = add_list(set_skip_headers, "from");
    set_skip_headers = add_list(set_skip_headers, "date");
    set_skip_headers = add_list(set_skip_headers, "subject");

    /*
     * Did they decide to use stdin by specifying it on the command line ?
     * If not then check and see if that is the default they wanted from
     * the options.h or environment values.
     */
    if (!use_stdin) {
	if (optind < argc && set_increment == -1 && !set_mbox) {
	    set_mbox = strsav(argv[optind]);
	}
	else if (!set_mbox || !strcasecmp(set_mbox, "NONE"))
	    use_stdin = TRUE;
	else
	    use_stdin = FALSE;
    }
    else {
	if (set_mbox)
	    free(set_mbox);
	set_mbox = NULL;
    }

    /*
    ** Deprecated options 
    */
    if (set_showhr) {
      fprintf (stderr, "The \"showhr\" option has been deprecated. Ignoring it.\n");
      set_showhr = FALSE;
    }

    if (set_usetable) {
      fprintf (stderr, "The \"usetable\" option has been deprecated. Ignoring it.\n");
      set_usetable = FALSE;
    }

    /*
     * Read the contents of the file into the variables to be used
     * in printing out the pages.
     */

    ihtmlheaderfile = expand_contents(set_ihtmlheader);
    ihtmlfooterfile = expand_contents(set_ihtmlfooter);
    ihtmlheadfile = expand_contents(set_ihtmlhead);
    ihtmlhelpupfile = expand_contents(set_ihtmlhelpup);
    ihtmlhelplowfile = expand_contents(set_ihtmlhelplow);
    ihtmlnavbar2upfile = expand_contents(set_ihtmlnavbar2up);
    mhtmlheaderfile = expand_contents(set_mhtmlheader);
    mhtmlfooterfile = expand_contents(set_mhtmlfooter);

    if (set_dir)
	set_dir = strreplace(set_dir, dirpath(set_dir));

    /*
     * Default names for directories and labels need to be figured out.
     */

    if (use_stdin && (!set_dir || !strcasecmp(set_dir, "NONE")))
	set_dir = strreplace(set_dir, DIRNAME);

    if (!set_dir || !strcasecmp(set_dir, "NONE"))
	set_dir = strreplace(set_dir, (strrchr(set_mbox, '/')) ? strrchr(set_mbox, '/') + 1 : set_mbox);

    if (set_dir[strlen(set_dir) - 1] != PATH_SEPARATOR)
	trio_asprintf(&set_dir, "%s%c", set_dir, PATH_SEPARATOR);

    if (!set_label || !strcasecmp(set_label, "NONE"))
	set_label = set_mbox ? (strreplace(set_label, (strrchr(set_mbox, '/')) ? strrchr(set_mbox, '/') + 1 : set_mbox)) : "stdin";

    /*
     * Which index file will be called "index.html"?
     */

    index_name[1][DATE_INDEX] = setindex(set_defaultindex, "date", set_htmlsuffix);
    index_name[1][THREAD_INDEX] = setindex(set_defaultindex, "thread", set_htmlsuffix);
    index_name[1][SUBJECT_INDEX] = setindex(set_defaultindex, "subject", set_htmlsuffix);
    index_name[1][AUTHOR_INDEX] = setindex(set_defaultindex, "author", set_htmlsuffix);
    if (set_attachmentsindex) {
	index_name[1][ATTACHMENT_INDEX]
	    = setindex(set_defaultindex, "attachment", set_htmlsuffix);
    }
    if (set_folder_by_date || set_msgsperfolder) {
	index_name[0][DATE_INDEX] = setindex(set_default_top_index, "date", set_htmlsuffix);
	index_name[0][THREAD_INDEX] = setindex(set_default_top_index, "thread", set_htmlsuffix);
	index_name[0][SUBJECT_INDEX] = setindex(set_default_top_index, "subject", set_htmlsuffix);
	index_name[0][AUTHOR_INDEX] = setindex(set_default_top_index, "author", set_htmlsuffix);
	if (set_attachmentsindex) {
	    index_name[0][ATTACHMENT_INDEX] = setindex(set_default_top_index, "attachment", set_htmlsuffix);
	}
	index_name[0][FOLDERS_INDEX] = setindex(set_default_top_index, "folders", set_htmlsuffix);
    }
    else {
	index_name[0][DATE_INDEX] = index_name[1][DATE_INDEX];
	index_name[0][THREAD_INDEX] = index_name[1][THREAD_INDEX];
	index_name[0][AUTHOR_INDEX] = index_name[1][AUTHOR_INDEX];
	index_name[0][SUBJECT_INDEX] = index_name[1][SUBJECT_INDEX];
	index_name[0][ATTACHMENT_INDEX] = index_name[1][ATTACHMENT_INDEX];
    }

    init_index_names();

    if (set_msgsperfolder && set_folder_by_date) {
	progerr("msgsperfolder and folder_by_date may not be used at the same time!");
    }

    /*
     * General settings for mail command and rewriting.
     */

    if (!set_domainaddr || !strcasecmp(set_domainaddr, "NONE"))
	use_domainaddr = 0;
    else
	use_domainaddr = 1;

    if (!set_mailto || !strcasecmp(set_mailto, "NONE"))
	use_mailto = 0;
    else
	use_mailto = 1;

    if (!set_mailcommand || !strcasecmp(set_mailcommand, "NONE"))
	use_mailcommand = 0;
    else
	use_mailcommand = 1;

#ifndef HAVE_LIBFNV
    /* the nonsequential mode won't work unless we compiled the FNV hash library
       (./configure --enable-libfnv) */
    if (set_nonsequential)
		progerr("the nonsequential mode is only available if you enabled the\n compilation" "of the fnv hash library. Try doing a\n\t./configure --enable-libfnv\n" "and recompile if you want to use this option.");
#endif /* HAVE_LIBFNV */

    /* 
     * A little performance speed up.  The following was being done
     * over and over in the write functions. This way it is done once.
     * A bigger win on larger archives.
     */

    if (set_hmail && !strcasecmp(set_hmail, "NONE")) {
	free(set_hmail);
	set_hmail = NULL;
    }

    if (set_archives && !strcasecmp(set_archives, "NONE")) {
	free(set_archives);
	set_archives = NULL;
    }

    if (set_custom_archives && !strcasecmp(set_custom_archives, "NONE")) {
	free(set_custom_archives);
	set_custom_archives = NULL;
    }

    if (set_about && !strcasecmp(set_about, "NONE")) {
	free(set_about);
	set_about = NULL;
    }

    /* Simply show what the values of the variables are and exit */

    if (cmd_show_variables) {
	if (!set_mbox)
	    set_mbox = "NONE";
	MakeConfig(TRUE); 
	free(configfile);
	return (0);
    }

    /* Injecting a little sanity... */

    if (use_mbox && use_stdin) {
	cmderr(lang[MSG_CANNOT_READ_FROM_BOTH_FILE_AND_STDIN]);
    }
    if (set_append && use_mbox) {
        cmderr(lang[MSG_CANNOT_BOTH_READ_AND_WRITE_TO_MBOX]);
    }

    gettimezone();
    getthisyear();

    /*
     * MIME processing requires the files be created as they
     * are read in loadheaders() so assure the directories are 
     * there first...
     */

    checkdir(set_dir);

    /*
     * Let's do it.
     */

    if (set_uselock)
	lock_archive(set_dir);

    if (set_increment == -1) {
	int save_append = set_append;
	set_append = 0;
	if (set_mbox_shortened)
	    progerr("can not use increment = -1 option with mbox_shortened option\n");
	amount_new = parsemail(set_mbox, use_stdin, 1, -1, set_dir, set_inlinehtml, 0);
	set_increment = !matches_existing(set_startmsgnum);
	if (set_increment && set_folder_by_date && !set_usegdbm)
	    progerr("folder_by_date with incremental update requires usegdbm option");
	reinit_structs();
	set_append = save_append;
    }
    if (set_increment) {
	int num_displayable;
	if (set_linkquotes)
	    replylist = NULL;
	/* we have to start with the msgnum - 1 so that the rest of the
	   code works ok when there are no old headers. */
	max_msgnum = set_startmsgnum - 1;
	num_displayable = loadoldheaders(set_dir);
	amount_old = max_msgnum + 1; /* counts gaps as messages */

	/* start numbering at this number */
	amount_new = num_displayable + parsemail(set_mbox, use_stdin, set_readone, set_increment, set_dir, set_inlinehtml, amount_old);
	if (set_linkquotes)
	    analyze_headers(max_msgnum + 1);

	/* write the index of msgno/msgid_hash filenames */
	if (set_nonsequential)
		write_messageindex(0, max_msgnum + 1);

	writearticles(amount_old, max_msgnum + 1);

	/* JK: in function of other hypermail configuration options, 
	   delete_incremental will continuous escape and add more markup
	   to non-deleted messages that are replies to deleted messages.
	   Thus, a setup option to disable it */
	if (set_delete_incremental && deletedlist)
	    update_deletions(amount_old);

	if (set_show_msg_links) {
	    fixnextheader(set_dir, amount_old, -1);
	    for (i = amount_old; i <= max_msgnum; ++i) {
		if (set_showreplies)
		    fixreplyheader(set_dir, i, 0, amount_old);
		fixthreadheader(set_dir, i, amount_old);
	    }
	}
    }
    else {
	if (set_mbox_shortened) {
	    if (!set_usegdbm) progerr("mbox_shortened option requires that the usegdbm option be on");
	    max_msgnum = set_startmsgnum - 1;
	    loadoldheaders(set_dir);
	}
	amount_new = parsemail(set_mbox, use_stdin, set_readone, set_increment, set_dir, 
			       set_inlinehtml, set_startmsgnum);	/* number from 0 */
	if (!set_mbox_shortened && !matches_existing(0)) {
	    progerr("First message in mailbox does not "
		    "match first message in archive\n"
		    "or obsolete gdbm file present.\n"
		    "Maybe you want to enable the mbox_shortened option?\n");
	}
	if (set_linkquotes)
	    analyze_headers(max_msgnum + 1);

	/* write the index of msgno/msgid_hash filenames */
	if (set_nonsequential)
		write_messageindex(0, max_msgnum + 1);

	writearticles(0, max_msgnum + 1);
    }

    if (amount_new) {		/* Always write the index files */
	if (set_linkquotes) {
	    threadlist = NULL;
	    threadlist_end = NULL;
	    printedthreadlist = NULL;
	    for (i = 0; i <= max_msgnum; ++i) {
	        struct emailinfo *ep;
		if (hashnumlookup(i, &ep)) {
		    ep->flags &= ~USED_THREAD;
#ifdef FASTREPLYCODE
		    ep->isreply = 0;
#endif
		}
		threadlist_by_msgnum[i] = NULL;
	    } /* redo threading with more complete info than in 1st pass */
	    crossindexthread1(datelist);
	    for (i = 0; i <= max_msgnum; ++i) {
	        struct emailinfo *ep, *etmp;
		hashnumlookup(i, &ep);
		etmp = nextinthread(i);
		if (etmp && ep->initial_next_in_thread != etmp->msgnum)
		    fixthreadheader(set_dir, etmp->msgnum, amount_new);
		/* if (ep->flags & THREADING_ALTERED) */
	    }
	}
	count_deleted(max_msgnum + 1);
	if (show_index[0][DATE_INDEX])
	    writedates(amount_new, NULL);
	if (show_index[0][THREAD_INDEX])
	    writethreads(amount_new, NULL);
	if (show_index[0][SUBJECT_INDEX])
	    writesubjects(amount_new, NULL);
	if (show_index[0][AUTHOR_INDEX])
	    writeauthors(amount_new, NULL);
	if (set_attachmentsindex) {
	    writeattachments(amount_new, NULL);
	}
	if (set_writehaof) 
            writehaof(amount_new, NULL);
	if (set_folder_by_date || set_msgsperfolder)
	    write_toplevel_indices(amount_new);
	if (set_monthly_index || set_yearly_index)
	    write_summary_indices(amount_new);
	if (set_latest_folder)
	    symlink_latest();
    }
    else {
	printf("No mails to output!\n");
    }

    if (set_uselock)
	unlock_archive();

    if (configfile)
	free(configfile);
    if (ihtmlheaderfile)
	free(ihtmlheaderfile);
    if (ihtmlfooterfile)
	free(ihtmlfooterfile);
    if (ihtmlheadfile)
	free(ihtmlheadfile);
    if (ihtmlhelpupfile)
	free(ihtmlhelpupfile);
    if (ihtmlhelplowfile)
	free(ihtmlhelplowfile);
    if (ihtmlnavbar2upfile)
	free(ihtmlnavbar2upfile);
    if (mhtmlheaderfile)
	free(mhtmlheaderfile);
    if (mhtmlfooterfile)
	free(mhtmlfooterfile);

    return (0);
}
Ejemplo n.º 30
0
Archivo: main.c Proyecto: Drooids/nrf
int main(void)
{
  uint8_t tx_addr[4] = { 0xaa, 0xab, 0xac, 0xad };
  uint8_t rx_addr[4] = { 0xa1, 0xa2, 0xa3, 0xa4 };

  sys_setup();

  uart_setup();

  /* setup spi first */
  spi_setup_master();
  spi_set_sck_freq(SPI_SCK_FREQ_FOSC2);

  nrf905_setup();
  nrf905_set_tx_addr(tx_addr, 4);
  nrf905_set_rx_addr(rx_addr, 4);
  nrf905_set_payload_width(2);
  nrf905_commit_config();

#if 0
  {
    uint8_t i;
    dump_config();
    for (i = 0; i != sizeof(nrf905_config); ++i)
      nrf905_config[i] = 0x2a;
    nrf905_cmd_rc();
    dump_config();
  }
#endif

#if 0
  {
    uint8_t x;
    uart_write((uint8_t*)"rx side\r\n", 9);
    uart_write((uint8_t*)"press space\r\n", 13);
    uart_read_uint8(&x);
    uart_write((uint8_t*)"starting\r\n", 10);
  }
#endif

  led_setup();

  nrf905_set_rx();

  while (1)
  {
  wait_cd:
    if (nrf905_is_cd() == 0)
    {
      led_set(LED_RED);
      while (nrf905_is_cd() == 0) ;
      /* uart_write((uint8_t*)"cd\r\n", 4); */
    }

#if 0
    while (nrf905_is_am() == 0) ;
    uart_write((uint8_t*)"am\r\n", 4);
    led_mask = LED_GREEN;
#endif

    led_set(LED_GREEN);

  wait_dr:
    while (nrf905_is_dr() == 0)
    {
      if (nrf905_is_cd() == 0) goto wait_cd;
    }
    uart_write((uint8_t*)"dr\r\n", 4);

    reset_pattern();

    /* wait(); */
    nrf905_read_payload();

    if (check_pattern() == 0)
    {
      uart_write((uint8_t*)"ok\r\n", 4);
      led_set(LED_BLUE);
    }
    else led_set(LED_GREEN);

    goto wait_dr;
  }

  return 0;
}