home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / bin / sh / expand.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-04-15  |  21.6 KB  |  1,105 lines

  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
  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
  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
  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
  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.         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 *
  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
  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
  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.         syntax = quoted? DQSYNTAX : BASESYNTAX;
  503.         for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
  504.             /* should insert CTLESC characters */
  505.             while (*p) {
  506.                 if (syntax[*p] == CCTL)
  507.                     STPUTC(CTLESC, expdest);
  508.                 STPUTC(*p++, expdest);
  509.             }
  510.             if (*ap)
  511.                 STPUTC(sep, expdest);
  512.         }
  513.         break;
  514.     case '0':
  515.         p = arg0;
  516. string:
  517.         syntax = quoted? DQSYNTAX : BASESYNTAX;
  518.         while (*p) {
  519.             if (syntax[*p] == CCTL)
  520.                 STPUTC(CTLESC, expdest);
  521.             STPUTC(*p++, expdest);
  522.         }
  523.         break;
  524.     default:
  525.         if ((unsigned)(name -= '1') <= '9' - '1') {
  526.             p = shellparam.p[name];
  527.             goto string;
  528.         }
  529.         break;
  530.     }
  531. }
  532.  
  533.  
  534.  
  535. /*
  536.  * Record the the fact that we have to scan this region of the
  537.  * string for IFS characters.
  538.  */
  539.  
  540. STATIC void
  541. recordregion(start, end, nulonly) {
  542.     register struct ifsregion *ifsp;
  543.  
  544.     if (ifslastp == NULL) {
  545.         ifsp = &ifsfirst;
  546.     } else {
  547.         ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
  548.         ifslastp->next = ifsp;
  549.     }
  550.     ifslastp = ifsp;
  551.     ifslastp->next = NULL;
  552.     ifslastp->begoff = start;
  553.     ifslastp->endoff = end;
  554.     ifslastp->nulonly = nulonly;
  555. }
  556.  
  557.  
  558.  
  559. /*
  560.  * Break the argument string into pieces based upon IFS and add the
  561.  * strings to the argument list.  The regions of the string to be
  562.  * searched for IFS characters have been stored by recordregion.
  563.  */
  564.  
  565. STATIC void
  566. ifsbreakup(string, arglist)
  567.     char *string;
  568.     struct arglist *arglist;
  569.     {
  570.     struct ifsregion *ifsp;
  571.     struct strlist *sp;
  572.     char *start;
  573.     register char *p;
  574.     char *q;
  575.     char *ifs;
  576.  
  577.     start = string;
  578.     if (ifslastp != NULL) {
  579.         ifsp = &ifsfirst;
  580.         do {
  581.             p = string + ifsp->begoff;
  582.             ifs = ifsp->nulonly? nullstr : ifsval();
  583.             while (p < string + ifsp->endoff) {
  584.                 q = p;
  585.                 if (*p == CTLESC)
  586.                     p++;
  587.                 if (strchr(ifs, *p++)) {
  588.                     if (q > start || *ifs != ' ') {
  589.                         *q = '\0';
  590.                         sp = (struct strlist *)stalloc(sizeof *sp);
  591.                         sp->text = start;
  592.                         *arglist->lastp = sp;
  593.                         arglist->lastp = &sp->next;
  594.                     }
  595.                     if (*ifs == ' ') {
  596.                         for (;;) {
  597.                             if (p >= string + ifsp->endoff)
  598.                                 break;
  599.                             q = p;
  600.                             if (*p == CTLESC)
  601.                                 p++;
  602.                             if (strchr(ifs, *p++) == NULL) {
  603.                                 p = q;
  604.                                 break;
  605.                             }
  606.                         }
  607.                     }
  608.                     start = p;
  609.                 }
  610.             }
  611.         } while ((ifsp = ifsp->next) != NULL);
  612.         if (*start || (*ifs != ' ' && start > string)) {
  613.             sp = (struct strlist *)stalloc(sizeof *sp);
  614.             sp->text = start;
  615.             *arglist->lastp = sp;
  616.             arglist->lastp = &sp->next;
  617.         }
  618.     } else {
  619.         sp = (struct strlist *)stalloc(sizeof *sp);
  620.         sp->text = start;
  621.         *arglist->lastp = sp;
  622.         arglist->lastp = &sp->next;
  623.     }
  624. }
  625.  
  626.  
  627.  
  628. /*
  629.  * Expand shell metacharacters.  At this point, the only control characters
  630.  * should be escapes.  The results are stored in the list exparg.
  631.  */
  632.  
  633. char *expdir;
  634.  
  635.  
  636. STATIC void
  637. expandmeta(str)
  638.     struct strlist *str;
  639.     {
  640.     char *p;
  641.     struct strlist **savelastp;
  642.     struct strlist *sp;
  643.     char c;
  644.  
  645.     while (str) {
  646.         if (fflag)
  647.             goto nometa;
  648.         p = str->text;
  649. #if UDIR
  650.         if (p[0] == '/' && p[1] == 'u' && p[2] == '/')
  651.             str->text = p = expudir(p);
  652. #endif
  653.         for (;;) {            /* fast check for meta chars */
  654.             if ((c = *p++) == '\0')
  655.                 goto nometa;
  656.             if (c == '*' || c == '?' || c == '[' || c == '!')
  657.                 break;
  658.         }
  659.         savelastp = exparg.lastp;
  660.         INTOFF;
  661.         if (expdir == NULL)
  662.             expdir = ckmalloc(1024); /* I hope this is big enough */
  663.         expmeta(expdir, str->text);
  664.         ckfree(expdir);
  665.         expdir = NULL;
  666.         INTON;
  667.         if (exparg.lastp == savelastp) {
  668.             if (! zflag) {
  669. nometa:
  670.                 *exparg.lastp = str;
  671.                 rmescapes(str->text);
  672.                 exparg.lastp = &str->next;
  673.             }
  674.         } else {
  675.             *exparg.lastp = NULL;
  676.             *savelastp = sp = expsort(*savelastp);
  677.             while (sp->next != NULL)
  678.                 sp = sp->next;
  679.             exparg.lastp = &sp->next;
  680.         }
  681.         str = str->next;
  682.     }
  683. }
  684.  
  685.  
  686. #if UDIR
  687. /*
  688.  * Expand /u/username into the home directory for the specified user.
  689.  * We could use the getpw stuff here, but then we would have to load
  690.  * in stdio and who knows what else.
  691.  */
  692.  
  693. #define MAXLOGNAME 32
  694. #define MAXPWLINE 128
  695.  
  696. char *pfgets();
  697.  
  698.  
  699. STATIC char *
  700. expudir(path)
  701.     char *path;
  702.     {
  703.     register char *p, *q, *r;
  704.     char name[MAXLOGNAME];
  705.     char line[MAXPWLINE];
  706.     int i;
  707.  
  708.     r = path;                /* result on failure */
  709.     p = r + 3;            /* the 3 skips "/u/" */
  710.     q = name;
  711.     while (*p && *p != '/') {
  712.         if (q >= name + MAXLOGNAME - 1)
  713.             return r;        /* fail, name too long */
  714.         *q++ = *p++;
  715.     }
  716.     *q = '\0';
  717.     setinputfile("/etc/passwd", 1);
  718.     q = line + strlen(name);
  719.     while (pfgets(line, MAXPWLINE) != NULL) {
  720.         if (line[0] == name[0] && prefix(name, line) && *q == ':') {
  721.             /* skip to start of home directory */
  722.             i = 4;
  723.             do {
  724.                 while (*++q && *q != ':');
  725.             } while (--i > 0);
  726.             if (*q == '\0')
  727.                 break;        /* fail, corrupted /etc/passwd */
  728.             q++;
  729.             for (r = q ; *r && *r != '\n' && *r != ':' ; r++);
  730.             *r = '\0';        /* nul terminate home directory */
  731.             i = r - q;        /* i = strlen(q) */
  732.             r = stalloc(i + strlen(p) + 1);
  733.             scopy(q, r);
  734.             scopy(p, r + i);
  735.             TRACE(("expudir converts %s to %s\n", path, r));
  736.             didudir = 1;
  737.             path = r;        /* succeed */
  738.             break;
  739.         }
  740.     }
  741.     popfile();
  742.     return r;
  743. }
  744. #endif
  745.  
  746.  
  747. /*
  748.  * Do metacharacter (i.e. *, ?, [...]) expansion.
  749.  */
  750.  
  751. STATIC void
  752. expmeta(enddir, name)
  753.     char *enddir;
  754.     char *name;
  755.     {
  756.     register char *p;
  757.     char *q;
  758.     char *start;
  759.     char *endname;
  760.     int metaflag;
  761.     struct stat statb;
  762.     DIR *dirp;
  763.     struct dirent *dp;
  764.     int atend;
  765.     int matchdot;
  766.  
  767.     metaflag = 0;
  768.     start = name;
  769.     for (p = name ; ; p++) {
  770.         if (*p == '*' || *p == '?')
  771.             metaflag = 1;
  772.         else if (*p == '[') {
  773.             q = p + 1;
  774.             if (*q == '!')
  775.                 q++;
  776.             for (;;) {
  777.                 if (*q == CTLESC)
  778.                     q++;
  779.                 if (*q == '/' || *q == '\0')
  780.                     break;
  781.                 if (*++q == ']') {
  782.                     metaflag = 1;
  783.                     break;
  784.                 }
  785.             }
  786.         } else if (*p == '!' && p[1] == '!'    && (p == name || p[-1] == '/')) {
  787.             metaflag = 1;
  788.         } else if (*p == '\0')
  789.             break;
  790.         else if (*p == CTLESC)
  791.             p++;
  792.         if (*p == '/') {
  793.             if (metaflag)
  794.                 break;
  795.             start = p + 1;
  796.         }
  797.     }
  798.     if (metaflag == 0) {    /* we've reached the end of the file name */
  799.         if (enddir != expdir)
  800.             metaflag++;
  801.         for (p = name ; ; p++) {
  802.             if (*p == CTLESC)
  803.                 p++;
  804.             *enddir++ = *p;
  805.             if (*p == '\0')
  806.                 break;
  807.         }
  808.         if (metaflag == 0 || stat(expdir, &statb) >= 0)
  809.             addfname(expdir);
  810.         return;
  811.     }
  812.     endname = p;
  813.     if (start != name) {
  814.         p = name;
  815.         while (p < start) {
  816.             if (*p == CTLESC)
  817.                 p++;
  818.             *enddir++ = *p++;
  819.         }
  820.     }
  821.     if (enddir == expdir) {
  822.         p = ".";
  823.     } else if (enddir == expdir + 1 && *expdir == '/') {
  824.         p = "/";
  825.     } else {
  826.         p = expdir;
  827.         enddir[-1] = '\0';
  828.     }
  829.     if ((dirp = opendir(p)) == NULL)
  830.         return;
  831.     if (enddir != expdir)
  832.         enddir[-1] = '/';
  833.     if (*endname == 0) {
  834.         atend = 1;
  835.     } else {
  836.         atend = 0;
  837.         *endname++ = '\0';
  838.     }
  839.     matchdot = 0;
  840.     if (start[0] == '.' || start[0] == CTLESC && start[1] == '.')
  841.         matchdot++;
  842.     while (! int_pending() && (dp = readdir(dirp)) != NULL) {
  843.         if (dp->d_name[0] == '.' && ! matchdot)
  844.             continue;
  845.         if (patmatch(start, dp->d_name)) {
  846.             if (atend) {
  847.                 scopy(dp->d_name, enddir);
  848.                 addfname(expdir);
  849.             } else {
  850.                 char *q;
  851.                 for (p = enddir, q = dp->d_name ; *p++ = *q++ ;);
  852.                 p[-1] = '/';
  853.                 expmeta(p, endname);
  854.             }
  855.         }
  856.     }
  857.     closedir(dirp);
  858.     if (! atend)
  859.         endname[-1] = '/';
  860. }
  861.  
  862.  
  863. /*
  864.  * Add a file name to the list.
  865.  */
  866.  
  867. STATIC void
  868. addfname(name)
  869.     char *name;
  870.     {
  871.     char *p;
  872.     struct strlist *sp;
  873.  
  874.     p = stalloc(strlen(name) + 1);
  875.     scopy(name, p);
  876.     sp = (struct strlist *)stalloc(sizeof *sp);
  877.     sp->text = p;
  878.     *exparg.lastp = sp;
  879.     exparg.lastp = &sp->next;
  880. }
  881.  
  882.  
  883. /*
  884.  * Sort the results of file name expansion.  It calculates the number of
  885.  * strings to sort and then calls msort (short for merge sort) to do the
  886.  * work.
  887.  */
  888.  
  889. STATIC struct strlist *
  890. expsort(str)
  891.     struct strlist *str;
  892.     {
  893.     int len;
  894.     struct strlist *sp;
  895.  
  896.     len = 0;
  897.     for (sp = str ; sp ; sp = sp->next)
  898.         len++;
  899.     return msort(str, len);
  900. }
  901.  
  902.  
  903. STATIC struct strlist *
  904. msort(list, len)
  905.     struct strlist *list;
  906.     {
  907.     struct strlist *p, *q;
  908.     struct strlist **lpp;
  909.     int half;
  910.     int n;
  911.  
  912.     if (len <= 1)
  913.         return list;
  914.     half = len >> 1;      
  915.     p = list;
  916.     for (n = half ; --n >= 0 ; ) {
  917.         q = p;
  918.         p = p->next;
  919.     }
  920.     q->next = NULL;            /* terminate first half of list */
  921.     q = msort(list, half);        /* sort first half of list */
  922.     p = msort(p, len - half);        /* sort second half */
  923.     lpp = &list;
  924.     for (;;) {
  925.         if (strcmp(p->text, q->text) < 0) {
  926.             *lpp = p;
  927.             lpp = &p->next;
  928.             if ((p = *lpp) == NULL) {
  929.                 *lpp = q;
  930.                 break;
  931.             }
  932.         } else {
  933.             *lpp = q;
  934.             lpp = &q->next;
  935.             if ((q = *lpp) == NULL) {
  936.                 *lpp = p;
  937.                 break;
  938.             }
  939.         }
  940.     }
  941.     return list;
  942. }
  943.  
  944.  
  945.  
  946. /*
  947.  * Returns true if the pattern matches the string.
  948.  */
  949.  
  950. int
  951. patmatch(pattern, string)
  952.     char *pattern;
  953.     char *string;
  954.     {
  955.     if (pattern[0] == '!' && pattern[1] == '!')
  956.         return 1 - pmatch(pattern + 2, string);
  957.     else
  958.         return pmatch(pattern, string);
  959. }
  960.  
  961.  
  962. STATIC int
  963. pmatch(pattern, string)
  964.     char *pattern;
  965.     char *string;
  966.     {
  967.     register char *p, *q;
  968.     register char c;
  969.  
  970.     p = pattern;
  971.     q = string;
  972.     for (;;) {
  973.         switch (c = *p++) {
  974.         case '\0':
  975.             goto breakloop;
  976.         case CTLESC:
  977.             if (*q++ != *p++)
  978.                 return 0;
  979.             break;
  980.         case '?':
  981.             if (*q++ == '\0')
  982.                 return 0;
  983.             break;
  984.         case '*':
  985.             c = *p;
  986.             if (c != CTLESC && c != '?' && c != '*' && c != '[') {
  987.                 while (*q != c) {
  988.                     if (*q == '\0')
  989.                         return 0;
  990.                     q++;
  991.                 }
  992.             }
  993.             do {
  994.                 if (pmatch(p, q))
  995.                     return 1;
  996.             } while (*q++ != '\0');
  997.             return 0;
  998.         case '[': {
  999.             char *endp;
  1000.             int invert, found;
  1001.             char chr;
  1002.  
  1003.             endp = p;
  1004.             if (*endp == '!')
  1005.                 endp++;
  1006.             for (;;) {
  1007.                 if (*endp == '\0')
  1008.                     goto dft;        /* no matching ] */
  1009.                 if (*endp == CTLESC)
  1010.                     endp++;
  1011.                 if (*++endp == ']')
  1012.                     break;
  1013.             }
  1014.             invert = 0;
  1015.             if (*p == '!') {
  1016.                 invert++;
  1017.                 p++;
  1018.             }
  1019.             found = 0;
  1020.             chr = *q++;
  1021.             c = *p++;
  1022.             do {
  1023.                 if (c == CTLESC)
  1024.                     c = *p++;
  1025.                 if (*p == '-' && p[1] != ']') {
  1026.                     p++;
  1027.                     if (*p == CTLESC)
  1028.                         p++;
  1029.                     if (chr >= c && chr <= *p)
  1030.                         found = 1;
  1031.                     p++;
  1032.                 } else {
  1033.                     if (chr == c)
  1034.                         found = 1;
  1035.                 }
  1036.             } while ((c = *p++) != ']');
  1037.             if (found == invert)
  1038.                 return 0;
  1039.             break;
  1040.         }
  1041. dft:        default:
  1042.             if (*q++ != c)
  1043.                 return 0;
  1044.             break;
  1045.         }
  1046.     }
  1047. breakloop:
  1048.     if (*q != '\0')
  1049.         return 0;
  1050.     return 1;
  1051. }
  1052.  
  1053.  
  1054.  
  1055. /*
  1056.  * Remove any CTLESC characters from a string.
  1057.  */
  1058.  
  1059. void
  1060. rmescapes(str)
  1061.     char *str;
  1062.     {
  1063.     register char *p, *q;
  1064.  
  1065.     p = str;
  1066.     while (*p != CTLESC) {
  1067.         if (*p++ == '\0')
  1068.             return;
  1069.     }
  1070.     q = p;
  1071.     while (*p) {
  1072.         if (*p == CTLESC)
  1073.             p++;
  1074.         *q++ = *p++;
  1075.     }
  1076.     *q = '\0';
  1077. }
  1078.  
  1079.  
  1080.  
  1081. /*
  1082.  * See if a pattern matches in a case statement.
  1083.  */
  1084.  
  1085. int
  1086. casematch(pattern, val)
  1087.     union node *pattern;
  1088.     char *val;
  1089.     {
  1090.     struct stackmark smark;
  1091.     int result;
  1092.     char *p;
  1093.  
  1094.     setstackmark(&smark);
  1095.     argbackq = pattern->narg.backquote;
  1096.     STARTSTACKSTR(expdest);
  1097.     ifslastp = NULL;
  1098.     argstr(pattern->narg.text, 0);
  1099.     STPUTC('\0', expdest);
  1100.     p = grabstackstr(expdest);
  1101.     result = patmatch(p, val);
  1102.     popstackmark(&smark);
  1103.     return result;
  1104. }
  1105.