コード例 #1
0
ファイル: localed.c プロジェクト: vlajos/systemd
static int read_next_mapping(FILE *f, unsigned *n, char ***a) {
        assert(f);
        assert(n);
        assert(a);

        for (;;) {
                char line[LINE_MAX];
                char *l, **b;
                int r;

                errno = 0;
                if (!fgets(line, sizeof(line), f)) {

                        if (ferror(f))
                                return errno ? -errno : -EIO;

                        return 0;
                }

                (*n) ++;

                l = strstrip(line);
                if (l[0] == 0 || l[0] == '#')
                        continue;

                r = strv_split_quoted(&b, l, false);
                if (r < 0)
                        return r;

                if (strv_length(b) < 5) {
                        log_error("Invalid line "SYSTEMD_KBD_MODEL_MAP":%u, ignoring.", *n);
                        strv_free(b);
                        continue;

                }

                *a = b;
                return 1;
        }
}
コード例 #2
0
static int apply_file(struct kmod_ctx *ctx, const char *path, bool ignore_enoent) {
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(ctx);
        assert(path);

        r = search_and_fopen_nulstr(path, "re", NULL, conf_file_dirs, &f);
        if (r < 0) {
                if (ignore_enoent && r == -ENOENT)
                        return 0;

                return log_error_errno(r, "Failed to open %s, ignoring: %m", path);
        }

        log_debug("apply: %s", path);
        for (;;) {
                char line[LINE_MAX], *l;
                int k;

                if (!fgets(line, sizeof(line), f)) {
                        if (feof(f))
                                break;

                        return log_error_errno(errno, "Failed to read file '%s', ignoring: %m", path);
                }

                l = strstrip(line);
                if (!*l)
                        continue;
                if (strchr(COMMENTS "\n", *l))
                        continue;

                k = load_module(ctx, l);
                if (k < 0 && r == 0)
                        r = k;
        }

        return r;
}
コード例 #3
0
ファイル: binfmt.c プロジェクト: rowhit/systemd
static int apply_file(const char *path, bool ignore_enoent) {
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(path);

        r = search_and_fopen_nulstr(path, "re", NULL, conf_file_dirs, &f);
        if (r < 0) {
                if (ignore_enoent && r == -ENOENT)
                        return 0;

                return log_error_errno(r, "Failed to open file '%s', ignoring: %m", path);
        }

        log_debug("apply: %s", path);
        for (;;) {
                char l[LINE_MAX], *p;
                int k;

                if (!fgets(l, sizeof(l), f)) {
                        if (feof(f))
                                break;

                        log_error_errno(errno, "Failed to read file '%s', ignoring: %m", path);
                        return -errno;
                }

                p = strstrip(l);
                if (!*p)
                        continue;
                if (strchr(COMMENTS "\n", *p))
                        continue;

                k = apply_rule(p);
                if (k < 0 && r == 0)
                        r = k;
        }

        return r;
}
コード例 #4
0
ファイル: envoy-exec.c プロジェクト: blueyed/envoy
static char *extract_binary(char *path)
{
    struct stat st;
    char *memblock, *command = NULL;

    _cleanup_close_ int fd = open(path, O_RDONLY);
    if (fd < 0)
        return command;

    if (fstat(fd, &st) < 0)
        err(EXIT_FAILURE, "failed to stat %s", path);

    memblock = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);
    madvise(memblock, st.st_size, MADV_WILLNEED | MADV_SEQUENTIAL);

    if (memblock[0] != '#' || memblock[1] != '!')
        goto error;

    memblock += strcspn(memblock, "\n");
    while (*memblock++ == '\n') {
        memblock += strspn(memblock, "#\t ");
        if (memblock[0] == '\0')
            break;
        else if (memblock[0] == '\n')
            continue;

        size_t eol = strcspn(memblock, "\n#");
        if (memblock[0] == '#') {
            memblock += eol;
            continue;
        } else {
            command = strndup(memblock, eol);
            goto error;
        }
    }

