glob.c revision 1.1.1.1.2.2 1 /* Copyright (C) 1991-2002,2003,2004,2005 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 02111-1307 USA. */
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22
23 #include <glob.h>
24
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <stddef.h>
29
30 /* Outcomment the following line for production quality code. */
31 /* #define NDEBUG 1 */
32 #include <assert.h>
33
34 #include <stdio.h> /* Needed on stupid SunOS for assert. */
35
36 #if !defined _LIBC || !defined GLOB_ONLY_P
37 #if defined HAVE_UNISTD_H || defined _LIBC
38 # include <unistd.h>
39 # ifndef POSIX
40 # ifdef _POSIX_VERSION
41 # define POSIX
42 # endif
43 # endif
44 #endif
45
46 #include <pwd.h>
47
48 #include <errno.h>
49 #ifndef __set_errno
50 # define __set_errno(val) errno = (val)
51 #endif
52
53 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
54 # include <dirent.h>
55 # define NAMLEN(dirent) strlen((dirent)->d_name)
56 #else
57 # define dirent direct
58 # define NAMLEN(dirent) (dirent)->d_namlen
59 # ifdef HAVE_SYS_NDIR_H
60 # include <sys/ndir.h>
61 # endif
62 # ifdef HAVE_SYS_DIR_H
63 # include <sys/dir.h>
64 # endif
65 # ifdef HAVE_NDIR_H
66 # include <ndir.h>
67 # endif
68 # ifdef HAVE_VMSDIR_H
69 # include "vmsdir.h"
70 # endif /* HAVE_VMSDIR_H */
71 #endif
72
73
74 /* In GNU systems, <dirent.h> defines this macro for us. */
75 #ifdef _D_NAMLEN
76 # undef NAMLEN
77 # define NAMLEN(d) _D_NAMLEN(d)
78 #endif
79
80 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
81 if the `d_type' member for `struct dirent' is available.
82 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
83 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
84 /* True if the directory entry D must be of type T. */
85 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
86
87 /* True if the directory entry D might be a symbolic link. */
88 # define DIRENT_MIGHT_BE_SYMLINK(d) \
89 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
90
91 /* True if the directory entry D might be a directory. */
92 # define DIRENT_MIGHT_BE_DIR(d) \
93 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
94
95 #else /* !HAVE_D_TYPE */
96 # define DIRENT_MUST_BE(d, t) false
97 # define DIRENT_MIGHT_BE_SYMLINK(d) true
98 # define DIRENT_MIGHT_BE_DIR(d) true
99 #endif /* HAVE_D_TYPE */
100
101 /* If the system has the `struct dirent64' type we use it internally. */
102 #if defined _LIBC && !defined COMPILE_GLOB64
103 # if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
104 # define CONVERT_D_NAMLEN(d64, d32)
105 # else
106 # define CONVERT_D_NAMLEN(d64, d32) \
107 (d64)->d_namlen = (d32)->d_namlen;
108 # endif
109
110 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
111 # define CONVERT_D_INO(d64, d32)
112 # else
113 # define CONVERT_D_INO(d64, d32) \
114 (d64)->d_ino = (d32)->d_ino;
115 # endif
116
117 # ifdef _DIRENT_HAVE_D_TYPE
118 # define CONVERT_D_TYPE(d64, d32) \
119 (d64)->d_type = (d32)->d_type;
120 # else
121 # define CONVERT_D_TYPE(d64, d32)
122 # endif
123
124 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
125 memcpy ((d64)->d_name, (d32)->d_name, NAMLEN (d32) + 1); \
126 CONVERT_D_NAMLEN (d64, d32) \
127 CONVERT_D_INO (d64, d32) \
128 CONVERT_D_TYPE (d64, d32)
129 #endif
130
131
132 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
133 /* Posix does not require that the d_ino field be present, and some
134 systems do not provide it. */
135 # define REAL_DIR_ENTRY(dp) 1
136 #else
137 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
138 #endif /* POSIX */
139
140 #include <stdlib.h>
141 #include <string.h>
142
143 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
144 #include <limits.h>
145 #ifndef NAME_MAX
146 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
147 #endif
148
149 #include <alloca.h>
150
151 #ifdef _LIBC
152 # undef strdup
153 # define strdup(str) __strdup (str)
154 # define sysconf(id) __sysconf (id)
155 # define closedir(dir) __closedir (dir)
156 # define opendir(name) __opendir (name)
157 # define readdir(str) __readdir64 (str)
158 # define getpwnam_r(name, bufp, buf, len, res) \
159 __getpwnam_r (name, bufp, buf, len, res)
160 # ifndef __stat64
161 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
162 # endif
163 # define struct_stat64 struct stat64
164 #else /* !_LIBC */
165 # include "getlogin_r.h"
166 # include "mempcpy.h"
167 # include "stat-macros.h"
168 # include "strdup.h"
169 # define __stat64(fname, buf) stat (fname, buf)
170 # define struct_stat64 struct stat
171 # define __stat(fname, buf) stat (fname, buf)
172 # define __alloca alloca
173 # define __readdir readdir
174 # define __readdir64 readdir64
175 # define __glob_pattern_p glob_pattern_p
176 #endif /* _LIBC */
177
178 #include <stdbool.h>
179 #include <fnmatch.h>
180
181 #ifdef _SC_GETPW_R_SIZE_MAX
182 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
183 #else
184 # define GETPW_R_SIZE_MAX() (-1)
185 #endif
186 #ifdef _SC_LOGIN_NAME_MAX
187 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
188 #else
189 # define GET_LOGIN_NAME_MAX() (-1)
190 #endif
191
192 static const char *next_brace_sub (const char *begin, int flags) __THROW;
194
195 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
196
197 static int glob_in_dir (const char *pattern, const char *directory,
198 int flags, int (*errfunc) (const char *, int),
199 glob_t *pglob);
200
201 #if !defined _LIBC || !defined GLOB_ONLY_P
202 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
203 static int collated_compare (const void *, const void *) __THROW;
204
205
206 /* Find the end of the sub-pattern in a brace expression. */
207 static const char *
208 next_brace_sub (const char *cp, int flags)
209 {
210 unsigned int depth = 0;
211 while (*cp != '\0')
212 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
213 {
214 if (*++cp == '\0')
215 break;
216 ++cp;
217 }
218 else
219 {
220 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
221 break;
222
223 if (*cp++ == '{')
224 depth++;
225 }
226
227 return *cp != '\0' ? cp : NULL;
228 }
229
230 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
231
232 /* Do glob searching for PATTERN, placing results in PGLOB.
233 The bits defined above may be set in FLAGS.
234 If a directory cannot be opened or read and ERRFUNC is not nil,
235 it is called with the pathname that caused the error, and the
236 `errno' value from the failing call; if it returns non-zero
237 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
238 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
239 Otherwise, `glob' returns zero. */
240 int
241 #ifdef GLOB_ATTRIBUTE
242 GLOB_ATTRIBUTE
243 #endif
244 glob (pattern, flags, errfunc, pglob)
245 const char *pattern;
246 int flags;
247 int (*errfunc) (const char *, int);
248 glob_t *pglob;
249 {
250 const char *filename;
251 const char *dirname;
252 size_t dirlen;
253 int status;
254 size_t oldcount;
255
256 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
257 {
258 __set_errno (EINVAL);
259 return -1;
260 }
261
262 if (!(flags & GLOB_DOOFFS))
263 /* Have to do this so `globfree' knows where to start freeing. It
264 also makes all the code that uses gl_offs simpler. */
265 pglob->gl_offs = 0;
266
267 if (flags & GLOB_BRACE)
268 {
269 const char *begin;
270
271 if (flags & GLOB_NOESCAPE)
272 begin = strchr (pattern, '{');
273 else
274 {
275 begin = pattern;
276 while (1)
277 {
278 if (*begin == '\0')
279 {
280 begin = NULL;
281 break;
282 }
283
284 if (*begin == '\\' && begin[1] != '\0')
285 ++begin;
286 else if (*begin == '{')
287 break;
288
289 ++begin;
290 }
291 }
292
293 if (begin != NULL)
294 {
295 /* Allocate working buffer large enough for our work. Note that
296 we have at least an opening and closing brace. */
297 size_t firstc;
298 char *alt_start;
299 const char *p;
300 const char *next;
301 const char *rest;
302 size_t rest_len;
303 #ifdef __GNUC__
304 char onealt[strlen (pattern) - 1];
305 #else
306 char *onealt = malloc (strlen (pattern) - 1);
307 if (onealt == NULL)
308 {
309 if (!(flags & GLOB_APPEND))
310 {
311 pglob->gl_pathc = 0;
312 pglob->gl_pathv = NULL;
313 }
314 return GLOB_NOSPACE;
315 }
316 #endif
317
318 /* We know the prefix for all sub-patterns. */
319 alt_start = mempcpy (onealt, pattern, begin - pattern);
320
321 /* Find the first sub-pattern and at the same time find the
322 rest after the closing brace. */
323 next = next_brace_sub (begin + 1, flags);
324 if (next == NULL)
325 {
326 /* It is an illegal expression. */
327 #ifndef __GNUC__
328 free (onealt);
329 #endif
330 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
331 }
332
333 /* Now find the end of the whole brace expression. */
334 rest = next;
335 while (*rest != '}')
336 {
337 rest = next_brace_sub (rest + 1, flags);
338 if (rest == NULL)
339 {
340 /* It is an illegal expression. */
341 #ifndef __GNUC__
342 free (onealt);
343 #endif
344 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
345 }
346 }
347 /* Please note that we now can be sure the brace expression
348 is well-formed. */
349 rest_len = strlen (++rest) + 1;
350
351 /* We have a brace expression. BEGIN points to the opening {,
352 NEXT points past the terminator of the first element, and END
353 points past the final }. We will accumulate result names from
354 recursive runs for each brace alternative in the buffer using
355 GLOB_APPEND. */
356
357 if (!(flags & GLOB_APPEND))
358 {
359 /* This call is to set a new vector, so clear out the
360 vector so we can append to it. */
361 pglob->gl_pathc = 0;
362 pglob->gl_pathv = NULL;
363 }
364 firstc = pglob->gl_pathc;
365
366 p = begin + 1;
367 while (1)
368 {
369 int result;
370
371 /* Construct the new glob expression. */
372 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
373
374 result = glob (onealt,
375 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
376 | GLOB_APPEND), errfunc, pglob);
377
378 /* If we got an error, return it. */
379 if (result && result != GLOB_NOMATCH)
380 {
381 #ifndef __GNUC__
382 free (onealt);
383 #endif
384 if (!(flags & GLOB_APPEND))
385 {
386 globfree (pglob);
387 pglob->gl_pathc = 0;
388 }
389 return result;
390 }
391
392 if (*next == '}')
393 /* We saw the last entry. */
394 break;
395
396 p = next + 1;
397 next = next_brace_sub (p, flags);
398 assert (next != NULL);
399 }
400
401 #ifndef __GNUC__
402 free (onealt);
403 #endif
404
405 if (pglob->gl_pathc != firstc)
406 /* We found some entries. */
407 return 0;
408 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
409 return GLOB_NOMATCH;
410 }
411 }
412
413 /* Find the filename. */
414 filename = strrchr (pattern, '/');
415 #if defined __MSDOS__ || defined WINDOWS32
416 /* The case of "d:pattern". Since `:' is not allowed in
417 file names, we can safely assume that wherever it
418 happens in pattern, it signals the filename part. This
419 is so we could some day support patterns like "[a-z]:foo". */
420 if (filename == NULL)
421 filename = strchr (pattern, ':');
422 #endif /* __MSDOS__ || WINDOWS32 */
423 if (filename == NULL)
424 {
425 /* This can mean two things: a simple name or "~name". The latter
426 case is nothing but a notation for a directory. */
427 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
428 {
429 dirname = pattern;
430 dirlen = strlen (pattern);
431
432 /* Set FILENAME to NULL as a special flag. This is ugly but
433 other solutions would require much more code. We test for
434 this special case below. */
435 filename = NULL;
436 }
437 else
438 {
439 filename = pattern;
440 #ifdef _AMIGA
441 dirname = "";
442 #else
443 dirname = ".";
444 #endif
445 dirlen = 0;
446 }
447 }
448 else if (filename == pattern)
449 {
450 /* "/pattern". */
451 dirname = "/";
452 dirlen = 1;
453 ++filename;
454 }
455 else
456 {
457 char *newp;
458 dirlen = filename - pattern;
459 #if defined __MSDOS__ || defined WINDOWS32
460 if (*filename == ':'
461 || (filename > pattern + 1 && filename[-1] == ':'))
462 {
463 char *drive_spec;
464
465 ++dirlen;
466 drive_spec = __alloca (dirlen + 1);
467 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
468 /* For now, disallow wildcards in the drive spec, to
469 prevent infinite recursion in glob. */
470 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
471 return GLOB_NOMATCH;
472 /* If this is "d:pattern", we need to copy `:' to DIRNAME
473 as well. If it's "d:/pattern", don't remove the slash
474 from "d:/", since "d:" and "d:/" are not the same.*/
475 }
476 #endif
477 newp = __alloca (dirlen + 1);
478 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
479 dirname = newp;
480 ++filename;
481
482 if (filename[0] == '\0'
483 #if defined __MSDOS__ || defined WINDOWS32
484 && dirname[dirlen - 1] != ':'
485 && (dirlen < 3 || dirname[dirlen - 2] != ':'
486 || dirname[dirlen - 1] != '/')
487 #endif
488 && dirlen > 1)
489 /* "pattern/". Expand "pattern", appending slashes. */
490 {
491 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
492 if (val == 0)
493 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
494 | (flags & GLOB_MARK));
495 return val;
496 }
497 }
498
499 if (!(flags & GLOB_APPEND))
500 {
501 pglob->gl_pathc = 0;
502 if (!(flags & GLOB_DOOFFS))
503 pglob->gl_pathv = NULL;
504 else
505 {
506 size_t i;
507 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
508 if (pglob->gl_pathv == NULL)
509 return GLOB_NOSPACE;
510
511 for (i = 0; i <= pglob->gl_offs; ++i)
512 pglob->gl_pathv[i] = NULL;
513 }
514 }
515
516 oldcount = pglob->gl_pathc + pglob->gl_offs;
517
518 #ifndef VMS
519 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
520 {
521 if (dirname[1] == '\0' || dirname[1] == '/')
522 {
523 /* Look up home directory. */
524 const char *home_dir = getenv ("HOME");
525 # ifdef _AMIGA
526 if (home_dir == NULL || home_dir[0] == '\0')
527 home_dir = "SYS:";
528 # else
529 # ifdef WINDOWS32
530 if (home_dir == NULL || home_dir[0] == '\0')
531 home_dir = "c:/users/default"; /* poor default */
532 # else
533 if (home_dir == NULL || home_dir[0] == '\0')
534 {
535 int success;
536 char *name;
537 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
538
539 if (buflen == 0)
540 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
541 a moderate value. */
542 buflen = 20;
543 name = __alloca (buflen);
544
545 success = getlogin_r (name, buflen) == 0;
546 if (success)
547 {
548 struct passwd *p;
549 # if defined HAVE_GETPWNAM_R || defined _LIBC
550 long int pwbuflen = GETPW_R_SIZE_MAX ();
551 char *pwtmpbuf;
552 struct passwd pwbuf;
553 int save = errno;
554
555 # ifndef _LIBC
556 if (pwbuflen == -1)
557 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
558 Try a moderate value. */
559 pwbuflen = 1024;
560 # endif
561 pwtmpbuf = __alloca (pwbuflen);
562
563 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
564 != 0)
565 {
566 if (errno != ERANGE)
567 {
568 p = NULL;
569 break;
570 }
571 # ifdef _LIBC
572 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
573 2 * pwbuflen);
574 # else
575 pwbuflen *= 2;
576 pwtmpbuf = __alloca (pwbuflen);
577 # endif
578 __set_errno (save);
579 }
580 # else
581 p = getpwnam (name);
582 # endif
583 if (p != NULL)
584 home_dir = p->pw_dir;
585 }
586 }
587 if (home_dir == NULL || home_dir[0] == '\0')
588 {
589 if (flags & GLOB_TILDE_CHECK)
590 return GLOB_NOMATCH;
591 else
592 home_dir = "~"; /* No luck. */
593 }
594 # endif /* WINDOWS32 */
595 # endif
596 /* Now construct the full directory. */
597 if (dirname[1] == '\0')
598 dirname = home_dir;
599 else
600 {
601 char *newp;
602 size_t home_len = strlen (home_dir);
603 newp = __alloca (home_len + dirlen);
604 mempcpy (mempcpy (newp, home_dir, home_len),
605 &dirname[1], dirlen);
606 dirname = newp;
607 }
608 }
609 # if !defined _AMIGA && !defined WINDOWS32
610 else
611 {
612 char *end_name = strchr (dirname, '/');
613 const char *user_name;
614 const char *home_dir;
615
616 if (end_name == NULL)
617 user_name = dirname + 1;
618 else
619 {
620 char *newp;
621 newp = __alloca (end_name - dirname);
622 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
623 = '\0';
624 user_name = newp;
625 }
626
627 /* Look up specific user's home directory. */
628 {
629 struct passwd *p;
630 # if defined HAVE_GETPWNAM_R || defined _LIBC
631 long int buflen = GETPW_R_SIZE_MAX ();
632 char *pwtmpbuf;
633 struct passwd pwbuf;
634 int save = errno;
635
636 # ifndef _LIBC
637 if (buflen == -1)
638 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
639 moderate value. */
640 buflen = 1024;
641 # endif
642 pwtmpbuf = __alloca (buflen);
643
644 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
645 {
646 if (errno != ERANGE)
647 {
648 p = NULL;
649 break;
650 }
651 # ifdef _LIBC
652 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
653 # else
654 buflen *= 2;
655 pwtmpbuf = __alloca (buflen);
656 # endif
657 __set_errno (save);
658 }
659 # else
660 p = getpwnam (user_name);
661 # endif
662 if (p != NULL)
663 home_dir = p->pw_dir;
664 else
665 home_dir = NULL;
666 }
667 /* If we found a home directory use this. */
668 if (home_dir != NULL)
669 {
670 char *newp;
671 size_t home_len = strlen (home_dir);
672 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
673 newp = __alloca (home_len + rest_len + 1);
674 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
675 end_name, rest_len)) = '\0';
676 dirname = newp;
677 }
678 else
679 if (flags & GLOB_TILDE_CHECK)
680 /* We have to regard it as an error if we cannot find the
681 home directory. */
682 return GLOB_NOMATCH;
683 }
684 # endif /* Not Amiga && not WINDOWS32. */
685 }
686 #endif /* Not VMS. */
687
688 /* Now test whether we looked for "~" or "~NAME". In this case we
689 can give the answer now. */
690 if (filename == NULL)
691 {
692 struct stat st;
693 struct_stat64 st64;
694
695 /* Return the directory if we don't check for error or if it exists. */
696 if ((flags & GLOB_NOCHECK)
697 || (((flags & GLOB_ALTDIRFUNC)
698 ? ((*pglob->gl_stat) (dirname, &st) == 0
699 && S_ISDIR (st.st_mode))
700 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
701 {
702 int newcount = pglob->gl_pathc + pglob->gl_offs;
703 char **new_gl_pathv;
704
705 new_gl_pathv
706 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
707 if (new_gl_pathv == NULL)
708 {
709 nospace:
710 free (pglob->gl_pathv);
711 pglob->gl_pathv = NULL;
712 pglob->gl_pathc = 0;
713 return GLOB_NOSPACE;
714 }
715 pglob->gl_pathv = new_gl_pathv;
716
717 pglob->gl_pathv[newcount] = strdup (dirname);
718 if (pglob->gl_pathv[newcount] == NULL)
719 goto nospace;
720 pglob->gl_pathv[++newcount] = NULL;
721 ++pglob->gl_pathc;
722 pglob->gl_flags = flags;
723
724 return 0;
725 }
726
727 /* Not found. */
728 return GLOB_NOMATCH;
729 }
730
731 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
732 {
733 /* The directory name contains metacharacters, so we
734 have to glob for the directory, and then glob for
735 the pattern in each directory found. */
736 glob_t dirs;
737 size_t i;
738
739 if ((flags & GLOB_ALTDIRFUNC) != 0)
740 {
741 /* Use the alternative access functions also in the recursive
742 call. */
743 dirs.gl_opendir = pglob->gl_opendir;
744 dirs.gl_readdir = pglob->gl_readdir;
745 dirs.gl_closedir = pglob->gl_closedir;
746 dirs.gl_stat = pglob->gl_stat;
747 dirs.gl_lstat = pglob->gl_lstat;
748 }
749
750 status = glob (dirname,
751 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE
752 | GLOB_ALTDIRFUNC))
753 | GLOB_NOSORT | GLOB_ONLYDIR),
754 errfunc, &dirs);
755 if (status != 0)
756 return status;
757
758 /* We have successfully globbed the preceding directory name.
759 For each name we found, call glob_in_dir on it and FILENAME,
760 appending the results to PGLOB. */
761 for (i = 0; i < dirs.gl_pathc; ++i)
762 {
763 int old_pathc;
764
765 #ifdef SHELL
766 {
767 /* Make globbing interruptible in the bash shell. */
768 extern int interrupt_state;
769
770 if (interrupt_state)
771 {
772 globfree (&dirs);
773 return GLOB_ABORTED;
774 }
775 }
776 #endif /* SHELL. */
777
778 old_pathc = pglob->gl_pathc;
779 status = glob_in_dir (filename, dirs.gl_pathv[i],
780 ((flags | GLOB_APPEND)
781 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
782 errfunc, pglob);
783 if (status == GLOB_NOMATCH)
784 /* No matches in this directory. Try the next. */
785 continue;
786
787 if (status != 0)
788 {
789 globfree (&dirs);
790 globfree (pglob);
791 pglob->gl_pathc = 0;
792 return status;
793 }
794
795 /* Stick the directory on the front of each name. */
796 if (prefix_array (dirs.gl_pathv[i],
797 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
798 pglob->gl_pathc - old_pathc))
799 {
800 globfree (&dirs);
801 globfree (pglob);
802 pglob->gl_pathc = 0;
803 return GLOB_NOSPACE;
804 }
805 }
806
807 flags |= GLOB_MAGCHAR;
808
809 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
810 But if we have not found any matching entry and the GLOB_NOCHECK
811 flag was set we must return the input pattern itself. */
812 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
813 {
814 /* No matches. */
815 if (flags & GLOB_NOCHECK)
816 {
817 int newcount = pglob->gl_pathc + pglob->gl_offs;
818 char **new_gl_pathv;
819
820 new_gl_pathv = realloc (pglob->gl_pathv,
821 (newcount + 2) * sizeof (char *));
822 if (new_gl_pathv == NULL)
823 {
824 globfree (&dirs);
825 return GLOB_NOSPACE;
826 }
827 pglob->gl_pathv = new_gl_pathv;
828
829 pglob->gl_pathv[newcount] = strdup (pattern);
830 if (pglob->gl_pathv[newcount] == NULL)
831 {
832 globfree (&dirs);
833 globfree (pglob);
834 pglob->gl_pathc = 0;
835 return GLOB_NOSPACE;
836 }
837
838 ++pglob->gl_pathc;
839 ++newcount;
840
841 pglob->gl_pathv[newcount] = NULL;
842 pglob->gl_flags = flags;
843 }
844 else
845 {
846 globfree (&dirs);
847 return GLOB_NOMATCH;
848 }
849 }
850
851 globfree (&dirs);
852 }
853 else
854 {
855 int old_pathc = pglob->gl_pathc;
856
857 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
858 if (status != 0)
859 return status;
860
861 if (dirlen > 0)
862 {
863 /* Stick the directory on the front of each name. */
864 if (prefix_array (dirname,
865 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
866 pglob->gl_pathc - old_pathc))
867 {
868 globfree (pglob);
869 pglob->gl_pathc = 0;
870 return GLOB_NOSPACE;
871 }
872 }
873 }
874
875 if (!(flags & GLOB_NOSORT))
876 {
877 /* Sort the vector. */
878 qsort (&pglob->gl_pathv[oldcount],
879 pglob->gl_pathc + pglob->gl_offs - oldcount,
880 sizeof (char *), collated_compare);
881 }
882
883 return 0;
884 }
885 #if defined _LIBC && !defined glob
886 libc_hidden_def (glob)
887 #endif
888
889
890 #if !defined _LIBC || !defined GLOB_ONLY_P
891
892 /* Free storage allocated in PGLOB by a previous `glob' call. */
893 void
894 globfree (pglob)
895 register glob_t *pglob;
896 {
897 if (pglob->gl_pathv != NULL)
898 {
899 size_t i;
900 for (i = 0; i < pglob->gl_pathc; ++i)
901 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
902 free (pglob->gl_pathv[pglob->gl_offs + i]);
903 free (pglob->gl_pathv);
904 pglob->gl_pathv = NULL;
905 }
906 }
907 #if defined _LIBC && !defined globfree
908 libc_hidden_def (globfree)
909 #endif
910
911
912 /* Do a collated comparison of A and B. */
913 static int
914 collated_compare (const void *a, const void *b)
915 {
916 const char *const s1 = *(const char *const * const) a;
917 const char *const s2 = *(const char *const * const) b;
918
919 if (s1 == s2)
920 return 0;
921 if (s1 == NULL)
922 return 1;
923 if (s2 == NULL)
924 return -1;
925 return strcoll (s1, s2);
926 }
927
928
929 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
930 elements in place. Return nonzero if out of memory, zero if successful.
931 A slash is inserted between DIRNAME and each elt of ARRAY,
932 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
933 static int
934 prefix_array (const char *dirname, char **array, size_t n)
935 {
936 register size_t i;
937 size_t dirlen = strlen (dirname);
938 #if defined __MSDOS__ || defined WINDOWS32
939 int sep_char = '/';
940 # define DIRSEP_CHAR sep_char
941 #else
942 # define DIRSEP_CHAR '/'
943 #endif
944
945 if (dirlen == 1 && dirname[0] == '/')
946 /* DIRNAME is just "/", so normal prepending would get us "//foo".
947 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
948 dirlen = 0;
949 #if defined __MSDOS__ || defined WINDOWS32
950 else if (dirlen > 1)
951 {
952 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
953 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
954 --dirlen;
955 else if (dirname[dirlen - 1] == ':')
956 {
957 /* DIRNAME is "d:". Use `:' instead of `/'. */
958 --dirlen;
959 sep_char = ':';
960 }
961 }
962 #endif
963
964 for (i = 0; i < n; ++i)
965 {
966 size_t eltlen = strlen (array[i]) + 1;
967 char *new = malloc (dirlen + 1 + eltlen);
968 if (new == NULL)
969 {
970 while (i > 0)
971 free (array[--i]);
972 return 1;
973 }
974
975 {
976 char *endp = mempcpy (new, dirname, dirlen);
977 *endp++ = DIRSEP_CHAR;
978 mempcpy (endp, array[i], eltlen);
979 }
980 free (array[i]);
981 array[i] = new;
982 }
983
984 return 0;
985 }
986
987
988 /* We must not compile this function twice. */
989 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
990 /* Return nonzero if PATTERN contains any metacharacters.
991 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
992 int
993 __glob_pattern_p (pattern, quote)
994 const char *pattern;
995 int quote;
996 {
997 register const char *p;
998 int open = 0;
999
1000 for (p = pattern; *p != '\0'; ++p)
1001 switch (*p)
1002 {
1003 case '?':
1004 case '*':
1005 return 1;
1006
1007 case '\\':
1008 if (quote && p[1] != '\0')
1009 ++p;
1010 break;
1011
1012 case '[':
1013 open = 1;
1014 break;
1015
1016 case ']':
1017 if (open)
1018 return 1;
1019 break;
1020 }
1021
1022 return 0;
1023 }
1024 # ifdef _LIBC
1025 weak_alias (__glob_pattern_p, glob_pattern_p)
1026 # endif
1027 #endif
1028
1029 #endif /* !GLOB_ONLY_P */
1030
1031
1032 /* We put this in a separate function mainly to allow the memory
1033 allocated with alloca to be recycled. */
1034 #if !defined _LIBC || !defined GLOB_ONLY_P
1035 static bool
1036 is_dir_p (const char *dir, size_t dirlen, const char *fname,
1037 glob_t *pglob, int flags)
1038 {
1039 size_t fnamelen = strlen (fname);
1040 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1041 struct stat st;
1042 struct_stat64 st64;
1043
1044 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1045 fname, fnamelen + 1);
1046
1047 return ((flags & GLOB_ALTDIRFUNC)
1048 ? (*pglob->gl_stat) (fullname, &st) == 0 && S_ISDIR (st.st_mode)
1049 : __stat64 (fullname, &st64) == 0 && S_ISDIR (st64.st_mode));
1050 }
1051 #endif
1052
1053
1054 /* Like `glob', but PATTERN is a final pathname component,
1055 and matches are searched for in DIRECTORY.
1056 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1057 The GLOB_APPEND flag is assumed to be set (always appends). */
1058 static int
1059 glob_in_dir (const char *pattern, const char *directory, int flags,
1060 int (*errfunc) (const char *, int),
1061 glob_t *pglob)
1062 {
1063 size_t dirlen = strlen (directory);
1064 void *stream = NULL;
1065 struct globlink
1066 {
1067 struct globlink *next;
1068 char *name;
1069 };
1070 struct globlink *names = NULL;
1071 size_t nfound;
1072 int meta;
1073 int save;
1074
1075 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1076 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1077 {
1078 /* We need not do any tests. The PATTERN contains no meta
1079 characters and we must not return an error therefore the
1080 result will always contain exactly one name. */
1081 flags |= GLOB_NOCHECK;
1082 nfound = 0;
1083 }
1084 else if (meta == 0 &&
1085 ((flags & GLOB_NOESCAPE) || strchr (pattern, '\\') == NULL))
1086 {
1087 /* Since we use the normal file functions we can also use stat()
1088 to verify the file is there. */
1089 struct stat st;
1090 struct_stat64 st64;
1091 size_t patlen = strlen (pattern);
1092 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1093
1094 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1095 "/", 1),
1096 pattern, patlen + 1);
1097 if (((flags & GLOB_ALTDIRFUNC)
1098 ? (*pglob->gl_stat) (fullname, &st)
1099 : __stat64 (fullname, &st64)) == 0)
1100 /* We found this file to be existing. Now tell the rest
1101 of the function to copy this name into the result. */
1102 flags |= GLOB_NOCHECK;
1103
1104 nfound = 0;
1105 }
1106 else
1107 {
1108 if (pattern[0] == '\0')
1109 {
1110 /* This is a special case for matching directories like in
1111 "*a/". */
1112 names = __alloca (sizeof (struct globlink));
1113 names->name = malloc (1);
1114 if (names->name == NULL)
1115 goto memory_error;
1116 names->name[0] = '\0';
1117 names->next = NULL;
1118 nfound = 1;
1119 meta = 0;
1120 }
1121 else
1122 {
1123 stream = ((flags & GLOB_ALTDIRFUNC)
1124 ? (*pglob->gl_opendir) (directory)
1125 : opendir (directory));
1126 if (stream == NULL)
1127 {
1128 if (errno != ENOTDIR
1129 && ((errfunc != NULL && (*errfunc) (directory, errno))
1130 || (flags & GLOB_ERR)))
1131 return GLOB_ABORTED;
1132 nfound = 0;
1133 meta = 0;
1134 }
1135 else
1136 {
1137 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1138 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1139 #if defined _AMIGA || defined VMS
1140 | FNM_CASEFOLD
1141 #endif
1142 );
1143 nfound = 0;
1144 flags |= GLOB_MAGCHAR;
1145
1146 while (1)
1147 {
1148 const char *name;
1149 size_t len;
1150 #if defined _LIBC && !defined COMPILE_GLOB64
1151 struct dirent64 *d;
1152 union
1153 {
1154 struct dirent64 d64;
1155 char room [offsetof (struct dirent64, d_name[0])
1156 + NAME_MAX + 1];
1157 }
1158 d64buf;
1159
1160 if (flags & GLOB_ALTDIRFUNC)
1161 {
1162 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1163 if (d32 != NULL)
1164 {
1165 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1166 d = &d64buf.d64;
1167 }
1168 else
1169 d = NULL;
1170 }
1171 else
1172 d = __readdir64 (stream);
1173 #else
1174 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1175 ? ((*pglob->gl_readdir) (stream))
1176 : __readdir (stream));
1177 #endif
1178 if (d == NULL)
1179 break;
1180 if (! REAL_DIR_ENTRY (d))
1181 continue;
1182
1183 /* If we shall match only directories use the information
1184 provided by the dirent call if possible. */
1185 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1186 continue;
1187
1188 name = d->d_name;
1189
1190 if (fnmatch (pattern, name, fnm_flags) == 0)
1191 {
1192 /* ISDIR will often be incorrectly set to false
1193 when not in GLOB_ONLYDIR || GLOB_MARK mode, but we
1194 don't care. It won't be used and we save the
1195 expensive call to stat. */
1196 int need_dir_test =
1197 (GLOB_MARK | (DIRENT_MIGHT_BE_SYMLINK (d)
1198 ? GLOB_ONLYDIR : 0));
1199 bool isdir = (DIRENT_MUST_BE (d, DT_DIR)
1200 || ((flags & need_dir_test)
1201 && is_dir_p (directory, dirlen, name,
1202 pglob, flags)));
1203
1204 /* In GLOB_ONLYDIR mode, skip non-dirs. */
1205 if ((flags & GLOB_ONLYDIR) && !isdir)
1206 continue;
1207
1208 {
1209 struct globlink *new =
1210 __alloca (sizeof (struct globlink));
1211 char *p;
1212 len = NAMLEN (d);
1213 new->name =
1214 malloc (len + 1 + ((flags & GLOB_MARK) && isdir));
1215 if (new->name == NULL)
1216 goto memory_error;
1217 p = mempcpy (new->name, name, len);
1218 if ((flags & GLOB_MARK) && isdir)
1219 *p++ = '/';
1220 *p = '\0';
1221 new->next = names;
1222 names = new;
1223 ++nfound;
1224 }
1225 }
1226 }
1227 }
1228 }
1229 }
1230
1231 if (nfound == 0 && (flags & GLOB_NOCHECK))
1232 {
1233 size_t len = strlen (pattern);
1234 nfound = 1;
1235 names = __alloca (sizeof (struct globlink));
1236 names->next = NULL;
1237 names->name = malloc (len + 1);
1238 if (names->name == NULL)
1239 goto memory_error;
1240 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1241 }
1242
1243 if (nfound != 0)
1244 {
1245 char **new_gl_pathv;
1246
1247 new_gl_pathv
1248 = realloc (pglob->gl_pathv,
1249 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1250 * sizeof (char *));
1251 if (new_gl_pathv == NULL)
1252 goto memory_error;
1253 pglob->gl_pathv = new_gl_pathv;
1254
1255 for (; names != NULL; names = names->next)
1256 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc++] = names->name;
1257 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1258
1259 pglob->gl_flags = flags;
1260 }
1261
1262 save = errno;
1263 if (stream != NULL)
1264 {
1265 if (flags & GLOB_ALTDIRFUNC)
1266 (*pglob->gl_closedir) (stream);
1267 else
1268 closedir (stream);
1269 }
1270 __set_errno (save);
1271
1272 return nfound == 0 ? GLOB_NOMATCH : 0;
1273
1274 memory_error:
1275 {
1276 int save = errno;
1277 if (flags & GLOB_ALTDIRFUNC)
1278 (*pglob->gl_closedir) (stream);
1279 else
1280 closedir (stream);
1281 __set_errno (save);
1282 }
1283 while (names != NULL)
1284 {
1285 if (names->name != NULL)
1286 free (names->name);
1287 names = names->next;
1288 }
1289 return GLOB_NOSPACE;
1290 }
1291