static void
stats_top_output_diff(struct top_context *ctx,
		      const struct top_line *line, unsigned int i)
{
	uint64_t prev_num, cur_num;
	double prev_double, cur_double, prev_time, cur_time;
	char numstr[MAX_INT_STRLEN];

	if (str_to_uint64(line->prev_values[i], &prev_num) == 0 &&
	    str_to_uint64(line->cur_values[i], &cur_num) == 0) {
		if (i_snprintf(numstr, sizeof(numstr), "%llu",
			       (unsigned long long)(cur_num - prev_num)) < 0)
			i_unreached();
		doveadm_print(numstr);
	} else if (get_double(line->prev_values[i], &prev_double) == 0 &&
		   get_double(line->cur_values[i], &cur_double) == 0 &&
		   get_double(line->prev_values[ctx->last_update_idx], &prev_time) == 0 &&
		   get_double(line->cur_values[ctx->last_update_idx], &cur_time) == 0) {
		/* %CPU */
		if (i_snprintf(numstr, sizeof(numstr), "%d",
			       (int)((cur_double - prev_double) *
				     (cur_time - prev_time) * 100)) < 0)
			i_unreached();
		doveadm_print(numstr);
	} else {
		doveadm_print(line->cur_values[i]);
	}
}
示例#2
0
文件: tsdb_set.c 项目: tumi8/tsdb
static void process_args(int argc, char *argv[], set_args *args) {
    int c;

    args->timestamp = 0;
    args->verbose = 0;

    while ((c = getopt(argc, argv, "hvt:")) != -1) {
        switch (c) {
        case 'h':
            help(0);
            break;
        case 'v':
            args->verbose = 1;
            break;
        case 't':
            args->timestamp = (uint32_t)str_to_uint64(optarg, "timestamp");
            break;
        default:
            help(1);
        }
    }

    int remaining = argc - optind;
    if (remaining < 2) {
        help(1);
    }

    args->file = argv[optind];
    args->key = argv[optind + 1];
    args->values_start = optind + 2;
    args->values_stop = argc - 1;
    args->argv = argv;
}
static bool
store_parse_modifiers(struct imap_store_context *ctx,
		      const struct imap_arg *args)
{
	const char *name, *value;

	for (; !IMAP_ARG_IS_EOL(args); args += 2) {
		if (!imap_arg_get_atom(&args[0], &name) ||
		    !imap_arg_get_atom(&args[1], &value)) {
			client_send_command_error(ctx->cmd,
				"Invalid STORE modifiers.");
			return FALSE;
		}

		if (strcasecmp(name, "UNCHANGEDSINCE") == 0) {
			if (ctx->cmd->client->nonpermanent_modseqs) {
				client_send_command_error(ctx->cmd,
					"STORE UNCHANGEDSINCE can't be used with non-permanent modseqs");
				return FALSE;
			}
			if (str_to_uint64(value, &ctx->max_modseq) < 0) {
				client_send_command_error(ctx->cmd,
							  "Invalid modseq");
				return FALSE;
			}
			(void)client_enable(ctx->cmd->client,
					    MAILBOX_FEATURE_CONDSTORE);
		} else {
			client_send_command_error(ctx->cmd,
						  "Unknown STORE modifier");
			return FALSE;
		}
	}
	return TRUE;
}
示例#4
0
static bool
fetch_parse_modifier(struct imap_fetch_context *ctx,
		     struct client_command_context *cmd,
		     struct mail_search_args *search_args,
		     const char *name, const struct imap_arg **args,
		     bool *send_vanished)
{
	const char *str;
	uint64_t modseq;

	if (strcmp(name, "CHANGEDSINCE") == 0) {
		if (!imap_arg_get_atom(*args, &str) ||
		    str_to_uint64(str, &modseq) < 0) {
			client_send_command_error(cmd,
				"Invalid CHANGEDSINCE modseq.");
			return FALSE;
		}
		*args += 1;
		imap_search_add_changed_since(search_args, modseq);
		imap_fetch_init_nofail_handler(ctx, imap_fetch_modseq_init);
		return TRUE;
	}
	if (strcmp(name, "VANISHED") == 0 && cmd->uid) {
		if ((ctx->client->enabled_features &
		     MAILBOX_FEATURE_QRESYNC) == 0) {
			client_send_command_error(cmd, "QRESYNC not enabled");
			return FALSE;
		}
		*send_vanished = TRUE;
		return TRUE;
	}

	client_send_command_error(cmd, "Unknown FETCH modifier");
	return FALSE;
}
static struct mail_search_arg *
imap_search_modseq(struct mail_search_build_context *ctx)
{
	struct mail_search_arg *sarg;
	const char *value;
	int ret;

	/* [<name> <type>] <modseq> */
	sarg = mail_search_build_new(ctx, SEARCH_MODSEQ);
	sarg->value.modseq = p_new(ctx->pool, struct mail_search_modseq, 1);

	if (mail_search_parse_string(ctx->parser, &value) < 0)
		return NULL;

	if ((ret = arg_modseq_set_ext(ctx, sarg, value)) < 0)
		return NULL;
	if (ret > 0) {
		/* extension data used */
		if (mail_search_parse_string(ctx->parser, &value) < 0)
			return NULL;
	}

	if (str_to_uint64(value, &sarg->value.modseq->modseq) < 0) {
		ctx->_error = "Invalid MODSEQ value";
		return NULL;
	}
	return sarg;
}
示例#6
0
文件: args.c 项目: josejamilena/xz
static void
parse_block_list(char *str)
{
	// It must be non-empty and not begin with a comma.
	if (str[0] == '\0' || str[0] == ',')
		message_fatal(_("%s: Invalid argument to --block-list"), str);

	// Count the number of comma-separated strings.
	size_t count = 1;
	for (size_t i = 0; str[i] != '\0'; ++i)
		if (str[i] == ',')
			++count;

	// Prevent an unlikely integer overflow.
	if (count > SIZE_MAX / sizeof(uint64_t) - 1)
		message_fatal(_("%s: Too many arguments to --block-list"),
				str);

	// Allocate memory to hold all the sizes specified.
	// If --block-list was specified already, its value is forgotten.
	free(opt_block_list);
	opt_block_list = xmalloc((count + 1) * sizeof(uint64_t));

	for (size_t i = 0; i < count; ++i) {
		// Locate the next comma and replace it with \0.
		char *p = strchr(str, ',');
		if (p != NULL)
			*p = '\0';

		if (str[0] == '\0') {
			// There is no string, that is, a comma follows
			// another comma. Use the previous value.
			//
			// NOTE: We checked earler that the first char
			// of the whole list cannot be a comma.
			assert(i > 0);
			opt_block_list[i] = opt_block_list[i - 1];
		} else {
			opt_block_list[i] = str_to_uint64("block-list", str,
					0, UINT64_MAX);

			// Zero indicates no more new Blocks.
			if (opt_block_list[i] == 0) {
				if (i + 1 != count)
					message_fatal(_("0 can only be used "
							"as the last element "
							"in --block-list"));

				opt_block_list[i] = UINT64_MAX;
			}
		}

		str = p + 1;
	}

	// Terminate the array.
	opt_block_list[count] = 0;
	return;
}
static double sort_num_diff(const struct top_line *line)
{
	uint64_t prev, cur, diff;

	if (str_to_uint64(line->prev_values[sort_ctx->sort_idx1], &prev) < 0 ||
	    str_to_uint64(line->cur_values[sort_ctx->sort_idx1], &cur) < 0)
		i_fatal("sorting: not a number");
	diff = cur - prev;

	if (sort_ctx->sort_idx2 != 0) {
		if (str_to_uint64(line->prev_values[sort_ctx->sort_idx2], &prev) < 0 ||
		    str_to_uint64(line->cur_values[sort_ctx->sort_idx2], &cur) < 0)
			i_fatal("sorting: not a number");
		diff += cur - prev;
	}
	return diff;
}
示例#8
0
int main(int argc, char **argv[])
{
    char *s;
    int error;
    int64_t i;
    uint64_t u;

    //s = "-128";
    //s = "-32768";
    //s = "-2147483648";
    //s = "-9223372036854775808";
    //s = "128";
    //s = "32768";
    //s = "2147483648";
    //s = "9223372036854775808";
    //s = "255";
    //s = "65535";
    //s = "4294967295";
    s = "18446744073709551615";
    //s = "256";
    //s = "65536";
    //s = "4294967296";
    //s = "18446744073709551616";
    printf("s = '%s'\n\n", s);

    i = str_to_int64(s, INT8_MIN, INT8_MAX, &error);
    printf(" 8: i = %lld  error = %d\n", i, error);
    i = str_to_int64(s, INT16_MIN, INT16_MAX, &error);
    printf("16: i = %lld  error = %d\n", i, error);
    i = str_to_int64(s, INT32_MIN, INT32_MAX, &error);
    printf("32: i = %lld  error = %d\n", i, error);
    i = str_to_int64(s, INT64_MIN, INT64_MAX, &error);
    printf("64: i = %lld  error = %d\n", i, error);

    printf("\n");

    u = str_to_uint64(s, UINT8_MAX, &error);
    printf(" 8: u = %llu  error = %d\n", u, error);
    u = str_to_uint64(s, UINT16_MAX, &error);
    printf("16: u = %llu  error = %d\n", u, error);
    u = str_to_uint64(s, UINT32_MAX, &error);
    printf("32: u = %llu  error = %d\n", u, error);
    u = str_to_uint64(s, UINT64_MAX, &error);
    printf("64: u = %llu  error = %d\n", u, error);
    return 0;
}
示例#9
0
int parse_ip(struct parser *p, uint64_t *ip, enum pt_ip_compression *ipc,
	     char *payload)
{
	int errcode;
	char *endptr;

	if (bug_on(!ip))
		return -err_internal;

	if (bug_on(!ipc))
		return -err_internal;

	*ipc = pt_ipc_suppressed;
	*ip = 0;

	payload = strtok(payload, " :");
	if (!payload || *payload == '\0')
		return -err_parse_no_args;

	*ipc = (enum pt_ip_compression) strtol(payload, &endptr, 0);
	if (payload == endptr || *endptr != '\0')
		return -err_parse_ipc;

	/* is ipc valid?  */
	errcode = check_ipc(*ipc);
	if (errcode < 0)
		return errcode;

	payload = strtok(NULL, " :");
	if (!payload)
		return -err_parse_ip_missing;

	/* can be resolved to a label?  */
	if (*payload == '%') {
		int errcode;

		if (!p)
			return -err_internal;

		errcode = yasm_lookup_label(p->y, ip, payload + 1);
		if (errcode < 0)
			return errcode;
	} else {
		/* can be parsed as address?  */
		int errcode;

		errcode = str_to_uint64(payload, ip);
		if (errcode < 0)
			return errcode;
	}

	/* no more tokens left.  */
	payload = strtok(NULL, " ");
	if (payload)
		return -err_parse_trailing_tokens;

	return 0;
}
示例#10
0
uint64_t config_get_default_uint(const config_t *config, const char *section,
		const char *name)
{
	const char *value = config_get_default_string(config, section, name);
	if (value)
		return str_to_uint64(value);

	return 0;
}
示例#11
0
bool config_get_default_bool(const config_t *config, const char *section,
		const char *name)
{
	const char *value = config_get_default_string(config, section, name);
	if (value)
		return astrcmpi(value, "true") == 0 ||
		       !!str_to_uint64(value);

	return false;
}
示例#12
0
void Slave::load_status(){
	std::string key;
	std::string seq;
	meta->hget(status_key(), "last_key", &key);
	meta->hget(status_key(), "last_seq", &seq);
	if(!key.empty()){
		this->last_key = key;
	}
	if(!seq.empty()){
		this->last_seq = str_to_uint64(seq);
	}
}
示例#13
0
static int
process_io_buffer_parse(const char *buf, struct mail_stats *stats)
{
	const char *const *tmp;

	tmp = t_strsplit(buf, "\n");
	for (; *tmp != NULL; tmp++) {
		if (strncmp(*tmp, "rchar: ", 7) == 0) {
			if (str_to_uint64(*tmp + 7, &stats->read_bytes) < 0)
				return -1;
		} else if (strncmp(*tmp, "wchar: ", 7) == 0) {
			if (str_to_uint64(*tmp + 7, &stats->write_bytes) < 0)
				return -1;
		} else if (strncmp(*tmp, "syscr: ", 7) == 0) {
			if (str_to_uint32(*tmp + 7, &stats->read_count) < 0)
				return -1;
		} else if (strncmp(*tmp, "syscw: ", 7) == 0) {
			if (str_to_uint32(*tmp + 7, &stats->write_count) < 0)
				return -1;
		}
	}
	return 0;
}
示例#14
0
文件: args.c 项目: pexip/os-xz-utils
/// Parse and set the memory usage limit for compression and/or decompression.
static void
parse_memlimit(const char *name, const char *name_percentage, char *str,
		bool set_compress, bool set_decompress)
{
	bool is_percentage = false;
	uint64_t value;

	const size_t len = strlen(str);
	if (len > 0 && str[len - 1] == '%') {
		str[len - 1] = '\0';
		is_percentage = true;
		value = str_to_uint64(name_percentage, str, 1, 100);
	} else {
		// On 32-bit systems, SIZE_MAX would make more sense than
		// UINT64_MAX. But use UINT64_MAX still so that scripts
		// that assume > 4 GiB values don't break.
		value = str_to_uint64(name, str, 0, UINT64_MAX);
	}

	hardware_memlimit_set(
			value, set_compress, set_decompress, is_percentage);
	return;
}
示例#15
0
文件: tsdb_set.c 项目: tumi8/tsdb
static tsdb_value *alloc_values(set_args *args, int value_count) {
    tsdb_value *values = calloc(value_count, sizeof(tsdb_value));
    if (!values) {
         printf("tsdb-set: Could not allocate memory for values!");
	 exit(1);
    }

    int cur_value = args->values_start;
    int i = 0;
    while (i < value_count && cur_value <= args->values_stop) {
        values[i++] = str_to_uint64(args->argv[cur_value++], "value");
    }
    return values;
}
示例#16
0
int parse_uint64(uint64_t *x, char *payload)
{
	int errcode;

	if (bug_on(!x))
		return -err_internal;

	payload = strtok(payload, " ,");
	if (!payload)
		return -err_parse_no_args;

	errcode = str_to_uint64(payload, x);
	if (errcode < 0)
		return errcode;

	return 0;
}
示例#17
0
文件: lex.c 项目: gearsforwork/bareos
static uint64_t scan_pint64(LEX *lf, char *str)
{
   uint64_t val = 0;

   if (!is_a_number(str)) {
      scan_err1(lf, _("expected a positive integer number, got: %s"), str);
      /* NOT REACHED */
   } else {
      errno = 0;
      val = str_to_uint64(str);
      if (errno != 0) {
         scan_err1(lf, _("expected a positive integer number, got: %s"), str);
         /* NOT REACHED */
      }
   }

   return val;
}
示例#18
0
static bool cmd_setquota(struct client_command_context *cmd)
{
	struct quota_root *root;
        const struct imap_arg *args, *list_args;
	const char *root_name, *name, *value_str, *error;
	uint64_t value;

	/* <quota root> <resource limits> */
	if (!client_read_args(cmd, 2, 0, &args))
		return FALSE;

	if (!imap_arg_get_astring(&args[0], &root_name) ||
	    !imap_arg_get_list(&args[1], &list_args)) {
		client_send_command_error(cmd, "Invalid arguments.");
		return TRUE;
	}

	root = quota_root_lookup(cmd->client->user, root_name);
	if (root == NULL) {
		client_send_tagline(cmd, "NO Quota root doesn't exist.");
		return TRUE;
	}

	for (; !IMAP_ARG_IS_EOL(list_args); list_args += 2) {
		if (!imap_arg_get_atom(&list_args[0], &name) ||
		    !imap_arg_get_atom(&list_args[1], &value_str) ||
		    str_to_uint64(value_str, &value) < 0) {
			client_send_command_error(cmd, "Invalid arguments.");
			return TRUE;
		}

		if (quota_set_resource(root, name, value, &error) < 0) {
			client_send_command_error(cmd, error);
			return TRUE;
		}
	}

	client_send_tagline(cmd, "OK Setquota completed.");
	return TRUE;
}
示例#19
0
文件: imapc-mail.c 项目: bjacke/core
static int
imapc_mail_get_special(struct mail *_mail, enum mail_fetch_field field,
		       const char **value_r)
{
	struct imapc_mailbox *mbox = (struct imapc_mailbox *)_mail->box;
	struct index_mail *imail = (struct index_mail *)_mail;
	uint64_t num;

	switch (field) {
	case MAIL_FETCH_GUID:
		if (!IMAPC_BOX_HAS_FEATURE(mbox, IMAPC_FEATURE_GUID_FORCED) &&
		    mbox->guid_fetch_field_name == NULL) {
			/* GUIDs not supported by server */
			break;
		}
		*value_r = "";
		return imapc_mail_get_guid(_mail, value_r);
	case MAIL_FETCH_UIDL_BACKEND:
		if (!IMAPC_BOX_HAS_FEATURE(mbox, IMAPC_FEATURE_GMAIL_MIGRATION))
			break;
		if (imapc_mail_get_guid(_mail, value_r) < 0)
			return -1;
		if (str_to_uint64(*value_r, &num) < 0) {
			mail_storage_set_critical(_mail->box->storage,
				"X-GM-MSGID not 64bit integer as expected for POP3 UIDL generation: %s", *value_r);
			return -1;
		}

		*value_r = p_strdup_printf(imail->mail.data_pool, "GmailId%llx",
					   (unsigned long long)num);
		return 0;
	default:
		break;
	}

	return index_mail_get_special(_mail, field, value_r);
}
示例#20
0
文件: edit.c 项目: AlD/bareos
int64_t str_to_int64(const char *str)
{
   const char *p = str;
   int64_t value;
   bool negative = false;

   if (!p) {
      return 0;
   }
   while (B_ISSPACE(*p)) {
      p++;
   }
   if (*p == '+') {
      p++;
   } else if (*p == '-') {
      negative = true;
      p++;
   }
   value = str_to_uint64(p);
   if (negative) {
      value = -value;
   }
   return value;
}
示例#21
0
void *read_rows(FILE *f, int *nrows, char *fmt,
                char delimiter, char quote, char comment,
                char sci, char decimal,
                int allow_embedded_newline,
                char *datetime_fmt,
                int tz_offset,
                int32_t *usecols, int num_usecols,
                int skiprows,
                void *data_array,
                int *p_error_type, int *p_error_lineno)
{
    void *fb;
    char *data_ptr;
    int num_fields, current_num_fields;
    char **result;
    int fmt_nfields;
    field_type *ftypes;
    int size;
    int row_count;
    int j;
    int *valid_usecols;
    char word_buffer[WORD_BUFFER_SIZE];
    int tok_error_type;

    *p_error_type = 0;
    *p_error_lineno = 0;

    if (datetime_fmt == NULL || strlen(datetime_fmt) == 0) {
        datetime_fmt = "%Y-%m-%d %H:%M:%S";
    }

    size = (*nrows) * calc_size(fmt, &fmt_nfields);

    ftypes = enumerate_fields(fmt);  /* Must free this when finished. */
    if (ftypes == NULL) {
        /* Out of memory. */
        *p_error_type = READ_ERROR_OUT_OF_MEMORY;
        return NULL;
    }

    /*
    for (k = 0; k < fmt_nfields; ++k) {
        printf("k = %d  typechar = '%c'  size = %d\n", k, ftypes[k].typechar, ftypes[k].size);
    }
    printf("size = %d\n", size);
    printf("-----\n");
    */

    if (data_array == NULL) {
        /* XXX The case where data_ptr is allocated here is untested. */
        data_ptr = malloc(size);
    }
    else {
        data_ptr = data_array;
    }

    fb = new_file_buffer(f, -1);
    if (fb == NULL) {
        free(ftypes);
        *p_error_type = ERROR_OUT_OF_MEMORY;
        return NULL;
    }

    /* XXX Check interaction of skiprows with comments. */
    while ((skiprows > 0) && ((result = tokenize(fb, word_buffer, WORD_BUFFER_SIZE,
                              delimiter, quote, comment, &num_fields, TRUE, &tok_error_type)) != NULL)) {
        if (result == NULL) {
            break;
        }
        free(result);
        --skiprows;
    }

    if (skiprows > 0) {
        /* There were fewer rows in the file than skiprows. */
        /* This is not treated as an error. The result should be an empty array. */
        *nrows = 0;
        free(ftypes);
        del_file_buffer(fb, RESTORE_FINAL);
        return data_ptr;
    }

    /* XXX Assume *nrows > 0! */
    /*
     *  Read the first row to get the number of fields in the file.
     *  We'll then use this to pre-validate the values in usecols.
     *  (It might be easier to do this in the Python wrapper, but that
     *  would require refactoring the C interface a bit to expose more
     *  to Python.)
     */
    row_count = 0;
    result = tokenize(fb, word_buffer, WORD_BUFFER_SIZE,
                              delimiter, quote, comment, &num_fields, TRUE, &tok_error_type);
    if (result == NULL) {
        *p_error_type = tok_error_type;
        *p_error_lineno = 1;
        free(ftypes);
        del_file_buffer(fb, RESTORE_FINAL);
        return NULL;
    }

    valid_usecols = (int *) malloc(num_usecols * sizeof(int));
    if (valid_usecols == NULL) {
        /* Out of memory. */
        *p_error_type = ERROR_OUT_OF_MEMORY;
        free(result);
        free(ftypes);
        del_file_buffer(fb, RESTORE_FINAL);
        return NULL;
    }

    /*
     *  Validate the column indices in usecols, and put the validated
     *  column indices in valid_usecols.
     */
    for (j = 0; j < num_usecols; ++j) {

        int32_t k;
        k = usecols[j];
        if (k < -num_fields || k >= num_fields) {
            /* Invalid column index. */
            *p_error_type = ERROR_INVALID_COLUMN_INDEX;
            *p_error_lineno = j;  /* Abuse 'lineno' and put the bad column index there. */
            free(valid_usecols);
            free(result);
            free(ftypes);
            del_file_buffer(fb, RESTORE_FINAL);
            return NULL;
        }
        if (k < 0) {
            k += num_fields;
        }
        valid_usecols[j] = k;
    }

    current_num_fields = num_fields;
    row_count = 0;
    do {
        int j, k;

        if (current_num_fields != num_fields) {
            *p_error_type = ERROR_CHANGED_NUMBER_OF_FIELDS;
            *p_error_lineno = line_number(fb);
            break;
        }

        for (j = 0; j < num_usecols; ++j) {

            int error;
            char typ = ftypes[j].typechar;
            /* k is the column index of the field in the file. */
            k = valid_usecols[j];

            /* XXX Handle error != 0 in the following cases. */
            if (typ == 'b') {
                int8_t x = (int8_t) str_to_int64(result[k], INT8_MIN, INT8_MAX, &error);
                *(int8_t *) data_ptr = x;
                data_ptr += ftypes[j].size;
            }
            else if (typ == 'B') {
                uint8_t x = (uint8_t) str_to_uint64(result[k], UINT8_MAX, &error);
                *(uint8_t *) data_ptr = x;
                data_ptr += ftypes[j].size;   
            }
            else if (typ == 'h') {
                int16_t x = (int16_t) str_to_int64(result[k], INT16_MIN, INT16_MAX, &error);
                *(int16_t *) data_ptr = x;
                data_ptr += ftypes[j].size;
            }
            else if (typ == 'H') {
                uint16_t x = (uint16_t) str_to_uint64(result[k], UINT16_MAX, &error);
                *(uint16_t *) data_ptr = x;
                data_ptr += ftypes[j].size;    
            }
            else if (typ == 'i') {
                int32_t x = (int32_t) str_to_int64(result[k], INT32_MIN, INT32_MAX, &error);
                *(int32_t *) data_ptr = x;
                data_ptr += ftypes[j].size;   
            }
            else if (typ == 'I') {
                uint32_t x = (uint32_t) str_to_uint64(result[k], UINT32_MAX, &error);
                *(uint32_t *) data_ptr = x;
                data_ptr += ftypes[j].size;   
            }
            else if (typ == 'q') {
                int64_t x = (int64_t) str_to_int64(result[k], INT64_MIN, INT64_MAX, &error);
                *(int64_t *) data_ptr = x;
                data_ptr += ftypes[j].size; 
            }
            else if (typ == 'Q') {
                uint64_t x = (uint64_t) str_to_uint64(result[k], UINT64_MAX, &error);
                *(uint64_t *) data_ptr = x;
                data_ptr += ftypes[j].size;    
            }
            else if (typ == 'f' || typ == 'd') {
                // Convert to float.
                double x;
                if ((strlen(result[k]) == 0) || !to_double(result[k], &x, sci, decimal)) {
                    // XXX  Find the canonical platform-independent method to assign nan.
                    x = 0.0 / 0.0;
                }
                if (typ == 'f')
                    *(float *) data_ptr = (float) x;
                else
                    *(double *) data_ptr = x;
                data_ptr += ftypes[j].size;
            }
            else if (typ == 'c' || typ == 'z') {
                // Convert to complex.
                double x, y;
                if ((strlen(result[k]) == 0) || !to_complex(result[k], &x, &y, sci, decimal)) {
                    // XXX  Find the canonical platform-independent method to assign nan.
                    x = 0.0 / 0.0;
                    y = x;
                }
                if (typ == 'c') {
                    *(float *) data_ptr = (float) x;
                    data_ptr += ftypes[j].size / 2;
                    *(float *) data_ptr = (float) y;
                }
                else {
                    *(double *) data_ptr = x;
                    data_ptr += ftypes[j].size / 2; 
                    *(double *) data_ptr = y;
                }
                data_ptr += ftypes[j].size / 2;
            }
            else if (typ == 'U') {
                // Datetime64, microseconds.
                struct tm tm = {0,0,0,0,0,0,0,0,0};
                time_t t;

                if (strptime(result[k], datetime_fmt, &tm) == NULL) {
                    memset(data_ptr, 0, 8);
                }
                else {
                    tm.tm_isdst = -1;
                    t = mktime(&tm);
                    if (t == -1) {
                        memset(data_ptr, 0, 8);
                    }
                    else {
                        *(uint64_t *) data_ptr = (long long) (t - tz_offset) * 1000000L;
                    }
                }
                data_ptr += 8;
            }
            else {
                // String
                strncpy(data_ptr, result[k], ftypes[j].size);
                data_ptr += ftypes[j].size;
            }
        }
        free(result);
        ++row_count;
    } while ((row_count < *nrows) && (result = tokenize(fb, word_buffer, WORD_BUFFER_SIZE,
                              delimiter, quote, comment, &current_num_fields, TRUE, &tok_error_type)) != NULL);

    del_file_buffer(fb, RESTORE_FINAL);

    *nrows = row_count;

    free(valid_usecols);

    return (void *) data_ptr;
}
示例#22
0
static uint8_t client_parse(Client *client, int size) {
	char *end, *str;
	uint16_t status_code;

	switch (client->parser_state) {
		case PARSER_START:
			//printf("parse (START):\n%s\n", &client->buffer[client->parser_offset]);
			/* look for HTTP/1.1 200 OK */
			if (client->buffer_offset < sizeof("HTTP/1.1 200\r\n"))
				return 1;

			if (strncmp(client->buffer, "HTTP/1.1 ", sizeof("HTTP/1.1 ")-1) != 0)
				return 0;

			// now the status code
			status_code = 0;
			str = client->buffer + sizeof("HTTP/1.1 ")-1;
			for (end = str + 3; str != end; str++) {
				if (*str < '0' || *str > '9')
					return 0;

				status_code *= 10;
				status_code += *str - '0';
			}

			// look for next \r\n
			end = memchr(end, '\r', client->buffer_offset);
			if (!end || *(end+1) != '\n')
				return (!end || *(end+1) == '\0') && client->buffer_offset < 1024 ? 1 : 0;

			if (status_code >= 200 && status_code < 300) {
				client->worker->stats.req_2xx++;
				client->status_success = 1;
			} else if (status_code < 400) {
				client->worker->stats.req_3xx++;
				client->status_success = 1;
			} else if (status_code < 500) {
				client->worker->stats.req_4xx++;
			} else if (status_code < 600) {
				client->worker->stats.req_5xx++;
			} else {
				// invalid status code
				return 0;
			}

			client->parser_offset = end + 2 - client->buffer;
			client->parser_state = PARSER_HEADER;
		case PARSER_HEADER:
			//printf("parse (HEADER)\n");
			/* look for Content-Length and Connection header */
			while (NULL != (end = memchr(&client->buffer[client->parser_offset], '\r', client->buffer_offset - client->parser_offset))) {
				if (*(end+1) != '\n')
					return *(end+1) == '\0' && client->buffer_offset - client->parser_offset < 1024 ? 1 : 0;

				if (end == &client->buffer[client->parser_offset]) {
					/* body reached */
					client->parser_state = PARSER_BODY;
					client->header_size = end + 2 - client->buffer;
					//printf("body reached\n");

					return client_parse(client, size - client->header_size);
				}

				*end = '\0';
				str = &client->buffer[client->parser_offset];
				//printf("checking header: '%s'\n", str);

				if (strncasecmp(str, "Content-Length: ", sizeof("Content-Length: ")-1) == 0) {
					/* content length header */
					client->content_length = str_to_uint64(str + sizeof("Content-Length: ") - 1);
				} else if (strncasecmp(str, "Connection: ", sizeof("Connection: ")-1) == 0) {
					/* connection header */
					str += sizeof("Connection: ") - 1;

					if (strncasecmp(str, "close", sizeof("close")-1) == 0)
						client->keepalive = 0;
					else if (strncasecmp(str, "keep-alive", sizeof("keep-alive")-1) == 0)
						client->keepalive = client->worker->config->keep_alive;
					else
						return 0;
				} else if (strncasecmp(str, "Transfer-Encoding: ", sizeof("Transfer-Encoding: ")-1) == 0) {
					/* transfer encoding header */
					str += sizeof("Transfer-Encoding: ") - 1;

					if (strncasecmp(str, "chunked", sizeof("chunked")-1) == 0)
						client->chunked = 1;
					else
						return 0;
				}


				if (*(end+2) == '\r' && *(end+3) == '\n') {
					/* body reached */
					client->parser_state = PARSER_BODY;
					client->header_size = end + 4 - client->buffer;
					client->parser_offset = client->header_size;
					//printf("body reached\n");

					return client_parse(client, size - client->header_size);
				}

				client->parser_offset = end - client->buffer + 2;
			}

			return 1;
		case PARSER_BODY:
			//printf("parse (BODY)\n");
			/* do nothing, just consume the data */
			/*printf("content-l: %"PRIu64", header: %d, recevied: %"PRIu64"\n",
			client->content_length, client->header_size, client->bytes_received);*/

			if (client->chunked) {
				int consume_max;

				str = &client->buffer[client->parser_offset];
				/*printf("parsing chunk: '%s'\n(%"PRIi64" received, %"PRIi64" size, %d parser offset)\n",
					str, client->chunk_received, client->chunk_size, client->parser_offset
				);*/

				if (client->chunk_size == -1) {
					/* read chunk size */
					client->chunk_size = 0;
					client->chunk_received = 0;
					end = str + size;

					for (; str < end; str++) {
						if (*str == ';' || *str == '\r')
							break;

						client->chunk_size *= 16;
						if (*str >= '0' && *str <= '9')
							client->chunk_size += *str - '0';
						else if (*str >= 'A' && *str <= 'Z')
							client->chunk_size += 10 + *str - 'A';
						else if (*str >= 'a' && *str <= 'z')
							client->chunk_size += 10 + *str - 'a';
						else
							return 0; /*(src < end checked above)*/
					}

					if (str[0] != '\r') {
						str = memchr(str, '\r', end-str);
						if (!str) {
							client->chunk_size = -1;
							return size < 1024 ? 1 : 0;
						}
					}
					if (str[1] != '\n') {
						client->chunk_size = -1;
						return str+1 == end ? 1 : 0;
					}
					str += 2;

					//printf("---------- chunk size: %"PRIi64", %d read, %d offset, data: '%s'\n", client->chunk_size, size, client->parser_offset, str);

					size -= str - &client->buffer[client->parser_offset];
					client->parser_offset = str - client->buffer;

					if (client->chunk_size == 0) {
						/* chunk of size 0 marks end of content body */
						client->state = CLIENT_END;
						client->success = client->status_success ? 1 : 0;
						return 1;
					}
				}

				/* consume chunk till chunk_size is reached */
				consume_max = client->chunk_size - client->chunk_received;

				if (size < consume_max)
					consume_max = size;

				client->chunk_received += consume_max;
				client->parser_offset += consume_max;

				//printf("---------- chunk consuming: %d, received: %"PRIi64" of %"PRIi64", offset: %d\n", consume_max, client->chunk_received, client->chunk_size, client->parser_offset);

				if (client->chunk_received == client->chunk_size) {
					if (size - consume_max < 2)
						return 1;

					if (client->buffer[client->parser_offset] != '\r' || client->buffer[client->parser_offset+1] != '\n')
						return 0;

					/* got whole chunk, next! */
					//printf("---------- got whole chunk!!\n");
					client->chunk_size = -1;
					client->chunk_received = 0;
					client->parser_offset += 2;
					consume_max += 2;

					/* there is stuff left to parse */
					if (size - consume_max > 0)
						return client_parse(client, size - consume_max);
				}

				client->parser_offset = 0;
				client->buffer_offset = 0;

				return 1;
			} else {
				/* not chunked, just consume all data till content-length is reached */
				client->buffer_offset = 0;

				if (client->content_length == -1)
					return 0;

				if (client->bytes_received == (uint64_t) (client->header_size + client->content_length)) {
					/* full response received */
					client->state = CLIENT_END;
					client->success = client->status_success ? 1 : 0;
				}
			}

			return 1;
	}

	return 1;
}
示例#23
0
文件: args.c 项目: pexip/os-xz-utils
static void
parse_real(args_info *args, int argc, char **argv)
{
	enum {
		OPT_X86 = INT_MIN,
		OPT_POWERPC,
		OPT_IA64,
		OPT_ARM,
		OPT_ARMTHUMB,
		OPT_SPARC,
		OPT_DELTA,
		OPT_LZMA1,
		OPT_LZMA2,

		OPT_SINGLE_STREAM,
		OPT_NO_SPARSE,
		OPT_FILES,
		OPT_FILES0,
		OPT_BLOCK_SIZE,
		OPT_MEM_COMPRESS,
		OPT_MEM_DECOMPRESS,
		OPT_NO_ADJUST,
		OPT_INFO_MEMORY,
		OPT_ROBOT,
	};

	static const char short_opts[]
			= "cC:defF:hHlkM:qQrS:tT:vVz0123456789";

	static const struct option long_opts[] = {
		// Operation mode
		{ "compress",     no_argument,       NULL,  'z' },
		{ "decompress",   no_argument,       NULL,  'd' },
		{ "uncompress",   no_argument,       NULL,  'd' },
		{ "test",         no_argument,       NULL,  't' },
		{ "list",         no_argument,       NULL,  'l' },

		// Operation modifiers
		{ "keep",         no_argument,       NULL,  'k' },
		{ "force",        no_argument,       NULL,  'f' },
		{ "stdout",       no_argument,       NULL,  'c' },
		{ "to-stdout",    no_argument,       NULL,  'c' },
		{ "single-stream", no_argument,      NULL,  OPT_SINGLE_STREAM },
		{ "no-sparse",    no_argument,       NULL,  OPT_NO_SPARSE },
		{ "suffix",       required_argument, NULL,  'S' },
		// { "recursive",      no_argument,       NULL,  'r' }, // TODO
		{ "files",        optional_argument, NULL,  OPT_FILES },
		{ "files0",       optional_argument, NULL,  OPT_FILES0 },

		// Basic compression settings
		{ "format",       required_argument, NULL,  'F' },
		{ "check",        required_argument, NULL,  'C' },
		{ "block-size",   required_argument, NULL,  OPT_BLOCK_SIZE },
		{ "memlimit-compress",   required_argument, NULL, OPT_MEM_COMPRESS },
		{ "memlimit-decompress", required_argument, NULL, OPT_MEM_DECOMPRESS },
		{ "memlimit",     required_argument, NULL,  'M' },
		{ "memory",       required_argument, NULL,  'M' }, // Old alias
		{ "no-adjust",    no_argument,       NULL,  OPT_NO_ADJUST },
		{ "threads",      required_argument, NULL,  'T' },

		{ "extreme",      no_argument,       NULL,  'e' },
		{ "fast",         no_argument,       NULL,  '0' },
		{ "best",         no_argument,       NULL,  '9' },

		// Filters
		{ "lzma1",        optional_argument, NULL,  OPT_LZMA1 },
		{ "lzma2",        optional_argument, NULL,  OPT_LZMA2 },
		{ "x86",          optional_argument, NULL,  OPT_X86 },
		{ "powerpc",      optional_argument, NULL,  OPT_POWERPC },
		{ "ia64",         optional_argument, NULL,  OPT_IA64 },
		{ "arm",          optional_argument, NULL,  OPT_ARM },
		{ "armthumb",     optional_argument, NULL,  OPT_ARMTHUMB },
		{ "sparc",        optional_argument, NULL,  OPT_SPARC },
		{ "delta",        optional_argument, NULL,  OPT_DELTA },

		// Other options
		{ "quiet",        no_argument,       NULL,  'q' },
		{ "verbose",      no_argument,       NULL,  'v' },
		{ "no-warn",      no_argument,       NULL,  'Q' },
		{ "robot",        no_argument,       NULL,  OPT_ROBOT },
		{ "info-memory",  no_argument,       NULL,  OPT_INFO_MEMORY },
		{ "help",         no_argument,       NULL,  'h' },
		{ "long-help",    no_argument,       NULL,  'H' },
		{ "version",      no_argument,       NULL,  'V' },

		{ NULL,           0,                 NULL,   0 }
	};

	int c;

	while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL))
			!= -1) {
		switch (c) {
		// Compression preset (also for decompression if --format=raw)
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			coder_set_preset(c - '0');
			break;

		// --memlimit-compress
		case OPT_MEM_COMPRESS:
			parse_memlimit("memlimit-compress",
					"memlimit-compress%", optarg,
					true, false);
			break;

		// --memlimit-decompress
		case OPT_MEM_DECOMPRESS:
			parse_memlimit("memlimit-decompress",
					"memlimit-decompress%", optarg,
					false, true);
			break;

		// --memlimit
		case 'M':
			parse_memlimit("memlimit", "memlimit%", optarg,
					true, true);
			break;

		// --suffix
		case 'S':
			suffix_set(optarg);
			break;

		case 'T':
			// The max is from src/liblzma/common/common.h.
			hardware_threads_set(str_to_uint64("threads",
					optarg, 0, 16384));
			break;

		// --version
		case 'V':
			// This doesn't return.
			message_version();

		// --stdout
		case 'c':
			opt_stdout = true;
			break;

		// --decompress
		case 'd':
			opt_mode = MODE_DECOMPRESS;
			break;

		// --extreme
		case 'e':
			coder_set_extreme();
			break;

		// --force
		case 'f':
			opt_force = true;
			break;

		// --info-memory
		case OPT_INFO_MEMORY:
			// This doesn't return.
			hardware_memlimit_show();

		// --help
		case 'h':
			// This doesn't return.
			message_help(false);

		// --long-help
		case 'H':
			// This doesn't return.
			message_help(true);

		// --list
		case 'l':
			opt_mode = MODE_LIST;
			break;

		// --keep
		case 'k':
			opt_keep_original = true;
			break;

		// --quiet
		case 'q':
			message_verbosity_decrease();
			break;

		case 'Q':
			set_exit_no_warn();
			break;

		case 't':
			opt_mode = MODE_TEST;
			break;

		// --verbose
		case 'v':
			message_verbosity_increase();
			break;

		// --robot
		case OPT_ROBOT:
			opt_robot = true;

			// This is to make sure that floating point numbers
			// always have a dot as decimal separator.
			setlocale(LC_NUMERIC, "C");
			break;

		case 'z':
			opt_mode = MODE_COMPRESS;
			break;

		// Filter setup

		case OPT_X86:
			coder_add_filter(LZMA_FILTER_X86,
					options_bcj(optarg));
			break;

		case OPT_POWERPC:
			coder_add_filter(LZMA_FILTER_POWERPC,
					options_bcj(optarg));
			break;

		case OPT_IA64:
			coder_add_filter(LZMA_FILTER_IA64,
					options_bcj(optarg));
			break;

		case OPT_ARM:
			coder_add_filter(LZMA_FILTER_ARM,
					options_bcj(optarg));
			break;

		case OPT_ARMTHUMB:
			coder_add_filter(LZMA_FILTER_ARMTHUMB,
					options_bcj(optarg));
			break;

		case OPT_SPARC:
			coder_add_filter(LZMA_FILTER_SPARC,
					options_bcj(optarg));
			break;

		case OPT_DELTA:
			coder_add_filter(LZMA_FILTER_DELTA,
					options_delta(optarg));
			break;

		case OPT_LZMA1:
			coder_add_filter(LZMA_FILTER_LZMA1,
					options_lzma(optarg));
			break;

		case OPT_LZMA2:
			coder_add_filter(LZMA_FILTER_LZMA2,
					options_lzma(optarg));
			break;

		// Other

		// --format
		case 'F': {
			// Just in case, support both "lzma" and "alone" since
			// the latter was used for forward compatibility in
			// LZMA Utils 4.32.x.
			static const struct {
				char str[8];
				enum format_type format;
			} types[] = {
				{ "auto",   FORMAT_AUTO },
				{ "xz",     FORMAT_XZ },
				{ "lzma",   FORMAT_LZMA },
				{ "alone",  FORMAT_LZMA },
				// { "gzip",   FORMAT_GZIP },
				// { "gz",     FORMAT_GZIP },
				{ "raw",    FORMAT_RAW },
			};

			size_t i = 0;
			while (strcmp(types[i].str, optarg) != 0)
				if (++i == ARRAY_SIZE(types))
					message_fatal(_("%s: Unknown file "
							"format type"),
							optarg);

			opt_format = types[i].format;
			break;
		}

		// --check
		case 'C': {
			static const struct {
				char str[8];
				lzma_check check;
			} types[] = {
				{ "none",   LZMA_CHECK_NONE },
				{ "crc32",  LZMA_CHECK_CRC32 },
				{ "crc64",  LZMA_CHECK_CRC64 },
				{ "sha256", LZMA_CHECK_SHA256 },
			};

			size_t i = 0;
			while (strcmp(types[i].str, optarg) != 0) {
				if (++i == ARRAY_SIZE(types))
					message_fatal(_("%s: Unsupported "
							"integrity "
							"check type"), optarg);
			}

			// Use a separate check in case we are using different
			// liblzma than what was used to compile us.
			if (!lzma_check_is_supported(types[i].check))
				message_fatal(_("%s: Unsupported integrity "
						"check type"), optarg);

			coder_set_check(types[i].check);
			break;
		}

		case OPT_BLOCK_SIZE:
			opt_block_size = str_to_uint64("block-size", optarg,
					0, LZMA_VLI_MAX);
			break;

		case OPT_SINGLE_STREAM:
			opt_single_stream = true;
			break;

		case OPT_NO_SPARSE:
			io_no_sparse();
			break;

		case OPT_FILES:
			args->files_delim = '\n';

		// Fall through

		case OPT_FILES0:
			if (args->files_name != NULL)
				message_fatal(_("Only one file can be "
						"specified with `--files' "
						"or `--files0'."));

			if (optarg == NULL) {
				args->files_name = (char *)stdin_filename;
				args->files_file = stdin;
			} else {
				args->files_name = optarg;
				args->files_file = fopen(optarg,
						c == OPT_FILES ? "r" : "rb");
				if (args->files_file == NULL)
					message_fatal("%s: %s", optarg,
							strerror(errno));
			}

			break;

		case OPT_NO_ADJUST:
			opt_auto_adjust = false;
			break;

		default:
			message_try_help();
			tuklib_exit(E_ERROR, E_ERROR, false);
		}
	}

	return;
}
示例#24
0
文件: sql_find.c 项目: debfx/bareos
/*
 * Find Available Media (Volume) for Pool
 *
 * Find a Volume for a given PoolId, MediaType, and Status.
 * The unwanted_volumes variable lists the VolumeNames which we should skip if any.
 *
 * Returns: 0 on failure
 *          numrows on success
 */
