Exemplo n.º 1
0
/* translates SELinux context from human to raw format and
 * appends it to the mount extra options.
 *
 * returns -1 on error and 0 on success
 */
static int
append_context(const char *optname, char *optdata, char **extra_opts)
{
	security_context_t raw = NULL;
	char *data = NULL;

	if (is_selinux_enabled() != 1)
		/* ignore the option if we running without selinux */
		return 0;

	if (optdata == NULL || *optdata == '\0' || optname == NULL)
		return -1;

	/* TODO: use strip_quotes() for all mount options? */
	data = *optdata == '"' ? strip_quotes(optdata) : optdata;

	if (selinux_trans_to_raw_context(
			(security_context_t) data, &raw) == -1 ||
			raw == NULL)
		return -1;

	if (verbose)
		printf(_("%s: translated %s '%s' to '%s'\n"),
		       progname, optname, data, (char *) raw);

	*extra_opts = append_opt(*extra_opts, optname, NULL);
	*extra_opts = xstrconcat4(*extra_opts, "\"", (char *) raw, "\"");

	freecon(raw);
	return 0;
}
Exemplo n.º 2
0
static Character const* __cdecl get_directory(
    Character const*  const alternative,
    Character const** const result
    ) throw()
{
    typedef __acrt_stdio_char_traits<Character> stdio_traits;

    __crt_unique_heap_ptr<Character const> tmp(get_tmp_directory<Character>());
    if (tmp.get() != nullptr)
    {
        if (stdio_traits::taccess_s(tmp.get(), 0) == 0)
            return *result = tmp.detach();

        // Otherwise, try stripping quotes out of the TMP path and check again:
        __crt_unique_heap_ptr<Character const> unquoted_tmp(strip_quotes(tmp.get()));
        if (unquoted_tmp.get() != nullptr && stdio_traits::taccess_s(unquoted_tmp.get(), 0) == 0)
            return *result = unquoted_tmp.detach();
    }

    // Otherwise, the TMP path is not usable; use the alternative path if one
    // was provided and is accessible:
    if (alternative != nullptr && stdio_traits::taccess_s(alternative, 0) == 0)
        return (*result = alternative), nullptr;

    // Otherwise, fall back to \ or .:
    static Character const root_fallback[] = { '\\', '\0' };
    static Character const cwd_fallback [] = { '.',  '\0' };
    
    if (stdio_traits::taccess_s(root_fallback, 0) == 0)
        return (*result = root_fallback), nullptr;

    return (*result = cwd_fallback), nullptr;
}
Exemplo n.º 3
0
static int _set_rec(int *start, int argc, char *argv[],
		    slurmdb_job_rec_t *job)
{
	int i;
	int set = 0;
	int end = 0;
	int command_len = 0;

	for (i=(*start); i<argc; i++) {
		end = parse_option_end(argv[i]);
		if (!end)
			command_len=strlen(argv[i]);
		else {
			command_len=end-1;
			if (argv[i][end] == '=') {
				end++;
			}
		}

		if (!strncasecmp (argv[i], "Where", MAX(command_len, 5))) {
			i--;
			break;
		} else if (!end && !strncasecmp(argv[i], "set",
					       MAX(command_len, 3))) {
			continue;
		} else if (!end) {
			exit_code=1;
			fprintf(stderr,
				" Bad format on %s: End your option with "
				"an '=' sign\n", argv[i]);
		} else if ((!strncasecmp(argv[i], "DerivedExitCode",
					 MAX(command_len, 12))) ||
			   (!strncasecmp(argv[i], "DerivedEC",
					 MAX(command_len, 9)))) {
			if (get_uint(argv[i]+end, &job->derived_ec,
				     "DerivedExitCode") == SLURM_SUCCESS) {
				set = 1;
			}
		} else if ((!strncasecmp(argv[i], "Comment",
					 MAX(command_len, 7))) ||
			   (!strncasecmp(argv[i], "DerivedExitString",
					 MAX(command_len, 12))) ||
			   (!strncasecmp(argv[i], "DerivedES",
					 MAX(command_len, 9)))) {
			if (job->derived_es)
				xfree(job->derived_es);
			job->derived_es = strip_quotes(argv[i]+end, NULL, 1);
			set = 1;
		} else {
			printf(" Unknown option: %s\n"
			       " Use keyword 'where' to modify condition\n",
			       argv[i]);
		}
	}

	(*start) = i;

	return set;
}
Exemplo n.º 4
0
/* parses the destination directory parameters from pszSection
 * the parameters are of the form: root,key,value,unknown,fallback
 * we first read the reg value root\\key\\value and if that fails,
 * use fallback as the destination directory
 */
static void get_dest_dir(HINF hInf, PCWSTR pszSection, PWSTR pszBuffer, DWORD dwSize)
{
    INFCONTEXT context;
    WCHAR key[MAX_PATH + 2], value[MAX_PATH + 2];
    WCHAR prefix[PREFIX_LEN + 2];
    HKEY root, subkey = 0;
    DWORD size;

    static const WCHAR hklm[] = {'H','K','L','M',0};
    static const WCHAR hkcu[] = {'H','K','C','U',0};

    /* load the destination parameters */
    SetupFindFirstLineW(hInf, pszSection, NULL, &context);
    SetupGetStringFieldW(&context, 1, prefix, PREFIX_LEN + 2, &size);
    strip_quotes(prefix, &size);
    SetupGetStringFieldW(&context, 2, key, MAX_PATH + 2, &size);
    strip_quotes(key, &size);
    SetupGetStringFieldW(&context, 3, value, MAX_PATH + 2, &size);
    strip_quotes(value, &size);

    if (!lstrcmpW(prefix, hklm))
        root = HKEY_LOCAL_MACHINE;
    else if (!lstrcmpW(prefix, hkcu))
        root = HKEY_CURRENT_USER;
    else
        root = NULL;

    size = dwSize * sizeof(WCHAR);

    /* fallback to the default destination dir if reg fails */
    if (RegOpenKeyW(root, key, &subkey) ||
        RegQueryValueExW(subkey, value, NULL, NULL, (LPBYTE)pszBuffer, &size))
    {
        SetupGetStringFieldW(&context, 5, pszBuffer, dwSize, &size);
        strip_quotes(pszBuffer, &size);
    }

    if (subkey) RegCloseKey(subkey);
}
Exemplo n.º 5
0
Arquivo: hook.c Projeto: jollywho/nav
void hook_add(char *group, char *event, char *pattern, char *expr, int id)
{
  log_msg("HOOK", "ADD");
  log_msg("HOOK", "<%s> %s `%s`", event, pattern, expr);

  EventHandler *evh = get_event(event_idx(event));
  if (!evh)
    return;

  expr = strip_quotes(expr);

  Pattern *pat = NULL;
  if (pattern)
    pat = regex_pat_new(pattern);

  Hook hook = { id, HK_CMD, NULL, NULL, NULL, pat, .data.cmd = expr };
  augroup_insert(group, &hook);
  utarray_push_back(evh->hooks, &hook);
}

static void hook_delete(EventHandler *evh, Augroup *aug)
{
  for (int i = 0; i < utarray_len(evh->hooks); i++) {
    Hook *it = (Hook*)utarray_eltptr(evh->hooks, i);
    if (it->type == HK_CMD && it->aug == aug) {
      free(it->data.cmd);
      utarray_erase(evh->hooks, i, 1);
    }
  }
}

void hook_remove(char *group, char *event, char *pattern)
{
  log_msg("HOOK", "REMOVE");
  log_msg("HOOK", "<%s> %s `%s`", event, pattern, group);

  Augroup *aug = NULL;
  if (group)
    HASH_FIND_STR(aug_tbl, group, aug);

  if (event) {
    EventHandler *evh = get_event(event_idx(event));
    if (!evh)
      return;
    return hook_delete(evh, aug);
  }

  EventHandler *it;
  for (it = default_events; it != NULL; it = it->hh.next)
    hook_delete(it, aug);
}
Exemplo n.º 6
0
void PymolWriter::cleanup(std::string name, bool close) {
  if (close) {
    if (open_type_ != NONE) {
      get_stream() << "END,\n";
      open_type_ = NONE;
    }
    if (lastname_ != placeholder_name) get_stream() << "]\n";
  }
  lastname_ = placeholder_name;
  get_stream() << "k= '" << strip_quotes(name) << "'" << std::endl;
  get_stream() << "if k in data.keys():\n"
               << "  data[k]= data[k]+curdata\nelse:\n"
               << "  data[k]= curdata\n\n";
}
Exemplo n.º 7
0
int conf_parse(const char *filename,
               int (*handler) (void *, const char *, const char *),
               void *usercfg)
{
    FILE *fin;
    char buf[MAX_LINE];

    char *start;
    char *end;
    char *name;
    char *value;

    int error = 0;

    fin = fopen(filename, "r");
    if (!fin)
        return -1;

    int lineno = 0;

    /* Scan through file line by line */
    while (fgets(buf, sizeof(buf), fin) != NULL) {
        lineno++;
        start = lskip(rstrip(buf));     /* chop whites */

        if (*start && *start != '#') {
            /* Not a comment, must be a name = value pair  */
            end = find_char_or_comment(start, '=');
            if (*end == '=') {
                *end = '\0';
                name = rstrip(start);
                value = lskip(end + 1);
                end = find_char_or_comment(value, '#');
                if (*end == '#')
                    *end = '\0';
                value = rstrip(value);
                value = strip_quotes(value);
                /* Valid name=value pair found, call handler  */
                if (handler(usercfg, name, value) && !error)
                    error = lineno;
            } else if (!error) {
                /* No '=' found on name=value line  */
                error = lineno;
            }
        }
    }
    fclose(fin);
    return error;
}
Exemplo n.º 8
0
static gn_error ReplyIdentify(int messagetype, unsigned char *buffer, int length, gn_data *data, struct gn_statemachine *state)
{
	at_line_buffer buf;
	gn_error error;
	char *model;

	/* If we got incorrect answer, fallback to the default handler;
	 * we got error handling in there.
	 * strlen(buffer) < 2 is to avoid overflow with buffer + 1
	 */
	if (strlen(buffer) < 2 || strncmp(buffer + 1, "AT+CGMM", 7) != 0) {
		return (*identify)(messagetype, buffer, length, data, state);
	}

	if ((error = at_error_get(buffer, state)) != GN_ERR_NONE)
		return error;

	buf.line1 = buffer + 1;
	buf.length = length;
	splitlines(&buf);

	/* The line usually looks like:
	 * +CGMM: "GSM900","GSM1800","GSM1900","GSM850","MODEL=V547"
	 */
	model = strstr(buf.line2, "MODEL=");
	if (!model) {
		snprintf(data->model, GN_MODEL_MAX_LENGTH, "%s", strip_quotes(buf.line2 + 1 + strlen("+CGMM: ")));
	} else {
		snprintf(data->model, GN_MODEL_MAX_LENGTH, "%s", strip_quotes(model + strlen("MODEL=")));
		model = strchr(data->model, '"');
		if (model)
			*model = '\0';
	}

	return GN_ERR_NONE;
}
Exemplo n.º 9
0
void PymolWriter::setup(std::string name, Type type, bool opendata) {
  if (name == lastname_) {
    if (open_type_ != type && open_type_ != NONE) {
      get_stream() << "END,\n";
      open_type_ = NONE;
    }
    return;
  } else if (lastname_ != placeholder_name) {
    cleanup(lastname_);
  }
  if (name.empty()) {
    name = "unnamed";
  }
  get_stream() << "k= '" << strip_quotes(name) << "'\n";
  get_stream() << "if not k in data.keys():\n"
               << "   data[k]=[]\n";
  if (opendata) get_stream() << "curdata=[\n";
  lastname_ = name;
}
Exemplo n.º 10
0
/*
 *	defread() - read an entry from the defopen file
 *
 *	defread(cp)
 *		char *cp
 *
 *	The defopen data file must have been previously opened by
 *	defopen().  defread scans the data file looking for a line
 *	which begins with the string '*cp'.  If such a line is found,
 *	defread returns a pointer to the first character following
 *	the matched string (*cp).  If no line is found or no file
 *	is open, defread() returns NULL.
 *
 *	Note that there is no way to simulatniously peruse multiple
 *	defopen files; since there is no way of indicating 'which one'
 *	to defread().  If you want to peruse a secondary file you must
 *	recall defopen().  If you need to go back to the first file,
 *	you must call defopen() again.
 */
