Exemplo n.º 1
0
/* check target VE RATE on destination node */
int check_rate(struct string_list *rate)
{
	int rc = 0;
	struct string_list_el *r;
	char *str, *p, *dev, *id;
	struct string_list iflist;
	struct string_list idlist;

	logger(LOG_DEBUG, "check rate");

	string_list_init(&iflist);
	string_list_init(&idlist);
	if ((rc = read_iflist(&iflist)))
		return rc;
	if ((rc = read_idlist(&idlist)))
		return rc;

	string_list_for_each(rate, r) {
		/* parse rate record */
		if ((str = strdup(r->s)) == NULL)
			return putErr(MIG_ERR_SYSTEM, MIG_MSG_SYSTEM);
		dev = str;
		if ((p = strchr(str, ':')) == NULL) {
			rc = putErr(MIG_ERR_RATE, "invalid rate : %s", r->s);
			goto cleanup;
		}
		*p = '\0';
		id = p + 1;
		if ((p = strchr(id, ':')) == NULL) {
			rc = putErr(MIG_ERR_RATE, "invalid rate : %s", r->s);
			goto cleanup;
		}
		*p = '\0';

		/* check interface */
		if (strcmp(dev, "*")) {
			if (string_list_find(&iflist, dev) == NULL) {
				rc = putErr(MIG_ERR_RATE,
					"rate device %s not found", dev);
				goto cleanup;
			}
		}

		/* check class id */
		if (strcmp(id, "*")) {
			if (string_list_find(&idlist, id) == NULL) {
				rc = putErr(MIG_ERR_RATE,
					"rate class %s not found", id);
				goto cleanup;
			}
		}
cleanup:
		free((void *)str);
		if (rc)
			break;
	}
	string_list_clean(&idlist);
	string_list_clean(&iflist);
	return rc;
}
Exemplo n.º 2
0
void    resolve_init(void)
{
    query = vstring_alloc(100);
    channel = vstring_alloc(100);
    nexthop = vstring_alloc(100);
    nextrcpt = vstring_alloc(100);

    if (*var_virt_alias_doms)
	virt_alias_doms =
	    string_list_init(MATCH_FLAG_NONE, var_virt_alias_doms);

    if (*var_virt_mailbox_doms)
	virt_mailbox_doms =
	    string_list_init(MATCH_FLAG_NONE, var_virt_mailbox_doms);

    if (*var_relay_domains)
	relay_domains =
	    domain_list_init(match_parent_style(VAR_RELAY_DOMAINS),
			     var_relay_domains);

    if (*var_relocated_maps)
	relocated_maps =
	    maps_create(VAR_RELOCATED_MAPS, var_relocated_maps,
			DICT_FLAG_LOCK);
}
Exemplo n.º 3
0
int     main(int argc, char **argv)
{
    STRING_LIST *list;
    char   *string;
    int     ch;

    msg_vstream_init(argv[0], VSTREAM_ERR);

    while ((ch = GETOPT(argc, argv, "v")) > 0) {
	switch (ch) {
	case 'v':
	    msg_verbose++;
	    break;
	default:
	    usage(argv[0]);
	}
    }
    if (argc != optind + 2)
	usage(argv[0]);
    list = string_list_init(MATCH_FLAG_NONE, argv[optind]);
    string = argv[optind + 1];
    vstream_printf("%s: %s\n", string, string_list_match(list, string) ?
		   "YES" : "NO");
    vstream_fflush(VSTREAM_OUT);
    string_list_free(list);
}
Exemplo n.º 4
0
int VEObj::operateVE(const char * func, const char * action,
		const char ** options, int quiet)
{
	int rc, i;
	string_list argv;

	if (action && !quiet)
		logger(LOG_INFO, "%s CT %s ...", action, ctid());

	string_list_init(&argv);
	string_list_add(&argv, BIN_VZCTL);
	if (quiet)
		string_list_add(&argv, "--quiet");
	string_list_add(&argv, "--skiplock");
	string_list_add(&argv, "--skipowner");
	string_list_add(&argv, "--ignore-ha-cluster");
	string_list_add(&argv, (char *)func);
	string_list_add(&argv, ctid());
	if (options) {
		for (i = 0; options[i]; i++)
			string_list_add(&argv, (char *)options[i]);
	}

	rc = vzml_execve(&argv, NULL, -1, -1, quiet);

	string_list_clean(&argv);

	if (action && (rc == 0) && !quiet)
		logger(LOG_INFO, "done");

	return rc;
}
Exemplo n.º 5
0
/* Stores the variables occurring in the string in variables_set.  */
static void
note_variables (const char *string)
{
  string_list_init (&variables_set);
  find_variables (string, &note_variable);
  string_list_sort (&variables_set);
}
Exemplo n.º 6
0
void string_list_clean (string_list * list)
{
    for (size_t i = 0; i < list->length; ++i)
        free (list->list[i]);
    free (list->list);
    string_list_init (list);
}
Exemplo n.º 7
0
/* Return a pointer to a new menu item */
MenuItem*
MenuItem::create(MenuItemKind kind_, const char *text_, int init_toggle_, Menu* target_menu_, int id, int* int_p_)
{
  MenuItem *pnew_item = new MenuItem;

  pnew_item->kind = kind_;
  pnew_item->text = (char*) malloc(sizeof(char) * (strlen(text_) + 1));
  strcpy(pnew_item->text, text_);

  if(kind_ == MN_TOGGLE)
    pnew_item->toggled = init_toggle_;
  else
    pnew_item->toggled = false;

  pnew_item->target_menu = target_menu_;
  pnew_item->input = (char*) malloc(sizeof(char));
  pnew_item->input[0] = '\0';

  if(kind_ == MN_STRINGSELECT)
  {
    pnew_item->list = (string_list_type*) malloc(sizeof(string_list_type));
    string_list_init(pnew_item->list);
  }
  else
    pnew_item->list = NULL;

  pnew_item->id = id;
  pnew_item->int_p = int_p_;

  pnew_item->input_flickering = false;
  pnew_item->input_flickering_timer.init(true);
  pnew_item->input_flickering_timer.start(FLICK_CURSOR_TIME);

  return pnew_item;
}
Exemplo n.º 8
0
static int packed_transaction_prepare(struct ref_store *ref_store,
				      struct ref_transaction *transaction,
				      struct strbuf *err)
{
	struct packed_ref_store *refs = packed_downcast(
			ref_store,
			REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
			"ref_transaction_prepare");
	struct packed_transaction_backend_data *data;
	size_t i;
	int ret = TRANSACTION_GENERIC_ERROR;

	/*
	 * Note that we *don't* skip transactions with zero updates,
	 * because such a transaction might be executed for the side
	 * effect of ensuring that all of the references are peeled or
	 * ensuring that the `packed-refs` file is sorted. If the
	 * caller wants to optimize away empty transactions, it should
	 * do so itself.
	 */

	data = xcalloc(1, sizeof(*data));
	string_list_init(&data->updates, 0);

	transaction->backend_data = data;

	/*
	 * Stick the updates in a string list by refname so that we
	 * can sort them:
	 */
	for (i = 0; i < transaction->nr; i++) {
		struct ref_update *update = transaction->updates[i];
		struct string_list_item *item =
			string_list_append(&data->updates, update->refname);

		/* Store a pointer to update in item->util: */
		item->util = update;
	}
	string_list_sort(&data->updates);

	if (ref_update_reject_duplicates(&data->updates, err))
		goto failure;

	if (!is_lock_file_locked(&refs->lock)) {
		if (packed_refs_lock(ref_store, 0, err))
			goto failure;
		data->own_lock = 1;
	}

	if (write_with_updates(refs, &data->updates, err))
		goto failure;