int db_find_next_volume(JCR *jcr, B_DB *mdb, int item, bool InChanger, MEDIA_DBR *mr, const char *unwanted_volumes)
{
   char ed1[50];
   int num_rows = 0;
   SQL_ROW row = NULL;
   bool find_oldest = false;
   bool found_candidate = false;
   char esc_type[MAX_ESCAPE_NAME_LENGTH];
   char esc_status[MAX_ESCAPE_NAME_LENGTH];

   db_lock(mdb);

   mdb->db_escape_string(jcr, esc_type, mr->MediaType, strlen(mr->MediaType));
   mdb->db_escape_string(jcr, esc_status, mr->VolStatus, strlen(mr->VolStatus));

   if (item == -1) {
      find_oldest = true;
      item = 1;
   }

retry_fetch:
   if (find_oldest) {
      /*
       * Find oldest volume(s)
       */
      Mmsg(mdb->cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
                     "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
                     "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
                     "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
                     "EndFile,EndBlock,LabelType,LabelDate,StorageId,"
                     "Enabled,LocationId,RecycleCount,InitialWrite,"
                     "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,"
                     "ActionOnPurge,EncryptionKey,MinBlocksize,MaxBlocksize "
                     "FROM Media WHERE PoolId=%s AND MediaType='%s' AND VolStatus IN ('Full',"
                     "'Recycle','Purged','Used','Append') AND Enabled=1 "
                     "ORDER BY LastWritten LIMIT %d",
           edit_int64(mr->PoolId, ed1), esc_type, item);
   } else {
      POOL_MEM changer(PM_FNAME);
      const char *order;

      /*
       * Find next available volume
       */
      if (InChanger) {
         Mmsg(changer, "AND InChanger=1 AND StorageId=%s", edit_int64(mr->StorageId, ed1));
      }

      if (bstrcmp(mr->VolStatus, "Recycle") ||
          bstrcmp(mr->VolStatus, "Purged")) {
         order = "AND Recycle=1 ORDER BY LastWritten ASC,MediaId";  /* take oldest that can be recycled */
      } else {
         order = sql_media_order_most_recently_written[db_get_type_index(mdb)];    /* take most recently written */
      }

      Mmsg(mdb->cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
                     "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
                     "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
                     "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
                     "EndFile,EndBlock,LabelType,LabelDate,StorageId,"
                     "Enabled,LocationId,RecycleCount,InitialWrite,"
                     "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,"
                     "ActionOnPurge,EncryptionKey,MinBlocksize,MaxBlocksize "
                     "FROM Media WHERE PoolId=%s AND MediaType='%s' AND Enabled=1 "
                     "AND VolStatus='%s' "
                     "%s "
                     "%s LIMIT %d",
           edit_int64(mr->PoolId, ed1), esc_type,
           esc_status, changer.c_str(), order, item);
   }

   Dmsg1(100, "fnextvol=%s\n", mdb->cmd);
   if (!QUERY_DB(jcr, mdb, mdb->cmd)) {
      goto bail_out;
   }

   num_rows = sql_num_rows(mdb);
   if (item > num_rows || item < 1) {
      Dmsg2(050, "item=%d got=%d\n", item, num_rows);
      Mmsg2(&mdb->errmsg, _("Request for Volume item %d greater than max %d or less than 1\n"), item, num_rows);
      num_rows = 0;
      goto bail_out;
   }

   for (int i = 0 ; i < item; i++) {
      if ((row = sql_fetch_row(mdb)) == NULL) {
         Dmsg1(050, "Fail fetch item=%d\n", i);
         Mmsg1(&mdb->errmsg, _("No Volume record found for item %d.\n"), i);
         sql_free_result(mdb);
         num_rows = 0;
         goto bail_out;
      }

      /*
       * See if this is not on the unwanted volumes list.
       */
      if (unwanted_volumes && is_on_unwanted_volumes_list(row[1], unwanted_volumes)) {
         continue;
      }

      /*
       * Return fields in Media Record
       */
      mr->MediaId = str_to_int64(row[0]);
      bstrncpy(mr->VolumeName, (row[1] != NULL) ? row[1] : "", sizeof(mr->VolumeName));
      mr->VolJobs = str_to_int64(row[2]);
      mr->VolFiles = str_to_int64(row[3]);
      mr->VolBlocks = str_to_int64(row[4]);
      mr->VolBytes = str_to_uint64(row[5]);
      mr->VolMounts = str_to_int64(row[6]);
      mr->VolErrors = str_to_int64(row[7]);
      mr->VolWrites = str_to_int64(row[8]);
      mr->MaxVolBytes = str_to_uint64(row[9]);
      mr->VolCapacityBytes = str_to_uint64(row[10]);
      bstrncpy(mr->MediaType, (row[11] != NULL) ? row[11] : "", sizeof(mr->MediaType));
      bstrncpy(mr->VolStatus, (row[12] != NULL) ? row[12] : "", sizeof(mr->VolStatus));
      mr->PoolId = str_to_int64(row[13]);
      mr->VolRetention = str_to_uint64(row[14]);
      mr->VolUseDuration = str_to_uint64(row[15]);
      mr->MaxVolJobs = str_to_int64(row[16]);
      mr->MaxVolFiles = str_to_int64(row[17]);
      mr->Recycle = str_to_int64(row[18]);
      mr->Slot = str_to_int64(row[19]);
      bstrncpy(mr->cFirstWritten, (row[20] != NULL) ? row[20] : "", sizeof(mr->cFirstWritten));
      mr->FirstWritten = (time_t)str_to_utime(mr->cFirstWritten);
      bstrncpy(mr->cLastWritten, (row[21] != NULL) ? row[21] : "", sizeof(mr->cLastWritten));
      mr->LastWritten = (time_t)str_to_utime(mr->cLastWritten);
      mr->InChanger = str_to_uint64(row[22]);
      mr->EndFile = str_to_uint64(row[23]);
      mr->EndBlock = str_to_uint64(row[24]);
      mr->LabelType = str_to_int64(row[25]);
      bstrncpy(mr->cLabelDate, (row[26] != NULL) ? row[26] : "", sizeof(mr->cLabelDate));
      mr->LabelDate = (time_t)str_to_utime(mr->cLabelDate);
      mr->StorageId = str_to_int64(row[27]);
      mr->Enabled = str_to_int64(row[28]);
      mr->LocationId = str_to_int64(row[29]);
      mr->RecycleCount = str_to_int64(row[30]);
      bstrncpy(mr->cInitialWrite, (row[31] != NULL) ? row[31] : "", sizeof(mr->cInitialWrite));
      mr->InitialWrite = (time_t)str_to_utime(mr->cInitialWrite);
      mr->ScratchPoolId = str_to_int64(row[32]);
      mr->RecyclePoolId = str_to_int64(row[33]);
      mr->VolReadTime = str_to_int64(row[34]);
      mr->VolWriteTime = str_to_int64(row[35]);
      mr->ActionOnPurge = str_to_int64(row[36]);
      bstrncpy(mr->EncrKey, (row[37] != NULL) ? row[37] : "", sizeof(mr->EncrKey));
      mr->MinBlocksize = str_to_int32(row[38]);
      mr->MaxBlocksize = str_to_int32(row[39]);

      sql_free_result(mdb);
      found_candidate = true;
      break;
   }

   if (!found_candidate && find_oldest) {
      item++;
      goto retry_fetch;
   }

bail_out:
   db_unlock(mdb);
   Dmsg1(050, "Rtn numrows=%d\n", num_rows);

   return num_rows;
}
示例#25
0
/*
 * Initialize the static structure to zeros, then apply all the default values.
 */
