check for "<<>>" etc as equivalent to "<>"
[unix-history] / usr / src / usr.sbin / sendmail / src / parseaddr.c
index a4e2d25..aa32d1a 100644 (file)
@@ -1,13 +1,13 @@
 /*
  * Copyright (c) 1983 Eric P. Allman
 /*
  * Copyright (c) 1983 Eric P. Allman
- * Copyright (c) 1988 Regents of the University of California.
- * All rights reserved.
+ * Copyright (c) 1988, 1993
+ *     The Regents of the University of California.  All rights reserved.
  *
  * %sccs.include.redist.c%
  */
 
 #ifndef lint
  *
  * %sccs.include.redist.c%
  */
 
 #ifndef lint
-static char sccsid[] = "@(#)parseaddr.c        6.14 (Berkeley) %G%";
+static char sccsid[] = "@(#)parseaddr.c        8.40 (Berkeley) %G%";
 #endif /* not lint */
 
 #include "sendmail.h"
 #endif /* not lint */
 
 #include "sendmail.h"
@@ -42,16 +42,12 @@ char        *DelimChar;             /* set to point to the delimiter */
 **             addr -- the address to parse.
 **             a -- a pointer to the address descriptor buffer.
 **                     If NULL, a header will be created.
 **             addr -- the address to parse.
 **             a -- a pointer to the address descriptor buffer.
 **                     If NULL, a header will be created.
-**             copyf -- determines what shall be copied:
-**                     -1 -- don't copy anything.  The printname
-**                             (q_paddr) is just addr, and the
-**                             user & host are allocated internally
-**                             to parse.
-**                     0 -- copy out the parsed user & host, but
-**                             don't copy the printname.
-**                     +1 -- copy everything.
+**             flags -- describe detail for parsing.  See RF_ definitions
+**                     in sendmail.h.
 **             delim -- the character to terminate the address, passed
 **                     to prescan.
 **             delim -- the character to terminate the address, passed
 **                     to prescan.
+**             delimptr -- if non-NULL, set to the location of the
+**                     delim character that was found.
 **             e -- the envelope that will contain this address.
 **
 **     Returns:
 **             e -- the envelope that will contain this address.
 **
 **     Returns:
@@ -64,17 +60,20 @@ char        *DelimChar;             /* set to point to the delimiter */
 */
 
 /* following delimiters are inherent to the internal algorithms */
 */
 
 /* following delimiters are inherent to the internal algorithms */
-# define DELIMCHARS    "\001()<>,;\\\"\r\n"    /* word delimiters */
+# define DELIMCHARS    "()<>,;\r\n"    /* default word delimiters */
 
 ADDRESS *
 
 ADDRESS *
-parseaddr(addr, a, copyf, delim, e)
+parseaddr(addr, a, flags, delim, delimptr, e)
        char *addr;
        register ADDRESS *a;
        char *addr;
        register ADDRESS *a;
