Added config.h, miscfn.h header files
[platform/upstream/rpm.git] / misc / glob.c
1 #ifdef __sgi
2 #define SYSDIR
3 #endif
4
5 #ifdef __hpux
6 #define SYSDIR
7 #endif
8
9 #if defined(sun) && !defined(__svr4__)
10 #define SYSDIR
11 #endif
12
13 /* Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
14
15 This library is free software; you can redistribute it and/or
16 modify it under the terms of the GNU Library General Public License as
17 published by the Free Software Foundation; either version 2 of the
18 License, or (at your option) any later version.
19
20 This library is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23 Library General Public License for more details.
24
25 You should have received a copy of the GNU Library General Public
26 License along with this library; see the file COPYING.LIB.  If
27 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
28 Cambridge, MA 02139, USA.  */
29
30 /* AIX requires this to be the first thing in the file.  */
31 #if defined (_AIX) && !defined (__GNUC__)
32  #pragma alloca
33 #endif
34
35 #include <errno.h>
36 #include <sys/types.h>
37
38 #include "config.h"
39
40 /* Comment out all this code if we are using the GNU C Library, and are not
41    actually compiling the library itself.  This code is part of the GNU C
42    Library, but also included in many other GNU distributions.  Compiling
43    and linking in this code is a waste when using the GNU C library
44    (especially if it is a shared library).  Rather than having every GNU
45    program understand `configure --with-gnu-libc' and omit the object files,
46    it is simpler to just do this in the source for each such file.  */
47
48 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
49
50
51 #ifdef  STDC_HEADERS
52 #include <stddef.h>
53 #endif
54
55 #ifdef  HAVE_UNISTD_H
56 #include <unistd.h>
57 #ifndef POSIX
58 #ifdef  _POSIX_VERSION
59 #define POSIX
60 #endif
61 #endif
62 #endif
63
64 #if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS)
65 extern int errno;
66 #endif
67
68 #ifndef NULL
69 #define NULL    0
70 #endif
71
72 #if     defined (POSIX) || defined (DIRENT) || defined (__GNU_LIBRARY__)  || defined(HAVE_DIRENT_H)
73 #include <dirent.h>
74 #ifndef __GNU_LIBRARY__
75 #define D_NAMLEN(d) strlen((d)->d_name)
76 #else   /* GNU C library.  */
77 #define D_NAMLEN(d) ((d)->d_namlen)
78 #endif  /* Not GNU C library.  */
79 #else   /* Not POSIX or DIRENT.  */
80 #define direct dirent
81 #define D_NAMLEN(d) ((d)->d_namlen)
82 #ifdef  SYSNDIR
83 #include <sys/ndir.h>
84 #endif  /* SYSNDIR */
85 #ifdef  SYSDIR
86 #include <sys/dir.h>
87 #endif  /* SYSDIR */
88 #ifdef NDIR
89 #include <ndir.h>
90 #endif  /* NDIR */
91 #endif  /* POSIX or DIRENT or __GNU_LIBRARY__.  */
92
93 #if defined (POSIX) && !defined (__GNU_LIBRARY__)
94 /* Posix does not require that the d_ino field be present, and some
95    systems do not provide it. */
96 #define REAL_DIR_ENTRY(dp) 1
97 #else
98 #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
99 #endif /* POSIX */
100
101 #if     (defined (STDC_HEADERS) || defined (__GNU_LIBRARY__))
102 #include <stdlib.h>
103 #include <string.h>
104 #define ANSI_STRING
105 #else   /* No standard headers.  */
106
107 #ifdef HAVE_STRING_H
108 #include <string.h>
109 #define ANSI_STRING
110 #else
111 #include <strings.h>
112 #endif
113 #ifdef  HAVE_MEMORY_H
114 #include <memory.h>
115 #endif
116
117 extern char *malloc (), *realloc ();
118 extern void free ();
119
120 extern void qsort ();
121 extern void abort (), exit ();
122
123 #endif  /* Standard headers.  */
124
125 #ifndef ANSI_STRING
126
127 #ifndef bzero
128 extern void bzero ();
129 #endif
130 #ifndef bcopy
131 extern void bcopy ();
132 #endif
133
134 #define memcpy(d, s, n) bcopy ((s), (d), (n))
135 #define strrchr rindex
136 /* memset is only used for zero here, but let's be paranoid.  */
137 #define memset(s, better_be_zero, n) \
138   ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
139 #endif  /* Not ANSI_STRING.  */
140
141 #ifndef HAVE_STRCOLL
142 #define strcoll strcmp
143 #endif
144
145
146 #ifndef __GNU_LIBRARY__
147 #ifdef  __GNUC__
148 __inline
149 #endif
150 static char *
151 my_realloc (p, n)
152      char *p;
153      unsigned int n;
154 {
155   /* These casts are the for sake of the broken Ultrix compiler,
156      which warns of illegal pointer combinations otherwise.  */
157   if (p == NULL)
158     return (char *) malloc (n);
159   return (char *) realloc (p, n);
160 }
161 #define realloc my_realloc
162 #endif
163
164
165 #if     !defined(__alloca) && !defined(__GNU_LIBRARY__)
166
167 #ifdef  __GNUC__
168 #undef  alloca
169 #define alloca(n)       __builtin_alloca (n)
170 #else   /* Not GCC.  */
171 #if     defined (sparc) || defined (HAVE_ALLOCA_H)
172 #include <alloca.h>
173 #else   /* Not sparc or HAVE_ALLOCA_H.  */
174 #ifndef _AIX
175 extern char *alloca ();
176 #endif  /* Not _AIX.  */
177 #endif  /* sparc or HAVE_ALLOCA_H.  */
178 #endif  /* GCC.  */
179
180 #define __alloca        alloca
181
182 #endif
183
184 #ifndef STDC_HEADERS
185 #undef  size_t
186 #define size_t  unsigned int
187 #endif
188
189 /* Some system header files erroneously define these.
190    We want our own definitions from <fnmatch.h> to take precedence.  */
191 #undef  FNM_PATHNAME
192 #undef  FNM_NOESCAPE
193 #undef  FNM_PERIOD
194
195 /* Some system header files erroneously define these.
196    We want our own definitions from <glob.h> to take precedence.  */
197 #undef  GLOB_ERR
198 #undef  GLOB_MARK
199 #undef  GLOB_NOSORT
200 #undef  GLOB_DOOFFS
201 #undef  GLOB_NOCHECK
202 #undef  GLOB_APPEND
203 #undef  GLOB_NOESCAPE
204 #undef  GLOB_PERIOD
205 #include "miscfn.h"
206 \f
207 __ptr_t (*__glob_opendir_hook) __P ((const char *directory));
208 const char *(*__glob_readdir_hook) __P ((__ptr_t stream));
209 void (*__glob_closedir_hook) __P ((__ptr_t stream));
210
211 static int glob_pattern_p __P ((const char *pattern, int quote));
212 static int glob_in_dir __P ((const char *pattern, const char *directory,
213                              int flags,
214                              int (*errfunc) __P ((const char *, int)),
215                              glob_t *pglob));
216 static int prefix_array __P ((const char *prefix, char **array, size_t n));
217 static int collated_compare __P ((const __ptr_t, const __ptr_t));
218
219 /* Do glob searching for PATTERN, placing results in PGLOB.
220    The bits defined above may be set in FLAGS.
221    If a directory cannot be opened or read and ERRFUNC is not nil,
222    it is called with the pathname that caused the error, and the
223    `errno' value from the failing call; if it returns non-zero
224    `glob' returns GLOB_ABEND; if it returns zero, the error is ignored.
225    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
226    Otherwise, `glob' returns zero.  */
227 int
228 glob (pattern, flags, errfunc, pglob)
229      const char *pattern;
230      int flags;
231      int (*errfunc) __P ((const char *, int));
232      glob_t *pglob;
233 {
234   const char *filename;
235   char *dirname;
236   size_t dirlen;
237   int status;
238   int oldcount;
239
240   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
241     {
242       errno = EINVAL;
243       return -1;
244     }
245
246   /* Find the filename.  */
247   filename = strrchr (pattern, '/');
248   if (filename == NULL)
249     {
250       filename = pattern;
251       dirname = (char *) ".";
252       dirlen = 0;
253     }
254   else if (filename == pattern)
255     {
256       /* "/pattern".  */
257       dirname = (char *) "/";
258       dirlen = 1;
259       ++filename;
260     }
261   else
262     {
263       dirlen = filename - pattern;
264       dirname = (char *) __alloca (dirlen + 1);
265       memcpy (dirname, pattern, dirlen);
266       dirname[dirlen] = '\0';
267       ++filename;
268     }
269
270   if (filename[0] == '\0' && dirlen > 1)
271     /* "pattern/".  Expand "pattern", appending slashes.  */
272     {
273       int ret = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
274       if (ret == 0)
275         pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
276       return ret;
277     }
278
279   if (!(flags & GLOB_APPEND))
280     {
281       pglob->gl_pathc = 0;
282       pglob->gl_pathv = NULL;
283     }
284
285   oldcount = pglob->gl_pathc;
286
287   if (glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
288     {
289       /* The directory name contains metacharacters, so we
290          have to glob for the directory, and then glob for
291          the pattern in each directory found.  */
292       glob_t dirs;
293       register int i;
294
295       status = glob (dirname,
296                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE)) |
297                       GLOB_NOSORT),
298                      errfunc, &dirs);
299       if (status != 0)
300         return status;
301
302       /* We have successfully globbed the preceding directory name.
303          For each name we found, call glob_in_dir on it and FILENAME,
304          appending the results to PGLOB.  */
305       for (i = 0; i < dirs.gl_pathc; ++i)
306         {
307           int oldcount;
308
309 #ifdef  SHELL
310           {
311             /* Make globbing interruptible in the bash shell. */
312             extern int interrupt_state;
313
314             if (interrupt_state)
315               {
316                 globfree (&dirs);
317                 globfree (&files);
318                 return GLOB_ABEND;
319               }
320           }
321 #endif /* SHELL.  */
322
323           oldcount = pglob->gl_pathc;
324           status = glob_in_dir (filename, dirs.gl_pathv[i],
325                                 (flags | GLOB_APPEND) & ~GLOB_NOCHECK,
326                                 errfunc, pglob);
327           if (status == GLOB_NOMATCH)
328             /* No matches in this directory.  Try the next.  */
329             continue;
330
331           if (status != 0)
332             {
333               globfree (&dirs);
334               globfree (pglob);
335               return status;
336             }
337
338           /* Stick the directory on the front of each name.  */
339           if (prefix_array (dirs.gl_pathv[i],
340                             &pglob->gl_pathv[oldcount],
341                             pglob->gl_pathc - oldcount))
342             {
343               globfree (&dirs);
344               globfree (pglob);
345               return GLOB_NOSPACE;
346             }
347         }
348
349       flags |= GLOB_MAGCHAR;
350
351       if (pglob->gl_pathc == oldcount)
352         /* No matches.  */
353         if (flags & GLOB_NOCHECK)
354           {
355             size_t len = strlen (pattern) + 1;
356             char *patcopy = (char *) malloc (len);
357             if (patcopy == NULL)
358               return GLOB_NOSPACE;
359             memcpy (patcopy, pattern, len);
360
361             pglob->gl_pathv
362               = (char **) realloc (pglob->gl_pathv,
363                                    (pglob->gl_pathc +
364                                     ((flags & GLOB_DOOFFS) ?
365                                      pglob->gl_offs : 0) +
366                                     1 + 1) *
367                                    sizeof (char *));
368             if (pglob->gl_pathv == NULL)
369               {
370                 free (patcopy);
371                 return GLOB_NOSPACE;
372               }
373
374             if (flags & GLOB_DOOFFS)
375               while (pglob->gl_pathc < pglob->gl_offs)
376                 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
377
378             pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
379             pglob->gl_pathv[pglob->gl_pathc] = NULL;
380             pglob->gl_flags = flags;
381           }
382         else
383           return GLOB_NOMATCH;
384     }
385   else
386     {
387       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
388       if (status != 0)
389         return status;
390
391       if (dirlen > 0)
392         {
393           /* Stick the directory on the front of each name.  */
394           if (prefix_array (dirname,
395                             &pglob->gl_pathv[oldcount],
396                             pglob->gl_pathc - oldcount))
397             {
398               globfree (pglob);
399               return GLOB_NOSPACE;
400             }
401         }
402     }
403
404   if (!(flags & GLOB_NOSORT))
405     /* Sort the vector.  */
406     qsort ((__ptr_t) & pglob->gl_pathv[oldcount],
407            pglob->gl_pathc - oldcount,
408            sizeof (char *), collated_compare);
409
410   return 0;
411 }
412
413
414 /* Free storage allocated in PGLOB by a previous `glob' call.  */
415 void
416 globfree (pglob)
417      register glob_t *pglob;
418 {
419   if (pglob->gl_pathv != NULL)
420     {
421       register int i;
422       for (i = 0; i < pglob->gl_pathc; ++i)
423         if (pglob->gl_pathv[i] != NULL)
424           free ((__ptr_t) pglob->gl_pathv[i]);
425       free ((__ptr_t) pglob->gl_pathv);
426     }
427 }
428
429
430 /* Do a collated comparison of A and B.  */
431 static int
432 collated_compare (a, b)
433      const __ptr_t a;
434      const __ptr_t b;
435 {
436   const char *const s1 = *(const char *const * const) a;
437   const char *const s2 = *(const char *const * const) b;
438
439   if (s1 == s2)
440     return 0;
441   if (s1 == NULL)
442     return 1;
443   if (s2 == NULL)
444     return -1;
445   return strcoll (s1, s2);
446 }
447
448
449 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
450    elements in place.  Return nonzero if out of memory, zero if successful.
451    A slash is inserted between DIRNAME and each elt of ARRAY,
452    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
453 static int
454 prefix_array (dirname, array, n)
455      const char *dirname;
456      char **array;
457      const size_t n;
458 {
459   register size_t i;
460   size_t dirlen = strlen (dirname);
461
462   if (dirlen == 1 && dirname[0] == '/')
463     /* DIRNAME is just "/", so normal prepending would get us "//foo".
464        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
465     dirlen = 0;
466
467   for (i = 0; i < n; ++i)
468     {
469       size_t eltlen = strlen (array[i]) + 1;
470       char *new = (char *) malloc (dirlen + 1 + eltlen);
471       if (new == NULL)
472         {
473           while (i > 0)
474             free ((__ptr_t) array[--i]);
475           return 1;
476         }
477
478       memcpy (new, dirname, dirlen);
479       new[dirlen] = '/';
480       memcpy (&new[dirlen + 1], array[i], eltlen);
481       free ((__ptr_t) array[i]);
482       array[i] = new;
483     }
484
485   return 0;
486 }
487
488
489 /* Return nonzero if PATTERN contains any metacharacters.
490    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
491 static int
492 glob_pattern_p (pattern, quote)
493      const char *pattern;
494      const int quote;
495 {
496   register const char *p;
497   int open = 0;
498
499   for (p = pattern; *p != '\0'; ++p)
500     switch (*p)
501       {
502       case '?':
503       case '*':
504         return 1;
505
506       case '\\':
507         if (quote)
508           ++p;
509         break;
510
511       case '[':
512         open = 1;
513         break;
514
515       case ']':
516         if (open)
517           return 1;
518         break;
519       }
520
521   return 0;
522 }
523
524
525 /* Like `glob', but PATTERN is a final pathname component,
526    and matches are searched for in DIRECTORY.
527    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
528    The GLOB_APPEND flag is assumed to be set (always appends).  */
529 static int
530 glob_in_dir (pattern, directory, flags, errfunc, pglob)
531      const char *pattern;
532      const char *directory;
533      int flags;
534      int (*errfunc) __P ((const char *, int));
535      glob_t *pglob;
536 {
537   __ptr_t stream;
538
539   struct globlink
540     {
541       struct globlink *next;
542       char *name;
543     };
544   struct globlink *names = NULL;
545   size_t nfound = 0;
546
547   if (!glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
548     {
549       stream = NULL;
550       flags |= GLOB_NOCHECK;
551     }
552   else
553     {
554       flags |= GLOB_MAGCHAR;
555
556       stream = (__glob_opendir_hook ? (*__glob_opendir_hook) (directory)
557                 : (__ptr_t) opendir (directory));
558       if (stream == NULL)
559         {
560           if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
561               (flags & GLOB_ERR))
562             return GLOB_ABEND;
563         }
564       else
565         while (1)
566           {
567             const char *name;
568             size_t len;
569
570             if (__glob_readdir_hook)
571               {
572                 name = (*__glob_readdir_hook) (stream);
573                 if (name == NULL)
574                   break;
575                 len = 0;
576               }
577             else
578               {
579                 struct dirent *d = readdir ((DIR *) stream);
580                 if (d == NULL)
581                   break;
582                 if (! REAL_DIR_ENTRY (d))
583                   continue;
584                 name = d->d_name;
585 #ifdef  HAVE_D_NAMLEN
586                 len = d->d_namlen;
587 #else
588                 len = 0;
589 #endif
590               }
591                 
592             if (fnmatch (pattern, name,
593                          (!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
594                          ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)) == 0)
595               {
596                 struct globlink *new
597                   = (struct globlink *) __alloca (sizeof (struct globlink));
598                 if (len == 0)
599                   len = strlen (name);
600                 new->name
601                   = (char *) malloc (len + ((flags & GLOB_MARK) ? 1 : 0) + 1);
602                 if (new->name == NULL)
603                   goto memory_error;
604                 memcpy ((__ptr_t) new->name, name, len);
605                 if (flags & GLOB_MARK)
606                   new->name[len++] = '/';
607                 new->name[len] = '\0';
608                 new->next = names;
609                 names = new;
610                 ++nfound;
611               }
612           }
613     }
614
615   if (nfound == 0 && (flags & GLOB_NOCHECK))
616     {
617       size_t len = strlen (pattern);
618       nfound = 1;
619       names = (struct globlink *) __alloca (sizeof (struct globlink));
620       names->next = NULL;
621       names->name = (char *) malloc (len + ((flags & GLOB_MARK) ? 1 : 0) + 1);
622       if (names->name == NULL)
623         goto memory_error;
624       memcpy (names->name, pattern, len);
625       if (flags & GLOB_MARK)
626         names->name[len++] = '/';
627       names->name[len] = '\0';
628     }
629
630   pglob->gl_pathv
631     = (char **) realloc (pglob->gl_pathv,
632                          (pglob->gl_pathc +
633                           ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
634                           nfound + 1) *
635                          sizeof (char *));
636   if (pglob->gl_pathv == NULL)
637     goto memory_error;
638
639   if (flags & GLOB_DOOFFS)
640     while (pglob->gl_pathc < pglob->gl_offs)
641       pglob->gl_pathv[pglob->gl_pathc++] = NULL;
642
643   for (; names != NULL; names = names->next)
644     pglob->gl_pathv[pglob->gl_pathc++] = names->name;
645   pglob->gl_pathv[pglob->gl_pathc] = NULL;
646
647   pglob->gl_flags = flags;
648
649   if (stream != NULL)
650     {
651       int save = errno;
652       if (__glob_closedir_hook)
653         (*__glob_closedir_hook) (stream);
654       else
655         (void) closedir ((DIR *) stream);
656       errno = save;
657     }
658   return nfound == 0 ? GLOB_NOMATCH : 0;
659
660  memory_error:
661   {
662     int save = errno;
663     if (__glob_closedir_hook)
664       (*__glob_closedir_hook) (stream);
665     else
666       (void) closedir ((DIR *) stream);
667     errno = save;
668   }
669   while (names != NULL)
670     {
671       if (names->name != NULL)
672         free ((__ptr_t) names->name);
673       names = names->next;
674     }
675   return GLOB_NOSPACE;
676 }
677
678 #endif  /* _LIBC or not __GNU_LIBRARY__.  */