Example #1
0
static void
pmaps(int pid, print_flags_t pflags, regex_t *regex, int fd_kflags, int fd_kcount)
{
	FILE *maps = NULL;
	int fd_p=-1;
	unsigned long start_addr, end_addr;
	char *line=0;
	size_t line_n=0;
	maps = fopen(proc_fn(pid, "maps"), "r");
	if (!maps) {
		fprintf(stderr,
			"ERROR: could not open /proc/%d/maps: %s\n",
			pid, strerror(errno));
		goto done;
	}
	fd_p = open(proc_fn(pid, "pagemap"), O_RDONLY);
	if (fd_p<0) {
		fprintf(stderr,
			"ERROR: could not open /proc/%d/pagemap: %s\n",
			pid, strerror(errno));
		goto done;
	}
	while (1) {
		int ret = getline(&line, &line_n, maps);
		if (ret == -1) {
			goto done;
		}
		if (pflags & STACK_ONLY) {
			if (strstr(line, "[stack]") == NULL)
				continue;
		} else if (pflags & HEAP_ONLY) {
			if (strstr(line, "[heap]") == NULL)
				continue;
		} else if (regex) {
			if (regexec(regex, line, 0, NULL, 0) != 0)
				continue;
		}
		if (sscanf(line, "%lx-%lx", &start_addr, &end_addr) != 2) {
			(void) fprintf(stderr,
			"ERROR: did not understand line from /proc/pid/maps. :(\n");
			goto done;
		}
		(void) printf("%s", line);
		unsigned long page_start = start_addr / pagesize;
		unsigned long page_end = end_addr / pagesize;
		x_lseek(fd_p, sizeof(uint64_t)*page_start, SEEK_SET);
		unsigned long nr_read = 0;
		unsigned long nr_read_total = 0;
		for (; page_start < page_end; page_start += BSIZE, nr_read_total += nr_read) {
			nr_read = min_ul(page_end-page_start, BSIZE);
			if (read(fd_p, pagemap, nr_read*sizeof(uint64_t))
					!= (ssize_t)(nr_read*sizeof(uint64_t))) {
				// Reading the /proc/pid/pagemap entry for
				// /proc/pid/maps [vsyscall] resulted in zero
				// byte reads. Let's just ignore such cases.
				continue;
			}
			populate(fd_kflags, pageflags, nr_read);
			populate(fd_kcount, pagecount, nr_read);
			for (unsigned i=0; i < nr_read; ++i) {
				if (PMAP_PRESENT&pagemap[i] && !(pflags & SWAPPED_ONLY)) {
					printf("    %#lx -> pfn:%#08llx count:%4llu flags:%s\n",
					       start_addr + (nr_read_total+i)*pagesize,
					       PMAP_PFN&pagemap[i],
					       (unsigned long long)pagecount[i],
					       flags2str(pageflags[i]));
				} else if (PMAP_SWAPPED&pagemap[i] && !(pflags & RESIDENT_ONLY)) {
					printf("   #%#lx -> swaptype:%#llx swapoff:%#08llx\n",
					       start_addr + (nr_read_total+i)*pagesize,
					       PMAP_SWAP_TYPE&pagemap[i],
					       (PMAP_SWAP_OFF&pagemap[i])>>5);
				} else if (!(pflags & (SWAPPED_ONLY|RESIDENT_ONLY))) {
					printf("   !%#lx\n",
					       start_addr + (nr_read_total+i)*pagesize);
				}
			}
		}
Example #2
0
int checkCoordinates(struct gpsCoordinates gpsData, struct repeater repeater){

        regex_t regex;
        int reti;



        reti = regcomp(&regex, "^[0-9][0-9][0-9][0-9][.][0-9][0-9][NZ]$", 0);
        if(reti){
                syslog(LOG_NOTICE,"[%s]Hyt GPS decode,could not compile regex latitude",repeater.callsign);
                return 0;
        }
        reti = regexec(&regex,gpsData.latitude,0,NULL,0);
        if(reti == REG_NOMATCH){
                syslog(LOG_NOTICE,"[%s]Corrupt latitude received",repeater.callsign);
                regfree(&regex);
                return 0;
        }
        regfree(&regex);

        reti = regcomp(&regex, "^[0-9][0-9][0-9][0-9][0-9][.][0-9][0-9][EW]$", 0);
        if(reti){
                syslog(LOG_NOTICE,"[%s]Hyt GPS decode,could not compile regex longitude",repeater.callsign);
                regfree(&regex);
                return 0;
        }
        reti = regexec(&regex,gpsData.longitude,0,NULL,0);
        if(reti == REG_NOMATCH){
                syslog(LOG_NOTICE,"[%s]Corrupt longitude received",repeater.callsign);
                regfree(&regex);
                return 0;
        }

        reti = regcomp(&regex, "^[0-9][0-9][0-9]$", 0);
        if(reti){
                syslog(LOG_NOTICE,"[%s]Hyt GPS decode,could not compile regex heading",repeater.callsign);
                regfree(&regex);
                return 0;
        }
        reti = regexec(&regex,gpsData.heading,0,NULL,0);
        if(reti == REG_NOMATCH){
                syslog(LOG_NOTICE,"[%s]Corrupt heading received",repeater.callsign);
                regfree(&regex);
                return 0;
        }

        reti = regcomp(&regex, "^[0-9.][0-9.][0-9.]$", 0);
        if(reti){
                syslog(LOG_NOTICE,"[%s]Hyt GPS decode,could not compile regex speed",repeater.callsign);
                regfree(&regex);
                return 0;
        }
        reti = regexec(&regex,gpsData.speed,0,NULL,0);
        if(reti == REG_NOMATCH){
                syslog(LOG_NOTICE,"[%s]Corrupt speed received",repeater.callsign);
                regfree(&regex);
                return 0;
        }

        regfree(&regex);
	return 1;
} 
Example #3
0
static char *find_matching(char *buf, size_t size, const char *dir,
                           const char *lib)
{
    char           pattern[PATH_MAX], path[PATH_MAX], *p;
    const char    *l;
    int            len, prfx, ok;
    DIR           *dp;
    struct dirent *de;
    regex_t        re;
    regmatch_t     rm;

    if (strchr(lib, '*') == NULL && strchr(lib, '?') == NULL) {
        if ((size_t)snprintf(buf, size, "%s/%s", dir, lib) >= size)
            return NULL;
        if (access(buf, R_OK) == 0)
            return buf;
        else
            return NULL;
    }

    if ((dp = opendir(dir)) == NULL)
        return NULL;

    p    = pattern;
    l    = lib;
    len  = size;
    prfx = -1;
    while (len > 1 && *l) {
        switch (*l) {
        case '?':
        case '*':
            if (len <= 3)
                goto fail;

            if (prfx < 0)
                prfx = (p - pattern);

            *p++ = '.';
            *p++ = *l++;
            len -= 2;
            break;

        case '.':
            if (len <= 3)
                goto fail;

            if (prfx < 0)
                prfx = (p - pattern);

            *p++ = '\\';
            *p++ = *l++;
            len -= 2;
            break;

        default:
            *p++ = *l++;
            len--;
        }
    }

    *p = '\0';

    mrp_debug("regex pattern to match: '%s'", pattern);

    if (regcomp(&re, pattern, REG_NOSUB) != 0)
        goto fail;

    while ((de = readdir(dp)) != NULL) {
        if (de->d_type == DT_REG) {
        check_match:
            if (prfx > 0 && strncmp(de->d_name, pattern, prfx) != 0)
                continue;

            if (regexec(&re, de->d_name, 1, &rm, 0) != 0)
                continue;

            ok = (size_t)snprintf(buf, size, "%s/%s", dir, de->d_name) < size;

            closedir(dp);
            regfree(&re);

            return ok ? buf : NULL;
        }
        else if (de->d_type == DT_LNK) {
            struct stat st;

            snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);

            if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
                goto check_match;
        }
    }

    closedir(dp);
    regfree(&re);

    return NULL;

 fail:
    if (dp != NULL)
        closedir(dp);
    return NULL;
}
char * rewrite_stylesheet_urls(const char *source, unsigned int size,
		int *osize, const char *base,
		struct save_complete_entry *list)
{
	char *res;
	const char *url;
	char *url2;
	char buf[20];
	unsigned int offset = 0;
	int url_len = 0;
	hlcache_handle *content;
	int m;
	unsigned int i;
	unsigned int imports = 0;
	regmatch_t match[11];
	url_func_result result;

	/* count number occurences of @import to (over)estimate result size */
	/* can't use strstr because source is not 0-terminated string */
	for (i = 0; 7 < size && i != size - 7; i++) {
		if (source[i] == '@' &&
				tolower(source[i + 1]) == 'i' &&
				tolower(source[i + 2]) == 'm' &&
				tolower(source[i + 3]) == 'p' &&
				tolower(source[i + 4]) == 'o' &&
				tolower(source[i + 5]) == 'r' &&
				tolower(source[i + 6]) == 't')
			imports++;
	}

	res = malloc(size + imports * 20);
	if (!res)
		return 0;
	*osize = 0;

	while (offset < size) {
		m = regexec(&save_complete_import_re, source + offset,
				11, match, 0);
		if (m)
			break;

		/*for (unsigned int i = 0; i != 11; i++) {
			if (match[i].rm_so == -1)
				continue;
			fprintf(stderr, "%i: '%.*s'\n", i,
					match[i].rm_eo - match[i].rm_so,
					source + offset + match[i].rm_so);
		}*/

		url = 0;
		if (match[2].rm_so != -1) {
			url = source + offset + match[2].rm_so;
			url_len = match[2].rm_eo - match[2].rm_so;
		} else if (match[4].rm_so != -1) {
			url = source + offset + match[4].rm_so;
			url_len = match[4].rm_eo - match[4].rm_so;
		} else if (match[6].rm_so != -1) {
			url = source + offset + match[6].rm_so;
			url_len = match[6].rm_eo - match[6].rm_so;
		} else if (match[8].rm_so != -1) {
			url = source + offset + match[8].rm_so;
			url_len = match[8].rm_eo - match[8].rm_so;
		} else if (match[10].rm_so != -1) {
			url = source + offset + match[10].rm_so;
			url_len = match[10].rm_eo - match[10].rm_so;
		}
		assert(url);

		url2 = strndup(url, url_len);
		if (!url2) {
			free(res);
			return 0;
		}
		result = url_join(url2, base, (char**)&url);
		free(url2);
		if (result == URL_FUNC_NOMEM) {
			free(res);
			return 0;
		}

		/* copy data before match */
		memcpy(res + *osize, source + offset, match[0].rm_so);
		*osize += match[0].rm_so;

		if (result == URL_FUNC_OK) {
			content = save_complete_list_find(url, list);
			if (content) {
				/* replace import */
				snprintf(buf, sizeof buf, "@import '%p'",
						content);
				memcpy(res + *osize, buf, strlen(buf));
				*osize += strlen(buf);
			} else {
				/* copy import */
				memcpy(res + *osize, source + offset + match[0].rm_so,
					match[0].rm_eo - match[0].rm_so);
				*osize += match[0].rm_eo - match[0].rm_so;
			}
		}
		else {
			/* copy import */
			memcpy(res + *osize, source + offset + match[0].rm_so,
				match[0].rm_eo - match[0].rm_so);
			*osize += match[0].rm_eo - match[0].rm_so;
		}

		assert(0 < match[0].rm_eo);
		offset += match[0].rm_eo;
	}

	/* copy rest of source */
	if (offset < size) {
		memcpy(res + *osize, source + offset, size - offset);
		*osize += size - offset;
	}

	return res;
}
// Polls for and processes events for all present joysticks
//
static void pollJoystickEvents(void)
{
#if defined(__linux__)
    int i;
    struct js_event e;
    ssize_t offset = 0;
    char buffer[16384];

    const ssize_t size = read(_glfw.linux_js.inotify, buffer, sizeof(buffer));

    while (size > offset)
    {
        regmatch_t match;
        const struct inotify_event* e = (struct inotify_event*) (buffer + offset);

        if (regexec(&_glfw.linux_js.regex, e->name, 1, &match, 0) == 0)
        {
            char path[20];
            snprintf(path, sizeof(path), "/dev/input/%s", e->name);
            openJoystickDevice(path);
        }

        offset += sizeof(struct inotify_event) + e->len;
    }

    for (i = 0;  i <= GLFW_JOYSTICK_LAST;  i++)
    {
        if (!_glfw.linux_js.js[i].present)
            continue;

        // Read all queued events (non-blocking)
        for (;;)
        {
            errno = 0;
            if (read(_glfw.linux_js.js[i].fd, &e, sizeof(e)) < 0)
            {
                if (errno == ENODEV)
                {
                    // The joystick was disconnected

                    free(_glfw.linux_js.js[i].axes);
                    free(_glfw.linux_js.js[i].buttons);
                    free(_glfw.linux_js.js[i].name);
                    free(_glfw.linux_js.js[i].path);

                    memset(&_glfw.linux_js.js[i], 0, sizeof(_glfw.linux_js.js[i]));
                }

                break;
            }

            // We don't care if it's an init event or not
            e.type &= ~JS_EVENT_INIT;

            switch (e.type)
            {
                case JS_EVENT_AXIS:
                    _glfw.linux_js.js[i].axes[e.number] =
                        (float) e.value / 32767.0f;
                    break;

                case JS_EVENT_BUTTON:
                    _glfw.linux_js.js[i].buttons[e.number] =
                        e.value ? GLFW_PRESS : GLFW_RELEASE;
                    break;

                default:
                    break;
            }
        }
    }
#endif // __linux__
}
Example #6
0
static int
update_princ_encryption_1(void *cb, krb5_db_entry *ent)
{
    struct update_enc_mkvno *p = cb;
    char *pname = 0;
    krb5_error_code retval;
    int match;
    krb5_timestamp now;
    int result;
    krb5_kvno old_mkvno;

    retval = krb5_unparse_name(util_context, ent->princ, &pname);
    if (retval) {
        com_err(progname, retval,
                _("getting string representation of principal name"));
        goto fail;
    }

    if (krb5_principal_compare(util_context, ent->princ, master_princ)) {
        goto skip;
    }

#ifdef SOLARIS_REGEXPS
    match = (step(pname, p->expbuf) != 0);
#endif
#ifdef POSIX_REGEXPS
    match = (regexec(&p->preg, pname, 0, NULL, 0) == 0);
#endif
#ifdef BSD_REGEXPS
    match = (re_exec(pname) != 0);
#endif
    if (!match) {
        goto skip;
    }
    p->re_match_count++;
    retval = krb5_dbe_get_mkvno(util_context, ent, &old_mkvno);
    if (retval) {
        com_err(progname, retval,
                _("determining master key used for principal '%s'"), pname);
        goto fail;
    }
    /* Line up "skip" and "update" messages for viewing.  */
    if (old_mkvno == new_mkvno) {
        if (p->dry_run && p->verbose)
            printf(_("would skip:   %s\n"), pname);
        else if (p->verbose)
            printf(_("skipping: %s\n"), pname);
        p->already_current++;
        goto skip;
    }
    if (p->dry_run) {
        if (p->verbose)
            printf(_("would update: %s\n"), pname);
        p->updated++;
        goto skip;
    } else if (p->verbose)
        printf(_("updating: %s\n"), pname);
    retval = master_key_convert (util_context, ent);
    if (retval) {
        com_err(progname, retval,
                _("error re-encrypting key for principal '%s'"), pname);
        goto fail;
    }
    if ((retval = krb5_timeofday(util_context, &now))) {
        com_err(progname, retval, _("while getting current time"));
        goto fail;
    }

    if ((retval = krb5_dbe_update_mod_princ_data(util_context, ent,
                                                 now, master_princ))) {
        com_err(progname, retval,
                _("while updating principal '%s' modification time"), pname);
        goto fail;
    }

    ent->mask |= KADM5_KEY_DATA;

    if ((retval = krb5_db_put_principal(util_context, ent))) {
        com_err(progname, retval, _("while updating principal '%s' key data "
                                    "in the database"), pname);
        goto fail;
    }
    p->updated++;
skip:
    result = 0;
    goto egress;
fail:
    exit_status++;
    result = 1;
egress:
    if (pname)
        krb5_free_unparsed_name(util_context, pname);
    return result;
}
Example #7
0
static char *save_complete_rewrite_stylesheet_urls(save_complete_ctx *ctx,
		const char *source, unsigned long size, const nsurl *base,
		unsigned long *osize)
{
	char *rewritten;
	unsigned long offset = 0;
	unsigned int imports = 0;
	nserror error;

	/* count number occurrences of @import to (over)estimate result size */
	/* can't use strstr because source is not 0-terminated string */
	for (offset = 0; SLEN("@import") < size &&
			offset <= size - SLEN("@import"); offset++) {
		if (source[offset] == '@' &&
				tolower(source[offset + 1]) == 'i' &&
				tolower(source[offset + 2]) == 'm' &&
				tolower(source[offset + 3]) == 'p' &&
				tolower(source[offset + 4]) == 'o' &&
				tolower(source[offset + 5]) == 'r' &&
				tolower(source[offset + 6]) == 't')
			imports++;
	}

	rewritten = malloc(size + imports * 20);
	if (rewritten == NULL)
		return NULL;
	*osize = 0;

	offset = 0;
	while (offset < size) {
		const char *import_url = NULL;
		char *import_url_copy;
		int import_url_len = 0;
		nsurl *url = NULL;
		regmatch_t match[11];
		int m = regexec(&save_complete_import_re, source + offset,
				11, match, 0);
		if (m)
			break;

		if (match[2].rm_so != -1) {
			import_url = source + offset + match[2].rm_so;
			import_url_len = match[2].rm_eo - match[2].rm_so;
		} else if (match[4].rm_so != -1) {
			import_url = source + offset + match[4].rm_so;
			import_url_len = match[4].rm_eo - match[4].rm_so;
		} else if (match[6].rm_so != -1) {
			import_url = source + offset + match[6].rm_so;
			import_url_len = match[6].rm_eo - match[6].rm_so;
		} else if (match[8].rm_so != -1) {
			import_url = source + offset + match[8].rm_so;
			import_url_len = match[8].rm_eo - match[8].rm_so;
		} else if (match[10].rm_so != -1) {
			import_url = source + offset + match[10].rm_so;
			import_url_len = match[10].rm_eo - match[10].rm_so;
		}
		assert(import_url != NULL);

		import_url_copy = strndup(import_url, import_url_len);
		if (import_url_copy == NULL) {
			free(rewritten);
			return NULL;
		}

		error = nsurl_join(base, import_url_copy, &url);
		free(import_url_copy);
		if (error == NSERROR_NOMEM) {
			free(rewritten);
			return NULL;
		}

		/* copy data before match */
		memcpy(rewritten + *osize, source + offset, match[0].rm_so);
		*osize += match[0].rm_so;

		if (url != NULL) {
			hlcache_handle *content;
			content = save_complete_ctx_find_content(ctx, url);
			if (content != NULL) {
				/* replace import */
				char buf[64];
				snprintf(buf, sizeof buf, "@import '%p'",
						content);
				memcpy(rewritten + *osize, buf, strlen(buf));
				*osize += strlen(buf);
			} else {
				/* copy import */
				memcpy(rewritten + *osize,
					source + offset + match[0].rm_so,
					match[0].rm_eo - match[0].rm_so);
				*osize += match[0].rm_eo - match[0].rm_so;
			}
			nsurl_unref(url);
		} else {
			/* copy import */
			memcpy(rewritten + *osize,
				source + offset + match[0].rm_so,
				match[0].rm_eo - match[0].rm_so);
			*osize += match[0].rm_eo - match[0].rm_so;
		}

		assert(0 < match[0].rm_eo);
		offset += match[0].rm_eo;
	}

	/* copy rest of source */
	if (offset < size) {
		memcpy(rewritten + *osize, source + offset, size - offset);
		*osize += size - offset;
	}

	return rewritten;
}
Example #8
0
int clear_name_png(char *name)
{
return !regexec(&write_png, name, 0, NULL, 0);
}
Example #9
0
int
sdp_mangle_ip (struct sip_msg *msg, char *oldip, char *newip)
{
	int i, old_content_length, new_content_length;
	int diff, oldlen, len, off, ret, need_to_deallocate;
	unsigned int mask, address, locatedIp;
	struct lump *l;
	regmatch_t pmatch;
	regex_t *re;
	char *s, *pos, *begin, *key;
	char buffer[16];	/* 123.456.789.123\0 */
	str body;

#ifdef DEBUG
	fprintf (stdout,"---START--------MANGLE IP-----------------\n");
#endif


	key = IP_REGEX;

	/*
	 * Checking if msg has a payload
	 */
	if (msg == NULL)
	{
		LM_ERR("msg null\n");
		return -1;
	}

	if ( get_body(msg,&body)!=0 || body.len==0)
	{
		LM_ERR(" failed to get a body \n");
		return -2;
	}

	old_content_length = get_content_length(msg);

	/* checking oldip */
	if (oldip == NULL)
		{
		LM_ERR("received NULL for oldip\n");
		return -3;
		}
	/* checking newip */
	if (newip == NULL)
		{
		LM_ERR("received NULL for newip\n");
		return -4;
		}
	i = parse_ip_netmask (oldip, &pos, &mask);

	if (i == -1)
	{
		/* invalid value for the netmask specified in oldip */
		LM_ERR("invalid value for the netmask specified in oldip\n");
		return -5;
	}
	else
	{
		i = parse_ip_address (pos, &address);
		if (pos != NULL) free (pos);
		if (i == 0)
			{
			LM_ERR("invalid value for the ip specified in oldip\n");
			return -6;	/* parse error in ip */
			}
	}

	/* now we have in address/netmask binary values */

	begin = body.s;
	ret = -1;
	len = strlen (newip);

	/* try to use pre-compiled expressions */
	need_to_deallocate = 0;
	if (ipExpression != NULL)
		{
		re = ipExpression;
#ifdef DEBUG
		fprintf(stdout,"Using PRECOMPILED expression for ip ...\n");
#endif

		}
		else /* we are not using pre-compiled expressions */
			{
			re = pkg_malloc(sizeof(regex_t));
			if (re == NULL)
				{
				LM_ERR("unable to allocate re in pkg mem\n");
				return -7;
				}
			need_to_deallocate = 1;
			if ((regcomp (re, key, REG_EXTENDED)) != 0)
				{
				LM_ERR("unable to compile %s \n",key);
				return -8;
				}
#ifdef DEBUG
		fprintf(stdout,"Using ALLOCATED expression for ip ...\n");
#endif
			}

	diff = 0;
	while ((begin < msg->buf + msg->len) && (regexec (re, begin, 1, &pmatch, 0) == 0))
	{
		off = begin - msg->buf;
		if (pmatch.rm_so == -1)
		{
			LM_ERR("offset unknown\n");
			return -9;
		}

#ifdef STRICT_CHECK
		pmatch.rm_eo --; /* return with one space,\n,\r */
#endif

		/*
                for BSD and Solaris we avoid memrchr
                pos = (char *) memrchr (begin + pmatch.rm_so, ' ',pmatch.rm_eo - pmatch.rm_so);
                */
                pos = begin+pmatch.rm_eo;
                do pos--; while (*pos != ' '); /* we should find ' ' because we matched c=IN IP4 ip */

		pos++;		/* jumping over space */
		oldlen = (pmatch.rm_eo - pmatch.rm_so) - (pos - (begin + pmatch.rm_so));	/* ip length */
		if (oldlen > 15)
		{
			LM_WARN("silent fail because oldlen > 15\n");
#ifdef STRICT_CHECK
			return -10;
#else
			goto continue2;	/* silent fail return -10; invalid ip format ,probably like 1000.3.12341.2 */
#endif


		}
		buffer[0] = '\0';
		strncat ((char *) buffer, pos, oldlen);
		buffer[oldlen] = '\0';
		i = parse_ip_address (buffer, &locatedIp);
		if (i == 0)
		{
			LM_WARN("silent fail on parsing matched address \n");

#ifdef STRICT_CHECK
			return -11;
#else
			goto continue2;
#endif
		}
		if (same_net (locatedIp, address, mask) == 0)
		{
			LM_WARN("silent fail because matched address is not in network\n");
#ifdef DEBUG
		fprintf(stdout,"Extracted ip is %s and not mangling \n",buffer);
#endif
			goto continue2;	/* not in the same net, skipping */
		}
#ifdef DEBUG
		fprintf(stdout,"Extracted ip is %s and mangling to %s\n",buffer,newip);
#endif


		/* replacing ip */

		/* deleting old ip */
		if ((l = del_lump (msg,pmatch.rm_so + off +
						(pos - (begin + pmatch.rm_so)),oldlen, 0)) == 0)
		{
			LM_ERR("del_lump failed\n");
			return -12;
		}
		s = pkg_malloc (len);
		if (s == 0)
		{
			LM_ERR("no more pkg mem\n");
			return -13;
		}
		memcpy (s, newip, len);

		if (insert_new_lump_after (l, s, len, 0) == 0)
		{
			LM_ERR("could not insert new lump\n");
			pkg_free (s);
			return -14;
		}
		diff = diff + len /*new length */  - oldlen;
		/* new cycle */
		ret++;
continue2:
		begin = begin + pmatch.rm_eo;

	}			/* while */
	if (need_to_deallocate)
	{
		regfree (re);		/* if I am going to use pre-compiled expressions to be removed */
		pkg_free(re);
#ifdef DEBUG
		fprintf(stdout,"Deallocating expression for ip ...\n");
#endif
	}

	if (diff != 0)
	{
		new_content_length = old_content_length + diff;
		patch_content_length (msg, new_content_length);
	}

#ifdef DEBUG
	fprintf (stdout,"---END--------MANGLE IP-----------------\n");
#endif

	return ret+2;

}
Example #10
0
static bool
rematch (const char *re, const char *s)
{
  /*
   * If this system has regular expression capability, then
   * add support for regular expressions in the skip lists.
   */

#if defined(HAVE_REGCOMP)

  int result;
  regmatch_t match;
  regex_t compiled;

  /* compile the regular expression */
  result = regcomp (&compiled, re, REG_EXTENDED | REG_ICASE | REG_NOSUB);
  if (result)
    {
      char errorstring[128];

      regerror (result, &compiled, errorstring, sizeof (errorstring));
      Message ("regexp error: %s\n", errorstring);
      regfree (&compiled);
      return (false);
    }

  result = regexec (&compiled, s, 1, &match, 0);
  regfree (&compiled);

  if (result == 0)
    return (true);
  else
    return (false);

#elif defined(HAVE_RE_COMP)
  int m;
  char *rslt;

  /* compile the regular expression */
  if ((rslt = re_comp (re)) != NULL)
    {
      Message ("re_comp error: %s\n", rslt);
      return (false);
    }

  m = re_exec (s);

  switch m
    {
    case 1:
      return (true);
      break;

    case 0:
      return (false);
      break;

    default:
      Message ("re_exec error\n");
      break;
    }

#else
  return (false);
#endif

}
Example #11
0
int clear_name_dat(char *name)
{
return !regexec(&write_dat, name, 0, NULL, 0);
}
Example #12
0
/** Compares check and vp by value.
 *
 * Does not call any per-attribute comparison function, but does honour
 * check.operator. Basically does "vp.value check.op check.value".
 *
 * @param request Current request.
 * @param check rvalue, and operator.
 * @param vp lvalue.
 * @return 0 if check and vp are equal, -1 if vp value is less than check value, 1 is vp value is more than check
 *	value, -2 on error.
 */
int radius_compare_vps(REQUEST *request, VALUE_PAIR *check, VALUE_PAIR *vp)
{
	int ret = 0;

	/*
	 *      Check for =* and !* and return appropriately
	 */
	if (check->op == T_OP_CMP_TRUE)  return 0;
	if (check->op == T_OP_CMP_FALSE) return 1;

#ifdef HAVE_REGEX_H
	if (check->op == T_OP_REG_EQ) {
		int compare;
		regex_t reg;
		char value[1024];
		regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];

		vp_prints_value(value, sizeof(value), vp, -1);

		/*
		 *	Include substring matches.
		 */
		compare = regcomp(&reg, check->vp_strvalue, REG_EXTENDED);
		if (compare != 0) {
			char buffer[256];
			regerror(compare, &reg, buffer, sizeof(buffer));

			RDEBUG("Invalid regular expression %s: %s", check->vp_strvalue, buffer);
			return -2;
		}

		memset(&rxmatch, 0, sizeof(rxmatch));	/* regexec does not seem to initialise unused elements */
		compare = regexec(&reg, value, REQUEST_MAX_REGEX + 1, rxmatch, 0);
		regfree(&reg);
		rad_regcapture(request, compare, value, rxmatch);

		ret = (compare == 0) ? 0 : -1;
		goto finish;
	}

	if (check->op == T_OP_REG_NE) {
		int compare;
		regex_t reg;
		char value[1024];
		regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];

		vp_prints_value(value, sizeof(value), vp, -1);

		/*
		 *	Include substring matches.
		 */
		compare = regcomp(&reg, check->vp_strvalue, REG_EXTENDED);
		if (compare != 0) {
			char buffer[256];
			regerror(compare, &reg, buffer, sizeof(buffer));

			RDEBUG("Invalid regular expression %s: %s", check->vp_strvalue, buffer);
			return -2;
		}
		compare = regexec(&reg, value,  REQUEST_MAX_REGEX + 1, rxmatch, 0);
		regfree(&reg);

		ret = (compare != 0) ? 0 : -1;
	}
