]> git.saurik.com Git - apple/libc.git/blob - gen/FreeBSD/glob.c
Libc-1244.50.9.tar.gz
[apple/libc.git] / gen / FreeBSD / glob.c
1 /*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Guido van Rossum.
7 *
8 * Copyright (c) 2011 The FreeBSD Foundation
9 * All rights reserved.
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "xlocale_private.h"
45
46 /*
47 * glob(3) -- a superset of the one defined in POSIX 1003.2.
48 *
49 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
50 *
51 * Optional extra services, controlled by flags not defined by POSIX:
52 *
53 * GLOB_QUOTE:
54 * Escaping convention: \ inhibits any special meaning the following
55 * character might have (except \ at end of string is retained).
56 * GLOB_MAGCHAR:
57 * Set in gl_flags if pattern contained a globbing character.
58 * GLOB_NOMAGIC:
59 * Same as GLOB_NOCHECK, but it will only append pattern if it did
60 * not contain any magic characters. [Used in csh style globbing]
61 * GLOB_ALTDIRFUNC:
62 * Use alternately specified directory access functions.
63 * GLOB_TILDE:
64 * expand ~user/foo to the /home/dir/of/user/foo
65 * GLOB_BRACE:
66 * expand {1,2}{a,b} to 1a 1b 2a 2b
67 * gl_matchc:
68 * Number of matches in the current invocation of glob.
69 */
70
71 /*
72 * Some notes on multibyte character support:
73 * 1. Patterns with illegal byte sequences match nothing - even if
74 * GLOB_NOCHECK is specified.
75 * 2. Illegal byte sequences in filenames are handled by treating them as
76 * single-byte characters with a values of such bytes of the sequence
77 * cast to wchar_t.
78 * 3. State-dependent encodings are not currently supported.
79 */
80
81 #include <sys/param.h>
82 #include <sys/stat.h>
83
84 #include <ctype.h>
85 #include <dirent.h>
86 #include <errno.h>
87 #include <glob.h>
88 #include <limits.h>
89 #include <pwd.h>
90 #include <stdint.h>
91 #include <stdio.h>
92 #include <stdlib.h>
93 #include <string.h>
94 #include <unistd.h>
95 #include <wchar.h>
96 #include <malloc_private.h>
97
98 #include "collate.h"
99
100 /*
101 * glob(3) expansion limits. Stop the expansion if any of these limits
102 * is reached. This caps the runtime in the face of DoS attacks. See
103 * also CVE-2010-2632
104 */
105 #define GLOB_LIMIT_BRACE 128 /* number of brace calls */
106 #define GLOB_LIMIT_PATH 1024 /* number of path elements */
107 #define GLOB_LIMIT_READDIR 16384 /* number of readdirs */
108 #define GLOB_LIMIT_STAT 128 /* number of stat system calls */
109 #define GLOB_LIMIT_STRING 65536 /* maximum total size for paths */
110
111 struct glob_limit {
112 size_t l_brace_cnt;
113 size_t l_path_lim;
114 size_t l_readdir_cnt;
115 size_t l_stat_cnt;
116 size_t l_string_cnt;
117 };
118
119 #define DOT L'.'
120 #define EOS L'\0'
121 #define LBRACKET L'['
122 #define NOT L'!'
123 #define QUESTION L'?'
124 #define QUOTE L'\\'
125 #define RANGE L'-'
126 #define RBRACKET L']'
127 #define SEP L'/'
128 #define STAR L'*'
129 #define TILDE L'~'
130 #define LBRACE L'{'
131 #define RBRACE L'}'
132 #define COMMA L','
133
134 #define M_QUOTE 0x8000000000ULL
135 #define M_PROTECT 0x4000000000ULL
136 #define M_MASK 0xffffffffffULL
137 #define M_CHAR 0x00ffffffffULL
138
139 typedef uint_fast64_t Char;
140
141 #define CHAR(c) ((Char)((c)&M_CHAR))
142 #define META(c) ((Char)((c)|M_QUOTE))
143 #define UNPROT(c) ((c) & ~M_PROTECT)
144 #define M_ALL META(L'*')
145 #define M_END META(L']')
146 #define M_NOT META(L'!')
147 #define M_ONE META(L'?')
148 #define M_RNG META(L'-')
149 #define M_SET META(L'[')
150 #define ismeta(c) (((c)&M_QUOTE) != 0)
151 #ifdef DEBUG
152 #define isprot(c) (((c)&M_PROTECT) != 0)
153 #endif
154
155
156 #define compare __gl_compare
157 #define g_Ctoc __gl_g_Ctoc
158 #define g_strchr __gl_g_strchr
159 #define globextend __gl_globextend
160 #define globtilde __gl_globtilde
161 #define match __gl_match
162
163 __private_extern__ int compare(const void *, const void *);
164 __private_extern__ int g_Ctoc(const Char *, char *, size_t, locale_t);
165 static int g_lstat(Char *, struct stat *, glob_t *, locale_t);
166 static DIR *g_opendir(Char *, glob_t *, locale_t);
167 __private_extern__ const Char *g_strchr(const Char *, wchar_t);
168 #ifdef notdef
169 static Char *g_strcat(Char *, const Char *);
170 #endif
171 static int g_stat(Char *, struct stat *, glob_t *, locale_t);
172 static int glob0(const Char *, glob_t *, struct glob_limit *,
173 const char *,locale_t);
174 static int glob1(Char *, glob_t *, struct glob_limit *, locale_t);
175 static int glob2(Char *, Char *, Char *, Char *, glob_t *,
176 struct glob_limit *, locale_t);
177 static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *,
178 struct glob_limit *, locale_t);
179 __private_extern__ int globextend(const Char *, glob_t *, struct glob_limit *,
180 const char *, locale_t);
181 __private_extern__ const Char * globtilde(const Char *, Char *, size_t, glob_t *,
182 locale_t);
183 static int globexp0(const Char *, glob_t *, struct glob_limit *,
184 const char *, locale_t);
185 static int globexp1(const Char *, glob_t *, struct glob_limit *, locale_t);
186 static int globexp2(const Char *, const Char *, glob_t *,
187 struct glob_limit *, locale_t);
188 static int globfinal(glob_t *, struct glob_limit *, size_t,
189 const char *, locale_t);
190 __private_extern__ int match(Char *, Char *, Char *, locale_t);
191 static int err_nomatch(glob_t *, struct glob_limit *, const char *, locale_t loc);
192 static int err_aborted(glob_t *, int, char *);
193 #ifdef DEBUG
194 static void qprintf(const char *, Char *);
195 #endif
196
197 static int
198 __glob(const char *pattern, glob_t *pglob)
199 {
200 struct glob_limit limit = { 0, 0, 0, 0, 0 };
201 const char *patnext;
202 Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
203 mbstate_t mbs;
204 wchar_t wc;
205 size_t clen;
206 int too_long;
207 locale_t loc = __current_locale();
208 int mb_cur_max = MB_CUR_MAX_L(loc);
209
210 patnext = pattern;
211 if (!(pglob->gl_flags & GLOB_APPEND)) {
212 pglob->gl_pathc = 0;
213 pglob->gl_pathv = NULL;
214 if (!(pglob->gl_flags & GLOB_DOOFFS))
215 pglob->gl_offs = 0;
216 }
217 if (pglob->gl_flags & GLOB_LIMIT) {
218 limit.l_path_lim = pglob->gl_matchc;
219 if (limit.l_path_lim == 0)
220 limit.l_path_lim = GLOB_LIMIT_PATH;
221 }
222 pglob->gl_matchc = 0;
223
224 bufnext = patbuf;
225 bufend = bufnext + MAXPATHLEN - 1;
226 too_long = 1;
227 if (pglob->gl_flags & GLOB_NOESCAPE) {
228 memset(&mbs, 0, sizeof(mbs));
229 while (bufend - bufnext >= mb_cur_max) {
230 clen = mbrtowc_l(&wc, patnext, MB_LEN_MAX, &mbs, loc);
231 if (clen == (size_t)-1 || clen == (size_t)-2)
232 return (err_nomatch(pglob, &limit, pattern, loc));
233 else if (clen == 0) {
234 too_long = 0;
235 break;
236 }
237 *bufnext++ = wc;
238 patnext += clen;
239 }
240 } else {
241 /* Protect the quoted characters. */
242 memset(&mbs, 0, sizeof(mbs));
243 while (bufend - bufnext >= mb_cur_max) {
244 if (*patnext == '\\') {
245 if (*++patnext == '\0') {
246 *bufnext++ = QUOTE;
247 continue;
248 }
249 prot = M_PROTECT;
250 } else
251 prot = 0;
252 clen = mbrtowc_l(&wc, patnext, MB_LEN_MAX, &mbs, loc);
253 if (clen == (size_t)-1 || clen == (size_t)-2)
254 return (err_nomatch(pglob, &limit, pattern, loc));
255 else if (clen == 0) {
256 too_long = 0;
257 break;
258 }
259 *bufnext++ = wc | prot;
260 patnext += clen;
261 }
262 }
263 if (too_long)
264 return (err_nomatch(pglob, &limit, pattern, loc));
265 *bufnext = EOS;
266
267 if (pglob->gl_flags & GLOB_BRACE)
268 return globexp0(patbuf, pglob, &limit, pattern, loc);
269 else
270 return glob0(patbuf, pglob, &limit, pattern, loc);
271 }
272
273 int
274 glob(const char *pattern, int flags, int (*errfunc)(const char *, int), glob_t *pglob)
275 {
276 #ifdef __BLOCKS__
277 pglob->gl_flags = flags & ~(GLOB_MAGCHAR | _GLOB_ERR_BLOCK);
278 #else /* !__BLOCKS__ */
279 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
280 #endif /* __BLOCKS__ */
281 pglob->gl_errfunc = errfunc;
282 return __glob(pattern, pglob);
283 }
284
285 #ifdef __BLOCKS__
286 int
287 glob_b(const char *pattern, int flags, int (^errblk)(const char *, int), glob_t *pglob)
288 {
289 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
290 pglob->gl_flags |= _GLOB_ERR_BLOCK;
291 pglob->gl_errblk = errblk;
292 return __glob(pattern, pglob);
293 }
294 #endif /* __BLOCKS__ */
295
296 static int
297 globexp0(const Char *pattern, glob_t *pglob, struct glob_limit *limit,
298 const char *origpat, locale_t loc) {
299 int rv;
300 size_t oldpathc;
301
302 /* Protect a single {}, for find(1), like csh */
303 if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) {
304 if ((pglob->gl_flags & GLOB_LIMIT) &&
305 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
306 errno = E2BIG;
307 return (GLOB_NOSPACE);
308 }
309 return (glob0(pattern, pglob, limit, origpat, loc));
310 }
311
312 oldpathc = pglob->gl_pathc;
313
314 if ((rv = globexp1(pattern, pglob, limit, loc)) != 0)
315 return rv;
316
317 return (globfinal(pglob, limit, oldpathc, origpat, loc));
318 }
319
320 /*
321 * Expand recursively a glob {} pattern. When there is no more expansion
322 * invoke the standard globbing routine to glob the rest of the magic
323 * characters
324 */
325 static int
326 globexp1(const Char *pattern, glob_t *pglob, struct glob_limit *limit, locale_t loc)
327 {
328 const Char* ptr;
329
330 if ((ptr = g_strchr(pattern, LBRACE)) != NULL) {
331 if ((pglob->gl_flags & GLOB_LIMIT) &&
332 limit->l_brace_cnt++ >= GLOB_LIMIT_BRACE) {
333 errno = E2BIG;
334 return (GLOB_NOSPACE);
335 }
336 return (globexp2(ptr, pattern, pglob, limit, loc));
337 }
338
339 return (glob0(pattern, pglob, limit, NULL, loc));
340 }
341
342
343 /*
344 * Recursive brace globbing helper. Tries to expand a single brace.
345 * If it succeeds then it invokes globexp1 with the new pattern.
346 * If it fails then it tries to glob the rest of the pattern and returns.
347 */
348 static int
349 globexp2(const Char *ptr, const Char *pattern, glob_t *pglob,
350 struct glob_limit *limit, locale_t loc)
351 {
352 int i, rv;
353 Char *lm, *ls;
354 const Char *pe, *pm, *pm1, *pl;
355 Char patbuf[MAXPATHLEN];
356
357 /* copy part up to the brace */
358 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
359 continue;
360 *lm = EOS;
361 ls = lm;
362
363 /* Find the balanced brace */
364 for (i = 0, pe = ++ptr; *pe != EOS; pe++)
365 if (*pe == LBRACKET) {
366 /* Ignore everything between [] */
367 for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
368 continue;
369 if (*pe == EOS) {
370 /*
371 * We could not find a matching RBRACKET.
372 * Ignore and just look for RBRACE
373 */
374 pe = pm;
375 }
376 }
377 else if (*pe == LBRACE)
378 i++;
379 else if (*pe == RBRACE) {
380 if (i == 0)
381 break;
382 i--;
383 }
384
385 /* Non matching braces; just glob the pattern */
386 if (i != 0 || *pe == EOS)
387 return (glob0(pattern, pglob, limit, NULL, loc));
388
389 for (i = 0, pl = pm = ptr; pm <= pe; pm++)
390 switch (*pm) {
391 case LBRACKET:
392 /* Ignore everything between [] */
393 for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
394 continue;
395 if (*pm == EOS) {
396 /*
397 * We could not find a matching RBRACKET.
398 * Ignore and just look for RBRACE
399 */
400 pm = pm1;
401 }
402 break;
403
404 case LBRACE:
405 i++;
406 break;
407
408 case RBRACE:
409 if (i) {
410 i--;
411 break;
412 }
413 /* FALLTHROUGH */
414 case COMMA:
415 if (i && *pm == COMMA)
416 break;
417 else {
418 /* Append the current string */
419 for (lm = ls; (pl < pm); *lm++ = *pl++)
420 continue;
421 /*
422 * Append the rest of the pattern after the
423 * closing brace
424 */
425 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
426 continue;
427
428 /* Expand the current pattern */
429 #ifdef DEBUG
430 qprintf("globexp2:", patbuf);
431 #endif
432 rv = globexp1(patbuf, pglob, limit, loc);
433 if (rv)
434 return (rv);
435
436 /* move after the comma, to the next string */
437 pl = pm + 1;
438 }
439 break;
440
441 default:
442 break;
443 }
444 return (0);
445 }
446
447
448
449 #ifndef BUILDING_VARIANT
450 /*
451 * expand tilde from the passwd file.
452 */
453 __private_extern__ const Char *
454 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob, locale_t loc)
455 {
456 struct passwd *pwd;
457 char *h, *sc;
458 const Char *p;
459 Char *b, *eb;
460 wchar_t wc;
461 wchar_t wbuf[MAXPATHLEN];
462 wchar_t *wbufend, *dc;
463 size_t clen;
464 mbstate_t mbs;
465 int too_long;
466
467 if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
468 return (pattern);
469
470 /*
471 * Copy up to the end of the string or /
472 */
473 eb = &patbuf[patbuf_len - 1];
474 for (p = pattern + 1, b = patbuf;
475 b < eb && *p != EOS && UNPROT(*p) != SEP; *b++ = *p++)
476 continue;
477
478 if (*p != EOS && UNPROT(*p) != SEP)
479 return (NULL);
480
481 *b = EOS;
482 h = NULL;
483
484 if (patbuf[0] == EOS) {
485 /*
486 * handle a plain ~ or ~/ by expanding $HOME first (iff
487 * we're not running setuid or setgid) and then trying
488 * the password file
489 */
490 if (issetugid() != 0 ||
491 (h = getenv("HOME")) == NULL) {
492 if (((h = getlogin()) != NULL &&
493 (pwd = getpwnam(h)) != NULL) ||
494 (pwd = getpwuid(getuid())) != NULL)
495 h = pwd->pw_dir;
496 else
497 return (pattern);
498 }
499 }
500 else {
501 /*
502 * Expand a ~user
503 */
504 if (g_Ctoc(patbuf, (char *)wbuf, sizeof(wbuf), loc))
505 return (NULL);
506 if ((pwd = getpwnam((char *)wbuf)) == NULL)
507 return (pattern);
508 else
509 h = pwd->pw_dir;
510 }
511
512 /* Copy the home directory */
513 dc = wbuf;
514 sc = h;
515 wbufend = wbuf + MAXPATHLEN - 1;
516 too_long = 1;
517 memset(&mbs, 0, sizeof(mbs));
518 while (dc <= wbufend) {
519 clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
520 if (clen == (size_t)-1 || clen == (size_t)-2) {
521 /* XXX See initial comment #2. */
522 wc = (unsigned char)*sc;
523 clen = 1;
524 memset(&mbs, 0, sizeof(mbs));
525 }
526 if ((*dc++ = wc) == EOS) {
527 too_long = 0;
528 break;
529 }
530 sc += clen;
531 }
532 if (too_long)
533 return (NULL);
534
535 dc = wbuf;
536 for (b = patbuf; b < eb && *dc != EOS; *b++ = *dc++ | M_PROTECT)
537 continue;
538 if (*dc != EOS)
539 return (NULL);
540
541 /* Append the rest of the pattern */
542 if (*p != EOS) {
543 too_long = 1;
544 while (b <= eb) {
545 if ((*b++ = *p++) == EOS) {
546 too_long = 0;
547 break;
548 }
549 }
550 if (too_long)
551 return (NULL);
552 } else
553 *b = EOS;
554
555 return (patbuf);
556 }
557 #endif /* BUILDING_VARIANT */
558
559
560 /*
561 * The main glob() routine: compiles the pattern (optionally processing
562 * quotes), calls glob1() to do the real pattern matching, and finally
563 * sorts the list (unless unsorted operation is requested). Returns 0
564 * if things went well, nonzero if errors occurred.
565 */
566 static int
567 glob0(const Char *pattern, glob_t *pglob, struct glob_limit *limit,
568 const char *origpat, locale_t loc)
569 {
570 const Char *qpatnext;
571 int err;
572 size_t oldpathc;
573 Char *bufnext, c, patbuf[MAXPATHLEN];
574
575 qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob, loc);
576 if (qpatnext == NULL) {
577 errno = E2BIG;
578 return (GLOB_NOSPACE);
579 }
580 oldpathc = pglob->gl_pathc;
581 bufnext = patbuf;
582
583 /* We don't need to check for buffer overflow any more. */
584 while ((c = *qpatnext++) != EOS) {
585 switch (c) {
586 case LBRACKET:
587 c = *qpatnext;
588 if (c == NOT)
589 ++qpatnext;
590 if (*qpatnext == EOS ||
591 g_strchr(qpatnext+1, RBRACKET) == NULL) {
592 *bufnext++ = LBRACKET;
593 if (c == NOT)
594 --qpatnext;
595 break;
596 }
597 *bufnext++ = M_SET;
598 if (c == NOT)
599 *bufnext++ = M_NOT;
600 c = *qpatnext++;
601 do {
602 *bufnext++ = CHAR(c);
603 if (*qpatnext == RANGE &&
604 (c = qpatnext[1]) != RBRACKET) {
605 *bufnext++ = M_RNG;
606 *bufnext++ = CHAR(c);
607 qpatnext += 2;
608 }
609 } while ((c = *qpatnext++) != RBRACKET);
610 pglob->gl_flags |= GLOB_MAGCHAR;
611 *bufnext++ = M_END;
612 break;
613 case QUESTION:
614 pglob->gl_flags |= GLOB_MAGCHAR;
615 *bufnext++ = M_ONE;
616 break;
617 case STAR:
618 pglob->gl_flags |= GLOB_MAGCHAR;
619 /* collapse adjacent stars to one,
620 * to ensure "**" at the end continues to match the
621 * empty string
622 */
623 if (bufnext == patbuf || bufnext[-1] != M_ALL)
624 *bufnext++ = M_ALL;
625 break;
626 default:
627 *bufnext++ = CHAR(c);
628 break;
629 }
630 }
631 *bufnext = EOS;
632 #ifdef DEBUG
633 qprintf("glob0:", patbuf);
634 #endif
635
636 if ((err = glob1(patbuf, pglob, limit, loc)) != 0)
637 return(err);
638
639 if (origpat != NULL)
640 return (globfinal(pglob, limit, oldpathc, origpat, loc));
641
642 return (0);
643 }
644
645 static int
646 globfinal(glob_t *pglob, struct glob_limit *limit, size_t oldpathc,
647 const char *origpat, locale_t loc) {
648 if (pglob->gl_pathc == oldpathc)
649 return (err_nomatch(pglob, limit, origpat, loc));
650
651 if (!(pglob->gl_flags & GLOB_NOSORT))
652 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
653 pglob->gl_pathc - oldpathc, sizeof(char *), compare);
654
655 return (0);
656 }
657
658 #ifndef BUILDING_VARIANT
659 __private_extern__ int
660 compare(const void *p, const void *q)
661 {
662 return(strcoll(*(char **)p, *(char **)q));
663 }
664 #endif /* BUILDING_VARIANT */
665
666 static int
667 glob1(Char *pattern, glob_t *pglob, struct glob_limit *limit, locale_t loc)
668 {
669 Char pathbuf[MAXPATHLEN];
670
671 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
672 if (*pattern == EOS)
673 return (0);
674 return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
675 pattern, pglob, limit, loc));
676 }
677
678 /*
679 * The functions glob2 and glob3 are mutually recursive; there is one level
680 * of recursion for each segment in the pattern that contains one or more
681 * meta characters.
682 */
683 static int
684 glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
685 glob_t *pglob, struct glob_limit *limit, locale_t loc)
686 {
687 struct stat sb;
688 Char *p, *q;
689 int anymeta;
690
691 /*
692 * Loop over pattern segments until end of pattern or until
693 * segment with meta character found.
694 */
695 for (anymeta = 0;;) {
696 if (*pattern == EOS) { /* End of pattern? */
697 *pathend = EOS;
698 if (g_lstat(pathbuf, &sb, pglob, loc))
699 return (0);
700
701 if ((pglob->gl_flags & GLOB_LIMIT) &&
702 limit->l_stat_cnt++ >= GLOB_LIMIT_STAT) {
703 errno = E2BIG;
704 return (GLOB_NOSPACE);
705 }
706 if ((pglob->gl_flags & GLOB_MARK) &&
707 UNPROT(pathend[-1]) != SEP &&
708 (S_ISDIR(sb.st_mode) ||
709 (S_ISLNK(sb.st_mode) &&
710 g_stat(pathbuf, &sb, pglob, loc) == 0 &&
711 S_ISDIR(sb.st_mode)))) {
712 if (pathend + 1 > pathend_last) {
713 errno = E2BIG;
714 return (GLOB_NOSPACE);
715 }
716 *pathend++ = SEP;
717 *pathend = EOS;
718 }
719 ++pglob->gl_matchc;
720 return (globextend(pathbuf, pglob, limit, NULL, loc));
721 }
722
723 /* Find end of next segment, copy tentatively to pathend. */
724 q = pathend;
725 p = pattern;
726 while (*p != EOS && UNPROT(*p) != SEP) {
727 if (ismeta(*p))
728 anymeta = 1;
729 if (q + 1 > pathend_last) {
730 errno = E2BIG;
731 return (GLOB_NOSPACE);
732 }
733 *q++ = *p++;
734 }
735
736 if (!anymeta) { /* No expansion, do next segment. */
737 pathend = q;
738 pattern = p;
739 while (UNPROT(*pattern) == SEP) {
740 if (pathend + 1 > pathend_last) {
741 errno = E2BIG;
742 return (GLOB_NOSPACE);
743 }
744 *pathend++ = *pattern++;
745 }
746 } else /* Need expansion, recurse. */
747 return(glob3(pathbuf, pathend, pathend_last, pattern,
748 p, pglob, limit, loc));
749 }
750 /* NOTREACHED */
751 }
752
753 static int
754 glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
755 Char *pattern, Char *restpattern,
756 glob_t *pglob, struct glob_limit *limit, locale_t loc)
757 {
758 struct dirent *dp;
759 DIR *dirp;
760 int err, too_long, saverrno, saverrno2;
761 char buf[MAXPATHLEN + MB_LEN_MAX - 1];
762
763 /*
764 * The readdirfunc declaration can't be prototyped, because it is
765 * assigned, below, to two functions which are prototyped in glob.h
766 * and dirent.h as taking pointers to differently typed opaque
767 * structures.
768 */
769 struct dirent *(*readdirfunc)();
770
771 if (pathend > pathend_last) {
772 errno = E2BIG;
773 return (GLOB_NOSPACE);
774 }
775 *pathend = EOS;
776 if ((pglob->gl_errfunc != NULL || pglob->gl_errblk != NULL) &&
777 g_Ctoc(pathbuf, buf, sizeof(buf), loc)) {
778 errno = E2BIG;
779 return (GLOB_NOSPACE);
780 }
781
782 saverrno = errno;
783 errno = 0;
784
785 if ((dirp = g_opendir(pathbuf, pglob, loc)) == NULL) {
786 if (errno == ENOENT || errno == ENOTDIR)
787 return (0);
788
789 err = err_aborted(pglob, errno, buf);
790 if (errno == 0)
791 errno = saverrno;
792 return (err);
793 }
794
795 err = 0;
796
797 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
798 readdirfunc = pglob->gl_readdir;
799 else
800 readdirfunc = readdir;
801
802 errno = 0;
803 /* Search directory for matching names. */
804 while ((dp = (*readdirfunc)(dirp)) != NULL) {
805 char *sc;
806 Char *dc;
807 wchar_t wc;
808 size_t clen;
809 mbstate_t mbs;
810
811 if ((pglob->gl_flags & GLOB_LIMIT) &&
812 limit->l_readdir_cnt++ >= GLOB_LIMIT_READDIR) {
813 errno = E2BIG;
814 err = GLOB_NOSPACE;
815 break;
816 }
817
818 /* Initial DOT must be matched literally. */
819 if (dp->d_name[0] == '.' && UNPROT(*pattern) != DOT) {
820 errno = 0;
821 continue;
822 }
823 memset(&mbs, 0, sizeof(mbs));
824 dc = pathend;
825 sc = dp->d_name;
826 too_long = 1;
827 while (dc <= pathend_last) {
828 clen = mbrtowc_l(&wc, sc, MB_LEN_MAX, &mbs, loc);
829 if (clen == (size_t)-1 || clen == (size_t)-2) {
830 /* XXX See initial comment #2. */
831 wc = (unsigned char)*sc;
832 clen = 1;
833 memset(&mbs, 0, sizeof(mbs));
834 }
835 if ((*dc++ = wc) == EOS) {
836 too_long = 0;
837 break;
838 }
839 sc += clen;
840 }
841 if (too_long && (err = err_aborted(pglob, ENAMETOOLONG,
842 buf))) {
843 errno = ENAMETOOLONG;
844 break;
845 }
846 if (too_long || !match(pathend, pattern, restpattern, loc)) {
847 *pathend = EOS;
848 errno = 0;
849 continue;
850 }
851 if (errno == 0)
852 errno = saverrno;
853 err = glob2(pathbuf, --dc, pathend_last, restpattern,
854 pglob, limit, loc);
855 if (err)
856 break;
857 errno = 0;
858 }
859
860 saverrno2 = errno;
861 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
862 (*pglob->gl_closedir)(dirp);
863 else
864 closedir(dirp);
865 errno = saverrno2;
866
867 if (err)
868 return (err);
869
870 if (dp == NULL && errno != 0 &&
871 (err = err_aborted(pglob, errno, buf)))
872 return (err);
873
874 if (errno == 0)
875 errno = saverrno;
876 return (0);
877 }
878
879
880 #ifndef BUILDING_VARIANT
881 /*
882 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
883 * add the new item, and update gl_pathc.
884 *
885 * This assumes the BSD realloc, which only copies the block when its size
886 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
887 * behavior.
888 *
889 * Return 0 if new item added, error code if memory couldn't be allocated.
890 *
891 * Invariant of the glob_t structure:
892 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
893 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
894 */
895 __private_extern__ int
896 globextend(const Char *path, glob_t *pglob, struct glob_limit *limit,
897 const char *origpat, locale_t loc)
898 {
899 char **pathv;
900 size_t i, newn, len;
901 char *copy;
902 const Char *p;
903
904 if ((pglob->gl_flags & GLOB_LIMIT) &&
905 pglob->gl_matchc > limit->l_path_lim) {
906 errno = E2BIG;
907 return (GLOB_NOSPACE);
908 }
909
910 newn = 2 + pglob->gl_pathc + pglob->gl_offs;
911 /* reallocarray(NULL, newn, size) is equivalent to malloc(newn*size). */
912 pathv = reallocarray(pglob->gl_pathv, newn, sizeof(*pathv));
913 if (pathv == NULL)
914 return (GLOB_NOSPACE);
915
916 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
917 /* first time around -- clear initial gl_offs items */
918 pathv += pglob->gl_offs;
919 for (i = pglob->gl_offs + 1; --i > 0; )
920 *--pathv = NULL;
921 }
922 pglob->gl_pathv = pathv;
923
924 if (origpat != NULL)
925 copy = strdup(origpat);
926 else {
927 for (p = path; *p++ != EOS;)
928 continue;
929 len = MB_CUR_MAX_L(loc) * (size_t)(p - path); /* XXX overallocation */
930 if ((copy = malloc(len)) != NULL) {
931 if (g_Ctoc(path, copy, len, loc)) {
932 free(copy);
933 errno = E2BIG;
934 return (GLOB_NOSPACE);
935 }
936 }
937 }
938 if (copy != NULL) {
939 limit->l_string_cnt += strlen(copy) + 1;
940 if ((pglob->gl_flags & GLOB_LIMIT) &&
941 limit->l_string_cnt >= GLOB_LIMIT_STRING) {
942 free(copy);
943 errno = E2BIG;
944 return (GLOB_NOSPACE);
945 }
946 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
947 }
948 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
949 return (copy == NULL ? GLOB_NOSPACE : 0);
950 }
951
952 /*
953 * pattern matching function for filenames.
954 */
955 __private_extern__ int
956 match(Char *name, Char *pat, Char *patend, locale_t loc)
957 {
958 int ok, negate_range;
959 Char c, k, *nextp, *nextn;
960
961 nextn = NULL;
962 nextp = NULL;
963
964 while (1) {
965 while (pat < patend) {
966 c = *pat++;
967 switch (c & M_MASK) {
968 case M_ALL:
969 if (pat == patend)
970 return (1);
971 if (*name == EOS)
972 return (0);
973 nextn = name + 1;
974 nextp = pat - 1;
975 break;
976 case M_ONE:
977 if (*name++ == EOS)
978 goto fail;
979 break;
980 case M_SET:
981 ok = 0;
982 if ((k = *name++) == EOS)
983 goto fail;
984 negate_range = ((*pat & M_MASK) == M_NOT);
985 if (negate_range != 0)
986 ++pat;
987 while (((c = *pat++) & M_MASK) != M_END)
988 if ((*pat & M_MASK) == M_RNG) {
989 if (loc->__collate_load_error ?
990 CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
991 __collate_range_cmp(CHAR(c), CHAR(k), loc) <= 0
992 && __collate_range_cmp(CHAR(k), CHAR(pat[1]), loc) <= 0
993 ) {
994 ok = 1;
995 }
996 pat += 2;
997 } else if (c == k)
998 ok = 1;
999 if (ok == negate_range)
1000 goto fail;
1001 break;
1002 default:
1003 if (*name++ != c)
1004 goto fail;
1005 break;
1006 }
1007 }
1008 if (*name == EOS)
1009 return (1);
1010
1011 fail:
1012 if (nextn == NULL)
1013 break;
1014 pat = nextp;
1015 name = nextn;
1016 }
1017 return (0);
1018 }
1019
1020 /* Free allocated data belonging to a glob_t structure. */
1021 void
1022 globfree(glob_t *pglob)
1023 {
1024 size_t i;
1025 char **pp;
1026
1027 if (pglob->gl_pathv != NULL) {
1028 pp = pglob->gl_pathv + pglob->gl_offs;
1029 for (i = pglob->gl_pathc; i--; ++pp)
1030 if (*pp)
1031 free(*pp);
1032 free(pglob->gl_pathv);
1033 pglob->gl_pathv = NULL;
1034 }
1035 }
1036 #endif /* !BUILDING_VARIANT */
1037
1038 static DIR *
1039 g_opendir(Char *str, glob_t *pglob, locale_t loc)
1040 {
1041 char buf[MAXPATHLEN + MB_LEN_MAX - 1];
1042
1043 if (*str == EOS)
1044 strcpy(buf, ".");
1045 else {
1046 if (g_Ctoc(str, buf, sizeof(buf), loc)) {
1047 errno = ENAMETOOLONG;
1048 return (NULL);
1049 }
1050 }
1051
1052 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1053 return ((*pglob->gl_opendir)(buf));
1054
1055 return (opendir(buf));
1056 }
1057
1058 static int
1059 g_lstat(Char *fn, struct stat *sb, glob_t *pglob, locale_t loc)
1060 {
1061 char buf[MAXPATHLEN + MB_LEN_MAX - 1];
1062
1063 if (g_Ctoc(fn, buf, sizeof(buf), loc)) {
1064 errno = ENAMETOOLONG;
1065 return (-1);
1066 }
1067 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1068 return((*pglob->gl_lstat)(buf, sb));
1069 return (lstat(buf, sb));
1070 }
1071
1072 static int
1073 g_stat(Char *fn, struct stat *sb, glob_t *pglob, locale_t loc)
1074 {
1075 char buf[MAXPATHLEN + MB_LEN_MAX - 1];
1076
1077 if (g_Ctoc(fn, buf, sizeof(buf), loc)) {
1078 errno = ENAMETOOLONG;
1079 return (-1);
1080 }
1081 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1082 return ((*pglob->gl_stat)(buf, sb));
1083 return (stat(buf, sb));
1084 }
1085
1086 #ifndef BUILDING_VARIANT
1087 __private_extern__ const Char *
1088 g_strchr(const Char *str, wchar_t ch)
1089 {
1090
1091 do {
1092 if (*str == ch)
1093 return (str);
1094 } while (*str++);
1095 return (NULL);
1096 }
1097
1098 __private_extern__ int
1099 g_Ctoc(const Char *str, char *buf, size_t len, locale_t loc)
1100 {
1101 mbstate_t mbs;
1102 size_t clen;
1103 int mb_cur_max = MB_CUR_MAX_L(loc);
1104
1105 memset(&mbs, 0, sizeof(mbs));
1106 while (len >= mb_cur_max) {
1107 clen = wcrtomb_l(buf, *str, &mbs, loc);
1108 if (clen == (size_t)-1) {
1109 /* XXX See initial comment #2. */
1110 *buf = (char)CHAR(*str);
1111 clen = 1;
1112 memset(&mbs, 0, sizeof(mbs));
1113 }
1114 if (CHAR(*str) == EOS)
1115 return (0);
1116 str++;
1117 buf += clen;
1118 len -= clen;
1119 }
1120 return (1);
1121 }
1122 #endif /* !BUILDING_VARIANT */
1123
1124 static int
1125 err_nomatch(glob_t *pglob, struct glob_limit *limit, const char *origpat, locale_t loc) {
1126 /*
1127 * If there was no match we are going to append the origpat
1128 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
1129 * and the origpat did not contain any magic characters
1130 * GLOB_NOMAGIC is there just for compatibility with csh.
1131 */
1132 if ((pglob->gl_flags & GLOB_NOCHECK) ||
1133 ((pglob->gl_flags & GLOB_NOMAGIC) &&
1134 !(pglob->gl_flags & GLOB_MAGCHAR)))
1135 return (globextend(NULL, pglob, limit, origpat, loc));
1136 return (GLOB_NOMATCH);
1137 }
1138
1139 static int
1140 err_aborted(glob_t *pglob, int err, char *buf) {
1141 #ifdef __BLOCKS__
1142 if (pglob->gl_flags & _GLOB_ERR_BLOCK && pglob->gl_errblk(buf, errno)) {
1143 return (GLOB_ABORTED);
1144 } else
1145 #endif /* __BLOCKS__ */
1146 if (pglob->gl_errfunc != NULL && pglob->gl_errfunc(buf, errno)) {
1147 return (GLOB_ABORTED);
1148 } else if (pglob->gl_flags & GLOB_ERR) {
1149 return (GLOB_ABORTED);
1150 }
1151 return (0);
1152 }
1153
1154 #ifdef DEBUG
1155 static void
1156 qprintf(const char *str, Char *s)
1157 {
1158 Char *p;
1159
1160 (void)printf("%s\n", str);
1161 if (s != NULL) {
1162 for (p = s; *p != EOS; p++)
1163 (void)printf("%c", (char)CHAR(*p));
1164 (void)printf("\n");
1165 for (p = s; *p != EOS; p++)
1166 (void)printf("%c", (isprot(*p) ? '\\' : ' '));
1167 (void)printf("\n");
1168 for (p = s; *p != EOS; p++)
1169 (void)printf("%c", (ismeta(*p) ? '_' : ' '));
1170 (void)printf("\n");
1171 }
1172 }
1173 #endif