58248675c203b239cc7fd86c6199cde9b629ff02
[musl] / src / regex / glob.c
1 #define _BSD_SOURCE
2 #include <glob.h>
3 #include <fnmatch.h>
4 #include <sys/stat.h>
5 #include <dirent.h>
6 #include <limits.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <errno.h>
10 #include <stddef.h>
11 #include <unistd.h>
12 #include <pwd.h>
13
14 struct match
15 {
16         struct match *next;
17         char name[];
18 };
19
20 static int append(struct match **tail, const char *name, size_t len, int mark)
21 {
22         struct match *new = malloc(sizeof(struct match) + len + 2);
23         if (!new) return -1;
24         (*tail)->next = new;
25         new->next = NULL;
26         memcpy(new->name, name, len+1);
27         if (mark && len && name[len-1]!='/') {
28                 new->name[len] = '/';
29                 new->name[len+1] = 0;
30         }
31         *tail = new;
32         return 0;
33 }
34
35 static int do_glob(char *buf, size_t pos, int type, char *pat, int flags, int (*errfunc)(const char *path, int err), struct match **tail)
36 {
37         /* If GLOB_MARK is unused, we don't care about type. */
38         if (!type && !(flags & GLOB_MARK)) type = DT_REG;
39
40         /* Special-case the remaining pattern being all slashes, in
41          * which case we can use caller-passed type if it's a dir. */
42         if (*pat && type!=DT_DIR) type = 0;
43         while (pos+1 < PATH_MAX && *pat=='/') buf[pos++] = *pat++;
44
45         /* Consume maximal [escaped-]literal prefix of pattern, copying
46          * and un-escaping it to the running buffer as we go. */
47         ptrdiff_t i=0, j=0;
48         int in_bracket = 0, overflow = 0;
49         for (; pat[i]!='*' && pat[i]!='?' && (!in_bracket || pat[i]!=']'); i++) {
50                 if (!pat[i]) {
51                         if (overflow) return 0;
52                         pat += i;
53                         pos += j;
54                         i = j = 0;
55                         break;
56                 } else if (pat[i] == '[') {
57                         in_bracket = 1;
58                 } else if (pat[i] == '\\' && !(flags & GLOB_NOESCAPE)) {
59                         /* Backslashes inside a bracket are (at least by
60                          * our interpretation) non-special, so if next
61                          * char is ']' we have a complete expression. */
62                         if (in_bracket && pat[i+1]==']') break;
63                         /* Unpaired final backslash never matches. */
64                         if (!pat[i+1]) return 0;
65                         i++;
66                 }
67                 if (pat[i] == '/') {
68                         if (overflow) return 0;
69                         in_bracket = 0;
70                         pat += i+1;
71                         i = -1;
72                         pos += j+1;
73                         j = -1;
74                 }
75                 /* Only store a character if it fits in the buffer, but if
76                  * a potential bracket expression is open, the overflow
77                  * must be remembered and handled later only if the bracket
78                  * is unterminated (and thereby a literal), so as not to
79                  * disallow long bracket expressions with short matches. */
80                 if (pos+(j+1) < PATH_MAX) {
81                         buf[pos+j++] = pat[i];
82                 } else if (in_bracket) {
83                         overflow = 1;
84                 } else {
85                         return 0;
86                 }
87                 /* If we consume any new components, the caller-passed type
88                  * or dummy type from above is no longer valid. */
89                 type = 0;
90         }
91         buf[pos] = 0;
92         if (!*pat) {
93                 /* If we consumed any components above, or if GLOB_MARK is
94                  * requested and we don't yet know if the match is a dir,
95                  * we must call stat to confirm the file exists and/or
96                  * determine its type. */
97                 struct stat st;
98                 if ((flags & GLOB_MARK) && type==DT_LNK) type = 0;
99                 if (!type && stat(buf, &st)) {
100                         if (errno!=ENOENT && (errfunc(buf, errno) || (flags & GLOB_ERR)))
101                                 return GLOB_ABORTED;
102                         return 0;
103                 }
104                 if (!type && S_ISDIR(st.st_mode)) type = DT_DIR;
105                 if (append(tail, buf, pos, (flags & GLOB_MARK) && type==DT_DIR))
106                         return GLOB_NOSPACE;
107                 return 0;
108         }
109         char *p2 = strchr(pat, '/'), saved_sep = '/';
110         /* Check if the '/' was escaped and, if so, remove the escape char
111          * so that it will not be unpaired when passed to fnmatch. */
112         if (p2 && !(flags & GLOB_NOESCAPE)) {
113                 char *p;
114                 for (p=p2; p>pat && p[-1]=='\\'; p--);
115                 if ((p2-p)%2) {
116                         p2--;
117                         saved_sep = '\\';
118                 }
119         }
120         DIR *dir = opendir(pos ? buf : ".");
121         if (!dir) {
122                 if (errfunc(buf, errno) || (flags & GLOB_ERR))
123                         return GLOB_ABORTED;
124                 return 0;
125         }
126         int old_errno = errno;
127         struct dirent *de;
128         while (errno=0, de=readdir(dir)) {
129                 /* Quickly skip non-directories when there's pattern left. */
130                 if (p2 && de->d_type && de->d_type!=DT_DIR && de->d_type!=DT_LNK)
131                         continue;
132
133                 size_t l = strlen(de->d_name);
134                 if (l >= PATH_MAX-pos) continue;
135
136                 if (p2) *p2 = 0;
137
138                 int fnm_flags= ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
139                         | ((!(flags & GLOB_PERIOD)) ? FNM_PERIOD : 0);
140
141                 if (fnmatch(pat, de->d_name, fnm_flags))
142                         continue;
143
144                 /* With GLOB_PERIOD, don't allow matching . or .. unless
145                  * fnmatch would match them with FNM_PERIOD rules in effect. */
146                 if (p2 && (flags & GLOB_PERIOD) && de->d_name[0]=='.'
147                     && (!de->d_name[1] || de->d_name[1]=='.' && !de->d_name[2])
148                     && fnmatch(pat, de->d_name, fnm_flags | FNM_PERIOD))
149                         continue;
150
151                 memcpy(buf+pos, de->d_name, l+1);
152                 if (p2) *p2 = saved_sep;
153                 int r = do_glob(buf, pos+l, de->d_type, p2 ? p2 : "", flags, errfunc, tail);
154                 if (r) {
155                         closedir(dir);
156                         return r;
157                 }
158         }
159         int readerr = errno;
160         if (p2) *p2 = saved_sep;
161         closedir(dir);
162         if (readerr && (errfunc(buf, errno) || (flags & GLOB_ERR)))
163                 return GLOB_ABORTED;
164         errno = old_errno;
165         return 0;
166 }
167
168 static int ignore_err(const char *path, int err)
169 {
170         return 0;
171 }
172
173 static void freelist(struct match *head)
174 {
175         struct match *match, *next;
176         for (match=head->next; match; match=next) {
177                 next = match->next;
178                 free(match);
179         }
180 }
181
182 static int sort(const void *a, const void *b)
183 {
184         return strcmp(*(const char **)a, *(const char **)b);
185 }
186
187 static int expand_tilde(char **pat, char *buf, size_t *pos)
188 {
189         char *p = *pat + 1;
190         size_t i = 0;
191
192         char delim, *name_end = __strchrnul(p, '/');
193         if ((delim = *name_end)) *name_end++ = 0;
194         *pat = name_end;
195
196         char *home = *p ? NULL : getenv("HOME");
197         if (!home) {
198                 struct passwd pw, *res;
199                 switch (*p ? getpwnam_r(p, &pw, buf, PATH_MAX, &res)
200                            : getpwuid_r(getuid(), &pw, buf, PATH_MAX, &res)) {
201                 case ENOMEM:
202                         return GLOB_NOSPACE;
203                 case 0:
204                         if (!res)
205                 default:
206                                 return GLOB_NOMATCH;
207                 }
208                 home = pw.pw_dir;
209         }
210         while (i < PATH_MAX - 2 && *home)
211                 buf[i++] = *home++;
212         if (*home)
213                 return GLOB_NOMATCH;
214         if ((buf[i] = delim))
215                 buf[++i] = 0;
216         *pos = i;
217         return 0;
218 }
219
220 int glob(const char *restrict pat, int flags, int (*errfunc)(const char *path, int err), glob_t *restrict g)
221 {
222         struct match head = { .next = NULL }, *tail = &head;
223         size_t cnt, i;
224         size_t offs = (flags & GLOB_DOOFFS) ? g->gl_offs : 0;
225         int error = 0;
226         char buf[PATH_MAX];
227         
228         if (!errfunc) errfunc = ignore_err;
229
230         if (!(flags & GLOB_APPEND)) {
231                 g->gl_offs = offs;
232                 g->gl_pathc = 0;
233                 g->gl_pathv = NULL;
234         }
235
236         if (*pat) {
237                 char *p = strdup(pat);
238                 if (!p) return GLOB_NOSPACE;
239                 buf[0] = 0;
240                 size_t pos = 0;
241                 char *s = p;
242                 if ((flags & (GLOB_TILDE | GLOB_TILDE_CHECK)) && *p == '~')
243                         error = expand_tilde(&s, buf, &pos);
244                 if (!error)
245                         error = do_glob(buf, pos, 0, s, flags, errfunc, &tail);
246                 free(p);
247         }
248
249         if (error == GLOB_NOSPACE) {
250                 freelist(&head);
251                 return error;
252         }
253         
254         for (cnt=0, tail=head.next; tail; tail=tail->next, cnt++);
255         if (!cnt) {
256                 if (flags & GLOB_NOCHECK) {
257                         tail = &head;
258                         if (append(&tail, pat, strlen(pat), 0))
259                                 return GLOB_NOSPACE;
260                         cnt++;
261                 } else
262                         return GLOB_NOMATCH;
263         }
264
265         if (flags & GLOB_APPEND) {
266                 char **pathv = realloc(g->gl_pathv, (offs + g->gl_pathc + cnt + 1) * sizeof(char *));
267                 if (!pathv) {
268                         freelist(&head);
269                         return GLOB_NOSPACE;
270                 }
271                 g->gl_pathv = pathv;
272                 offs += g->gl_pathc;
273         } else {
274                 g->gl_pathv = malloc((offs + cnt + 1) * sizeof(char *));
275                 if (!g->gl_pathv) {
276                         freelist(&head);
277                         return GLOB_NOSPACE;
278                 }
279                 for (i=0; i<offs; i++)
280                         g->gl_pathv[i] = NULL;
281         }
282         for (i=0, tail=head.next; i<cnt; tail=tail->next, i++)
283                 g->gl_pathv[offs + i] = tail->name;
284         g->gl_pathv[offs + i] = NULL;
285         g->gl_pathc += cnt;
286
287         if (!(flags & GLOB_NOSORT))
288                 qsort(g->gl_pathv+offs, cnt, sizeof(char *), sort);
289         
290         return error;
291 }
292
293 void globfree(glob_t *g)
294 {
295         size_t i;
296         for (i=0; i<g->gl_pathc; i++)
297                 free(g->gl_pathv[g->gl_offs + i] - offsetof(struct match, name));
298         free(g->gl_pathv);
299         g->gl_pathc = 0;
300         g->gl_pathv = NULL;
301 }
302
303 weak_alias(glob, glob64);
304 weak_alias(globfree, globfree64);