char *
defread(char *cp)
{
	struct thr_data *thr_data = _get_thr_data();
	int (*compare)(const char *, const char *, size_t);
	char *buf_tmp, *ret_ptr = NULL;
	size_t off, patlen;

	if (thr_data == NULL)
		return (NULL);

	if (thr_data->fp == NULL)
		return (NULL);

	compare = TSTBITS(thr_data->Dcflags, DC_CASE) ? strncmp : strncasecmp;
	patlen = strlen(cp);

	if (!TSTBITS(thr_data->Dcflags, DC_NOREWIND))
		rewind(thr_data->fp);

	while (fgets(thr_data->buf, sizeof (thr_data->buf), thr_data->fp)) {
		for (buf_tmp = thr_data->buf; *buf_tmp == ' '; buf_tmp++)
			;
		off = strlen(buf_tmp) - 1;
		if (buf_tmp[off] == '\n')
			buf_tmp[off] = 0;
		else
			break;	/* line too long */
		if ((*compare)(cp, buf_tmp, patlen) == 0) {
			/* found it */
			/* strip quotes if requested */
			if (TSTBITS(thr_data->Dcflags, DC_STRIP_QUOTES)) {
				strip_quotes(buf_tmp);
			}
			ret_ptr = &buf_tmp[patlen];
			break;
		}
	}

	return (ret_ptr);
}
Exemplo n.º 11
0
extern int get_uint(char *in_value, uint32_t *out_value, char *type)
{
	char *ptr = NULL, *meat = NULL;
	long num;

	if (!(meat = strip_quotes(in_value, NULL))) {
		error("Problem with strip_quotes");
		return SLURM_ERROR;
	}
	num = strtol(meat, &ptr, 10);
	if ((num == 0) && ptr && ptr[0]) {
		error("Invalid value for %s (%s)", type, meat);
		xfree(meat);
		return SLURM_ERROR;
	}
	xfree(meat);

	if (num < 0)
		*out_value = INFINITE;		/* flag to clear */
	else
		*out_value = (uint32_t) num;
	return SLURM_SUCCESS;
}
Exemplo n.º 12
0
extern int sacctmgr_archive_load(int argc, char *argv[])
{
	int rc = SLURM_SUCCESS;
	slurmdb_archive_rec_t *arch_rec =
		xmalloc(sizeof(slurmdb_archive_rec_t));
	int i=0, command_len = 0;
	struct stat st;

	for (i=0; i<argc; i++) {
		int end = parse_option_end(argv[i]);
		if (!end)
			command_len=strlen(argv[i]);
		else {
			command_len=end-1;
			if (argv[i][end] == '=') {
				end++;
			}
		}

		if (!end
		   || !strncasecmp (argv[i], "File", MAX(command_len, 1))) {
			arch_rec->archive_file =
				strip_quotes(argv[i]+end, NULL, 0);
		} else if (!strncasecmp (argv[i], "Insert",
					 MAX(command_len, 2))) {
			arch_rec->insert = strip_quotes(argv[i]+end, NULL, 1);
		} else {
			exit_code=1;
			fprintf(stderr, " Unknown option: %s\n", argv[i]);
		}
	}

	if (exit_code) {
		slurmdb_destroy_archive_rec(arch_rec);
		return SLURM_ERROR;
	}

	if (arch_rec->archive_file) {
		char *fullpath;
		char cwd[MAXPATHLEN + 1];
		int  mode = F_OK;

		if ((getcwd(cwd, MAXPATHLEN)) == NULL)
			fatal("getcwd failed: %m");

		if ((fullpath = search_path(cwd, arch_rec->archive_file,
					    true, mode, false))) {
			xfree(arch_rec->archive_file);
			arch_rec->archive_file = fullpath;
		}

		if (stat(arch_rec->archive_file, &st) < 0) {
			exit_code = errno;
			fprintf(stderr, " load: Failed to stat %s: %s\n "
				"Note: For archive load, the file must be on "
				"the calling host.\n",
				arch_rec->archive_file, slurm_strerror(errno));
			return SLURM_ERROR;
		}
	}

	rc = jobacct_storage_g_archive_load(db_conn, arch_rec);
	if (rc == SLURM_SUCCESS) {
		if (commit_check("Would you like to commit changes?")) {
			acct_storage_g_commit(db_conn, 1);
		} else {
			printf(" Changes Discarded\n");
			acct_storage_g_commit(db_conn, 0);
		}
	} else {
		exit_code=1;
		fprintf(stderr, " Problem loading archive file: %s\n",
			slurm_strerror(rc));
		rc = SLURM_ERROR;
	}

	slurmdb_destroy_archive_rec(arch_rec);

	return rc;
}
Exemplo n.º 13
0
static int _set_cond(int *start, int argc, char *argv[],
		     slurmdb_archive_cond_t *arch_cond)
{
	int i;
	int set = 0;
	int end = 0;
	int command_len = 0;
 	uint32_t tmp;
	slurmdb_job_cond_t *job_cond = NULL;

	if (!arch_cond) {
		error("No arch_cond given");
		return -1;
	}
	if (!arch_cond->job_cond)
		arch_cond->job_cond = xmalloc(sizeof(slurmdb_job_cond_t));
	job_cond = arch_cond->job_cond;

	for (i=(*start); i<argc; i++) {
		end = parse_option_end(argv[i]);
		if (!end)
			command_len=strlen(argv[i]);
		else {
			command_len=end-1;
			if (argv[i][end] == '=') {
				end++;
			}
		}

		if (!end && !strncasecmp(argv[i], "where",
					MAX(command_len, 5))) {
			continue;
		} else if (!end && !strncasecmp(argv[i], "events",
					  MAX(command_len, 1))) {
			arch_cond->purge_event |= SLURMDB_PURGE_ARCHIVE;
			set = 1;
		} else if (!end && !strncasecmp(argv[i], "jobs",
					  MAX(command_len, 1))) {
			arch_cond->purge_job |= SLURMDB_PURGE_ARCHIVE;
			set = 1;
		} else if (!end && !strncasecmp(argv[i], "reservations",
					  MAX(command_len, 1))) {
			arch_cond->purge_resv |= SLURMDB_PURGE_ARCHIVE;
			set = 1;
		} else if (!end && !strncasecmp(argv[i], "steps",
					  MAX(command_len, 1))) {
			arch_cond->purge_step |= SLURMDB_PURGE_ARCHIVE;
			set = 1;
		} else if (!end && !strncasecmp(argv[i], "suspend",
					  MAX(command_len, 1))) {
			arch_cond->purge_suspend |= SLURMDB_PURGE_ARCHIVE;
			set = 1;
		} else if (!end
			  || !strncasecmp(argv[i], "Clusters",
					  MAX(command_len, 1))) {
			if (!job_cond->cluster_list)
				job_cond->cluster_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(job_cond->cluster_list,
					      argv[i]+end);
			set = 1;
		} else if (!strncasecmp (argv[i], "Accounts",
					 MAX(command_len, 2))) {
			if (!job_cond->acct_list)
				job_cond->acct_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(job_cond->acct_list,
					      argv[i]+end);
			set = 1;
		} else if (!strncasecmp (argv[i], "Associations",
					 MAX(command_len, 2))) {
			if (!job_cond->associd_list)
				job_cond->associd_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(job_cond->associd_list,
					      argv[i]+end);
			set = 1;
		} else if (!strncasecmp (argv[i], "Directory",
					 MAX(command_len, 2))) {
			arch_cond->archive_dir =
				strip_quotes(argv[i]+end, NULL, 0);
			set = 1;
		} else if (!strncasecmp (argv[i], "End", MAX(command_len, 1))) {
			job_cond->usage_end = parse_time(argv[i]+end, 1);
			set = 1;
		} else if (!strncasecmp (argv[i], "Gid", MAX(command_len, 2))) {
			if (!job_cond->groupid_list)
				job_cond->groupid_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(job_cond->groupid_list,
					      argv[i]+end);
			set = 1;
		} else if (!strncasecmp (argv[i], "Jobs",
					 MAX(command_len, 1))) {
			char *end_char = NULL, *start_char = argv[i]+end;
			slurmdb_selected_step_t *selected_step = NULL;
			char *dot = NULL;
			if (!job_cond->step_list)
				job_cond->step_list =
					list_create(slurm_destroy_char);

			while ((end_char = strstr(start_char, ","))
			       && start_char) {
				*end_char = 0;
				while (isspace(*start_char))
					start_char++;  /* discard whitespace */
				if (!(int)*start_char)
					continue;
				selected_step = xmalloc(
					sizeof(slurmdb_selected_step_t));
				list_append(job_cond->step_list, selected_step);

				dot = strstr(start_char, ".");
				if (dot == NULL) {
					debug2("No jobstep requested");
					selected_step->stepid = NO_VAL;
				} else {
					*dot++ = 0;
					selected_step->stepid = atoi(dot);
				}
				selected_step->jobid = atoi(start_char);
				start_char = end_char + 1;
			}

			set = 1;
		} else if (!strncasecmp (argv[i], "Partitions",
					 MAX(command_len, 2))) {
			if (!job_cond->partition_list)
				job_cond->partition_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(job_cond->partition_list,
					      argv[i]+end);
			set = 1;
		} else if (!strncasecmp (argv[i], "PurgeEventAfter",
					 MAX(command_len, 10))) {
			if ((tmp = slurmdb_parse_purge(argv[i]+end))
			    == NO_VAL) {
				exit_code = 1;
			} else {
				arch_cond->purge_event |= tmp;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeJobAfter",
					 MAX(command_len, 10))) {
			if ((tmp = slurmdb_parse_purge(argv[i]+end))
			    == NO_VAL) {
				exit_code = 1;
			} else {
				arch_cond->purge_job |= tmp;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeResvAfter",
					 MAX(command_len, 10))) {
			if ((tmp = slurmdb_parse_purge(argv[i]+end))
			    == NO_VAL) {
				exit_code = 1;
			} else {
				arch_cond->purge_resv |= tmp;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeStepAfter",
					 MAX(command_len, 10))) {
			if ((tmp = slurmdb_parse_purge(argv[i]+end))
			    == NO_VAL) {
				exit_code = 1;
			} else {
				arch_cond->purge_step |= tmp;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeSuspendAfter",
					 MAX(command_len, 10))) {
			if ((tmp = slurmdb_parse_purge(argv[i]+end))
			    == NO_VAL) {
				exit_code = 1;
			} else {
				arch_cond->purge_suspend |= tmp;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeEventMonths",
					 MAX(command_len, 6))) {
			if (get_uint(argv[i]+end, &tmp, "PurgeEventMonths")
			    != SLURM_SUCCESS) {
				exit_code = 1;
			} else {
				arch_cond->purge_event |= tmp;
				arch_cond->purge_event |= SLURMDB_PURGE_MONTHS;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeJobMonths",
					 MAX(command_len, 6))) {
			if (get_uint(argv[i]+end, &tmp, "PurgeJobMonths")
			    != SLURM_SUCCESS) {
				exit_code = 1;
			} else {
				arch_cond->purge_job |= tmp;
				arch_cond->purge_job |= SLURMDB_PURGE_MONTHS;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeResvMonths",
					 MAX(command_len, 6))) {
			if (get_uint(argv[i]+end, &tmp, "PurgeResvMonths")
			    != SLURM_SUCCESS) {
				exit_code = 1;
			} else {
				arch_cond->purge_resv |= tmp;
				arch_cond->purge_resv |= SLURMDB_PURGE_MONTHS;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeStepMonths",
					 MAX(command_len, 7))) {
			if (get_uint(argv[i]+end, &tmp, "PurgeStepMonths")
			    != SLURM_SUCCESS) {
				exit_code = 1;
			} else {
				arch_cond->purge_step |= tmp;
				arch_cond->purge_step |= SLURMDB_PURGE_MONTHS;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "PurgeSuspendMonths",
					 MAX(command_len, 7))) {
			if (get_uint(argv[i]+end, &tmp, "PurgeSuspendMonths")
			    != SLURM_SUCCESS) {
				exit_code = 1;
			} else {
				arch_cond->purge_suspend |= tmp;
				arch_cond->purge_suspend
					|= SLURMDB_PURGE_MONTHS;
				set = 1;
			}
		} else if (!strncasecmp (argv[i], "Start",
					 MAX(command_len, 2))) {
			job_cond->usage_start = parse_time(argv[i]+end, 1);
			set = 1;
		} else if (!strncasecmp (argv[i], "Script",
					 MAX(command_len, 2))) {
			arch_cond->archive_script =
				strip_quotes(argv[i]+end, NULL, 0);
			set = 1;
		} else if (!strncasecmp (argv[i], "Users",
					 MAX(command_len, 1))) {
			if (!job_cond->userid_list)
				job_cond->userid_list =
					list_create(slurm_destroy_char);
			_addto_uid_char_list(job_cond->userid_list,
					     argv[i]+end);
			set = 1;
		} else {
			exit_code=1;
			fprintf(stderr, " Unknown condition: %s\n", argv[i]);
		}
	}

	(*start) = i;

	return set;
}
Exemplo n.º 14
0
void SimpleJsonParser::parse( std::vector<CString>& tokens )
{
    enum ParseState {
        SCAN=1,
        ARRAY,
        PAIR,
        PAIR_COLON,
        RVALUE,
        RVALUE_SEPARATOR
    };

    ParseState state = SCAN;
    LPCSTR tag_name = NULL;
    CString array_index;
    std::stack<JsonNode *> nodeStack;

    m_values.clear();
    m_type = JSONROOT;

    nodeStack.push( this );

    for ( CString& token : tokens ) {
        // printf( "%s ", (LPCSTR)token );

        switch ( state ) {
            case SCAN:
                if ( token == "[" ) {                   // Start of array
                    m_type = JSONARRAY;
                    state = RVALUE;
                    break;
                }
                else if ( token == "{" ) {              // Start of object
                    m_type = JSONOBJECT;
                    state = PAIR;
                    break;
                }

                throw std::exception( "Parser expected opening object or array" );

            case PAIR:
                // Check for empty object
                if ( token == "}" && nodeStack.top()->m_type == JSONOBJECT && nodeStack.top()->m_values.size() == 0 ) {
                    nodeStack.pop();
                    state = RVALUE_SEPARATOR;
                    break;
                }

                tag_name = strip_quotes( token );
                state = PAIR_COLON;
                break;

            case PAIR_COLON:
                if ( token != ":" )
                    throw std::exception( "Parser expecting colon seperator" );
                state = RVALUE;
                break;

            case RVALUE: {
                if ( token == "]" ) {       // Empty array
                    if ( nodeStack.top()->m_type != JSONARRAY  )
                        throw std::exception( "Unexpected array closing bracket" );

                    nodeStack.pop();
                    state = RVALUE_SEPARATOR;
                    break;
                }

                JsonNode* node = nodeStack.top();

                if ( node->m_type == JSONARRAY ) {
                    array_index.Format( "%d", node->m_values.size() );
                    tag_name = (LPCSTR)array_index;
                }

                if ( node->m_values.find( tag_name ) != node->m_values.end() ) {
                    CString error;
                    error.Format( "Duplicate JSON tag name '%s'", tag_name );
                    throw std::exception( (LPCSTR)error );
                }

                if ( token == "[" ) {
                    node->m_values[ tag_name ] = JsonNode( JSONARRAY );
                    state = RVALUE;
                    nodeStack.push( &node->m_values[ tag_name ] );
                    break;
                }

                if ( token == "{" ) {
                    node->m_values[ tag_name ] = JsonNode( JSONOBJECT );
                    state = PAIR;
                    nodeStack.push( &node->m_values[ tag_name ] );
                    break;
                }

                // Add a constant to current node container

                if ( node->m_type != JSONOBJECT && node->m_type != JSONARRAY)
                    throw std::exception( "Parser expecting container JSON node" );

                node->m_values[ tag_name ] = JsonNode( strip_quotes( token ) );
                state = RVALUE_SEPARATOR;
                break;
            }

            case RVALUE_SEPARATOR: {
                JsonNode* node = nodeStack.top();

                if ( token == "," ) {
                    state = node->m_type == JSONARRAY ? RVALUE : PAIR;
                    break;
                }

                if ( token == "}" && node->m_type == JSONOBJECT  ) {
                    nodeStack.pop();
                    break;
                }

                if ( token == "]" && node->m_type == JSONARRAY ) {
                    // Assert all non-null nodes in the array are the same type
                    JsonNodeType expected_type = JSONNULL;
                    for ( auto child : node->m_values ) {
                        if ( child.second.m_type == JSONNULL )
                            ;
                        else if ( expected_type == JSONNULL )
                            expected_type = child.second.m_type;
                        else if ( child.second.m_type != expected_type ) {
                            CString error;
                            error.Format( "Mixed object types in '%s'", child.first );
                            throw std::exception( (LPCSTR)error );
                        }
                    }

                    nodeStack.pop();
                    break;
                }

                throw std::exception( "Parser expecting object or array seperator" );
            }
        }
    }

    if ( nodeStack.size() > 0 )
        throw std::exception( "Unclosed JSON objects detected" );
}
Exemplo n.º 15
0
static int _set_res_rec(int *start, int argc, char *argv[],
			List name_list, List cluster_list,
			slurmdb_res_rec_t *res)
{
	int i;
	int set = 0;
	int end = 0;
	int command_len = 0;
	int option = 0;

	xassert(res);

	for (i=(*start); i<argc; i++) {
		end = parse_option_end(argv[i]);
		if (!end)
			command_len=strlen(argv[i]);
		else {
			command_len=end-1;
			if (argv[i][end] == '=') {
				option = (int)argv[i][end-1];
				end++;
			}
		}

		if (!strncasecmp(argv[i], "Where", MAX(command_len, 5))) {
			i--;
			break;
		} else if (!end && !strncasecmp(argv[i], "set",
						MAX(command_len, 3))) {
			continue;
		} else if (!end
			  || !strncasecmp(argv[i], "Names",
					  MAX(command_len, 1))
			   || !strncasecmp(argv[i], "Resources",
					   MAX(command_len, 1))) {
			if (name_list)
				slurm_addto_char_list(name_list, argv[i]+end);
		} else if (!strncasecmp(argv[i], "Clusters",
					 MAX(command_len, 1))) {
			if (cluster_list) {
				slurm_addto_char_list(cluster_list,
						      argv[i]+end);
				if (sacctmgr_validate_cluster_list(
					    cluster_list) != SLURM_SUCCESS) {
					exit_code=1;
					fprintf(stderr,
						" Need a valid cluster name to "
						"add a cluster resource.\n");
				}
			} else {
				exit_code=1;
				fprintf(stderr,
					" Can't modify the cluster "
					"of an resource\n");
			}
		} else if (!strncasecmp(argv[i], "Count",
					MAX(command_len, 3))) {
			if (get_uint(argv[i]+end, &res->count,
				     "count") == SLURM_SUCCESS) {
				set = 1;
			}
		} else if (!strncasecmp(argv[i], "Description",
					 MAX(command_len, 1))) {
			if (!res->description)
				res->description =
					strip_quotes(argv[i]+end, NULL, 1);
			set = 1;
		} else if (!strncasecmp(argv[i], "Flags",
					 MAX(command_len, 2))) {
			res->flags = str_2_res_flags(argv[i]+end, option);
			if (res->flags == SLURMDB_RES_FLAG_NOTSET) {
				char *tmp_char = slurmdb_res_flags_str(
					SLURMDB_RES_FLAG_BASE);
				printf(" Unknown Server Resource flag used "
				       "in:\n  '%s'\n"
				       " Valid Server Resource flags are\n"
				       " '%s'\n", argv[i]+end, tmp_char);
				xfree(tmp_char);
				exit_code = 1;
			} else
				set = 1;
		} else if (!strncasecmp(argv[i], "Manager",
					 MAX(command_len, 1))) {
			if (!res->manager)
				res->manager =
					strip_quotes(argv[i]+end, NULL, 1);
			set = 1;
		} else if (!strncasecmp(argv[i], "PercentAllowed",
					MAX(command_len, 1))) {
			/* overload percent_used here */
			if (get_uint16(argv[i]+end, &res->percent_used,
				       "PercentAllowed") == SLURM_SUCCESS) {
				set = 1;
			}
		} else if (!strncasecmp(argv[i], "Server",
					  MAX(command_len, 1))) {
			if (!res->server) {
				res->server=
					strip_quotes(argv[i]+end, NULL, 1);
			}
			set = 1;
		} else if (!strncasecmp(argv[i], "Type",
					MAX(command_len, 1))) {
			char *temp = strip_quotes(argv[i]+end, NULL, 1);

			if (!strncasecmp("License", temp,
					 MAX(strlen(temp), 1))) {
				res->type = SLURMDB_RESOURCE_LICENSE;
			} else {
				exit_code=1;
				fprintf(stderr,
					" Unknown resource type: '%s'  "
					"Valid resources is License.\n",
					temp);
			}
		} else {
			exit_code = 1;
			printf(" Unknown option: %s\n"
			       " Use keyword 'where' to modify condition\n",
			       argv[i]);
		}
	}

	(*start) = i;

	return set;
}
Exemplo n.º 16
0
/*
 * parse_slash_copy parses copy options from the given meta-command line. The
 * function then returns a dynamically allocated structure with the options, or
 * Null on parsing error.
 */