void CONFIG::init_resource(int type, RES_ITEM *items, int pass)
{
   URES *res_all;

   memset(m_res_all, 0, m_res_all_size);
   res_all = ((URES *)m_res_all);
   res_all->hdr.rcode = type;
   res_all->hdr.refcnt = 1;

   /*
    * See what pass of the config parsing this is.
    */
   switch (pass) {
   case 1: {
      /*
       * Set all defaults for types that are filled in pass 1 of the config parser.
       */
      int i;

      for (i = 0; items[i].name; i++) {
         Dmsg3(900, "Item=%s def=%s defval=%s\n", items[i].name,
               (items[i].flags & CFG_ITEM_DEFAULT) ? "yes" : "no",
               (items[i].default_value) ? items[i].default_value : "None");

         /*
          * Sanity check.
          *
          * Items with a default value but without the CFG_ITEM_DEFAULT flag set
          * are most of the time an indication of a programmers error.
          */
         if (items[i].default_value != NULL && !(items[i].flags & CFG_ITEM_DEFAULT)) {
            Pmsg1(000, _("Found config item %s which has default value but no CFG_ITEM_DEFAULT flag set\n"),
                  items[i].name);
            items[i].flags |= CFG_ITEM_DEFAULT;
         }

         /*
          * See if the CFG_ITEM_DEFAULT flag is set and a default value is available.
          */
         if (items[i].flags & CFG_ITEM_DEFAULT && items[i].default_value != NULL) {
            /*
             * First try to handle the generic types.
             */
            switch (items[i].type) {
            case CFG_TYPE_BIT:
               if (bstrcasecmp(items[i].default_value, "on")) {
                  set_bit(items[i].code, items[i].bitvalue);
               } else if (bstrcasecmp(items[i].default_value, "off")) {
                  clear_bit(items[i].code, items[i].bitvalue);
               }
               break;
            case CFG_TYPE_BOOL:
               if (bstrcasecmp(items[i].default_value, "yes") ||
                   bstrcasecmp(items[i].default_value, "true")) {
                  *(items[i].boolvalue) = true;
               } else if (bstrcasecmp(items[i].default_value, "no") ||
                          bstrcasecmp(items[i].default_value, "false")) {
                  *(items[i].boolvalue) = false;
               }
               break;
            case CFG_TYPE_PINT32:
            case CFG_TYPE_INT32:
            case CFG_TYPE_SIZE32:
               *(items[i].ui32value) = str_to_int32(items[i].default_value);
               break;
            case CFG_TYPE_INT64:
               *(items[i].i64value) = str_to_int64(items[i].default_value);
               break;
            case CFG_TYPE_SIZE64:
               *(items[i].ui64value) = str_to_uint64(items[i].default_value);
               break;
            case CFG_TYPE_SPEED:
               *(items[i].ui64value) = str_to_uint64(items[i].default_value);
               break;
            case CFG_TYPE_TIME:
               *(items[i].utimevalue) = str_to_int64(items[i].default_value);
               break;
            case CFG_TYPE_STRNAME:
            case CFG_TYPE_STR:
               *(items[i].value) = bstrdup(items[i].default_value);
               break;
            case CFG_TYPE_DIR: {
               POOL_MEM pathname(PM_FNAME);

               pm_strcpy(pathname, items[i].default_value);
               if (*pathname.c_str() != '|') {
                  int size;

                  /*
                   * Make sure we have enough room
                   */
                  size = pathname.size() + 1024;
                  pathname.check_size(size);
                  do_shell_expansion(pathname.c_str(), pathname.size());
               }
               *items[i].value = bstrdup(pathname.c_str());
               break;
            }
            case CFG_TYPE_ADDRESSES:
               init_default_addresses(items[i].dlistvalue, items[i].default_value);
               break;
            default:
               /*
                * None of the generic types fired if there is a registered callback call that now.
                */
               if (m_init_res) {
                  m_init_res(&items[i], pass);
               }
               break;
            }

            if (!m_omit_defaults) {
               set_bit(i, res_all->hdr.inherit_content);
            }
         }

         /*
          * If this triggers, take a look at lib/parse_conf.h
          */
         if (i >= MAX_RES_ITEMS) {
            Emsg1(M_ERROR_TERM, 0, _("Too many items in %s resource\n"), m_resources[type - m_r_first]);
         }
      }
      break;
   }
   case 2: {
      /*
       * Set all defaults for types that are filled in pass 2 of the config parser.
       */
      int i;

      for (i = 0; items[i].name; i++) {
         Dmsg3(900, "Item=%s def=%s defval=%s\n", items[i].name,
               (items[i].flags & CFG_ITEM_DEFAULT) ? "yes" : "no",
               (items[i].default_value) ? items[i].default_value : "None");

         /*
          * See if the CFG_ITEM_DEFAULT flag is set and a default value is available.
          */
         if (items[i].flags & CFG_ITEM_DEFAULT && items[i].default_value != NULL) {
            /*
             * First try to handle the generic types.
             */
            switch (items[i].type) {
            case CFG_TYPE_ALIST_STR:
               if (!*items[i].alistvalue) {
                  *(items[i].alistvalue) = New(alist(10, owned_by_alist));
               }
               (*(items[i].alistvalue))->append(bstrdup(items[i].default_value));
               break;
            case CFG_TYPE_ALIST_DIR: {
               POOL_MEM pathname(PM_FNAME);

               if (!*items[i].alistvalue) {
                  *(items[i].alistvalue) = New(alist(10, owned_by_alist));
               }

               pm_strcpy(pathname, items[i].default_value);
               if (*items[i].default_value != '|') {
                  int size;

                  /*
                   * Make sure we have enough room
                   */
                  size = pathname.size() + 1024;
                  pathname.check_size(size);
                  do_shell_expansion(pathname.c_str(), pathname.size());
               }
               (*(items[i].alistvalue))->append(bstrdup(pathname.c_str()));
               break;
            }
            default:
               /*
                * None of the generic types fired if there is a registered callback call that now.
                */
               if (m_init_res) {
                  m_init_res(&items[i], pass);
               }
               break;
            }

            if (!m_omit_defaults) {
               set_bit(i, res_all->hdr.inherit_content);
            }
         }

         /*
          * If this triggers, take a look at lib/parse_conf.h
          */
         if (i >= MAX_RES_ITEMS) {
            Emsg1(M_ERROR_TERM, 0, _("Too many items in %s resource\n"), m_resources[type - m_r_first]);
         }
      }
      break;
   }
   default:
      break;
   }
}
示例#26
0
int parse_yasm_labels(struct label *l, const struct text *t)
{
	int errcode, no_org_directive;
	size_t i;
	uint64_t base_addr;
	enum { linelen = 1024 };
	char line[linelen];
	struct label *length;

	if (bug_on(!t))
		return -err_internal;

	base_addr = 0;
	no_org_directive = 1;
	length = NULL;

	/* determine base address from org directive and insert special
	 * section labels.
	 */
	for (i = 0; i < t->n; i++) {
		char *tmp;

		errcode = text_line(t, line, linelen, i);
		if (errcode < 0)
			return errcode;

		tmp = strstr(line, "[section");
		if (tmp) {
			tmp += strlen("[section");
			errcode = parse_section(tmp, l, &length);
			if (errcode < 0)
				return errcode;
			continue;
		}

		tmp = strstr(line, "[org");
		if (tmp) {
			base_addr = strtol(tmp+strlen("[org"), NULL, 0);

			errcode = l_append(l, "org", base_addr);
			if (errcode < 0)
				return errcode;

			no_org_directive = 0;
			continue;
		}

		/* update the section_<name>_length label, if we have one.
		 *
		 * this must be last; it destroys @line.
		 */
		if (length) {
			uint64_t value, size;

			tmp = strtok(line, " ");
			if (!tmp)
				continue;

			/* we expect a line number. */
			errcode = str_to_uint64(tmp, &value, 10);
			if (errcode < 0)
				continue;

			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* we expect an address. */
			errcode = str_to_uint64(tmp, &value, 16);
			if (errcode < 0)
				continue;

			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* we expect an opcode. */
			errcode = str_to_uint64(tmp, &value, 16);
			if (errcode < 0)
				continue;

			/* we got an opcode - let's compute it's size. */
			for (size = 0; value != 0; value >>= 8)
				size += 1;

			/* update the section_<name>_length label. */
			length->addr += size;
		}
	}

	if (no_org_directive)
		return -err_no_org_directive;

	for (i = 0; i < t->n; i++) {
		char *tmp, *name;
		uint64_t addr;

		errcode = text_line(t, line, linelen, i);
		if (errcode < 0)
			goto error;

		/* Change the base on section switches. */
		tmp = strstr(line, "[section");
		if (tmp) {
			tmp += strlen("[section");
			errcode = lookup_section_vstart(l, tmp, &base_addr);
			if (errcode < 0)
				return errcode;
			continue;
		}

		/* skip line number count.  */
		tmp = strtok(line, " ");
		if (!tmp)
			continue;

		/* the label can now be on the same line as the memory
		 * address or on a line by its own.
		 * we look at the next token and (1) if it looks like a
		 * label, we search in the following lines for the
		 * corresponding address; or (2) if it looks like an
		 * address, we store it and see if the token after the
		 * opcode looks like a token; or (3) none of the above,
		 * we continue with the next line.
		 */

		/* second token after the line number count.  it's
		 * either an address; or a label.
		 */
		tmp = strtok(NULL, " ");
		if (!tmp)
			continue;

		if (!make_label(tmp)) {
			/* get address in case we find a label later.  */
			if (sscanf(tmp, "%" PRIx64, &addr) != 1)
				continue;

			/* skip the opcode token.  */
			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* this might be a label now.  */
			tmp = strtok(NULL, " ");
			if (!make_label(tmp))
				continue;

			errcode = l_append(l, tmp, addr + base_addr);
			if (errcode < 0)
				goto error;
			continue;
		}
		name = duplicate_str(tmp);
		if (!name) {
			errcode = -err_no_mem;
			goto error;
		}

		/* there was a label so now an address needs to
		 * be found.
		 */
		errcode = -err_label_addr;
		for (i += 1; i < t->n; i++) {
			int errcode_text;

			errcode_text = text_line(t, line, linelen, i);
			if (errcode_text < 0) {
				errcode = errcode_text;
				break;
			}
			if (sscanf(line, "%*d %" PRIx64 " %*x %*s", &addr)
			    == 1) {
				errcode = l_append(l, name, addr + base_addr);
				break;
			}
		}
		if (errcode == -err_label_addr)
			fprintf(stderr, "label '%s' has no address\n", name);
		free(name);
		if (errcode < 0)
			goto error;
	}

	return 0;

error:
	l_free(l->next);
	free(l->name);
	l->next = NULL;
	l->name = NULL;
	return errcode;
}
示例#27
0
/*
 * Initialize the static structure to zeros, then
 *  apply all the default values.
 */
