aboutsummaryrefslogtreecommitdiff
path: root/src/match_regex.c
blob: b8549bf7b9faa103d2cc69fdfd144e4ff78ac601 (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
67
/* 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"

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_regex_init(PROCSCANBUF buf, char const *pattern)
{
	regex_t *rx = xmalloc(sizeof(*rx));
	int rc;
	char *tmp = NULL;
	int cflags = REG_EXTENDED|REG_NOSUB;
	if (buf->flags & PROCF_ICASE)
		cflags |= REG_ICASE;
	if (!pattern) {
		pattern = tmp = progname_pattern(genrc_program);
	}
		
	rc = regcomp(rx, pattern, cflags);
	free(tmp);
	if (rc) {
		char errbuf[512];
		regerror(rc, rx, errbuf, sizeof(errbuf));
		usage_error("invalid regular expression: %s", errbuf);
	}
	buf->pattern = rx;
}

void
match_regex_free(PROCSCANBUF buf)
{
	regfree((regex_t*)buf->pattern);
	free(buf->pattern);
}

int
match_regex(PROCSCANBUF buf, char const *arg)
{
	return regexec((regex_t*)buf->pattern, arg, 0, NULL, 0);
}

Return to:

Send suggestions and report system problems to the System administrator.