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