2007-09-02 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / io-layer / wapi_glob.c
1 /*      $OpenBSD: glob.c,v 1.26 2005/11/28 17:50:12 deraadt Exp $ */
2 /*
3  * Copyright (c) 1989, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Guido van Rossum.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * _wapi_glob(3) -- a subset of the one defined in POSIX 1003.2.
36  *
37  * Optional extra services, controlled by flags not defined by POSIX:
38  *
39  * GLOB_MAGCHAR:
40  *      Set in gl_flags if pattern contained a globbing character.
41  */
42 #include <sys/param.h>
43 #include <sys/stat.h>
44
45 #include <glib.h>
46 #include <ctype.h>
47 #include <dirent.h>
48 #include <errno.h>
49 #include <pwd.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54
55 #include "wapi_glob.h"
56
57 #define EOS             '\0'
58 #define NOT             '!'
59 #define QUESTION        '?'
60 #define QUOTE           '\\'
61 #define STAR            '*'
62
63 #ifndef DEBUG
64
65 #define M_QUOTE         0x8000
66 #define M_PROTECT       0x4000
67 #define M_MASK          0xffff
68 #define M_ASCII         0x00ff
69
70 typedef u_short Char;
71
72 #else
73
74 #define M_QUOTE         0x80
75 #define M_PROTECT       0x40
76 #define M_MASK          0xff
77 #define M_ASCII         0x7f
78
79 typedef char Char;
80
81 #endif
82
83
84 #define CHAR(c)         ((gchar)((c)&M_ASCII))
85 #define META(c)         ((gchar)((c)|M_QUOTE))
86 #define M_ALL           META('*')
87 #define M_ONE           META('?')
88 #define ismeta(c)       (((c)&M_QUOTE) != 0)
89
90
91 static int       g_Ctoc(const gchar *, char *, u_int);
92 static int       glob0(GDir *dir, const gchar *, wapi_glob_t *, gboolean,
93                        gboolean);
94 static int       glob1(GDir *dir, gchar *, gchar *, wapi_glob_t *, size_t *,
95                        gboolean, gboolean);
96 static int       glob3(GDir *dir, gchar *, gchar *, wapi_glob_t *, size_t *,
97                        gboolean, gboolean);
98 static int       globextend(const gchar *, wapi_glob_t *, size_t *);
99 static int       match(const gchar *, gchar *, gchar *, gboolean);
100 #ifdef DEBUG
101 static void      qprintf(const char *, Char *);
102 #endif
103
104 int
105 _wapi_glob(GDir *dir, const char *pattern, int flags, wapi_glob_t *pglob)
106 {
107         const u_char *patnext;
108         int c;
109         gchar *bufnext, *bufend, patbuf[MAXPATHLEN];
110
111         patnext = (u_char *) pattern;
112         if (!(flags & WAPI_GLOB_APPEND)) {
113                 pglob->gl_pathc = 0;
114                 pglob->gl_pathv = NULL;
115                 pglob->gl_offs = 0;
116         }
117         pglob->gl_flags = flags & ~WAPI_GLOB_MAGCHAR;
118
119         bufnext = patbuf;
120         bufend = bufnext + MAXPATHLEN - 1;
121
122         /* Protect the quoted characters. */
123         while (bufnext < bufend && (c = *patnext++) != EOS)
124                 if (c == QUOTE) {
125                         if ((c = *patnext++) == EOS) {
126                                 c = QUOTE;
127                                 --patnext;
128                         }
129                         *bufnext++ = c | M_PROTECT;
130                 } else
131                         *bufnext++ = c;
132
133         *bufnext = EOS;
134
135         return glob0(dir, patbuf, pglob, flags & WAPI_GLOB_IGNORECASE,
136                      flags & WAPI_GLOB_UNIQUE);
137 }
138
139 /*
140  * The main glob() routine: compiles the pattern (optionally processing
141  * quotes), calls glob1() to do the real pattern matching, and finally
142  * sorts the list (unless unsorted operation is requested).  Returns 0
143  * if things went well, nonzero if errors occurred.  It is not an error
144  * to find no matches.
145  */
146 static int
147 glob0(GDir *dir, const gchar *pattern, wapi_glob_t *pglob, gboolean ignorecase,
148         gboolean unique)
149 {
150         const gchar *qpatnext;
151         int c, err, oldpathc;
152         gchar *bufnext, patbuf[MAXPATHLEN];
153         size_t limit = 0;
154
155         qpatnext = pattern;
156         oldpathc = pglob->gl_pathc;
157         bufnext = patbuf;
158
159         /* We don't need to check for buffer overflow any more. */
160         while ((c = *qpatnext++) != EOS) {
161                 switch (c) {
162                 case QUESTION:
163                         pglob->gl_flags |= WAPI_GLOB_MAGCHAR;
164                         *bufnext++ = M_ONE;
165                         break;
166                 case STAR:
167                         pglob->gl_flags |= WAPI_GLOB_MAGCHAR;
168                         /* collapse adjacent stars to one,
169                          * to avoid exponential behavior
170                          */
171                         if (bufnext == patbuf || bufnext[-1] != M_ALL)
172                                 *bufnext++ = M_ALL;
173                         break;
174                 default:
175                         *bufnext++ = CHAR(c);
176                         break;
177                 }
178         }
179         *bufnext = EOS;
180 #ifdef DEBUG
181         qprintf("glob0:", patbuf);
182 #endif
183
184         if ((err = glob1(dir, patbuf, patbuf+MAXPATHLEN-1, pglob, &limit,
185                          ignorecase, unique)) != 0)
186                 return(err);
187
188         if (pglob->gl_pathc == oldpathc) {
189                 return(WAPI_GLOB_NOMATCH);
190         }
191
192         return(0);
193 }
194
195 static int
196 glob1(GDir *dir, gchar *pattern, gchar *pattern_last, wapi_glob_t *pglob,
197       size_t *limitp, gboolean ignorecase, gboolean unique)
198 {
199         /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
200         if (*pattern == EOS)
201                 return(0);
202         return(glob3(dir, pattern, pattern_last, pglob, limitp, ignorecase,
203                      unique));
204 }
205
206 static gboolean contains (wapi_glob_t *pglob, const gchar *name)
207 {
208         int i;
209         char **pp;
210         
211         if (pglob->gl_pathv != NULL) {
212                 pp = pglob->gl_pathv + pglob->gl_offs;
213                 for (i = pglob->gl_pathc; i--; ++pp) {
214                         if (*pp) {
215                                 if (!strcmp (*pp, name)) {
216                                         return(TRUE);
217                                 }
218                         }
219                 }
220         }
221         
222         return(FALSE);
223 }
224
225 static int
226 glob3(GDir *dir, gchar *pattern, gchar *pattern_last, wapi_glob_t *pglob,
227       size_t *limitp, gboolean ignorecase, gboolean unique)
228 {
229         const gchar *name;
230
231         /* Search directory for matching names. */
232         while ((name = g_dir_read_name(dir))) {
233                 if (!match(name, pattern, pattern + strlen (pattern),
234                            ignorecase)) {
235                         continue;
236                 }
237                 if (!unique ||
238                     !contains (pglob, name)) {
239                         globextend (name, pglob, limitp);
240                 }
241         }
242
243         return(0);
244 }
245
246
247 /*
248  * Extend the gl_pathv member of a wapi_glob_t structure to accommodate a new item,
249  * add the new item, and update gl_pathc.
250  *
251  * This assumes the BSD realloc, which only copies the block when its size
252  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
253  * behavior.
254  *
255  * Return 0 if new item added, error code if memory couldn't be allocated.
256  *
257  * Invariant of the wapi_glob_t structure:
258  *      Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
259  *      gl_pathv points to (gl_offs + gl_pathc + 1) items.
260  */
261 static int
262 globextend(const gchar *path, wapi_glob_t *pglob, size_t *limitp)
263 {
264         char **pathv;
265         int i;
266         u_int newsize, len;
267         char *copy;
268         const gchar *p;
269
270         newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
271         pathv = pglob->gl_pathv ? realloc((char *)pglob->gl_pathv, newsize) :
272             malloc(newsize);
273         if (pathv == NULL) {
274                 if (pglob->gl_pathv) {
275                         free(pglob->gl_pathv);
276                         pglob->gl_pathv = NULL;
277                 }
278                 return(WAPI_GLOB_NOSPACE);
279         }
280
281         if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
282                 /* first time around -- clear initial gl_offs items */
283                 pathv += pglob->gl_offs;
284                 for (i = pglob->gl_offs; --i >= 0; )
285                         *--pathv = NULL;
286         }
287         pglob->gl_pathv = pathv;
288
289         for (p = path; *p++;)
290                 ;
291         len = (size_t)(p - path);
292         *limitp += len;
293         if ((copy = malloc(len)) != NULL) {
294                 if (g_Ctoc(path, copy, len)) {
295                         free(copy);
296                         return(WAPI_GLOB_NOSPACE);
297                 }
298                 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
299         }
300         pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
301
302         if ((pglob->gl_flags & WAPI_GLOB_LIMIT) &&
303             newsize + *limitp >= ARG_MAX) {
304                 errno = 0;
305                 return(WAPI_GLOB_NOSPACE);
306         }
307
308         return(copy == NULL ? WAPI_GLOB_NOSPACE : 0);
309 }
310
311
312 /*
313  * pattern matching function for filenames.  Each occurrence of the *
314  * pattern causes a recursion level.
315  */
316 static int
317 match(const gchar *name, gchar *pat, gchar *patend, gboolean ignorecase)
318 {
319         gchar c;
320
321         while (pat < patend) {
322                 c = *pat++;
323                 switch (c & M_MASK) {
324                 case M_ALL:
325                         if (pat == patend)
326                                 return(1);
327                         do {
328                                 if (match(name, pat, patend, ignorecase))
329                                         return(1);
330                         } while (*name++ != EOS);
331                         return(0);
332                 case M_ONE:
333                         if (*name++ == EOS)
334                                 return(0);
335                         break;
336                 default:
337                         if (ignorecase) {
338                                 if (g_ascii_tolower (*name++) != g_ascii_tolower (c))
339                                         return(0);
340                         } else {
341                                 if (*name++ != c)
342                                         return(0);
343                         }
344                         
345                         break;
346                 }
347         }
348         return(*name == EOS);
349 }
350
351 /* Free allocated data belonging to a wapi_glob_t structure. */
352 void
353 _wapi_globfree(wapi_glob_t *pglob)
354 {
355         int i;
356         char **pp;
357
358         if (pglob->gl_pathv != NULL) {
359                 pp = pglob->gl_pathv + pglob->gl_offs;
360                 for (i = pglob->gl_pathc; i--; ++pp)
361                         if (*pp)
362                                 free(*pp);
363                 free(pglob->gl_pathv);
364                 pglob->gl_pathv = NULL;
365         }
366 }
367
368 static int
369 g_Ctoc(const gchar *str, char *buf, u_int len)
370 {
371
372         while (len--) {
373                 if ((*buf++ = *str++) == EOS)
374                         return (0);
375         }
376         return (1);
377 }
378
379 #ifdef DEBUG
380 static void
381 qprintf(const char *str, Char *s)
382 {
383         Char *p;
384
385         (void)printf("%s:\n", str);
386         for (p = s; *p; p++)
387                 (void)printf("%c", CHAR(*p));
388         (void)printf("\n");
389         for (p = s; *p; p++)
390                 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
391         (void)printf("\n");
392         for (p = s; *p; p++)
393                 (void)printf("%c", ismeta(*p) ? '_' : ' ');
394         (void)printf("\n");
395 }
396 #endif