copy_options *
parse_slash_copy(const char *args)
{
	struct copy_options *result;
	char	   *token;
	const char *whitespace = " \t\n\r";
	char		nonstd_backslash = standard_strings() ? 0 : '\\';

	if (!args)
	{
		psql_error("\\copy: arguments required\n");
		return NULL;
	}

	result = pg_malloc0(sizeof(struct copy_options));

	result->before_tofrom = pg_strdup("");		/* initialize for appending */

	token = strtokx(args, whitespace, ".,()", "\"",
					0, false, false, pset.encoding);
	if (!token)
		goto error;

	/* The following can be removed when we drop 7.3 syntax support */
	if (pg_strcasecmp(token, "binary") == 0)
	{
		xstrcat(&result->before_tofrom, token);
		token = strtokx(NULL, whitespace, ".,()", "\"",
						0, false, false, pset.encoding);
		if (!token)
			goto error;
	}

	/* Handle COPY (SELECT) case */
	if (token[0] == '(')
	{
		int			parens = 1;

		while (parens > 0)
		{
			xstrcat(&result->before_tofrom, " ");
			xstrcat(&result->before_tofrom, token);
			token = strtokx(NULL, whitespace, "()", "\"'",
							nonstd_backslash, true, false, pset.encoding);
			if (!token)
				goto error;
			if (token[0] == '(')
				parens++;
			else if (token[0] == ')')
				parens--;
		}
	}

	xstrcat(&result->before_tofrom, " ");
	xstrcat(&result->before_tofrom, token);
	token = strtokx(NULL, whitespace, ".,()", "\"",
					0, false, false, pset.encoding);
	if (!token)
		goto error;

	/*
	 * strtokx() will not have returned a multi-character token starting with
	 * '.', so we don't need strcmp() here.  Likewise for '(', etc, below.
	 */
	if (token[0] == '.')
	{
		/* handle schema . table */
		xstrcat(&result->before_tofrom, token);
		token = strtokx(NULL, whitespace, ".,()", "\"",
						0, false, false, pset.encoding);
		if (!token)
			goto error;
		xstrcat(&result->before_tofrom, token);
		token = strtokx(NULL, whitespace, ".,()", "\"",
						0, false, false, pset.encoding);
		if (!token)
			goto error;
	}

	if (token[0] == '(')
	{
		/* handle parenthesized column list */
		for (;;)
		{
			xstrcat(&result->before_tofrom, " ");
			xstrcat(&result->before_tofrom, token);
			token = strtokx(NULL, whitespace, "()", "\"",
							0, false, false, pset.encoding);
			if (!token)
				goto error;
			if (token[0] == ')')
				break;
		}
		xstrcat(&result->before_tofrom, " ");
		xstrcat(&result->before_tofrom, token);
		token = strtokx(NULL, whitespace, ".,()", "\"",
						0, false, false, pset.encoding);
		if (!token)
			goto error;
	}

	if (pg_strcasecmp(token, "from") == 0)
		result->from = true;
	else if (pg_strcasecmp(token, "to") == 0)
		result->from = false;
	else
		goto error;

	/* { 'filename' | PROGRAM 'command' | STDIN | STDOUT | PSTDIN | PSTDOUT } */
	token = strtokx(NULL, whitespace, ";", "'",
					0, false, false, pset.encoding);
	if (!token)
		goto error;

	if (pg_strcasecmp(token, "program") == 0)
	{
		int			toklen;

		token = strtokx(NULL, whitespace, ";", "'",
						0, false, false, pset.encoding);
		if (!token)
			goto error;

		/*
		 * The shell command must be quoted. This isn't fool-proof, but
		 * catches most quoting errors.
		 */
		toklen = strlen(token);
		if (token[0] != '\'' || toklen < 2 || token[toklen - 1] != '\'')
			goto error;

		strip_quotes(token, '\'', 0, pset.encoding);

		result->program = true;
		result->file = pg_strdup(token);
	}
	else if (pg_strcasecmp(token, "stdin") == 0 ||
			 pg_strcasecmp(token, "stdout") == 0)
	{
		result->file = NULL;
	}
	else if (pg_strcasecmp(token, "pstdin") == 0 ||
			 pg_strcasecmp(token, "pstdout") == 0)
	{
		result->psql_inout = true;
		result->file = NULL;
	}
	else
	{
		/* filename can be optionally quoted */
		strip_quotes(token, '\'', 0, pset.encoding);
		result->file = pg_strdup(token);
		expand_tilde(&result->file);
	}

	/* Collect the rest of the line (COPY options) */
	token = strtokx(NULL, "", NULL, NULL,
					0, false, false, pset.encoding);
	if (token)
		result->after_tofrom = pg_strdup(token);

	/* set data staging options to null */
	result->tableName = NULL;
	result->columnList = NULL;

	return result;

error:
	if (token)
		psql_error("\\copy: parse error at \"%s\"\n", token);
	else
		psql_error("\\copy: parse error at end of line\n");
	free_copy_options(result);

	return NULL;
}
Exemplo n.º 17
0
/*
 * Replacement for strtok() (a.k.a. poor man's flex)
 *
 * Splits a string into tokens, returning one token per call, then NULL
 * when no more tokens exist in the given string.
 *
 * The calling convention is similar to that of strtok, but with more
 * frammishes.
 *
 * s -			string to parse, if NULL continue parsing the last string
 * whitespace - set of whitespace characters that separate tokens
 * delim -		set of non-whitespace separator characters (or NULL)
 * quote -		set of characters that can quote a token (NULL if none)
 * escape -		character that can quote quotes (0 if none)
 * e_strings -	if TRUE, treat E'...' syntax as a valid token
 * del_quotes - if TRUE, strip quotes from the returned token, else return
 *				it exactly as found in the string
 * encoding -	the active character-set encoding
 *
 * Characters in 'delim', if any, will be returned as single-character
 * tokens unless part of a quoted token.
 *
 * Double occurrences of the quoting character are always taken to represent
 * a single quote character in the data.  If escape isn't 0, then escape
 * followed by anything (except \0) is a data character too.
 *
 * The combination of e_strings and del_quotes both TRUE is not currently
 * handled.  This could be fixed but it's not needed anywhere at the moment.
 *
 * Note that the string s is _not_ overwritten in this implementation.
 *
 * NB: it's okay to vary delim, quote, and escape from one call to the
 * next on a single source string, but changing whitespace is a bad idea
 * since you might lose data.
 */