	transaction->state = REF_TRANSACTION_PREPARED;
	return 0;

failure:
	packed_transaction_cleanup(refs, transaction);
	return ret;
}
Exemplo n.º 9
0
void    resolve_local_init(void)
{
    /* Allow on-the-fly update to make testing easier. */
    if (resolve_local_list)
	string_list_free(resolve_local_list);
    resolve_local_list = string_list_init(VAR_MYDEST, MATCH_FLAG_RETURN,
					  var_mydest);
}
Exemplo n.º 10
0
Arquivo: setup.c Projeto: 1tgr/git
int read_repository_format(struct repository_format *format, const char *path)
{
	memset(format, 0, sizeof(*format));
	format->version = -1;
	format->is_bare = -1;
	string_list_init(&format->unknown_extensions, 1);
	git_config_from_file(check_repo_format, path, format);
	return format->version;
}
Exemplo n.º 11
0
const char *check_user_acl_byuid(char *acl, uid_t uid)
{
    struct mypasswd *mypwd;
    STRING_LIST *list;
    static VSTRING *who = 0;
    int     matched;
    const char *name;

    /*
     * Optimize for the most common case. This also makes Postfix a little
     * more robust in the face of local infrastructure failures. Note that we
     * only need to match the "static:" substring, not the result value.
     */
    if (strncmp(acl, DICT_TYPE_STATIC ":", sizeof(DICT_TYPE_STATIC)) == 0)
	return (0);

    /*
     * XXX: Substitute "unknown" for UIDs without username, so that
     * static:anyone results in "permit" even when the uid is not found in
     * the password file, and so that a pattern of !unknown can be used to
     * block non-existent accounts.
     * 
     * The alternative is to use the UID as a surrogate lookup key for
     * non-existent accounts. There are several reasons why this is not a
     * good idea. 1) An ACL with a numerical UID should work regardless of
     * whether or not an account has a password file entry. Therefore we
     * would always have search on the numerical UID whenever the username
     * fails to produce a match. 2) The string-list infrastructure is not
     * really suitable for mixing numerical and non-numerical user
     * information, because the numerical match is done in a separate pass
     * from the non-numerical match. This breaks when the ! operator is used.
     * 
     * XXX To avoid waiting until the lookup completes (e.g., LDAP or NIS down)
     * invoke mypwuid_err(), and either change the user_acl() API to
     * propagate the error to the caller, or treat lookup errors as fatal.
     */
    if ((mypwd = mypwuid(uid)) == 0) {
	name = "unknown";
    } else {
	name = mypwd->pw_name;
    }

    list = string_list_init(MATCH_FLAG_NONE, acl);
    if ((matched = string_list_match(list, name)) == 0) {
	if (!who)
	    who = vstring_alloc(10);
	vstring_strcpy(who, name);
    }
    string_list_free(list);
    if (mypwd)
	mypwfree(mypwd);

    return (matched ? 0 : vstring_str(who));
}
Exemplo n.º 12
0
void    smtp_sasl_initialize(void)
{

    /*
     * Sanity check.
     */
    if (smtp_sasl_passwd_map || smtp_sasl_impl)
	msg_panic("smtp_sasl_initialize: repeated call");
    if (*var_smtp_sasl_passwd == 0)
	msg_fatal("specify a password table via the `%s' configuration parameter",
		  VAR_SMTP_SASL_PASSWD);

    /*
     * Open the per-host password table and initialize the SASL library. Use
     * shared locks for reading, just in case someone updates the table.
     */
    smtp_sasl_passwd_map = maps_create("smtp_sasl_passwd",
				       var_smtp_sasl_passwd,
				       DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if ((smtp_sasl_impl = xsasl_client_init(var_smtp_sasl_type,
					    var_smtp_sasl_path)) == 0)
	msg_fatal("SASL library initialization");

    /*
     * Initialize optional supported mechanism matchlist
     */
    if (*var_smtp_sasl_mechs)
	smtp_sasl_mechs = string_list_init(MATCH_FLAG_NONE,
					   var_smtp_sasl_mechs);

    /*
     * Initialize the 535 SASL authentication failure cache.
     */
    if (*var_smtp_sasl_auth_cache_name) {
#ifdef HAVE_SASL_AUTH_CACHE
	smtp_sasl_auth_cache =
	    smtp_sasl_auth_cache_init(var_smtp_sasl_auth_cache_name,
				      var_smtp_sasl_auth_cache_time);
#else
	msg_warn("not compiled with TLS support -- "
		 "ignoring the " VAR_SMTP_SASL_AUTH_CACHE_NAME " setting");
#endif
    }
}
Exemplo n.º 13
0
/* 0 - ipadd, 1 - ipdel*/
static int ipset(const char *ctid, const char *cmd, struct string_list *iplist)
{
	int rc;
	struct string_list argv;
	struct string_list_el *p;

	if (string_list_empty(iplist))
		return 0;

	string_list_init(&argv);

	string_list_add(&argv, BIN_VZCTL);
	string_list_add(&argv, "--skiplock");
	string_list_add(&argv, "--skipowner");
	string_list_add(&argv, "set");
	string_list_add(&argv, ctid);

	string_list_for_each(iplist, p) {
		string_list_add(&argv, cmd);
		string_list_add(&argv, p->s);
	}
Exemplo n.º 14
0
void    db_common_parse_domain(CFG_PARSER *parser, void *ctxPtr)
{
    DB_COMMON_CTX *ctx = (DB_COMMON_CTX *) ctxPtr;
    char   *domainlist;
    const char *myname = "db_common_parse_domain";

    domainlist = cfg_get_str(parser, "domain", "", 0, 0);
    if (*domainlist) {
	ctx->domain = string_list_init(MATCH_FLAG_NONE, domainlist);
	if (ctx->domain == 0)

	    /*
	     * The "domain" optimization skips input keys that may in fact
	     * have unwanted matches in the database, so failure to create
	     * the match list is fatal.
	     */
	    msg_fatal("%s: %s: domain match list creation using '%s' failed",
		      myname, parser->name, domainlist);
    }
    myfree(domainlist);
}
Exemplo n.º 15
0
/**
 * The entry point for the submit folder list thread.
 *
 * @param msg
 * @return
 */
static int imap_submit_folder_list_entry(struct imap_submit_folder_list_entry_msg *msg)
{
	struct imap_server *server = imap_duplicate(msg->server);
	struct string_list list;
	struct string_node *node;

	string_list_init(&list);
	node = string_list_first(msg->list);
	while (node)
	{
		string_list_insert_tail(&list,node->string);
		node = string_node_next(node);
	}


	if (thread_parent_task_can_contiue())
	{
		struct imap_submit_folder_options options = {0};

		thread_call_function_async(thread_get_main(),status_init,1,0);
		thread_call_function_async(thread_get_main(),status_open,0);

		options.server = server;
		options.list = &list;
		options.callbacks.set_status = imap_set_status;
		options.callbacks.set_status_static = imap_set_status_static;
		options.callbacks.set_connect_to_server = imap_set_connect_to_server;
		options.callbacks.set_head = imap_set_head;
		options.callbacks.set_title = imap_set_title;
		options.callbacks.set_title_utf8 = imap_set_title_utf8;

		imap_submit_folder_list_really(&options);

		thread_call_function_async(thread_get_main(),status_close,0);
	}
	string_list_clear(&list);
	return 0;
}
Exemplo n.º 16
0
static int graph_write(int argc, const char **argv)
{
	struct string_list *pack_indexes = NULL;
	struct string_list *commit_hex = NULL;
	struct string_list lines;

	static struct option builtin_commit_graph_write_options[] = {
		OPT_STRING(0, "object-dir", &opts.obj_dir,
			N_("dir"),
			N_("The object directory to store the graph")),
		OPT_BOOL(0, "reachable", &opts.reachable,
			N_("start walk at all refs")),
		OPT_BOOL(0, "stdin-packs", &opts.stdin_packs,
			N_("scan pack-indexes listed by stdin for commits")),
		OPT_BOOL(0, "stdin-commits", &opts.stdin_commits,
			N_("start walk at commits listed by stdin")),
		OPT_BOOL(0, "append", &opts.append,
			N_("include all commits already in the commit-graph file")),
		OPT_END(),
	};

	argc = parse_options(argc, argv, NULL,
			     builtin_commit_graph_write_options,
			     builtin_commit_graph_write_usage, 0);

	if (opts.reachable + opts.stdin_packs + opts.stdin_commits > 1)
		die(_("use at most one of --reachable, --stdin-commits, or --stdin-packs"));
	if (!opts.obj_dir)
		opts.obj_dir = get_object_directory();

	read_replace_refs = 0;

	if (opts.reachable) {
		write_commit_graph_reachable(opts.obj_dir, opts.append, 1);
		return 0;
	}

	string_list_init(&lines, 0);
	if (opts.stdin_packs || opts.stdin_commits) {
		struct strbuf buf = STRBUF_INIT;

		while (strbuf_getline(&buf, stdin) != EOF)
			string_list_append(&lines, strbuf_detach(&buf, NULL));

		if (opts.stdin_packs)
			pack_indexes = &lines;
		if (opts.stdin_commits)
			commit_hex = &lines;

		UNLEAK(buf);
	}

	write_commit_graph(opts.obj_dir,
			   pack_indexes,
			   commit_hex,
			   opts.append,
			   1);

	UNLEAK(lines);
	return 0;
}
Exemplo n.º 17
0
string_list_type dfiles(const char *rel_path, const  char* glob, const  char* exception_str)
{
  DIR *dirStructP;
  struct dirent *direntp;
  string_list_type sdirs;
  char path[1024];

  string_list_init(&sdirs);
  sprintf(path,"%s/%s",st_dir,rel_path);
  if((dirStructP = opendir(path)) != NULL)
    {
      while((direntp = readdir(dirStructP)) != NULL)
        {
          char absolute_filename[1024];
          struct stat buf;

          sprintf(absolute_filename, "%s/%s", path, direntp->d_name);

          if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
            {
              if(exception_str != NULL)
                {
                  if(strstr(direntp->d_name,exception_str) != NULL)
                    continue;
                }
              if(glob != NULL)
                if(strstr(direntp->d_name,glob) == NULL)
                  continue;

              string_list_add_item(&sdirs,direntp->d_name);
            }
        }
      closedir(dirStructP);
    }

  sprintf(path,"%s/%s",datadir.c_str(),rel_path);
  if((dirStructP = opendir(path)) != NULL)
    {
      while((direntp = readdir(dirStructP)) != NULL)
        {
          char absolute_filename[1024];
          struct stat buf;

          sprintf(absolute_filename, "%s/%s", path, direntp->d_name);

          if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
            {
              if(exception_str != NULL)
                {
                  if(strstr(direntp->d_name,exception_str) != NULL)
                    continue;
                }
              if(glob != NULL)
                if(strstr(direntp->d_name,glob) == NULL)
                  continue;

              string_list_add_item(&sdirs,direntp->d_name);
            }
        }
      closedir(dirStructP);
    }

  return sdirs;
}
Exemplo n.º 18
0
int cmd_main(int argc, const char **argv)
{
	struct strbuf buf = STRBUF_INIT;
	int nongit;

	setup_git_directory_gently(&nongit);
	if (argc < 2) {
		error("remote-curl: usage: git remote-curl <remote> [<url>]");
		return 1;
	}

	options.verbosity = 1;
	options.progress = !!isatty(2);
	options.thin = 1;
	string_list_init(&options.deepen_not, 1);
	string_list_init(&options.push_options, 1);

	remote = remote_get(argv[1]);

	if (argc > 2) {
		end_url_with_slash(&url, argv[2]);
	} else {
		end_url_with_slash(&url, remote->url[0]);
	}

	http_init(remote, url.buf, 0);

	do {
		const char *arg;

		if (strbuf_getline_lf(&buf, stdin) == EOF) {
			if (ferror(stdin))
				error("remote-curl: error reading command stream from git");
			return 1;
		}
		if (buf.len == 0)
			break;
		if (starts_with(buf.buf, "fetch ")) {
			if (nongit)
				die("remote-curl: fetch attempted without a local repo");
			parse_fetch(&buf);

		} else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
			int for_push = !!strstr(buf.buf + 4, "for-push");
			output_refs(get_refs(for_push));

		} else if (starts_with(buf.buf, "push ")) {
			parse_push(&buf);

		} else if (skip_prefix(buf.buf, "option ", &arg)) {
			char *value = strchr(arg, ' ');
			int result;

			if (value)
				*value++ = '\0';
			else
				value = "true";

			result = set_option(arg, value);
			if (!result)
				printf("ok\n");
			else if (result < 0)
				printf("error invalid value\n");
			else
				printf("unsupported\n");
			fflush(stdout);

		} else if (!strcmp(buf.buf, "capabilities")) {
			printf("stateless-connect\n");
			printf("fetch\n");
			printf("option\n");
			printf("push\n");
			printf("check-connectivity\n");
			printf("\n");
			fflush(stdout);
		} else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
			if (!stateless_connect(arg))
				break;
		} else {
			error("remote-curl: unknown command '%s' from git", buf.buf);
			return 1;
		}
		strbuf_reset(&buf);
	} while (1);

	http_cleanup();

	return 0;
}
Exemplo n.º 19
0
/* Note: The user has to free the allocated space. */
string_list_type dsubdirs(const char *rel_path,const  char* expected_file)
{
  DIR *dirStructP;
  struct dirent *direntp;
  string_list_type sdirs;
  char filename[1024];
  char path[1024];

  string_list_init(&sdirs);
  sprintf(path,"%s/%s",st_dir,rel_path);
  if((dirStructP = opendir(path)) != NULL)
    {
      while((direntp = readdir(dirStructP)) != NULL)
        {
          char absolute_filename[1024];
          struct stat buf;

          sprintf(absolute_filename, "%s/%s", path, direntp->d_name);

          if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
            {
              if(expected_file != NULL)
                {
                  sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
                  if(!faccessible(filename))
                    continue;
                }

              string_list_add_item(&sdirs,direntp->d_name);
            }
        }
      closedir(dirStructP);
    }

  sprintf(path,"%s/%s",datadir.c_str(),rel_path);
  if((dirStructP = opendir(path)) != NULL)
    {
      while((direntp = readdir(dirStructP)) != NULL)
        {
          char absolute_filename[1024];
          struct stat buf;

          sprintf(absolute_filename, "%s/%s", path, direntp->d_name);

          if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
            {
              if(expected_file != NULL)
                {
                  sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
                  if(!faccessible(filename))
                    {
                      continue;
                    }
                  else
                    {
                      sprintf(filename,"%s/%s/%s/%s",st_dir,rel_path,direntp->d_name,expected_file);
                      if(faccessible(filename))
                        continue;
                    }
                }

              string_list_add_item(&sdirs,direntp->d_name);
            }
        }
      closedir(dirStructP);
    }

  return sdirs;
}
Exemplo n.º 20
0
/* --- TITLE SCREEN --- */
void title(void)
{
  random_timer.init(true);

  walking = true;

  st_pause_ticks_init();

  GameSession session(datadir + "/levels/misc/menu.stl", 0, ST_GL_DEMO_GAME);

  clearscreen(0, 0, 0);
  updatescreen();

  /* Load images: */
  bkg_title = new Surface(datadir + "/images/title/background.jpg", IGNORE_ALPHA);
  logo = new Surface(datadir + "/images/title/logo.png", USE_ALPHA);
  img_choose_subset = new Surface(datadir + "/images/status/choose-level-subset.png", USE_ALPHA);

  /* Generating contrib maps by only using a string_list */
  // Since there isn't any world dir or anything, add a hardcoded entry for Bonus Island
  string_list_init(&worldmap_list);

  string_list_type files = dfiles("levels/worldmaps/", ".stwm", "couldn't list worldmaps");
  for(int i = 0; i < files.num_items; ++i) {
    if(strcmp(files.item[i], "world1.stwm") == 0)
      continue;
    string_list_add_item(&worldmap_list, files.item[i]);
  }
  string_list_free(&files);

  /* --- Main title loop: --- */
  frame = 0;

  /* Draw the title background: */
  bkg_title->draw_bg();

  update_time = st_get_ticks();
  random_timer.start(rand() % 2000 + 2000);

  Menu::set_current(main_menu);
  while (Menu::current())
    {
      // if we spent to much time on a menu entry
      if( (update_time - last_update_time) > 1000)
        update_time = last_update_time = st_get_ticks();

      // Calculate the movement-factor
      double frame_ratio = ((double)(update_time-last_update_time))/((double)FRAME_RATE);
      if(frame_ratio > 1.5) /* Quick hack to correct the unprecise CPU clocks a little bit. */
        frame_ratio = 1.5 + (frame_ratio - 1.5) * 0.85;
      /* Lower the frame_ratio that Tux doesn't jump to hectically throught the demo. */
      frame_ratio /= 2;

      SDL_Event event;
      while (SDL_PollEvent(&event))
        {
          if (Menu::current())
            {
              Menu::current()->event(event);
            }
         // FIXME: QUIT signal should be handled more generic, not locally
          if (event.type == SDL_QUIT)
            Menu::set_current(0);
        }

      /* Draw the background: */
      draw_demo(&session, frame_ratio);
      
      if (Menu::current() == main_menu)
        logo->draw( 160, 30);

      white_small_text->draw(" SuperTux " VERSION "\n"
                             "Copyright (c) 2003 SuperTux Devel Team\n"
                             "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you\n"
                             "are welcome to redistribute it under certain conditions; see the file COPYING\n"
                             "for details.\n",
                             0, 420, 0);

      /* Don't draw menu, if quit is true */
      Menu* menu = Menu::current();
      if(menu)
        {
          menu->draw();
          menu->action();
        
          if(menu == main_menu)
            {
              MusicManager* music_manager;
	      MusicRef menu_song;
              switch (main_menu->check())
                {
                case MNID_STARTGAME:
                  // Start Game, ie. goto the slots menu
                  update_load_save_game_menu(load_game_menu);
                  break;
                case MNID_CONTRIB:
                  // Contrib Menu
                  puts("Entering contrib menu");
                  generate_contrib_menu();
                  break;
                case MNID_LEVELEDITOR:
                  leveleditor();
                  Menu::set_current(main_menu);
                  break;
                case MNID_CREDITS:
                  music_manager = new MusicManager();
                  menu_song  = music_manager->load_music(datadir + "/music/credits.ogg");
                  music_manager->halt_music();
                  music_manager->play_music(menu_song,0);
                  display_text_file("CREDITS", bkg_title, SCROLL_SPEED_CREDITS);
                  music_manager->halt_music();
                  menu_song = music_manager->load_music(datadir + "/music/theme.mod");
                  music_manager->play_music(menu_song);
                  Menu::set_current(main_menu);
                  break;
                case MNID_QUITMAINMENU:
                  Menu::set_current(0);
                  break;
                }
            }
          else if(menu == options_menu)
            {
              process_options_menu();
            }
          else if(menu == load_game_menu)
            {
              if(event.key.keysym.sym == SDLK_DELETE)
                {
                int slot = menu->get_active_item_id();
                char str[1024];
                sprintf(str,"Are you sure you want to delete slot %d?", slot);
                
                draw_background();

                if(confirm_dialog(str))
                  {
                  sprintf(str,"%s/slot%d.stsg", st_save_dir, slot);
                  printf("Removing: %s\n",str);
                  remove(str);
                  }

                update_load_save_game_menu(load_game_menu);
                update_time = st_get_ticks();
                Menu::set_current(main_menu);
                }
              else if (process_load_game_menu())
                {
                  // FIXME: shouldn't be needed if GameSession doesn't relay on global variables
                  // reset tux
                  scroll_x = 0;
                  //titletux.level_begin();
                  update_time = st_get_ticks();
                }
            }
          else if(menu == contrib_menu)
            {
              check_contrib_menu();
            }
          else if (menu == contrib_subset_menu)
            {
              check_contrib_subset_menu();
            }
        }

      mouse_cursor->draw();
      
      flipscreen();

      /* Set the time of the last update and the time of the current update */
      last_update_time = update_time;
      update_time = st_get_ticks();

      /* Pause: */
      frame++;
      SDL_Delay(25);
    }
  /* Free surfaces: */

  free_contrib_menu();
  string_list_free(&worldmap_list);
  delete bkg_title;
  delete logo;
  delete img_choose_subset;
}
Exemplo n.º 21
0
/** 
 * Execute the command READCSS to read a CSS file 
 * 
 * @param nerr 
 *    Error Return Flag
 *    - 0 on Success
 *
 * @date   970403:  New option to conveniently select the channel.
 * @date   970206:  New option to specify which magnitude to read.  maf
 * @date   961216:  Now filtering on station rather than gain.  maf
 * @date   920420:  Changed null string, "", to ' ' - porting to IBM. 
 * @date   910703:  add # to parameter keyword GAIN; 
 *                  add * as a legal value for params GAIN, BAND, ORIENT
 * @date   910402:  New code.
 *
 */