#endif

	/*
	 *	Attributes must be of the same type.
	 *
	 *	FIXME: deal with type mismatch properly if one side contain
	 *	ABINARY, OCTETS or STRING by converting the other side to
	 *	a string
	 *
	 */
	if (vp->da->type != check->da->type) return -1;

	/*
	 *	Tagged attributes are equal if and only if both the
	 *	tag AND value match.
	 */
	if (check->da->flags.has_tag && !TAG_EQ(check->tag, vp->tag)) {
		ret = ((int) vp->tag) - ((int) check->tag);
		if (ret != 0) goto finish;
	}

	/*
	 *	Not a regular expression, compare the types.
	 */
	switch(check->da->type) {
#ifdef WITH_ASCEND_BINARY
		/*
		 *	Ascend binary attributes can be treated
		 *	as opaque objects, I guess...
		 */
		case PW_TYPE_ABINARY:
#endif
		case PW_TYPE_OCTETS:
			if (vp->length != check->length) {
				ret = 1; /* NOT equal */
				break;
			}
			ret = memcmp(vp->vp_strvalue, check->vp_strvalue,
				     vp->length);
			break;

		case PW_TYPE_STRING:
			ret = strcmp(vp->vp_strvalue,
				     check->vp_strvalue);
			break;

		case PW_TYPE_BYTE:
		case PW_TYPE_SHORT:
		case PW_TYPE_INTEGER:
			ret = vp->vp_integer - check->vp_integer;
			break;

		case PW_TYPE_INTEGER64:
			/*
			 *	Don't want integer overflow!
			 */
			if (vp->vp_integer64 < check->vp_integer64) {
				ret = -1;
			} else if (vp->vp_integer64 > check->vp_integer64) {
				ret = +1;
			} else {
				ret = 0;
			}
			break;

		case PW_TYPE_SIGNED:
			if (vp->vp_signed < check->vp_signed) {
				ret = -1;
			} else if (vp->vp_signed > check->vp_signed) {
				ret = +1;
			} else {
				ret = 0;
			}
			break;

		case PW_TYPE_DATE:
			ret = vp->vp_date - check->vp_date;
			break;

		case PW_TYPE_IPV4_ADDR:
			ret = ntohl(vp->vp_ipaddr) - ntohl(check->vp_ipaddr);
			break;

		case PW_TYPE_IPV6_ADDR:
			ret = memcmp(&vp->vp_ipv6addr, &check->vp_ipv6addr,
				     sizeof(vp->vp_ipv6addr));
			break;

		case PW_TYPE_IPV6_PREFIX:
			ret = memcmp(&vp->vp_ipv6prefix, &check->vp_ipv6prefix,
				     sizeof(vp->vp_ipv6prefix));
			break;

		case PW_TYPE_IFID:
			ret = memcmp(&vp->vp_ifid, &check->vp_ifid,
				     sizeof(vp->vp_ifid));
			break;

		default:
			break;
	}

	finish:
	if (ret > 0) {
		return 1;
	}
	if (ret < 0) {
		return -1;
	}
	return 0;
}
Example #13
0
int eglob(const char *pattern,
          int flags,
          int (*errfunc) (const char *epath, int eerrno),
          glob_t *pglob)
{
    int status = 0;

    /* Detect '**'. */
    regex_t ss_regex;
    size_t nmatch = 2;
    regmatch_t pmatch[nmatch];

    size_t start = 0;
    size_t end = 0;
    int ss_present = 0;

    status = regcomp(&ss_regex, "[^\\](/[*][*])|^(/[*][*])|^([*][*])", REG_EXTENDED);
    if (status != 0) {
        // fprintf(stderr, "[ERROR] Failed to compile regex.\n");
        regfree(&ss_regex);
        return -1;
    }

    status = regexec(&ss_regex, pattern, nmatch, pmatch, 0);
    if (status != REG_NOMATCH) {
        if (pmatch[1].rm_so != -1) {
            start = pmatch[1].rm_so;
            end = pmatch[1].rm_eo;
        }
        else {
            start = pmatch[0].rm_so;
            end = pmatch[0].rm_eo;
        }

        ss_present = 1;

        // fprintf(stderr, "Start: %zu End: %zu\n", start, end);

        status = regexec(&ss_regex, &pattern[end], nmatch, pmatch, 0);
        if (status != REG_NOMATCH) {
            regfree(&ss_regex);

            /* More than one '**' is NOT permitted. */
            // fprintf(stderr, "[ERROR] Only one '**' per glob is permitted:\n");
            // fprintf(stderr, "[ERROR] %s\n", pattern);
            // fprintf(stderr, "[ERROR] ");
            // for (size_t i = 0; i < (end + pmatch[0].rm_so + 1); i++) {
            //     fprintf(stderr, "-");
            // }
            // fprintf(stderr, "^\n");

            return -2;
        }

    }
    regfree(&ss_regex);

    /* No '**', fallback to normal glob. */
    if (ss_present == 0) {
        return glob(pattern, flags, errfunc, pglob);
    }

    // fprintf(stderr, "Found '**'...\n");

    /* Split glob into pre and post '**'. */
    const size_t pattern_size = strlen(pattern);

    int pre_mashup = 0;
    size_t pre_size = start + 1;
    if (pre_size == 1) {
        pre_size++;
        pre_mashup = 1;
    }

    char pre[pre_size];
    if (pre_mashup == 0) {
        memcpy(pre, pattern, sizeof(pre) - 1);
    }
    else {
        pre[0] = '.';
    }
    pre[sizeof(pre) - 1] = '\0';

    char post[pattern_size - end + 1];
    memcpy(post, pattern + end, sizeof(post) - 1);
    post[sizeof(post) - 1] = '\0';

    /* Glob the prefix path. */
    glob_t prefix_glob = {0, NULL, 0};
    status = glob(pre[0] == '\0' ? "." : pre, flags, errfunc, &prefix_glob);
    if (status != 0) {
        // fprintf(stderr, "[ERROR] Prefix glob failed: %s\n", pre);
        return -1;
    }

    // fprintf(stderr, "Walking %zu paths...\n", prefix_glob.gl_pathc - prefix_glob.gl_offs);

    /* Walk the paths found for prefix to compute longest path. */
    for (size_t i = prefix_glob.gl_offs; i < prefix_glob.gl_pathc; i++) {
        // fprintf(stderr, "Walking[%zu]: %s\n", i, prefix_glob.gl_pathv[i]);
        status = nftw(prefix_glob.gl_pathv[i], walker, MAX_OPEN_FD, FTW_PHYS);
        if (status != 0) {
            // fprintf(stderr, "[ERROR] Walking path failed.\n");
            globfree(&prefix_glob);
            return -1;
        }
    }
    globfree(&prefix_glob);

    // fprintf(stderr, "Max walker depth: %zu\n", walker_depth);

    /* Fold globs. */
    for (size_t i = 0; i <= walker_depth; i++) {
        char extended[sizeof(pre) + sizeof(post) + (i * 2) - 1];

        /* Grow pattern with slash star for each depth. */
        memcpy(extended, pre, sizeof(pre) - 1);
        size_t j = 0;
        for (; j < i; j++) {
            memcpy(&extended[(sizeof(pre) - 1) + (j * 2)], "/*", 2);
        }
        memcpy(&extended[(sizeof(pre) - 1) + (j * 2)], post, sizeof(post));

        // fprintf(stderr, "Processing: %s\n", extended);

        status = glob(extended, flags | GLOB_APPEND, errfunc, pglob);
        if (status != 0 && status != GLOB_NOMATCH) {
            return -1;
        }
    }

    return 0;
}
Example #14
0
File: grep.c Project: Inkdit/git
static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol, enum grep_context ctx)
{
	int hit = 0;
	int at_true_bol = 1;
	int saved_ch = 0;
	regmatch_t pmatch[10];

	if ((p->token != GREP_PATTERN) &&
	    ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
		return 0;

	if (p->token == GREP_PATTERN_HEAD) {
		const char *field;
		size_t len;
		assert(p->field < ARRAY_SIZE(header_field));
		field = header_field[p->field].field;
		len = header_field[p->field].len;
		if (strncmp(bol, field, len))
			return 0;
		bol += len;
		saved_ch = strip_timestamp(bol, &eol);
	}

 again:
	if (!opt->fixed) {
		regex_t *exp = &p->regexp;
		hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
			       pmatch, 0);
	}
	else {
		hit = !fixmatch(p->pattern, bol, pmatch);
	}

	if (hit && opt->word_regexp) {
		if ((pmatch[0].rm_so < 0) ||
		    (eol - bol) <= pmatch[0].rm_so ||
		    (pmatch[0].rm_eo < 0) ||
		    (eol - bol) < pmatch[0].rm_eo)
			die("regexp returned nonsense");

		/* Match beginning must be either beginning of the
		 * line, or at word boundary (i.e. the last char must
		 * not be a word char).  Similarly, match end must be
		 * either end of the line, or at word boundary
		 * (i.e. the next char must not be a word char).
		 */
		if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
		      !word_char(bol[pmatch[0].rm_so-1])) &&
		     ((pmatch[0].rm_eo == (eol-bol)) ||
		      !word_char(bol[pmatch[0].rm_eo])) )
			;
		else
			hit = 0;

		if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
			/* There could be more than one match on the
			 * line, and the first match might not be
			 * strict word match.  But later ones could be!
			 */
			bol = pmatch[0].rm_so + bol + 1;
			at_true_bol = 0;
			goto again;
		}
	}
	if (p->token == GREP_PATTERN_HEAD && saved_ch)
		*eol = saved_ch;
	return hit;
}
Example #15
0
int
Pass1(FILE *fd, unsigned applied)
{
    u_char *p,*q;
    MD5_CTX ctx;
    int i,j,sep,cnt;
    u_char *md5=0,*name=0,*trash=0;
    struct CTM_Syntax *sp;
    int slashwarn=0, match=0, total_matches=0;
    unsigned current;
    char md5_1[33];

    if(Verbose>3)
        printf("Pass1 -- Checking integrity of incoming CTM-patch\n");
    MD5Init (&ctx);

    GETFIELD(p,' ');				/* CTM_BEGIN */
    if(strcmp(p,"CTM_BEGIN")) {
        Fatal("Probably not a CTM-patch at all.");
        if(Verbose>3)
            fprintf(stderr,"Expected \"CTM_BEGIN\" got \"%s\".\n",p);
        return 1;
    }

    GETFIELDCOPY(Version,' ');				/* <Version> */
    if(strcmp(Version,VERSION)) {
        Fatal("CTM-patch is wrong version.");
        if(Verbose>3)
            fprintf(stderr,"Expected \"%s\" got \"%s\".\n",VERSION,p);
        return 1;
    }

    GETFIELDCOPY(Name,' ');				/* <Name> */
    GETFIELDCOPY(Nbr,' ');				/* <Nbr> */
    GETFIELDCOPY(TimeStamp,' ');			/* <TimeStamp> */
    GETFIELDCOPY(Prefix,'\n');				/* <Prefix> */

    sscanf(Nbr, "%u", &current);
    if (FilterList || ListIt)
        current = 0;	/* ignore if -l or if filters are present */
    if(current && current <= applied) {
        if(Verbose > 0)
            fprintf(stderr,"Delta number %u is already applied; ignoring.\n",
                    current);
        return Exit_Version;
    }

    for(;;) {
        Delete(md5);
        Delete(name);
        Delete(trash);
        cnt = -1;
        /* if a filter list is defined we assume that all pathnames require
           an action opposite to that requested by the first filter in the
           list.
           If no filter is defined, all pathnames are assumed to match. */
        match = (FilterList ? !(FilterList->Action) : CTM_FILTER_ENABLE);

        GETFIELD(p,' ');			/* CTM_something */

        if (p[0] != 'C' || p[1] != 'T' || p[2] != 'M') {
            Fatal("Expected CTM keyword.");
            fprintf(stderr,"Got [%s]\n",p);
            return 1;
        }

        if(!strcmp(p+3,"_END"))
            break;

        for(sp=Syntax; sp->Key; sp++)
            if(!strcmp(p+3,sp->Key))
                goto found;
        Fatal("Expected CTM keyword.");
        fprintf(stderr,"Got [%s]\n",p);
        return 1;
found:
        if(Verbose > 5)
            fprintf(stderr,"%s ",sp->Key);
        for(i=0; (j = sp->List[i]); i++) {
            if (sp->List[i+1] && (sp->List[i+1] & CTM_F_MASK) != CTM_F_Bytes)
                sep = ' ';
            else
                sep = '\n';

            if(Verbose > 5)
                fprintf(stderr," %x(%d)",sp->List[i],sep);

            switch (j & CTM_F_MASK) {
            case CTM_F_Name: /* XXX check for garbage and .. */
                GETFIELDCOPY(name,sep);
                j = strlen(name);
                if(name[j-1] == '/' && !slashwarn)  {
                    fprintf(stderr,"Warning: contains trailing slash\n");
                    slashwarn++;
                }
                if (name[0] == '/') {
                    Fatal("Absolute paths are illegal.");
                    return Exit_Mess;
                }
                q = name;
                for (;;) {
                    if (q[0] == '.' && q[1] == '.')
                        if (q[2] == '/' || q[2] == '\0') {
                            Fatal("Paths containing '..' are illegal.");
                            return Exit_Mess;
                        }
                    if ((q = strchr(q, '/')) == NULL)
                        break;
                    q++;
                }

                /* if we have been asked to `keep' files then skip
                   removes; i.e. we don't match these entries at
                   all. */
                if (KeepIt &&
                        (!strcmp(sp->Key,"DR") || !strcmp(sp->Key,"FR"))) {
                    match = CTM_FILTER_DISABLE;
                    break;
                }

                /* If filter expression have been defined, match the
                   path name against the expression list.  */

                if (FilterList) {
                    struct CTM_Filter *filter;

                    for (filter = FilterList; filter;
                            filter = filter->Next) {
                        if (0 == regexec(&filter->CompiledRegex, name,
                                         0, 0, 0))
                            /* if the name matches, adopt the
                               action */
                            match = filter->Action;
                    }
                }

                /* Add up the total number of matches */
                total_matches += match;
                break;
            case CTM_F_Uid:
                GETFIELD(p,sep);
                while(*p) {
                    if(!isdigit(*p)) {
                        Fatal("Non-digit in uid.");
                        return 32;
                    }
                    p++;
                }
                break;
            case CTM_F_Gid:
                GETFIELD(p,sep);
                while(*p) {
                    if(!isdigit(*p)) {
                        Fatal("Non-digit in gid.");
                        return 32;
                    }
                    p++;
                }
                break;
            case CTM_F_Mode:
                GETFIELD(p,sep);
                while(*p) {
                    if(!isdigit(*p)) {
                        Fatal("Non-digit in mode.");
                        return 32;
                    }
                    p++;
                }
                break;
            case CTM_F_MD5:
                if(j & CTM_Q_MD5_Chunk) {
                    GETFIELDCOPY(md5,sep);  /* XXX check for garbage */
                } else if(j & CTM_Q_MD5_Before) {
                    GETFIELD(p,sep);  /* XXX check for garbage */
                } else if(j & CTM_Q_MD5_After) {
                    GETFIELD(p,sep);  /* XXX check for garbage */
                } else {
                    fprintf(stderr,"List = 0x%x\n",j);
                    Fatal("Unqualified MD5.");
                    return 32;
                }
                break;
            case CTM_F_Count:
                GETBYTECNT(cnt,sep);
                break;
            case CTM_F_Bytes:
                if(cnt < 0) WRONG
                    GETDATA(trash,cnt);
                p = MD5Data(trash,cnt,md5_1);
                if(md5 && strcmp(md5,p)) {
                    Fatal("Internal MD5 failed.");
                    return Exit_Garbage;
                default:
                    fprintf(stderr,"List = 0x%x\n",j);
                    Fatal("List had garbage.");
                    return Exit_Garbage;
                }
            }
        }
        if(Verbose > 5)
            putc('\n',stderr);
        if(ListIt && match)
            printf("> %s %s\n", sp->Key, name);
    }

    Delete(md5);
    Delete(name);
    Delete(trash);

    q = MD5End (&ctx,md5_1);
    if(Verbose > 2)
        printf("Expecting Global MD5 <%s>\n",q);
    GETFIELD(p,'\n');			/* <MD5> */
    if(Verbose > 2)
        printf("Reference Global MD5 <%s>\n",p);
    if(strcmp(q,p)) {
        Fatal("MD5 sum doesn't match.");
        fprintf(stderr,"\tI have:<%s>\n",q);
        fprintf(stderr,"\tShould have been:<%s>\n",p);
        return Exit_Garbage;
    }
    if (-1 != getc(fd)) {
        if(!Force) {
            Fatal("Trailing junk in CTM-file.  Can Force with -F.");
            return 16;
        }
    }
    if ((Verbose > 1) && (0 == total_matches))
        printf("No matches in \"%s\"\n", FileName);
    return (total_matches ? Exit_OK : Exit_NoMatch);
}
Example #16
0
int
sdp_mangle_port (struct sip_msg *msg, char *offset, char *unused)
{
	int old_content_length, new_content_length, oldlen, err, oldPort, newPort,
		diff, offsetValue,len,off,ret,need_to_deallocate;
	struct lump *l;
	regmatch_t pmatch;
	regex_t *re;
	char *s, *pos,*begin,*key;
	char buf[6];
	str body;


	key = PORT_REGEX;
	/*
	 * Checking if msg has a payload
	 */
	if (msg == NULL)
	{
		LM_ERR("received NULL msg\n");
		return -1;
	}

	if ( get_body(msg,&body)!=0 || body.len==0)
	{
		LM_ERR(" failed to get a body \n");
		return -2;
	}

	old_content_length = get_content_length(msg);

	if (offset == NULL)
		return -14;
	if (sscanf (offset, "%d", &offsetValue) != 1)
	{
		LM_ERR("invalid value for offset \n");
		return -13;
	}

	//offsetValue = (int)offset;
#ifdef DEBUG
	fprintf (stdout,"---START--------MANGLE PORT-----------------\n");
	fprintf(stdout,"===============OFFSET = %d\n",offsetValue);
#endif

	if ((offsetValue < MIN_OFFSET_VALUE) || (offsetValue > MAX_OFFSET_VALUE))
	{
		LM_ERR("invalid value %d for offset \n",offsetValue);
		return -3;
	}

	begin = body.s;
	ret = -1;

	/* try to use pre-compiled expressions */
	need_to_deallocate = 0;
	if (portExpression != NULL)
		{
		re = portExpression;
#ifdef DEBUG
		fprintf(stdout,"Using PRECOMPILED expression for port ...\n");
#endif
		}
		else /* we are not using pre-compiled expressions */
			{
			re = pkg_malloc(sizeof(regex_t));
			if (re == NULL)
				{
				LM_ERR("unable to allocate re\n");
				return -4;
				}
			need_to_deallocate = 1;
			if ((regcomp (re, key, REG_EXTENDED)) != 0)
				{
				LM_ERR("unable to compile %s \n",key);
				return -5;
				}
#ifdef DEBUG
		fprintf(stdout,"Using ALLOCATED expression for port ...\n");
#endif

			}

	diff = 0;
	while ((begin < msg->buf + msg->len) && (regexec (re, begin, 1, &pmatch, 0) == 0))
	{
		off = begin - msg->buf;
		if (pmatch.rm_so == -1)
		{
			LM_ERR("offset unknown\n");
			return -6;
		}

#ifdef STRICT_CHECK
		pmatch.rm_eo --; /* return with one space */
#endif

		/*
                for BSD and Solaris we avoid memrchr
                pos = (char *) memrchr (begin + pmatch.rm_so, ' ',pmatch.rm_eo - pmatch.rm_so);
                */
                pos = begin+pmatch.rm_eo;
#ifdef DEBUG
                printf("begin=%c pos=%c rm_so=%d rm_eo=%d\n",*begin,*pos,pmatch.rm_so,pmatch.rm_eo);
#endif
                do pos--; while (*pos != ' '); /* we should find ' ' because we matched m=audio port */

		pos++;		/* jumping over space */
		oldlen = (pmatch.rm_eo - pmatch.rm_so) - (pos - (begin + pmatch.rm_so));	/* port length */

		/* convert port to int */
		oldPort = str2s (pos, oldlen, &err);
#ifdef DEBUG
                printf("port to convert [%.*s] to int\n",oldlen,pos);
#endif
		if (err)
			{
			LM_ERR("failed to convert [%.*s] to int\n",oldlen,pos);
#ifdef STRICT_CHECK
			return -7;
#else
			goto continue1;
#endif
			}
		if ((oldPort < MIN_ORIGINAL_PORT) || (oldPort > MAX_ORIGINAL_PORT))	/* we silently fail,we ignore this match or return -11 */
		{
#ifdef DEBUG
                printf("WARNING: sdp_mangle_port: Silent fail for not matching old port %d\n",oldPort);
#endif

			LM_WARN("silent fail for not matching old port %d\n",oldPort);
#ifdef STRICT_CHECK
			return -8;
#else
			goto continue1;
#endif
		}
                if ((offset[0] != '+')&&(offset[0] != '-')) newPort = offsetValue;//fix value
		else newPort = oldPort + offsetValue;
		/* new port is between 1 and 65536, or so should be */
		if ((newPort < MIN_MANGLED_PORT) || (newPort > MAX_MANGLED_PORT))	/* we silently fail,we ignore this match */
		{
#ifdef DEBUG
                printf("WARNING: sdp_mangle_port: Silent fail for not matching new port %d\n",newPort);
#endif

			LM_WARN("silent fail for not matching new port %d\n",newPort);
#ifdef STRICT_CHECK
			return -9;
#else
			goto continue1;
#endif
		}

#ifdef DEBUG
		fprintf(stdout,"Extracted port is %d and mangling to %d\n",oldPort,newPort);
#endif

		/*
		len = 1;
		while ((newPort = (newPort / 10)) != 0)	len++;
		newPort = oldPort + offsetValue;
		*/
		if (newPort >= 10000) len = 5;
			else
				if (newPort >= 1000) len = 4;
					else
						if (newPort >= 100) len = 3;
							else
								if (newPort >= 10) len = 2;
									else len = 1;

		/* replaced five div's + 1 add with most probably 1 comparison or 2 */

		/* deleting old port */
		if ((l = del_lump (msg, pmatch.rm_so + off +
						(pos -(begin + pmatch.rm_so)),oldlen, 0)) == 0)
		{
			LM_ERR("del_lump failed\n");
			return -10;
		}
		s = pkg_malloc (len);
		if (s == 0)
		{
			LM_ERR("no more pkg memory\n");
			return -11;
		}
		snprintf (buf, len + 1, "%u", newPort);	/* converting to string */
		memcpy (s, buf, len);

		if (insert_new_lump_after (l, s, len, 0) == 0)
		{
			LM_ERR("could not insert new lump\n");
			pkg_free (s);
			return -12;
		}
		diff = diff + len /*new length */  - oldlen;
		/* new cycle */
		ret++;
#ifndef STRICT_CHECK
continue1:
#endif
		begin = begin + pmatch.rm_eo;

	}			/* while  */
	if (need_to_deallocate)
		{
		regfree (re);
		pkg_free(re);
#ifdef DEBUG
		fprintf(stdout,"Deallocating expression for port ...\n");
#endif
		}

	if (diff != 0)
	{
		new_content_length = old_content_length + diff;
		patch_content_length (msg, new_content_length);
	}

#ifdef DEBUG
	fprintf (stdout,"---END--------MANGLE PORT-----------------\n");
#endif

	return ret+2;
}
Example #17
0
/** @brief Read's a defined log file and stores the entries into entry list struct
 *  @param [in] log_file the full path of the log file to read
 *  @param [in] search_string a string you are searching for.
 *		Set to NULL to disable search function
 *  @param [in] reverse this bool defines which order the log entries should return
 *  @param [in] ts_start defines the start timestamp for log entries
 *	@arg >=0 means unix timestamp
 *	@arg -1 deactivated
 *  @param [in] ts_end defines the end timestamp for log entries
 *	@arg >=0 means unix timestamp
 *	@arg -1 deactivated
 *  @return
 *	@retval READLOG_OK
 *	@retval READLOG_ERROR
 *	@retval READLOG_ERROR_MEMORY
 *	@retval READLOG_ERROR_NOFILE
 *	@retval READLOG_ERROR_FILTER
 *  @author Ricardo Bartels
 *
 *  This functions reads a  \c log_file and and try's (if set) to filter for a search string.
 *  This search string uses regular expressions. The reverse option defines if you want
 *  have your log entries returned in normal or revers order. Normal order for returning
 *  would be from the newest entry to the oldest. You can also set a time "window". This
 *  defines if you want to exclude entries which are outside of these "window". Then only
 *  entries will be returned which are between start and end. Very useful if user has all
 *  entries in one log file.
**/
int get_log_entries(char *log_file, char *search_string, int reverse, time_t ts_start, time_t ts_end) {
	char *input = NULL;
	char *temp_buffer = NULL;
	char *search_regex = NULL;
	int type = 0;
	int regex_i = 0, i = 0, len = 0;
	short keep_entry = TRUE;
	time_t timestamp;
	mmapfile *thefile = NULL;
	logentry *temp_entry = NULL;
	regex_t preg;
	logfilter *temp_filter;

	if ((thefile = mmap_fopen(log_file)) != NULL) {

		if (search_string != NULL) {
			/* allocate for 3 extra chars, ^, $ and \0 */
			search_regex = malloc(sizeof(char) * (strlen(search_string) * 2 + 3));
			len = strlen(search_string);
			for (i = 0; i < len; i++, regex_i++) {
				if (search_string[i] == '*') {
					search_regex[regex_i++] = '.';
					search_regex[regex_i] = '*';
				} else
					search_regex[regex_i] = search_string[i];
			}
			//search_regex[0]='^';
			//search_regex[regex_i++]='$';

			search_regex[regex_i] = '\0';

			/* check and compile regex */
			if (regcomp(&preg, search_regex, REG_ICASE | REG_NOSUB) != 0) {
				regfree(&preg);
				mmap_fclose(thefile);
				return READLOG_ERROR_FILTER;
			}
		}

		while (1) {

			/* free memory */
			my_free(input);

			if ((input = mmap_fgets(thefile)) == NULL)
				break;

			strip(input);

			if ((int)strlen(input) == 0)
				continue;

			/* get timestamp */
			temp_buffer = strtok(input, "]");
			timestamp = (temp_buffer == NULL) ? 0L : strtoul(temp_buffer + 1, NULL, 10);

			/* skip line if out of time range */
			if ((ts_start >= 0 && timestamp < ts_start) || (ts_end >= 0 && timestamp > ts_end))
				continue;

			/* get log entry text */
			temp_buffer = strtok(NULL, "\n");

			if (search_string != NULL) {
				if (regexec(&preg, temp_buffer, 0, NULL, 0) == REG_NOMATCH)
					continue;
			}


			if (strstr(temp_buffer, " starting..."))
				type = LOGENTRY_STARTUP;
			else if (strstr(temp_buffer, " shutting down..."))
				type = LOGENTRY_SHUTDOWN;
			else if (strstr(temp_buffer, "Bailing out"))
				type = LOGENTRY_BAILOUT;
			else if (strstr(temp_buffer, " restarting..."))
				type = LOGENTRY_RESTART;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";DOWN;"))
				type = LOGENTRY_HOST_DOWN;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UNREACHABLE;"))
				type = LOGENTRY_HOST_UNREACHABLE;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_HOST_RECOVERY;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UP;"))
				type = LOGENTRY_HOST_UP;
			else if (strstr(temp_buffer, "HOST NOTIFICATION:"))
				type = LOGENTRY_HOST_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";CRITICAL;"))
				type = LOGENTRY_SERVICE_CRITICAL;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";WARNING;"))
				type = LOGENTRY_SERVICE_WARNING;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";UNKNOWN;"))
				type = LOGENTRY_SERVICE_UNKNOWN;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_SERVICE_RECOVERY;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";OK;"))
				type = LOGENTRY_SERVICE_OK;
			else if (strstr(temp_buffer, "SERVICE NOTIFICATION:"))
				type = LOGENTRY_SERVICE_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE EVENT HANDLER:"))
				type = LOGENTRY_SERVICE_EVENT_HANDLER;
			else if (strstr(temp_buffer, "HOST EVENT HANDLER:"))
				type = LOGENTRY_HOST_EVENT_HANDLER;
			else if (strstr(temp_buffer, "EXTERNAL COMMAND:"))
				type = LOGENTRY_EXTERNAL_COMMAND;
			else if (strstr(temp_buffer, "PASSIVE SERVICE CHECK:"))
				type = LOGENTRY_PASSIVE_SERVICE_CHECK;
			else if (strstr(temp_buffer, "PASSIVE HOST CHECK:"))
				type = LOGENTRY_PASSIVE_HOST_CHECK;
			else if (strstr(temp_buffer, "LOG ROTATION:"))
				type = LOGENTRY_LOG_ROTATION;
			else if (strstr(temp_buffer, "active mode..."))
				type = LOGENTRY_ACTIVE_MODE;
			else if (strstr(temp_buffer, "standby mode..."))
				type = LOGENTRY_STANDBY_MODE;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_SERVICE_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_HOST_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_HOST_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "INITIAL SERVICE STATE:"))
				type = LOGENTRY_SERVICE_INITIAL_STATE;
			else if (strstr(temp_buffer, "INITIAL HOST STATE:"))
				type = LOGENTRY_HOST_INITIAL_STATE;
			else if (strstr(temp_buffer, "CURRENT SERVICE STATE:"))
				type = LOGENTRY_SERVICE_CURRENT_STATE;
			else if (strstr(temp_buffer, "CURRENT HOST STATE:"))
				type = LOGENTRY_HOST_CURRENT_STATE;
			else if (strstr(temp_buffer, "error executing command"))
				type = LOGENTRY_ERROR_COMMAND_EXECUTION;
			else if (strstr(temp_buffer, "idomod:"))
				type = LOGENTRY_IDOMOD;
			else if (strstr(temp_buffer, "npcdmod:"))
				type = LOGENTRY_NPCDMOD;
			else if (strstr(temp_buffer, "Auto-save of"))
				type = LOGENTRY_AUTOSAVE;
			else if (strstr(temp_buffer, "Warning:"))
				type = LOGENTRY_SYSTEM_WARNING;
			else
				type = LOGENTRY_UNDEFINED;

			/* apply filters */
			if (filter_list != NULL) {
				keep_entry = FALSE;
				for (temp_filter = filter_list; temp_filter != NULL; temp_filter = temp_filter->next) {
					if (temp_filter->include != 0) {
						if (temp_filter->include == type) {
							keep_entry = TRUE;
							break;
						}
					} else if (temp_filter->exclude != 0) {
						if (temp_filter->exclude == type) {
							keep_entry = FALSE;
							break;
						} else
							keep_entry = TRUE;
					}
				}
				if (keep_entry == FALSE)
					continue;
			}

			/* initialzie */
			/* allocate memory for a new log entry */
			temp_entry = (logentry *)malloc(sizeof(logentry));
			if (temp_entry == NULL) {
				mmap_fclose(thefile);
				return READLOG_ERROR_MEMORY;
			}

			temp_entry->timestamp = 0L;
			temp_entry->type = 0;
			temp_entry->entry_text = NULL;
			temp_entry->next = NULL;


			temp_entry->timestamp = timestamp;
			temp_entry->type = type;
			temp_entry->entry_text = strdup(temp_buffer);

			if (reverse == TRUE) {
				if (entry_list == NULL) {
					entry_list = temp_entry;
					last_entry = entry_list;
				} else {
					last_entry->next = temp_entry;
					last_entry = temp_entry;
				}
			} else {
				temp_entry->next = entry_list;
				entry_list = temp_entry;
			}
		}

		mmap_fclose(thefile);

		if (search_string != NULL)
			regfree(&preg);
	} else
		return READLOG_ERROR_NOFILE;

	return READLOG_OK;
}
Example #18
0
int
irc_ignore_check (struct t_irc_server *server, const char *channel,
                  const char *nick, const char *host)
{
    struct t_irc_ignore *ptr_ignore;
    int server_match, channel_match;
    char *pos;

    if (!server)
        return 0;

    /*
     * if nick is the same as server, then we will not ignore
     * (it is possible when connected to an irc proxy)
     */
    if (nick && server->nick
        && (irc_server_strcasecmp (server, server->nick, nick) == 0))
    {
        return 0;
    }

    for (ptr_ignore = irc_ignore_list; ptr_ignore;
         ptr_ignore = ptr_ignore->next_ignore)
    {
        if (strcmp (ptr_ignore->server, "*") == 0)
            server_match = 1;
        else
            server_match = (weechat_strcasecmp (ptr_ignore->server,
                                                server->name) == 0);

        channel_match = 0;
        if (!channel || (strcmp (ptr_ignore->channel, "*") == 0))
            channel_match = 1;
        else
        {
            if (irc_channel_is_channel (server, channel))
            {
                channel_match = (weechat_strcasecmp (ptr_ignore->channel,
                                                     channel) == 0);
            }
            else if (nick)
            {
                channel_match = (weechat_strcasecmp (ptr_ignore->channel,
                                                     nick) == 0);
            }
        }

        if (server_match && channel_match)
        {
            if (nick && (regexec (ptr_ignore->regex_mask, nick, 0, NULL, 0) == 0))
                return 1;
            if (host)
            {
                if (regexec (ptr_ignore->regex_mask, host, 0, NULL, 0) == 0)
                    return 1;
                if (!strchr (ptr_ignore->mask, '!'))
                {
                    pos = strchr (host, '!');
                    if (pos && (regexec (ptr_ignore->regex_mask, pos + 1,
                                         0, NULL, 0) == 0))
                    {
                        return 1;
                    }
                }
            }
        }
    }

    return 0;
}
static void readconfig() {
	const char	*val = NULL;
#ifdef DEBUG
	fprintf(stderr, "Reading configuration file...");
#endif

	config_t cfg;

	config_init(&cfg);
	if (!config_read_file(&cfg, config_file))   {
		char *message = "Config file not found in /etc/libnss.conf.\n";
		syslog(LOG_ERR, "%s", message);

#ifdef DEBUG
		fprintf(stderr, "%s", message);
		fprintf(stderr, "%s\n", config_error_text(&cfg));
#endif

		config_destroy(&cfg);  
		return;
	}

	readconfig_value(&cfg, "url_passwd", &url_passwd);
	readconfig_value(&cfg, "url_group", &url_group);
	readconfig_value(&cfg, "cafile", &cafile);
	readconfig_value(&cfg, "sslcheck", &sslcheck);
	readconfig_value(&cfg, "username", &username);
	readconfig_value(&cfg, "password", &password);

	if (get_cookies() == NULL) {
		int		i = 0;
		regex_t	envVar;
		readconfig_value(&cfg, "cookie_num", &val);
		if (val == NULL) goto end_config;
		int num_cookies = atoi(val);

		if(regcomp(&envVar, "\\$\\{[a-zA-Z0-9_-]+\\}", REG_EXTENDED))
			goto end_config;

		for(i=1; i <= num_cookies; ++i) {
			char 	strkey[512],
				*cookie_name = NULL,
				*cookie_value = NULL;

			sprintf(strkey, "cookie_%d_name", i);
			readconfig_value(&cfg, strkey, (const char **)&cookie_name);
			sprintf(strkey, "cookie_%d_value", i);
			readconfig_value(&cfg, strkey, (const char **)&cookie_value);
			if(!cookie_value || !cookie_name)
				goto on_gen_err;
			/* expand cookie_name */
			char		*tmpVal = cookie_name,
					tmpBuf[2048];
			tmpBuf[0] = '\0';
			regmatch_t	match; 
			while(!regexec(&envVar, tmpVal, 1, &match, 0)) {
				if(-1 == match.rm_so)
					break;
				strncat(tmpBuf, tmpVal, match.rm_so);
				char            *pEnd = &tmpVal[match.rm_eo-1],
						tVal = *pEnd;
				*pEnd = '\0';
				const char	*envVal = getenv(tmpVal + match.rm_so + 2);
				*pEnd = tVal;
				tmpVal += match.rm_eo;
				if(envVal) strcat(tmpBuf, envVal);
			}
			free(cookie_name);
			cookie_name = strdup(tmpBuf);
			if(!cookie_name) goto on_gen_err;
			/* do the same for cookie_value */
			tmpVal = cookie_value;
			tmpBuf[0] = '\0';
			while(!regexec(&envVar, tmpVal, 1, &match, 0)) {
				if(-1 == match.rm_so)
					break;
				strncat(tmpBuf, tmpVal, match.rm_so);
				char            *pEnd = &tmpVal[match.rm_eo-1],
						tVal = *pEnd;
				*pEnd = '\0';
				const char	*envVal = getenv(tmpVal + match.rm_so + 2);
				*pEnd = tVal;
				tmpVal += match.rm_eo;
				if(envVal) strcat(tmpBuf, envVal);
			}
			free(cookie_value);
			cookie_value = strdup(tmpBuf);
			if(!cookie_value) goto on_gen_err;
			/* add to cookies */
			BODY *curcookie = (BODY *) malloc(sizeof(BODY));
			if(!curcookie) goto on_gen_err;
			curcookie->row = (char *) malloc(strlen(cookie_name)+strlen(cookie_value)+2);
			if(!curcookie->row) {
				free(curcookie);
				goto on_gen_err;
			}
			sprintf(curcookie->row, "%s=%s", cookie_name, cookie_value);
			curcookie->next = get_cookies();
			set_cookies(curcookie);

#ifdef DEBUG
			fprintf(stderr, "Read new cookie: [%s] => %s\n", cookie_name, cookie_value);
#endif

on_gen_err:
			if(cookie_value) free(cookie_value);
			if(cookie_name) free(cookie_name);
		}
		regfree(&envVar);
	}

end_config:
	config_destroy(&cfg);
	if(val) free((void*)val); 
}
Example #20
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData) {
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

        strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
  DIR *testDir = opendir(szPath);
  if (testDir) {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0) {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

        if (strFiles == "*.*")
           strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();

  int status;
  regex_t re;
  if (regcomp(&re, strFiles, REG_EXTENDED|REG_NOSUB) != 0) {
    return(INVALID_HANDLE_VALUE);
  }

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0) {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    status = regexec(&re, strComp.c_str(), (size_t) 0, NULL, 0);
    if (status == 0) {
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    }
    free(namelist[n]);
  }
  free(namelist);

  regfree(&re);

  if (pHandle->m_FindFileResults.size() == 0) {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
Example #21
0
/* Prevent SQL injection
 */
static int prevent_sqli_str(t_session *session, char *str, int length) {
	char *data, *c, *begin, *end;
	t_sqli_pattern *pattern;
	int result = 0, i;

	if ((str == NULL) || (length <= 0)) {
		return 0;
	}

	if ((data = (char*)malloc(length + 1)) == NULL) {
		return -1;
	}

	memcpy(data, str, length);
	for (i = 0; i < length; i++) {
		if (data[i] == '\0') {
			data[i] = ' ';
		} else if (strncmp(data + i, "%00", 3) == 0) {
			data[i + 1] = '2';
		}
	}
	data[length] = '\0';

	url_decode(data);

	c = data;
	while (*c != '\0') {
		if (*c == '+') {
			*c = ' ';
		}
		c++;
	}

	/* Remove comments
	 */
	end = data;
	while ((begin = strstr(end, "/*")) != NULL) {
		if ((end = strstr(begin + 2, "*/")) == NULL) {
			break;
		}
		end += 2;
		if (*(begin + 2) != '!') {
			memset(begin, ' ', end - begin);
		}
	}

	/* Remove double parenthesis
	 */
	end = data;
	while ((begin = strchr(end, '(')) != NULL) {
		end = begin + 1;
		while (*end == ' ') {
			end++;
		}
		if (*end == '(') {
			*begin = ' ';
		}
	}

	/* SQL operators
	 */
	if ((c = strchr(data, '\'')) != NULL) {
		do {
			c++;
		} while ((*c == ' ') || (*c == '\t'));

		for (i = 0; sql_operators[i].text != NULL; i++) {
			if (strncasecmp(c, sql_operators[i].text, strlen(sql_operators[i].text)) == 0) {
				log_sqli_attempt(session, str);
				result = 1;
				goto sqli_done;
			}
		}
	}

	/* Match patterns
	 */
	pattern = sqli_patterns;
	while (pattern != NULL) {
		if (regexec(&(pattern->regex), data, 0, NULL, 0) != REG_NOMATCH) {
			log_sqli_attempt(session, str);
			result = 1;
			goto sqli_done;
		}

		pattern = pattern->next;
	}

sqli_done:
	free(data);

	return result;
}
Example #22
0
int
apply_substitution(struct bsdtar *bsdtar, const char *name, char **result, int symlink_only)
{
    const char *path = name;
    regmatch_t matches[10];
    size_t i, j;
    struct subst_rule *rule;
    struct substitution *subst;
    int c, got_match, print_match;

    *result = NULL;

    if ((subst = bsdtar->substitution) == NULL)
        return 0;

    got_match = 0;
    print_match = 0;

    for (rule = subst->first_rule; rule != NULL; rule = rule->next) {
        if (symlink_only && !rule->symlink)
            continue;
        if (regexec(&rule->re, name, 10, matches, 0))
            continue;

        got_match = 1;
        print_match |= rule->print;
        realloc_strncat(result, name, matches[0].rm_so);

        for (i = 0, j = 0; rule->result[i] != '\0'; ++i) {
            if (rule->result[i] == '~') {
                realloc_strncat(result, rule->result + j, i - j);
                realloc_strncat(result, name, matches[0].rm_eo);
                j = i + 1;
                continue;
            }
            if (rule->result[i] != '\\')
                continue;

            ++i;
            c = rule->result[i];
            switch (c) {
            case '~':
            case '\\':
                realloc_strncat(result, rule->result + j, i - j - 1);
                j = i;
                break;
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                realloc_strncat(result, rule->result + j, i - j - 1);
                if ((size_t)(c - '0') > (size_t)(rule->re.re_nsub)) {
                    free(*result);
                    *result = NULL;
                    return -1;
                }
                realloc_strncat(result, name + matches[c - '0'].rm_so, matches[c - '0'].rm_eo - matches[c - '0'].rm_so);
                j = i + 1;
                break;
            default:
                /* Just continue; */
                break;
            }

        }

        realloc_strcat(result, rule->result + j);

        name += matches[0].rm_eo;

        if (!rule->global)
            break;
    }

    if (got_match)
        realloc_strcat(result, name);

    if (print_match)
        fprintf(stderr, "%s >> %s\n", path, *result);

    return got_match;
}
Example #23
0
static int
constraint_violation( constraint *c, struct berval *bv, Operation *op )
{
	if ((!c) || (!bv)) return LDAP_SUCCESS;

	switch (c->type) {
		case CONSTRAINT_SIZE:
			if (bv->bv_len > c->size)
				return LDAP_CONSTRAINT_VIOLATION; /* size violation */
			break;
		case CONSTRAINT_REGEX:
			if (regexec(c->re, bv->bv_val, 0, NULL, 0) == REG_NOMATCH)
				return LDAP_CONSTRAINT_VIOLATION; /* regular expression violation */
			break;
		case CONSTRAINT_URI: {
			Operation nop = *op;
			slap_overinst *on = (slap_overinst *) op->o_bd->bd_info;
			slap_callback cb;
			int i;
			int found = 0;
			int rc;
			size_t len;
			struct berval filterstr;
			char *ptr;

			cb.sc_next = NULL;
			cb.sc_response = constraint_uri_cb;
			cb.sc_cleanup = NULL;
			cb.sc_private = &found;

			nop.o_protocol = LDAP_VERSION3;
			nop.o_tag = LDAP_REQ_SEARCH;
			nop.o_time = slap_get_time();
			if (c->lud->lud_dn) {
				struct berval dn;

				ber_str2bv(c->lud->lud_dn, 0, 0, &dn);
				nop.o_req_dn = dn;
				nop.o_req_ndn = dn;
				nop.o_bd = select_backend(&nop.o_req_ndn, 1 );
				if (!nop.o_bd) {
					return LDAP_NO_SUCH_OBJECT; /* unexpected error */
				}
				if (!nop.o_bd->be_search) {
					return LDAP_OTHER; /* unexpected error */
				}
			} else {
				nop.o_req_dn = nop.o_bd->be_nsuffix[0];
				nop.o_req_ndn = nop.o_bd->be_nsuffix[0];
				nop.o_bd = on->on_info->oi_origdb;
			}
			nop.o_do_not_cache = 1;
			nop.o_callback = &cb;

			nop.ors_scope = c->lud->lud_scope;
			nop.ors_deref = LDAP_DEREF_NEVER;
			nop.ors_slimit = SLAP_NO_LIMIT;
			nop.ors_tlimit = SLAP_NO_LIMIT;
			nop.ors_limit = NULL;

			nop.ors_attrsonly = 0;
			nop.ors_attrs = slap_anlist_no_attrs;

			len = STRLENOF("(&(") +
				  c->filter.bv_len +
				  STRLENOF(")(|");

			for (i = 0; c->attrs[i]; i++) {
				len += STRLENOF("(") +
					   c->attrs[i]->ad_cname.bv_len +
					   STRLENOF("=") +
					   bv->bv_len +
					   STRLENOF(")");
			}

			len += STRLENOF("))");
			filterstr.bv_len = len;
			filterstr.bv_val = op->o_tmpalloc(len + 1, op->o_tmpmemctx);

			ptr = filterstr.bv_val +
				snprintf(filterstr.bv_val, len, "(&(%s)(|", c->lud->lud_filter);
			for (i = 0; c->attrs[i]; i++) {
				*ptr++ = '(';
				ptr = lutil_strcopy( ptr, c->attrs[i]->ad_cname.bv_val );
				*ptr++ = '=';
				ptr = lutil_strcopy( ptr, bv->bv_val );
				*ptr++ = ')';
			}
			*ptr++ = ')';
			*ptr++ = ')';
			*ptr++ = '\0';

			nop.ors_filterstr = filterstr;
			nop.ors_filter = str2filter_x(&nop, filterstr.bv_val);
			if ( nop.ors_filter == NULL ) {
				Debug( LDAP_DEBUG_ANY,
					"%s constraint_violation uri filter=\"%s\" invalid\n",
					op->o_log_prefix, filterstr.bv_val );
				rc = LDAP_OTHER;

			} else {
				SlapReply nrs = { REP_RESULT };

				Debug(LDAP_DEBUG_TRACE,
					"==> constraint_violation uri filter = %s\n",
					filterstr.bv_val);

				rc = nop.o_bd->be_search( &nop, &nrs );

				Debug(LDAP_DEBUG_TRACE,
					"==> constraint_violation uri rc = %d, found = %d\n",
					rc, found);
			}
			op->o_tmpfree(filterstr.bv_val, op->o_tmpmemctx);

			if ((rc != LDAP_SUCCESS) && (rc != LDAP_NO_SUCH_OBJECT)) {
				return rc; /* unexpected error */
			}

			if (!found)
				return LDAP_CONSTRAINT_VIOLATION; /* constraint violation */
			break;
		}
	}

	return LDAP_SUCCESS;
}
Example #24
0
/** Parses a string into a date, given a format. The format must
 * include the year. This function should only be called by
 * parse_date.
 * @param date_str The string containing a date being parsed
 * @param format An index specifying a format in date_format_user
 * @return The parsed value of date_str on success or -1 on failure
 */
static time_t parse_date_with_year(const char* date_str, int format)
{
    time_t rawtime; /* The integer time */
    struct tm retvalue, test_retvalue; /* The time in a broken-down structure */

    int i, j, mem_length, orig_year = -1, orig_month = -1, orig_day = -1;

    /* Buffer for containing individual parts (e.g. year, month, day) of a date */
    char date_segment[5];

    /* The compiled regular expression */
    regex_t preg = {0};

    /* An array containing indices specifying the matched substrings in date_str */
    regmatch_t pmatch[4] = { {0}, {0}, {0}, {0} };

    /* The regular expression for parsing dates */
    const char* regex = "^ *([0-9]+) *[-/.'] *([0-9]+) *[-/.'] *([0-9]+).*$|^ *([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]).*$";

    /* We get our matches using the regular expression. */
    regcomp(&preg, regex, REG_EXTENDED);
    regexec(&preg, date_str, 4, pmatch, 0);
    regfree(&preg);

    /* If there wasn't a match, there was an error. */
    if (pmatch[0].rm_eo == 0)
        return -1;

    /* If this is a string without separators ... */
    if (pmatch[1].rm_so == -1)
    {
        /* ... we will fill in the indices based on the user's selection. */
        int k = 0; /* k traverses date_str by keeping track of where separators "should" be. */
        j = 1; /* j traverses pmatch. */
        for (i = 0; date_format_user[format][i]; i++)
        {
            char segment_type = date_format_user[format][i];
            /* Only do something if this is a meaningful character */
            if (segment_type == 'y' || segment_type == 'm' || segment_type == 'd')
            {
                pmatch[j].rm_so = k;
                switch (segment_type)
                {
                case 'm':
                case 'd':
                    k += 2;
                    break;

                case 'y':
                    k += 4;
                    break;
                }

                pmatch[j].rm_eo = k;
                j++;
            }
        }
    }

    /* Put some sane values in retvalue by using the current time for
     * the non-year-month-day parts of the date. */
    time(&rawtime);
    localtime_r(&rawtime, &retvalue);

    /* j traverses pmatch (index 0 contains the entire string, so we
     * start at index 1 for the first meaningful match). */
    j = 1;
    /* Go through the date format and interpret the matches in order of
     * the sections in the date format. */
    for (i = 0; date_format_user[format][i]; i++)
    {
        char segment_type = date_format_user[format][i];
        /* Only do something if this is a meaningful character */
        if (segment_type == 'y' || segment_type == 'm' || segment_type == 'd')
        {
            /* Copy the matching substring into date_segment so that we can
             * convert it into an integer. */
            mem_length = pmatch[j].rm_eo - pmatch[j].rm_so;
            memcpy(date_segment, date_str + pmatch[j].rm_so, mem_length);
            date_segment[mem_length] = '\0';

            /* Set the appropriate member of retvalue. Save the original
             * values so that we can check if the change when we use mktime
             * below. */
            switch (segment_type)
            {
            case 'y':
                retvalue.tm_year = atoi(date_segment);

                /* Handle two-digit years. */
                if (retvalue.tm_year < 100)
                {
                    /* We allow two-digit years in the range 1969 - 2068. */
                    if (retvalue.tm_year < 69)
                        retvalue.tm_year += 100;
                }
                else
                    retvalue.tm_year -= 1900;
                orig_year = retvalue.tm_year;
                break;

            case 'm':
                orig_month = retvalue.tm_mon = atoi(date_segment) - 1;
                break;

            case 'd':
                orig_day = retvalue.tm_mday = atoi(date_segment);
                break;
            }
            j++;
        }
    }
    /* Convert back to an integer. If mktime leaves retvalue unchanged,
     * everything is okay; otherwise, an error has occurred. */
    /* We have to use a "test" date value to account for changes in
     * daylight savings time, which can cause a date change with mktime
     * near midnight, causing the code to incorrectly think a date is
     * incorrect. */
    test_retvalue = retvalue;
    mktime(&test_retvalue);
    retvalue.tm_isdst = test_retvalue.tm_isdst;
    rawtime = mktime(&retvalue);
    if (retvalue.tm_mday == orig_day &&
    retvalue.tm_mon == orig_month &&
    retvalue.tm_year == orig_year)
    {
        return rawtime;
    }
    else
    {
        return -1;
    }
}
// Initialize joystick interface
//
int _glfwInitJoysticks(void)
{
#if defined(__linux__)
    const char* dirname = "/dev/input";
    DIR* dir;

    _glfw.linux_js.inotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
    if (_glfw.linux_js.inotify == -1)
    {
        _glfwInputError(GLFW_PLATFORM_ERROR,
                        "Linux: Failed to initialize inotify: %s",
                        strerror(errno));
        return GL_FALSE;
    }

    // HACK: Register for IN_ATTRIB as well to get notified when udev is done
    //       This works well in practice but the true way is libudev

    _glfw.linux_js.watch = inotify_add_watch(_glfw.linux_js.inotify,
                                             dirname,
                                             IN_CREATE | IN_ATTRIB);
    if (_glfw.linux_js.watch == -1)
    {
        _glfwInputError(GLFW_PLATFORM_ERROR,
                        "Linux: Failed to watch for joystick connections in %s: %s",
                        dirname,
                        strerror(errno));
        // Continue without device connection notifications
    }

    if (regcomp(&_glfw.linux_js.regex, "^js[0-9]\\+$", 0) != 0)
    {
        _glfwInputError(GLFW_PLATFORM_ERROR, "Linux: Failed to compile regex");
        return GL_FALSE;
    }

    dir = opendir(dirname);
    if (dir)
    {
        struct dirent* entry;

        while ((entry = readdir(dir)))
        {
            char path[20];
            regmatch_t match;

            if (regexec(&_glfw.linux_js.regex, entry->d_name, 1, &match, 0) != 0)
                continue;

            snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);
            openJoystickDevice(path);
        }

        closedir(dir);
    }
    else
    {
        _glfwInputError(GLFW_PLATFORM_ERROR,
                        "Linux: Failed to open joystick device directory %s: %s",
                        dirname,
                        strerror(errno));
        // Continue with no joysticks detected
    }

#endif // __linux__

    return GL_TRUE;
}
Example #26
0
/* @param flag bit0= do not shortcut last component of to_match
               bit1= consider match if regex matches parent of path
               bit2= retry beginning at failed last component 

 @return 0=match , else no match 
*/
int Xorriso_regexec(struct XorrisO *xorriso, char *to_match, int *failed_at,
                    int flag)
{
 int ret,i,re_start= 0,reg_nomatch= -1;
 char *cpt,*npt, *adr_part= NULL, *mpt;

 Xorriso_alloc_meM(adr_part, char, SfileadrL);

 reg_nomatch= REG_NOMATCH;

 *failed_at= 0;
 if(!(xorriso->structured_search && xorriso->re_count>0)) {
   if(xorriso->re_constants!=NULL)
     if(xorriso->re_constants[0]!=NULL) {
       if(xorriso->re_constants[0][0]==0)
         {ret= 0; goto ex;}
       if(strcmp(xorriso->re_constants[0],to_match)!=0)
         {ret= reg_nomatch; goto ex;}
       {ret= 0; goto ex;}
     }  
   ret= regexec(&(xorriso->re[0]),to_match,1,xorriso->match,0);
   goto ex;
 }

 cpt= to_match;
 while(*cpt=='/')
  cpt++;
 if(flag&4)
   re_start= xorriso->re_failed_at;
 if(re_start<0)
   re_start= 0;
 for(i= re_start;i<xorriso->re_fill;i++) {
   *failed_at= i;
   npt= strchr(cpt,'/');
   if(npt==NULL) {
     if(i<xorriso->re_fill-1 && !(flag&1)) 
       {ret= reg_nomatch; goto ex;} /* this must be the last expression part */
     mpt= cpt;
   } else {
     strncpy(adr_part,cpt,npt-cpt);
     adr_part[npt-cpt]= 0;
     mpt= adr_part;
   }
   if(xorriso->re_constants[i]!=NULL) {
     if(xorriso->re_constants[i][0]!=0) /* empty constant matches anything */
       if(strcmp(xorriso->re_constants[i],mpt)!=0)
         {ret= reg_nomatch; goto ex;}
   } else {
     ret= regexec(&(xorriso->re[i]),mpt,1,xorriso->match,0);
     if(ret!=0)
       goto ex;
   }
   if(npt==NULL) {
     if(i>=xorriso->re_fill-1)
       {ret= 0; goto ex;} /* MATCH */
     *failed_at= i+1;
     {ret= reg_nomatch; goto ex;}
   }
   cpt= npt+1;
   while(*cpt=='/')
     cpt++; 
 }
 *failed_at= xorriso->re_fill;
 if(flag & 2)
   {ret= 0; goto ex;} /* MATCH */
 ret= reg_nomatch;
ex:;
 Xorriso_free_meM(adr_part);
 return(ret);
}
Example #27
0
File: color.c Project: aosm/nano
/* Update the color information based on the current filename. */
void color_update(void)
{
    const syntaxtype *tmpsyntax;
    colortype *tmpcolor, *defcolor = NULL;

    assert(openfile != NULL);

    openfile->colorstrings = NULL;

    /* If we specified a syntax override string, use it. */
    if (syntaxstr != NULL) {
	/* If the syntax override is "none", it's the same as not having
	 * a syntax at all, so get out. */
	if (strcmp(syntaxstr, "none") == 0)
	    return;

	for (tmpsyntax = syntaxes; tmpsyntax != NULL;
		tmpsyntax = tmpsyntax->next) {
	    if (strcmp(tmpsyntax->desc, syntaxstr) == 0)
		openfile->colorstrings = tmpsyntax->color;

	    if (openfile->colorstrings != NULL)
		break;
	}
    }

    /* If we didn't specify a syntax override string, or if we did and
     * there was no syntax by that name, get the syntax based on the
     * file extension. */
    if (openfile->colorstrings == NULL) {
	for (tmpsyntax = syntaxes; tmpsyntax != NULL;
		tmpsyntax = tmpsyntax->next) {
	    exttype *e;

	    /* If this is the default syntax, it has no associated
	     * extensions, which we've checked for elsewhere.  Skip over
	     * it here, but keep track of its color regexes. */
	    if (strcmp(tmpsyntax->desc, "default") == 0) {
		defcolor = tmpsyntax->color;
		continue;
	    }

	    for (e = tmpsyntax->extensions; e != NULL; e = e->next) {
		bool not_compiled = (e->ext == NULL);

		/* e->ext_regex has already been checked for validity
		 * elsewhere.  Compile its specified regex if we haven't
		 * already. */
		if (not_compiled) {
		    e->ext = (regex_t *)nmalloc(sizeof(regex_t));
		    regcomp(e->ext, e->ext_regex, REG_EXTENDED);
		}

		/* Set colorstrings if we matched the extension
		 * regex. */
		if (regexec(e->ext, openfile->filename, 0, NULL,
			0) == 0)
		    openfile->colorstrings = tmpsyntax->color;

		if (openfile->colorstrings != NULL)
		    break;

		/* Decompile e->ext_regex's specified regex if we aren't
		 * going to use it. */
		if (not_compiled) {
		    regfree(e->ext);
		    free(e->ext);
		    e->ext = NULL;
		}
	    }
	}
    }

    /* If we didn't get a syntax based on the file extension, and we
     * have a default syntax, use it. */
    if (openfile->colorstrings == NULL && defcolor != NULL)
	openfile->colorstrings = defcolor;

    for (tmpcolor = openfile->colorstrings; tmpcolor != NULL;
	tmpcolor = tmpcolor->next) {
	/* tmpcolor->start_regex and tmpcolor->end_regex have already
	 * been checked for validity elsewhere.  Compile their specified
	 * regexes if we haven't already. */
	if (tmpcolor->start == NULL) {
	    tmpcolor->start = (regex_t *)nmalloc(sizeof(regex_t));
	    regcomp(tmpcolor->start, tmpcolor->start_regex,
		REG_EXTENDED | (tmpcolor->icase ? REG_ICASE : 0));
	}

	if (tmpcolor->end_regex != NULL && tmpcolor->end == NULL) {
	    tmpcolor->end = (regex_t *)nmalloc(sizeof(regex_t));
	    regcomp(tmpcolor->end, tmpcolor->end_regex,
		REG_EXTENDED | (tmpcolor->icase ? REG_ICASE : 0));
	}
    }
}
Example #28
0
/*
 * Remove old .spool files written by me from the working directory.
 */
static void cleanup_old_files()
{
   DIR* dp;
   struct dirent *entry, *result;
   int rc, name_max;
   int my_name_len = strlen(my_name);
   int len = strlen(me->working_directory);
   POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
   POOLMEM *basename = get_pool_memory(PM_MESSAGE);
   regex_t preg1;
   char prbuf[500];
   berrno be;

   /* Look for .spool files but don't allow spaces */
   const char *pat1 = "^[^ ]+\\.spool$";

   /* Setup working directory prefix */
   pm_strcpy(basename, me->working_directory);
   if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
      pm_strcat(basename, "/");
   }

   /* Compile regex expressions */
   rc = regcomp(&preg1, pat1, REG_EXTENDED);
   if (rc != 0) {
      regerror(rc, &preg1, prbuf, sizeof(prbuf));
      Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
           pat1, prbuf);
      goto get_out2;
   }

   name_max = pathconf(".", _PC_NAME_MAX);
   if (name_max < 1024) {
      name_max = 1024;
   }

   if (!(dp = opendir(me->working_directory))) {
      berrno be;
      Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
            me->working_directory, be.bstrerror());
      goto get_out1;
   }

   entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
   while (1) {
      if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
         break;
      }
      /* Exclude any name with ., .., not my_name or containing a space */
      if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
          strncmp(result->d_name, my_name, my_name_len) != 0) {
         Dmsg1(500, "Skipped: %s\n", result->d_name);
         continue;
      }

      /* Unlink files that match regex */
      if (regexec(&preg1, result->d_name, 0, NULL, 0) == 0) {
         pm_strcpy(cleanup, basename);
         pm_strcat(cleanup, result->d_name);
         Dmsg1(500, "Unlink: %s\n", cleanup);
         secure_erase(NULL, cleanup);
      }
   }
   free(entry);
   closedir(dp);