-       int copyf;
-       char delim;
+       int flags;
+       int delim;
+       char **delimptr;
        register ENVELOPE *e;
 {
        register char **pvp;
        register ENVELOPE *e;
 {
        register char **pvp;
+       auto char *delimptrbuf;
+       bool queueup;
        char pvpbuf[PSBUFSIZE];
 
        /*
        char pvpbuf[PSBUFSIZE];
 
        /*
@@ -85,13 +84,6 @@ parseaddr(addr, a, copyf, delim, e)
        if (tTd(20, 1))
                printf("\n--parseaddr(%s)\n", addr);
 
        if (tTd(20, 1))
                printf("\n--parseaddr(%s)\n", addr);
 
-       if (invalidaddr(addr))
-       {
-               if (tTd(20, 1))
-                       printf("parseaddr-->bad address\n");
-               return NULL;
-       }
-
        {
                extern char *DelimChar;         /* parseaddr.c */
                char savec;
        {
                extern char *DelimChar;         /* parseaddr.c */
                char savec;
@@ -108,7 +100,10 @@ parseaddr(addr, a, copyf, delim, e)
                        return (NULL);
        }
 
                        return (NULL);
        }
 
-       pvp = prescan(addr, delim, pvpbuf);
+       if (delimptr == NULL)
+               delimptr = &delimptrbuf;
+
+       pvp = prescan(addr, delim, pvpbuf, sizeof pvpbuf, delimptr);
        if (pvp == NULL)
        {
                if (tTd(20, 1))
        if (pvp == NULL)
        {
                if (tTd(20, 1))
@@ -116,39 +111,74 @@ parseaddr(addr, a, copyf, delim, e)
                return (NULL);
        }
 
                return (NULL);
        }
 
+       if (invalidaddr(addr, delim == '\0' ? NULL : *delimptr))
+       {
+               if (tTd(20, 1))
+                       printf("parseaddr-->bad address\n");
+               return NULL;
+       }
+
        /*
        /*
-       **  Apply rewriting rules.
-       **      Ruleset 0 does basic parsing.  It must resolve.
+       **  Save addr if we are going to have to.
+       **
+       **      We have to do this early because there is a chance that
+       **      the map lookups in the rewriting rules could clobber
+       **      static memory somewhere.
        */
 
        */
 
-       rewrite(pvp, 3);
-       rewrite(pvp, 0);
+       if (bitset(RF_COPYPADDR, flags) && addr != NULL)
+       {
+               char savec = **delimptr;
+
+               if (savec != '\0')
+                       **delimptr = '\0';
+               e->e_to = addr = newstr(addr);
+               if (savec != '\0')
+                       **delimptr = savec;
+       }
 
        /*
 
        /*
-       **  See if we resolved to a real mailer.
+       **  Apply rewriting rules.
+       **      Ruleset 0 does basic parsing.  It must resolve.
        */
 
        */
 
-       if (pvp[0][0] != CANONNET)
-       {
-               setstat(EX_USAGE);
-               usrerr("cannot resolve name");
-               return (NULL);
-       }
+       queueup = FALSE;
+       if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
+               queueup = TRUE;
+       if (rewrite(pvp, 0, 0, e) == EX_TEMPFAIL)
+               queueup = TRUE;
+
 
        /*
        **  Build canonical address from pvp.
        */
 
 
        /*
        **  Build canonical address from pvp.
        */
 
-       a = buildaddr(pvp, a);
-       if (a == NULL)
-               return (NULL);
+       a = buildaddr(pvp, a, flags, e);
 
        /*
        **  Make local copies of the host & user and then
        **  transport them out.
        */
 
 
        /*
        **  Make local copies of the host & user and then
        **  transport them out.
        */
 
-       allocaddr(a, copyf, addr);
+       allocaddr(a, flags, addr);
+       if (bitset(QBADADDR, a->q_flags))
+               return a;
+
+       /*
+       **  If there was a parsing failure, mark it for queueing.
+       */
+
+       if (queueup)
+       {
+               char *msg = "Transient parse error -- message queued for future delivery";
+
+               if (tTd(20, 1))
+                       printf("parseaddr: queuing message\n");
+               message(msg);
+               if (e->e_message == NULL)
+                       e->e_message = newstr(msg);
+               a->q_flags |= QQUEUEUP;
+       }
 
        /*
        **  Compute return value.
 
        /*
        **  Compute return value.
@@ -174,19 +204,43 @@ parseaddr(addr, a, copyf, delim, e)
 */
 
 bool
 */
 
 bool
-invalidaddr(addr)
+invalidaddr(addr, delimptr)
        register char *addr;
        register char *addr;
+       char *delimptr;
 {
 {
+       char savedelim;
+
+       if (delimptr != NULL)
+       {
+               savedelim = *delimptr;
+               if (savedelim != '\0')
+                       *delimptr = '\0';
+       }
+#if 0
+       /* for testing.... */
+       if (strcmp(addr, "INvalidADDR") == 0)
+       {
+               usrerr("553 INvalid ADDRess");
+               goto addrfailure;
+       }
+#endif
        for (; *addr != '\0'; addr++)
        {
        for (; *addr != '\0'; addr++)
        {
-               if (!isascii((int) *addr & 0377) ||
-                   !iscntrl(*addr) || isspace(*addr))
-                       continue;
-               setstat(EX_USAGE);
-               usrerr("Address contained invalid control characters");
-               return TRUE;
+               if ((*addr & 0340) == 0200)
+                       break;
+       }
+       if (*addr == '\0')
+       {
+               if (savedelim != '\0' && delimptr != NULL)
+                       *delimptr = savedelim;
+               return FALSE;
        }
        }
-       return FALSE;
+       setstat(EX_USAGE);
+       usrerr("553 Address contained invalid control characters");
+  addrfailure:
+       if (savedelim != '\0' && delimptr != NULL)
+               *delimptr = savedelim;
+       return TRUE;
 }
 \f/*
 **  ALLOCADDR -- do local allocations of address on demand.
 }
 \f/*
 **  ALLOCADDR -- do local allocations of address on demand.
@@ -195,7 +249,8 @@ invalidaddr(addr)
 **
 **     Parameters:
 **             a -- the address to reallocate.
 **
 **     Parameters:
 **             a -- the address to reallocate.
-**             copyf -- the copy flag (see parseaddr for description).
+**             flags -- the copy flag (see RF_ definitions in sendmail.h
+**                     for a description).
 **             paddr -- the printname of the address.
 **
 **     Returns:
 **             paddr -- the printname of the address.
 **
 **     Returns:
@@ -205,30 +260,22 @@ invalidaddr(addr)
 **             Copies portions of a into local buffers as requested.
 */
 
 **             Copies portions of a into local buffers as requested.
 */
 
-allocaddr(a, copyf, paddr)
+allocaddr(a, flags, paddr)
        register ADDRESS *a;
        register ADDRESS *a;
-       int copyf;
+       int flags;
        char *paddr;
 {
        char *paddr;
 {
-       register MAILER *m = a->q_mailer;
+       if (tTd(24, 4))
+               printf("allocaddr(flags=%x, paddr=%s)\n", flags, paddr);
 
 
-       if (copyf > 0 && paddr != NULL)
-       {
-               char savec = *DelimChar;
-
-               *DelimChar = '\0';
-               a->q_paddr = newstr(paddr);
-               *DelimChar = savec;
-       }
-       else
-               a->q_paddr = paddr;
+       a->q_paddr = paddr;
 
        if (a->q_user == NULL)
                a->q_user = "";
        if (a->q_host == NULL)
                a->q_host = "";
 
 
        if (a->q_user == NULL)
                a->q_user = "";
        if (a->q_host == NULL)
                a->q_host = "";
 
-       if (copyf >= 0)
+       if (bitset(RF_COPYPARSE, flags))
        {
                a->q_host = newstr(a->q_host);
                if (a->q_user != a->q_paddr)
        {
                a->q_host = newstr(a->q_host);
                if (a->q_user != a->q_paddr)
@@ -237,36 +284,6 @@ allocaddr(a, copyf, paddr)
 
        if (a->q_paddr == NULL)
                a->q_paddr = a->q_user;
 
        if (a->q_paddr == NULL)
                a->q_paddr = a->q_user;
-
-       /*
-       **  Convert host name to lower case if requested.
-       **      User name will be done later.
-       */
-
-       if (!bitnset(M_HST_UPPER, m->m_flags))
-               makelower(a->q_host);
-}
-\f/*
-**  LOWERADDR -- map UPPER->lower case on addresses as requested.
-**
-**     Parameters:
-**             a -- address to be mapped.
-**
-**     Returns:
-**             none.
-**
-**     Side Effects:
-**             none.
-*/
-
-void
-loweraddr(a)
-       register ADDRESS *a;
-{
-       register MAILER *m = a->q_mailer;
-
-       if (!bitnset(M_USR_UPPER, m->m_flags))
-               makelower(a->q_user);
 }
 \f/*
 **  INVALIDADDR -- check an address string for invalid control characters.
 }
 \f/*
 **  INVALIDADDR -- check an address string for invalid control characters.
@@ -330,13 +347,13 @@ invalidaddr(addr)
 **                     If '\t' then we are reading the .cf file.
 **             pvpbuf -- place to put the saved text -- note that
 **                     the pointers are static.
 **                     If '\t' then we are reading the .cf file.
 **             pvpbuf -- place to put the saved text -- note that
 **                     the pointers are static.
+**             pvpbsize -- size of pvpbuf.
+**             delimptr -- if non-NULL, set to the location of the
+**                     terminating delimiter.
 **
 **     Returns:
 **             A pointer to a vector of tokens.
 **             NULL on error.
 **
 **     Returns:
 **             A pointer to a vector of tokens.
 **             NULL on error.
-**
-**     Side Effects:
-**             sets DelimChar to point to the character matching 'delim'.
 */
 
 /* states and character types */
 */
 
 /* states and character types */
@@ -364,13 +381,38 @@ static short StateTab[NSTATES][NSTATES] =
        /*ONE*/         OPR,    OPR,    OPR,    OPR,    OPR,
 };
 
        /*ONE*/         OPR,    OPR,    OPR,    OPR,    OPR,
 };
 
+/* token type table -- it gets modified with $o characters */
+static TokTypeTab[256] =
+{
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM,ATM,SPC,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
+       OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+       ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
+};
+
+#define toktype(c)     ((int) TokTypeTab[(c) & 0xff])
+
+
 # define NOCHAR                -1      /* signal nothing in lookahead token */
 
 char **
 # define NOCHAR                -1      /* signal nothing in lookahead token */
 
 char **
-prescan(addr, delim, pvpbuf)
+prescan(addr, delim, pvpbuf, pvpbsize, delimptr)
        char *addr;
        char delim;
        char pvpbuf[];
        char *addr;
        char delim;
        char pvpbuf[];
+       char **delimptr;
 {
        register char *p;
        register char *q;
 {
        register char *p;
        register char *q;
@@ -382,7 +424,24 @@ prescan(addr, delim, pvpbuf)
        char *tok;
        int state;
        int newstate;
        char *tok;
        int state;
        int newstate;
+       char *saveto = CurEnv->e_to;
        static char *av[MAXATOM+1];
        static char *av[MAXATOM+1];
+       static char firsttime = TRUE;
+
+       if (firsttime)
+       {
+               /* initialize the token type table */
+               char obuf[50];
+
+               firsttime = FALSE;
+               expand("\201o", obuf, &obuf[sizeof obuf - sizeof DELIMCHARS], CurEnv);
+               strcat(obuf, DELIMCHARS);
+               for (p = obuf; *p != '\0'; p++)
+               {
+                       if (TokTypeTab[*p & 0xff] == ATM)
+                               TokTypeTab[*p & 0xff] = OPR;
+               }
+       }
 
        /* make sure error messages don't have garbage on them */
        errno = 0;
 
        /* make sure error messages don't have garbage on them */
        errno = 0;
@@ -395,6 +454,7 @@ prescan(addr, delim, pvpbuf)
        state = ATM;
        c = NOCHAR;
        p = addr;
        state = ATM;
        c = NOCHAR;
        p = addr;
+       CurEnv->e_to = p;
        if (tTd(22, 11))
        {
                printf("prescan: ");
        if (tTd(22, 11))
        {
                printf("prescan: ");
@@ -409,13 +469,16 @@ prescan(addr, delim, pvpbuf)
                for (;;)
                {
                        /* store away any old lookahead character */
                for (;;)
                {
                        /* store away any old lookahead character */
-                       if (c != NOCHAR)
+                       if (c != NOCHAR && !bslashmode)
                        {
                                /* see if there is room */
                        {
                                /* see if there is room */
-                               if (q >= &pvpbuf[PSBUFSIZE - 5])
+                               if (q >= &pvpbuf[pvpbsize - 5])
                                {
                                {
-                                       usrerr("Address too long");
-                                       DelimChar = p;
+                                       usrerr("553 Address too long");
+       returnnull:
+                                       if (delimptr != NULL)
+                                               *delimptr = p;
+                                       CurEnv->e_to = saveto;
                                        return (NULL);
                                }
 
                                        return (NULL);
                                }
 
@@ -430,18 +493,18 @@ prescan(addr, delim, pvpbuf)
                                /* diagnose and patch up bad syntax */
                                if (state == QST)
                                {
                                /* diagnose and patch up bad syntax */
                                if (state == QST)
                                {
-                                       usrerr("Unbalanced '\"'");
+                                       usrerr("653 Unbalanced '\"'");
                                        c = '"';
                                }
                                else if (cmntcnt > 0)
                                {
                                        c = '"';
                                }
                                else if (cmntcnt > 0)
                                {
-                                       usrerr("Unbalanced '('");
+                                       usrerr("653 Unbalanced '('");
                                        c = ')';
                                }
                                else if (anglecnt > 0)
                                {
                                        c = '>';
                                        c = ')';
                                }
                                else if (anglecnt > 0)
                                {
                                        c = '>';
-                                       usrerr("Unbalanced '<'");
+                                       usrerr("653 Unbalanced '<'");
                                }
                                else
                                        break;
                                }
                                else
                                        break;
@@ -459,20 +522,24 @@ prescan(addr, delim, pvpbuf)
                        *q = '\0';
                        if (bslashmode)
                        {
                        *q = '\0';
                        if (bslashmode)
                        {
-                               /* kludge \! for naive users */
-                               if (c != '!')
-                                       *q++ = '\\';
                                bslashmode = FALSE;
                                bslashmode = FALSE;
+
+                               /* kludge \! for naive users */
                                if (cmntcnt > 0)
                                if (cmntcnt > 0)
+                               {
                                        c = NOCHAR;
                                        c = NOCHAR;
-                               continue;
+                                       continue;
+                               }
+                               else if (c != '!' || state == QST)
+                               {
+                                       *q++ = '\\';
+                                       continue;
+                               }
                        }
 
                        if (c == '\\')
                        {
                                bslashmode = TRUE;
                        }
 
                        if (c == '\\')
                        {
                                bslashmode = TRUE;
-                               c = NOCHAR;
-                               continue;
                        }
                        if (state == QST)
                        {
                        }
                        if (state == QST)
                        {
@@ -487,9 +554,8 @@ prescan(addr, delim, pvpbuf)
                        {
                                if (cmntcnt <= 0)
                                {
                        {
                                if (cmntcnt <= 0)
                                {
-                                       usrerr("Unbalanced ')'");
-                                       DelimChar = p;
-                                       return (NULL);
+                                       usrerr("653 Unbalanced ')'");
+                                       c = NOCHAR;
                                }
                                else
                                        cmntcnt--;
                                }
                                else
                                        cmntcnt--;
@@ -502,13 +568,13 @@ prescan(addr, delim, pvpbuf)
                        {
                                if (anglecnt <= 0)
                                {
                        {
                                if (anglecnt <= 0)
                                {
-                                       usrerr("Unbalanced '>'");
-                                       DelimChar = p;
-                                       return (NULL);
+                                       usrerr("653 Unbalanced '>'");
+                                       c = NOCHAR;
                                }
                                }
-                               anglecnt--;
+                               else
+                                       anglecnt--;
                        }
                        }
-                       else if (delim == ' ' && isspace(c))
+                       else if (delim == ' ' && isascii(c) && isspace(c))
                                c = ' ';
                        else if (c == ':' && !CurEnv->e_oldstyle)
                        {
                                c = ' ';
                        else if (c == ':' && !CurEnv->e_oldstyle)
                        {
@@ -554,65 +620,34 @@ prescan(addr, delim, pvpbuf)
                        }
                        if (avp >= &av[MAXATOM])
                        {
                        }
                        if (avp >= &av[MAXATOM])
                        {
-                               syserr("prescan: too many tokens");
-                               DelimChar = p;
-                               return (NULL);
+                               syserr("553 prescan: too many tokens");
+                               goto returnnull;
+                       }
+                       if (q - tok > MAXNAME)
+                       {
+                               syserr("553 prescan: token too long");
+                               goto returnnull;
                        }
                        *avp++ = tok;
                }
        } while (c != '\0' && (c != delim || anglecnt > 0));
        *avp = NULL;
                        }
                        *avp++ = tok;
                }
        } while (c != '\0' && (c != delim || anglecnt > 0));
        *avp = NULL;
-       DelimChar = --p;
+       p--;
+       if (delimptr != NULL)
+               *delimptr = p;
        if (tTd(22, 12))
        {
                printf("prescan==>");
                printav(av);
        }
        if (tTd(22, 12))
        {
                printf("prescan==>");
                printav(av);
        }
-       if (av[0] != NULL)
-               return (av);
-       return (NULL);
-}
-\f/*
-**  TOKTYPE -- return token type
-**
-**     Parameters:
-**             c -- the character in question.
-**
-**     Returns:
-**             Its type.
-**
-**     Side Effects:
-**             none.
-*/
-
-static int
-toktype(c)
-       register char c;
-{
-       static char buf[50];
-       static bool firstime = TRUE;
-
-       if (firstime)
+       CurEnv->e_to = saveto;
+       if (av[0] == NULL)
        {
        {
-               firstime = FALSE;
-               expand("\001o", buf, &buf[sizeof buf - 1], CurEnv);
-               (void) strcat(buf, DELIMCHARS);
+               if (tTd(22, 1))
+                       printf("prescan: null leading token\n");
+               return (NULL);
        }
        }
-       if (c == MATCHCLASS || c == MATCHREPL || c == MATCHNCLASS)
-               return (ONE);
-#ifdef MACVALUE
-       if (c == MACVALUE)
-               return (ONE);
-#endif /* MACVALUE */
-       if (c == '"')
-               return (QST);
-       if (!isascii(c))
-               return (ATM);
-       if (isspace(c) || c == ')')
-               return (SPC);
-       if (iscntrl(c) || strchr(buf, c) != NULL)
-               return (OPR);
-       return (ATM);
+       return (av);
 }
 \f/*
 **  REWRITE -- apply rewrite rules to token vector.
 }
 \f/*
 **  REWRITE -- apply rewrite rules to token vector.
@@ -638,9 +673,13 @@ toktype(c)
 **
 **     Parameters:
 **             pvp -- pointer to token vector.
 **
 **     Parameters:
 **             pvp -- pointer to token vector.
+**             ruleset -- the ruleset to use for rewriting.
+**             reclevel -- recursion level (to catch loops).
+**             e -- the current envelope.
 **
 **     Returns:
 **
 **     Returns:
-**             none.
+**             A status code.  If EX_TEMPFAIL, higher level code should
+**                     attempt recovery.
 **
 **     Side Effects:
 **             pvp is modified.
 **
 **     Side Effects:
 **             pvp is modified.
@@ -655,6 +694,7 @@ struct match
 {
        char    **first;        /* first token matched */
        char    **last;         /* last token matched */
 {
        char    **first;        /* first token matched */
        char    **last;         /* last token matched */
+       char    **pattern;      /* pointer to pattern */
        char    **source;       /* left hand source operand */
        char    flags;          /* attributes of this operator */
 };
        char    **source;       /* left hand source operand */
        char    flags;          /* attributes of this operator */
 };
@@ -662,8 +702,13 @@ struct match
 # define MAXMATCH      9       /* max params per rewrite */
 # define MAX_CONTROL ' '
 
 # define MAXMATCH      9       /* max params per rewrite */
 # define MAX_CONTROL ' '
 
+# ifndef MAXRULERECURSION
+#  define MAXRULERECURSION     50      /* max recursion depth */
+# endif
 static char control_opts[MAX_CONTROL];
 
 static char control_opts[MAX_CONTROL];
 
+
+int
 static char control_init_data[] = { 
        MATCHZANY,      OP_VARLEN,
        MATCHONE,       OP_NONZLEN,
 static char control_init_data[] = { 
        MATCHZANY,      OP_VARLEN,
        MATCHONE,       OP_NONZLEN,
@@ -678,9 +723,11 @@ static char control_init_data[] = {
 static int nrw;
 
 void
 static int nrw;
 
 void
-rewrite(pvp, ruleset)
+rewrite(pvp, ruleset, reclevel, e)
        char **pvp;
        int ruleset;
        char **pvp;
        int ruleset;
+       int reclevel;
+       register ENVELOPE *e;
 {
        nrw = 0;
        _rewrite(pvp, ruleset);
 {
        nrw = 0;
        _rewrite(pvp, ruleset);
@@ -697,6 +744,9 @@ _rewrite(pvp, ruleset)
        register char **rvp;            /* rewrite vector pointer */
        register struct match *mlp;     /* cur ptr into mlist */
        register struct rewrite *rwr;   /* pointer to current rewrite rule */
        register char **rvp;            /* rewrite vector pointer */
        register struct match *mlp;     /* cur ptr into mlist */
        register struct rewrite *rwr;   /* pointer to current rewrite rule */
+       int ruleno;                     /* current rule number */
+       int rstat = EX_OK;              /* return status */
+       int loopcount;
        int subr;                       /* subroutine number if >= 0 */
        bool dolookup;                  /* do host aliasing */
        char *npvp[MAXATOM+1];          /* temporary space for rebuild */
        int subr;                       /* subroutine number if >= 0 */
        bool dolookup;                  /* do host aliasing */
        char *npvp[MAXATOM+1];          /* temporary space for rebuild */
@@ -707,18 +757,23 @@ _rewrite(pvp, ruleset)
        struct match *old_mlp;          /* to save our place */
        bool extend_match;      /* extend existing match during backup */
 
        struct match *old_mlp;          /* to save our place */
        bool extend_match;      /* extend existing match during backup */
 
-       if (OpMode == MD_TEST || tTd(21, 2))
+       if (OpMode == MD_TEST || tTd(21, 1))
        {
                printf("rewrite: ruleset %2d   input:", ruleset);
                printcav(pvp);
        }
        if (ruleset < 0 || ruleset >= MAXRWSETS)
        {
        {
                printf("rewrite: ruleset %2d   input:", ruleset);
                printcav(pvp);
        }
        if (ruleset < 0 || ruleset >= MAXRWSETS)
        {
-               syserr("rewrite: illegal ruleset number %d", ruleset);
-               return;
+               syserr("554 rewrite: illegal ruleset number %d", ruleset);
+               return EX_CONFIG;
+       }
+       if (reclevel++ > MAXRULERECURSION)
+       {
+               syserr("rewrite: infinite recursion, ruleset %d", ruleset);
+               return EX_CONFIG;
        }
        if (pvp == NULL)
        }
        if (pvp == NULL)
-               return;
+               return EX_USAGE;
 
        if (++nrw > 100)
        {
 
        if (++nrw > 100)
        {
@@ -738,10 +793,10 @@ _rewrite(pvp, ruleset)
        **  Run through the list of rewrite rules, applying any that match.
        */
 
        **  Run through the list of rewrite rules, applying any that match.
        */
 
+       ruleno = 1;
+       loopcount = 0;
        for (rwr = RewriteRules[ruleset]; rwr != NULL; )
        {
        for (rwr = RewriteRules[ruleset]; rwr != NULL; )
        {
-               int loopcount = 0;
-
                if (tTd(21, 12))
                {
                        printf("-----trying rule:");
                if (tTd(21, 12))
                {
                        printf("-----trying rule:");
@@ -787,7 +842,7 @@ _rewrite(pvp, ruleset)
                nloops = 0;
                extend_match = FALSE;
 
                nloops = 0;
                extend_match = FALSE;
 
-               while ((ap = *avp) != NULL || *rvp != NULL)
+               if (++loopcount > 100)
                {
                        if (nloops++ > 400)
                        {
                {
                        if (nloops++ > 400)
                        {
@@ -796,18 +851,23 @@ _rewrite(pvp, ruleset)
                                mlp = mlist - 1; /* force rule failure */
                                break;
                        }
                                mlp = mlist - 1; /* force rule failure */
                                break;
                        }
-                       if (++loopcount > 100)
+                       syserr("554 Infinite loop in ruleset %d, rule %d",
+                               ruleset, ruleno);
+                       if (tTd(21, 1))
                        {
                        {
-                               syserr("Infinite loop in ruleset %d", ruleset);
                                printf("workspace: ");
                                printav(pvp);
                                printf("workspace: ");
                                printav(pvp);
-                               break;
                        }
                        }
+                       break;
+               }
+
+               while ((ap = *avp) != NULL || *rvp != NULL)
+               {
                        rp = *rvp;
 
                        if (tTd(21, 35))
                        {
                        rp = *rvp;
 
                        if (tTd(21, 35))
                        {
-                               printf("rp=");
+                               printf("ADVANCE rp=");
                                xputs(rp);
                                printf(", ap=");
                                xputs(ap);
                                xputs(rp);
                                printf(", ap=");
                                xputs(ap);
@@ -885,22 +945,52 @@ _rewrite(pvp, ruleset)
                        {
                                switch (*rp)
                                {
                        {
                                switch (*rp)
                                {
-                                       register STAB *s;
-
-                                   case MATCHNCLASS:
-                                       /* match any single token not in a class */
-                                       s = stab(ap, ST_CLASS, ST_FIND);
-                                       if (s != NULL && bitnset(rp[1], s->s_class))
-                                               goto backup;
                                        break;
                                }
 
                                avp = mlp->last;
                                rvp++;
                                mlp++;
                                        break;
                                }
 
                                avp = mlp->last;
                                rvp++;
                                mlp++;
+                               break;
+
+                         case MATCHZERO:
+                               /* match zero tokens */
                                continue;
                        }
 
                                continue;
                        }
 
+                         case MACRODEXPAND:
+                               /*
+                               **  Match against run-time macro.
+                               **  This algorithm is broken for the
+                               **  general case (no recursive macros,
+                               **  improper tokenization) but should
+                               **  work for the usual cases.
+                               */
+
+                               ap = macvalue(rp[1], e);
+                               mlp->first = avp;
+                               if (tTd(21, 2))
+                                       printf("rewrite: LHS $&%c => \"%s\"\n",
+                                               rp[1],
+                                               ap == NULL ? "(NULL)" : ap);
+
+                               if (ap == NULL)
+                                       break;
+                               while (*ap != '\0')
+                               {
+                                       if (*avp == NULL ||
+                                           strncasecmp(ap, *avp, strlen(*avp)) != 0)
+                                       {
+                                               /* no match */
+                                               avp = mlp->first;
+                                               goto backup;
+                                       }
+                                       ap += strlen(*avp++);
+                               }
+
+                               /* match */
+                               break;
+
                        /*
                        **  We now have a variable length item.  It could
                        **  be $+ or $* in which case no special checking
                        /*
                        **  We now have a variable length item.  It could
                        **  be $+ or $* in which case no special checking
@@ -1036,6 +1126,7 @@ backup:
 
                        if (*avp == NULL)
                        {
 
                        if (*avp == NULL)
                        {
+                               rvp = mlp->pattern;
                                while (--mlp > mlist)
                                {
                                        if ((mlp->flags & OP_CLASS) &&
                                while (--mlp > mlist)
                                {
                                        if ((mlp->flags & OP_CLASS) &&
@@ -1092,6 +1183,8 @@ backup:
                        if (tTd(21, 10))
                                printf("----- rule fails\n");
                        rwr = rwr->r_next;
                        if (tTd(21, 10))
                                printf("----- rule fails\n");
                        rwr = rwr->r_next;
+                       ruleno++;
+                       loopcount = 0;
                        nmatches = 0;
                        continue;
                }
                        nmatches = 0;
                        continue;
                }
@@ -1113,18 +1206,20 @@ backup:
                }
 
                rp = *rvp;
                }
 
                rp = *rvp;
-               if (*rp == CANONUSER)
+               if ((*rp & 0377) == CANONUSER)
                {
                        rvp++;
                        rwr = rwr->r_next;
                {
                        rvp++;
                        rwr = rwr->r_next;
+                       ruleno++;
+                       loopcount = 0;
                        nmatches = 0;
                }
                        nmatches = 0;
                }
-               else if (*rp == CANONHOST)
+               else if ((*rp & 0377) == CANONHOST)
                {
                        rvp++;
                        rwr = NULL;
                }
                {
                        rvp++;
                        rwr = NULL;
                }
-               else if (*rp == CANONNET)
+               else if ((*rp & 0377) == CANONNET)
                        rwr = NULL;
 
                /* substitute */
                        rwr = NULL;
 
                /* substitute */
@@ -1150,7 +1245,7 @@ backup:
                                  toolong:
                                        syserr("rewrite: ruleset %d: replacement #%c out of bounds",
                                                ruleset, rp[1]);
                                  toolong:
                                        syserr("rewrite: ruleset %d: replacement #%c out of bounds",
                                                ruleset, rp[1]);
-                                       return;
+                                       return EX_CONFIG;
                                }
                                if (tTd(21, 15))
                                {
                                }
                                if (tTd(21, 15))
                                {
@@ -1204,7 +1299,6 @@ backup:
                        char **hbrvp, **ubrvp;
                        char **xpvp;
                        int trsize;
                        char **hbrvp, **ubrvp;
                        char **xpvp;
                        int trsize;
-                       char *olddelimchar;
                        char *replac;
                        int endtoken;
                        STAB *map;
                        char *replac;
                        int endtoken;
                        STAB *map;
@@ -1216,11 +1310,13 @@ backup:
                        char *pvpb1[MAXATOM + 1];
                        char *argvect[10];
                        char pvpbuf[PSBUFSIZE];
                        char *pvpb1[MAXATOM + 1];
                        char *argvect[10];
                        char pvpbuf[PSBUFSIZE];
+                       char *nullpvp[1];
                        bool match, defaultpart;
                        char begintype;
                        char db = '\0';
 
                        bool match, defaultpart;
                        char begintype;
                        char db = '\0';
 
-                       if (**rvp != HOSTBEGIN && **rvp != LOOKUPBEGIN)
+                       if ((**rvp & 0377) != HOSTBEGIN &&
+                           (**rvp & 0377) != LOOKUPBEGIN)
                                continue;
 
                        /*
                                continue;
 
                        /*
@@ -1232,7 +1328,7 @@ backup:
                        begintype = **rvp;
                        hbrvp = rvp;
                        ubrvp = NULL;
                        begintype = **rvp;
                        hbrvp = rvp;
                        ubrvp = NULL;
-                       if (**rvp == HOSTBEGIN)
+                       if ((**rvp & 0377) == HOSTBEGIN)
                        {
                                endtoken = HOSTEND;
                                mapname = "host";
                        {
                                endtoken = HOSTEND;
                                mapname = "host";
@@ -1244,7 +1340,7 @@ backup:
                        }
                        map = stab(mapname, ST_MAP, ST_FIND);
                        if (map == NULL)
                        }
                        map = stab(mapname, ST_MAP, ST_FIND);
                        if (map == NULL)
-                               syserr("rewrite: map %s not found", mapname);
+                               syserr("554 rewrite: map %s not found", mapname);
 
                        /* extract the match part */
                        key_rvp = ++rvp;
 
                        /* extract the match part */
                        key_rvp = ++rvp;
@@ -1252,9 +1348,9 @@ backup:
                        arg_rvp = argvect;
                        xpvp = NULL;
                        replac = pvpbuf;
                        arg_rvp = argvect;
                        xpvp = NULL;
                        replac = pvpbuf;
-                       while (*rvp != NULL && **rvp != endtoken)
+                       while (*rvp != NULL && (**rvp & 0377) != endtoken)
                        {
                        {
-                               int nodetype = **rvp;
+                               int nodetype = **rvp & 0377;
 
                                if (nodetype != CANONHOST && nodetype != CANONUSER)
                                {
 
                                if (nodetype != CANONHOST && nodetype != CANONUSER)
                                {
@@ -1266,8 +1362,9 @@ backup:
 
                                if (xpvp != NULL)
                                {
 
                                if (xpvp != NULL)
                                {
-                                       cataddr(xpvp, replac,
-                                               &pvpbuf[sizeof pvpbuf] - replac);
+                                       cataddr(xpvp, NULL, replac,
+                                               &pvpbuf[sizeof pvpbuf] - replac,
+                                               '\0');
                                        *++arg_rvp = replac;
                                        replac += strlen(replac) + 1;
                                        xpvp = NULL;
                                        *++arg_rvp = replac;
                                        replac += strlen(replac) + 1;
                                        xpvp = NULL;
@@ -1287,8 +1384,9 @@ backup:
                                *rvp++ = NULL;
                        if (xpvp != NULL)
                        {
                                *rvp++ = NULL;
                        if (xpvp != NULL)
                        {
-                               cataddr(xpvp, replac,
-                                       &pvpbuf[sizeof pvpbuf] - replac);
+                               cataddr(xpvp, NULL, replac,
+                                       &pvpbuf[sizeof pvpbuf] - replac, 
+                                       '\0');
                                *++arg_rvp = replac;
                        }
                        *++arg_rvp = NULL;
                                *++arg_rvp = replac;
                        }
                        *++arg_rvp = NULL;
@@ -1373,11 +1471,13 @@ backup:
                }
        }
 
                }
        }
 
-       if (OpMode == MD_TEST || tTd(21, 2))
+       if (OpMode == MD_TEST || tTd(21, 1))
        {
                printf("rewrite: ruleset %2d returns:", ruleset);
                printcav(pvp);
        }
        {
                printf("rewrite: ruleset %2d returns:", ruleset);
                printcav(pvp);
        }
+
+       return rstat;
 }
 \f/*
 **  CALLSUBR -- call subroutines in rewrite vector
 }
 \f/*
 **  CALLSUBR -- call subroutines in rewrite vector
@@ -1434,6 +1534,9 @@ callsubr(pvp)
 **             tv -- token vector.
 **             a -- pointer to address descriptor to fill.
 **                     If NULL, one will be allocated.
 **             tv -- token vector.
 **             a -- pointer to address descriptor to fill.
 **                     If NULL, one will be allocated.
+**             flags -- info regarding whether this is a sender or
+**                     a recipient.
+**             e -- the current envelope.
 **
 **     Returns:
 **             NULL if there was an error.
 **
 **     Returns:
 **             NULL if there was an error.
@@ -1463,34 +1566,57 @@ struct errcodes
 };
 
 static ADDRESS *
 };
 
 static ADDRESS *
-buildaddr(tv, a)
+buildaddr(tv, a, flags, e)
        register char **tv;
        register ADDRESS *a;
        register char **tv;
        register ADDRESS *a;
+       int flags;
+       register ENVELOPE *e;
 {
        struct mailer **mp;
        register struct mailer *m;
        char *bp;
        int spaceleft;
 {
        struct mailer **mp;
        register struct mailer *m;
        char *bp;
        int spaceleft;
+       static MAILER errormailer;
+       static char *errorargv[] = { "ERROR", NULL };
        static char buf[MAXNAME];
 
        static char buf[MAXNAME];
 
+       if (tTd(24, 5))
+       {
+               printf("buildaddr, flags=%x, tv=", flags);
+               printav(tv);
+       }
+
        if (a == NULL)
                a = (ADDRESS *) xalloc(sizeof *a);
        clear((char *) a, sizeof *a);
 
        if (a == NULL)
                a = (ADDRESS *) xalloc(sizeof *a);
        clear((char *) a, sizeof *a);
 
+       /* set up default error return flags */
+       a->q_flags |= QPINGONFAILURE;
+
        /* figure out what net/mailer to use */
        if (*tv == NULL || **tv != CANONNET)
        {
        /* figure out what net/mailer to use */
        if (*tv == NULL || **tv != CANONNET)
        {
-               syserr("buildaddr: no net");
-               return (NULL);
+               syserr("554 buildaddr: no net");
+badaddr:
+               a->q_flags |= QBADADDR;
+               a->q_mailer = &errormailer;
+               if (errormailer.m_name == NULL)
+               {
+                       /* initialize the bogus mailer */
+                       errormailer.m_name = "*error*";
+                       errormailer.m_mailer = "ERROR";
+                       errormailer.m_argv = errorargv;
+               }
+               return a;
        }
        tv++;
        }
        tv++;
-       if (!strcasecmp(*tv, "error"))
+       if (strcasecmp(*tv, "error") == 0)
        {
        {
-               if (**++tv == CANONHOST)
+               if ((**++tv & 0377) == CANONHOST)
                {
                        register struct errcodes *ep;
 
                {
                        register struct errcodes *ep;
 
-                       if (isdigit(**++tv))
+                       if (isascii(**++tv) && isdigit(**tv))
                        {
                                setstat(atoi(*tv));
                        }
                        {
                                setstat(atoi(*tv));
                        }
@@ -1503,6 +1629,8 @@ buildaddr(tv, a)
                        }
                        tv++;
                }
                        }
                        tv++;
                }
+               else
+                       setstat(EX_UNAVAILABLE);
                buf[0] = '\0';
                for (; (*tv != NULL) && (**tv != CANONUSER); tv++)
                {
                buf[0] = '\0';
                for (; (*tv != NULL) && (**tv != CANONUSER); tv++)
                {
@@ -1510,62 +1638,60 @@ buildaddr(tv, a)
                                (void) strcat(buf, " ");
                        (void) strcat(buf, *tv);
                }
                                (void) strcat(buf, " ");
                        (void) strcat(buf, *tv);
                }
-               if (**tv != CANONUSER)
-                       syserr("buildaddr: error: no user");
-               while (*++tv != NULL)
-               {
-                       int i = strlen(*tv);
-
-                       if (i > spaceleft)
-                       {
-                               /* out of space for this address */
-                               if (spaceleft >= 0)
-                                       syserr("buildaddr: error message too long (%.40s...)",
-                                               buf);
-                               i = spaceleft;
-                               spaceleft = 0;
-                       }
-                       if (i <= 0)
-                               continue;
-                       if (bp != buf)
-                       {
-                               *bp++ = ' ';
-                               spaceleft--;
-                       }
-                       bcopy(*tv, bp, i);
-                       bp += i;
-                       spaceleft -= i;
-               }
-               *bp = '\0';
+               if ((**tv & 0377) != CANONUSER)
+                       syserr("554 buildaddr: error: no user");
+               cataddr(++tv, NULL, buf, sizeof buf, ' ');
+               stripquotes(buf);
 #ifdef LOG
                if (LogLevel > 8)
                        syslog (LOG_DEBUG, "%s: Trace: $#ERROR $: %s",
                                CurEnv->e_id, buf);
 #endif /* LOG */
 #ifdef LOG
                if (LogLevel > 8)
                        syslog (LOG_DEBUG, "%s: Trace: $#ERROR $: %s",
                                CurEnv->e_id, buf);
 #endif /* LOG */
-               usrerr(buf);
-               return (NULL);
+               if (isascii(buf[0]) && isdigit(buf[0]) &&
+                   isascii(buf[1]) && isdigit(buf[1]) &&
+                   isascii(buf[2]) && isdigit(buf[2]) &&
+                   buf[3] == ' ')
+               {
+                       char fmt[10];
+
+                       strncpy(fmt, buf, 3);
+                       strcpy(&fmt[3], " %s");
+                       usrerr(fmt, buf + 4);
+
+                       /*
+                       **  If this is a 4xx code and we aren't running
+                       **  SMTP on our input, bounce this message;
+                       **  otherwise it disappears without a trace.
+                       */
+
+                       if (fmt[0] == '4' && OpMode != MD_SMTP &&
+                           OpMode != MD_DAEMON)
+                       {
+                               e->e_flags |= EF_FATALERRS;
+                       }
+               }
+               else
+               {
+                       usrerr("553 %s", buf);
+               }
+               goto badaddr;
        }
 
        for (mp = Mailer; (m = *mp++) != NULL; )
        {
        }
 
        for (mp = Mailer; (m = *mp++) != NULL; )
        {
-               if (!strcasecmp(m->m_name, *tv))
+               if (strcasecmp(m->m_name, *tv) == 0)
                        break;
        }
        if (m == NULL)
        {
                        break;
        }
        if (m == NULL)
        {
-               syserr("buildaddr: unknown mailer %s", *tv);
-               return (NULL);
+               syserr("554 buildaddr: unknown mailer %s", *tv);
+               goto badaddr;
        }
        a->q_mailer = m;
 
        /* figure out what host (if any) */
        if (**++tv != CANONHOST)
        {
        }
        a->q_mailer = m;
 
        /* figure out what host (if any) */
        if (**++tv != CANONHOST)
        {
-               if (!bitnset(M_LOCAL, m->m_flags))
-               {
-                       syserr("buildaddr: no host");
-                       return (NULL);
-               }
                a->q_host = NULL;
        }
        else
                a->q_host = NULL;
        }
        else
@@ -1581,28 +1707,28 @@ buildaddr(tv, a)
        }
 
        /* figure out the user */
        }
 
        /* figure out the user */
-       if (*tv == NULL || **tv != CANONUSER)
+       if (*tv == NULL || (**tv & 0377) != CANONUSER)
        {
        {
-               syserr("buildaddr: no user");
-               return (NULL);
+               syserr("554 buildaddr: no user");
+               goto badaddr;
        }
        tv++;
 
        /* do special mapping for local mailer */
        }
        tv++;
 
        /* do special mapping for local mailer */
-       if (m == LocalMailer && *tv != NULL)
+       if (*tv != NULL)
        {
                register char *p = *tv;
 
                if (*p == '"')
                        p++;
        {
                register char *p = *tv;
 
                if (*p == '"')
                        p++;
-               if (*p == '|')
+               if (*p == '|' && bitnset(M_CHECKPROG, m->m_flags))
                        a->q_mailer = m = ProgMailer;
                        a->q_mailer = m = ProgMailer;
-               else if (*p == '/')
+               else if (*p == '/' && bitnset(M_CHECKFILE, m->m_flags))
                        a->q_mailer = m = FileMailer;
                        a->q_mailer = m = FileMailer;
-               else if (*p == ':')
+               else if (*p == ':' && bitnset(M_CHECKINCLUDE, m->m_flags))
                {
                        /* may be :include: */
                {
                        /* may be :include: */
-                       cataddr(tv, buf, sizeof buf);
+                       cataddr(tv, NULL, buf, sizeof buf, '\0');
                        stripquotes(buf);
                        if (strncasecmp(buf, ":include:", 9) == 0)
                        {
                        stripquotes(buf);
                        if (strncasecmp(buf, ":include:", 9) == 0)
                        {
@@ -1614,22 +1740,30 @@ buildaddr(tv, a)
                }
        }
 
                }
        }
 
-       if (m == LocalMailer && *tv != NULL && strcmp(*tv, "@") == 0)
+       if (bitnset(M_CHECKUDB, m->m_flags) && *tv != NULL &&
+           strcmp(*tv, "@") == 0)
        {
                tv++;
                a->q_flags |= QNOTREMOTE;
        }
 
        {
                tv++;
                a->q_flags |= QNOTREMOTE;
        }
 
-       /* rewrite according recipient mailer rewriting rules */
-       rewrite(tv, 2);
        if (m->m_r_rwset > 0)
                rewrite(tv, m->m_r_rwset);
        if (m->m_r_rwset > 0)
                rewrite(tv, m->m_r_rwset);
-       rewrite(tv, 4);
+       (void) rewrite(tv, 4, 0, e);
 
        /* save the result for the command line/RCPT argument */
 
        /* save the result for the command line/RCPT argument */
-       cataddr(tv, buf, sizeof buf);
+       cataddr(tv, NULL, buf, sizeof buf, '\0');
        a->q_user = buf;
 
        a->q_user = buf;
 
+       /*
+       **  Do mapping to lower case as requested by mailer
+       */
+
+       if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
+               makelower(a->q_host);
+       if (!bitnset(M_USR_UPPER, m->m_flags))
+               makelower(a->q_user);
+
        return (a);
 }
 \f/*
        return (a);
 }
 \f/*
@@ -1637,8 +1771,12 @@ buildaddr(tv, a)
 **
 **     Parameters:
 **             pvp -- parameter vector to rebuild.
 **
 **     Parameters:
 **             pvp -- parameter vector to rebuild.
+**             evp -- last parameter to include.  Can be NULL to
+**                     use entire pvp.
 **             buf -- buffer to build the string into.
 **             sz -- size of buf.
 **             buf -- buffer to build the string into.
 **             sz -- size of buf.
+**             spacesub -- the space separator character; if null,
+**                     use SpaceSub.
 **
 **     Returns:
 **             none.
 **
 **     Returns:
 **             none.
@@ -1648,16 +1786,21 @@ buildaddr(tv, a)
 */
 
 void
 */
 
 void
-cataddr(pvp, buf, sz)
+cataddr(pvp, evp, buf, sz, spacesub)
        char **pvp;
        char **pvp;
+       char **evp;
        char *buf;
        register int sz;
        char *buf;
        register int sz;
+       char spacesub;
 {
        bool oatomtok = FALSE;
        bool natomtok;
        register int i;
        register char *p;
 
 {
        bool oatomtok = FALSE;
        bool natomtok;
        register int i;
        register char *p;
 
+       if (spacesub == '\0')
+               spacesub = SpaceSub;
+
        if (pvp == NULL)
        {
                (void) strcpy(buf, "");
        if (pvp == NULL)
        {
                (void) strcpy(buf, "");
@@ -1669,12 +1812,13 @@ cataddr(pvp, buf, sz)
        {
                natomtok = (toktype(**pvp) == ATM);
                if (oatomtok && natomtok)
        {
                natomtok = (toktype(**pvp) == ATM);
                if (oatomtok && natomtok)
-                       *p++ = SpaceSub;
+                       *p++ = spacesub;
                (void) strcpy(p, *pvp);
                oatomtok = natomtok;
                p += i;
                sz -= i + 1;
                (void) strcpy(p, *pvp);
                oatomtok = natomtok;
                p += i;
                sz -= i + 1;
-               pvp++;
+               if (pvp++ == evp)
+                       break;
        }
        *p = '\0';
 }
        }
        *p = '\0';
 }
@@ -1700,6 +1844,8 @@ sameaddr(a, b)
        register ADDRESS *a;
        register ADDRESS *b;
 {
        register ADDRESS *a;
        register ADDRESS *b;
 {
+       register ADDRESS *ca, *cb;
+
        /* if they don't have the same mailer, forget it */
        if (a->q_mailer != b->q_mailer)
                return (FALSE);
        /* if they don't have the same mailer, forget it */
        if (a->q_mailer != b->q_mailer)
                return (FALSE);
@@ -1708,13 +1854,28 @@ sameaddr(a, b)
        if (strcasecmp(a->q_user, b->q_user))
                return (FALSE);
 
        if (strcasecmp(a->q_user, b->q_user))
                return (FALSE);
 
-       /* if the mailer ignores hosts, we have succeeded! */
-       if (bitnset(M_LOCAL, a->q_mailer->m_flags))
-               return (TRUE);
+       /* if we have good uids for both but they differ, these are different */
+       if (a->q_mailer == ProgMailer)
+       {
+               ca = getctladdr(a);
+               cb = getctladdr(b);
+               if (ca != NULL && cb != NULL &&
+                   bitset(QGOODUID, ca->q_flags & cb->q_flags) &&
+                   ca->q_uid != cb->q_uid)
+                       return (FALSE);
+       }
 
        /* otherwise compare hosts (but be careful for NULL ptrs) */
 
        /* otherwise compare hosts (but be careful for NULL ptrs) */
+       if (a->q_host == b->q_host)
+       {
+               /* probably both null pointers */
+               return (TRUE);
+       }
        if (a->q_host == NULL || b->q_host == NULL)
        if (a->q_host == NULL || b->q_host == NULL)
+       {
+               /* only one is a null pointer */
                return (FALSE);
                return (FALSE);
+       }
        if (strcasecmp(a->q_host, b->q_host))
                return (FALSE);
 
        if (strcasecmp(a->q_host, b->q_host))
                return (FALSE);
 
@@ -1781,7 +1942,24 @@ printaddr(a, follow)
        if (first)
                printf("[NULL]\n");
 }
        if (first)
                printf("[NULL]\n");
 }
+\f/*
+**  EMPTYADDR -- return TRUE if this address is empty (``<>'')
+**
+**     Parameters:
+**             a -- pointer to the address
+**
+**     Returns:
+**             TRUE -- if this address is "empty" (i.e., no one should
+**                     ever generate replies to it.
+**             FALSE -- if it is a "regular" (read: replyable) address.
+*/
 
 
+bool
+emptyaddr(a)
+       register ADDRESS *a;
+{
+       return strcmp(a->q_paddr, "<>") == 0 || strcmp(a->q_user, "<>") == 0;
+}
 \f/*
 **  REMOTENAME -- return the name relative to the current mailer
 **
 \f/*
 **  REMOTENAME -- return the name relative to the current mailer
 **
@@ -1789,12 +1967,8 @@ printaddr(a, follow)
 **             name -- the name to translate.
 **             m -- the mailer that we want to do rewriting relative
 **                     to.
 **             name -- the name to translate.
 **             m -- the mailer that we want to do rewriting relative
 **                     to.
-**             senderaddress -- if set, uses the sender rewriting rules
-**                     rather than the recipient rewriting rules.
-**             header -- set if this address is in the header, rather
-**                     than an envelope header.
-**             canonical -- if set, strip out any comment information,
-**                     etc.
+**             flags -- fine tune operations.
+**             pstat -- pointer to status word.
 **             e -- the current envelope.
 **
 **     Returns:
 **             e -- the current envelope.
 **
 **     Returns:
@@ -1810,12 +1984,11 @@ printaddr(a, follow)
 */
 
 char *
 */
 
 char *
-remotename(name, m, senderaddress, header, canonical, e)
+remotename(name, m, flags, pstat, e)
        char *name;
        MAILER *m;
        char *name;
        MAILER *m;
-       bool senderaddress;
-       bool header;
-       bool canonical;
+       int flags;
+       int *pstat;
        register ENVELOPE *e;
 {
        register char **pvp;
        register ENVELOPE *e;
 {
        register char **pvp;
@@ -1838,8 +2011,8 @@ remotename(name, m, senderaddress, header, canonical, e)
        **      This will leave the name as a comment and a $g macro.
        */
 
        **      This will leave the name as a comment and a $g macro.
        */
 
-       if (canonical || bitnset(M_NOCOMMENT, m->m_flags))
-               fancy = "\001g";
+       if (bitset(RF_CANONICAL, flags) || bitnset(M_NOCOMMENT, m->m_flags))
+               fancy = "\201g";
        else
                fancy = crackaddr(name);
 
        else
                fancy = crackaddr(name);
 
@@ -1851,11 +2024,12 @@ remotename(name, m, senderaddress, header, canonical, e)
        **      domain will be appended.
        */
 
        **      domain will be appended.
        */
 
-       pvp = prescan(name, '\0', pvpbuf);
+       pvp = prescan(name, '\0', pvpbuf, sizeof pvpbuf, NULL);
        if (pvp == NULL)
                return (name);
        if (pvp == NULL)
                return (name);
-       rewrite(pvp, 3);
-       if (e->e_fromdomain != NULL)
+       if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
+               *pstat = EX_TEMPFAIL;
+       if (bitset(RF_ADDDOMAIN, flags) && e->e_fromdomain != NULL)
        {
                /* append from domain to this address */
                register char **pxp = pvp;
        {
                /* append from domain to this address */
                register char **pxp = pvp;
@@ -1870,7 +2044,8 @@ remotename(name, m, senderaddress, header, canonical, e)
 
                        while ((*pxp++ = *qxq++) != NULL)
                                continue;
 
                        while ((*pxp++ = *qxq++) != NULL)
                                continue;
-                       rewrite(pvp, 3);
+                       if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
+                               *pstat = EX_TEMPFAIL;
                }
        }
 
                }
        }
 
@@ -1882,10 +2057,13 @@ remotename(name, m, senderaddress, header, canonical, e)
        **      Then run it through any receiving-mailer-specific rulesets.
        */
 
        **      Then run it through any receiving-mailer-specific rulesets.
        */
 
-       if (senderaddress)
        else
        else
+       {
        if (rwset > 0)
        if (rwset > 0)
-               rewrite(pvp, rwset);
+       {
+               if (rewrite(pvp, rwset, 0, e) == EX_TEMPFAIL)
+                       *pstat = EX_TEMPFAIL;
+       }
 
        /*
        **  Do any final sanitation the address may require.
 
        /*
        **  Do any final sanitation the address may require.
@@ -1894,15 +2072,22 @@ remotename(name, m, senderaddress, header, canonical, e)
        **      may be used as a default to the above rules.
        */
 
        **      may be used as a default to the above rules.
        */
 
-       rewrite(pvp, 4);
+       if (rewrite(pvp, 4, 0, e) == EX_TEMPFAIL)
+               *pstat = EX_TEMPFAIL;
 
        /*
        **  Now restore the comment information we had at the beginning.
        */
 
 
        /*
        **  Now restore the comment information we had at the beginning.
        */
 
-       cataddr(pvp, lbuf, sizeof lbuf);
+       cataddr(pvp, NULL, lbuf, sizeof lbuf, '\0');
        define('g', lbuf, e);
        define('g', lbuf, e);
-       expand(fancy, buf, &buf[sizeof buf - 1], e);
+
+       /* need to make sure route-addrs have <angle brackets> */
+       if (bitset(RF_CANONICAL, flags) && lbuf[0] == '@')
+               expand("<\201g>", buf, &buf[sizeof buf - 1], e);
+       else
+               expand(fancy, buf, &buf[sizeof buf - 1], e);
+
        define('g', oldg, e);
 
        if (tTd(12, 1))
        define('g', oldg, e);
 
        if (tTd(12, 1))
@@ -1998,6 +2183,7 @@ maplocaluser(a, sendq, e)
 {
        register char **pvp;
        register ADDRESS *a1 = NULL;
 {
        register char **pvp;
        register ADDRESS *a1 = NULL;
+       auto char *delimptr;
        char pvpbuf[PSBUFSIZE];
 
        if (tTd(29, 1))
        char pvpbuf[PSBUFSIZE];
 
        if (tTd(29, 1))
@@ -2005,16 +2191,16 @@ maplocaluser(a, sendq, e)
                printf("maplocaluser: ");
                printaddr(a, FALSE);
        }
                printf("maplocaluser: ");
                printaddr(a, FALSE);
        }
-       pvp = prescan(a->q_user, '\0', pvpbuf);
+       pvp = prescan(a->q_user, '\0', pvpbuf, sizeof pvpbuf, &delimptr);
        if (pvp == NULL)
                return;
 
        if (pvp == NULL)
                return;
 
-       rewrite(pvp, 5);
-       if (pvp[0] == NULL || pvp[0][0] != CANONNET)
+       (void) rewrite(pvp, 5, 0, e);
+       if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
                return;
 
        /* if non-null, mailer destination specified -- has it changed? */
                return;
 
        /* if non-null, mailer destination specified -- has it changed? */
-       a1 = buildaddr(pvp, NULL);
+       a1 = buildaddr(pvp, NULL, 0, e);
        if (a1 == NULL || sameaddr(a, a1))
                return;
 
        if (a1 == NULL || sameaddr(a, a1))
                return;
 
@@ -2026,6 +2212,148 @@ maplocaluser(a, sendq, e)
                printaddr(a, FALSE);
        }
        a1->q_alias = a;
                printaddr(a, FALSE);
        }
        a1->q_alias = a;
-       allocaddr(a1, 1, NULL);
+       allocaddr(a1, RF_COPYALL, NULL);
        (void) recipient(a1, sendq, e);
 }
        (void) recipient(a1, sendq, e);
 }
+\f/*
+**  DEQUOTE_INIT -- initialize dequote map
+**
+**     This is a no-op.
+**
+**     Parameters:
+**             map -- the internal map structure.
+**             args -- arguments.
+**
+**     Returns:
+**             TRUE.
+*/
+
+bool
+dequote_init(map, args)
+       MAP *map;
+       char *args;
+{
+       register char *p = args;
+
+       for (;;)
+       {
+               while (isascii(*p) && isspace(*p))
+                       p++;
+               if (*p != '-')
+                       break;
+               switch (*++p)
+               {
+                 case 'a':
+                       map->map_app = ++p;
+                       break;
+
+                 case 's':
+                       map->map_coldelim = *++p;
+                       break;
+               }
+               while (*p != '\0' && !(isascii(*p) && isspace(*p)))
+                       p++;
+               if (*p != '\0')
+                       *p = '\0';
+       }
+       if (map->map_app != NULL)
+               map->map_app = newstr(map->map_app);
+
+       return TRUE;
+}
+\f/*
+**  DEQUOTE_MAP -- unquote an address
+**
+**     Parameters:
+**             map -- the internal map structure (ignored).
+**             name -- the name to dequote.
+**             av -- arguments (ignored).
+**             statp -- pointer to status out-parameter.
+**
+**     Returns:
+**             NULL -- if there were no quotes, or if the resulting
+**                     unquoted buffer would not be acceptable to prescan.
+**             else -- The dequoted buffer.
+*/
+
+char *
+dequote_map(map, name, av, statp)
+       MAP *map;
+       char *name;
+       char **av;
+       int *statp;
+{
+       register char *p;
+       register char *q;
+       register char c;
+       int anglecnt = 0;
+       int cmntcnt = 0;
+       int quotecnt = 0;
+       int spacecnt = 0;
+       bool quotemode = FALSE;
+       bool bslashmode = FALSE;
+       char spacesub = map->map_coldelim;
+
+       for (p = q = name; (c = *p++) != '\0'; )
+       {
+               if (bslashmode)
+               {
+                       bslashmode = FALSE;
+                       *q++ = c;
+                       continue;
+               }
+
+               if (c == ' ' && spacesub != '\0')
+                       c = spacesub;
+
+               switch (c)
+               {
+                 case '\\':
+                       bslashmode = TRUE;
+                       break;
+
+                 case '(':
+                       cmntcnt++;
+                       break;
+
+                 case ')':
+                       if (cmntcnt-- <= 0)
+                               return NULL;
+                       break;
+
+                 case ' ':
+                       spacecnt++;
+                       break;
+               }
+
+               if (cmntcnt > 0)
+               {
+                       *q++ = c;
+                       continue;
+               }
+
+               switch (c)
+               {
+                 case '"':
+                       quotemode = !quotemode;
+                       quotecnt++;
+                       continue;
+
+                 case '<':
+                       anglecnt++;
+                       break;
+
+                 case '>':
+                       if (anglecnt-- <= 0)
+                               return NULL;
+                       break;
+               }
+               *q++ = c;
+       }
+
+       if (anglecnt != 0 || cmntcnt != 0 || bslashmode ||
+           quotemode || quotecnt <= 0 || spacecnt != 0)
+               return NULL;
+       *q++ = '\0';
+       return name;
+}