static inline void init_resource(CONFIG *config, int type, RES_ITEM *items, int pass)
{
   memset(config->m_res_all, 0, config->m_res_all_size);
   res_all.hdr.rcode = type;
   res_all.hdr.refcnt = 1;

   /*
    * Set defaults in each item. We only set defaults in pass 1.
    */
   if (pass == 1) {
      int i;

      for (i = 0; items[i].name; i++) {
         Dmsg3(900, "Item=%s def=%s defval=%s\n", items[i].name,
               (items[i].flags & ITEM_DEFAULT) ? "yes" : "no",
               (items[i].default_value) ? items[i].default_value : "None");

         /*
          * Sanity check.
          *
          * Items with a default value but without the ITEM_DEFAULT flag set
          * are most of the time an indication of a programmers error.
          */
         if (items[i].default_value != NULL && !(items[i].flags & ITEM_DEFAULT)) {
            Pmsg1(000, _("Found config item %s which has default value but no ITEM_DEFAULT flag set\n"),
                  items[i].name);
            items[i].flags |= ITEM_DEFAULT;
         }

         if (items[i].flags & ITEM_DEFAULT && items[i].default_value != NULL) {
            /*
             * First try to handle the generic types.
             */
            if (items[i].handler == store_bit) {
               if (bstrcasecmp(items[i].default_value, "on")) {
                  *(uint32_t *)(items[i].value) |= items[i].code;
               } else if (bstrcasecmp(items[i].default_value, "off")) {
                  *(uint32_t *)(items[i].value) &= ~(items[i].code);
               }
            } else if (items[i].handler == store_bool) {
               if (bstrcasecmp(items[i].default_value, "yes") ||
                   bstrcasecmp(items[i].default_value, "true")) {
                  *(bool *)(items[i].value) = true;
               } else if (bstrcasecmp(items[i].default_value, "no") ||
                          bstrcasecmp(items[i].default_value, "false")) {
                  *(bool *)(items[i].value) = false;
               }
            } else if (items[i].handler == store_pint32 ||
                       items[i].handler == store_int32 ||
                       items[i].handler == store_size32) {
               *(uint32_t *)(items[i].value) = str_to_int32(items[i].default_value);
            } else if (items[i].handler == store_int64) {
               *(int64_t *)(items[i].value) = str_to_int64(items[i].default_value);
            } else if (items[i].handler == store_size64) {
               *(uint64_t *)(items[i].value) = str_to_uint64(items[i].default_value);
            } else if (items[i].handler == store_speed) {
               *(uint64_t *)(items[i].value) = str_to_uint64(items[i].default_value);
            } else if (items[i].handler == store_time) {
               *(utime_t *)(items[i].value) = str_to_int64(items[i].default_value);
            } else if (items[i].handler == store_strname ||
                       items[i].handler == store_str) {
               *items[i].value = bstrdup(items[i].default_value);
            } else if (items[i].handler == store_dir) {
               char pathname[MAXSTRING];

               bstrncpy(pathname, items[i].default_value, sizeof(pathname));
               if (pathname[0] != '|') {
                  do_shell_expansion(pathname, sizeof(pathname));
               }
               *items[i].value = bstrdup(pathname);
            } else if (items[i].handler == store_addresses) {
               init_default_addresses((dlist **)items[i].value, items[i].default_value);
            } else {
               /*
                * None of the generic types fired if there is a registered callback call that now.
                */
               if (config->m_init_res) {
                  config->m_init_res(&items[i]);
               }
            }
         }

         /*
          * If this triggers, take a look at lib/parse_conf.h
          */
         if (i >= MAX_RES_ITEMS) {
            Emsg1(M_ERROR_TERM, 0, _("Too many items in %s resource\n"), resources[type - r_first]);
         }
      }
   }
}
示例#28
0
static int bvfs_result_handler(void *ctx, int fields, char **row)
{
   UAContext *ua = (UAContext *)ctx;
   char *fileid=row[BVFS_FileId];
   char *lstat=row[BVFS_LStat];
   char *jobid=row[BVFS_JobId];

   char empty[] = "A A A A A A A A A A A A A A";
   char zero[] = "0";
   int32_t LinkFI = 0;

   /*
    * We need to deal with non existant path
    */
   if (!fileid || !is_a_number(fileid)) {
      lstat = empty;
      jobid = zero;
      fileid = zero;
   }

   Dmsg1(100, "type=%s\n", row[0]);
   if (bvfs_is_dir(row)) {
      char *path = bvfs_basename_dir(row[BVFS_Name]);

      ua->send->object_start();
      ua->send->object_key_value("Type", row[BVFS_Type]);
      ua->send->object_key_value("PathId", str_to_uint64(row[BVFS_PathId]), "%lld\t");
      ua->send->object_key_value("FilenameId", (uint64_t)0, "%lld\t");
      ua->send->object_key_value("FileId", str_to_uint64(fileid), "%lld\t");
      ua->send->object_key_value("JobId", str_to_uint64(jobid), "%lld\t");
      ua->send->object_key_value("lstat", lstat, "%s\t");
      ua->send->object_key_value("Name", path, "%s\n");
      ua->send->object_key_value("Fullpath", row[BVFS_Name]);
      bvfs_stat(ua, lstat, &LinkFI);
      ua->send->object_key_value("LinkFileIndex", LinkFI);
      ua->send->object_end();
  } else if (bvfs_is_version(row)) {
      ua->send->object_start();
      ua->send->object_key_value("Type", row[BVFS_Type]);
      ua->send->object_key_value("PathId", str_to_uint64(row[BVFS_PathId]), "%lld\t");
      ua->send->object_key_value("FilenameId", str_to_uint64(row[BVFS_FilenameId]), "%lld\t");
      ua->send->object_key_value("FileId", str_to_uint64(fileid), "%lld\t");
      ua->send->object_key_value("JobId", str_to_uint64(jobid), "%lld\t");
      ua->send->object_key_value("lstat", lstat, "%s\t");
      ua->send->object_key_value("MD5", row[BVFS_Md5], "%s\t");
      ua->send->object_key_value("VolumeName", row[BVFS_VolName], "%s\t");
      ua->send->object_key_value("VolumeInChanger", str_to_uint64(row[BVFS_VolInchanger]), "%lld\n");
      ua->send->object_end();
   } else if (bvfs_is_file(row)) {
      ua->send->object_start();
      ua->send->object_key_value("Type", row[BVFS_Type]);
      ua->send->object_key_value("PathId", str_to_uint64(row[BVFS_PathId]), "%lld\t");
      ua->send->object_key_value("FilenameId", str_to_uint64(row[BVFS_FilenameId]), "%lld\t");
      ua->send->object_key_value("FileId", str_to_uint64(fileid), "%lld\t");
      ua->send->object_key_value("JobId", str_to_uint64(jobid), "%lld\t");
      ua->send->object_key_value("lstat", lstat, "%s\t");
      ua->send->object_key_value("Name", row[BVFS_Name], "%s\n");
      bvfs_stat(ua, lstat, &LinkFI);
      ua->send->object_key_value("LinkFileIndex", LinkFI);
      ua->send->object_end();
   }

   return 0;
}
示例#29
0
/*
 * Find Available Media (Volume) for Pool
 *
 * Find a Volume for a given PoolId, MediaType, and Status.
 *
 * Returns: 0 on failure
 *          numrows on success
 */