void 
xrcss(int *nerr) {

    char _c0[2];
    char file[MCMSG+1];
    int len;
	int lmore, lshift, lscale, larray ;
	int nchar;
    static int Verbose = 0;
    static int ibinORasc;
    static string_list *last_list = NULL;
    double memory_max;

    memory_max = 0.30;

	char kmag[4] ;	/* magnitude type: mb, ms, or ml. maf 970206 */
    string_list *list;

    if(!last_list) {
        last_list = string_list_init();
    }

	*nerr = 0;
    list = string_list_init();

	/* PARSING PHASE: */
	/* - Parse position-dependent tokens: */
	lmore = FALSE;
  
	while ( lcmore( nerr ) ){
    
    /* -- "MORE":  signifies addition of more files to current read 
     *  filelist rather than replacement of current list with new one */
    if( lckey( "MORE#$",7 ) && cmdfm.ndfl > 0 ){
      lmore = TRUE;
      continue ;
    }
    
    /* -- "VERBOSE ON|OFF":  turn Verbose mode on or off. */
    else if( lklog( "VER$BOSE",9, &Verbose ) ){
      continue ;
    }
    /* -- "SHIFT ON|OFF":  turn calibration on or off. */
    else if( lklog( "SHIFT$",7, &lshift ) ){
      cmdfm.lshift = lshift ;
      continue ;
    }

	    /* -- "SCALE ON|OFF":  turn scaling on or off. */
    else if( lklog( "SCALE$",7, &lscale ) ){
      cmdfm.lscale = lscale ;
      continue ;
    }
    
    /* -- "ARRAY ON|OFF":  turn lienient array behavior on or off. */
    else if ( lklog ( "ARRAY$" , 7 , &larray ) ) {
      cmdfm.larray = larray ;
      continue ;
    }
    
    /* -- "MAXMEM v": change maximum fractional memory used by SeisMgr*/
    else if( lkreal( "MAX#MEM$",9, &memory_max ) )
	    { 
        MaxMem = memory_max;
      }
    
    /* -- "DIR CURRENT|name": set the name of the default subdirectory*/
    else if(lkchar("DIR#$",6,MCPFN,kmdfm.krdcssdir,MCPFN+1,&nchar)){
      if( memcmp(kmdfm.krdcssdir,"CURRENT",7) == 0 ||
          memcmp(kmdfm.krdcssdir ,"current",7) == 0 ){
		    cfmt( "ILLEGAL PARAM VALUE: current",30 );
		    cresp();
		    return ;
      }
      else if( kmdfm.krdcssdir[nchar - 1] != KDIRDL ){
		    _c0[0] = KDIRDL;
		    _c0[1] = '\0';
		    subscpy( kmdfm.krdcssdir, nchar, -1, MCPFN, _c0 );
      }
      continue;
    }
    
    /* -- "MAGNITUDE|mb|ms|ml|def":  specify a field for magnitude, or
       if def is found, use the algorithm to determine which
       magnitude to read.  maf 970206. */
    else if ( lkchar ( "MAG#NITUDE$", 12 , 4 , kmag , 4 , &nchar ) ) {
      if ( kmag [ 0 ] == 'm' || kmag[ 0 ] == 'M' ) {
		    if ( kmag [ 1 ] == 'b' || kmag [ 1 ] == 'B' ) 
          cmdfm.nMagSpec = MbMag ;
		    else if ( kmag [ 1 ] == 's' || kmag [ 1 ] == 'S' )
          cmdfm.nMagSpec = MsMag ;
		    else if ( kmag [ 1 ] == 'l' || kmag [ 1 ] == 'L' )
          cmdfm.nMagSpec = MlMag ;
		    else {
          cfmt( "ILLEGAL PARAM VALUE:",22 );
          cresp();
          return ;
		    }
      } /* end if ( kmag [ 0 ] == 'm' ... ) */
      else if ( strncmp ( kmag , "def" , 3 ) == 0 || 
                strncmp ( kmag , "DEF" , 3 ) == 0 )
		    cmdfm.nMagSpec = Any ;
      else {
		    cfmt( "ILLEGAL PARAM VALUE:",22 );
		    cresp();
		    return ;
      }
    } /* end if ( lkchar ( "MAG#NITUDE$", ... ) */


	    /* -- "STATION": whether wfdisc record fld 'sta' matches given */
	    /*		string.   maf 961216 */
    else if( lklogc("STA#TION$",10,&kmdfm.lstation,kmdfm.kstation,7 ) ){
      char *ptr ; 
      
      ptr = strchr ( kmdfm.kstation , ' ' ) ;
      if ( ptr != NULL )
		    *ptr = '\0' ;
      continue;
    }

    /* -- "CHANNEL": whether wfdisc record fld 'chan' matches the 
     *              given string.  maf 970403 */
    else if( lklogc("CHAN#NEL$",10,&kmdfm.lchannel,kmdfm.kchannel,9 ) ){
      char *ptr ;
      
      ptr = strchr ( kmdfm.kchannel , ' ' ) ;
      if ( ptr != NULL )
		    *ptr = '\0' ;
      //if( jcdflbeg > 0 && jcdflend == 0 )
      //  jcdflend = jcparmbeg - 1;
      continue;
    }


    /* -- "BANDWIDTH": whether wfdisc record fld 'chan' has a leading 
     *     letter which is S(short), M(medium), or L(long) */
    else if( lklogc( "BAND#WIDTH$",12, &kmdfm.lbandw,kmdfm.kbandw,9 ) ){
      //if( jcdflbeg > 0 && jcdflend == 0 )
      //jcdflend = jcparmbeg - 1;
      continue;
    } /* end else if( lklogc( "BAND#WIDTH$" ... */

	    /* -- "ORIENTATION: whether wfdisc record fld 'chan' has a second 
	     *     letter which is N(north), E(east), or Z(vertical) */
    else if(lklogc("ORIENT#ATION$",14,&kmdfm.lorient,kmdfm.korient,9)){
      //if( jcdflbeg > 0 && jcdflend == 0 )
      //jcdflend = jcparmbeg - 1;
      continue;
    } /* end else if( lklogc( "ORIENT#ATION$" ... */
    
    /* -- TRUST:  whether or not to trust matching evids while moving
       data from SAC buffers to CSS buffers. */
    else if( lklog( "TRUST#$",8, &cmdfm.ltrust ) )
      { /* do nothing */ }
    
    /* -- "COMMIT|RECALLTRACE|ROLLBACK":
       how to treat existing data */
    else if ( lckeyExact ( "COMMIT" , 7 ) )
      cmdfm.icomORroll = COMMIT ;
    else if (lckeyExact ( "RECALLTRACE" , 12 ) )
      cmdfm.icomORroll = RECALL ;
    else if ( lckeyExact ( "RECALL" , 7 ) )
      cmdfm.icomORroll = RECALL ;
    else if ( lckeyExact ( "ROLLBACK" , 9 ) )
      cmdfm.icomORroll = ROLLBACK ;
    
    
    /* -- "BINARY|ASCII": CSSB versus flat files */
    else if( lclist( (char*)kmdfm.kbinORasc,9, 2, &ibinORasc ) ) {
      cmdfm.lrascii = ibinORasc - 1 ;
    }
    
	    /* -- Else assume it to be beginning/continuing dfl, if not 
	     *    recognized as above 
	     *    Use kdflin as dummy buffer to skip a string  */
	    else if(lcchar(MCMSG, file, MCMSG+1, &len)) {
            string_list_put(list, file, len);
	    } 
	} 

	/* - The above loop is over when one of two conditions has been met:
	 *   (1) An error in parsing has occurred.  In this case NERR is > 0 .
	 *   (2) All the tokens in the command have been successfully parsed. */

	if( *nerr != 0 )
	    return ;

    if(string_list_length(list) <= 0) {
        string_list_extend(list, last_list);
    }
	/* EXECUTION PHASE: */

        /* - Commit or rollback data according to lmore and cmdfm.icomORroll */
        if ( lmore ) {
            alignFiles ( nerr ) ;
	    if ( *nerr )
		return ;
	    cmdfm.nfilesFirst = cmdfm.ndfl ;
        } /* end if */
	else {
	    cmdfm.nreadflag = HIGH ;
	    cmdfm.nfilesFirst = 0 ;
	}

        /* Copy Current List to Last_List */
        string_list_clear(last_list);
        string_list_extend(last_list, list);
        /* - Expand the filelist and read the files into memory.
         * -- Parameter kstation, kband, korient are picked up in readcfl from
         *    ../../inc/dfm */
        readcfl( lmore, kmdfm.krdcssdir,MCPFN+1, list, 
                 Verbose, cmdfm.lrascii, MaxMem, nerr );

        string_list_free(list);
        list = NULL;
	return;

}
Exemplo n.º 22
0
static void pre_jail_init(char *unused_name, char **unused_argv)
{
    VSTRING *redirect;

    /*
     * Open read-only maps before dropping privilege, for consistency with
     * other Postfix daemons.
     */
    psc_acl_pre_jail_init(var_mynetworks, VAR_PSC_ACL);
    if (*var_psc_acl)
	psc_acl = psc_acl_parse(var_psc_acl, VAR_PSC_ACL);
    /* Ignore smtpd_forbid_cmds lookup errors. Non-critical feature. */
    if (*var_psc_forbid_cmds)
	psc_forbid_cmds = string_list_init(MATCH_FLAG_RETURN,
					   var_psc_forbid_cmds);
    if (*var_psc_dnsbl_reply)
	psc_dnsbl_reply = dict_open(var_psc_dnsbl_reply, O_RDONLY,
				    DICT_FLAG_DUP_WARN);

    /*
     * Never, ever, get killed by a master signal, as that would corrupt the
     * database when we're in the middle of an update.
     */
    if (setsid() < 0)
	msg_warn("setsid: %m");

    /*
     * Security: don't create root-owned files that contain untrusted data.
     * And don't create Postfix-owned files in root-owned directories,
     * either. We want a correct relationship between (file or directory)
     * ownership and (file or directory) content. To open files before going
     * to jail, temporarily drop root privileges.
     */
    SAVE_AND_SET_EUGID(var_owner_uid, var_owner_gid);
    redirect = vstring_alloc(100);

    /*
     * Keep state in persistent external map. As a safety measure we sync the
     * database on each update. This hurts on LINUX file systems that sync
     * all dirty disk blocks whenever any application invokes fsync().
     * 
     * Start the cache maintenance pseudo thread after dropping privileges.
     */
#define PSC_DICT_OPEN_FLAGS (DICT_FLAG_DUP_REPLACE | DICT_FLAG_SYNC_UPDATE | \
	    DICT_FLAG_OPEN_LOCK)

    if (*var_psc_cache_map)
	psc_cache_map =
	    dict_cache_open(data_redirect_map(redirect, var_psc_cache_map),
			    O_CREAT | O_RDWR, PSC_DICT_OPEN_FLAGS);

    /*
     * Clean up and restore privilege.
     */
    vstring_free(redirect);
    RESTORE_SAVED_EUGID();

    /*
     * Initialize the dummy SMTP engine.
     */
    psc_smtpd_pre_jail_init();
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
	int rc = 0;
	SSL_METHOD *meth = NULL;
	SSL * ssl = NULL;
	SSL_CTX * ctx = NULL;
	X509 *server_cert = NULL;
	long res;
	char *srv;
	int sd, ferr;
	unsigned long addr;
	struct sockaddr_in saddr;
	unsigned short port = 4422;
	int lcipher;
	struct string_list arglist;
	char *dir, *name;
	char path[PATH_MAX+1];

	if ( argc < 3 )
		usage(basename(argv[0]), 1);
	if (parse_cmd_line(argc, argv))
		usage(basename(argv[0]), 1);

	if (argc <= optind+1)
		usage(basename(argv[0]), 1);
	srv = argv[optind];
	strncpy(path, argv[optind+1], sizeof(path));
	name = basename(path);
	dir = dirname(path);

	if ((addr = inet_addr(srv)) == INADDR_NONE) {
		/* need to resolve address */
		struct hostent *host;
		if ((host = gethostbyname(srv)) == NULL) {
			fprintf(stderr, "gethostbyname(%s) err : %m\n", srv);
			return 1;
		}
		memcpy(&addr, host->h_addr, sizeof(addr));
	}

	if (crtfile == NULL)
		crtfile = strdup("certificate.pem");
	if (keyfile == NULL)
		keyfile = strdup("private.key");
	if (ciphers == NULL)
		lcipher = 0;
	else if (strcasecmp(ciphers, "none") == 0)
		lcipher = 0;
	else
		lcipher = 1;

	string_list_init(&arglist);
	string_list_add(&arglist, "tar");
	string_list_add(&arglist, "-c");
	string_list_add(&arglist, "-S");
	string_list_add(&arglist, "--ignore-failed-read");
	string_list_add(&arglist, "-f");
	string_list_add(&arglist, "-");
	string_list_add(&arglist, "-C");
	string_list_add(&arglist, dir);
	string_list_add(&arglist, name);

	/* Set up the library */
	SSL_library_init();
	SSL_load_error_strings();

	/* Create SSL context (framework) */
	meth = SSLv23_client_method();
	if ((ctx = SSL_CTX_new(meth)) == NULL) {
		fprintf(stderr, "SSL_CTX_new() : %m\n");
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_0;
	}

	/* load certificat from file */
	if(SSL_CTX_use_certificate_file(ctx, crtfile, SSL_FILETYPE_PEM) < 1) {
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_1;
	}
	if(SSL_CTX_use_PrivateKey_file(ctx, keyfile, SSL_FILETYPE_PEM) < 1) {
		ERR_print_errors_fp(stdout);
		rc = 1;
		goto cleanup_1;
	}
	if (lcipher) {
		/* load available cipher list */
		if (SSL_CTX_set_cipher_list(ctx, ciphers) == 0) {
			fprintf(stderr, "Error loading cipher list\n");
			ERR_print_errors_fp(stderr);
			rc = 1;
			goto cleanup_1;
		}
	}
	SSL_CTX_set_verify(ctx,
		SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);

	/* ----------------------------------------------- */
	/* Create a socket and connect to server using normal socket calls. */
	if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
		fprintf(stderr, "socket() err : %m\n");
		rc = 1;
		goto cleanup_1;
	}

	saddr.sin_family = AF_INET;
	saddr.sin_addr.s_addr = addr;
	saddr.sin_port = htons(port);

	if (connect(sd, (struct sockaddr *)&saddr, sizeof(saddr))) {
		// if (errno != EINPROGRESS) - for NONBLOCK
		fprintf(stderr, "connect() : %m\n");
		rc = 1;
		goto cleanup_1;
	}
	/* ----------------------------------------------- */
	/* Now we have TCP connection. Start SSL negotiation. */

	/* Create SSL obj */
	if ((ssl = SSL_new(ctx)) == NULL) {
		fprintf(stderr, "Error creating SSL object\n");
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_1;
	}

	SSL_set_fd(ssl, sd);
	SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

	/* try to connect */
	if(SSL_connect(ssl) <= 0) {
		fprintf(stderr, "Error attempting to connect\n");
		/* TODO SSL_get_error() */
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_2;
	}

	/* Get server's certificate. Note: dynamic allocation */
	if ((server_cert = SSL_get_peer_certificate(ssl)) == NULL) {
		fprintf(stderr, "Can't get peer certificate\n");
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_2;
	}

	X509_free(server_cert);

	/* verify the certificate
	From SSL_get_verify_result() man page:
	If no peer certificate was presented, the returned result code is
	X509_V_OK. This is because no verification error occurred, it does how-
	ever not indicate success. SSL_get_verify_result() is only useful in
	connection with SSL_get_peer_certificate(3).
	*/
	res = SSL_get_verify_result(ssl);
	/* will use expired certificate for test */
	if (	(res != X509_V_OK) &&
		(res != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) &&
		(res != X509_V_ERR_CERT_HAS_EXPIRED)) {
		fprintf(stderr, "Certificate verification error: %ld\n", res);
		fprintf(stderr, "See verify man page for more info\n");
		ERR_print_errors_fp(stderr);
		rc = 1;
		goto cleanup_2;
	}
	printf("Server certificate verified\n");

	ferr = dup(STDERR_FILENO);
	if (lcipher)
		;
	else {
		rc = run_rw(sd, sd, ferr, &arglist);
	}
	close(ferr);
	printf("rc = %d\n", rc);

	SSL_shutdown(ssl);

	/* Close the connection and free the context */
