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