aboutsummaryrefslogtreecommitdiff
path: root/src/match_pcre.c
blob: dac61cff43ca79f1c15fb82abd70342bdb1b9778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* This file is part of genrc
Copyryght (C) 2018 Sergey Poznyakoff
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
*/
#include "genrc.h"
#include <pcre.h>

static char *
progname_pattern(char const *prog)
{
	grecs_txtacc_t acc;
	char *ret;
	static char const specials[] = "\\[]?.*+(){}|";
	
	acc = grecs_txtacc_create();
	grecs_txtacc_grow_char(acc, '^');
	if (prog[0] != '/')
		grecs_txtacc_grow_string(acc, "(?:/(?:.*/)?)?");
	for (; *prog; prog++) {
		if (strchr(specials, *prog))
			grecs_txtacc_grow_char(acc, '\\');
		grecs_txtacc_grow_char(acc, *prog);
	}
	grecs_txtacc_grow_char(acc, '$');
	grecs_txtacc_grow_char(acc, 0);
	ret = grecs_txtacc_finish(acc, 1);
	grecs_txtacc_free(acc);
	return ret;
}

void
match_pcre_init(PROCSCANBUF buf, char const *pattern)
{
	pcre *pcre;
	char const *error;
	int error_offset;
	char *tmp = NULL;
	int cflags = 0;
	if (buf->flags & PROCF_ICASE)
		cflags |= PCRE_CASELESS;
	if (!pattern) {
		pattern = tmp = progname_pattern(genrc_program);
	}		
	pcre = pcre_compile(pattern, cflags, &error, &error_offset, 0);
	free(tmp);
	if (!pcre)
		usage_error("%s at offset %d", error, error_offset);
	buf->pattern = pcre;
}

void
match_pcre_free(PROCSCANBUF buf)
{
	pcre_free ((pcre*)buf->pattern);
}

int
match_pcre(PROCSCANBUF buf, char const *arg)
{
	int rc = pcre_exec((pcre*)buf->pattern, 0, arg, strlen(arg),
			   0, 0, NULL, 0);
	return !(rc >= 0);
	/* FIXME: error message unless rc == PCRE_ERROR_NOMATCH */
}

Return to:

Send suggestions and report system problems to the System administrator.