cleanup_2:
	if (ssl)
		SSL_free(ssl);

cleanup_1:
	if (ctx)
		SSL_CTX_free(ctx);

cleanup_0:
	string_list_clean(&arglist);

	return rc;
}
Exemplo n.º 24
0
void    cleanup_pre_jail(char *unused_name, char **unused_argv)
{
    static const NAME_MASK send_canon_class_table[] = {
	CANON_CLASS_ENV_FROM, CLEANUP_CANON_FLAG_ENV_FROM,
	CANON_CLASS_HDR_FROM, CLEANUP_CANON_FLAG_HDR_FROM,
	0,
    };
    static const NAME_MASK rcpt_canon_class_table[] = {
	CANON_CLASS_ENV_RCPT, CLEANUP_CANON_FLAG_ENV_RCPT,
	CANON_CLASS_HDR_RCPT, CLEANUP_CANON_FLAG_HDR_RCPT,
	0,
    };
    static const NAME_MASK canon_class_table[] = {
	CANON_CLASS_ENV_FROM, CLEANUP_CANON_FLAG_ENV_FROM,
	CANON_CLASS_ENV_RCPT, CLEANUP_CANON_FLAG_ENV_RCPT,
	CANON_CLASS_HDR_FROM, CLEANUP_CANON_FLAG_HDR_FROM,
	CANON_CLASS_HDR_RCPT, CLEANUP_CANON_FLAG_HDR_RCPT,
	0,
    };
    static const NAME_MASK masq_class_table[] = {
	MASQ_CLASS_ENV_FROM, CLEANUP_MASQ_FLAG_ENV_FROM,
	MASQ_CLASS_ENV_RCPT, CLEANUP_MASQ_FLAG_ENV_RCPT,
	MASQ_CLASS_HDR_FROM, CLEANUP_MASQ_FLAG_HDR_FROM,
	MASQ_CLASS_HDR_RCPT, CLEANUP_MASQ_FLAG_HDR_RCPT,
	0,
    };

    if (*var_canonical_maps)
	cleanup_comm_canon_maps =
	    maps_create(VAR_CANONICAL_MAPS, var_canonical_maps,
			DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if (*var_send_canon_maps)
	cleanup_send_canon_maps =
	    maps_create(VAR_SEND_CANON_MAPS, var_send_canon_maps,
			DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if (*var_rcpt_canon_maps)
	cleanup_rcpt_canon_maps =
	    maps_create(VAR_RCPT_CANON_MAPS, var_rcpt_canon_maps,
			DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if (*var_virt_alias_maps)
	cleanup_virt_alias_maps = maps_create(VAR_VIRT_ALIAS_MAPS,
					      var_virt_alias_maps,
					      DICT_FLAG_LOCK
					      | DICT_FLAG_FOLD_FIX);
    if (*var_canon_classes)
	cleanup_comm_canon_flags =
	    name_mask(VAR_CANON_CLASSES, canon_class_table,
		      var_canon_classes);
    if (*var_send_canon_classes)
	cleanup_send_canon_flags =
	    name_mask(VAR_CANON_CLASSES, send_canon_class_table,
		      var_send_canon_classes);
    if (*var_rcpt_canon_classes)
	cleanup_rcpt_canon_flags =
	    name_mask(VAR_CANON_CLASSES, rcpt_canon_class_table,
		      var_rcpt_canon_classes);
    if (*var_masq_domains)
	cleanup_masq_domains = argv_split(var_masq_domains, " ,\t\r\n");
    if (*var_header_checks)
	cleanup_header_checks =
	    maps_create(VAR_HEADER_CHECKS, var_header_checks, DICT_FLAG_LOCK);
    if (*var_mimehdr_checks)
	cleanup_mimehdr_checks =
	    maps_create(VAR_MIMEHDR_CHECKS, var_mimehdr_checks, DICT_FLAG_LOCK);
    if (*var_nesthdr_checks)
	cleanup_nesthdr_checks =
	    maps_create(VAR_NESTHDR_CHECKS, var_nesthdr_checks, DICT_FLAG_LOCK);
    if (*var_body_checks)
	cleanup_body_checks =
	    maps_create(VAR_BODY_CHECKS, var_body_checks, DICT_FLAG_LOCK);
    if (*var_masq_exceptions)
	cleanup_masq_exceptions =
	    string_list_init(MATCH_FLAG_NONE, var_masq_exceptions);
    if (*var_masq_classes)
	cleanup_masq_flags = name_mask(VAR_MASQ_CLASSES, masq_class_table,
				       var_masq_classes);
    if (*var_send_bcc_maps)
	cleanup_send_bcc_maps =
	    maps_create(VAR_SEND_BCC_MAPS, var_send_bcc_maps,
			DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if (*var_rcpt_bcc_maps)
	cleanup_rcpt_bcc_maps =
	    maps_create(VAR_RCPT_BCC_MAPS, var_rcpt_bcc_maps,
			DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
    if (*var_cleanup_milters)
	cleanup_milters = milter_create(var_cleanup_milters,
					var_milt_conn_time,
					var_milt_cmd_time,
					var_milt_msg_time,
					var_milt_protocol,
					var_milt_def_action,
					var_milt_conn_macros,
					var_milt_helo_macros,
					var_milt_mail_macros,
					var_milt_rcpt_macros,
					var_milt_data_macros,
					var_milt_eoh_macros,
					var_milt_eod_macros,
					var_milt_unk_macros);

    flush_init();
}
Exemplo n.º 25
0
/** 
 * Write a File to disk
 * 
 * @param lsdd 
 *    Set the Output to be a SDD file
 * @param nerr 
 *    Error Return Flag 
 *    - 0 on Success
 *
 * @date   970702:  Changed lckey and lkchar to lckeyExact and lkcharExact
 *                  throughout xw.c.  This will allow files to begin with 
 *                  the same string as the various options (eg. sacxz.021.z)
 *                  maf.
 * @date   910731:  Bug fixed in options PREPEND, DELETE, CHANGE.
 * @date   900904:  Added SDD as a format for write.
 * @date   881228:  Added four new options for generating write file list
 *                  from data file list: APPEND, PREPEND, CHANGE, DELETE.
 * @date   880204:  Fixed logic involving use of DIR option in READ and WRITE
 *                  by adding an ON/OFF flag as well as a directory name.
 * @date   880115:  Deleted call that forced default directory to lowercase.
 * @date   870626:  Added default directory option.
 * @date   860917:  Changed to character lists for storing data file names.
 * @date   850730:  Deleted SOCKITTOME  format.
 * @date   830120:  Added SOCK and CI output formats.
 * @date   820721:  Changed to newest set of parsing and checking functions.
 * @date   810120:  Changed to output message retrieval from disk.
 * @date   810203:  Fixed bug in file overwrite option.
 *
 */
void 
xw(int  lsdd, 
   int *nerr) {

    int i;
        char delimiter[2], kcdir[9], kchange[MCPFN+1], kdirpart[MCPFN+1];
	char kfile[MCPFN+1], kpdir[9], kstring[MCPFN+1], ktemp[9];
	int lexpnd;
	int jdfl, nchange, nchar, nchg, ndx1, ndx2;
	int nlen, nstr, nstring, nwrdir;
	static int lwrdir = FALSE;
    char *cattemp;
    char *strtemp1, *strtemp2, *strtemp3;
    
    char *file;
    string_list *list, *files;

	kschan[12]='\0';
	kschdr[80]='\0';
	ksclas[4]='\0';
	kscom[40]='\0';
	ksevnm[8]='\0';
	ksfrmt[8]='\0';
	ksstnm[8]='\0';
    memset(kfile, 0, sizeof(kfile));
    memset(kdirpart, 0, sizeof(kdirpart));
    memset(kchange, 0, sizeof(kchange));
    memset(ktemp, 0, sizeof(ktemp));
    memset(kstring, 0, sizeof(kstring));
    memset(kpdir, 0, sizeof(kpdir));
    memset(kcdir, 0, sizeof(kcdir));
    memset(delimiter, 0, sizeof(delimiter));

        lexpnd = FALSE;

	*nerr = 0;

    files = string_list_init();
    list  = NULL;

	if( lsdd )
	    cmdfm.iwfmt = 3;

	/* PARSING PHASE: */
	/* - Loop on each token in command: */
	while ( lcmore( nerr ) ){

	    /* -- "SAC|ALPHA":  set format to be used in writing files. */
	    if( lckeyExact( "SAC#$",6 ) )
		cmdfm.iwfmt = 1;

	    else if( lckeyExact( "ALPHA#$",8 ) )
		cmdfm.iwfmt = 2;

	    else if( lckeyExact( "CI#$",5 ) )
		cmdfm.iwfmt = 2;

	    else if( lckeyExact( "SDD#$",6 ) )
		cmdfm.iwfmt = 3;

	    else if( lckeyExact( "XDR#$",6 ) ) {
		cmdfm.iwfmt = 4;
            }
            else if( lckeyExact( "SEGY#$", 7 ) )
                cmdfm.iwfmt = 5;

	    /* -- "OVER":  overwrite files from previous READ command. */
	    else if( lckeyExact( "OVER#$",7 ) ){
		cmdfm.lovrrq = TRUE;
		lexpnd = FALSE;
        string_list_extend(files, datafiles);
	    }

	    /* generate names from the KSTCMP header field */
	    else if( lckeyExact( "KSTCMP#$",9 ) ){
		lexpnd = FALSE;
		gennames("KSTCMP ",7,files,string_list_length(datafiles),nerr);
		if(*nerr != 0)
		    goto L_8888;
	    }

	    /* -- "APPEND string": append string to filenames from READ command. */
	    else if( lkcharExact( "APPEND#$",9, MCPFN, kstring,MCPFN+1, &nstring ) ){
        for(i = 0; i < cmdfm.ndfl; i++) {
            strtemp1 = string_list_get(datafiles, i);
		    appendstring( kstring,MCPFN+1, strtemp1, strlen(strtemp1)+2, kfile,MCPFN+1 );

            string_list_put(files, kfile, MCPFN+1);
		    if( *nerr != 0 )
                goto L_8888;
		}
		cmdfm.lovrrq = FALSE;
		lexpnd = TRUE;
	    }

	    /* -- "PREPEND string": prepend string to filenames from READ command. */
	    else if( lkcharExact( "PREPEND#$",10, MCPFN, kstring,MCPFN+1, &nstring ) ){
        for(i = 0; i < cmdfm.ndfl; i++) {
		    strtemp1 = malloc(nstring+1);
		    strncpy(strtemp1,kstring,nstring);
		    strtemp1[nstring] = '\0';
            strtemp2 = string_list_get(datafiles, i);
		    prependstring( strtemp1, nstring+1, strtemp2, strlen(strtemp2)+2, kfile,MCPFN+1);

		    free(strtemp1);
            string_list_put(files, kfile, MCPFN+1);
		    if( *nerr != 0 )
			goto L_8888;
		}
		cmdfm.lovrrq = FALSE;
		lexpnd = TRUE;
	    }

	    /* -- "DELETE string": delete string from filenames from READ command. */
	    else if( lkcharExact( "DELETE#$",9, MCPFN, kstring,MCPFN+1, &nstring ) ){
        for(i = 0; i < cmdfm.ndfl; i++) {
		    strtemp1 = malloc(nstring+1);
		    strncpy(strtemp1,kstring,nstring);
		    strtemp1[nstring] = '\0';
            strtemp2 = string_list_get(datafiles, i);

		    deletestring( strtemp1, nstring+1, strtemp2, strlen(strtemp2)+2, kfile,MCPFN+1);

		    free(strtemp1);
            string_list_put(files, kfile, MCPFN+1);
		    if( *nerr != 0 )
			goto L_8888;
		}
		cmdfm.lovrrq = FALSE;
		lexpnd = TRUE;
	    }

	    /* -- "CHANGE string1 string2": change string1 to string2 in READ filenames. */
	    else if( lkcharExact( "CHANGE#$",9, MCPFN, kstring,MCPFN+1, &nstring ) ){
		lcchar( MCPFN, kchange,MCPFN+1, &nchange );
        for(i = 0; i < cmdfm.ndfl; i++) {
		    nstr = indexb( kstring,MCPFN+1 );
		    nchg = indexb( kchange,MCPFN+1 );

		    strtemp1 = malloc(nstr+1);
		    strtemp2 = malloc(nchg+1);
		    strncpy(strtemp1,kstring,nstr);
		    strncpy(strtemp2,kchange,nchg);
		    strtemp1[nstr] = '\0';
		    strtemp2[nchg] = '\0';
            strtemp3 = string_list_get(datafiles, i);
		    changestring( strtemp1, nstr+1, strtemp2, nchg+1,
                          strtemp3, strlen(strtemp3)+2, kfile,MCPFN+1 );

		    free(strtemp1);            
		    free(strtemp2);

            string_list_put(files, kfile, MCPFN+1);
		    if( *nerr != 0 )
			goto L_8888;
		}
		cmdfm.lovrrq = FALSE;
		lexpnd = TRUE;
	    }

	    /* -- "DIR ON|OFF|CURRENT|name":  set the name of the default subdirectory. */
	    else if( lkcharExact( "DIR#$",6, MCPFN, kmdfm.kwrdir,MCPFN+1, &nchar ) ){
		modcase( TRUE, kmdfm.kwrdir, MCPW, ktemp );

		if( strncmp(ktemp,"OFF     ",8) == 0 ) {
          lwrdir = FALSE;
        } else if( strncmp(ktemp,"CURRENT ",8) == 0 ){
          lwrdir = TRUE;
          fstrncpy( kmdfm.kwrdir, MCPFN, " ", 1);
		} else if( kmdfm.kwrdir[nchar - 1] != KDIRDL ){ 
          /* If the string is mising the "/" path separator */
          lwrdir = TRUE;
          delimiter[0] = KDIRDL;
          delimiter[1] = '\0';
          subscpy( kmdfm.kwrdir, nchar, -1, MCPFN, delimiter );
		} else {
          /* Path is not OFF, CURRENT and has the "/" at the end */
          lwrdir = TRUE;
	    }
        }
	    /* -- "COMMIT|RECALLTRACE|ROLLBACK": 
	          how to treat existing data */
	    else if ( lckeyExact ( "COMMIT" , 7 ) )
		cmdfm.icomORroll = COMMIT ;
	    else if (lckeyExact ( "RECALLTRACE" , 12 ) )
		cmdfm.icomORroll = RECALL ;
	    else if ( lckeyExact ( "RECALL" , 7 ) )
		cmdfm.icomORroll = RECALL ;
	    else if ( lckeyExact ( "ROLLBACK" , 9 ) ) 
		cmdfm.icomORroll = ROLLBACK ;


	    /* -- "filelist":  write files using names in new filelist. */
	    else if( ( list = lcdfl() ) ){
		cmdfm.lovrrq = FALSE;
		lexpnd = FALSE;
	    }

	    /* -- Bad syntax. */
	    else{
		cfmt( "ILLEGAL OPTION:",17 );
		cresp();
	    }
	} /* end while ( lcmore( nerr ) ) */

	/* - The above loop is over when one of two conditions has been met:
	 *   (1) An error in parsing has occurred.  In this case NERR is > 0 .
	 *   (2) All the tokens in the command have been successfully parsed. */

	if( *nerr != 0 )
	    goto L_8888;

	/* CHECKING PHASE: */
    if(!list) {
        list = files;
    } else {
        /* List + Modifiers :: Use List */
        string_list_free(files);
        files = NULL;
    }

	/* - Check for null write filelist. */
	if( string_list_length(list) <= 0 ){
	    *nerr = 1311;
	    setmsg( "ERROR", *nerr );
	    goto L_8888;
	}

	/* - Make sure the write filelist has as many entries as read filelist. */

	if( string_list_length(list) != cmdfm.ndfl ){
	    *nerr = 1312;
        error(1312, "%d %d", string_list_length(list), cmdfm.ndfl);
	    goto L_8888;
	}

	/* EXECUTION PHASE: */

        /* - Commit or rollback data according to cmdfm.icomORroll */
	alignFiles ( nerr ) ;
	if ( *nerr )
	    return ;


	/* - Echo expanded filelist if requested. */

	if( cmdfm.lechof && lexpnd ){
	    setmsg( "OUTPUT", 0 );

        for(i = 0; i < string_list_length(list); i++) {
            file = string_list_get(list, i);

            getdir( file, strlen(file)+1, kcdir,9, kfile,MCPFN+1 );

		/* -- Echo the filename part if there is no directory part. */
            if( strcmp(kcdir,"        ") == 0 )
                apcmsg( kfile,MCPFN+1 );

		/* -- Prepend the filename part with some special characters if
         *    directory part is same as that of the previous file. */
            else if( memcmp(kcdir,kpdir,min(strlen(kcdir),strlen(kpdir)))
                     == 0 ){
                cattemp = malloc(3+strlen(kfile)+1);
                strcpy(cattemp, "...");
                strcat(cattemp,kfile);
                apcmsg( cattemp, 3+strlen(kfile)+1 );
                free(cattemp);
            }
		/* -- Echo complete pathname if directory part is different. */
            else{
                apcmsg2(file, strlen(file)+1);
                strcpy( kpdir, kcdir );
            }
	    }
	    wrtmsg( MUNOUT );
	}

	/* - Write each file in memory to disk. */

	nwrdir = indexb( kmdfm.kwrdir,MCPFN+1 );
	for( jdfl = 1; jdfl <= cmdfm.ndfl; jdfl++ ){
	    /* -- Get file from memory manager. */
        file = string_list_get(list, jdfl-1);
	    getfil( jdfl, TRUE, &nlen, &ndx1, &ndx2, nerr );
	    if( *nerr != 0 )
		goto L_8888;

	    /* isolate file name */
        file = string_list_get(list, jdfl-1);

	    /* -- Check overwrite-protect flag in header record. */
	    if( cmdfm.lovrrq && !*lovrok ){
		*nerr = 1303;
		setmsg( "ERROR", *nerr );
		apcmsg2(file, strlen(file)+1);
		outmsg () ;
		clrmsg () ;
		goto L_8888;
	    }

	    /* -- Prepare output file name:
	     * --- If directory option is ON (lwrdir=.TRUE. and nwrdir>0), 
	     *     concatenate directory name with file name part of write file list.
	     * --- If directory option is CURRENT (lwrdir=.TRUE. and nwrdir=0), 
	     *     use file name part of write file list.
	     * --- If directory option is OFF, use write file list. */
	    if( lwrdir ){
		if( nwrdir > 0 ){
		    fstrncpy( kfile, MCPFN, kmdfm.kwrdir,min(nwrdir,MCPFN));

            strtemp1 = file;
		    strtemp2 = malloc(130-(nwrdir+1));
		    strncpy(strtemp2,kfile+nwrdir,MCPFN+1-(nwrdir + 1));
		    strtemp2[MCPFN+1-(nwrdir+1)] = '\0';
		    getdir( strtemp1, strlen(strtemp1)+1, 
                    kdirpart, MCPFN+1, strtemp2,-(nwrdir+1)+130);
		    subscpy(kfile,nwrdir,-1,MCPFN,strtemp2);
		    free(strtemp2);
		}
		else{
		    fstrncpy( kfile, MCPFN, " ", 1);
		    getdir( file, strlen(file)+1, kdirpart,MCPFN+1, kfile,MCPFN+1 );
		}
	    }
	    else {
            fstrncpy( kfile, MCPFN, file, strlen(file));
        }
	    /* -- Write file in appropriate format. */
	    if( cmdfm.iwfmt == 2 )
		wrci( jdfl, kfile,MCPFN+1, "%#15.7g", nerr );

	    else if( cmdfm.iwfmt == 3 )
		wrsdd( jdfl, kfile,MCPFN+1, TRUE, nerr );

	    else if( cmdfm.iwfmt == 4 )
		wrxdr( jdfl, kfile,MCPFN+1, TRUE, nerr );

	    else if( cmdfm.iwfmt == 5 )
		wrsegy( jdfl , kfile , nerr ) ;

	    else
		wrsac( jdfl, kfile,MCPFN+1, TRUE, nerr );

	    if( *nerr != 0 )
		goto L_8888;

	} /* end for ( jdfl ) */

L_8888:
	return;
}
Exemplo n.º 26
0
int ls(const char *path, ulong flags)
{
	DIR *dir;
	struct dirent *d;
	char tmp[PATH_MAX];
	struct stat s;
	struct string_list sl;

	string_list_init(&sl);

	if (stat(path, &s))
		return errno;

	if (flags & LS_SHOWARG && s.st_mode & S_IFDIR)
		printf("%s:\n", path);

	if (!(s.st_mode & S_IFDIR)) {
		ls_one(path, &s);
		return 0;
	}

	dir = opendir(path);
	if (!dir)
		return errno;

	while ((d = readdir(dir))) {
		sprintf(tmp, "%s/%s", path, d->d_name);
		if (stat(tmp, &s))
			goto out;
		if (flags & LS_COLUMN)
			string_list_add_sorted(&sl, d->d_name);
		else
			ls_one(d->d_name, &s);
	}

	closedir(dir);

	if (flags & LS_COLUMN) {
		string_list_print_by_column(&sl);
		string_list_free(&sl);
	}

	if (!(flags & LS_RECURSIVE))
		return 0;

	dir = opendir(path);
	if (!dir) {
		errno = -ENOENT;
		return -ENOENT;
	}

	while ((d = readdir(dir))) {

		if (!strcmp(d->d_name, "."))
			continue;
		if (!strcmp(d->d_name, ".."))
			continue;
		sprintf(tmp, "%s/%s", path, d->d_name);

		if (stat(tmp, &s))
			goto out;
		if (s.st_mode & S_IFDIR) {
			char *norm = normalise_path(tmp);
			ls(norm, flags);
			free(norm);
		}
	}
out:
	closedir(dir);

	return 0;
}
Exemplo n.º 27
0
Arquivo: smtp.c Projeto: robn/postfix
static void pre_init(char *unused_name, char **unused_argv)
{
    int     use_tls;
    static const NAME_CODE addr_pref_map[] = {
        INET_PROTO_NAME_IPV6, SMTP_MISC_FLAG_PREF_IPV6,
        INET_PROTO_NAME_IPV4, SMTP_MISC_FLAG_PREF_IPV4,
        INET_PROTO_NAME_ANY, 0,
        0, -1,
    };

    /*
     * Turn on per-peer debugging.
     */
    debug_peer_init();

    /*
     * SASL initialization.
     */
    if (var_smtp_sasl_enable)
#ifdef USE_SASL_AUTH
        smtp_sasl_initialize();
#else
        msg_warn("%s is true, but SASL support is not compiled in",
                 VAR_SMTP_SASL_ENABLE);
#endif

    if (*var_smtp_tls_level != 0)
        switch (tls_level_lookup(var_smtp_tls_level)) {
        case TLS_LEV_SECURE:
        case TLS_LEV_VERIFY:
        case TLS_LEV_FPRINT:
        case TLS_LEV_ENCRYPT:
            var_smtp_use_tls = var_smtp_enforce_tls = 1;
            break;
        case TLS_LEV_MAY:
            var_smtp_use_tls = 1;
            var_smtp_enforce_tls = 0;
            break;
        case TLS_LEV_NONE:
            var_smtp_use_tls = var_smtp_enforce_tls = 0;
            break;
        default:
            /* tls_level_lookup() logs no warning. */
            /* session_tls_init() assumes that var_smtp_tls_level is sane. */
            msg_fatal("Invalid TLS level \"%s\"", var_smtp_tls_level);
        }
    use_tls = (var_smtp_use_tls || var_smtp_enforce_tls);

    /*
     * Initialize the TLS data before entering the chroot jail
     */
    if (use_tls || var_smtp_tls_per_site[0] || var_smtp_tls_policy[0]) {
#ifdef USE_TLS
        TLS_CLIENT_INIT_PROPS props;
        int     using_smtp = (strcmp(var_procname, "smtp") == 0);

        /*
         * We get stronger type safety and a cleaner interface by combining
         * the various parameters into a single tls_client_props structure.
         *
         * Large parameter lists are error-prone, so we emulate a language
         * feature that C does not have natively: named parameter lists.
         */
        smtp_tls_ctx =
            TLS_CLIENT_INIT(&props,
                            log_param = using_smtp ?
                                        VAR_SMTP_TLS_LOGLEVEL : VAR_LMTP_TLS_LOGLEVEL,
                            log_level = var_smtp_tls_loglevel,
                            verifydepth = var_smtp_tls_scert_vd,
                            cache_type = using_smtp ?
                                         TLS_MGR_SCACHE_SMTP : TLS_MGR_SCACHE_LMTP,
                            cert_file = var_smtp_tls_cert_file,
                            key_file = var_smtp_tls_key_file,
                            dcert_file = var_smtp_tls_dcert_file,
                            dkey_file = var_smtp_tls_dkey_file,
                            eccert_file = var_smtp_tls_eccert_file,
                            eckey_file = var_smtp_tls_eckey_file,
                            CAfile = var_smtp_tls_CAfile,
                            CApath = var_smtp_tls_CApath,
                            fpt_dgst = var_smtp_tls_fpt_dgst);
        smtp_tls_list_init();
#else
        msg_warn("TLS has been selected, but TLS support is not compiled in");
#endif
    }

    /*
     * Flush client.
     */
    flush_init();

    /*
     * Session cache domain list.
     */
    if (*var_smtp_cache_dest)
        smtp_cache_dest = string_list_init(MATCH_FLAG_RETURN, var_smtp_cache_dest);

    /*
     * EHLO keyword filter.
     */
    if (*var_smtp_ehlo_dis_maps)
        smtp_ehlo_dis_maps = maps_create(VAR_SMTP_EHLO_DIS_MAPS,
                                         var_smtp_ehlo_dis_maps,
                                         DICT_FLAG_LOCK);

    /*
     * PIX bug workarounds.
     */
    if (*var_smtp_pix_bug_maps)
        smtp_pix_bug_maps = maps_create(VAR_SMTP_PIX_BUG_MAPS,
                                        var_smtp_pix_bug_maps,
                                        DICT_FLAG_LOCK);

    /*
     * Generic maps.
     */
    if (*var_prop_extension)
        smtp_ext_prop_mask =
            ext_prop_mask(VAR_PROP_EXTENSION, var_prop_extension);
    if (*var_smtp_generic_maps)
        smtp_generic_maps =
            maps_create(VAR_SMTP_GENERIC_MAPS, var_smtp_generic_maps,
                        DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);

    /*
     * Header/body checks.
     */
    smtp_header_checks = hbc_header_checks_create(
                             VAR_SMTP_HEAD_CHKS, var_smtp_head_chks,
                             VAR_SMTP_MIME_CHKS, var_smtp_mime_chks,
                             VAR_SMTP_NEST_CHKS, var_smtp_nest_chks,
                             smtp_hbc_callbacks);
    smtp_body_checks = hbc_body_checks_create(
                           VAR_SMTP_BODY_CHKS, var_smtp_body_chks,
                           smtp_hbc_callbacks);

    /*
     * Server reply filter.
     */
    if (*var_smtp_resp_filter)
        smtp_chat_resp_filter =
            dict_open(var_smtp_resp_filter, O_RDONLY,
                      DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);

    /*
     * Address family preference.
     */
    if (*var_smtp_addr_pref) {
        smtp_addr_pref = name_code(addr_pref_map, NAME_CODE_FLAG_NONE,
                                   var_smtp_addr_pref);
        if (smtp_addr_pref < 0)
            msg_fatal("bad %s value: %s", VAR_SMTP_ADDR_PREF, var_smtp_addr_pref);
    }
}
Exemplo n.º 28
0
static int do_ls(struct command *cmdtp, int argc, char *argv[])
{
	int ret, opt, o;
	struct stat s;
	ulong flags = LS_COLUMN;
	struct string_list sl;

	while((opt = getopt(argc, argv, "RCl")) > 0) {
		switch(opt) {
		case 'R':
			flags |= LS_RECURSIVE | LS_SHOWARG;
			break;
		case 'C':
			flags |= LS_COLUMN;
			break;
		case 'l':
			flags &= ~LS_COLUMN;
			break;
		}
	}

	if (argc - optind > 1)
		flags |= LS_SHOWARG;

	if (optind == argc) {
		ret = ls(getcwd(), flags);
		return ret ? 1 : 0;
	}

	string_list_init(&sl);

	o = optind;

	/* first pass: all files */
	while (o < argc) {
		ret = stat(argv[o], &s);
		if (ret) {
			printf("%s: %s: %s\n", argv[0],
					argv[o], errno_str());
			o++;
			continue;
		}

		if (!(s.st_mode & S_IFDIR)) {
			if (flags & LS_COLUMN)
				string_list_add_sorted(&sl, argv[o]);
			else
				ls_one(argv[o], &s);
		}

		o++;
	}

	if (flags & LS_COLUMN)
		string_list_print_by_column(&sl);

	string_list_free(&sl);

	o = optind;

	/* second pass: directories */
	while (o < argc) {
		ret = stat(argv[o], &s);
		if (ret) {
			o++;
			continue;
		}

		if (s.st_mode & S_IFDIR) {
			ret = ls(argv[o], flags);
			if (ret) {
				perror("ls");
				o++;
				continue;
			}
		}

		o++;
	}

	return 0;
}