error:
    memblock != MAP_FAILED ? munmap(memblock, st.st_size) : 0;
    return strstrip(command);
}
コード例 #5
0
ファイル: rna.c プロジェクト: process1183/rosalind
int32_t main(int32_t argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <dataset file>\n", argv[0]);
        return 1;
    }

    FILE *inp_fp = fopen(argv[1], "r");
    if (inp_fp == NULL) {
        char *err_msg;
        asprintf(&err_msg, "Failed to open \"%s\"", argv[1]);
        perror(err_msg);
        free(err_msg);
        return 1;
    }

    char *line_ptr = NULL;
    size_t line_len = 0;
    ssize_t read_len = 0;

    read_len = getline(&line_ptr, &line_len, inp_fp);
    fclose(inp_fp);

    if (read_len == -1) {
        char *err_msg;
        asprintf(&err_msg, "Failed to get line from \"%s\"", argv[1]);
        perror(err_msg);
        free(err_msg);
        return 1;
    }

    char *dna_str = strstrip(line_ptr);
    char *rna_str = transcribe_dna_to_rna(dna_str);

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

    free(line_ptr);
    free(rna_str);
}
コード例 #6
0
static int set_param_str(const char *val, const struct kernel_param *kp)
{
	action_fn  fn = (action_fn) kp->arg;
	int        rv = 0;
	char       valcp[16];
	char       *s;

	strncpy(valcp, val, 16);
	valcp[15] = '\0';

	s = strstrip(valcp);

	rv = fn(s, NULL);
	if (rv)
		goto out;

	check_parms();
	if (watchdog_user)
		rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);

 out:
	return rv;
}
コード例 #7
0
static ssize_t tcp_cgroup_write(struct kernfs_open_file *of,
				char *buf, size_t nbytes, loff_t off)
{
	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
	unsigned long long val;
	int ret = 0;

	buf = strstrip(buf);

	switch (of_cft(of)->private) {
	case RES_LIMIT:
		/* see memcontrol.c */
		ret = res_counter_memparse_write_strategy(buf, &val);
		if (ret)
			break;
		ret = tcp_update_limit(memcg, val);
		break;
	default:
		ret = -EINVAL;
		break;
	}
	return ret ?: nbytes;
}
コード例 #8
0
/***************************************************
**
**	The first digit control component Y output DAC number
**	The 2nd digit control component U output DAC number
**	The 3rd digit control component V output DAC number
**	The 4th digit control composite CVBS output DAC number
**	The 5th digit control s-video Luma output DAC number
**	The 6th digit control s-video chroma output DAC number
** 	examble :
**		echo  120120 > /sys/class/display/vdac_setting
**		the first digit from the left side .	
******************************************************/
static void  parse_vdac_setting(char *para) 
{
	int  i;
	char  *pt=strstrip(para);
	int len=strlen(pt);
	u32  vdac_sequence=get_current_vdac_setting();
	
	amlog_mask_level(LOG_MASK_PARA,LOG_LEVEL_LOW,"origin vdac setting:0x%x,strlen:%d\n",vdac_sequence,len);
	if(len!=6)
	{
		amlog_mask_level(LOG_MASK_PARA,LOG_LEVEL_HIGH,"can't parse vdac settings\n");
		return ;
	}
	vdac_sequence=0;
	for(i=0;i<6;i++)
	{
		vdac_sequence<<=4;
		vdac_sequence|=*pt -'0';
		pt++;
	}
	amlog_mask_level(LOG_MASK_PARA,LOG_LEVEL_LOW,"current vdac setting:0x%x\n",vdac_sequence);
	
	change_vdac_setting(vdac_sequence,get_current_vmode());
}
コード例 #9
0
ファイル: hostname-util.c プロジェクト: Werkov/systemd
int read_etc_hostname_stream(FILE *f, char **ret) {
        int r;

        assert(f);
        assert(ret);

        for (;;) {
                _cleanup_free_ char *line = NULL;
                char *p;

                r = read_line(f, LONG_LINE_MAX, &line);
                if (r < 0)
                        return r;
                if (r == 0) /* EOF without any hostname? the file is empty, let's treat that exactly like no file at all: ENOENT */
                        return -ENOENT;

                p = strstrip(line);

                /* File may have empty lines or comments, ignore them */
                if (!IN_SET(*p, '\0', '#')) {
                        char *copy;

                        hostname_cleanup(p); /* normalize the hostname */

                        if (!hostname_is_valid(p, true)) /* check that the hostname we return is valid */
                                return -EBADMSG;

                        copy = strdup(p);
                        if (!copy)
                                return -ENOMEM;

                        *ret = copy;
                        return 0;
                }
        }
}
コード例 #10
0
ファイル: keymap-util.c プロジェクト: halfline/systemd
int x11_read_data(Context *c, sd_bus_message *m) {
        _cleanup_fclose_ FILE *f = NULL;
        bool in_section = false;
        char line[LINE_MAX];
        struct stat st;
        usec_t t;
        int r;

        /* Do not try to re-read the file within single bus operation. */
        if (m) {
                if (m == c->x11_cache)
                        return 0;

                sd_bus_message_unref(c->x11_cache);
                c->x11_cache = sd_bus_message_ref(m);
        }

        if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st) < 0) {
                if (errno != ENOENT)
                        return -errno;

                c->x11_mtime = USEC_INFINITY;
                context_free_x11(c);
                return 0;
        }

        /* If mtime is not changed, then we do not need to re-read */
        t = timespec_load(&st.st_mtim);
        if (c->x11_mtime != USEC_INFINITY && t == c->x11_mtime)
                return 0;

        c->x11_mtime = t;
        context_free_x11(c);

        f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
        if (!f)
                return -errno;

        while (fgets(line, sizeof(line), f)) {
                char *l;

                char_array_0(line);
                l = strstrip(line);

                if (IN_SET(l[0], 0, '#'))
                        continue;

                if (in_section && first_word(l, "Option")) {
                        _cleanup_strv_free_ char **a = NULL;

                        r = strv_split_extract(&a, l, WHITESPACE, EXTRACT_QUOTES);
                        if (r < 0)
                                return r;

                        if (strv_length(a) == 3) {
                                char **p = NULL;

                                if (streq(a[1], "XkbLayout"))
                                        p = &c->x11_layout;
                                else if (streq(a[1], "XkbModel"))
                                        p = &c->x11_model;
                                else if (streq(a[1], "XkbVariant"))
                                        p = &c->x11_variant;
                                else if (streq(a[1], "XkbOptions"))
                                        p = &c->x11_options;

                                if (p) {
                                        free_and_replace(*p, a[2]);
                                }
                        }

                } else if (!in_section && first_word(l, "Section")) {
                        _cleanup_strv_free_ char **a = NULL;

                        r = strv_split_extract(&a, l, WHITESPACE, EXTRACT_QUOTES);
                        if (r < 0)
                                return -ENOMEM;

                        if (strv_length(a) == 2 && streq(a[1], "InputClass"))
                                in_section = true;

                } else if (in_section && first_word(l, "EndSection"))
                        in_section = false;
        }

        return 0;
}
コード例 #11
0
ファイル: cgtop.c プロジェクト: g33s3/systemmd
static int process(const char *controller, const char *path, Hashmap *a, Hashmap *b, unsigned iteration) {
        Group *g;
        int r;
        FILE *f = NULL;
        pid_t pid;
        unsigned n;

        assert(controller);
        assert(path);
        assert(a);

        g = hashmap_get(a, path);
        if (!g) {
                g = hashmap_get(b, path);
                if (!g) {
                        g = new0(Group, 1);
                        if (!g)
                                return -ENOMEM;

                        g->path = strdup(path);
                        if (!g->path) {
                                group_free(g);
                                return -ENOMEM;
                        }

                        r = hashmap_put(a, g->path, g);
                        if (r < 0) {
                                group_free(g);
                                return r;
                        }
                } else {
                        assert_se(hashmap_move_one(a, b, path) == 0);
                        g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false;
                }
        }

        /* Regardless which controller, let's find the maximum number
         * of processes in any of it */

        r = cg_enumerate_processes(controller, path, &f);
        if (r < 0)
                return r;

        n = 0;
        while (cg_read_pid(f, &pid) > 0)
                n++;
        fclose(f);

        if (n > 0) {
                if (g->n_tasks_valid)
                        g->n_tasks = MAX(g->n_tasks, n);
                else
                        g->n_tasks = n;

                g->n_tasks_valid = true;
        }

        if (streq(controller, "cpuacct")) {
                uint64_t new_usage;
                char *p, *v;
                struct timespec ts;

                r = cg_get_path(controller, path, "cpuacct.usage", &p);
                if (r < 0)
                        return r;

                r = read_one_line_file(p, &v);
                free(p);
                if (r < 0)
                        return r;

                r = safe_atou64(v, &new_usage);
                free(v);
                if (r < 0)
                        return r;

                assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);

                if (g->cpu_iteration == iteration - 1) {
                        uint64_t x, y;

                        x = ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec) -
                                ((uint64_t) g->cpu_timestamp.tv_sec * 1000000000ULL + (uint64_t) g->cpu_timestamp.tv_nsec);

                        y = new_usage - g->cpu_usage;

                        if (y > 0) {
                                g->cpu_fraction = (double) y / (double) x;
                                g->cpu_valid = true;
                        }
                }

                g->cpu_usage = new_usage;
                g->cpu_timestamp = ts;
                g->cpu_iteration = iteration;

        } else if (streq(controller, "memory")) {
                char *p, *v;

                r = cg_get_path(controller, path, "memory.usage_in_bytes", &p);
                if (r < 0)
                        return r;

                r = read_one_line_file(p, &v);
                free(p);
                if (r < 0)
                        return r;

                r = safe_atou64(v, &g->memory);
                free(v);
                if (r < 0)
                        return r;

                if (g->memory > 0)
                        g->memory_valid = true;

        } else if (streq(controller, "blkio")) {
                char *p;
                uint64_t wr = 0, rd = 0;
                struct timespec ts;

                r = cg_get_path(controller, path, "blkio.io_service_bytes", &p);
                if (r < 0)
                        return r;

                f = fopen(p, "re");
                free(p);

                if (!f)
                        return -errno;

                for (;;) {
                        char line[LINE_MAX], *l;
                        uint64_t k, *q;

                        if (!fgets(line, sizeof(line), f))
                                break;

                        l = strstrip(line);
                        l += strcspn(l, WHITESPACE);
                        l += strspn(l, WHITESPACE);

                        if (first_word(l, "Read")) {
                                l += 4;
                                q = &rd;
                        } else if (first_word(l, "Write")) {
                                l += 5;
                                q = &wr;
                        } else
                                continue;

                        l += strspn(l, WHITESPACE);
                        r = safe_atou64(l, &k);
                        if (r < 0)
                                continue;

                        *q += k;
                }

                fclose(f);

                assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);

                if (g->io_iteration == iteration - 1) {
                        uint64_t x, yr, yw;

                        x = ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec) -
                                ((uint64_t) g->io_timestamp.tv_sec * 1000000000ULL + (uint64_t) g->io_timestamp.tv_nsec);

                        yr = rd - g->io_input;
                        yw = wr - g->io_output;

                        if (yr > 0 || yw > 0) {
                                g->io_input_bps = (yr * 1000000000ULL) / x;
                                g->io_output_bps = (yw * 1000000000ULL) / x;
                                g->io_valid = true;

                        }
                }

                g->io_input = rd;
                g->io_output = wr;
                g->io_timestamp = ts;
                g->io_iteration = iteration;
        }

        return 0;
}
コード例 #12
0
ファイル: localed.c プロジェクト: MOBO-OSS/systemd-relative
static int x11_read_data(Context *c) {
        FILE *f;
        char line[LINE_MAX];
        bool in_section = false;

        context_free_x11(c);

        f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
        if (!f)
                return errno == ENOENT ? 0 : -errno;

        while (fgets(line, sizeof(line), f)) {
                char *l;

                char_array_0(line);
                l = strstrip(line);

                if (l[0] == 0 || l[0] == '#')
                        continue;

                if (in_section && first_word(l, "Option")) {
                        char **a;

                        a = strv_split_quoted(l);
                        if (!a) {
                                fclose(f);
                                return -ENOMEM;
                        }

                        if (strv_length(a) == 3) {
                                if (streq(a[1], "XkbLayout")) {
                                        free_and_replace(&c->x11_layout, a[2]);
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbModel")) {
                                        free_and_replace(&c->x11_model, a[2]);
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbVariant")) {
                                        free_and_replace(&c->x11_variant, a[2]);
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbOptions")) {
                                        free_and_replace(&c->x11_options, a[2]);
                                        a[2] = NULL;
                                }
                        }

                        strv_free(a);

                } else if (!in_section && first_word(l, "Section")) {
                        char **a;

                        a = strv_split_quoted(l);
                        if (!a) {
                                fclose(f);
                                return -ENOMEM;
                        }

                        if (strv_length(a) == 2 && streq(a[1], "InputClass"))
                                in_section = true;

                        strv_free(a);
                } else if (in_section && first_word(l, "EndSection"))
                        in_section = false;
        }

        fclose(f);

        return 0;
}
コード例 #13
0
static play_tree_t*
parse_smil(play_tree_parser_t* p) {
    int entrymode=0;
    char* line,source[512],*pos,*s_start,*s_end,*src_line;
    play_tree_t *list = NULL, *entry = NULL, *last_entry = NULL;
    int is_rmsmil = 0;
    unsigned int npkt, ttlpkt;

    mp_msg(MSGT_PLAYTREE,MSGL_V,"Trying smil playlist...\n");

    // Check if smil
    while((line = play_tree_parser_get_line(p)) != NULL) {
        strstrip(line);
        if(line[0] == '\0') // Ignore empties
            continue;
        if (strncasecmp(line,"<?xml",5)==0) // smil in xml
            continue;
        if (strncasecmp(line,"<!DOCTYPE smil",13)==0) // smil in xml
            continue;
        if (strncasecmp(line,"<smil",5)==0 || strncasecmp(line,"<?wpl",5)==0 ||
                strncasecmp(line,"(smil-document",14)==0)
            break; // smil header found
        else
            return NULL; //line not smil exit
    }

    if (!line) return NULL;
    mp_msg(MSGT_PLAYTREE,MSGL_V,"Detected smil playlist format\n");
    play_tree_parser_stop_keeping(p);

    if (strncasecmp(line,"(smil-document",14)==0) {
        mp_msg(MSGT_PLAYTREE,MSGL_V,"Special smil-over-realrtsp playlist header\n");
        is_rmsmil = 1;
        if (sscanf(line, "(smil-document (ver 1.0)(npkt %u)(ttlpkt %u", &npkt, &ttlpkt) != 2) {
            mp_msg(MSGT_PLAYTREE,MSGL_WARN,"smil-over-realrtsp: header parsing failure, assuming single packet.\n");
            npkt = ttlpkt = 1;
        }
        if (ttlpkt == 0 || npkt > ttlpkt) {
            mp_msg(MSGT_PLAYTREE,MSGL_WARN,"smil-over-realrtsp: bad packet counters (npkk = %u, ttlpkt = %u), assuming single packet.\n",
                   npkt, ttlpkt);
            npkt = ttlpkt = 1;
        }
    }

    //Get entries from smil
    src_line = line;
    line = NULL;
    do {
        strstrip(src_line);
        if (line) {
            free(line);
            line = NULL;
        }
        /* If we're parsing smil over realrtsp and this is not the last packet and
         * this is the last line in the packet (terminating with ") ) we must get
         * the next line, strip the header, and concatenate it to the current line.
         */
        if (is_rmsmil && npkt != ttlpkt && strstr(src_line,"\")")) {
            char *payload;

            line = strdup(src_line);
            if(!(src_line = play_tree_parser_get_line(p))) {
                mp_msg(MSGT_PLAYTREE,MSGL_WARN,"smil-over-realrtsp: can't get line from packet %u/%u.\n", npkt, ttlpkt);
                break;
            }
            strstrip(src_line);
            // Skip header, packet starts after "
            if(!(payload = strchr(src_line,'\"'))) {
                mp_msg(MSGT_PLAYTREE,MSGL_WARN,"smil-over-realrtsp: can't find start of packet, using complete line.\n");
                payload = src_line;
            } else
                payload++;
            // Skip ") at the end of the last line from the current packet
            line[strlen(line)-2] = 0;
            line = realloc(line, strlen(line)+strlen(payload)+1);
            strcat (line, payload);
            npkt++;
        } else
            line = strdup(src_line);
        /* Unescape \" to " for smil-over-rtsp */
        if (is_rmsmil && line[0] != '\0') {
            int i, j;

            for (i = 0; i < strlen(line); i++)
                if (line[i] == '\\' && line[i+1] == '"')
                    for (j = i; line[j]; j++)
                        line[j] = line[j+1];
        }
        pos = line;
        while (pos) {
            if (!entrymode) { // all entries filled so far
                while ((pos=strchr(pos, '<'))) {
                    if (strncasecmp(pos,"<video",6)==0  || strncasecmp(pos,"<audio",6)==0 || strncasecmp(pos,"<media",6)==0) {
                        entrymode=1;
                        break; // Got a valid tag, exit '<' search loop
                    }
                    pos++;
                }
            }
            if (entrymode) { //Entry found but not yet filled
                pos = strstr(pos,"src=");   // Is source present on this line
                if (pos != NULL) {
                    entrymode=0;
                    if (pos[4] != '"' && pos[4] != '\'') {
                        mp_msg(MSGT_PLAYTREE,MSGL_V,"Unknown delimiter %c in source line %s\n", pos[4], line);
                        break;
                    }
                    s_start=pos+5;
                    s_end=strchr(s_start,pos[4]);
                    if (s_end == NULL) {
                        mp_msg(MSGT_PLAYTREE,MSGL_V,"Error parsing this source line %s\n",line);
                        break;
                    }
                    if (s_end-s_start> 511) {
                        mp_msg(MSGT_PLAYTREE,MSGL_V,"Cannot store such a large source %s\n",line);
                        break;
                    }
                    strncpy(source,s_start,s_end-s_start);
                    source[(s_end-s_start)]='\0'; // Null terminate
                    entry = play_tree_new();
                    play_tree_add_file(entry,source);
                    if(!list)  //Insert new entry
                        list = entry;
                    else
                        play_tree_append_entry(last_entry,entry);
                    last_entry = entry;
                    pos = s_end;
                }
            }
        }
    } while((src_line = play_tree_parser_get_line(p)) != NULL);

    if (line)
        free(line);

    if(!list) return NULL; // Nothing found

    entry = play_tree_new();
    play_tree_set_child(entry,list);
    return entry;
}
コード例 #14
0
ファイル: conf-parser.c プロジェクト: olegchir/systemd
/* Parse a variable assignment line */
static int parse_line(
                const char *filename,
                unsigned line,
                const char *sections,
                ConfigItemLookup lookup,
                void *table,
                bool relaxed,
                char **section,
                char *l,
                void *userdata) {

        char *e;

        assert(filename);
        assert(line > 0);
        assert(lookup);
        assert(l);

        l = strstrip(l);

        if (!*l)
                return 0;

        if (strchr(COMMENTS, *l))
                return 0;

        if (startswith(l, ".include ")) {
                char *fn;
                int r;

                fn = file_in_same_dir(filename, strstrip(l+9));
                if (!fn)
                        return -ENOMEM;

                r = config_parse(fn, NULL, sections, lookup, table, relaxed, userdata);
                free(fn);

                return r;
        }

        if (*l == '[') {
                size_t k;
                char *n;

                k = strlen(l);
                assert(k > 0);

                if (l[k-1] != ']') {
                        log_error("[%s:%u] Invalid section header.", filename, line);
                        return -EBADMSG;
                }

                n = strndup(l+1, k-2);
                if (!n)
                        return -ENOMEM;

                if (sections && !nulstr_contains(sections, n)) {

                        if (!relaxed)
                                log_info("[%s:%u] Unknown section '%s'. Ignoring.", filename, line, n);

                        free(n);
                        *section = NULL;
                } else {
                        free(*section);
                        *section = n;
                }

                return 0;
        }

        if (sections && !*section) {

                if (!relaxed)
                        log_info("[%s:%u] Assignment outside of section. Ignoring.", filename, line);

                return 0;
        }

        e = strchr(l, '=');
        if (!e) {
                log_error("[%s:%u] Missing '='.", filename, line);
                return -EBADMSG;
        }

        *e = 0;
        e++;

        return next_assignment(
                        filename,
                        line,
                        lookup,
                        table,
                        *section,
                        strstrip(l),
                        strstrip(e),
                        relaxed,
                        userdata);
}
コード例 #15
0
static int process(
                const char *controller,
                const char *path,
                Hashmap *a,
                Hashmap *b,
                unsigned iteration,
                Group **ret) {

        Group *g;
        int r;

        assert(controller);
        assert(path);
        assert(a);

        g = hashmap_get(a, path);
        if (!g) {
                g = hashmap_get(b, path);
                if (!g) {
                        g = new0(Group, 1);
                        if (!g)
                                return -ENOMEM;

                        g->path = strdup(path);
                        if (!g->path) {
                                group_free(g);
                                return -ENOMEM;
                        }

                        r = hashmap_put(a, g->path, g);
                        if (r < 0) {
                                group_free(g);
                                return r;
                        }
                } else {
                        r = hashmap_move_one(a, b, path);
                        if (r < 0)
                                return r;

                        g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false;
                }
        }

        if (streq(controller, SYSTEMD_CGROUP_CONTROLLER) && IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES)) {
                _cleanup_fclose_ FILE *f = NULL;
                pid_t pid;

                r = cg_enumerate_processes(controller, path, &f);
                if (r == -ENOENT)
                        return 0;
                if (r < 0)
                        return r;

                g->n_tasks = 0;
                while (cg_read_pid(f, &pid) > 0) {

                        if (arg_count == COUNT_USERSPACE_PROCESSES && is_kernel_thread(pid) > 0)
                                continue;

                        g->n_tasks++;
                }

                if (g->n_tasks > 0)
                        g->n_tasks_valid = true;

        } else if (streq(controller, "pids") && arg_count == COUNT_PIDS) {
                _cleanup_free_ char *p = NULL, *v = NULL;

                r = cg_get_path(controller, path, "pids.current", &p);
                if (r < 0)
                        return r;

                r = read_one_line_file(p, &v);
                if (r == -ENOENT)
                        return 0;
                if (r < 0)
                        return r;

                r = safe_atou64(v, &g->n_tasks);
                if (r < 0)
                        return r;

                if (g->n_tasks > 0)
                        g->n_tasks_valid = true;

        } else if (streq(controller, "cpu") || streq(controller, "cpuacct")) {
                _cleanup_free_ char *p = NULL, *v = NULL;
                uint64_t new_usage;
                nsec_t timestamp;

                if (cg_all_unified() > 0) {
                        const char *keys[] = { "usage_usec", NULL };
                        _cleanup_free_ char *val = NULL;

                        if (!streq(controller, "cpu"))
                                return 0;

                        r = cg_get_keyed_attribute("cpu", path, "cpu.stat", keys, &val);
                        if (r == -ENOENT)
                                return 0;
                        if (r < 0)
                                return r;

                        r = safe_atou64(val, &new_usage);
                        if (r < 0)
                                return r;

                        new_usage *= NSEC_PER_USEC;
                } else {
                        if (!streq(controller, "cpuacct"))
                                return 0;

                        r = cg_get_path(controller, path, "cpuacct.usage", &p);
                        if (r < 0)
                                return r;

                        r = read_one_line_file(p, &v);
                        if (r == -ENOENT)
                                return 0;
                        if (r < 0)
                                return r;

                        r = safe_atou64(v, &new_usage);
                        if (r < 0)
                                return r;
                }

                timestamp = now_nsec(CLOCK_MONOTONIC);

                if (g->cpu_iteration == iteration - 1 &&
                    (nsec_t) new_usage > g->cpu_usage) {

                        nsec_t x, y;

                        x = timestamp - g->cpu_timestamp;
                        if (x < 1)
                                x = 1;

                        y = (nsec_t) new_usage - g->cpu_usage;
                        g->cpu_fraction = (double) y / (double) x;
                        g->cpu_valid = true;
                }

                g->cpu_usage = (nsec_t) new_usage;
                g->cpu_timestamp = timestamp;
                g->cpu_iteration = iteration;

        } else if (streq(controller, "memory")) {
                _cleanup_free_ char *p = NULL, *v = NULL;

                if (cg_all_unified() <= 0)
                        r = cg_get_path(controller, path, "memory.usage_in_bytes", &p);
                else
                        r = cg_get_path(controller, path, "memory.current", &p);
                if (r < 0)
                        return r;

                r = read_one_line_file(p, &v);
                if (r == -ENOENT)
                        return 0;
                if (r < 0)
                        return r;

                r = safe_atou64(v, &g->memory);
                if (r < 0)
                        return r;

                if (g->memory > 0)
                        g->memory_valid = true;

        } else if ((streq(controller, "io") && cg_all_unified() > 0) ||
                   (streq(controller, "blkio") && cg_all_unified() <= 0)) {
                _cleanup_fclose_ FILE *f = NULL;
                _cleanup_free_ char *p = NULL;
                bool unified = cg_all_unified() > 0;
                uint64_t wr = 0, rd = 0;
                nsec_t timestamp;

                r = cg_get_path(controller, path, unified ? "io.stat" : "blkio.io_service_bytes", &p);
                if (r < 0)
                        return r;

                f = fopen(p, "re");
                if (!f) {
                        if (errno == ENOENT)
                                return 0;
                        return -errno;
                }

                for (;;) {
                        char line[LINE_MAX], *l;
                        uint64_t k, *q;

                        if (!fgets(line, sizeof(line), f))
                                break;

                        /* Trim and skip the device */
                        l = strstrip(line);
                        l += strcspn(l, WHITESPACE);
                        l += strspn(l, WHITESPACE);

                        if (unified) {
                                while (!isempty(l)) {
                                        if (sscanf(l, "rbytes=%" SCNu64, &k))
                                                rd += k;
                                        else if (sscanf(l, "wbytes=%" SCNu64, &k))
                                                wr += k;

                                        l += strcspn(l, WHITESPACE);
                                        l += strspn(l, WHITESPACE);
                                }
                        } else {
                                if (first_word(l, "Read")) {
                                        l += 4;
                                        q = &rd;
                                } else if (first_word(l, "Write")) {
                                        l += 5;
                                        q = &wr;
                                } else
                                        continue;

                                l += strspn(l, WHITESPACE);
                                r = safe_atou64(l, &k);
                                if (r < 0)
                                        continue;

                                *q += k;
                        }
                }

                timestamp = now_nsec(CLOCK_MONOTONIC);

                if (g->io_iteration == iteration - 1) {
                        uint64_t x, yr, yw;

                        x = (uint64_t) (timestamp - g->io_timestamp);
                        if (x < 1)
                                x = 1;

                        if (rd > g->io_input)
                                yr = rd - g->io_input;
                        else
                                yr = 0;

                        if (wr > g->io_output)
                                yw = wr - g->io_output;
                        else
                                yw = 0;

                        if (yr > 0 || yw > 0) {
                                g->io_input_bps = (yr * 1000000000ULL) / x;
                                g->io_output_bps = (yw * 1000000000ULL) / x;
                                g->io_valid = true;
                        }
                }

                g->io_input = rd;
                g->io_output = wr;
                g->io_timestamp = timestamp;
                g->io_iteration = iteration;
        }

        if (ret)
                *ret = g;

        return 0;
}
コード例 #16
0
ファイル: conf-parser.c プロジェクト: kreijack/systemd
/* Parse a variable assignment line */
static int parse_line(const char* unit,
                      const char *filename,
                      unsigned line,
                      const char *sections,
                      ConfigItemLookup lookup,
                      const void *table,
                      bool relaxed,
                      bool allow_include,
                      char **section,
                      unsigned *section_line,
                      bool *section_ignored,
                      char *l,
                      void *userdata) {

    char *e;

    assert(filename);
    assert(line > 0);
    assert(lookup);
    assert(l);

    l = strstrip(l);

    if (!*l)
        return 0;

    if (strchr(COMMENTS "\n", *l))
        return 0;

    if (startswith(l, ".include ")) {
        _cleanup_free_ char *fn = NULL;

        /* .includes are a bad idea, we only support them here
         * for historical reasons. They create cyclic include
         * problems and make it difficult to detect
         * configuration file changes with an easy
         * stat(). Better approaches, such as .d/ drop-in
         * snippets exist.
         *
         * Support for them should be eventually removed. */

        if (!allow_include) {
            log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
                       ".include not allowed here. Ignoring.");
            return 0;
        }

        fn = file_in_same_dir(filename, strstrip(l+9));
        if (!fn)
            return -ENOMEM;

        return config_parse(unit, fn, NULL, sections, lookup, table, relaxed, false, false, userdata);
    }

    if (*l == '[') {
        size_t k;
        char *n;

        k = strlen(l);
        assert(k > 0);

        if (l[k-1] != ']') {
            log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
                       "Invalid section header '%s'", l);
            return -EBADMSG;
        }

        n = strndup(l+1, k-2);
        if (!n)
            return -ENOMEM;

        if (sections && !nulstr_contains(sections, n)) {

            if (!relaxed && !startswith(n, "X-"))
                log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
                           "Unknown section '%s'. Ignoring.", n);

            free(n);
            free(*section);
            *section = NULL;
            *section_line = 0;
            *section_ignored = true;
        } else {
            free(*section);
            *section = n;
            *section_line = line;
            *section_ignored = false;
        }

        return 0;
    }

    if (sections && !*section) {

        if (!relaxed && !*section_ignored)
            log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
                       "Assignment outside of section. Ignoring.");

        return 0;
    }

    e = strchr(l, '=');
    if (!e) {
        log_syntax(unit, LOG_WARNING, filename, line, EINVAL, "Missing '='.");
        return -EBADMSG;
    }

    *e = 0;
    e++;

    return next_assignment(unit,
                           filename,
                           line,
                           lookup,
                           table,
                           *section,
                           *section_line,
                           strstrip(l),
                           strstrip(e),
                           relaxed,
                           userdata);
}
コード例 #17
0
ファイル: localed.c プロジェクト: mariux/systemd
static int read_data_x11(void) {
        FILE *f;
        char line[LINE_MAX];
        bool in_section = false;

        free_data_x11();

        f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
        if (!f) {
                if (errno == ENOENT) {

#ifdef TARGET_FEDORA
                        f = fopen("/etc/X11/xorg.conf.d/00-system-setup-keyboard.conf", "re");
                        if (!f) {
                                if (errno == ENOENT)
                                        return 0;
                                else
                                        return -errno;
                        }
#else
                        return 0;
#endif

                } else
                          return -errno;
        }

        while (fgets(line, sizeof(line), f)) {
                char *l;

                char_array_0(line);
                l = strstrip(line);

                if (l[0] == 0 || l[0] == '#')
                        continue;

                if (in_section && first_word(l, "Option")) {
                        char **a;

                        a = strv_split_quoted(l);
                        if (!a) {
                                fclose(f);
                                return -ENOMEM;
                        }

                        if (strv_length(a) == 3) {

                                if (streq(a[1], "XkbLayout")) {
                                        free(state.x11_layout);
                                        state.x11_layout = a[2];
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbModel")) {
                                        free(state.x11_model);
                                        state.x11_model = a[2];
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbVariant")) {
                                        free(state.x11_variant);
                                        state.x11_variant = a[2];
                                        a[2] = NULL;
                                } else if (streq(a[1], "XkbOptions")) {
                                        free(state.x11_options);
                                        state.x11_options = a[2];
                                        a[2] = NULL;
                                }
                        }

                        strv_free(a);

                } else if (!in_section && first_word(l, "Section")) {
                        char **a;

                        a = strv_split_quoted(l);
                        if (!a) {
                                fclose(f);
                                return -ENOMEM;
                        }

                        if (strv_length(a) == 2 && streq(a[1], "InputClass"))
                                in_section = true;

                        strv_free(a);
                } else if (in_section && first_word(l, "EndSection"))
                        in_section = false;
        }

        fclose(f);

        return 0;
}
コード例 #18
0
/* Parse a single logical line */
static int parse_line(
                const char* unit,
                const char *filename,
                unsigned line,
                const char *sections,
                ConfigItemLookup lookup,
                const void *table,
                ConfigParseFlags flags,
                char **section,
                unsigned *section_line,
                bool *section_ignored,
                char *l,
                void *userdata) {

        char *e, *include;

        assert(filename);
        assert(line > 0);
        assert(lookup);
        assert(l);

        l = strstrip(l);
        if (!*l)
                return 0;

        if (strchr(COMMENTS "\n", *l))
                return 0;

        include = first_word(l, ".include");
        if (include) {
                _cleanup_free_ char *fn = NULL;

                /* .includes are a bad idea, we only support them here
                 * for historical reasons. They create cyclic include
                 * problems and make it difficult to detect
                 * configuration file changes with an easy
                 * stat(). Better approaches, such as .d/ drop-in
                 * snippets exist.
                 *
                 * Support for them should be eventually removed. */

                if (!(flags & CONFIG_PARSE_ALLOW_INCLUDE)) {
                        log_syntax(unit, LOG_ERR, filename, line, 0, ".include not allowed here. Ignoring.");
                        return 0;
                }

                log_syntax(unit, LOG_WARNING, filename, line, 0,
                           ".include directives are deprecated, and support for them will be removed in a future version of systemd. "
                           "Please use drop-in files instead.");

                fn = file_in_same_dir(filename, strstrip(include));
                if (!fn)
                        return -ENOMEM;

                return config_parse(unit, fn, NULL, sections, lookup, table, flags, userdata);
        }

        if (!utf8_is_valid(l))
                return log_syntax_invalid_utf8(unit, LOG_WARNING, filename, line, l);

        if (*l == '[') {
                size_t k;
                char *n;

                k = strlen(l);
                assert(k > 0);

                if (l[k-1] != ']') {
                        log_syntax(unit, LOG_ERR, filename, line, 0, "Invalid section header '%s'", l);
                        return -EBADMSG;
                }

                n = strndup(l+1, k-2);
                if (!n)
                        return -ENOMEM;

                if (sections && !nulstr_contains(sections, n)) {

                        if (!(flags & CONFIG_PARSE_RELAXED) && !startswith(n, "X-"))
                                log_syntax(unit, LOG_WARNING, filename, line, 0, "Unknown section '%s'. Ignoring.", n);

                        free(n);
                        *section = mfree(*section);
                        *section_line = 0;
                        *section_ignored = true;
                } else {
                        free_and_replace(*section, n);
                        *section_line = line;
                        *section_ignored = false;
                }

                return 0;
        }

        if (sections && !*section) {

                if (!(flags & CONFIG_PARSE_RELAXED) && !*section_ignored)
                        log_syntax(unit, LOG_WARNING, filename, line, 0, "Assignment outside of section. Ignoring.");

                return 0;
        }

        e = strchr(l, '=');
        if (!e) {
                log_syntax(unit, LOG_WARNING, filename, line, 0, "Missing '='.");
                return -EINVAL;
        }

        *e = 0;
        e++;

        return next_assignment(unit,
                               filename,
                               line,
                               lookup,
                               table,
                               *section,
                               *section_line,
                               strstrip(l),
                               strstrip(e),
                               flags,
                               userdata);
}
コード例 #19
0
ファイル: catalog.c プロジェクト: systemdiet/systemdiet
int catalog_import_file(Hashmap *h, struct strbuf *sb, const char *path) {
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *payload = NULL;
        unsigned n = 0;
        sd_id128_t id;
        char language[32];
        bool got_id = false, empty_line = true;
        int r;

        assert(h);
        assert(sb);
        assert(path);

        f = fopen(path, "re");
        if (!f) {
                log_error("Failed to open file %s: %m", path);
                return -errno;
        }

        for (;;) {
                char line[LINE_MAX];
                size_t a, b, c;
                char *t;

                if (!fgets(line, sizeof(line), f)) {
                        if (feof(f))
                                break;

                        log_error("Failed to read file %s: %m", path);
                        return -errno;
                }

                n++;

                truncate_nl(line);

                if (line[0] == 0) {
                        empty_line = true;
                        continue;
                }

                if (strchr(COMMENTS "\n", line[0]))
                        continue;

                if (empty_line &&
                    strlen(line) >= 2+1+32 &&
                    line[0] == '-' &&
                    line[1] == '-' &&
                    line[2] == ' ' &&
                    (line[2+1+32] == ' ' || line[2+1+32] == '\0')) {

                        bool with_language;
                        sd_id128_t jd;

                        /* New entry */

                        with_language = line[2+1+32] != '\0';
                        line[2+1+32] = '\0';

                        if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) {

                                if (got_id) {
                                        r = finish_item(h, sb, id, language, payload);
                                        if (r < 0)
                                                return r;
                                }

                                if (with_language) {
                                        t = strstrip(line + 2 + 1 + 32 + 1);

                                        c = strlen(t);
                                        if (c <= 0) {
                                                log_error("[%s:%u] Language too short.", path, n);
                                                return -EINVAL;
                                        }
                                        if (c > sizeof(language) - 1) {
                                                log_error("[%s:%u] language too long.", path, n);
                                                return -EINVAL;
                                        }

                                        strscpy(language, sizeof(language), t);
                                } else
                                        language[0] = '\0';

                                got_id = true;
                                empty_line = false;
                                id = jd;

                                if (payload)
                                        payload[0] = '\0';

                                continue;
                        }
                }

                /* Payload */
                if (!got_id) {
                        log_error("[%s:%u] Got payload before ID.", path, n);
                        return -EINVAL;
                }

                a = payload ? strlen(payload) : 0;
                b = strlen(line);

                c = a + (empty_line ? 1 : 0) + b + 1 + 1;
                t = realloc(payload, c);
                if (!t)
                        return log_oom();

                if (empty_line) {
                        t[a] = '\n';
                        memcpy(t + a + 1, line, b);
                        t[a+b+1] = '\n';
                        t[a+b+2] = 0;
                } else {
                        memcpy(t + a, line, b);
                        t[a+b] = '\n';
                        t[a+b+1] = 0;
                }

                payload = t;
                empty_line = false;
        }

        if (got_id) {
                r = finish_item(h, sb, id, language, payload);
                if (r < 0)
                        return r;
        }

        return 0;
}
コード例 #20
0
ファイル: parse.cpp プロジェクト: inspirer/textmapper
int lalr1::parse()
{
	char *token = new char[4096];
	int  lapg_head = 0, group = 0, lapg_i, lapg_size, chr;
	lapg_symbol *lapg_m = new lapg_symbol[512];
	lapg_symbol lapg_n = { NULL, -1, 0 };
	lapg_place lapg_current = { 1, 1 };

	lapg_m[0].state = 0;
	chr = *l++;if( l == end ) fillb();

	do {
		lapg_n.pos = lapg_current;
		for( lapg_size = 0, lapg_i = group; lapg_i >= 0; ) {
			if( lapg_size < 4096-1 ) token[lapg_size++] = chr;
			lapg_i = lapg_lexem[lapg_i][lapg_char2no[chr]];
			if( lapg_i >= -1 && chr ) { 
				lapg_current.column++;
				if( chr == '\n' ) lapg_current.column = 1, lapg_current.line++;
				chr = *l++;if( l == end ) fillb();
			}
		}
		token[lapg_size] = 0;

		if( lapg_i == -1 ) {
			error( 0, "invalid lexem at line %i, column %i: `%s`, skipped\n", lapg_n.pos.line, lapg_n.pos.column, token );
			continue;
		}

		token[lapg_size-1] = 0;
		lapg_n.lexem = -lapg_i-2;
		lapg_n.sym = NULL;
		switch( lapg_n.lexem ) {
			case 1: {
				#line 30 "syntax"
				 *(char* *)&lapg_n.sym = _strdup(token); 
			} break;
			case 2: {
				#line 31 "syntax"
				 *(char* *)&lapg_n.sym = strstrip(token); 
			} break;
			case 3: {
				#line 32 "syntax"
				 *(char* *)&lapg_n.sym = _strdup(token+1); 
			} break;
			case 4: {
				#line 33 "syntax"
				 *(char* *)&lapg_n.sym = _strdup(token+3); 
			} break;
			case 5: {
				#line 34 "syntax"
				 *(char* *)&lapg_n.sym = strstrip(token); 
			} break;
			case 6: {
				#line 35 "syntax"
				 *(char* *)&lapg_n.sym = strstrip(token); 
			} break;
			case 7: {
				#line 36 "syntax"
				 *(char* *)&lapg_n.sym = strstrip(token); 
			} break;
			case 8: {
				#line 37 "syntax"
				 *(int *)&lapg_n.sym = strtol(token,NULL,10); 
			} break;
			case 10: {
				#line 40 "syntax"
				 continue; 
			} break;
		}

		do {
			lapg_i = lapg_next( lapg_m[lapg_head].state, lapg_n.lexem );

			if( lapg_i >= 0 ) {
				lapg_symbol lapg_gg={(lapg_rlen[lapg_i])?lapg_m[lapg_head+1-lapg_rlen[lapg_i]].sym:NULL,lapg_rlex[lapg_i],0 };
				#ifdef DEBUG_syntax
					fprintf( stdout, "reduce to %s\n", lapg_syms[lapg_rlex[lapg_i]] );
				#endif
				lapg_gg.pos = (lapg_rlen[lapg_i])?lapg_m[lapg_head+1-lapg_rlen[lapg_i]].pos:lapg_n.pos;
				switch( lapg_i ) {
					case 2: {
						#line 64 "syntax"
						 lapg_gg.pos.line++; 
					} break;
					case 4: {
						#line 68 "syntax"
						lapg_gg.sym = concat( NULL, ((char*)lapg_m[lapg_head-0].sym), sourcename, lapg_m[lapg_head-0].pos.line );
					} break;
					case 5: {
						#line 70 "syntax"
						lapg_gg.sym = concat( *(char* *)&lapg_gg.sym, ((char*)lapg_m[lapg_head-0].sym), sourcename, (lapg_m[lapg_head-1].pos.line+1!=lapg_m[lapg_head-0].pos.line)?lapg_m[lapg_head-0].pos.line:-1 );
						lapg_gg.pos = lapg_m[lapg_head-0].pos;
					} break;
					case 8: {
						#line 78 "syntax"
						process_directive( ((char*)lapg_m[lapg_head-1].sym), ((char*)lapg_m[lapg_head-0].sym), lapg_m[lapg_head-2].pos.line, lapg_m[lapg_head-2].pos.column );
						delete[] ((char*)lapg_m[lapg_head-1].sym);
					} break;
					case 9: {
						#line 82 "syntax"
						process_directive( ((char*)lapg_m[lapg_head-1].sym), ((int)lapg_m[lapg_head-0].sym), lapg_m[lapg_head-2].pos.line, lapg_m[lapg_head-2].pos.column );
						delete[] ((char*)lapg_m[lapg_head-1].sym);
					} break;
					case 14: {
						#line 88 "syntax"
						 if( ((int)lapg_m[lapg_head-0].sym) < 0 || ((int)lapg_m[lapg_head-0].sym) >= BITS ) *(int *)&lapg_gg.sym = 0; else *(int *)&lapg_gg.sym = 1 << ((int)lapg_m[lapg_head-0].sym); 
					} break;
					case 16: {
						#line 89 "syntax"
						 *(int *)&lapg_gg.sym |= ((int)lapg_m[lapg_head-0].sym); 
					} break;
					case 17: {
						#line 90 "syntax"
						 lb.currentgroups = ((int)lapg_m[lapg_head-1].sym); 
					} break;
					case 18: {
						#line 94 "syntax"
						gb.terminal(((char*)lapg_m[lapg_head-1].sym)); delete[] ((char*)lapg_m[lapg_head-1].sym); 
					} break;
					case 19: {
						#line 97 "syntax"
						gb.terminal(((char*)lapg_m[lapg_head-2].sym),((char*)lapg_m[lapg_head-1].sym)); delete[] ((char*)lapg_m[lapg_head-2].sym); delete[] ((char*)lapg_m[lapg_head-1].sym);
					} break;
					case 22: {
						#line 100 "syntax"
						lb.lexem( gb.terminal(((char*)lapg_m[lapg_head-4].sym)), ((char*)lapg_m[lapg_head-2].sym), ((char*)lapg_m[lapg_head-4].sym), ((char*)lapg_m[lapg_head-0].sym), ((int)lapg_m[lapg_head-1].sym) );
						delete[] ((char*)lapg_m[lapg_head-4].sym); delete[] ((char*)lapg_m[lapg_head-2].sym); delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 23: {
						#line 104 "syntax"
						lb.lexem( gb.terminal(((char*)lapg_m[lapg_head-3].sym)), ((char*)lapg_m[lapg_head-1].sym), ((char*)lapg_m[lapg_head-3].sym), NULL, ((int)lapg_m[lapg_head-0].sym) );
						delete[] ((char*)lapg_m[lapg_head-3].sym); delete[] ((char*)lapg_m[lapg_head-1].sym);
					} break;
					case 24: {
						#line 108 "syntax"
						lb.lexem( gb.terminal(((char*)lapg_m[lapg_head-5].sym), ((char*)lapg_m[lapg_head-4].sym)), ((char*)lapg_m[lapg_head-2].sym), ((char*)lapg_m[lapg_head-5].sym), ((char*)lapg_m[lapg_head-0].sym), ((int)lapg_m[lapg_head-1].sym) );
						delete[] ((char*)lapg_m[lapg_head-5].sym); delete[] ((char*)lapg_m[lapg_head-4].sym); delete[] ((char*)lapg_m[lapg_head-2].sym); delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 25: {
						#line 112 "syntax"
						lb.lexem( gb.terminal(((char*)lapg_m[lapg_head-4].sym), ((char*)lapg_m[lapg_head-3].sym)), ((char*)lapg_m[lapg_head-1].sym), ((char*)lapg_m[lapg_head-4].sym), NULL, ((int)lapg_m[lapg_head-0].sym) );
						delete[] ((char*)lapg_m[lapg_head-4].sym); delete[] ((char*)lapg_m[lapg_head-3].sym); delete[] ((char*)lapg_m[lapg_head-1].sym);
					} break;
					case 31: {
						#line 121 "syntax"
						gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0, NULL, gb.symbol( ((char*)lapg_m[lapg_head-2].sym), 0 ) );
						delete[] ((char*)lapg_m[lapg_head-2].sym);
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 32: {
						#line 125 "syntax"
						gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0, NULL, -1 );
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 43: {
						#line 146 "syntax"
						if( !strcmp(((char*)lapg_m[lapg_head-0].sym),"left")) lapg_gg.sym = (void*)1;
						else if( !strcmp(((char*)lapg_m[lapg_head-0].sym),"right")) lapg_gg.sym = (void*)2;
						else if( !strcmp(((char*)lapg_m[lapg_head-0].sym),"nonassoc")) lapg_gg.sym = (void*)3;
						else { error(0,"wrong priority declaration: %%%s",((char*)lapg_m[lapg_head-0].sym));lapg_gg.sym = 0; }
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 45: {
						#line 153 "syntax"
						 gb.addprio(((char*)lapg_m[lapg_head-0].sym),((int)lapg_m[lapg_head-1].sym),0); 
					} break;
					case 46: {
						#line 153 "syntax"
						 gb.addprio(((char*)lapg_m[lapg_head-0].sym),((int)lapg_m[lapg_head-2].sym),1); 
					} break;
					case 47: {
						#line 156 "syntax"
						 *(int *)&lapg_gg.sym = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0 ); delete[] ((char*)lapg_m[lapg_head-0].sym); 
					} break;
					case 48: {
						#line 157 "syntax"
						 *(int *)&lapg_gg.sym = -1; 
					} break;
					case 49: {
						#line 161 "syntax"
						gb.rule( length, ((int)lapg_m[lapg_head-1].sym), ((char*)lapg_m[lapg_head-0].sym), rule, lapg_gg.pos.line );
					} break;
					case 50: {
						#line 164 "syntax"
						gb.rule( length, ((int)lapg_m[lapg_head-0].sym), NULL, rule, lapg_gg.pos.line );
					} break;
					case 51: {
						#line 167 "syntax"
						gb.rule( 0, ((int)lapg_m[lapg_head-0].sym), ((char*)lapg_m[lapg_head-1].sym), rule, lapg_gg.pos.line );
					} break;
					case 52: {
						#line 170 "syntax"
						gb.rule( 0, ((int)lapg_m[lapg_head-0].sym), NULL, rule, lapg_gg.pos.line );
					} break;
					case 55: {
						#line 175 "syntax"
						if( ((char*)lapg_m[lapg_head-1].sym) ) {
							length += 2;
							rule[length] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0 );
							rule[length-1] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 2, NULL, rule[length] );
							gb.rule( 0, -1, ((char*)lapg_m[lapg_head-1].sym), rule+length-1, lapg_m[lapg_head-2].pos.line );
						} else rule[++length] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0 );
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 56: {
						#line 184 "syntax"
						length = 0;
						if( ((char*)lapg_m[lapg_head-1].sym) ) {
							length += 2;
							rule[length] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0 );
							rule[length-1] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 2, NULL, rule[length] );
							gb.rule( 0, -1, ((char*)lapg_m[lapg_head-1].sym), rule+length-1, lapg_m[lapg_head-1].pos.line );
						} else rule[++length] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 0 );
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 57: {
						#line 196 "syntax"
						rule[0] = gb.symbol( ((char*)lapg_m[lapg_head-0].sym), 1 );
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
					case 58: {
						#line 200 "syntax"
						rule[0] = gb.symbol( ((char*)lapg_m[lapg_head-1].sym), 1, ((char*)lapg_m[lapg_head-0].sym) );
						delete[] ((char*)lapg_m[lapg_head-1].sym);
						delete[] ((char*)lapg_m[lapg_head-0].sym);
					} break;
				}
				lapg_head -= lapg_rlen[lapg_i];
				lapg_m[++lapg_head] = lapg_gg;
				lapg_m[lapg_head].state = lapg_state_sym( lapg_m[lapg_head-1].state, lapg_gg.lexem );
			} else if( lapg_i == -1 ) {
				lapg_m[++lapg_head] = lapg_n;
				lapg_m[lapg_head].state = lapg_state_sym( lapg_m[lapg_head-1].state, lapg_n.lexem );
				#ifdef DEBUG_syntax
					fprintf( stdout, "shift: %s (%s)\n", lapg_syms[lapg_n.lexem], token );
				#endif
			}

		} while( lapg_i >= 0 && lapg_m[lapg_head].state != -1 );

		if( (lapg_i == -2 || lapg_m[lapg_head].state == -1) && lapg_n.lexem != 0 ) {
			break;
		}

	} while( lapg_n.lexem );

	if( lapg_m[lapg_head].state == 91-1 ) lapg_i = 1; else lapg_i = 0;
	delete[] lapg_m;
	delete[] token;

	if( !lapg_i ) error( 0, "syntax error before line %i, column %i\n", lapg_n.pos.line, lapg_n.pos.column );
	return lapg_i;
}
コード例 #21
0
ファイル: iniparser.c プロジェクト: chenan2005/WebGameServer
/*--------------------------------------------------------------------------*/
static line_status iniparser_line(
    int line_size,
    const char * input_line,
    char ** section_out,
    char ** key_out,
    char ** value_out)
{
    line_status sta ;
    int len = line_size-1;
    char * line = malloc(line_size);
    char * key = NULL;
    char * value = NULL;
    char * equals = NULL;

    if (!line) {
        fprintf(stderr, "iniparser: memory alloc error\n");
        return LINE_ERROR;
    }

    *line = 0;


    strcpy(line, input_line);
    strstrip(line);
    len = (int)strlen(line);

    /* only allocate necessary space for key & val */
    equals = strchr(line, '=');
    if (equals) {
        value = malloc((len + line) - equals + 1);
        key = malloc(equals - line + 1);
       *value = 0;
    } else {
        key = malloc(line_size + 1);
    }

    if (!key || (equals && !value)) {
        fprintf(stderr, "iniparser: memory alloc error\n");
        sta = LINE_ERROR;
        goto out;
    }

    *key = 0;

    sta = LINE_UNPROCESSED ;
    if (len<1) {
        /* Empty line */
        sta = LINE_EMPTY ;
    } else if (line[0]=='#' || line[0]==';') {
        /* Comment line */
        sta = LINE_COMMENT ;
    } else if (line[0]=='[' && line[len-1]==']') {
        /* Section name */
        sscanf(line, "[%[^]]", key);
        strstrip(key);
        strlwc(key);
        sta = LINE_SECTION ;
        *section_out=key;
        /* don't free key's memory */
        key = NULL;
    } else if (equals && (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
           ||  sscanf (line, "%[^=] = '%[^\']'",   key, value) == 2
           ||  sscanf (line, "%[^=] = %[^;#]",     key, value) == 2)) {
        /* Usual key=value, with or without comments */
        strstrip(key);
        strlwc(key);
        strstrip(value);
        /*
         * sscanf cannot handle '' or "" as empty values
         * this is done here
         */
        if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
            value[0]=0 ;
        }
        *key_out = key;
        *value_out = value;
        key = NULL;
        value = NULL;
        sta = LINE_VALUE ;
    } else if (equals && (sscanf(line, "%[^=] = %[;#]", key, value)==2
           ||  sscanf(line, "%[^=] %[=]", key, value) == 2)) {
        /*
         * Special cases:
         * key=
         * key=;
         * key=#
         */
        strstrip(key);
        strlwc(key);
        value[0]=0 ;
        *key_out = key;
        *value_out = value;

        /* don't free out params key or val's memory */
        key = NULL;
        value = NULL;
        sta = LINE_VALUE ;
    } else {
        /* Generate syntax error */
        sta = LINE_ERROR ;
    }

