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