xref: /netbsd-src/bin/sh/expand.c (revision 811e6386f8c5e4a3521c7003da29ec8673e344fa)
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)expand.c	5.1 (Berkeley) 3/7/91";
39 static char rcsid[] = "$Header: /cvsroot/src/bin/sh/expand.c,v 1.3 1993/03/23 00:28:00 cgd Exp $";
40 #endif /* not lint */
41 
42 /*
43  * Routines to expand arguments to commands.  We have to deal with
44  * backquotes, shell variables, and file metacharacters.
45  */
46 
47 #include "shell.h"
48 #include "main.h"
49 #include "nodes.h"
50 #include "eval.h"
51 #include "expand.h"
52 #include "syntax.h"
53 #include "parser.h"
54 #include "jobs.h"
55 #include "options.h"
56 #include "var.h"
57 #include "input.h"
58 #include "output.h"
59 #include "memalloc.h"
60 #include "error.h"
61 #include "mystring.h"
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <errno.h>
65 #include <dirent.h>
66 
67 /*
68  * Structure specifying which parts of the string should be searched
69  * for IFS characters.
70  */
71 
72 struct ifsregion {
73 	struct ifsregion *next;	/* next region in list */
74 	int begoff;		/* offset of start of region */
75 	int endoff;		/* offset of end of region */
76 	int nulonly;		/* search for nul bytes only */
77 };
78 
79 
80 char *expdest;			/* output of current string */
81 struct nodelist *argbackq;	/* list of back quote expressions */
82 struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
83 struct ifsregion *ifslastp;	/* last struct in list */
84 struct arglist exparg;		/* holds expanded arg list */
85 #if UDIR
86 /*
87  * Set if the last argument processed had /u/logname expanded.  This
88  * variable is read by the cd command.
89  */
90 int didudir;
91 #endif
92 
93 #ifdef __STDC__
94 STATIC void argstr(char *, int);
95 STATIC void expbackq(union node *, int, int);
96 STATIC char *evalvar(char *, int);
97 STATIC int varisset(int);
98 STATIC void varvalue(int, int, int);
99 STATIC void recordregion(int, int, int);
100 STATIC void ifsbreakup(char *, struct arglist *);
101 STATIC void expandmeta(struct strlist *);
102 STATIC void expmeta(char *, char *);
103 STATIC void addfname(char *);
104 STATIC struct strlist *expsort(struct strlist *);
105 STATIC struct strlist *msort(struct strlist *, int);
106 STATIC int pmatch(char *, char *);
107 #else
108 STATIC void argstr();
109 STATIC void expbackq();
110 STATIC char *evalvar();
111 STATIC int varisset();
112 STATIC void varvalue();
113 STATIC void recordregion();
114 STATIC void ifsbreakup();
115 STATIC void expandmeta();
116 STATIC void expmeta();
117 STATIC void addfname();
118 STATIC struct strlist *expsort();
119 STATIC struct strlist *msort();
120 STATIC int pmatch();
121 #endif
122 #if UDIR
123 #ifdef __STDC__
124 STATIC char *expudir(char *);
125 #else
126 STATIC char *expudir();
127 #endif
128 #endif /* UDIR */
129 
130 
131 
132 /*
133  * Expand shell variables and backquotes inside a here document.
134  */
135 
136 void
137 expandhere(arg, fd)
138 	union node *arg;	/* the document */
139 	int fd;			/* where to write the expanded version */
140 	{
141 	herefd = fd;
142 	expandarg(arg, (struct arglist *)NULL, 0);
143 	xwrite(fd, stackblock(), expdest - stackblock());
144 }
145 
146 
147 /*
148  * Perform variable substitution and command substitution on an argument,
149  * placing the resulting list of arguments in arglist.  If full is true,
150  * perform splitting and file name expansion.  When arglist is NULL, perform
151  * here document expansion.
152  */
153 
154 void
155 expandarg(arg, arglist, full)
156 	union node *arg;
157 	struct arglist *arglist;
158 	{
159 	struct strlist *sp;
160 	char *p;
161 
162 #if UDIR
163 	didudir = 0;
164 #endif
165 	argbackq = arg->narg.backquote;
166 	STARTSTACKSTR(expdest);
167 	ifsfirst.next = NULL;
168 	ifslastp = NULL;
169 	argstr(arg->narg.text, full);
170 	if (arglist == NULL)
171 		return;			/* here document expanded */
172 	STPUTC('\0', expdest);
173 	p = grabstackstr(expdest);
174 	exparg.lastp = &exparg.list;
175 	if (full) {
176 		ifsbreakup(p, &exparg);
177 		*exparg.lastp = NULL;
178 		exparg.lastp = &exparg.list;
179 		expandmeta(exparg.list);
180 	} else {
181 		sp = (struct strlist *)stalloc(sizeof (struct strlist));
182 		sp->text = p;
183 		*exparg.lastp = sp;
184 		exparg.lastp = &sp->next;
185 	}
186 	while (ifsfirst.next != NULL) {
187 		struct ifsregion *ifsp;
188 		INTOFF;
189 		ifsp = ifsfirst.next->next;
190 		ckfree(ifsfirst.next);
191 		ifsfirst.next = ifsp;
192 		INTON;
193 	}
194 	*exparg.lastp = NULL;
195 	if (exparg.list) {
196 		*arglist->lastp = exparg.list;
197 		arglist->lastp = exparg.lastp;
198 	}
199 }
200 
201 
202 
203 /*
204  * Perform variable and command substitution.  If full is set, output CTLESC
205  * characters to allow for further processing.  If full is not set, treat
206  * $@ like $* since no splitting will be performed.
207  */
208 
209 STATIC void
210 argstr(p, full)
211 	register char *p;
212 	{
213 	char c;
214 
215 	for (;;) {
216 		switch (c = *p++) {
217 		case '\0':
218 		case CTLENDVAR:
219 			goto breakloop;
220 		case CTLESC:
221 			if (full)
222 				STPUTC(c, expdest);
223 			c = *p++;
224 			STPUTC(c, expdest);
225 			break;
226 		case CTLVAR:
227 			p = evalvar(p, full);
228 			break;
229 		case CTLBACKQ:
230 		case CTLBACKQ|CTLQUOTE:
231 			expbackq(argbackq->n, c & CTLQUOTE, full);
232 			argbackq = argbackq->next;
233 			break;
234 		default:
235 			STPUTC(c, expdest);
236 		}
237 	}
238 breakloop:;
239 }
240 
241 
242 /*
243  * Expand stuff in backwards quotes.
244  */
245 
246 STATIC void
247 expbackq(cmd, quoted, full)
248 	union node *cmd;
249 	{
250 	struct backcmd in;
251 	int i;
252 	char buf[128];
253 	char *p;
254 	char *dest = expdest;
255 	struct ifsregion saveifs, *savelastp;
256 	struct nodelist *saveargbackq;
257 	char lastc;
258 	int startloc = dest - stackblock();
259 	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
260 	int saveherefd;
261 
262 	INTOFF;
263 	saveifs = ifsfirst;
264 	savelastp = ifslastp;
265 	saveargbackq = argbackq;
266 	saveherefd = herefd;
267 	herefd = -1;
268 	p = grabstackstr(dest);
269 	evalbackcmd(cmd, &in);
270 	ungrabstackstr(p, dest);
271 	ifsfirst = saveifs;
272 	ifslastp = savelastp;
273 	argbackq = saveargbackq;
274 	herefd = saveherefd;
275 
276 	p = in.buf;
277 	lastc = '\0';
278 	for (;;) {
279 		if (--in.nleft < 0) {
280 			if (in.fd < 0)
281 				break;
282 			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
283 			TRACE(("expbackq: read returns %d\n", i));
284 			if (i <= 0)
285 				break;
286 			p = buf;
287 			in.nleft = i - 1;
288 		}
289 		lastc = *p++;
290 		if (lastc != '\0') {
291 			if (full && syntax[lastc] == CCTL)
292 				STPUTC(CTLESC, dest);
293 			STPUTC(lastc, dest);
294 		}
295 	}
296 	if (lastc == '\n') {
297 		STUNPUTC(dest);
298 	}
299 	if (in.fd >= 0)
300 		close(in.fd);
301 	if (in.buf)
302 		ckfree(in.buf);
303 	if (in.jp)
304 		waitforjob(in.jp);
305 	if (quoted == 0)
306 		recordregion(startloc, dest - stackblock(), 0);
307 	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
308 		(dest - stackblock()) - startloc,
309 		(dest - stackblock()) - startloc,
310 		stackblock() + startloc));
311 	expdest = dest;
312 	INTON;
313 }
314 
315 
316 
317 /*
318  * Expand a variable, and return a pointer to the next character in the
319  * input string.
320  */
321 
322 STATIC char *
323 evalvar(p, full)
324 	char *p;
325 	{
326 	int subtype;
327 	int flags;
328 	char *var;
329 	char *val;
330 	int c;
331 	int set;
332 	int special;
333 	int startloc;
334 
335 	flags = *p++;
336 	subtype = flags & VSTYPE;
337 	var = p;
338 	special = 0;
339 	if (! is_name(*p))
340 		special = 1;
341 	p = strchr(p, '=') + 1;
342 again: /* jump here after setting a variable with ${var=text} */
343 	if (special) {
344 		set = varisset(*var);
345 		val = NULL;
346 	} else {
347 		val = lookupvar(var);
348 		if (val == NULL || (flags & VSNUL) && val[0] == '\0') {
349 			val = NULL;
350 			set = 0;
351 		} else
352 			set = 1;
353 	}
354 	startloc = expdest - stackblock();
355 	if (set && subtype != VSPLUS) {
356 		/* insert the value of the variable */
357 		if (special) {
358 			varvalue(*var, flags & VSQUOTE, full);
359 		} else {
360 			char const *syntax = (flags & VSQUOTE)? DQSYNTAX : BASESYNTAX;
361 
362 			while (*val) {
363 				if (full && syntax[*val] == CCTL)
364 					STPUTC(CTLESC, expdest);
365 				STPUTC(*val++, expdest);
366 			}
367 		}
368 	}
369 	if (subtype == VSPLUS)
370 		set = ! set;
371 	if (((flags & VSQUOTE) == 0 || (*var == '@' && shellparam.nparam != 1))
372 	 && (set || subtype == VSNORMAL))
373 		recordregion(startloc, expdest - stackblock(), flags & VSQUOTE);
374 	if (! set && subtype != VSNORMAL) {
375 		if (subtype == VSPLUS || subtype == VSMINUS) {
376 			argstr(p, full);
377 		} else {
378 			char *startp;
379 			int saveherefd = herefd;
380 			herefd = -1;
381 			argstr(p, 0);
382 			STACKSTRNUL(expdest);
383 			herefd = saveherefd;
384 			startp = stackblock() + startloc;
385 			if (subtype == VSASSIGN) {
386 				setvar(var, startp, 0);
387 				STADJUST(startp - expdest, expdest);
388 				flags &=~ VSNUL;
389 				goto again;
390 			}
391 			/* subtype == VSQUESTION */
392 			if (*p != CTLENDVAR) {
393 				outfmt(&errout, "%s\n", startp);
394 				error((char *)NULL);
395 			}
396 			error("%.*s: parameter %snot set", p - var - 1,
397 				var, (flags & VSNUL)? "null or " : nullstr);
398 		}
399 	}
400 	if (subtype != VSNORMAL) {	/* skip to end of alternative */
401 		int nesting = 1;
402 		for (;;) {
403 			if ((c = *p++) == CTLESC)
404 				p++;
405 			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
406 				if (set)
407 					argbackq = argbackq->next;
408 			} else if (c == CTLVAR) {
409 				if ((*p++ & VSTYPE) != VSNORMAL)
410 					nesting++;
411 			} else if (c == CTLENDVAR) {
412 				if (--nesting == 0)
413 					break;
414 			}
415 		}
416 	}
417 	return p;
418 }
419 
420 
421 
422 /*
423  * Test whether a specialized variable is set.
424  */
425 
426 STATIC int
427 varisset(name)
428 	char name;
429 	{
430 	char **ap;
431 
432 	if (name == '!') {
433 		if (backgndpid == -1)
434 			return 0;
435 	} else if (name == '@' || name == '*') {
436 		if (*shellparam.p == NULL)
437 			return 0;
438 	} else if ((unsigned)(name -= '1') <= '9' - '1') {
439 		ap = shellparam.p;
440 		do {
441 			if (*ap++ == NULL)
442 				return 0;
443 		} while (--name >= 0);
444 	}
445 	return 1;
446 }
447 
448 
449 
450 /*
451  * Add the value of a specialized variable to the stack string.
452  */
453 
454 STATIC void
455 varvalue(name, quoted, allow_split)
456 	char name;
457 	{
458 	int num;
459 	char temp[32];
460 	char *p;
461 	int i;
462 	extern int exitstatus;
463 	char sep;
464 	char **ap;
465 	char const *syntax;
466 
467 	switch (name) {
468 	case '$':
469 		num = rootpid;
470 		goto numvar;
471 	case '?':
472 		num = exitstatus;
473 		goto numvar;
474 	case '#':
475 		num = shellparam.nparam;
476 		goto numvar;
477 	case '!':
478 		num = backgndpid;
479 numvar:
480 		p = temp + 31;
481 		temp[31] = '\0';
482 		do {
483 			*--p = num % 10 + '0';
484 		} while ((num /= 10) != 0);
485 		while (*p)
486 			STPUTC(*p++, expdest);
487 		break;
488 	case '-':
489 		for (i = 0 ; optchar[i] ; i++) {
490 			if (optval[i])
491 				STPUTC(optchar[i], expdest);
492 		}
493 		break;
494 	case '@':
495 		if (allow_split) {
496 			sep = '\0';
497 			goto allargs;
498 		}
499 		/* fall through */
500 	case '*':
501 		sep = ' ';
502 allargs:
503 		syntax = quoted? DQSYNTAX : BASESYNTAX;
504 		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
505 			/* should insert CTLESC characters */
506 			while (*p) {
507 				if (syntax[*p] == CCTL)
508 					STPUTC(CTLESC, expdest);
509 				STPUTC(*p++, expdest);
510 			}
511 			if (*ap)
512 				STPUTC(sep, expdest);
513 		}
514 		break;
515 	case '0':
516 		p = arg0;
517 string:
518 		syntax = quoted? DQSYNTAX : BASESYNTAX;
519 		while (*p) {
520 			if (syntax[*p] == CCTL)
521 				STPUTC(CTLESC, expdest);
522 			STPUTC(*p++, expdest);
523 		}
524 		break;
525 	default:
526 		if ((unsigned)(name -= '1') <= '9' - '1') {
527 			p = shellparam.p[name];
528 			goto string;
529 		}
530 		break;
531 	}
532 }
533 
534 
535 
536 /*
537  * Record the the fact that we have to scan this region of the
538  * string for IFS characters.
539  */
540 
541 STATIC void
542 recordregion(start, end, nulonly) {
543 	register struct ifsregion *ifsp;
544 
545 	if (ifslastp == NULL) {
546 		ifsp = &ifsfirst;
547 	} else {
548 		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
549 		ifslastp->next = ifsp;
550 	}
551 	ifslastp = ifsp;
552 	ifslastp->next = NULL;
553 	ifslastp->begoff = start;
554 	ifslastp->endoff = end;
555 	ifslastp->nulonly = nulonly;
556 }
557 
558 
559 
560 /*
561  * Break the argument string into pieces based upon IFS and add the
562  * strings to the argument list.  The regions of the string to be
563  * searched for IFS characters have been stored by recordregion.
564  */
565 
566 STATIC void
567 ifsbreakup(string, arglist)
568 	char *string;
569 	struct arglist *arglist;
570 	{
571 	struct ifsregion *ifsp;
572 	struct strlist *sp;
573 	char *start;
574 	register char *p;
575 	char *q;
576 	char *ifs;
577 
578 	start = string;
579 	if (ifslastp != NULL) {
580 		ifsp = &ifsfirst;
581 		do {
582 			p = string + ifsp->begoff;
583 			ifs = ifsp->nulonly? nullstr : ifsval();
584 			while (p < string + ifsp->endoff) {
585 				q = p;
586 				if (*p == CTLESC)
587 					p++;
588 				if (strchr(ifs, *p++)) {
589 					if (q > start || *ifs != ' ') {
590 						*q = '\0';
591 						sp = (struct strlist *)stalloc(sizeof *sp);
592 						sp->text = start;
593 						*arglist->lastp = sp;
594 						arglist->lastp = &sp->next;
595 					}
596 					if (*ifs == ' ') {
597 						for (;;) {
598 							if (p >= string + ifsp->endoff)
599 								break;
600 							q = p;
601 							if (*p == CTLESC)
602 								p++;
603 							if (strchr(ifs, *p++) == NULL) {
604 								p = q;
605 								break;
606 							}
607 						}
608 					}
609 					start = p;
610 				}
611 			}
612 		} while ((ifsp = ifsp->next) != NULL);
613 		if (*start || (*ifs != ' ' && start > string)) {
614 			sp = (struct strlist *)stalloc(sizeof *sp);
615 			sp->text = start;
616 			*arglist->lastp = sp;
617 			arglist->lastp = &sp->next;
618 		}
619 	} else {
620 		sp = (struct strlist *)stalloc(sizeof *sp);
621 		sp->text = start;
622 		*arglist->lastp = sp;
623 		arglist->lastp = &sp->next;
624 	}
625 }
626 
627 
628 
629 /*
630  * Expand shell metacharacters.  At this point, the only control characters
631  * should be escapes.  The results are stored in the list exparg.
632  */
633 
634 char *expdir;
635 
636 
637 STATIC void
638 expandmeta(str)
639 	struct strlist *str;
640 	{
641 	char *p;
642 	struct strlist **savelastp;
643 	struct strlist *sp;
644 	char c;
645 
646 	while (str) {
647 		if (fflag)
648 			goto nometa;
649 		p = str->text;
650 #if UDIR
651 		if (p[0] == '/' && p[1] == 'u' && p[2] == '/')
652 			str->text = p = expudir(p);
653 #endif
654 		for (;;) {			/* fast check for meta chars */
655 			if ((c = *p++) == '\0')
656 				goto nometa;
657 			if (c == '*' || c == '?' || c == '[' || c == '!')
658 				break;
659 		}
660 		savelastp = exparg.lastp;
661 		INTOFF;
662 		if (expdir == NULL)
663 			expdir = ckmalloc(1024); /* I hope this is big enough */
664 		expmeta(expdir, str->text);
665 		ckfree(expdir);
666 		expdir = NULL;
667 		INTON;
668 		if (exparg.lastp == savelastp) {
669 			if (! zflag) {
670 nometa:
671 				*exparg.lastp = str;
672 				rmescapes(str->text);
673 				exparg.lastp = &str->next;
674 			}
675 		} else {
676 			*exparg.lastp = NULL;
677 			*savelastp = sp = expsort(*savelastp);
678 			while (sp->next != NULL)
679 				sp = sp->next;
680 			exparg.lastp = &sp->next;
681 		}
682 		str = str->next;
683 	}
684 }
685 
686 
687 #if UDIR
688 /*
689  * Expand /u/username into the home directory for the specified user.
690  * We could use the getpw stuff here, but then we would have to load
691  * in stdio and who knows what else.
692  */
693 
694 #define MAXLOGNAME 32
695 #define MAXPWLINE 128
696 
697 char *pfgets();
698 
699 
700 STATIC char *
701 expudir(path)
702 	char *path;
703 	{
704 	register char *p, *q, *r;
705 	char name[MAXLOGNAME];
706 	char line[MAXPWLINE];
707 	int i;
708 
709 	r = path;				/* result on failure */
710 	p = r + 3;			/* the 3 skips "/u/" */
711 	q = name;
712 	while (*p && *p != '/') {
713 		if (q >= name + MAXLOGNAME - 1)
714 			return r;		/* fail, name too long */
715 		*q++ = *p++;
716 	}
717 	*q = '\0';
718 	setinputfile("/etc/passwd", 1);
719 	q = line + strlen(name);
720 	while (pfgets(line, MAXPWLINE) != NULL) {
721 		if (line[0] == name[0] && prefix(name, line) && *q == ':') {
722 			/* skip to start of home directory */
723 			i = 4;
724 			do {
725 				while (*++q && *q != ':');
726 			} while (--i > 0);
727 			if (*q == '\0')
728 				break;		/* fail, corrupted /etc/passwd */
729 			q++;
730 			for (r = q ; *r && *r != '\n' && *r != ':' ; r++);
731 			*r = '\0';		/* nul terminate home directory */
732 			i = r - q;		/* i = strlen(q) */
733 			r = stalloc(i + strlen(p) + 1);
734 			scopy(q, r);
735 			scopy(p, r + i);
736 			TRACE(("expudir converts %s to %s\n", path, r));
737 			didudir = 1;
738 			path = r;		/* succeed */
739 			break;
740 		}
741 	}
742 	popfile();
743 	return r;
744 }
745 #endif
746 
747 
748 /*
749  * Do metacharacter (i.e. *, ?, [...]) expansion.
750  */
751 
752 STATIC void
753 expmeta(enddir, name)
754 	char *enddir;
755 	char *name;
756 	{
757 	register char *p;
758 	char *q;
759 	char *start;
760 	char *endname;
761 	int metaflag;
762 	struct stat statb;
763 	DIR *dirp;
764 	struct dirent *dp;
765 	int atend;
766 	int matchdot;
767 
768 	metaflag = 0;
769 	start = name;
770 	for (p = name ; ; p++) {
771 		if (*p == '*' || *p == '?')
772 			metaflag = 1;
773 		else if (*p == '[') {
774 			q = p + 1;
775 			if (*q == '!')
776 				q++;
777 			for (;;) {
778 				if (*q == CTLESC)
779 					q++;
780 				if (*q == '/' || *q == '\0')
781 					break;
782 				if (*++q == ']') {
783 					metaflag = 1;
784 					break;
785 				}
786 			}
787 		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
788 			metaflag = 1;
789 		} else if (*p == '\0')
790 			break;
791 		else if (*p == CTLESC)
792 			p++;
793 		if (*p == '/') {
794 			if (metaflag)
795 				break;
796 			start = p + 1;
797 		}
798 	}
799 	if (metaflag == 0) {	/* we've reached the end of the file name */
800 		if (enddir != expdir)
801 			metaflag++;
802 		for (p = name ; ; p++) {
803 			if (*p == CTLESC)
804 				p++;
805 			*enddir++ = *p;
806 			if (*p == '\0')
807 				break;
808 		}
809 		if (metaflag == 0 || stat(expdir, &statb) >= 0)
810 			addfname(expdir);
811 		return;
812 	}
813 	endname = p;
814 	if (start != name) {
815 		p = name;
816 		while (p < start) {
817 			if (*p == CTLESC)
818 				p++;
819 			*enddir++ = *p++;
820 		}
821 	}
822 	if (enddir == expdir) {
823 		p = ".";
824 	} else if (enddir == expdir + 1 && *expdir == '/') {
825 		p = "/";
826 	} else {
827 		p = expdir;
828 		enddir[-1] = '\0';
829 	}
830 	if ((dirp = opendir(p)) == NULL)
831 		return;
832 	if (enddir != expdir)
833 		enddir[-1] = '/';
834 	if (*endname == 0) {
835 		atend = 1;
836 	} else {
837 		atend = 0;
838 		*endname++ = '\0';
839 	}
840 	matchdot = 0;
841 	if (start[0] == '.' || start[0] == CTLESC && start[1] == '.')
842 		matchdot++;
843 	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
844 		if (dp->d_name[0] == '.' && ! matchdot)
845 			continue;
846 		if (patmatch(start, dp->d_name)) {
847 			if (atend) {
848 				scopy(dp->d_name, enddir);
849 				addfname(expdir);
850 			} else {
851 				char *q;
852 				for (p = enddir, q = dp->d_name ; *p++ = *q++ ;);
853 				p[-1] = '/';
854 				expmeta(p, endname);
855 			}
856 		}
857 	}
858 	closedir(dirp);
859 	if (! atend)
860 		endname[-1] = '/';
861 }
862 
863 
864 /*
865  * Add a file name to the list.
866  */
867 
868 STATIC void
869 addfname(name)
870 	char *name;
871 	{
872 	char *p;
873 	struct strlist *sp;
874 
875 	p = stalloc(strlen(name) + 1);
876 	scopy(name, p);
877 	sp = (struct strlist *)stalloc(sizeof *sp);
878 	sp->text = p;
879 	*exparg.lastp = sp;
880 	exparg.lastp = &sp->next;
881 }
882 
883 
884 /*
885  * Sort the results of file name expansion.  It calculates the number of
886  * strings to sort and then calls msort (short for merge sort) to do the
887  * work.
888  */
889 
890 STATIC struct strlist *
891 expsort(str)
892 	struct strlist *str;
893 	{
894 	int len;
895 	struct strlist *sp;
896 
897 	len = 0;
898 	for (sp = str ; sp ; sp = sp->next)
899 		len++;
900 	return msort(str, len);
901 }
902 
903 
904 STATIC struct strlist *
905 msort(list, len)
906 	struct strlist *list;
907 	{
908 	struct strlist *p, *q;
909 	struct strlist **lpp;
910 	int half;
911 	int n;
912 
913 	if (len <= 1)
914 		return list;
915 	half = len >> 1;
916 	p = list;
917 	for (n = half ; --n >= 0 ; ) {
918 		q = p;
919 		p = p->next;
920 	}
921 	q->next = NULL;			/* terminate first half of list */
922 	q = msort(list, half);		/* sort first half of list */
923 	p = msort(p, len - half);		/* sort second half */
924 	lpp = &list;
925 	for (;;) {
926 		if (strcmp(p->text, q->text) < 0) {
927 			*lpp = p;
928 			lpp = &p->next;
929 			if ((p = *lpp) == NULL) {
930 				*lpp = q;
931 				break;
932 			}
933 		} else {
934 			*lpp = q;
935 			lpp = &q->next;
936 			if ((q = *lpp) == NULL) {
937 				*lpp = p;
938 				break;
939 			}
940 		}
941 	}
942 	return list;
943 }
944 
945 
946 
947 /*
948  * Returns true if the pattern matches the string.
949  */
950 
951 int
952 patmatch(pattern, string)
953 	char *pattern;
954 	char *string;
955 	{
956 	if (pattern[0] == '!' && pattern[1] == '!')
957 		return 1 - pmatch(pattern + 2, string);
958 	else
959 		return pmatch(pattern, string);
960 }
961 
962 
963 STATIC int
964 pmatch(pattern, string)
965 	char *pattern;
966 	char *string;
967 	{
968 	register char *p, *q;
969 	register char c;
970 
971 	p = pattern;
972 	q = string;
973 	for (;;) {
974 		switch (c = *p++) {
975 		case '\0':
976 			goto breakloop;
977 		case CTLESC:
978 			if (*q++ != *p++)
979 				return 0;
980 			break;
981 		case '?':
982 			if (*q++ == '\0')
983 				return 0;
984 			break;
985 		case '*':
986 			c = *p;
987 			if (c != CTLESC && c != '?' && c != '*' && c != '[') {
988 				while (*q != c) {
989 					if (*q == '\0')
990 						return 0;
991 					q++;
992 				}
993 			}
994 			do {
995 				if (pmatch(p, q))
996 					return 1;
997 			} while (*q++ != '\0');
998 			return 0;
999 		case '[': {
1000 			char *endp;
1001 			int invert, found;
1002 			char chr;
1003 
1004 			endp = p;
1005 			if (*endp == '!')
1006 				endp++;
1007 			for (;;) {
1008 				if (*endp == '\0')
1009 					goto dft;		/* no matching ] */
1010 				if (*endp == CTLESC)
1011 					endp++;
1012 				if (*++endp == ']')
1013 					break;
1014 			}
1015 			invert = 0;
1016 			if (*p == '!') {
1017 				invert++;
1018 				p++;
1019 			}
1020 			found = 0;
1021 			chr = *q++;
1022 			c = *p++;
1023 			do {
1024 				if (c == CTLESC)
1025 					c = *p++;
1026 				if (*p == '-' && p[1] != ']') {
1027 					p++;
1028 					if (*p == CTLESC)
1029 						p++;
1030 					if (chr >= c && chr <= *p)
1031 						found = 1;
1032 					p++;
1033 				} else {
1034 					if (chr == c)
1035 						found = 1;
1036 				}
1037 			} while ((c = *p++) != ']');
1038 			if (found == invert)
1039 				return 0;
1040 			break;
1041 		}
1042 dft:	    default:
1043 			if (*q++ != c)
1044 				return 0;
1045 			break;
1046 		}
1047 	}
1048 breakloop:
1049 	if (*q != '\0')
1050 		return 0;
1051 	return 1;
1052 }
1053 
1054 
1055 
1056 /*
1057  * Remove any CTLESC characters from a string.
1058  */
1059 
1060 void
1061 rmescapes(str)
1062 	char *str;
1063 	{
1064 	register char *p, *q;
1065 
1066 	p = str;
1067 	while (*p != CTLESC) {
1068 		if (*p++ == '\0')
1069 			return;
1070 	}
1071 	q = p;
1072 	while (*p) {
1073 		if (*p == CTLESC)
1074 			p++;
1075 		*q++ = *p++;
1076 	}
1077 	*q = '\0';
1078 }
1079 
1080 
1081 
1082 /*
1083  * See if a pattern matches in a case statement.
1084  */
1085 
1086 int
1087 casematch(pattern, val)
1088 	union node *pattern;
1089 	char *val;
1090 	{
1091 	struct stackmark smark;
1092 	int result;
1093 	char *p;
1094 
1095 	setstackmark(&smark);
1096 	argbackq = pattern->narg.backquote;
1097 	STARTSTACKSTR(expdest);
1098 	ifslastp = NULL;
1099 	argstr(pattern->narg.text, 0);
1100 	STPUTC('\0', expdest);
1101 	p = grabstackstr(expdest);
1102 	result = patmatch(p, val);
1103 	popstackmark(&smark);
1104 	return result;
1105 }
1106