blob: 7c6b969ca2271f7125534379598792046b091baa (
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
/* glob.c - the only pattern matching in this program.
*
* Three metacharacters, no library. See the note in authz.h for why this is
* not fnmatch(3) or regex(3). */
#include "authz.h"
/* Length of the class starting at p ('[' ... ']'), or 0 when it is not closed
* and therefore means a literal '['. A ']' first - or first after a negation -
* is a member, like everywhere else. */
static int class_len(const char *p)
{
const char *c = p + 1;
if (*c == '!' || *c == '^')
c++;
if (*c == ']')
c++;
while (*c != '\0' && *c != ']')
c++;
return (*c == ']') ? (int)(c - p) + 1 : 0;
}
/* text is a complete class of len bytes, including the brackets. */
static int class_match(const char *text, int len, char c)
{
const char *p = text + 1;
const char *end = text + len - 1; /* the ']' */
int negate = 0;
int hit = 0;
if (p < end && (*p == '!' || *p == '^')) {
negate = 1;
p++;
}
while (p < end) {
char lo = *p++;
if (p + 1 < end && *p == '-') { /* 'a-z'; a trailing '-' is literal */
char hi = p[1];
p += 2;
if (c >= lo && c <= hi)
hit = 1;
} else if (lo == c) {
hit = 1;
}
}
return negate ? !hit : hit;
}
int glob_match(const char *pattern, const char *s)
{
const char *p = pattern;
const char *t = s;
const char *star = NULL; /* in the pattern, just after the last '*' */
const char *back = NULL; /* in the text, where that '*' may yet start */
int clen;
if (pattern == NULL || s == NULL)
return 0;
while (*t != '\0') {
if (*p == '*') {
star = p + 1;
back = t;
p++;
continue;
}
clen = (*p == '[') ? class_len(p) : 0;
if (clen > 0) {
if (!class_match(p, clen, *t)) {
/* The class was well formed and said no. Backtrack to the
* last '*' rather than comparing '[' against the text: a
* negated class must be able to fail. */
if (star == NULL)
return 0;
p = star;
t = ++back;
continue;
}
p += clen;
t++;
continue;
}
if (*p == '?') {
p++;
t++;
continue;
}
if (*p == *t) {
p++;
t++;
continue;
}
if (star == NULL)
return 0;
p = star;
t = ++back;
}
while (*p == '*')
p++;
return *p == '\0';
}
|