Initial import from FreeBSD RELENG_4:
[dragonfly.git] / usr.bin / rdist / expand.c
1 /*
2  * Copyright (c) 1983, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. 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 #ifndef lint
35 #if 0
36 static char sccsid[] = "@(#)expand.c    8.1 (Berkeley) 6/9/93";
37 #endif
38 static const char rcsid[] =
39   "$FreeBSD: src/usr.bin/rdist/expand.c,v 1.8 1999/08/28 01:05:06 peter Exp $";
40 #endif /* not lint */
41
42 #include "defs.h"
43
44 #define GAVSIZ  NCARGS / 6
45 #define LC '{'
46 #define RC '}'
47
48 static char     shchars[] = "${[*?";
49
50 int     which;          /* bit mask of types to expand */
51 int     eargc;          /* expanded arg count */
52 char    **eargv;        /* expanded arg vectors */
53 char    *path;
54 char    *pathp;
55 char    *lastpathp;
56 char    *tilde;         /* "~user" if not expanding tilde, else "" */
57 char    *tpathp;
58 int     nleft;
59
60 int     expany;         /* any expansions done? */
61 char    *entp;
62 char    **sortbase;
63
64 #define sort()  qsort((char *)sortbase, &eargv[eargc] - sortbase, \
65                       sizeof(*sortbase), argcmp), sortbase = &eargv[eargc]
66
67 static void     Cat __P((char *, char *));
68 static void     addpath __P((int));
69 static int      amatch __P((char *, char *));
70 static int      argcmp __P((const void *, const void *));
71 static int      execbrc __P((char *, char *));
72 static void     expsh __P((char *));
73 static void     expstr __P((char *));
74 static int      match __P((char *, char *));
75 static void     matchdir __P((char *));
76 static int      smatch __P((char *, char *));
77
78 /*
79  * Take a list of names and expand any macros, etc.
80  * wh = E_VARS if expanding variables.
81  * wh = E_SHELL if expanding shell characters.
82  * wh = E_TILDE if expanding `~'.
83  * or any of these or'ed together.
84  *
85  * Major portions of this were snarfed from csh/sh.glob.c.
86  */
87 struct namelist *
88 expand(list, wh)
89         struct namelist *list;
90         int wh;
91 {
92         register struct namelist *nl, *prev;
93         register int n;
94         char pathbuf[BUFSIZ];
95         char *argvbuf[GAVSIZ];
96
97         if (debug) {
98                 printf("expand(%p, %d)\nlist = ", list, wh);
99                 prnames(list);
100         }
101
102         if (wh == 0) {
103                 register char *cp;
104
105                 for (nl = list; nl != NULL; nl = nl->n_next)
106                         for (cp = nl->n_name; *cp; cp++)
107                                 *cp = *cp & TRIM;
108                 return(list);
109         }
110
111         which = wh;
112         path = tpathp = pathp = pathbuf;
113         *pathp = '\0';
114         lastpathp = &path[sizeof pathbuf - 2];
115         tilde = "";
116         eargc = 0;
117         eargv = sortbase = argvbuf;
118         *eargv = 0;
119         nleft = NCARGS - 4;
120         /*
121          * Walk the name list and expand names into eargv[];
122          */
123         for (nl = list; nl != NULL; nl = nl->n_next)
124                 expstr(nl->n_name);
125         /*
126          * Take expanded list of names from eargv[] and build a new list.
127          */
128         list = prev = NULL;
129         for (n = 0; n < eargc; n++) {
130                 nl = makenl(NULL);
131                 nl->n_name = eargv[n];
132                 if (prev == NULL)
133                         list = prev = nl;
134                 else {
135                         prev->n_next = nl;
136                         prev = nl;
137                 }
138         }
139         if (debug) {
140                 printf("expanded list = ");
141                 prnames(list);
142         }
143         return(list);
144 }
145
146 static void
147 expstr(s)
148         char *s;
149 {
150         register char *cp, *cp1;
151         register struct namelist *tp;
152         char *tail;
153         char buf[BUFSIZ];
154         int savec, oeargc;
155         extern char homedir[];
156
157         if (s == NULL || *s == '\0')
158                 return;
159
160         if ((which & E_VARS) && (cp = index(s, '$')) != NULL) {
161                 *cp++ = '\0';
162                 if (*cp == '\0') {
163                         yyerror("no variable name after '$'");
164                         return;
165                 }
166                 if (*cp == LC) {
167                         cp++;
168                         if ((tail = index(cp, RC)) == NULL) {
169                                 yyerror("unmatched '{'");
170                                 return;
171                         }
172                         *tail++ = savec = '\0';
173                         if (*cp == '\0') {
174                                 yyerror("no variable name after '$'");
175                                 return;
176                         }
177                 } else {
178                         tail = cp + 1;
179                         savec = *tail;
180                         *tail = '\0';
181                 }
182                 tp = lookup(cp, NULL, 0);
183                 if (savec != '\0')
184                         *tail = savec;
185                 if (tp != NULL) {
186                         for (; tp != NULL; tp = tp->n_next) {
187                                 snprintf(buf, sizeof(buf), 
188                                     "%s%s%s", s, tp->n_name, tail);
189                                 expstr(buf);
190                         }
191                         return;
192                 }
193                 snprintf(buf, sizeof(buf), "%s%s", s, tail);
194                 expstr(buf);
195                 return;
196         }
197         if ((which & ~E_VARS) == 0 || !strcmp(s, "{") || !strcmp(s, "{}")) {
198                 Cat(s, "");
199                 sort();
200                 return;
201         }
202         if (*s == '~') {
203                 cp = ++s;
204                 if (*cp == '\0' || *cp == '/') {
205                         tilde = "~";
206                         cp1 = homedir;
207                 } else {
208                         tilde = cp1 = buf;
209                         *cp1++ = '~';
210                         do
211                                 *cp1++ = *cp++;
212                         while (*cp && *cp != '/');
213                         *cp1 = '\0';
214                         if (pw == NULL || strcmp(pw->pw_name, buf+1) != 0) {
215                                 if ((pw = getpwnam(buf+1)) == NULL) {
216                                         strcat(buf, ": unknown user name");
217                                         yyerror(buf+1);
218                                         return;
219                                 }
220                         }
221                         cp1 = pw->pw_dir;
222                         s = cp;
223                 }
224                 for (cp = path; (*cp++ = *cp1++); )
225                         ;
226                 tpathp = pathp = cp - 1;
227         } else {
228                 tpathp = pathp = path;
229                 tilde = "";
230         }
231         *pathp = '\0';
232         if (!(which & E_SHELL)) {
233                 if (which & E_TILDE)
234                         Cat(path, s);
235                 else
236                         Cat(tilde, s);
237                 sort();
238                 return;
239         }
240         oeargc = eargc;
241         expany = 0;
242         expsh(s);
243         if (eargc == oeargc)
244                 Cat(s, "");             /* "nonomatch" is set */
245         sort();
246 }
247
248 static int
249 argcmp(a1, a2)
250         const void *a1, *a2;
251 {
252
253         return (strcmp(*(char **)a1, *(char **)a2));
254 }
255
256 /*
257  * If there are any Shell meta characters in the name,
258  * expand into a list, after searching directory
259  */
260 static void
261 expsh(s)
262         char *s;
263 {
264         register char *cp;
265         register char *spathp, *oldcp;
266         struct stat stb;
267
268         spathp = pathp;
269         cp = s;
270         while (!any(*cp, shchars)) {
271                 if (*cp == '\0') {
272                         if (!expany || stat(path, &stb) >= 0) {
273                                 if (which & E_TILDE)
274                                         Cat(path, "");
275                                 else
276                                         Cat(tilde, tpathp);
277                         }
278                         goto endit;
279                 }
280                 addpath(*cp++);
281         }
282         oldcp = cp;
283         while (cp > s && *cp != '/')
284                 cp--, pathp--;
285         if (*cp == '/')
286                 cp++, pathp++;
287         *pathp = '\0';
288         if (*oldcp == '{') {
289                 execbrc(cp, NULL);
290                 return;
291         }
292         matchdir(cp);
293 endit:
294         pathp = spathp;
295         *pathp = '\0';
296 }
297
298 static void
299 matchdir(pattern)
300         char *pattern;
301 {
302         struct stat stb;
303         register struct dirent *dp;
304         DIR *dirp;
305
306         dirp = opendir(path);
307         if (dirp == NULL) {
308                 if (expany)
309                         return;
310                 goto patherr2;
311         }
312         if (fstat(dirp->dd_fd, &stb) < 0)
313                 goto patherr1;
314         if (!ISDIR(stb.st_mode)) {
315                 errno = ENOTDIR;
316                 goto patherr1;
317         }
318         while ((dp = readdir(dirp)) != NULL)
319                 if (match(dp->d_name, pattern)) {
320                         if (which & E_TILDE)
321                                 Cat(path, dp->d_name);
322                         else {
323                                 strcpy(pathp, dp->d_name);
324                                 Cat(tilde, tpathp);
325                                 *pathp = '\0';
326                         }
327                 }
328         closedir(dirp);
329         return;
330
331 patherr1:
332         closedir(dirp);
333 patherr2:
334         strcat(path, ": ");
335         strcat(path, strerror(errno));
336         yyerror(path);
337 }
338
339 static int
340 execbrc(p, s)
341         char *p, *s;
342 {
343         char restbuf[BUFSIZ + 2];
344         register char *pe, *pm, *pl;
345         int brclev = 0;
346         char *lm, savec, *spathp;
347
348         for (lm = restbuf; *p != '{'; *lm++ = *p++)
349                 continue;
350         for (pe = ++p; *pe; pe++)
351                 switch (*pe) {
352
353                 case '{':
354                         brclev++;
355                         continue;
356
357                 case '}':
358                         if (brclev == 0)
359                                 goto pend;
360                         brclev--;
361                         continue;
362
363                 case '[':
364                         for (pe++; *pe && *pe != ']'; pe++)
365                                 continue;
366                         if (!*pe)
367                                 yyerror("Missing ']'");
368                         continue;
369                 }
370 pend:
371         if (brclev || !*pe) {
372                 yyerror("Missing '}'");
373                 return (0);
374         }
375         for (pl = pm = p; pm <= pe; pm++)
376                 switch (*pm & (QUOTE|TRIM)) {
377
378                 case '{':
379                         brclev++;
380                         continue;
381
382                 case '}':
383                         if (brclev) {
384                                 brclev--;
385                                 continue;
386                         }
387                         goto doit;
388
389                 case ',':
390                         if (brclev)
391                                 continue;
392 doit:
393                         savec = *pm;
394                         *pm = 0;
395                         strcpy(lm, pl);
396                         strcat(restbuf, pe + 1);
397                         *pm = savec;
398                         if (s == 0) {
399                                 spathp = pathp;
400                                 expsh(restbuf);
401                                 pathp = spathp;
402                                 *pathp = 0;
403                         } else if (amatch(s, restbuf))
404                                 return (1);
405                         sort();
406                         pl = pm + 1;
407                         continue;
408
409                 case '[':
410                         for (pm++; *pm && *pm != ']'; pm++)
411                                 continue;
412                         if (!*pm)
413                                 yyerror("Missing ']'");
414                         continue;
415                 }
416         return (0);
417 }
418
419 static int
420 match(s, p)
421         char *s, *p;
422 {
423         register int c;
424         register char *sentp;
425         char sexpany = expany;
426
427         if (*s == '.' && *p != '.')
428                 return (0);
429         sentp = entp;
430         entp = s;
431         c = amatch(s, p);
432         entp = sentp;
433         expany = sexpany;
434         return (c);
435 }
436
437 static int
438 amatch(s, p)
439         register char *s, *p;
440 {
441         register int scc;
442         int ok, lc;
443         char *spathp;
444         struct stat stb;
445         int c, cc;
446
447         expany = 1;
448         for (;;) {
449                 scc = *s++ & TRIM;
450                 switch (c = *p++) {
451
452                 case '{':
453                         return (execbrc(p - 1, s - 1));
454
455                 case '[':
456                         ok = 0;
457                         lc = 077777;
458                         while ((cc = *p++)) {
459                                 if (cc == ']') {
460                                         if (ok)
461                                                 break;
462                                         return (0);
463                                 }
464                                 if (cc == '-') {
465                                         if (lc <= scc && scc <= *p++)
466                                                 ok++;
467                                 } else
468                                         if (scc == (lc = cc))
469                                                 ok++;
470                         }
471                         if (cc == 0) {
472                                 yyerror("Missing ']'");
473                                 return (0);
474                         }
475                         continue;
476
477                 case '*':
478                         if (!*p)
479                                 return (1);
480                         if (*p == '/') {
481                                 p++;
482                                 goto slash;
483                         }
484                         for (s--; *s; s++)
485                                 if (amatch(s, p))
486                                         return (1);
487                         return (0);
488
489                 case '\0':
490                         return (scc == '\0');
491
492                 default:
493                         if ((c & TRIM) != scc)
494                                 return (0);
495                         continue;
496
497                 case '?':
498                         if (scc == '\0')
499                                 return (0);
500                         continue;
501
502                 case '/':
503                         if (scc)
504                                 return (0);
505 slash:
506                         s = entp;
507                         spathp = pathp;
508                         while (*s)
509                                 addpath(*s++);
510                         addpath('/');
511                         if (stat(path, &stb) == 0 && ISDIR(stb.st_mode)) {
512                                 if (*p == '\0') {
513                                         if (which & E_TILDE)
514                                                 Cat(path, "");
515                                         else
516                                                 Cat(tilde, tpathp);
517                                 } else
518                                         expsh(p);
519                         }
520                         pathp = spathp;
521                         *pathp = '\0';
522                         return (0);
523                 }
524         }
525 }
526
527 static int
528 smatch(s, p)
529         register char *s, *p;
530 {
531         register int scc;
532         int ok, lc;
533         int c, cc;
534
535         for (;;) {
536                 scc = *s++ & TRIM;
537                 switch (c = *p++) {
538
539                 case '[':
540                         ok = 0;
541                         lc = 077777;
542                         while ((cc = *p++)) {
543                                 if (cc == ']') {
544                                         if (ok)
545                                                 break;
546                                         return (0);
547                                 }
548                                 if (cc == '-') {
549                                         if (lc <= scc && scc <= *p++)
550                                                 ok++;
551                                 } else
552                                         if (scc == (lc = cc))
553                                                 ok++;
554                         }
555                         if (cc == 0) {
556                                 yyerror("Missing ']'");
557                                 return (0);
558                         }
559                         continue;
560
561                 case '*':
562                         if (!*p)
563                                 return (1);
564                         for (s--; *s; s++)
565                                 if (smatch(s, p))
566                                         return (1);
567                         return (0);
568
569                 case '\0':
570                         return (scc == '\0');
571
572                 default:
573                         if ((c & TRIM) != scc)
574                                 return (0);
575                         continue;
576
577                 case '?':
578                         if (scc == 0)
579                                 return (0);
580                         continue;
581
582                 }
583         }
584 }
585
586 static void
587 Cat(s1, s2)
588         register char *s1, *s2;
589 {
590         int len = strlen(s1) + strlen(s2) + 1;
591         register char *s;
592
593         nleft -= len;
594         if (nleft <= 0 || ++eargc >= GAVSIZ)
595                 yyerror("Arguments too long");
596         eargv[eargc] = 0;
597         eargv[eargc - 1] = s = malloc(len);
598         if (s == NULL)
599                 fatal("ran out of memory\n");
600         while ((*s++ = *s1++ & TRIM))
601                 ;
602         s--;
603         while ((*s++ = *s2++ & TRIM))
604                 ;
605 }
606
607 static void
608 addpath(c)
609         int c;
610 {
611
612         if (pathp >= lastpathp)
613                 yyerror("Pathname too long");
614         else {
615                 *pathp++ = c & TRIM;
616                 *pathp = '\0';
617         }
618 }
619
620 /*
621  * Expand file names beginning with `~' into the
622  * user's home directory path name. Return a pointer in buf to the
623  * part corresponding to `file'.
624  */
625 char *
626 exptilde(buf, file, maxlen)
627         char buf[];
628         register char *file;
629         int maxlen;
630 {
631         register char *s1, *s2, *s3;
632         extern char homedir[];
633
634         if (strlen(file) >= maxlen)
635            return(NULL);
636         if (*file != '~') {
637                 strcpy(buf, file);
638                 return(buf);
639         }
640         if (*++file == '\0') {
641                 s2 = homedir;
642                 s3 = NULL;
643         } else if (*file == '/') {
644                 s2 = homedir;
645                 s3 = file;
646         } else {
647                 s3 = file;
648                 while (*s3 && *s3 != '/')
649                         s3++;
650                 if (*s3 == '/')
651                         *s3 = '\0';
652                 else
653                         s3 = NULL;
654                 if (pw == NULL || strcmp(pw->pw_name, file) != 0) {
655                         if ((pw = getpwnam(file)) == NULL) {
656                                 error("%s: unknown user name\n", file);
657                                 if (s3 != NULL)
658                                         *s3 = '/';
659                                 return(NULL);
660                         }
661                 }
662                 if (s3 != NULL)
663                         *s3 = '/';
664                 s2 = pw->pw_dir;
665         }
666         for (s1 = buf; (*s1++ = *s2++) && s1 < buf+maxlen; )
667                 ;
668         s2 = --s1;
669         if (s3 != NULL && s1 < buf+maxlen) {
670                 s2++;
671                 while ((*s1++ = *s3++) && s1 < buf+maxlen)
672                         ;
673         }
674         if (s1 == buf+maxlen)
675                 return(NULL);
676         return(s2);
677 }