char *
strtokx(const char *s,
		const char *whitespace,
		const char *delim,
		const char *quote,
		char escape,
		bool e_strings,
		bool del_quotes,
		int encoding)
{
	static char *storage = NULL;/* store the local copy of the users string
								 * here */
	static char *string = NULL; /* pointer into storage where to continue on
								 * next call */

	/* variously abused variables: */
	unsigned int offset;
	char	   *start;
	char	   *p;

	if (s)
	{
		free(storage);

		/*
		 * We may need extra space to insert delimiter nulls for adjacent
		 * tokens.	2X the space is a gross overestimate, but it's unlikely
		 * that this code will be used on huge strings anyway.
		 */
		storage = pg_malloc(2 * strlen(s) + 1);
		strcpy(storage, s);
		string = storage;
	}

	if (!storage)
		return NULL;

	/* skip leading whitespace */
	offset = strspn(string, whitespace);
	start = &string[offset];

	/* end of string reached? */
	if (*start == '\0')
	{
		/* technically we don't need to free here, but we're nice */
		free(storage);
		storage = NULL;
		string = NULL;
		return NULL;
	}

	/* test if delimiter character */
	if (delim && strchr(delim, *start))
	{
		/*
		 * If not at end of string, we need to insert a null to terminate the
		 * returned token.	We can just overwrite the next character if it
		 * happens to be in the whitespace set ... otherwise move over the
		 * rest of the string to make room.  (This is why we allocated extra
		 * space above).
		 */
		p = start + 1;
		if (*p != '\0')
		{
			if (!strchr(whitespace, *p))
				memmove(p + 1, p, strlen(p) + 1);
			*p = '\0';
			string = p + 1;
		}
		else
		{
			/* at end of string, so no extra work */
			string = p;
		}

		return start;
	}

	/* check for E string */
	p = start;
	if (e_strings &&
		(*p == 'E' || *p == 'e') &&
		p[1] == '\'')
	{
		quote = "'";
		escape = '\\';			/* if std strings before, not any more */
		p++;
	}

	/* test if quoting character */
	if (quote && strchr(quote, *p))
	{
		/* okay, we have a quoted token, now scan for the closer */
		char		thisquote = *p++;

		for (; *p; p += PQmblen(p, encoding))
		{
			if (*p == escape && p[1] != '\0')
				p++;			/* process escaped anything */
			else if (*p == thisquote && p[1] == thisquote)
				p++;			/* process doubled quote */
			else if (*p == thisquote)
			{
				p++;			/* skip trailing quote */
				break;
			}
		}

		/*
		 * If not at end of string, we need to insert a null to terminate the
		 * returned token.	See notes above.
		 */
		if (*p != '\0')
		{
			if (!strchr(whitespace, *p))
				memmove(p + 1, p, strlen(p) + 1);
			*p = '\0';
			string = p + 1;
		}
		else
		{
			/* at end of string, so no extra work */
			string = p;
		}

		/* Clean up the token if caller wants that */
		if (del_quotes)
			strip_quotes(start, thisquote, escape, encoding);

		return start;
	}

	/*
	 * Otherwise no quoting character.	Scan till next whitespace, delimiter
	 * or quote.  NB: at this point, *start is known not to be '\0',
	 * whitespace, delim, or quote, so we will consume at least one character.
	 */
	offset = strcspn(start, whitespace);

	if (delim)
	{
		unsigned int offset2 = strcspn(start, delim);

		if (offset > offset2)
			offset = offset2;
	}

	if (quote)
	{
		unsigned int offset2 = strcspn(start, quote);

		if (offset > offset2)
			offset = offset2;
	}

	p = start + offset;

	/*
	 * If not at end of string, we need to insert a null to terminate the
	 * returned token.	See notes above.
	 */
	if (*p != '\0')
	{
		if (!strchr(whitespace, *p))
			memmove(p + 1, p, strlen(p) + 1);
		*p = '\0';
		string = p + 1;
	}
	else
	{
		/* at end of string, so no extra work */
		string = p;
	}

	return start;
}
Exemplo n.º 18
0
static int _set_cond(int *start, int argc, char *argv[],
		     slurmdb_reservation_cond_t *reservation_cond,
		     List format_list)
{
	int i;
	int set = 0;
	int end = 0;
	int command_len = 0;

	if (!reservation_cond) {
		exit_code=1;
		fprintf(stderr, "No reservation_cond given");
		return -1;
	}

	for (i=(*start); i<argc; i++) {
		end = parse_option_end(argv[i]);
		if (!end)
			command_len=strlen(argv[i]);
		else {
			command_len=end-1;
			if (argv[i][end] == '=') {
				end++;
			}
		}

		if (!strncasecmp(argv[i], "Set", MAX(command_len, 3))) {
			i--;
			break;
		} else if (!end && !strncasecmp(argv[i], "where",
					       MAX(command_len, 5))) {
			continue;
		} else if (!strncasecmp(argv[i], "Clusters",
					 MAX(command_len, 1))) {
			if (!reservation_cond->cluster_list) {
				reservation_cond->cluster_list =
					list_create(slurm_destroy_char);
			}
			if (slurm_addto_char_list(reservation_cond->name_list,
						  argv[i]+end))
				set = 1;
		} else if (!strncasecmp(argv[i], "Names",
					 MAX(command_len, 2))) {
			if (!reservation_cond->name_list) {
				reservation_cond->name_list =
					list_create(slurm_destroy_char);
			}
			if (slurm_addto_char_list(reservation_cond->name_list,
						  argv[i]+end))
				set = 1;
		} else if (!strncasecmp(argv[i], "Format",
					 MAX(command_len, 1))) {
			if (format_list)
				slurm_addto_char_list(format_list, argv[i]+end);
		} else if (!strncasecmp(argv[i], "Ids",
					 MAX(command_len, 1))) {
			if (!reservation_cond->id_list) {
				reservation_cond->id_list =
					list_create(slurm_destroy_char);
			}
			if (slurm_addto_char_list(reservation_cond->id_list,
						 argv[i]+end))
				set = 1;
		} else if (!strncasecmp(argv[i], "Nodes",
					 MAX(command_len, 2))) {
			xfree(reservation_cond->nodes);
			reservation_cond->nodes = strip_quotes(
				argv[i]+end, NULL, 1);
			set = 1;
		} else if (!strncasecmp(argv[i], "Start",
					 MAX(command_len, 5))) {
			reservation_cond->time_start =
				parse_time(argv[i]+end, 1);
			if (errno == ESLURM_INVALID_TIME_VALUE)
				exit_code = 1;
			else
				set = 1;
		} else if (!strncasecmp(argv[i], "End",
					 MAX(command_len, 5))) {
			reservation_cond->time_end =
				parse_time(argv[i]+end, 1);
			if (errno == ESLURM_INVALID_TIME_VALUE)
				exit_code = 1;
			else
				set = 1;
		} else {
			exit_code=1;
			fprintf(stderr, " Unknown condition: %s\n"
				" Use keyword 'set' to modify value\n",
				argv[i]);
		}
	}

	(*start) = i;

	if (set)
		return 1;

	return 0;
}
Exemplo n.º 19
0
static int _set_rec(int *start, int argc, char *argv[],
                    List name_list,
                    slurmdb_qos_rec_t *qos)
{
    int i, mins;
    int set = 0;
    int end = 0;
    int command_len = 0;
    int option = 0;

    for (i=(*start); i<argc; i++) {
        end = parse_option_end(argv[i]);
        if(!end)
            command_len=strlen(argv[i]);
        else {
            command_len=end-1;
            if(argv[i][end] == '=') {
                option = (int)argv[i][end-1];
                end++;
            }
        }

        if (!strncasecmp (argv[i], "Where", MAX(command_len, 5))) {
            i--;
            break;
        } else if(!end && !strncasecmp(argv[i], "set",
                                       MAX(command_len, 3))) {
            continue;
        } else if(!end
                  || !strncasecmp (argv[i], "Name",
                                   MAX(command_len, 1))) {
            if(name_list)
                slurm_addto_char_list(name_list, argv[i]+end);
        } else if (!strncasecmp (argv[i], "Description",
                                 MAX(command_len, 1))) {
            if(!qos->description)
                qos->description =
                    strip_quotes(argv[i]+end, NULL, 1);
            set = 1;
        } else if (!strncasecmp (argv[i], "Flags",
                                 MAX(command_len, 2))) {
            if(!qos)
                continue;
            qos->flags = str_2_qos_flags(argv[i]+end, option);
            if (qos->flags == QOS_FLAG_NOTSET) {
                char *tmp_char = NULL;
                qos->flags = INFINITE;
                qos->flags &= (~QOS_FLAG_NOTSET &
                               ~QOS_FLAG_ADD &
                               ~QOS_FLAG_REMOVE);
                tmp_char = slurmdb_qos_flags_str(qos->flags);
                printf(" Unknown QOS flag used in:\n  '%s'\n"
                       " Valid QOS flags are\n  '%s'\n",
                       argv[i]+end, tmp_char);
                xfree(tmp_char);
                exit_code = 1;
            } else
                set = 1;
        } else if (!strncasecmp (argv[i], "GraceTime",
                                 MAX(command_len, 3))) {
            if (!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grace_time,
                         "GraceTime") == SLURM_SUCCESS) {
                set = 1;
            }
        } else if (!strncasecmp (argv[i], "GrpCPUMins",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;
            if (get_uint64(argv[i]+end,
                           &qos->grp_cpu_mins,
                           "GrpCPUMins") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpCPURunMins",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;
            if (get_uint64(argv[i]+end, &qos->grp_cpu_run_mins,
                           "GrpCPURunMins") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpCPUs",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grp_cpus,
                         "GrpCPUs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpJobs",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grp_jobs,
                         "GrpJobs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpMemory",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grp_mem,
                         "GrpMemory") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpNodes",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grp_nodes,
                         "GrpNodes") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpSubmitJobs",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->grp_submit_jobs,
                         "GrpSubmitJobs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "GrpWall",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            mins = time_str2mins(argv[i]+end);
            if (mins != NO_VAL) {
                qos->grp_wall	= (uint32_t) mins;
                set = 1;
            } else {
                exit_code=1;
                fprintf(stderr,
                        " Bad GrpWall time format: %s\n",
                        argv[i]);
            }
        } else if (!strncasecmp (argv[i], "MaxCPUMinsPerJob",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;
            if (get_uint64(argv[i]+end,
                           &qos->max_cpu_mins_pj,
                           "MaxCPUMins") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxCPUsPerJob",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->max_cpus_pj,
                         "MaxCPUs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxCPUsPerUser",
                                 MAX(command_len, 11))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->max_cpus_pu,
                         "MaxCPUsPerUser") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxJobsPerUser",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->max_jobs_pu,
                         "MaxJobs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxNodesPerJob",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end,
                         &qos->max_nodes_pj,
                         "MaxNodes") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxNodesPerUser",
                                 MAX(command_len, 8))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end,
                         &qos->max_nodes_pu,
                         "MaxNodesPerUser") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxSubmitJobsPerUser",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            if (get_uint(argv[i]+end, &qos->max_submit_jobs_pu,
                         "MaxSubmitJobs") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "MaxWallDurationPerJob",
                                 MAX(command_len, 4))) {
            if(!qos)
                continue;
            mins = time_str2mins(argv[i]+end);
            if (mins != NO_VAL) {
                qos->max_wall_pj = (uint32_t) mins;
                set = 1;
            } else {
                exit_code=1;
                fprintf(stderr,
                        " Bad MaxWall time format: %s\n",
                        argv[i]);
            }
        } else if (!strncasecmp (argv[i], "PreemptMode",
                                 MAX(command_len, 8))) {
            if(!qos)
                continue;
            qos->preempt_mode = preempt_mode_num(argv[i]+end);
            if(qos->preempt_mode == (uint16_t)NO_VAL) {
                fprintf(stderr,
                        " Bad Preempt Mode given: %s\n",
                        argv[i]);
                exit_code = 1;
            } else if (qos->preempt_mode == PREEMPT_MODE_SUSPEND) {
                printf("PreemptType and PreemptMode "
                       "values incompatible\n");
                exit_code = 1;
            } else
                set = 1;
            /* Preempt needs to follow PreemptMode */
        } else if (!strncasecmp (argv[i], "Preempt",
                                 MAX(command_len, 7))) {
            if(!qos)
                continue;

            if(!qos->preempt_list)
                qos->preempt_list =
                    list_create(slurm_destroy_char);

            if(!g_qos_list)
                g_qos_list = acct_storage_g_get_qos(
                                 db_conn, my_uid, NULL);

            if(slurmdb_addto_qos_char_list(qos->preempt_list,
                                           g_qos_list, argv[i]+end,
                                           option))
                set = 1;
            else
                exit_code = 1;
        } else if (!strncasecmp (argv[i], "Priority",
                                 MAX(command_len, 3))) {
            if(!qos)
                continue;

            if (get_uint(argv[i]+end, &qos->priority,
                         "Priority") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "UsageFactor",
                                 MAX(command_len, 6))) {
            if(!qos)
                continue;

            if (get_double(argv[i]+end, &qos->usage_factor,
                           "UsageFactor") == SLURM_SUCCESS)
                set = 1;
        } else if (!strncasecmp (argv[i], "UsageThreshold",
                                 MAX(command_len, 6))) {
            if(!qos)
                continue;
            if (get_double(argv[i]+end, &qos->usage_thres,
                           "UsageThreshold") == SLURM_SUCCESS)
                set = 1;
        } else {
            exit_code = 1;
            printf(" Unknown option: %s\n"
                   " Use keyword 'where' to modify condition\n",
                   argv[i]);
        }
    }

    (*start) = i;

    return set;
}
Exemplo n.º 20
0
void run_command_set(char *args) /* {{{ */
{
	/**
	 * set a variable in the statusbar
	 * syntax: variable value
	 */
	var *this_var;
	char *message = NULL, *varname = NULL, *value = NULL;
	int ret = 0;

	/* parse args */
	if (args != NULL)
		ret = sscanf(args, "%ms %m[^\n]", &varname, &value);
	if (ret != 2)
	{
		statusbar_message(cfg.statusbar_timeout, "syntax: set <variable> <value>");
		tnc_fprintf(logfp, LOG_ERROR, "syntax: set <variable> <value> [%d](%s)", ret, args);
		goto cleanup;
	}

	/* find the variable */
	this_var = (var *)find_var(varname);
	if (this_var==NULL)
	{
		statusbar_message(cfg.statusbar_timeout, "variable not found: %s", varname);
		goto cleanup;
	}

	/* check for permission */
	if (this_var->perms == VAR_RO)
	{
		statusbar_message(cfg.statusbar_timeout, "variable is read only: %s", varname);
		goto cleanup;
	}
	if (this_var->perms == VAR_RC && tasklist != NULL)
	{
		statusbar_message(cfg.statusbar_timeout, "variable must be set in config: %s", varname);
		goto cleanup;
	}

	/* set the value */
	switch (this_var->type)
	{
		case VAR_INT:
			ret = sscanf(value, "%d", (int *)this_var->ptr);
			break;
		case VAR_CHAR:
			ret = sscanf(value, "%c", (char *)this_var->ptr);
			break;
		case VAR_STR:
			if (*(char **)(this_var->ptr)!=NULL)
				free(*(char **)(this_var->ptr));
			*(char **)(this_var->ptr) = calloc(strlen(value)+1, sizeof(char));
			ret = NULL!=strcpy(*(char **)(this_var->ptr), value);
			if (ret)
				strip_quotes((char **)this_var->ptr, 1);
			break;
		default:
			ret = 0;
			break;
	}
	if (ret<=0)
		tnc_fprintf(logfp, LOG_ERROR, "failed to parse value from command: set %s %s", varname, value);

	/* acquire the value string and print it */
	message = var_value_message(this_var, 1);
	statusbar_message(cfg.statusbar_timeout, message);

cleanup:
	free(message);
	free(varname);
	free(value);
	return;
} /* }}} */
Exemplo n.º 21
0
Arquivo: time.cpp Projeto: Quna/mspdev
void Def::process_time ()
{
    issue_diag (I_STAGE, false, 0, "processing %s section\n", lc_name);

    // nesting level
    int nesting_level = 0;

    time_def_found_ = true;

    while ((next = scanner_.next_token ()).token != Scanner::tok_time) {

        switch (next.token) {

        case Scanner::tok_end:
            next = scanner_.next_token ();
            if (next.token == Scanner::tok_time) {
                // end of numeric block
                if (nesting_level == 0) 
                    return;

                --nesting_level;
                scanner_.close ();
            }
            else
                issue_diag (E_SYNTAX, true, &next,
                            "wrong section name in END directive\n");
            break;

        case Scanner::tok_copy: {
            next = scanner_.next_token();
            if (next.token != Scanner::tok_string)
                issue_diag (E_SYNTAX, true, &next,
                            "expected string following \"copy\" directive\n");

            // bump up the nesting level
            ++nesting_level;

            // open the file
            scanner_.open (get_pathname (strip_quotes (next.name), next.file));

            // get comment char and escape char; 
            // these informations are stored by the scanner
            while ((next = scanner_.next_token ()).token != Scanner::tok_time) {
                // the LC_IDENTIFICATION section may also have a 
                // LC_TIME token that will mess up the parsing
                if (next.token == Scanner::tok_ident) {
                    while ((next = scanner_.next_token ()).token
                           != Scanner::tok_end);
                    next = scanner_.next_token ();
                }
            }
            break;
        }

        case Scanner::tok_abday: {

            const std::size_t nelems =
                sizeof time_st_.abday / sizeof *time_st_.abday;

            next = extract_string_array (time_st_.abday,
                                         time_st_.wabday,
                                         nelems);
            break;
        }

        case Scanner::tok_day: {

            const std::size_t nelems =
                sizeof time_st_.day / sizeof *time_st_.day;

            next = extract_string_array (time_st_.day,
                                         time_st_.wday,
                                         nelems);
            break;
        }

        case Scanner::tok_abmon: {

            const std::size_t nelems =
                sizeof time_st_.abmon / sizeof *time_st_.abmon;

            next = extract_string_array (time_st_.abmon,
                                         time_st_.wabmon,
                                         nelems);
            break;
        }

        case Scanner::tok_mon: {

            const std::size_t nelems =
                sizeof time_st_.mon / sizeof *time_st_.mon;

            next = extract_string_array (time_st_.mon,
                                         time_st_.wmon,
                                         nelems);
            break;
        }

        case Scanner::tok_d_t_fmt:
            next = scanner_.next_token();
            time_st_.d_t_fmt = convert_string (next.name);
            time_st_.wd_t_fmt = convert_wstring (next);
            break;

        case Scanner::tok_d_fmt:
            next = scanner_.next_token(); 
            time_st_.d_fmt = convert_string (next.name);
            time_st_.wd_fmt = convert_wstring (next);
            break;
        case Scanner::tok_t_fmt:
            next = scanner_.next_token(); 
            time_st_.t_fmt = convert_string (next.name);
            time_st_.wt_fmt = convert_wstring (next);
            break;

        case Scanner::tok_am_pm: {
            const std::size_t nelems =
                sizeof time_st_.am_pm / sizeof *time_st_.am_pm;

            next = extract_string_array (time_st_.am_pm,
                                         time_st_.wam_pm,
                                         nelems);
            break;
        }

        case Scanner::tok_t_fmt_ampm:
            next = scanner_.next_token(); 
            time_st_.t_fmt_ampm = convert_string (next.name);
            time_st_.wt_fmt_ampm = convert_wstring (next);
            break;
            // The time_get and time_put facets do not make use of eras or 
            // alternate digits, so we will ignore this part of the locale
            // definition
        case Scanner::tok_era:
            while ((next = scanner_.next_token()).token == Scanner::tok_string)
                parse_era (next);
            break;
        case Scanner::tok_era_d_fmt:
            next = scanner_.next_token();
            time_st_.era_d_fmt = convert_string (next.name);
            time_st_.wera_d_fmt = convert_wstring (next);
            break;
        case Scanner::tok_era_t_fmt:
            next = scanner_.next_token();
            time_st_.era_t_fmt = convert_string (next.name);
            time_st_.wera_t_fmt = convert_wstring (next);
            break;
        case Scanner::tok_era_d_t_fmt:
            next = scanner_.next_token();
            time_st_.era_d_t_fmt = convert_string (next.name);
            time_st_.wera_d_t_fmt = convert_wstring (next);
            break;
        case Scanner::tok_alt_digits:
            while ((next = scanner_.next_token()).token == Scanner::tok_string)
            {
                alt_digit_t digit;
                digit.n_alt_digit = convert_string (next.name);
                digit.w_alt_digit = convert_wstring (next);
                digit.n_offset = 0;
                digit.w_offset = 0;
                alt_digits_.push_back (digit);
            }
            break;
        default:
            break;
        }

    }
}
Exemplo n.º 22
0
void SimpleJsonParser::parse( SimpleJsonTokenizer& tokenizer )
{
#define IS_BREAK( t, b ) (t[0] == b && t[1] == '\0')

    enum ParseState {
        SCAN=1,
        ARRAY,
        PAIR,
        PAIR_COLON,
        RVALUE,
        RVALUE_SEPARATOR
    };

    ParseState state = SCAN;
    char tag_name[MAXTAGNAMELEN+1];
    CString array_index;

	reset();

	push( this );

	while ( tokenizer.hasToken() ) {
		LPSTR token = tokenizer.nextToken();

        switch ( state ) {
            case SCAN:
                if ( IS_BREAK( token, '[' ) ) {                   // Start of array
					setType( JSONARRAY );
                    state = RVALUE;
                    break;
                }
                else if ( IS_BREAK( token, '{' ) ) {              // Start of object
					setType( JSONOBJECT );
                    state = PAIR;
                    break;
                }

                throw std::exception( "Parser expected opening object or array" );

            case PAIR:
                // Check for empty object
                if ( IS_BREAK( token, '}' ) && top()->getType() == JSONOBJECT && top()->valueCount() == 0 ) {
					pop();
                    state = RVALUE_SEPARATOR;
                    break;
                }

                strcpy_s( tag_name, strip_quotes( token ) );
                state = PAIR_COLON;
                break;

            case PAIR_COLON:
                if ( !IS_BREAK( token, ':' ) )
                    throw std::exception( "Parser expecting colon seperator" );
                state = RVALUE;
                break;

            case RVALUE: {
                if ( IS_BREAK( token, ']' ) ) {       // Empty array
                    if ( top()->getType() != JSONARRAY  )
                        throw std::exception( "Unexpected array closing bracket" );

					pop();
                    state = RVALUE_SEPARATOR;
                    break;
                }

                JsonNode* node = top();

                if ( node->getType() == JSONARRAY ) {
					tag_name[0] = '\0';
                }
                else if ( node->has_key( tag_name ) ) {
                    CString error;
                    error.Format( "Duplicate JSON tag name '%s'", tag_name );
                    throw std::exception( (LPCSTR)error );
                }

                if ( IS_BREAK( token, '[' ) ) {
					push( node->setValue( JSONARRAY, tag_name ) );
                    state = RVALUE;
                    break;
                }

                if ( IS_BREAK( token, '{' )) {
					push( node->setValue( JSONOBJECT, tag_name ) );
                    state = PAIR;
                    break;
                }

                // Add a constant to current node container

                if ( node->getType() != JSONOBJECT && node->getType() != JSONARRAY)
                    throw std::exception( "Parser expecting container JSON node" );

                node->setValue( strip_quotes( token ), tag_name );
                state = RVALUE_SEPARATOR;
                break;
            }

            case RVALUE_SEPARATOR: {
                JsonNode* node = m_nodeStack[m_stack_ptr-1];

                if ( IS_BREAK( token, ',' ) ) {
                    state = node->getType() == JSONARRAY ? RVALUE : PAIR;
                    break;
                }

                if ( IS_BREAK( token, '}' ) && node->getType() == JSONOBJECT  ) {
					pop();
                    break;
                }

                if ( IS_BREAK( token, ']' ) && node->getType() == JSONARRAY ) {
					if ( !node->validateArray( ) ) {
						CString error;
						error.Format( "Mixed object types in '%s'", node->getTagName() );
						throw std::exception( (LPCSTR)error );
					}

					pop();
                    break;
                }

                throw std::exception( "Parser expecting object or array seperator" );
            }
        }
    }

    if ( stackSize() > 0 )
        throw std::exception( "Unclosed JSON objects detected" );
}
Exemplo n.º 23
0
// ----------------------------------------------------------------------------
//
void SimpleJsonParser::parse( LPCSTR json_data )
{
    m_values.clear();

    // May be a simple null nalue
    if ( !_strcmpi( "null", json_data ) )
        return;

    std::vector<CString> tokens = tokenize( json_data, "{},[]:", true );

    ParseState state = OPENING_BRACE;
    LPCSTR tag_name = NULL;

    // For embedded arrays of objects
    int brackets = 0;
    int braces = 0;

    for ( std::vector<CString>::iterator it=tokens.begin(); it != tokens.end(); ++it ) {
        //printf( "%s\n", (*it) );
        switch ( state ) {
            case OPENING_BRACE:
                if ( (*it) == "[" ) {           // Simple array with no name - eek!
                    tag_name = "";
                    m_values[ tag_name ] = "";
                    state = ARRAY_VALUE_OR_SEPARATOR;
                    brackets=1;
                    break;
                }
                else if ( (*it) != "{" )
                    throw std::exception( "Parser expecting opening brace" );
                state = TAG_NAME;
                break;

            case TAG_NAME:
                tag_name = strip_quotes( (*it) );
                state = COLON;
                break;

            case COLON:
                if ( (*it) != ":" )
                    throw std::exception( "Parser expecting colon seperator" );
                state = TAG_VALUE;
                break;
                
            case TAG_VALUE:
                if ( (*it) == "[" ) {
                    m_values[ tag_name ] = "";                    
                    state = ARRAY_VALUE_OR_SEPARATOR;
                    brackets = 1;
                    break;
                }

                if ( (*it) == "{" ) {
                    m_values[ tag_name ] = "\"";
                    m_values[ tag_name ] += (*it);              
                    state = OBJECT;
                    braces = 1;
                    break;
                }

                m_values[ tag_name ] = strip_quotes( (*it) );
                state = TAG_SEPARATOR;
                break;

            case TAG_SEPARATOR:
                if ( (*it) == "," )
                    state = TAG_NAME;
                else if ( (*it) == "}" )
                    state = DONE;
                else
                    throw std::exception( "Parser expecting tag seperator" );
                break;

            case DONE:
                throw std::exception( "Parser unexpected data after JSON obejct end" );

            case ARRAY_VALUE_OR_SEPARATOR:
                if ( "]" == (*it) ) {
                    brackets--;
                    if ( brackets == 0 )
                        state = TAG_SEPARATOR;
                    break;
                }
                else if ( "{" == (*it) ) {
                    state = ARRAY_OF_OBJECTS;
                    m_values[ tag_name ] = "\"";
                    m_values[ tag_name ] += (*it);
                    braces = 1;
                    break;
                }
                else if ( "[" == (*it) ) {
                    m_values[ tag_name ] += "\"";
                    m_values[ tag_name ] += (*it);
                    brackets++;
                    break;
                }

            case ARRAY_VALUE:
                m_values[ tag_name ] += strip_quotes( (*it) );                    
                state = ARRAY_SEPARATOR;
                break;

            case ARRAY_SEPARATOR:
                if ( "]" == (*it) ) {
                    brackets--;
                    if ( brackets == 0 ) {
                        state = TAG_SEPARATOR;
                        break;
                    }
                    m_values[ tag_name ] += (*it);
                    m_values[ tag_name ] += "\"";
                }
                else if ( (*it) == "," ) {
                    m_values[ tag_name ] += (*it);                    
                    state = ARRAY_VALUE_OR_SEPARATOR;
                }
                else
                    throw std::exception( "Parser expecting array item seperator" );
                break;

            case ARRAY_OF_OBJECTS: {
                if ( "]" == (*it) ) {
                    brackets--;
                    if ( brackets == 0 ) {
                        state = TAG_SEPARATOR;
                        break;
                    }
                }
                else if ( "[" == (*it) )
                    brackets++;
                else if ( "{" == (*it) )
                    braces++;
                else if ( "}" == (*it) )
                    braces--;

                CString escaped ( (*it) );
                escaped.Replace( "\"", "\\\"" );

                m_values[ tag_name ] += escaped;

                if ( !braces )
                    m_values[ tag_name ] += "\"";

                break;
            }

            case OBJECT: {
                if ( "}" == (*it) ) {
                    braces--;
                    if ( braces == 0 ) {
                       m_values[ tag_name ] += (*it);
                       m_values[ tag_name ] += "\"";
                        state = TAG_SEPARATOR;
                        break;
                    }
                }
                else if ( "{" == (*it) )
                    braces++;

                CString escaped ( (*it) );
                escaped.Replace( "\"", "\\\"" );

                m_values[ tag_name ] += escaped;
                break;
            }
        }
    }
}
Exemplo n.º 24
0
void Def::
process_ctype ()
{
    issue_diag (I_STAGE, false, 0, "processing %s section\n", lc_name);

    ctype_def_found_ = true;

    // used in processing  the copy/include directive
    int nesting_level = 0;

    while ((next = scanner_.next_token()).token != Scanner::tok_ctype) {

        switch(next.token) {

        case Scanner::tok_copy: {
            // when we see the copy directive in the ctype definition we 
            // are going to either create the shared database and create a 
            // symbolic link to it, or we are going to create a symbolic link
            // to the already existing shared ctype database.

            next = scanner_.next_token();
            if (next.token != Scanner::tok_string)
                issue_diag (E_SYNTAX, true, &next,
                            "expected string following \"copy\" directive\n"); 
#if !defined (_WIN32) && !defined (__CYGWIN__)

            ctype_symlink_ = true;

            // first lets make sure that the ctype database for this
            // locale hasn't already been generated
            ctype_filename_ = output_name_;
            // strip off the last directory
            ctype_filename_ = ctype_filename_.substr 
                (0, ctype_filename_.rfind
                 (_RWSTD_PATH_SEP, ctype_filename_.length() - 1) + 1);
            ctype_filename_ += strip_quotes(next.name);
            ctype_filename_ += ".ctype.";
            ctype_filename_ += charmap_.get_charmap_name();
            std::ifstream f (ctype_filename_.c_str(), std::ios::binary);
            if (f) {
                // the database exists so simply create a sym link to it
                ctype_written_ = true;
                f.close();
                continue;
            }

#endif  // !_WIN32 && !__CYGWIN__

            // bump up the nesting level
            nesting_level++;

            issue_diag (I_STAGE, false, 0, "processing copy directive\n");

            // open the file
            scanner_.open (get_pathname (strip_quotes (next.name), next.file));

            // get comment char and escape char; 
            // these informations are stored by the scanner
            while ((next = scanner_.next_token ()).token 
                   != Scanner::tok_ctype ){
                // the LC_IDENTIFICATION section may also have a 
                // LC_CTYPE token that will mess up the parsing
                if (next.token == Scanner::tok_ident) {
                    while ((next = scanner_.next_token()).token
                           != Scanner::tok_end );
                    next = scanner_.next_token();
                }
            }

            break;
        }
        case Scanner::tok_nl:
            break;

        case Scanner::tok_upper:
            process_mask (std::ctype_base::upper, "upper");
            break;

        case Scanner::tok_lower:
            process_mask (std::ctype_base::lower, "lower");
            break;

        case Scanner::tok_alpha:
            process_mask (std::ctype_base::alpha, "alpha");
            break;

        case Scanner::tok_digit:
            process_mask (std::ctype_base::digit, "digit");
            break;

        case Scanner::tok_space:
            process_mask (std::ctype_base::space, "space");
            break;

        case Scanner::tok_cntrl:
            process_mask (std::ctype_base::cntrl, "cntrl");
            break;

        case Scanner::tok_punct:
            process_mask (std::ctype_base::punct, "punct");
            break;

        case Scanner::tok_graph:
            process_mask (std::ctype_base::graph, "graph");
            break;

        case Scanner::tok_print:
            process_mask (std::ctype_base::print, "print");
            break;

        case Scanner::tok_xdigit:
            process_mask (std::ctype_base::xdigit, "xdigit");
            break;

        case Scanner::tok_toupper:
            process_upper_lower (Scanner::tok_toupper);
            break;

        case Scanner::tok_tolower:
            process_upper_lower (Scanner::tok_tolower);
            break;

        case Scanner::tok_blank:
            scanner_.ignore_line();
            break;

        case Scanner::tok_xlit_start:
            process_xlit ();
            break;

        case Scanner::tok_end:
            next = scanner_.next_token();
            if (next.token == Scanner::tok_ctype) {
                // end of ctype block
                if (nesting_level == 0) 
                    return;

                nesting_level--;
                scanner_.close ();
            } else
                issue_diag (E_SYNTAX, true, &next,
                            "wrong section name in END directive\n");

            break;

        default:
            // ignore locale specific character classes because the c++
            // library does not make use of them
            scanner_.ignore_line();
            break;

        }
    }
}
Exemplo n.º 25
0
void Def::
process_xlit ()
{
    issue_diag (I_STAGE, false, 0, "processing transliteration\n");

    std::size_t nchars  = 0;

    // used in processing  the include directive
    int nesting_level = 0;
    std::list<std::string> file_list;

    while (true) {
        next = scanner_.next_token ();

        switch (next.token) {
        case Scanner::tok_include: {

            // extract all file names from the list
            std::list<std::string> tmp_list;
            while (next.token != Scanner::tok_nl) {
                next = scanner_.next_token ();
                if (next.token == Scanner::tok_string &&
                    next.name.size () > 2)
                    tmp_list.push_back (next.name);
            }

            // insert this list into the main list - at beginning
            file_list.insert (file_list.begin (), 
                              tmp_list.begin (), tmp_list.end ());

            // get the top of the list
            std::string fname (file_list.front ());
            file_list.pop_front ();

            // bump up the nesting level
            nesting_level++;

            // get the full path for the included file and open it
            scanner_.open (get_pathname (strip_quotes (fname), next.file));

            // get comment char and escape char; 
            // these informations are stored by the scanner
            while ((next = scanner_.next_token ()).token 
                   != Scanner::tok_xlit_start );
            
            break;
        }
        case Scanner::tok_sym_name: {
            process_xlit_statement (nchars);
            break;
        }
        case Scanner::tok_xlit_end: {
            if (nesting_level == 0)
                return;

            // decrement nesting level, close opened file
            nesting_level--;
            scanner_.close ();

            // check if the list of files is empty or not
            if (file_list.empty ())
                break;

            // if not take the following file and open it
            std::string fname (file_list.front ());
            file_list.pop_front ();

            // bump up the nesting level
            nesting_level++;

            // get the full path for the included file and open it
            scanner_.open (get_pathname (strip_quotes (fname), next.file));

            // get comment char and escape char; 
            // these informations are stored by the scanner
            while ((next = scanner_.next_token ()).token 
                   != Scanner::tok_xlit_start);
            
        }
        default:
            break;
        }
    }

    issue_diag (I_STAGE, false, 0, "done processing transliteration "
                "(%lu tokens, %lu characters)");
}
Exemplo n.º 26
0
char *workspace_next_name(const char *output_name) {
	sway_log(L_DEBUG, "Workspace: Generating new workspace name for output %s", output_name);
	int i;
	int l = 1;
	// Scan all workspace bindings to find the next available workspace name,
	// if none are found/available then default to a number
	struct sway_mode *mode = config->current_mode;

	int order = INT_MAX;
	char *target = NULL;
	for (i = 0; i < mode->bindings->length; ++i) {
		struct sway_binding *binding = mode->bindings->items[i];
		char *cmdlist = strdup(binding->command);
		char *dup = cmdlist;
		char *name = NULL;

		// workspace n
		char *cmd = argsep(&cmdlist, " ");
		if (cmdlist) {
			name = argsep(&cmdlist, " ,;");
		}

		if (strcmp("workspace", cmd) == 0 && name) {
			sway_log(L_DEBUG, "Got valid workspace command for target: '%s'", name);
			char *_target = strdup(name);
			strip_quotes(_target);
			while (isspace(*_target))
				_target++;

			// Make sure that the command references an actual workspace
			// not a command about workspaces
			if (strcmp(_target, "next") == 0 ||
				strcmp(_target, "prev") == 0 ||
				strcmp(_target, "next_on_output") == 0 ||
				strcmp(_target, "prev_on_output") == 0 ||
				strcmp(_target, "number") == 0 ||
				strcmp(_target, "back_and_forth") == 0 ||
				strcmp(_target, "current") == 0)
			{
				free(_target);
				free(dup);
				continue;
			}

			// Make sure that the workspace doesn't already exist
			if (workspace_by_name(_target)) {
				free(_target);
				free(dup);
				continue;
			}

			// make sure that the workspace can appear on the given
			// output
			if (!workspace_valid_on_output(output_name, _target)) {
				free(_target);
				free(dup);
				continue;
			}

			if (binding->order < order) {
				order = binding->order;
				free(target);
				target = _target;
				sway_log(L_DEBUG, "Workspace: Found free name %s", _target);
			}
		}
		free(dup);
	}
	if (target != NULL) {
		return target;
	}
	// As a fall back, get the current number of active workspaces
	// and return that + 1 for the next workspace's name
	int ws_num = root_container.children->length;
	if (ws_num >= 10) {
		l = 2;
	} else if (ws_num >= 100) {
		l = 3;
	}
	char *name = malloc(l + 1);
	sprintf(name, "%d", ws_num++);
	return name;
}
Exemplo n.º 27
0
static int _set_rec(int *start, int argc, char *argv[],
                    List acct_list,
                    List cluster_list,
                    slurmdb_account_rec_t *acct,
                    slurmdb_association_rec_t *assoc)
{
    int i;
    int u_set = 0;
    int a_set = 0;
    int end = 0;
    int command_len = 0;
    int option = 0;

    for (i=(*start); i<argc; i++) {
        end = parse_option_end(argv[i]);
        if (!end)
            command_len=strlen(argv[i]);
        else {
            command_len=end-1;
            if (argv[i][end] == '=') {
                option = (int)argv[i][end-1];
                end++;
            }
        }

        if (!strncasecmp(argv[i], "Where", MAX(command_len, 5))) {
            i--;
            break;
        } else if (!end && !strncasecmp(argv[i], "set",
                                        MAX(command_len, 3))) {
            continue;
        } else if (!end
                   || !strncasecmp(argv[i], "Accounts",
                                   MAX(command_len, 1))
                   || !strncasecmp(argv[i], "Names",
                                   MAX(command_len, 1))
                   || !strncasecmp(argv[i], "Acct",
                                   MAX(command_len, 4))) {
            if (acct_list)
                slurm_addto_char_list(acct_list, argv[i]+end);
            else {
                exit_code=1;
                fprintf(stderr,
                        " Can't modify the name "
                        "of an account\n");
            }
        } else if (!strncasecmp(argv[i], "Clusters",
                                MAX(command_len, 1))) {
            if (cluster_list)
                slurm_addto_char_list(cluster_list,
                                      argv[i]+end);
            else {
                exit_code=1;
                fprintf(stderr,
                        " Can't modify the cluster "
                        "of an account\n");
            }
        } else if (!strncasecmp(argv[i], "Description",
                                MAX(command_len, 1))) {
            acct->description =  strip_quotes(argv[i]+end, NULL, 1);
            u_set = 1;
        } else if (!strncasecmp(argv[i], "Organization",
                                MAX(command_len, 1))) {
            acct->organization = strip_quotes(argv[i]+end, NULL, 1);
            u_set = 1;
        } else if (!strncasecmp (argv[i], "RawUsage",
                                 MAX(command_len, 7))) {
            uint32_t usage;
            if (!assoc)
                continue;
            assoc->usage = xmalloc(sizeof(
                                       assoc_mgr_association_usage_t));
            if (get_uint(argv[i]+end, &usage,
                         "RawUsage") == SLURM_SUCCESS) {
                assoc->usage->usage_raw = usage;
                a_set = 1;
            }
        } else if (!assoc ||
                   (assoc && !(a_set = sacctmgr_set_association_rec(
                                           assoc, argv[i], argv[i]+end,
                                           command_len, option)))) {
            exit_code=1;
            fprintf(stderr, " Unknown option: %s\n"
                    " Use keyword 'where' to modify condition\n",
                    argv[i]);
        }
    }

    (*start) = i;

    if (u_set && a_set)
        return 3;
    else if (a_set)
        return 2;
    else if (u_set)
        return 1;

    return 0;
}
Exemplo n.º 28
0
/**
 * Command line should look like this:
 *
 * <appname> [--analyze="title=(true|false|auto);delim=('<delimeter>'|auto)"] [--select="<enumerate_columns sep by ','>"] [--filter="<col><=,!= <,>, <=, >='><value> <and,or,xor>..."] [--smooth=<number_of_lines>] [--format="delim='<delim>',align=<true,false>"] [input_file] [output_file]
 *
 */
