summaryrefslogtreecommitdiffstats
path: root/usr/klibc/fnmatch.c
blob: 5d0a25f9bdc64f2b49997d721d838a9b2880cce3 (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
68
69
70
71
72
/*
 * fnmatch.c
 *
 * Original implementation by Kay Sievers, modified by H. Peter Anvin.
 */

#include <fnmatch.h>

int fnmatch(const char *p, const char *s, int flags)
{
	if (flags & FNM_PATHNAME && *s == '/')
		return (*p != '/') || fnmatch(p+1, s+1, flags);
	if (flags & FNM_PERIOD && *s == '.')
		return (*p != '.') || fnmatch(p+1, s+1, flags);

	flags &= ~FNM_PERIOD;	/* Only applies at beginning */

	if (!(flags & FNM_NOESCAPE) && *p == '\\') {
		p++;
		return (*p != *s) || fnmatch(p+1, s+1, flags);
	}

	if (*s == '\0') {
		while (*p == '*')
			p++;
		return (*p != '\0');
	}

	switch (*p) {
	case '[':
		{
			int not = 0;
			p++;
			if (*p == '!') {
				not = 1;
				p++;
			}
			while ((*p != '\0') && (*p != ']')) {
				int match = 0;
				if (p[1] == '-') {
					if ((*s >= *p) && (*s <= p[2]))
						match = 1;
					p += 3;
				} else {
					match = (*p == *s);
					p++;
				}
				if (match ^ not) {
					while ((*p != '\0') && (*p != ']'))
						p++;
					if (*p == ']')
						return fnmatch(p+1, s+1, flags);
				}
			}
		}
		break;
	case '*':
		if (fnmatch(p, s+1, flags))
			return fnmatch(p+1, s, flags);
		return 0;
	case '\0':
		if (*s == '\0') {
			return 0;
		}
		break;
	default:
		if ((*p == *s) || (*p == '?'))
			return fnmatch(p+1, s+1, flags);
		break;
	}
	return 1;
}