out:
    if (line) {
        free(line);
        line = NULL;
    }
    if (key) {
        free(key);
        key = NULL;
    }
    if (value) {
        free(value);
        value= NULL;
    }
    return sta ;
}
コード例 #22
0
ファイル: iniparser.c プロジェクト: wikthewiz/watch_it
/*--------------------------------------------------------------------------*/
static line_status iniparser_line(const char * input_line, char * section,
		char * key, char * value)
{
	line_status sta;
	char line[ASCIILINESZ + 1];
	int len;

	strcpy(line, strstrip(input_line));
	len = (int) strlen(line);

	sta = LINE_UNPROCESSED;
	if (len < 1)
	{
		/* Empty line */
		sta = LINE_EMPTY;
	}
	else if (line[0] == '#' || line[0] == ';')
	{
		/* Comment line */
		sta = LINE_COMMENT;
	}
	else if (line[0] == '[' && line[len - 1] == ']')
	{
		/* Section name */
		sscanf(line, "[%[^]]", section);
		strcpy(section, strstrip(section));
		strcpy(section, strlwc(section));
		sta = LINE_SECTION;
	}
	else if (sscanf(line, "%[^=] = \"%[^\"]\"", key, value) == 2
			|| sscanf(line, "%[^=] = '%[^\']'", key, value) == 2
			|| sscanf(line, "%[^=] = %[^;#]", key, value) == 2)
	{
		/* Usual key=value, with or without comments */
		strcpy(key, strstrip(key));
		strcpy(key, strlwc(key));
		strcpy(value, strstrip(value));
		/*
		 * sscanf cannot handle '' or "" as empty values
		 * this is done here
		 */
		if (!strcmp(value, "\"\"") || (!strcmp(value, "''")))
		{
			value[0] = 0;
		}
		sta = LINE_VALUE;
	}
	else if (sscanf(line, "%[^=] = %[;#]", key, value) == 2
			|| sscanf(line, "%[^=] %[=]", key, value) == 2)
	{
		/*
		 * Special cases:
		 * key=
		 * key=;
		 * key=#
		 */
		strcpy(key, strstrip(key));
		strcpy(key, strlwc(key));
		value[0] = 0;
		sta = LINE_VALUE;
	}
	else
	{
		/* Generate syntax error */
		sta = LINE_ERROR;
	}
	return sta;
}
コード例 #23
0
ファイル: conf-parser.c プロジェクト: ariscop/systemd
/* Parse a variable assignment line */
static int parse_line(const char* unit,
                      const char *filename,
                      unsigned line,
                      const char *sections,
                      ConfigItemLookup lookup,
                      void *table,
                      bool relaxed,
                      bool allow_include,
                      char **section,
                      unsigned *section_line,
                      char *l,
                      void *userdata) {

        char *e;

        assert(filename);
        assert(line > 0);
        assert(lookup);
        assert(l);

        l = strstrip(l);

        if (!*l)
                return 0;

        if (strchr(COMMENTS "\n", *l))
                return 0;

        if (startswith(l, ".include ")) {
                _cleanup_free_ char *fn = NULL;

                if (!allow_include) {
                        log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
                                   ".include not allowed here. Ignoring.");
                        return 0;
                }

                fn = file_in_same_dir(filename, strstrip(l+9));
                if (!fn)
                        return -ENOMEM;

                return config_parse(unit, fn, NULL, sections, lookup, table, relaxed, false, userdata);
        }

        if (*l == '[') {
                size_t k;
                char *n;

                k = strlen(l);
                assert(k > 0);

                if (l[k-1] != ']') {
                        log_syntax(unit, LOG_ERR, filename, line, EBADMSG,
                                   "Invalid section header '%s'", l);
                        return -EBADMSG;
                }

                n = strndup(l+1, k-2);
                if (!n)
                        return -ENOMEM;

                if (sections && !nulstr_contains(sections, n)) {

                        if (!relaxed)
                                log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
                                           "Unknown section '%s'. Ignoring.", n);

                        free(n);
                        free(*section);
                        *section = NULL;
                        *section_line = 0;
                } else {
                        free(*section);
                        *section = n;
                        *section_line = line;
                }

                return 0;
        }

        if (sections && !*section) {

                if (!relaxed)
                        log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
                                   "Assignment outside of section. Ignoring.");

                return 0;
        }

        e = strchr(l, '=');
        if (!e) {
                log_syntax(unit, LOG_WARNING, filename, line, EINVAL, "Missing '='.");
                return -EBADMSG;
        }

        *e = 0;
        e++;

        return next_assignment(unit,
                               filename,
                               line,
                               lookup,
                               table,
                               *section,
                               *section_line,
                               strstrip(l),
                               strstrip(e),
                               relaxed,
                               userdata);
}
コード例 #24
0
ファイル: localectl.c プロジェクト: ariscop/systemd
static int list_x11_keymaps(sd_bus *bus, char **args, unsigned n) {
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_strv_free_ char **list = NULL;
        char line[LINE_MAX];
        enum {
                NONE,
                MODELS,
                LAYOUTS,
                VARIANTS,
                OPTIONS
        } state = NONE, look_for;
        int r;

        if (n > 2) {
                log_error("Too many arguments.");
                return -EINVAL;
        }

        f = fopen("/usr/share/X11/xkb/rules/base.lst", "re");
        if (!f) {
                log_error("Failed to open keyboard mapping list. %m");
                return -errno;
        }

        if (streq(args[0], "list-x11-keymap-models"))
                look_for = MODELS;
        else if (streq(args[0], "list-x11-keymap-layouts"))
                look_for = LAYOUTS;
        else if (streq(args[0], "list-x11-keymap-variants"))
                look_for = VARIANTS;
        else if (streq(args[0], "list-x11-keymap-options"))
                look_for = OPTIONS;
        else
                assert_not_reached("Wrong parameter");

        FOREACH_LINE(line, f, break) {
                char *l, *w;

                l = strstrip(line);

                if (isempty(l))
                        continue;

                if (l[0] == '!') {
                        if (startswith(l, "! model"))
                                state = MODELS;
                        else if (startswith(l, "! layout"))
                                state = LAYOUTS;
                        else if (startswith(l, "! variant"))
                                state = VARIANTS;
                        else if (startswith(l, "! option"))
                                state = OPTIONS;
                        else
                                state = NONE;

                        continue;
                }

                if (state != look_for)
                        continue;

                w = l + strcspn(l, WHITESPACE);

                if (n > 1) {
                        char *e;

                        if (*w == 0)
                                continue;

                        *w = 0;
                        w++;
                        w += strspn(w, WHITESPACE);

                        e = strchr(w, ':');
                        if (!e)
                                continue;

                        *e = 0;

                        if (!streq(w, args[1]))
                                continue;
                } else
                        *w = 0;

                 r = strv_extend(&list, l);
                 if (r < 0)
                         return log_oom();
        }

        if (strv_isempty(list)) {
                log_error("Couldn't find any entries.");
                return -ENOENT;
        }

        strv_sort(list);
        strv_uniq(list);

        pager_open_if_enabled();

        strv_print(list);
        return 0;
}
コード例 #25
0
ファイル: trace-stat.c プロジェクト: josefbacik/trace-cmd
static void report_events(struct buffer_instance *instance)
{
	struct event_iter *iter;
	char *str;
	char *cont;
	char *path;
	char *system;
	enum event_iter_type type;
	enum event_process processed = PROCESSED_NONE;

	str = get_instance_file_content(instance, "events/enable");
	if (!str)
		return;

	cont = strstrip(str);

	printf("\nEvents:\n");

	switch(*cont) {
	case '1':
		printf(" All enabled\n");
		free(str);
		return;
	case '0':
		printf(" All disabled\n");
		free(str);
		return;
	}

	free(str);

	path = get_instance_file(instance, "events");
	if (!path)
		die("malloc");

	iter = trace_event_iter_alloc(path);

	while (trace_event_iter_next(iter, path, NULL)) {
		process_event_enable(path, NULL, iter->system_dent->d_name, &processed);
	}

	reset_event_iter(iter);

	processed = PROCESSED_NONE;
	system = NULL;
	while ((type = trace_event_iter_next(iter, path, system))) {

		if (type == EVENT_ITER_SYSTEM) {

			/* Only process systems that are not fully enabled */
			if (!process_individual_events(path, iter))
				continue;

			system = iter->system_dent->d_name;
			if (processed)
				processed = PROCESSED_SYSTEM;
			continue;
		}

		process_event_enable(path, iter->system_dent->d_name,
				     iter->event_dent->d_name, &processed);
	}

	trace_event_iter_free(iter);

	if (!processed)
		printf("  (none enabled)\n");

	tracecmd_put_tracing_file(path);
}
コード例 #26
0
static play_tree_t*
parse_asx(play_tree_parser_t* p) {
    int comments = 0,get_line = 1;
    char* line = NULL;

    mp_msg(MSGT_PLAYTREE,MSGL_V,"Trying asx...\n");

    while(1) {
        if(get_line) {
            line = play_tree_parser_get_line(p);
            if(!line)
                return NULL;
            strstrip(line);
            if(line[0] == '\0')
                continue;
        }
        if(!comments) {
            if(line[0] != '<') {
                mp_msg(MSGT_PLAYTREE,MSGL_DBG2,"First char isn't '<' but '%c'\n",line[0]);
                mp_msg(MSGT_PLAYTREE,MSGL_DBG3,"Buffer = [%s]\n",p->buffer);
                return NULL;
            } else if(strncmp(line,"<!--",4) == 0) { // Comments
                comments = 1;
                line += 4;
                if(line[0] != '\0' && strlen(line) > 0)
                    get_line = 0;
            } else if(strncasecmp(line,"<ASX",4) == 0) // We got an asx element
                break;
            else // We don't get an asx
                return NULL;
        } else { // Comments
            char* c;
            c = strchr(line,'-');
            if(c) {
                if (strncmp(c,"--!>",4) == 0) { // End of comments
                    comments = 0;
                    line = c+4;
                    if(line[0] != '\0') // There is some more data on this line : keep it
                        get_line = 0;

                } else {
                    line = c+1; // Jump the -
                    if(line[0] != '\0') // Some more data
                        get_line = 0;
                    else  // End of line
                        get_line = 1;
                }
            } else // No - on this line (or rest of line) : get next one
                get_line = 1;
        }
    }

    mp_msg(MSGT_PLAYTREE,MSGL_V,"Detected asx format\n");

    // We have an asx : load it in memory and parse

    while((line = play_tree_parser_get_line(p)) != NULL)
        /* NOTHING */;

    mp_msg(MSGT_PLAYTREE,MSGL_DBG3,"Parsing asx file: [%s]\n",p->buffer);
    return asx_parser_build_tree(p->buffer,p->deep);
}
コード例 #27
0
/* Run the main for a generic tessh* program */
int run_tessb_main(int argc, char **argv, const char *progname,
    double (*field)(TESSEROID, double, double, double, GLQ, GLQ, GLQ),
    double ratio1, double ratio2, double ratio3)
{
    TESSB_ARGS args;
    GLQ *glq_lon, *glq_lat, *glq_r;
    TESSEROID *model;
	
    int modelsize, rc, line, points = 0, error_exit = 0, bad_input = 0;
    char buff[10000];
	
    double lon, lat, height, res;
    FILE *logfile = NULL, *modelfile = NULL;
    time_t rawtime;
    clock_t tstart;
    struct tm * timeinfo;

	double (*field1)(TESSEROID, double, double, double, GLQ, GLQ, GLQ);
	double (*field2)(TESSEROID, double, double, double, GLQ, GLQ, GLQ);
	double (*field3)(TESSEROID, double, double, double, GLQ, GLQ, GLQ);
	double ggt_1, ggt_2, ggt_3;
	int n_tesseroid;


    log_init(LOG_INFO);

    rc = parse_tessb_args(argc, argv, progname, &args, &print_tessb_help);
    if(rc == 2)
    {
        return 0;
    }
    if(rc == 1)
    {
        log_warning("Terminating due to bad input");
        log_warning("Try '%s -h' for instructions", progname);

        return 1;
    }

    /* Set the appropriate logging level and log to file if necessary */
    if(!args.verbose)
    {
        log_init(LOG_WARNING);
    }
    if(args.logtofile)
    {
        logfile = fopen(args.logfname, "w");
        if(logfile == NULL)
        {
            log_error("unable to create log file %s", args.logfname);
            log_warning("Terminating due to bad input");
            log_warning("Try '%s -h' for instructions", progname);
            return 1;
        }
        log_tofile(logfile, LOG_DEBUG);
    }

    /* Check if a custom distance-size ratio is given */
    if(args.ratio1 != 0)
    {
        ratio1 = args.ratio1;
    }
	if(args.ratio2 != 0)
    {
        ratio2 = args.ratio2;
    }
	if(args.ratio3 != 0)
    {
        ratio3 = args.ratio3;
    }

    /* Print standard verbose */
    log_info("%s (Tesseroids project) %s", progname, tesseroids_version);
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    log_info("(local time) %s", asctime(timeinfo));
    log_info("Use recursive division of tesseroids: %s",
             args.adaptative ? "True" : "False");
    log_info("Distance-size ratio1 for recusive division: %g", ratio1);
	log_info("Distance-size ratio2 for recusive division: %g", ratio2);
	log_info("Distance-size ratio3 for recusive division: %g", ratio3);

    /* Make the necessary GLQ structures */
    log_info("Using GLQ orders: %d lon / %d lat / %d r", args.lon_order,
             args.lat_order, args.r_order);
    glq_lon = glq_new(args.lon_order, -1, 1);
    glq_lat = glq_new(args.lat_order, -1, 1);
    glq_r = glq_new(args.r_order, -1, 1);
    if(glq_lon == NULL || glq_lat == NULL || glq_r == NULL)
    {
        log_error("failed to create required GLQ structures");
        log_warning("Terminating due to bad input");
        log_warning("Try '%s -h' for instructions", progname);
        if(args.logtofile)
            fclose(logfile);
        return 1;
    }

    /* Read the tesseroid model file */
    log_info("Reading magnetic tesseroid model from file %s", args.modelfname);
    modelfile = fopen(args.modelfname, "r");
    if(modelfile == NULL)
    {
        log_error("failed to open model file %s", args.modelfname);
        log_warning("Terminating due to bad input");
        log_warning("Try '%s -h' for instructions", progname);
        if(args.logtofile)
            fclose(logfile);
        return 1;
    }
    model = read_mag_tess_model(modelfile, &modelsize);
    fclose(modelfile);
    if(modelsize == 0)
    {
        log_error("tesseroid file %s is empty", args.modelfname);
        log_warning("Terminating due to bad input");
        log_warning("Try '%s -h' for instructions", progname);
        if(args.logtofile)
            fclose(logfile);
        return 1;
    }
    if(model == NULL)
    {
        log_error("failed to read model from file %s", args.modelfname);
        log_warning("Terminating due to bad input");
        log_warning("Try '%s -h' for instructions", progname);
        if(args.logtofile)
            fclose(logfile);
        return 1;
    }
    log_info("Total of %d tesseroid(s) read", modelsize);

    /* Print a header on the output with provenance information */
    if(strcmp(progname + 4, "pot") == 0)
    {
        printf("# Potential calculated with %s %s:\n", progname,
               tesseroids_version);
    }
    else
    {
        printf("# %s component calculated with %s %s:\n", progname+4, progname,
               tesseroids_version);
    }
    printf("#   local time: %s", asctime(timeinfo));
    printf("#   model file: %s (%d tesseroids)\n", args.modelfname, modelsize);
    printf("#   GLQ order: %d lon / %d lat / %d r\n", args.lon_order,
           args.lat_order, args.r_order);
    printf("#   Use recursive division of tesseroids: %s\n",
           args.adaptative ? "True" : "False");
    printf("#   Distance-size ratio1 for recusive division: %g\n", ratio1);
	printf("#   Distance-size ratio2 for recusive division: %g\n", ratio2);
	printf("#   Distance-size ratio3 for recusive division: %g\n", ratio3);

	/////////////ELDAR BAYKIEV//////////////
	if (!strcmp("tessbx", progname))
	{
		field1 = &tess_gxx;
		field2 = &tess_gxy;
		field3 = &tess_gxz;
	}

	if (!strcmp("tessby", progname))
	{
		field1 = &tess_gxy;
		field2 = &tess_gyy;
		field3 = &tess_gyz;
	}

	if (!strcmp("tessbz", progname))
	{
		field1 = &tess_gxz;
		field2 = &tess_gyz;
		field3 = &tess_gzz;
	}
	/////////////ELDAR BAYKIEV//////////////

    /* Read each computation point from stdin and calculate */
    log_info("Calculating (this may take a while)...");
    tstart = clock();



	////////////////

	/*for(line = 1; !feof(stdin); line++)
    {
		if(fgets(filebuff[line], 10000, stdin) == NULL)
        {
            if(ferror(stdin))
            {
                log_error("problem encountered reading line %d", line);
                error_exit = 1;
                break;
            }
        }


	}*/


	//MAKE PRELOADED FILE
	///////////////
    for(line = 1; !feof(stdin); line++)
    {
        if(fgets(buff, 10000, stdin) == NULL)
        {
            if(ferror(stdin))
            {
                log_error("problem encountered reading line %d", line);
                error_exit = 1;
                break;
            }
        }
        else
        {
            /* Check for comments and blank lines */
            if(buff[0] == '#' || buff[0] == '\r' || buff[0] == '\n')
            {
                printf("%s", buff);
                continue;
            }
            if(sscanf(buff, "%lf %lf %lf", &lon, &lat, &height) != 3)
            {
                log_warning("bad/invalid computation point at line %d", line);
                log_warning("skipping this line and continuing");
                bad_input++;
                continue;
            }
            /* Need to remove \n and \r from end of buff first to print the
               result in the end */
            strstrip(buff);

			/////////////ELDAR BAYKIEV//////////////
			res = 0;			
            if(args.adaptative)
            {
				for(n_tesseroid = 0; n_tesseroid < modelsize; n_tesseroid++)
				{
					double B_to_H = model[n_tesseroid].suscept/(M_0);//IMPORTANT
					double M_vect[3] = {model[n_tesseroid].Bx * B_to_H, model[n_tesseroid].By * B_to_H, model[n_tesseroid].Bz * B_to_H};
					double M_vect_p[3] = {0, 0, 0};

					conv_vect_fast(M_vect, (model[n_tesseroid].w + model[n_tesseroid].e)*0.5, (model[n_tesseroid].s + model[n_tesseroid].n)*0.5, lon, lat, M_vect_p);
					
					ggt_1 = calc_tess_model_adapt(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field1, ratio1);
					ggt_2 = calc_tess_model_adapt(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field2, ratio2);
					ggt_3 = calc_tess_model_adapt(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field3, ratio3);

					res = res + M_0*EOTVOS2SI*(ggt_1 * M_vect_p[0]  + ggt_2 * M_vect_p[1] + ggt_3 * M_vect_p[2]) /(G*model[n_tesseroid].density*4*PI);

					//printf("res %g\n", res);
				}


				/////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            else
            {	
				/////////////////////////////////////////////////////////////////////////////////////////////////////////
				for(n_tesseroid = 0; n_tesseroid < modelsize; n_tesseroid++)
				{
					double B_to_H = model[n_tesseroid].suscept/(M_0);//IMPORTANT
					double M_vect[3] = {model[n_tesseroid].Bx * B_to_H, model[n_tesseroid].By * B_to_H, model[n_tesseroid].Bz * B_to_H};
					double M_vect_p[3] = {0, 0, 0};

					conv_vect_fast(M_vect, (model[n_tesseroid].w + model[n_tesseroid].e)*0.5, (model[n_tesseroid].s + model[n_tesseroid].n)*0.5, lon, lat, M_vect_p);
					
					ggt_1 = calc_tess_model(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field1);
					ggt_2 = calc_tess_model(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field2);
					ggt_3 = calc_tess_model(&model[n_tesseroid], 1, lon, lat, height + MEAN_EARTH_RADIUS, glq_lon, glq_lat, glq_r, field3);

					res = res + M_0*EOTVOS2SI*(ggt_1 * M_vect_p[0]  + ggt_2 * M_vect_p[1] + ggt_3 * M_vect_p[2]) /(G*model[n_tesseroid].density*4*PI);
				}
				/////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            printf("%s %.15g\n", buff, res);
            points++;
        }
    }
    if(bad_input)
    {
        log_warning("Encountered %d bad computation points which were skipped",
                    bad_input);
    }
    if(error_exit)
    {
        log_warning("Terminating due to error in input");
        log_warning("Try '%s -h' for instructions", progname);
    }
    else
    {
        log_info("Calculated on %d points in %.5g seconds", points,
                 (double)(clock() - tstart)/CLOCKS_PER_SEC);
    }
    /* Clean up */
    free(model);
    glq_free(glq_lon);
    glq_free(glq_lat);
    glq_free(glq_r);
    log_info("Done");
    if(args.logtofile)
        fclose(logfile);
    return 0;
}
コード例 #28
0
static play_tree_t*
parse_pls(play_tree_parser_t* p) {
    char *line,*v;
    pls_entry_t* entries = NULL;
    int n_entries = 0,max_entry=0,num;
    play_tree_t *list = NULL, *entry = NULL, *last_entry = NULL;

    mp_msg(MSGT_PLAYTREE,MSGL_V,"Trying Winamp playlist...\n");
    while((line = play_tree_parser_get_line(p))) {
        strstrip(line);
        if(strlen(line))
            break;
    }
    if (!line)
        return NULL;
    if(strcasecmp(line,"[playlist]"))
        return NULL;
    mp_msg(MSGT_PLAYTREE,MSGL_V,"Detected Winamp playlist format\n");
    play_tree_parser_stop_keeping(p);
    line = play_tree_parser_get_line(p);
    if(!line)
        return NULL;
    strstrip(line);
    if(strncasecmp(line,"NumberOfEntries",15) == 0) {
        v = pls_entry_get_value(line);
        n_entries = atoi(v);
        if(n_entries < 0)
            mp_msg(MSGT_PLAYTREE,MSGL_DBG2,"Invalid number of entries: very funny!!!\n");
        else
            mp_msg(MSGT_PLAYTREE,MSGL_DBG2,"Playlist claims to have %d entries. Let's see.\n",n_entries);
        line = play_tree_parser_get_line(p);
    }

    while(line) {
        strstrip(line);
        if(line[0] == '\0') {
            line = play_tree_parser_get_line(p);
            continue;
        }
        if(strncasecmp(line,"File",4) == 0) {
            num = pls_read_entry(line+4,&entries,&max_entry,&v);
            if(num < 0)
                mp_msg(MSGT_PLAYTREE,MSGL_ERR,"No value in entry %s\n",line);
            else
                entries[num-1].file = strdup(v);
        } else if(strncasecmp(line,"Title",5) == 0) {
            num = pls_read_entry(line+5,&entries,&max_entry,&v);
            if(num < 0)
                mp_msg(MSGT_PLAYTREE,MSGL_ERR,"No value in entry %s\n",line);
            else
                entries[num-1].title = strdup(v);
        } else if(strncasecmp(line,"Length",6) == 0) {
            num = pls_read_entry(line+6,&entries,&max_entry,&v);
            if(num < 0)
                mp_msg(MSGT_PLAYTREE,MSGL_ERR,"No value in entry %s\n",line);
            else
                entries[num-1].length = strdup(v);
        } else
            mp_msg(MSGT_PLAYTREE,MSGL_WARN,"Unknown entry type %s\n",line);
        line = play_tree_parser_get_line(p);
    }

    for(num = 0; num < max_entry ; num++) {
        if(entries[num].file == NULL)
            mp_msg(MSGT_PLAYTREE,MSGL_ERR,"Entry %d don't have a file !!!!\n",num+1);
        else {
            mp_msg(MSGT_PLAYTREE,MSGL_DBG2,"Adding entry %s\n",entries[num].file);
            entry = play_tree_new();
            play_tree_add_file(entry,entries[num].file);
            free(entries[num].file);
            if(list)
                play_tree_append_entry(last_entry,entry);
            else
                list = entry;
            last_entry = entry;
        }
        if(entries[num].title) {
            // When we have info in playtree we add this info
            free(entries[num].title);
        }
        if(entries[num].length) {
            // When we have info in playtree we add this info
            free(entries[num].length);
        }
    }

    free(entries);

    entry = play_tree_new();
    play_tree_set_child(entry,list);
    return entry;
}
コード例 #29
0
ファイル: iniparser.c プロジェクト: ansi88/iniparser
/*--------------------------------------------------------------------------*/
static line_status iniparser_line(
    const char * input_line,
    char * section,
    char * key,
    char * value)
{
    line_status sta ;
    char * line = NULL;
    size_t      len ;

    line = xstrdup(input_line);
    len = strstrip(line);

    sta = LINE_UNPROCESSED ;
    if (len<1) {
        /* Empty line */
        sta = LINE_EMPTY ;
    } else if (line[0]=='#' || line[0]==';') {
        /* Comment line */
        sta = LINE_COMMENT ;
    } else if (line[0]=='[' && line[len-1]==']') {
        /* Section name */
        sscanf(line, "[%[^]]", section);
        strstrip(section);
        strlwc(section, section, len);
        sta = LINE_SECTION ;
    } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
           ||  sscanf (line, "%[^=] = '%[^\']'",   key, value) == 2) {
        /* Usual key=value with quotes, with or without comments */
        strstrip(key);
        strlwc(key, key, len);
        /* Don't strip spaces from values surrounded with quotes */
        sta = LINE_VALUE ;
    } else if (sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
        /* Usual key=value without quotes, with or without comments */
        strstrip(key);
        strlwc(key, key, len);
        strstrip(value);
        /*
         * sscanf cannot handle '' or "" as empty values
         * this is done here
         */
        if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
            value[0]=0 ;
        }
        sta = LINE_VALUE ;
    } else if (sscanf(line, "%[^=] = %[;#]", key, value)==2
           ||  sscanf(line, "%[^=] %[=]", key, value) == 2) {
        /*
         * Special cases:
         * key=
         * key=;
         * key=#
         */
        strstrip(key);
        strlwc(key, key, len);
        value[0]=0 ;
        sta = LINE_VALUE ;
    } else {
        /* Generate syntax error */
        sta = LINE_ERROR ;
    }

    free(line);
    return sta ;
}
コード例 #30
0
static ssize_t rsc_ops_write(struct file *fp, const char __user *user_buffer,
						size_t count, loff_t *position)
{
	char buf[MAX_MSG_BUFFER], rsc_type_str[6] = {}, rpm_set[8] = {},
						key_str[6] = {};
	int i, pos, set = -1, nelems;
	char *cmp;
	uint32_t rsc_type, rsc_id, key, data;
	struct msm_rpm_request *req;

	count = min(count, sizeof(buf) - 1);
	if (copy_from_user(&buf, user_buffer, count))
		return -EFAULT;
	buf[count] = '\0';
	cmp = strstrip(buf);

	sscanf(cmp, "%7s %5s %u %d %n", rpm_set, rsc_type_str, &rsc_id,
							&nelems, &pos);
	if (strlen(rpm_set) > 6 || strlen(rsc_type_str) > 4) {
		pr_err("Invalid value of set or resource type\n");
		goto err;
	}

	if (!strcmp(rpm_set, "active"))
		set = 0;
	else if (!strcmp(rpm_set, "sleep"))
		set = 1;

	rsc_type = string_to_uint(rsc_type_str);

	if (set < 0 || nelems < 0) {
		pr_err("Invalid value of set or nelems\n");
		goto err;
	}
	if (nelems > MAX_KEY_VALUE_PAIRS) {
		pr_err("Exceeded max no of key-value entries\n");
		goto err;
	}

	req = msm_rpm_create_request(set, rsc_type, rsc_id, nelems);
	if (!req)
		return -ENOMEM;

	for (i = 0; i < nelems; i++) {
		cmp += pos;
		sscanf(cmp, "%5s %n", key_str, &pos);
		if (strlen(key_str) > 4) {
			pr_err("Key value cannot be more than 4 charecters");
			goto err;
		}
		key = string_to_uint(key_str);
		if (!key) {
			pr_err("Key values entered incorrectly\n");
			goto err;
		}

		cmp += pos;
		sscanf(cmp, "%u %n", &data, &pos);
		if (msm_rpm_add_kvp_data(req, key,
				(void *)&data, sizeof(data)))
			goto err_request;
	}

	if (msm_rpm_wait_for_ack(msm_rpm_send_request(req)))
		pr_err("Sending the RPM message failed\n");
	else
		pr_info("RPM message sent succesfully\n");

err_request:
	msm_rpm_free_request(req);
err:
	return count;
}