get_out1:
   regfree(&preg1);
get_out2:
   free_pool_memory(cleanup);
   free_pool_memory(basename);
}
Example #29
0
void
pds_process_line(pds_session_t *pdss, char *line)
{
	regmatch_t pmatch[9];
	char *cmdtag = NULL;
	char *cmdstr = NULL;
	char *key = NULL;
	char *val = NULL;
	char *buf = NULL;
	char *listenid = NULL;
	int reportperiod;
	int forsession;
	int res;

	//DPRINT(line);

	if ((res = regexec(&setex, line, 7, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		if (!getmatchsub(line, &key, pmatch, 2) || !key)
			goto fail;

		if (!getmatchsub(line, &val, pmatch, 5) &&
		    !getmatchsub(line, &val, pmatch, 4))
			goto fail;
		if (!val)
			goto fail;
		if ((forsession = getmatchsub(line, NULL, pmatch, 6)) > 0) {
			/* mark for expiration, but make sure it's only added once! */
			if(plist_walk(pdss->pdss_expire, is_key_in_list, key))
			{
				char *e;
				if (!(e = strdup(key)))
					goto fail;
				plist_add(e, NULL, &pdss->pdss_expire);
			}
		}
		pdss->pdss_pd_lock(pdss->pdss_pd_lock_arg);
		res = pdict_add(pdss->pdss_pd, key, val, NULL);
		pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
		if (!res)
			result(pdss, cmdtag, "304 set failed");
		else
			result(pdss, cmdtag, "200 set successful");
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		free(key); key = NULL;
		free(val); val = NULL;
		return;
	}
	if ((res = regexec(&listenex, line, 6, pmatch, 0)) == 0) {
		notify_arg_t *nap;
		notify_arg_t na;

		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		if ((!getmatchsub(line, &buf, pmatch, 4) && !getmatchsub(line,
		    &buf, pmatch, 3)) || !buf)
			goto fail;
		getmatchsub(line, &listenid, pmatch, 5);
		na.na_pdss = pdss;
		na.na_listenid = listenid;
		pthread_mutex_lock(&pdss->pdss_lock);
		if (!ptree_contains(&na, pdss->pdss_notify_args, nacmp,
		    (void **)&nap)) {
			if (!(nap = malloc(sizeof (*nap))))
				goto fail;
			nap->na_pdss = pdss;
			nap->na_listenid = listenid;
			nap->na_pd_ids = NULL;
			if (!ptree_replace(nap, &pdss->pdss_notify_args, nacmp,
			    NULL)) {
				free(nap); nap = NULL;
				pu_log(PUL_WARN, pdss->pdss_id,
				    "insufficient memory");
				pthread_mutex_unlock(&pdss->pdss_lock);
				free(listenid); listenid = NULL;
				free(buf); buf = NULL;
				goto fail;
			}
		}

		pdss->pdss_pd_lock(pdss->pdss_pd_lock_arg);
		if (!(res = pdict_add_persistent_change_listener(pdss->pdss_pd,
		    buf, notify, (void *)nap))) {
			if (!nap->na_pd_ids) {
				ptree_remove(nap, &pdss->pdss_notify_args,
				    nacmp, NULL);
				free((void *)nap->na_listenid); nap->na_listenid = NULL;
				free(nap); nap = NULL;
			}
			result(pdss, cmdtag,
			    "303 listen not established--bad pattern?");
		} else {
			if (!plist_add((void *)res, NULL, &nap->na_pd_ids)) {
				pdict_remove_persistent_change_listener(
				    pdss->pdss_pd, res);
				if (!nap->na_pd_ids) {
					ptree_remove(nap,
					    &pdss->pdss_notify_args, nacmp,
					    NULL);
					free((void *)nap->na_listenid); nap->na_listenid = NULL;
					free(nap); nap = NULL;
				}
				free(buf); buf = NULL;
				if (cmdtag) {
					free(cmdtag); cmdtag = NULL;
				}
				pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
				pthread_mutex_unlock(&pdss->pdss_lock);
				goto fail;
			} else {
				result(pdss, cmdtag,"200 listening, id %s",
				    listenid);
			}
		}
		pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
		pthread_mutex_unlock(&pdss->pdss_lock);
		free(buf); buf = NULL;
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}
	if ((res = regexec(&reportex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		if (!getmatchsub(line, &buf, pmatch, 2) || !buf)
			goto fail;
		if ((reportperiod = atoi(buf)) < 0 || reportperiod > 10000) {
			result(pdss, cmdtag, "301 invalid report/wait period"
			    "--specify milliseconds or 0 for off (max 10s)");
			if (cmdtag) {
				free(cmdtag); cmdtag = NULL;
			}
			free(buf); buf = NULL;
			return;
		}
		free(buf); buf = NULL;
		getmatchsub(line, &buf, pmatch, 3);
		set_report_period(pdss, cmdtag, buf, reportperiod);
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		if (buf) {
			free(buf); buf = NULL;
		}
		return;
	}
	if ((res = regexec(&waitex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		if (!getmatchsub(line, &buf, pmatch, 2) || !buf)
			goto fail;
		if (atoi(buf) < 0 || atoi(buf) > 10000) {
			result(pdss, cmdtag, "301 invalid wait period"
			    "--specify milliseconds (max 10s)");
			if (cmdtag) {
				free(cmdtag); cmdtag = NULL;
			}
			return;
		}
		usleep(atoi(buf) * 1000);
		result(pdss, cmdtag, "200 nothin' doin'");
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}
	if ((res = regexec(&flushex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		pthread_mutex_lock(&pdss->pdss_lock);
		pdss->pdss_pd_lock(pdss->pdss_pd_lock_arg);
		_flush(pdss);
		pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
		pthread_mutex_unlock(&pdss->pdss_lock);
		result(pdss, cmdtag, "200 glug glug");
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}
	if ((res = regexec(&walkex, line, 5, pmatch, 0)) == 0) {
		wa_t wa;

		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			free(cmdtag); cmdtag = NULL;
			return;
		}
		if (!getmatchsub(line, &cmdstr, pmatch, 2) || !cmdstr)
			goto fail;
		if (!getmatchsub(line, &buf, pmatch, 3) || !buf) {
			free(cmdstr); cmdstr = NULL;
			goto fail;
		}
		if ((regcomp(&wa.wa_regex, buf, REG_EXTENDED)) != 0) {
			free(cmdstr); cmdstr = NULL;
			free(buf); buf = NULL;
			result(pdss, cmdtag, "305 expression error"); 
			if (cmdtag) {
				free(cmdtag); cmdtag = NULL;
			}
			return;
		}
		wa.wa_pdss = pdss;
		wa.wa_cmdtag = cmdtag;
		wa.wa_l = NULL;
		pdss->pdss_pd_lock(pdss->pdss_pd_lock_arg);
		if (!pdict_walk(pdss->pdss_pd, add_to_wa_list, &wa)) {
			int e = errno;
			pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
			pu_log(PUL_WARN, pdss->pdss_id, strerror(e));
			result(pdss, cmdtag, "300 temporary failure: %s",
			    strerror(e)); 
		} else {
			pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
			if (strcmp(cmdstr, "remove") == 0)
				plist_walk(wa.wa_l, remove_wa_list, &wa);
			else
				plist_walk(wa.wa_l, print_wa_list, &wa);
			result(pdss, cmdtag, "200 done");
		}
		plist_clear(&wa.wa_l);
		regfree(&wa.wa_regex);
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		free(cmdstr); cmdstr = NULL;
		free(buf); buf = NULL;
		return;
	}
	if ((res = regexec(&ignoreex, line, 5, pmatch, 0)) == 0) {
		notify_arg_t *nap;
		notify_arg_t na;
		void *arg[2];
		int n;

		getmatchsub(line, &cmdtag, pmatch, 1);
		if (cmdtag && strcmp(cmdtag, "unknown") == 0) {
			result(pdss, cmdtag,
			    "304 unknown is a reserved command tag");
			if (cmdtag) {
				free(cmdtag); cmdtag = NULL;
			}
			return;
		}
		if (!getmatchsub(line, &listenid, pmatch, 2) || !listenid)
			goto fail;
		pthread_mutex_lock(&pdss->pdss_lock);
		pdss->pdss_pd_lock(pdss->pdss_pd_lock_arg);
		na.na_pdss = pdss;
		na.na_listenid = listenid;
		if (!ptree_remove(&na, &pdss->pdss_notify_args, nacmp,
		    (void **)&nap)) {
			pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
			pthread_mutex_unlock(&pdss->pdss_lock);
			result(pdss, cmdtag, "306 nonexistent key/id");
			if (cmdtag) {
				free(cmdtag); cmdtag = NULL;
			}
			return;
		}
		n = 0;
		plist_walk(nap->na_pd_ids, _count, &n);
		plist_walk(nap->na_pd_ids, remove_persistent_change_listener_cb,
		    pdss->pdss_pd);
		arg[0] = (void *)nap->na_listenid;
		arg[1] = &pdss->pdss_pending;
		ptree_walk(pdss->pdss_pending, PTREE_INORDER, remove_pending_id,
		    arg);
		free((void *)nap->na_listenid); nap->na_listenid = NULL;
		plist_clear(&nap->na_pd_ids);
		free(nap); nap = NULL;
		assert(!ptree_contains(&na, pdss->pdss_notify_args, nacmp,
		    NULL));
		pdss->pdss_pd_unlock(pdss->pdss_pd_lock_arg);
		pthread_mutex_unlock(&pdss->pdss_lock);

		result(pdss, cmdtag, "200 %d listener%s ignored", n, n > 1 ? "s"
		    : "");
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		free(listenid);
		return;
	}
	if ((res = regexec(&quitex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		result(pdss, cmdtag, "200 goodbye");
		pdss->pdss_should_close = 1;
		pdss->pdss_close(pdss->pdss_wfd, NULL, 0);
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}
	/* - handled in authenticate
	if ((res = regexec(&nullex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		pdss->pdss_client_cr_null = 1;
		result(pdss, cmdtag, "200 appending NULLs to lines");
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}*/
	if ((res = regexec(&getidex, line, 5, pmatch, 0)) == 0) {
		getmatchsub(line, &cmdtag, pmatch, 1);
		result(pdss, cmdtag, "200 %d", pdss->pdss_id);
		if (cmdtag) {
			free(cmdtag); cmdtag = NULL;
		}
		return;
	}
	
/* - handled in authenticate
#ifndef PDICTSERVER_EXCLUDE_GET_POLICY_FILE
	if ((res = regexec(&policyex, line, 5, pmatch, 0)) == 0) {
		cmdtag = NULL;
		pdss->pdss_client_cr_null = 1;
		result(pdss, cmdtag, get_policy_file(), pdss->pdss_id);
		return;
	}
#endif
*/
	result(pdss, NULL, "400 input unrecognized: %s", line);
	return;
fail:
	result(pdss, cmdtag, "300 command failed: %s", strerror(errno));
	if (cmdtag)
		free (cmdtag);
}
Example #30
0
static int extract(const char *filename, int arglen, char *args[]) {
	xar_t x;
	xar_iter_t i;
	xar_file_t f;
	int files_extracted = 0;

	x = xar_open(filename, READ);
	if( !x ) {
		fprintf(stderr, "Error opening xar archive: %s\n", filename);
		exit(1);
	}

	xar_register_errhandler(x, err_callback, NULL);

	if( Perms == SYMBOLIC ) {
		xar_opt_set(x, XAR_OPT_OWNERSHIP, XAR_OPT_VAL_SYMBOLIC);
	}
	if( Perms == NUMERIC ) {
		xar_opt_set(x, XAR_OPT_OWNERSHIP, XAR_OPT_VAL_NUMERIC);
	}
	if ( Rsize != NULL ) {
		xar_opt_set(x, XAR_OPT_RSIZE, Rsize);
	}
	
	i = xar_iter_new();
	if( !i ) {
		fprintf(stderr, "Error creating xar iterator\n");
		exit(1);
	}

	for(f = xar_file_first(x, i); f; f = xar_file_next(i)) {
		int matched = 0;
		int exclude_match = 1;
		struct lnode *i;

		char *path = xar_get_path(f);

		if( args[0] ) {
			int i;
			for(i = 0; args[i]; i++) {
				if( strcmp(path, args[i]) == 0 ) {
					matched = 1;
					break;
				}
			}
		} else {
			matched = 1;
		}

		for( i = Exclude; i; i=i->next ) {
			exclude_match = regexec(&i->reg, path, 0, NULL, 0);
			if( !exclude_match )
				break;
		}
		if( !exclude_match ) {
			if( Verbose )
				printf("Excluding %s\n", path);
			free(path);
			continue;
		}
		
		if( matched ) {
			files_extracted++;
			print_file(f);
			xar_extract(x, f);
		}
		free(path);
	}
	if( args[0] && (files_extracted == 0) ) {
		fprintf(stderr, "No files matched extraction criteria.\n");
		Err = 3;
	}

	if( Subdoc )
		extract_subdoc(x, NULL);

	xar_iter_free(i);
	if( xar_close(x) != 0 ) {
		fprintf(stderr, "Error extracting the archive\n");
		if( !Err )
			Err = 42;
	}
	return Err;
}