int BDB::bdb_find_next_volume(JCR *jcr, int item, bool InChanger, MEDIA_DBR *mr)
{
   SQL_ROW row = NULL;
   int numrows;
   const char *order;
   char esc_type[MAX_ESCAPE_NAME_LENGTH];
   char esc_status[MAX_ESCAPE_NAME_LENGTH];
   char ed1[50];

   bdb_lock();
   bdb_escape_string(jcr, esc_type, mr->MediaType, strlen(mr->MediaType));
   bdb_escape_string(jcr, esc_status, mr->VolStatus, strlen(mr->VolStatus));

   if (item == -1) {       /* find oldest volume */
      /* Find oldest volume */
      Mmsg(cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
         "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
         "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
         "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
         "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
         "Enabled,LocationId,RecycleCount,InitialWrite,"
         "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,ActionOnPurge "
         "FROM Media WHERE PoolId=%s AND MediaType='%s' AND VolStatus IN ('Full',"
         "'Recycle','Purged','Used','Append') AND Enabled=1 "
         "ORDER BY LastWritten LIMIT 1",
         edit_int64(mr->PoolId, ed1), esc_type);
     item = 1;
   } else {
      POOL_MEM changer(PM_FNAME);
      POOL_MEM voltype(PM_FNAME);
      POOL_MEM exclude(PM_FNAME);
      /* Find next available volume */
      if (InChanger) {
         Mmsg(changer, " AND InChanger=1 AND StorageId=%s ",
                 edit_int64(mr->StorageId, ed1));
      }
      /* Volumes will be automatically excluded from the query, we just take the
       * first one of the list 
       */
      if (mr->exclude_list && *mr->exclude_list) {
         item = 1;
         Mmsg(exclude, " AND MediaId NOT IN (%s) ", mr->exclude_list);
      }
      if (strcmp(mr->VolStatus, "Recycle") == 0 ||
          strcmp(mr->VolStatus, "Purged") == 0) {
         order = "AND Recycle=1 ORDER BY LastWritten ASC,MediaId";  /* take oldest that can be recycled */
      } else {
         order = sql_media_order_most_recently_written[bdb_get_type_index()];    /* take most recently written */
      }
      Mmsg(cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
         "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
         "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
         "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
         "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
         "Enabled,LocationId,RecycleCount,InitialWrite,"
         "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,ActionOnPurge "
         "FROM Media WHERE PoolId=%s AND MediaType='%s' AND Enabled=1 "
         "AND VolStatus='%s' "
         "%s "
         "%s "
         "%s "
         "%s LIMIT %d",
         edit_int64(mr->PoolId, ed1), esc_type,
         esc_status,
         voltype.c_str(),
         changer.c_str(), exclude.c_str(), order, item);
   }
   Dmsg1(100, "fnextvol=%s\n", cmd);
   if (!QueryDB(jcr, cmd)) {
      bdb_unlock();
      return 0;
   }

   numrows = sql_num_rows();
   if (item > numrows || item < 1) {
      Dmsg2(050, "item=%d got=%d\n", item, numrows);
      Mmsg2(&errmsg, _("Request for Volume item %d greater than max %d or less than 1\n"),
         item, numrows);
      bdb_unlock();
      return 0;
   }

   /* Note, we previously seeked to the row using:
    *  sql_data_seek(item-1);
    * but this failed on PostgreSQL, so now we loop
    * over all the records.  This should not be too horrible since
    * the maximum Volumes we look at in any case is 20.
    */
   while (item-- > 0) {
      if ((row = sql_fetch_row()) == NULL) {
         Dmsg1(050, "Fail fetch item=%d\n", item+1);
         Mmsg1(&errmsg, _("No Volume record found for item %d.\n"), item);
         sql_free_result();
         bdb_unlock();
         return 0;
      }
   }

   /* Return fields in Media Record */
   mr->MediaId = str_to_int64(row[0]);
   bstrncpy(mr->VolumeName, row[1]!=NULL?row[1]:"", sizeof(mr->VolumeName));
   mr->VolJobs = str_to_int64(row[2]);
   mr->VolFiles = str_to_int64(row[3]);
   mr->VolBlocks = str_to_int64(row[4]);
   mr->VolBytes = str_to_uint64(row[5]);
   mr->VolMounts = str_to_int64(row[6]);
   mr->VolErrors = str_to_int64(row[7]);
   mr->VolWrites = str_to_int64(row[8]);
   mr->MaxVolBytes = str_to_uint64(row[9]);
   mr->VolCapacityBytes = str_to_uint64(row[10]);
   bstrncpy(mr->MediaType, row[11]!=NULL?row[11]:"", sizeof(mr->MediaType));
   bstrncpy(mr->VolStatus, row[12]!=NULL?row[12]:"", sizeof(mr->VolStatus));
   mr->PoolId = str_to_int64(row[13]);
   mr->VolRetention = str_to_uint64(row[14]);
   mr->VolUseDuration = str_to_uint64(row[15]);
   mr->MaxVolJobs = str_to_int64(row[16]);
   mr->MaxVolFiles = str_to_int64(row[17]);
   mr->Recycle = str_to_int64(row[18]);
   mr->Slot = str_to_int64(row[19]);
   bstrncpy(mr->cFirstWritten, row[20]!=NULL?row[20]:"", sizeof(mr->cFirstWritten));
   mr->FirstWritten = (time_t)str_to_utime(mr->cFirstWritten);
   bstrncpy(mr->cLastWritten, row[21]!=NULL?row[21]:"", sizeof(mr->cLastWritten));
   mr->LastWritten = (time_t)str_to_utime(mr->cLastWritten);
   mr->InChanger = str_to_uint64(row[22]);
   mr->EndFile = str_to_uint64(row[23]);
   mr->EndBlock = str_to_uint64(row[24]);
   mr->VolType = str_to_int64(row[25]);   /* formerly VolParts */
   mr->LabelType = str_to_int64(row[26]);
   bstrncpy(mr->cLabelDate, row[27]!=NULL?row[27]:"", sizeof(mr->cLabelDate));
   mr->LabelDate = (time_t)str_to_utime(mr->cLabelDate);
   mr->StorageId = str_to_int64(row[28]);
   mr->Enabled = str_to_int64(row[29]);
   mr->LocationId = str_to_int64(row[30]);
   mr->RecycleCount = str_to_int64(row[31]);
   bstrncpy(mr->cInitialWrite, row[32]!=NULL?row[32]:"", sizeof(mr->cInitialWrite));
   mr->InitialWrite = (time_t)str_to_utime(mr->cInitialWrite);
   mr->ScratchPoolId = str_to_int64(row[33]);
   mr->RecyclePoolId = str_to_int64(row[34]);
   mr->VolReadTime = str_to_int64(row[35]);
   mr->VolWriteTime = str_to_int64(row[36]);
   mr->ActionOnPurge = str_to_int64(row[37]);

   sql_free_result();

   bdb_unlock();
   Dmsg1(050, "Rtn numrows=%d\n", numrows);
   return numrows;
}
示例#30
0
文件: config.c 项目: BzzzBoy/gethooks
/* init_global_config_store()
Initialize the global configuration store by parsing command line arguments.

This function must only be called from the main thread.
For now there is only one configuration store implemented and it's a global store (G->config).
'G->config' depends on the global program (G->prog) store.
*/
void init_global_config_store( void )
{
	int i = 0;
	unsigned arf = 0;
	char *debugstr = NULL;
	
	FAIL_IF( !G );   // The global store must exist.
	
	FAIL_IF( G->config->init_time );   // Fail if this store has already been initialized.
	
	FAIL_IF( !G->prog->init_time );   // The program store must be initialized.
	
	FAIL_IF( GetCurrentThreadId() != G->prog->dwMainThreadId );   // main thread only
	
	
	debugstr = getenv( "GETHOOKS_DEBUG" );
	if( debugstr && ( debugstr[ 0 ] == '1' ) && !debugstr[ 1 ] )
		G->config->flags |= CFG_DEBUG;
	
	G->config->polling = POLLING_DEFAULT;
	G->config->verbose = VERBOSE_DEFAULT;
	G->config->max_threads = MAX_THREADS_DEFAULT;
	
	/* parse command line arguments */
	i = 0;
	while( arf != END )
	{
		if( arf != OPT ) /* attempt to get an option from the command line arguments */
			arf = get_next_arg( &i, OPT );
		
		if( arf != OPT )
			continue;
		
		/* option found */
		
		switch( G->prog->argv[ i ][ 1 ] )
		{
			case '?':
			case 'h':
			case 'H':
			{
				/* show help */
				print_usage_and_exit();
			}
			
			
			/**
			desktop include option
			*/
			case 'd':
			case 'D':
			{
				G->config->desklist->type = LIST_INCLUDE_DESK;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				while( arf == OPTARG ) /* option argument found */
				{
					WCHAR *name = NULL;
					
					
					/* make the desktop name as a wide character string */
					if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
					{
						MSG_FATAL( "get_wstr_from_mbstr() failed." );
						printf( "desktop: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* append to the linked list */
					if( !add_list_item( G->config->desklist, 0, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "desktop: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/** 
			monitor option
			*/
			case 'm':
			case 'M':
			{
				if( G->config->polling != POLLING_DEFAULT )
				{
					MSG_FATAL( "Option 'm': this option has already been specified." );
					printf( "sec: %d\n", G->config->polling );
					exit( 1 );
				}
				
				G->config->polling = POLLING_ENABLED_DEFAULT;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				/* option argument found */
				
				if( !str_to_int( &G->config->polling, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "Option 'm': the string is not an integer representation." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				if( G->config->polling == 0 )
				{
					MSG_WARNING( "Option 'm': an interval of 0 uses too much CPU time." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
				}
				
				if( G->config->polling > 86400 ) // number of seconds in a day
				{
					MSG_WARNING( "Option 'm': more seconds than in a day (86400)." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
				}
				
				if( G->config->polling < POLLING_MIN )
				{
					MSG_FATAL( "Option 'm': less seconds than the minimum allowed." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					printf( "POLLING_MIN: %d\n", POLLING_MIN );
					exit( 1 );
				}
				else if( G->config->polling > POLLING_MAX )
				{
					MSG_FATAL( "Option 'm': more seconds than the maximum allowed." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					printf( "POLLING_MAX: %d\n", POLLING_MAX );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			hook include/exclude options
			i: include list for hooks
			x: exclude list for hooks
			*/
			case 'i':
			case 'I':
			{
				if( G->config->hooklist->type == LIST_EXCLUDE_HOOK )
				{
					MSG_FATAL( "Options 'i' and 'x' are mutually exclusive." );
					exit( 1 );
				}
				
				G->config->hooklist->type = LIST_INCLUDE_HOOK;
			}
			/* pass through to the exclude code. 
			the exclude code can handle either type of list, include or exclude.
			*/
			case 'x':
			case 'X':
			{
				if( G->config->hooklist->type != LIST_INCLUDE_HOOK )
				{
					G->config->hooklist->type = LIST_EXCLUDE_HOOK;
				}
				else if( ( G->prog->argv[ i ][ 1 ] == 'x' ) || ( G->prog->argv[ i ][ 1 ] == 'X' ) )
				{
					MSG_FATAL( "Options 'i' and 'x' are mutually exclusive." );
					exit( 1 );
				}
				
				/* the 'i' or 'x' option requires at least one associated argument (optarg).
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				while( arf == OPTARG ) /* option argument found */
				{
					__int64 id = 0;
					WCHAR *name = NULL;
					
					/* if the string is not an integer then it's a hook name not an id */
					if( !str_to_int64( &id, G->prog->argv[ i ] ) )
					{
						id = 0;
						
						/* make the hook name as a wide character string */
						if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
						{
							MSG_FATAL( "get_wstr_from_mbstr() failed." );
							printf( "hook: %s\n", G->prog->argv[ i ] );
							exit( 1 );
						}
						
						_wcsupr( name ); /* convert hook name to uppercase */
					}
					
					/* append to the linked list */
					if( !add_list_item( G->config->hooklist, id, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "hook: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/**
			program include/exclude options
			p: include list for programs
			r: exclude list for programs
			*/
			case 'p':
			case 'P':
			{
				if( G->config->proglist->type == LIST_EXCLUDE_PROG )
				{
					MSG_FATAL( "Options 'p' and 'r' are mutually exclusive." );
					exit( 1 );
				}
				
				G->config->proglist->type = LIST_INCLUDE_PROG;
			}
			/* pass through to the exclude code. 
			the exclude code can handle either type of list, include or exclude.
			*/
			case 'r':
			case 'R':
			{
				if( G->config->proglist->type != LIST_INCLUDE_PROG )
				{
					G->config->proglist->type = LIST_EXCLUDE_PROG;
				}
				else if( ( G->prog->argv[ i ][ 1 ] == 'r' ) || ( G->prog->argv[ i ][ 1 ] == 'R' ) )
				{
					MSG_FATAL( "Options 'p' and 'r' are mutually exclusive." );
					exit( 1 );
				}
				
				
				/* the 'p' or 'r' option requires at least one associated argument (optarg).
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				while( arf == OPTARG ) /* option argument found */
				{
					__int64 id = 0;
					WCHAR *name = NULL;
					const char *p = G->prog->argv[ i ];
					
					
					/* a colon is used as the escape character. 
					if the first character is a colon then a program name 
					is specified, not a PID/TID. this is only necessary 
					in cases where a program name can be mistaken by 
					the parser for an option or a PID/TID.
					*/
					if( *p == ':' )
						++p;
					
					/* if the first character is a colon, or the string is not an integer, 
					or it is and the integer is negative, then assume program name
					*/
					if( ( p != G->prog->argv[ i ] ) 
						|| ( str_to_int64( &id, G->prog->argv[ i ] ) != NUM_POS )
					)
					{
						/* make the program name as a wide character string */
						if( !get_wstr_from_mbstr( &name, p ) )
						{
							MSG_FATAL( "get_wstr_from_mbstr() failed." );
							printf( "prog: %s\n", G->prog->argv[ i ] );
							exit( 1 );
						}
						
						//_wcslwr( name ); /* convert program name to lowercase */
						
						/* program name and id are mutually exclusive. 
						elsewhere in the code if a list item's name != NULL 
						then its id is ignored.
						*/
					}
					/* else the id is valid and name remains NULL*/
					
					/* append to the linked list */
					if( !add_list_item( G->config->proglist, id, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "prog: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/** 
			verbosity option
			*/
			case 'v':
			case 'V':
			{
				if( G->config->verbose != VERBOSE_DEFAULT )
				{
					MSG_FATAL( "Option 'v': this option has already been specified." );
					printf( "verbosity level: %d\n", G->config->verbose );
					exit( 1 );
				}
				
				G->config->verbose = VERBOSE_ENABLED_DEFAULT;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				/* option argument found */
				
				if( !str_to_int( &G->config->verbose, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "Option 'v': the string is not an integer representation." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				if( G->config->verbose < VERBOSE_MIN )
				{
					MSG_FATAL( "Option 'v': less verbosity than the minimum allowed." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					printf( "VERBOSE_MIN: %d\n", VERBOSE_MIN );
					exit( 1 );
				}
				else if( G->config->verbose > VERBOSE_MAX )
				{
					MSG_FATAL( "Option 'v': more verbosity than the maximum allowed." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					printf( "VERBOSE_MAX: %d\n", VERBOSE_MAX );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			threads option (advanced)
			*/
			case 't':
			case 'T':
			{
				if( G->config->max_threads != MAX_THREADS_DEFAULT )
				{
					MSG_FATAL( "Option 't': this option has already been specified." );
					printf( "max threads: %u\n", G->config->max_threads );
					exit( 1 );
				}
				
				/* this option must have an associated argument (optarg). 
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				/* option argument found */
				
				/* if the string is not a positive integer representation > 0 */
				if( ( str_to_uint( &G->config->max_threads, G->prog->argv[ i ] ) != NUM_POS ) 
					|| ( G->config->max_threads <= 0 ) 
				)
				{
					MSG_FATAL( "Option 't': maximum number of threads invalid." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			test mode include option (advanced)
			*/
			case 'z':
			case 'Z':
			{
				unsigned __int64 id = 0;
				WCHAR *name = NULL;
				
				
				G->config->testlist->type = LIST_INCLUDE_TEST;
				
				/* the 'z' option requires one associated argument (optarg), and a second which is 
				optional.
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				if( arf != OPTARG )
				{
					print_testmode_usage();
					exit( 1 );
				}
				
				/* make the test name as a wide character string */
				if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "get_wstr_from_mbstr() failed." );
					printf( "name: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				arf = get_next_arg( &i, OPT | OPTARG ); // get the second optarg, which is optional
				
				/* at least one option argument (optarg) was found */
				
				/* if a second optarg was found it's the id. the value of id will be UI64_MAX if 
				the conversion fails or there's no second optarg.
				*/
				if( arf == OPTARG )
					str_to_uint64( &id, G->prog->argv[ i ] );
				else
					id = UI64_MAX;
				
				/* append to the linked list */
				if( !add_list_item( G->config->testlist, (__int64)id, name ) )
				{
					MSG_FATAL( "add_list_item() failed." );
					printf( "test id: 0x%I64X\n", id );
					printf( "test name: %ls\n", name );
					exit( 1 );
				}
				
				/* if add_list_item() was successful then it made a duplicate of the 
				wide string pointed to by name. in any case name should now be freed.
				*/
				free( name );
				name = NULL;
				
				continue;
			}
			
			
			
			/**
			option to ignore internal hooks (advanced)
			*/
			case 'e':
			case 'E':
			{
				G->config->flags |= CFG_IGNORE_INTERNAL_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore known hooks (advanced)
			*/
			case 'u':
			case 'U':
			{
				G->config->flags |= CFG_IGNORE_KNOWN_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore targeted hooks (advanced)
			*/
			case 'g':
			case 'G':
			{
				G->config->flags |= CFG_IGNORE_TARGETED_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore failed NtQuerySystemInformation() calls (advanced)
			*/
			case 'f':
			case 'F':
			{
				G->config->flags |= CFG_IGNORE_FAILED_QUERIES;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore hook lock count changes (advanced)
			*/
			case 'c':
			case 'C':
			{
				G->config->flags |= CFG_IGNORE_LOCK_COUNTS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to go completely passive (advanced)
			*/
			case 'y':
			case 'Y':
			{
				G->config->flags |= CFG_COMPLETELY_PASSIVE;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			default:
			{
				MSG_FATAL( "Unknown option." );
				printf( "OPT: %s\n", G->prog->argv[ i ] );
				exit( 1 );
			}
		}
	}
	
	
	
	if( ( G->config->proglist->type == LIST_INCLUDE_PROG )
		|| ( G->config->proglist->type == LIST_EXCLUDE_PROG )
	)
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->proglist->init_time );
	
	if( ( G->config->hooklist->type == LIST_INCLUDE_HOOK )
		|| ( G->config->hooklist->type == LIST_EXCLUDE_HOOK )
	)
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->hooklist->init_time );
	
	if( ( G->config->desklist->type == LIST_INCLUDE_DESK ) )
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->desklist->init_time );
	
	if( ( G->config->testlist->type == LIST_INCLUDE_TEST ) )
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->testlist->init_time );
	
	
	/* G->config has been initialized */
	GetSystemTimeAsFileTime( (FILETIME *)&G->config->init_time );
	return;
}