void command_line_parser::parse_cmdline(int argc, char *argv[], std::string &ifile_name, std::string &ofile_name,
    configuration_t &cfg) {

    // for (size_t i = 0; i < argc; i++) {
    //     std::cout << i << "\t" << argv[i] << std::endl;
    // }

    struct option options[] = {
        // Analyzer-related configuration options
        { "has_header", optional_argument, nullptr, 'a'},
        { "trim_lines", optional_argument, nullptr, 'l'},
        { "trim_columns", optional_argument, nullptr, 't'},
        { "trim_quotes", optional_argument, nullptr, 'q' },
        { "ignore_empty_columns", optional_argument, nullptr, 'e' },
        { "column_separator", required_argument, nullptr, 'c'},
        { "buffer_size", required_argument, nullptr, 'b'},
        { "rebase", required_argument, nullptr, 'r'},

        // select-related configuration options
        { "select", required_argument, nullptr, 's'},

        // filter-related configuration options
        { "filter", required_argument, nullptr, 'f'},

        // smoothing-related filter options
        { "smooth", required_argument, nullptr, 'm'},

        // statistics-related filter option
        { "statistics", optional_argument, nullptr, 'i'},

        // output-related configuration options
        { "output_empty_lines", optional_argument, nullptr, 'E'}, // 0 means none, 1 means only one for a group of empty lines, 2 means all
        { "output_comment_lines", optional_argument, nullptr, 'C'},  // if true comment lines are printed
        { "output_header_line", optional_argument, nullptr, 'H'}, // if true the header line is printed
        { "align_columns", optional_argument, nullptr, 'A'}, // if true the columns are right justified and aligned
        { "header_column_filler_char", required_argument, nullptr, 'E'},  // character used to fill right aligned header strings
        { "number_column_filler_char", required_argument, nullptr, 'N'}, // character used to fill right aligned data columns of a number type
        { "string_column_filler_char", required_argument, nullptr, 'S'}, // character used to fill right aligned data columns of a string type
        { "flt_precision", required_argument, nullptr, 'F'}, // precision of float data columns
        { "int_length", required_argument, nullptr, 'I'}, // length of a column in characters
        { "output_datetime_format", required_argument, nullptr, 'D'}, // defines the datetime format for the output for all columns
        { "output_separator", required_argument, nullptr, 'P'}, // defines the character that separates columns in the output
		{ "order_columns", required_argument, nullptr, 'O' }, // defines in which way the columns shall be sorted

        { "help", no_argument, nullptr, 'h' }
    };

    int oc;
    int opts_index = 0;
    while ((oc = getopt_long(argc, argv, "+a::l::t::q::e::c:b:r:s:i::f:m:E::R::C::H::A::L:N:S:F:I:D:P:O:h", options, &opts_index)) != -1) {
        std::string stmp;
        if (optarg) {
            stmp = optarg;
            strip_quotes(stmp);
        } else {
            stmp = "1";
        }

        switch (oc) {
            case 'a':
                // std::cerr << "optarg: \"" << optarg << "\"" << std::endl;
                switch (stmp[0]) {
                    case '1': cfg.header_detection_mode = 1; break;
                    case '0': cfg.header_detection_mode = -1; break;
                    case 'a': cfg.header_detection_mode = 0; break;
                    default:  cfg.header_detection_mode = 0; break;
                }
                break;
            case 'l':
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.trim_lines, "trim_lines [l]")))
                    return;
                break;
            case 't':
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.trim_columns, "trim_columns [t]")))
                    return;
                break;
            case 'q':
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.trim_quotes, "trim_quotes [q]")))
                    return;
                break;
            case 'e':
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.ignore_empty_columns, "ignore_empty_columns [e]")))
                    return;
                break;
            case 'c':
                cfg.separator_auto_detection = false;
                if (stmp.length() > 0) {
                    cfg.separator = stmp[0];
                } else {
                    cfg.do_help = true;
                    std::cerr << "Option --separator [c] requires one character as parameter but found an empty string." << std::endl;
                    return;
                }
                break;
            case 'b':
                if ((cfg.do_help = !check_uint_cmdline_param(stmp, cfg.buffer_size, "buffer_size [b]"))) {
                    return;
                }
                break;
            case 'r':
            {
                cfg.do_rebase = true;
                strip_quotes(stmp);
                std::vector<std::string> rebase_pairs = split(stmp,
                                                              /*bool ignore_quotes = */ false,
                                                              /* bool ignore_empty = */ true,
                                                              /* const std::string &delimeters = */ ","
                                                              /* const std::string &quotes = "\"\'" */ );
                for (std::string s : rebase_pairs) {
                    std::vector<std::string> key_value_pair = split(s,
                                                                    /* bool ignore_quotes = */ false,
                                                                    /* bool ignore_empty = */ false,
                                                                    /* const std::string &delimeters = */ ":"
                                                                    /* const std::string &quotes = "\"\'" */ );
                    if (key_value_pair.size() != 2) {
                        throw std::runtime_error("can't parse the rebase string. Error parsing this part: " + s);
                    }
                    cfg.rebase_columns.push_back(s);
                }
                cfg.selected_column_titles.shrink_to_fit();
                cfg.selected_columns.resize(cfg.selected_column_titles.size());
                for (size_t i = 0; i < cfg.selected_column_titles.size(); i++) {
                    long long rslt;
                    size_t len;
                    if (parse_int(cfg.selected_column_titles[i], rslt, len)) {
                        cfg.selected_columns[i] = (size_t) rslt;
                    } else {
                        cfg.selected_columns[i] = std::string::npos;
                    }
                }
            }
                break;
            case 's':
                cfg.select_columns = 1;
                cfg.selected_column_titles = split(stmp, /*bool ignore_quotes = */ true, /* bool ignore_empty = */ true,
                                                   /* const std::string &delimeters = */ ","
                                                   /* const std::string &quotes = "\"\'" */ );
                cfg.selected_column_titles.shrink_to_fit();
                cfg.selected_columns.resize(cfg.selected_column_titles.size());
                for (size_t i = 0; i < cfg.selected_column_titles.size(); i++) {
                    long long rslt;
                    size_t len;
                    if (parse_int(cfg.selected_column_titles[i], rslt, len)) {
                        cfg.selected_columns[i] = (size_t) rslt;
                    } else {
                        cfg.selected_columns[i] = std::string::npos;
                    }
                }
                break;
            case 'i':
                {
                    // stmp contains a list looking like this: "counter, Mean,vAriance , TOTAL"
                    stmp = strip(stmp);
                    std::transform(stmp.begin(), stmp.end(), stmp.begin(), ::tolower);
                    // since parameter is given we output to true
                    cfg.output_statistics = true;
                    // set output to false for all values to begin with
                    for (bool v : cfg.statistics_output_selector) {
                            v = false;
                    }
                    if (stmp == "none") {
                        // none mean we deactivate output
                        cfg.output_statistics = false;
                    } else if (stmp == "all") {
                        // all means we want all output
                        cfg.output_statistics = true;
                        for (bool v : cfg.statistics_output_selector) {
                            v = true;
                        }
                    } else {
                        // neither none nor all: it must be a list of selected values
                        std::vector<std::string> selected_statistics_values = split(stmp, /*bool ignore_quotes = */ true, /* bool ignore_empty = */ true,
                                                   /* const std::string &delimeters = */ ","
                                                   /* const std::string &quotes = "\"\'" */ );
                        for (std::string& x : selected_statistics_values) {
                            x = strip(x);
                            // if x is a supported name for a statistics value we set it to true, or we throw an error.
                            auto it = statistics_name_dictionary.find(x); 
                            if (it == statistics_name_dictionary.end()) {
                                throw std::runtime_error("statistics calculation for \"" + x + "\" is not supported");
                            }
                            cfg.statistics_output_selector[it->second] = true;
                        }
                    }
                }
            case 'f':
                stmp = strip(stmp);
                // std::cerr << "stmp = \"" << stmp << "\"" << std::endl;
                // split into column, comparator, and value with regular expression
                // -f"@'abc' < 5 and @2 == 'x' or @'xyz' <= 17 >
                {
                    cfg.filter_expression.parse_filter(stmp);
                    /*
                    size_t i = 0;
                    while (i < stmp.length()) {
                        std::string column_name;
                        size_t column_number;
                        if (!parse_column_name(stmp, i, column_name, column_number)) { cfg.do_help = 1; return ; }
                        comparator_t comparator;
                        if (!parse_comparator(stmp, i, comparator)) { cfg.do_help = 1; return ; }
                        std::string value;
                        if (!parse_value(stmp, i, value)) { cfg.do_help = 1; return ; }
                        bool_operator_t op;
                        if (!parse_bool_operator(stmp, i, op)) { cfg.do_help = 1; return ; }
                        comparison_statement_t cs(column_name, column_number, comparator, value, op);
                        cfg.comparison_statements.push_back(cs);
                    }
                    */
                }
                break;
            case 'm':
                {
                    long long rslt;
                    size_t len;
                    if (parse_int(stmp, rslt, len)) {
                        cfg.smoothing_window_size = (size_t) rslt;
                    } else {
                        cfg.do_help = true;
                        std::cerr << "Illegal command line parameter: smooth length must be a number but it was \"";
                        std::cerr << stmp << "\"" << std::endl;
                        return;
                    }
                }
                break;
            case 'R':
            {

                stmp = strip(stmp);
                bool set_raw_output = true;
                if (stmp.length() > 0) {
                    if (stmp[0] == '0') {
                        set_raw_output = false;
                    }
                }
                cfg.output_raw = set_raw_output;
            }
            case 'E': // { "output_empty_lines", optional_argument, nullptr, 'E'}, // 0 means none, 1 means only one for a group of empty lines, 2 means all
                switch(stmp[0]) {
                    case '0': cfg.output_empty_lines = 0; break;
                    case '1': cfg.output_empty_lines = 1; break;
                    case '2': cfg.output_empty_lines = 2; break;
                    default:
                        cfg.do_help = true;
                        std::cerr << "Illegal command line parameter: output_empty_lines [E] must be 0, 1, or 2 but was \"";
                        std::cerr << stmp << "\"" << std::endl;
                        return;
                }
                break;
            case 'C': // { "output_comment_lines", optional_argument, nullptr, 'C'},  // if true comment lines are printed
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.output_comment_lines, "output_comment_lines [C]")))
                    return;
                break;
            case 'H': // { "output_header_line", optional_argument, nullptr, 'H'}, // if true the header line is printed
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.output_header_line, "output_header_line [H]")))
                    return;
                break;
            case 'A': // { "align_columns", optional_argument, nullptr, 'A'}, // if true the columns are right justified and aligned
                if ((cfg.do_help = !check_bool_cmdline_param(stmp, cfg.align_columns, "align_columns [A]")))
                    return;
                break;
            case 'L': // { "header_column_filler_char", required_argument, nullptr, 'E'},  // character used to fill right aligned header strings
                if (stmp.length() > 0) {
                    cfg.header_column_filler_char = stmp[0];
                } else {
                    std::cerr << "Empty --header_column_filler_char option [-L] - ignored." << std::endl;
                }
                break;
            case 'N': // { "number_column_filler_char", required_argument, nullptr, 'N'}, // character used to fill right aligned data columns of a number type
                if (stmp.length() > 0) {
                    cfg.number_column_filler_char = stmp[0];
                } else {
                    std::cerr << "Empty --number_column_filler_char option [-N] - ignored." << std::endl;
                }
                break;
            case 'S': // { "string_column_filler_char", required_argument, nullptr, 'S'}, // character used to fill right aligned data columns of a string type
                if (stmp.length() > 0) {
                    cfg.string_column_filler_char = stmp[0];
                } else {
                    std::cerr << "Empty --string_filler_char option [-S] - ignored." << std::endl;
                }
                break;
            case 'F': // { "flt_precision", required_argument, nullptr, 'F'}, // precision of float data columns
                if (!(cfg.do_help = check_uint_cmdline_param(stmp, cfg.flt_precission, "flt_precision [F]")))
                    return;
                break;
            case 'I': // { "int_length", required_argument, nullptr, 'I'}, // length of a column in characters
                if (!(cfg.do_help = check_uint_cmdline_param(stmp, cfg.int_length, "int_length [I]")))
                    return;
                break;
            case 'D': // { "output_datetime_format", required_argument, nullptr, 'D',
                if (stmp.length() > 0) {
                    cfg.output_datetime_format = stmp;
                } else {
                    std::cerr << "Empty --outout_datetime_format option [-D] - ignored." << std::endl;
                }
                break;
            case 'P': // { "output_separator", required_argument, nullptr, 'P'},
                if (stmp.length() > 0) {
                    cfg.output_separator = stmp;
                } else {
                    std::cerr << "Empty number output separator option [P] - ignored." << std::endl;
                }
                break;
			case 'O': // { "order_columns", required_argument, nullptr, 'O' }
				// Here are some example sort criterion: 
				//  -O"by_avg [2, 6:9, 11:13, 4, 'whatever_column']"
				//  -O"by_title"
				//  -O"by_max ['whatever_column':]"
				//  -O"by_min_descending [:7]"
				// So for the parameter reader we need to read the first token anything until we have a space, 
				// a '[', or the end of the string.
			{
				cfg.order_columns = true;
				size_t i = stmp.find_first_of("[ \t\n\r");
				if (i == std::string::npos) {
					cfg.order_criterion_string = stmp;
					cfg.order_range_string = "";
				}
				else {
					cfg.order_criterion_string = stmp.substr(0, i);
					cfg.order_range_string = strip(stmp.substr(i));
					if ((cfg.order_range_string.front() != '[') || (cfg.order_range_string.back() != ']')) {
						throw std::runtime_error("Order range incorrecltly specified: \"" + stmp + "\".");
					}
					cfg.order_range_string = cfg.order_range_string.substr(1, cfg.order_range_string.length() - 2);
					// all other parsing is done when the analyzer has finished it's job.
				}
				// check if the order criterion is ok:
				auto it = order_criteria_lookup_dict.find(cfg.order_criterion_string);
				if (it != order_criteria_lookup_dict.end()) {
					cfg.order_criterion = it->second;
				}
			}
				break;
            case 'h':
                cfg.do_help = true;
                std::cerr << "do_help = true" << std::endl;
                return;
            case ':':
                // missing option argument
                std::cerr << argv[0] << " option '-" << (char) optopt << "' requires an argument" << std::endl;
                break;
            case '?':
            default:
                // invalid option
                std::cerr << argv[0] << " option '-" << (char) optopt << "' is invalid: ignored." << std::endl;
                break;
        }
        // std::cerr << "opts_index = " << opts_index << std::endl;
        opts_index = 0;
    }

    //std::cerr << "optind: " << optind << std::endl;
    //std::cerr << "argc: " << argc << std::endl;

    if (argc > optind) {
        ifile_name = argv[optind];
    }
    if (argc > optind+1) {
        ofile_name = argv[optind+1];
    }
}
Exemplo n.º 29
0
static void parse_naptr(const ldns_rr *naptr, const char *number, enum_record_t **results)
{
	char *str = ldns_rr2str(naptr);
	char *argv[11] = { 0 };
	int i, argc;
	char *pack[4] = { 0 };
	int packc;

	char *p;
	int order = 10;
	int preference = 100;
	char *service = NULL;
	char *packstr;

	char *regex, *replace;
	
	if (zstr(str)) {
		if (str != NULL) {
			/* In this case ldns_rr2str returned a malloc'd null terminated string */
			switch_safe_free(str);
		}
		return;
	}

	for (p = str; p && *p; p++) {
		if (*p == '\t') *p = ' ';
		if (*p == ' ' && *(p+1) == '.') *p = '\0';
	}


	argc = switch_split(str, ' ', argv);

	for (i = 0; i < argc; i++) {
		if (i > 0) {
			strip_quotes(argv[i]);
		}
	}

	service = argv[7];
	packstr = argv[8];

	if (zstr(service) || zstr(packstr)) {
		goto end;
	}
	
	if (!zstr(argv[4])) {
		order = atoi(argv[4]);
	}

	if (!zstr(argv[5])) {
		preference = atoi(argv[5]);
	}


	if ((packc = switch_split(packstr, '!', pack))) {
		regex = pack[1];
		replace = pack[2];
	} else {
		goto end;
	}
	
	for (p = replace; p && *p; p++) {
		if (*p == '\\') {
			*p = '$';
		}
	}

	if (service && regex && replace) {
		switch_regex_t *re = NULL, *re2 = NULL;
		int proceed = 0, ovector[30];
		char *substituted = NULL;
		char *substituted_2 = NULL;
		char *orig_uri;
		char *uri_expanded = NULL;
		enum_route_t *route;
		int supported = 0;
		uint32_t len = 0;

		if ((proceed = switch_regex_perform(number, regex, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
			if (strchr(regex, '(')) {
				len = (uint32_t) (strlen(number) + strlen(replace) + 10) * proceed;
				if (!(substituted = malloc(len))) {
					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
					switch_regex_safe_free(re);
					goto end;
				}
				memset(substituted, 0, len);

				switch_perform_substitution(re, proceed, replace, number, substituted, len, ovector);
				orig_uri = substituted;
			} else {
				orig_uri = replace;
			}
			
			switch_mutex_lock(MUTEX);
			for (route = globals.route_order; route; route = route->next) {
				char *uri = orig_uri;
				
				if (strcasecmp(service, route->service)) {
					continue;
				}

				if ((proceed = switch_regex_perform(uri, route->regex, &re2, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
					switch_event_t *event = NULL;

					if (strchr(route->regex, '(')) {
						len = (uint32_t) (strlen(uri) + strlen(route->replace) + 10) * proceed;
						if (!(substituted_2 = malloc(len))) {
							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
							switch_safe_free(substituted);
							switch_regex_safe_free(re);
							switch_regex_safe_free(re2);
							switch_mutex_unlock(MUTEX);
							goto end;
						}
						memset(substituted_2, 0, len);

						switch_perform_substitution(re2, proceed, route->replace, uri, substituted_2, len, ovector);
						uri = substituted_2;
					} else {
						uri = route->replace;
					}
					switch_event_create(&event, SWITCH_EVENT_REQUEST_PARAMS);
					uri_expanded = switch_event_expand_headers(event, uri);
					switch_event_destroy(&event);

					if (uri_expanded == uri) {
						uri_expanded = NULL;
					} else {
						uri = uri_expanded;
					}

					supported++;
					add_result(results, order, preference, service, uri, supported);
					
				}
				switch_safe_free(uri_expanded);
				switch_safe_free(substituted_2);
				switch_regex_safe_free(re2);
			}
			switch_mutex_unlock(MUTEX);			

			if (!supported) {
				add_result(results, order, preference, service, orig_uri, 0);
			}

			switch_safe_free(substituted);
			switch_regex_safe_free(re);
		}
	}

 end:

	switch_safe_free(str);
	
	return;
}
Exemplo n.º 30
0
static int XCOPY_ParseCommandLine(WCHAR *suppliedsource,
                                  WCHAR *supplieddestination, DWORD *pflags)
{
    const WCHAR EXCLUDE[]  = {'E', 'X', 'C', 'L', 'U', 'D', 'E', ':', 0};
    DWORD flags = *pflags;
    WCHAR *cmdline, *word, *end, *next;
    int rc = RC_INITERROR;

    cmdline = _wcsdup(GetCommandLineW());
    if (cmdline == NULL)
        return rc;

    /* Skip first arg, which is the program name */
    if ((rc = find_end_of_word(cmdline, &word)) != RC_OK)
        goto out;
    word = skip_whitespace(word);

    while (*word)
    {
        WCHAR first;
        if ((rc = find_end_of_word(word, &end)) != RC_OK)
            goto out;

        next = skip_whitespace(end);
        first = word[0];
        *end = '\0';
        strip_quotes(word, &end);
        WINE_TRACE("Processing Arg: '%s'\n", wine_dbgstr_w(word));

        /* First non-switch parameter is source, second is destination */
        if (first != '/') {
            if (suppliedsource[0] == 0x00) {
                lstrcpyW(suppliedsource, word);
            } else if (supplieddestination[0] == 0x00) {
                lstrcpyW(supplieddestination, word);
            } else {
                XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARMS));
                goto out;
            }
        } else {
            /* Process all the switch options
                 Note: Windows docs say /P prompts when dest is created
                       but tests show it is done for each src file
                       regardless of the destination                   */
            switch (toupper(word[1])) {
            case 'I': flags |= OPT_ASSUMEDIR;     break;
            case 'S': flags |= OPT_RECURSIVE;     break;
            case 'Q': flags |= OPT_QUIET;         break;
            case 'F': flags |= OPT_FULL;          break;
            case 'L': flags |= OPT_SIMULATE;      break;
            case 'W': flags |= OPT_PAUSE;         break;
            case 'T': flags |= OPT_NOCOPY | OPT_RECURSIVE; break;
            case 'Y': flags |= OPT_NOPROMPT;      break;
            case 'N': flags |= OPT_SHORTNAME;     break;
            case 'U': flags |= OPT_MUSTEXIST;     break;
            case 'R': flags |= OPT_REPLACEREAD;   break;
            case 'H': flags |= OPT_COPYHIDSYS;    break;
            case 'C': flags |= OPT_IGNOREERRORS;  break;
            case 'P': flags |= OPT_SRCPROMPT;     break;
            case 'A': flags |= OPT_ARCHIVEONLY;   break;
            case 'M': flags |= OPT_ARCHIVEONLY |
                               OPT_REMOVEARCH;    break;

            /* E can be /E or /EXCLUDE */
            case 'E': if (CompareStringW(LOCALE_USER_DEFAULT,
                                         NORM_IGNORECASE | SORT_STRINGSORT,
                                         &word[1], 8,
                                         EXCLUDE, -1) == CSTR_EQUAL) {
                        if (XCOPY_ProcessExcludeList(&word[9])) {
                          XCOPY_FailMessage(ERROR_INVALID_PARAMETER);
                          goto out;
                        } else flags |= OPT_EXCLUDELIST;
                      } else flags |= OPT_EMPTYDIR | OPT_RECURSIVE;
                      break;

            /* D can be /D or /D: */
            case 'D': if (word[2]==':' && isdigit(word[3])) {
                          SYSTEMTIME st;
                          WCHAR     *pos = &word[3];
                          BOOL       isError = FALSE;
                          memset(&st, 0x00, sizeof(st));

                          /* Microsoft xcopy's usage message implies that the date
                           * format depends on the locale, but that is false.
                           * It is hardcoded to month-day-year.
                           */
                          st.wMonth = _wtol(pos);
                          while (*pos && isdigit(*pos)) pos++;
                          if (*pos++ != '-') isError = TRUE;

                          if (!isError) {
                              st.wDay = _wtol(pos);
                              while (*pos && isdigit(*pos)) pos++;
                              if (*pos++ != '-') isError = TRUE;
                          }

                          if (!isError) {
                              st.wYear = _wtol(pos);
                              while (*pos && isdigit(*pos)) pos++;
                              if (st.wYear < 100) st.wYear+=2000;
                          }

                          if (!isError && SystemTimeToFileTime(&st, &dateRange)) {
                              SYSTEMTIME st;
                              WCHAR datestring[32], timestring[32];

                              flags |= OPT_DATERANGE;

                              /* Debug info: */
                              FileTimeToSystemTime (&dateRange, &st);
                              GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring,
                                             sizeof(datestring)/sizeof(WCHAR));
                              GetTimeFormatW(0, TIME_NOSECONDS, &st,
                                             NULL, timestring, sizeof(timestring)/sizeof(WCHAR));

                              WINE_TRACE("Date being used is: %s %s\n",
                                         wine_dbgstr_w(datestring), wine_dbgstr_w(timestring));
                          } else {
                              XCOPY_FailMessage(ERROR_INVALID_PARAMETER);
                              goto out;
                          }
                      } else {
                          flags |= OPT_DATENEWER;
                      }
                      break;

            case '-': if (toupper(word[2])=='Y')
                          flags &= ~OPT_NOPROMPT;
                      break;
            case '?': XCOPY_wprintf(XCOPY_LoadMessage(STRING_HELP));
                      rc = RC_HELP;
                      goto out;
            default:
                WINE_TRACE("Unhandled parameter '%s'\n", wine_dbgstr_w(word));
                XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARM), word);
                goto out;
            }
        }
        word = next;
    }

    /* Default the destination if not supplied */
    if (supplieddestination[0] == 0x00)
        lstrcpyW(supplieddestination, wchr_dot);

    *pflags = flags;
    rc = RC_OK;

 out:
    free(cmdline);
    return rc;
}