parseaddr.c revision d4660949aa62dd6a963f4913b7120b383cf473c4
/*
* Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers.
* All rights reserved.
* Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include <sendmail.h>
SM_RCSID("@(#)$Id: parseaddr.c,v 8.403 2008/02/08 02:27:35 ca Exp $")
#include <sm/sendmail.h>
#include "map.h"
static bool hasctrlchar __P((register char *, bool, bool));
/* replacement for illegal characters in addresses */
#define BAD_CHAR_REPLACEMENT '?'
/*
** PARSEADDR -- Parse an address
**
** Parses an address and breaks it up into three parts: a
** net to transmit the message on, the host to transmit it
** to, and a user on that host. These are loaded into an
** ADDRESS header with the values squirreled away if necessary.
** The "user" part may not be a real user; the process may
** just reoccur on that machine. For example, on a machine
** with an arpanet connection, the address
** csvax.bill@berkeley
** will break up to a "user" of 'csvax.bill' and a host
** of 'berkeley' -- to be transmitted over the arpanet.
**
** Parameters:
** addr -- the address to parse.
** a -- a pointer to the address descriptor buffer.
** If NULL, an address will be created.
** flags -- describe detail for parsing. See RF_ definitions
** in sendmail.h.
** 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.
** isrcpt -- true if the address denotes a recipient; false
** indicates a sender.
**
** Returns:
** A pointer to the address descriptor header (`a' if
** `a' is non-NULL).
** NULL on error.
**
** Side Effects:
** e->e_to = addr
*/
/* following delimiters are inherent to the internal algorithms */
ADDRESS *
char *addr;
register ADDRESS *a;
int flags;
int delim;
char **delimptr;
register ENVELOPE *e;
bool isrcpt;
{
char **pvp;
auto char *delimptrbuf;
bool qup;
/*
** Initialize and prescan address.
*/
delimptr = &delimptrbuf;
ExtTokenTab, false);
{
sm_dprintf("parseaddr-->NULL\n");
return NULL;
}
{
sm_dprintf("parseaddr-->bad address\n");
return NULL;
}
/*
** 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.
*/
{
if (savec != '\0')
**delimptr = '\0';
if (savec != '\0')
}
/*
** Apply rewriting rules.
** Ruleset 0 does basic parsing. It must resolve.
*/
qup = false;
qup = true;
qup = true;
/*
** Build canonical address from pvp.
*/
{
sm_dprintf("parseaddr-->bad q_user\n");
/*
** Just mark the address as bad so DSNs work.
** hasctrlchar() has to make sure that the address
** has been sanitized, e.g., shortened.
*/
a->q_state = QS_BADADDR;
}
/*
** Make local copies of the host & user and then
** transport them out.
*/
if (QS_IS_BADADDR(a->q_state))
{
/* weed out bad characters in the printable address too */
return a;
}
/*
** Select a queue directory for recipient addresses.
** This is done here and in split_across_queue_groups(),
** but the latter applies to addresses after aliasing,
** and only if splitting is done.
*/
OpMode != MD_INITALIAS)
{
int r;
/* call ruleset which should return a queue group name */
sizeof(pvpbuf));
if (r == EX_OK &&
{
"can't find queue group name %s, selection ignored",
pvp[1]);
"queue group name %s -> %d",
pvp[1], r);
}
}
/*
** If there was a parsing failure, mark it for queueing.
*/
{
char *msg = "Transient parse error -- message queued for future delivery";
if (e->e_sendmode == SM_DEFER)
msg = "Deferring message until queue run";
sm_dprintf("parseaddr: queueing message\n");
a->q_state = QS_QUEUEUP;
a->q_status = "4.4.3";
}
/*
** Compute return value.
*/
{
sm_dprintf("parseaddr-->");
printaddr(sm_debug_file(), a, false);
}
return a;
}
/*
** INVALIDADDR -- check for address containing characters used for macros
**
** Parameters:
** addr -- the address to check.
** delimptr -- if non-NULL: end of address to check, i.e.,
** a pointer in the address string.
** isrcpt -- true iff the address is for a recipient.
**
** Returns:
** true -- if the address has characters that are reservered
** for macros or is too long.
** false -- otherwise.
*/
bool
register char *addr;
char *delimptr;
bool isrcpt;
{
bool result = false;
char savedelim = '\0';
char *b = addr;
int len = 0;
{
/* delimptr points to the end of the address to test */
}
{
{
result = true;
}
{
*addr = '\0';
usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
b, MAXNAME - 1);
result = true;
goto delim;
}
}
if (result)
{
if (isrcpt)
usrerr("501 5.1.3 8-bit character in mailbox address \"%s\"",
b);
else
usrerr("501 5.1.7 8-bit character in mailbox address \"%s\"",
b);
}
return result;
}
/*
** HASCTRLCHAR -- check for address containing meta-characters
**
** Checks that the address contains no meta-characters, and contains
** no "non-printable" characters unless they are quoted or escaped.
** Quoted or escaped characters are literals.
**
** Parameters:
** addr -- the address to check.
** isrcpt -- true if the address is for a recipient; false
** indicates a from.
** complain -- true if an error should issued if the address
** is invalid and should be "repaired".
**
** Returns:
** true -- if the address has any "wierd" characters or
** non-printable characters or if a quote is unbalanced.
** false -- otherwise.
*/
static bool
register char *addr;
{
bool quoted = false;
int len = 0;
char *b = addr;
return false;
{
{
if (complain)
{
usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
b, MAXNAME - 1);
return true;
}
result = "too long";
}
{
result = "non-printable character";
continue;
}
if (*addr == '"')
else if (*addr == '\\')
{
/* XXX Generic problem: no '\0' in strings. */
if (*++addr == '\0')
{
result = "trailing \\ character";
*--addr = BAD_CHAR_REPLACEMENT;
break;
}
}
{
result = "8-bit character";
continue;
}
}
if (quoted)
{
if (isrcpt)
usrerr("501 5.1.3 Syntax error in mailbox address \"%s\" (%s)",
b, result);
else
usrerr("501 5.1.7 Syntax error in mailbox address \"%s\" (%s)",
b, result);
}
}
/*
** ALLOCADDR -- do local allocations of address on demand.
**
** Also lowercases the host name if requested.
**
** Parameters:
** a -- the address to reallocate.
** flags -- the copy flag (see RF_ definitions in sendmail.h
** for a description).
** paddr -- the printname of the address.
** e -- envelope
**
** Returns:
** none.
**
** Side Effects:
** Copies portions of a into local buffers as requested.
*/
static void
register ADDRESS *a;
int flags;
char *paddr;
ENVELOPE *e;
{
a->q_user = "";
a->q_host = "";
{
}
}
/*
** PRESCAN -- Prescan name and make it canonical
**
** Scans a name and turns it into a set of tokens. This process
** deletes blanks and comments (in parentheses) (if the token type
** for left paren is SPC).
**
** This routine knows about quoted strings and angle brackets.
**
** There are certain subtleties to this routine. The one that
** comes to mind now is that backslashes on the ends of names
** are silently stripped off; this is intentional. The problem
** is that some versions of sndmsg (like at LBL) set the kill
** character to something other than @ when reading addresses;
** so people type "csvax.eric\@berkeley" -- which screws up the
** berknet mailer.
**
** Parameters:
** addr -- the name to chomp.
** delim -- the delimiter for the address, normally
** '\0' or ','; \0 is accepted in any case.
** 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.
** toktab -- if set, a token table to use for parsing.
** If NULL, use the default table.
** ignore -- if true, ignore unbalanced addresses
**
** Returns:
** A pointer to a vector of tokens.
** NULL on error.
*/
/* states and character types */
#define OPR 0 /* operator */
/* meta bits for table */
#define M 020 /* meta character; don't pass through */
#define B 040 /* cause a break */
#define MB M|B /* meta-break */
{
/* oldst chtype> OPR ATM QST SPC ONE ILL */
};
/* these all get modified with the OperatorChars */
/* token type table for external strings */
unsigned char ExtTokenTab[256] =
{
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
};
/* token type table for internal strings */
unsigned char IntTokenTab[256] =
{
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
};
/* token type table for MIME parsing */
unsigned char MimeTokenTab[256] =
{
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
};
/* token type table: don't strip comments */
unsigned char TokTypeNoC[256] =
{
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
/* sp ! " # $ % & ' ( ) * + , - . / */
/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
/* @ A B C D E F G H I J K L M N O */
/* P Q R S T U V W X Y Z [ \ ] ^ _ */
/* ` a b c d e f g h i j k l m n o */
/* p q r s t u v w x y z { | } ~ del */
};
char **
char *addr;
int delim;
char pvpbuf[];
int pvpbsize;
char **delimptr;
unsigned char *toktab;
bool ignore;
{
register char *p;
register char *q;
register int c;
char **avp;
bool bslashmode;
bool route_syntax;
int cmntcnt;
int anglecnt;
char *tok;
int state;
int newstate;
static bool firsttime = true;
if (firsttime)
{
/* initialize the token type table */
char obuf[50];
firsttime = false;
if (OperatorChars == NULL)
{
if (ConfigLevel < 7)
if (OperatorChars == NULL)
OperatorChars = ".:@[]";
}
CurEnv);
for (p = obuf; *p != '\0'; p++)
{
}
}
/* make sure error messages don't have garbage on them */
errno = 0;
q = pvpbuf;
bslashmode = false;
route_syntax = false;
cmntcnt = 0;
anglecnt = 0;
c = NOCHAR;
p = addr;
{
sm_dprintf("prescan: ");
xputs(sm_debug_file(), p);
sm_dprintf("\n");
}
do
{
/* read a token */
tok = q;
for (;;)
{
/* store away any old lookahead character */
if (c != NOCHAR && !bslashmode)
{
/* see if there is room */
{
usrerr("553 5.1.1 Address too long");
{
if (p > addr)
--p;
*delimptr = p;
}
return NULL;
}
/* squirrel it away */
#if !ALLOW_255
c &= 0x7f;
#endif /* !ALLOW_255 */
*q++ = c;
}
/* read a new input character */
c = (*p++) & 0x00ff;
if (c == '\0')
{
/* diagnose and patch up bad syntax */
if (ignore)
break;
{
usrerr("553 Unbalanced '\"'");
c = '"';
}
else if (cmntcnt > 0)
{
usrerr("553 Unbalanced '('");
c = ')';
}
else if (anglecnt > 0)
{
c = '>';
usrerr("553 Unbalanced '<'");
}
else
break;
p--;
}
{
if (anglecnt <= 0)
break;
/* special case for better error management */
{
usrerr("553 Unbalanced '<'");
c = '>';
p--;
}
}
/* chew up special characters */
*q = '\0';
if (bslashmode)
{
bslashmode = false;
/* kludge \! for naive users */
if (cmntcnt > 0)
{
c = NOCHAR;
continue;
}
{
/* see if there is room */
goto addrtoolong;
*q++ = '\\';
continue;
}
}
if (c == '\\')
{
bslashmode = true;
}
{
/* EMPTY */
/* do nothing, just avoid next clauses */
}
{
cmntcnt++;
c = NOCHAR;
}
{
if (cmntcnt <= 0)
{
if (!ignore)
{
usrerr("553 Unbalanced ')'");
c = NOCHAR;
}
}
else
cmntcnt--;
}
else if (cmntcnt > 0)
{
c = NOCHAR;
}
else if (c == '<')
{
char *ptr = p;
anglecnt++;
ptr++;
if (*ptr == '@')
route_syntax = true;
}
else if (c == '>')
{
if (anglecnt <= 0)
{
if (!ignore)
{
usrerr("553 Unbalanced '>'");
c = NOCHAR;
}
}
else
anglecnt--;
route_syntax = false;
}
c = ' ';
if (c == NOCHAR)
continue;
/* see if this is end of input */
break;
{
usrerr("553 Illegal character %c", c);
else
usrerr("553 Illegal character 0x%02x",
c & 0x0ff);
}
c = NOCHAR;
break;
}
/* new token */
if (tok != q)
{
/* see if there is room */
goto addrtoolong;
*q++ = '\0';
{
sm_dprintf("tok=");
sm_dprintf("\n");
}
{
usrerr("553 5.1.0 prescan: too many tokens");
goto returnnull;
}
{
usrerr("553 5.1.0 prescan: token too long");
goto returnnull;
}
}
{
if (p > addr)
p--;
*delimptr = p;
}
{
sm_dprintf("prescan==>");
}
{
sm_dprintf("prescan: null leading token\n");
return NULL;
}
return av;
}
/*
** REWRITE -- apply rewrite rules to token vector.
**
** This routine is an ordered production system. Each rewrite
** rule has a LHS (called the pattern) and a RHS (called the
** rewrite); 'rwr' points the the current rewrite rule.
**
** For each rewrite rule, 'avp' points the address vector we
** are trying to match against, and 'pvp' points to the pattern.
** If pvp points to a special match value (MATCHZANY, MATCHANY,
** MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
** matched is saved away in the match vector (pointed to by 'mvp').
**
** When a match between avp & pvp does not match, we try to
** back out. If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
** we must also back out the match in mvp. If we reach a
** MATCHANY or MATCHZANY we just extend the match and start
** over again.
**
** When we finally match, we rewrite the address vector
** and try over again.
**
** Parameters:
** pvp -- pointer to token vector.
** ruleset -- the ruleset to use for rewriting.
** reclevel -- recursion level (to catch loops).
** e -- the current envelope.
** maxatom -- maximum length of buffer (usually MAXATOM)
**
** Returns:
** A status code. If EX_TEMPFAIL, higher level code should
** attempt recovery.
**
** Side Effects:
** pvp is modified.
*/
struct match
{
char **match_first; /* first token matched */
char **match_last; /* last token matched */
char **match_pattern; /* pointer to pattern */
};
int
char **pvp;
int ruleset;
int reclevel;
register ENVELOPE *e;
int maxatom;
{
register char *ap; /* address pointer */
register char *rp; /* rewrite pointer */
register char *rulename; /* ruleset name */
register char *prefix;
register char **avp; /* address vector pointer */
register char **rvp; /* rewrite vector pointer */
int ruleno; /* current rule number */
int loopcount;
char name[6];
/*
** mlp will not exceed mlist[] because readcf enforces
** the upper limit of entries when reading rulesets.
*/
{
return EX_CONFIG;
}
{
}
prefix = "";
else
prefix = "rewrite: ruleset ";
{
}
{
}
if (reclevel++ > MaxRuleRecursion)
{
syserr("rewrite: excessive recursion (max %d), ruleset %s",
return EX_CONFIG;
}
return EX_USAGE;
if (maxatom <= 0)
return EX_USAGE;
/*
** Run through the list of rewrite rules, applying
** any that match.
*/
ruleno = 1;
loopcount = 0;
{
int status;
/* if already canonical, quit now */
break;
{
sm_dprintf("-----trying rule (line %d):",
else
sm_dprintf("-----trying rule:");
}
/* try to match on this rule */
if (++loopcount > 100)
{
syserr("554 5.3.5 Infinite loop in ruleset %s, rule %d",
{
sm_dprintf("workspace: ");
}
break;
}
{
{
sm_dprintf("ADVANCE rp=");
sm_dprintf(", ap=");
sm_dprintf("\n");
}
{
/* end-of-pattern before end-of-address */
goto backup;
}
{
/* end-of-input with patterns left */
goto backup;
}
switch (rp[0] & 0377)
{
case MATCHCLASS:
/* match any phrase in a class */
goto backup;
{
{
sm_dprintf("EXTEND rp=");
sm_dprintf(", ap=");
sm_dprintf("\n");
}
goto extendclass;
}
sm_dprintf("CLMATCH\n");
mlp++;
break;
case MATCHNCLASS:
/* match any token not in a class */
goto backup;
/* FALLTHROUGH */
case MATCHONE:
case MATCHANY:
/* match exactly one token */
mlp++;
break;
case MATCHZANY:
/* match zero or more tokens */
mlp++;
break;
case MATCHZERO:
/* match zero tokens */
break;
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.
*/
sm_dprintf("rewrite: LHS $&{%s} => \"%s\"\n",
break;
while (*ap != '\0')
{
{
/* no match */
goto backup;
}
}
/* match */
break;
default:
/* must have exact match */
goto backup;
avp++;
break;
}
/* successful match on this token */
rvp++;
continue;
/* match failed -- back up */
{
{
sm_dprintf("BACKUP rp=");
sm_dprintf(", ap=");
sm_dprintf("\n");
}
{
/* run off the end -- back up again */
continue;
}
{
/* extend binding and continue */
rvp++;
mlp++;
break;
}
{
/* extend binding and try again */
goto extendclass;
}
}
{
/* total failure to match */
break;
}
}
/*
** See if we successfully matched
*/
{
sm_dprintf("----- rule fails\n");
ruleno++;
loopcount = 0;
continue;
}
{
sm_dprintf("-----rule matches:");
}
{
{
rvp++;
ruleno++;
loopcount = 0;
}
{
rvp++;
}
}
/* substitute */
{
register struct match *m;
register char **pp;
{
/* substitute from LHS */
{
syserr("554 5.3.5 rewrite: ruleset %s: replacement $%c out of bounds",
return EX_CONFIG;
}
{
pp = m->match_first;
while (pp <= m->match_last)
{
sm_dflush();
}
sm_dprintf("\n");
}
pp = m->match_first;
while (pp <= m->match_last)
{
goto toolong;
}
}
else
{
/* some sort of replacement */
{
syserr("554 5.3.0 rewrite: expansion too long");
if (LogLevel > 9)
"rewrite: expansion too long, ruleset=%s, ruleno=%d",
return EX_DATAERR;
}
{
/* vanilla replacement from RHS */
}
else
{
/* $&{x} replacement */
char **xpvp;
static size_t pvpb1_size = 0;
sm_dprintf("rewrite: RHS $&{%s} => \"%s\"\n",
continue;
/* save the remainder of the input */
if (trsize > pvpb1_size)
{
pvpb1 = (char **)
pvpb1_size = trsize;
}
(char *) pvp,
trsize);
/* scan the new replacement */
NULL, false);
{
/* prescan pre-printed error */
return EX_DATAERR;
}
/* insert it into the output stream */
{
sm_dprintf(" ... %s\n",
*xpvp);
*avp++ = sm_rpool_strdup_x(
goto toolong;
xpvp++;
}
sm_dprintf(" ... DONE\n");
/* restore the old trailing input */
(char *) pvpb1,
trsize);
}
}
}
/*
*/
{
char **hbrvp;
char **xpvp;
char *replac;
int endtoken;
bool external;
char *mapname;
char **key_rvp;
char **arg_rvp;
char **default_rvp;
char *argvect[MAX_MAP_ARGS];
char *nullpvp[1];
{
mapname = "host";
}
{
{
syserr("554 5.3.0 rewrite: missing mapname");
/* NOTREACHED */
SM_ASSERT(0);
}
}
else
continue;
/*
**
** This could be optimized fairly easily.
*/
syserr("554 5.3.0 rewrite: map %s not found",
mapname);
/* extract the match part */
{
syserr("554 5.3.0 rewrite: missing key for map %s",
mapname);
/* NOTREACHED */
SM_ASSERT(0);
}
default_rvp = NULL;
{
{
rvp++;
continue;
}
{
'\0', false);
if (arg_rvp <
}
switch (nodetype)
{
case CANONHOST:
break;
case CANONUSER:
default_rvp = rvp;
break;
}
}
{
'\0', false);
}
else
/* save the remainder of the input string */
/* look it up */
true);
/* if no replacement, use default */
{
/* create the default */
'\0', false);
}
{
}
else if (*replac == '\0')
{
/* null replacement */
}
else
{
/* scan the new replacement */
false);
{
/* prescan already printed error */
return EX_DATAERR;
}
}
/* append it to the token list */
{
goto toolong;
}
/* restore the old trailing information */
goto toolong;
}
/*
** Check for subroutine calls.
*/
/* copy vector back into original space. */
continue;
{
sm_dprintf("rewritten as:");
}
}
{
}
{
}
return rstat;
}
/*
** CALLSUBR -- call subroutines in rewrite vector
**
** Parameters:
** pvp -- pointer to token vector.
** reclevel -- the current recursion level.
** e -- the current envelope.
**
** Returns:
** The status from the subroutine call.
**
** Side Effects:
** pvp is modified.
*/
static int
char **pvp;
int reclevel;
ENVELOPE *e;
{
char **avp;
register int i;
int subr, j;
int nsubr;
int status;
#define MAX_SUBR 16
int subrnumber[MAX_SUBR];
nsubr = 0;
/*
** Look for subroutine calls in pvp, collect them into subr*[]
** We will perform the calls in the next loop, because we will
** call the "last" subroutine first to avoid recursive calls
** and too much copying.
*/
{
{
if (subr < 0)
{
return EX_CONFIG;
}
/*
** XXX instead of doing this we could optimize
** the rules after reading them: just remove
** calls to empty rulesets
*/
/* subroutine is an empty ruleset? don't call it */
{
sm_dprintf("-----skip subr %s (%d)\n",
continue;
}
{
syserr("554 5.3.0 Too many subroutine calls (%d max)",
MAX_SUBR);
return EX_CONFIG;
}
}
}
/*
** Perform the actual subroutines calls, "last" one first, i.e.,
** go from the right to the left through all calls,
** do the rewriting in place.
*/
{
/* remove the subroutine call and name */
/*
** Now we need to call the ruleset specified for
** the subroutine. We can do this in place since
** we call the "last" subroutine first.
*/
return status;
}
return rstat;
}
/*
** MAP_LOOKUP -- do lookup in map
**
** Parameters:
** smap -- the map to use for the lookup.
** key -- the key to look up.
** argvect -- arguments to pass to the map lookup.
** pstat -- a pointer to an integer in which to store the
** status from the lookup.
** e -- the current envelope.
**
** Returns:
** The result of the lookup.
** NULL -- if there was no data for the given key.
*/
static char *
char key[];
char **argvect;
int *pstat;
ENVELOPE *e;
{
char *replac;
return NULL;
if (e->e_sendmode == SM_DEFER &&
{
/* don't do any map lookups */
sm_dprintf("map_lookup(%s, %s) => DEFERRED\n",
*pstat = EX_TEMPFAIL;
return NULL;
}
{
{
int i;
}
sm_dprintf(") => ");
}
sm_dprintf("%s (%d)\n",
status);
/* should recover if status == EX_TEMPFAIL */
{
*pstat = EX_TEMPFAIL;
sm_dprintf("map_lookup(%s, %s) tempfail: errno=%d\n",
{
char mbuf[320];
"%.80s map: lookup (%s): deferred",
}
}
{
if (i > rwbuflen)
{
rwbuflen = i;
}
sm_dprintf("map_lookup tempfail: returning \"%s\"\n",
rwbuf);
return rwbuf;
}
return replac;
}
/*
** INITERRMAILERS -- initialize error and discard mailers
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** initializes error and discard mailers.
*/
static MAILER discardmailer;
static MAILER errormailer;
void
{
{
/* initialize the discard mailer */
}
{
/* initialize the bogus mailer */
}
}
/*
** BUILDADDR -- build address from token vector.
**
** Parameters:
** 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.
** 'a' otherwise.
**
** Side Effects:
** fills in 'a'
*/
static struct errcodes
{
char *ec_name; /* name of error code */
int ec_code; /* numeric code */
} ErrorCodes[] =
{
{ "usage", EX_USAGE },
{ "nouser", EX_NOUSER },
{ "nohost", EX_NOHOST },
{ "unavailable", EX_UNAVAILABLE },
{ "software", EX_SOFTWARE },
{ "tempfail", EX_TEMPFAIL },
{ "protocol", EX_PROTOCOL },
{ "config", EX_CONFIG },
{ NULL, EX_UNAVAILABLE }
};
static ADDRESS *
register char **tv;
register ADDRESS *a;
int flags;
register ENVELOPE *e;
{
bool tempfail = false;
int maxatom;
register struct mailer *m;
register char *p;
char *mname;
char **hostp;
{
}
if (a == NULL)
memset((char *) a, '\0', sizeof(*a));
hbuf[0] = '\0';
/* set up default error return flags */
a->q_flags |= DefaultNotify;
{
syserr("554 5.3.5 buildaddr: no mailer in parsed address");
/*
** ExitStat may have been set by an earlier map open
** failure (to a permanent error (EX_OSERR) in syserr())
** so we also need to check if this particular $#error
** return wanted a 4XX failure.
**
** XXX the real fix is probably to set ExitStat correctly,
** i.e., to EX_TEMPFAIL if the map open is just a temporary
** error.
*/
a->q_state = QS_QUEUEUP;
else
{
a->q_state = QS_BADADDR;
a->q_mailer = &errormailer;
}
return a;
}
--maxatom;
/* extract host and user portions */
{
--maxatom;
}
else
--maxatom;
{
tv++;
--maxatom;
}
{
syserr("554 5.3.5 buildaddr: no user");
goto badaddr;
}
--maxatom;
/* save away the host name */
{
/* Set up triplet for use by -bv */
a->q_mailer = &errormailer;
/* XXX wrong place? */
{
{
hbuf);
}
{
}
else
{
break;
}
}
else
{
}
{
char fmt[16];
int off;
{
off += 5;
}
else
{
off = 4;
}
if (off > 4)
else
/* XXX ubuf[off - 1] = ' '; */
if (ubuf[0] == '4')
tempfail = true;
}
else
{
}
goto badaddr;
}
{
break;
}
if (m == NULL)
{
goto badaddr;
}
a->q_mailer = m;
/* figure out what host (if any) */
{
{
syserr("554 5.3.5 buildaddr: no host");
goto badaddr;
}
}
else
/* figure out the user */
p = ubuf;
{
p++;
tv++;
--maxatom;
a->q_flags |= QNOTREMOTE;
}
/* do special mapping for local mailer */
if (*p == '"')
p++;
a->q_mailer = m = ProgMailer;
a->q_mailer = m = FileMailer;
{
/* may be :include: */
{
/* if :include:, don't need further rewriting */
a->q_mailer = m = InclMailer;
return a;
}
}
/* rewrite according recipient mailer rewriting rules */
if (ConfigLevel >= 10 ||
{
/* sender addresses done later */
if (m->m_re_rwset > 0)
}
/*
** Do mapping to lower case as requested by mailer
*/
{
sm_dprintf("buildaddr => ");
printaddr(sm_debug_file(), a, false);
}
return a;
}
/*
** CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
**
** 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.
** spacesub -- the space separator character; if '\0',
** use SpaceSub.
** external -- convert to external form?
** (no metacharacters; METAQUOTEs removed, see below)
**
** Returns:
** none.
**
** Side Effects:
** Destroys buf.
**
** Notes:
** There are two formats for strings: internal and external.
** The external format is just an eight-bit clean string (no
** null bytes, everything else OK). The internal format can
** include sendmail metacharacters. The special character
** METAQUOTE essentially quotes the character following, stripping
** it of all special semantics.
**
** The cataddr routine needs to be aware of whether it is producing
** an internal or external form as output (it only takes internal
** form as input).
**
** The parseaddr routine has a similar issue on input, but that
** is flagged on the basis of which token table is passed in.
*/
void
char **pvp;
char **evp;
char *buf;
register int sz;
int spacesub;
bool external;
{
char *p;
{
}
if (sz <= 0)
return;
if (spacesub == '\0')
{
*buf = '\0';
return;
}
p = buf;
sz -= 2;
{
char *q;
{
*p++ = spacesub;
if (--sz <= 0)
break;
}
for (q = *pvp; *q != '\0'; )
{
int c;
if (--sz <= 0)
break;
*p++ = c = *q++;
/*
** If the current character (c) is METAQUOTE and we
** want the "external" form and the next character
** is not NUL, then overwrite METAQUOTE with that
** character (i.e., METAQUOTE ch is changed to
** ch). p[-1] is used because p is advanced (above).
*/
p[-1] = *q++;
}
if (sz <= 0)
break;
break;
}
#if 0
/*
** Silently truncate long strings: even though this doesn't
** seem like a good idea it is necessary because header checks
** send the whole header value to rscheck() and hence rewrite().
** The latter however sometimes uses a "short" buffer (e.g.,
** cbuf[MAXNAME + 1]) to call cataddr() which then triggers this
** error function. One possible fix to the problem is to pass
** flags to rscheck() and rewrite() to distinguish the various
** calls and only trigger the error if necessary. For now just
** undo the change from 8.13.0.
*/
if (sz <= 0)
usrerr("cataddr: string too long");
#endif
*p = '\0';
}
/*
** SAMEADDR -- Determine if two addresses are the same
**
** This is not just a straight comparison -- if the mailer doesn't
** care about the host we just ignore it, etc.
**
** Parameters:
** a, b -- pointers to the internal forms to compare.
**
** Returns:
** true -- they represent the same mailbox.
** false -- they don't.
**
** Side Effects:
** none.
*/
bool
sameaddr(a, b)
register ADDRESS *a;
register ADDRESS *b;
{
/* if they don't have the same mailer, forget it */
return false;
/* if the user isn't the same, we can drop out */
return false;
/* if we have good uids for both but they differ, these are different */
if (a->q_mailer == ProgMailer)
{
ca = getctladdr(a);
cb = getctladdr(b);
return false;
}
/* otherwise compare hosts (but be careful for NULL ptrs) */
{
/* probably both null pointers */
return true;
}
{
/* only one is a null pointer */
return false;
}
return false;
return true;
}
/*
** PRINTADDR -- print address (for debugging)
**
** Parameters:
** a -- the address to print
** follow -- follow the q_next chain.
**
** Returns:
** none.
**
** Side Effects:
** none.
*/
struct qflags
{
char *qf_name;
unsigned long qf_bit;
};
static struct qflags AddressFlags[] =
{
{ "QGOODUID", QGOODUID },
{ "QPRIMARY", QPRIMARY },
{ "QNOTREMOTE", QNOTREMOTE },
{ "QSELFREF", QSELFREF },
{ "QBOGUSSHELL", QBOGUSSHELL },
{ "QUNSAFEADDR", QUNSAFEADDR },
{ "QPINGONSUCCESS", QPINGONSUCCESS },
{ "QPINGONFAILURE", QPINGONFAILURE },
{ "QPINGONDELAY", QPINGONDELAY },
{ "QHASNOTIFY", QHASNOTIFY },
{ "QRELAYED", QRELAYED },
{ "QEXPANDED", QEXPANDED },
{ "QDELIVERED", QDELIVERED },
{ "QDELAYED", QDELAYED },
{ "QTHISPASS", QTHISPASS },
{ "QRCPTOK", QRCPTOK },
{ NULL, 0 }
};
void
register ADDRESS *a;
bool follow;
{
register MAILER *m;
bool firstone;
if (a == NULL)
{
return;
}
while (a != NULL)
{
/* find the mailer -- carefully */
m = a->q_mailer;
if (m == NULL)
{
m = &pseudomailer;
m->m_mno = -1;
m->m_name = "NULL";
}
"%s:\n\tmailer %d (%s), host `%s'\n",
"\tuser `%s', ruser `%s'\n",
a->q_user,
switch (a->q_state)
{
case QS_OK:
break;
case QS_DONTSEND:
"DONTSEND");
break;
case QS_BADADDR:
"BADADDR");
break;
case QS_QUEUEUP:
"QUEUEUP");
break;
case QS_RETRY:
break;
case QS_SENT:
break;
case QS_VERIFIED:
"VERIFIED");
break;
case QS_EXPANDED:
"EXPANDED");
break;
case QS_SENDER:
"SENDER");
break;
case QS_CLONED:
"CLONED");
break;
case QS_DISCARDED:
"DISCARDED");
break;
case QS_REPLACED:
"REPLACED");
break;
case QS_REMOVED:
"REMOVED");
break;
case QS_DUPLICATE:
"DUPLICATE");
break;
case QS_INCLUDED:
"INCLUDED");
break;
default:
"%d", a->q_state);
break;
}
", next=%p, alias %p, uid %d, gid %d\n",
a->q_flags);
firstone = true;
{
continue;
if (!firstone)
",");
firstone = false;
}
"\towner=%s, home=\"%s\", fullname=\"%s\"\n",
"\torcpt=\"%s\", statmta=%s, status=%s\n",
"\tfinalrcpt=\"%s\"\n",
"\trstatus=\"%s\"\n",
"\tstatdate=%s\n",
if (!follow)
return;
a = a->q_next;
}
}
/*
** 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;
{
}
/*
** REMOTENAME -- return the name relative to the current mailer
**
** Parameters:
** name -- the name to translate.
** m -- the mailer that we want to do rewriting relative to.
** flags -- fine tune operations.
** pstat -- pointer to status word.
** e -- the current envelope.
**
** Returns:
** the text string representing this address relative to
** the receiving mailer.
**
** Side Effects:
** none.
**
** Warnings:
** The text string returned is tucked away locally;
** copy it if you intend to save it.
*/
char *
char *name;
struct mailer *m;
int flags;
int *pstat;
register ENVELOPE *e;
{
register char **pvp;
char *SM_NONVOLATILE fancy;
char *oldg;
int rwset;
char addrtype[4];
{
sm_dprintf("remotename(");
sm_dprintf(")\n");
}
/* don't do anything if we are tagging it as special */
{
: m->m_se_rwset;
}
else
{
: m->m_re_rwset;
}
if (rwset < 0)
return name;
/*
** Do a heuristic crack of this name to extract any comment info.
** This will leave the name as a comment and a $g macro.
*/
fancy = "\201g";
else
/*
** Turn the name into canonical form.
** Normally this will be RFC 822 style, i.e., "user@domain".
** If this only resolves to "user", and the "C" flag is
** specified in the sending mailer, then the sender's
** domain will be appended.
*/
return name;
*pstat = EX_TEMPFAIL;
{
/* append from domain to this address */
int l = MAXATOM; /* size of buffer for pvp */
/* see if there is an "@domain" in the current name */
{
pxp++;
--l;
}
{
/* no.... append the "@domain" from the sender */
register char **qxq = e->e_fromdomain;
{
if (--l <= 0)
{
usrerr("553 5.1.0 remotename: too many tokens");
*pstat = EX_UNAVAILABLE;
break;
}
}
*pstat = EX_TEMPFAIL;
}
}
/*
** Do more specific rewriting.
** Rewrite using ruleset 1 or 2 depending on whether this is
** a sender address or not.
** Then run it through any receiving-mailer-specific rulesets.
*/
{
*pstat = EX_TEMPFAIL;
}
else
{
*pstat = EX_TEMPFAIL;
}
if (rwset > 0)
{
*pstat = EX_TEMPFAIL;
}
/*
** Do any final sanitation the address may require.
** This will normally be used to turn internal forms
** (e.g., user@host.LOCAL) into external form. This
** may be used as a default to the above rules.
*/
*pstat = EX_TEMPFAIL;
/*
** Now restore the comment information we had at the beginning.
*/
/* need to make sure route-addrs have <angle brackets> */
else
{
sm_dprintf("remotename => `");
sm_dprintf("'\n");
}
return buf;
}
/*
** MAPLOCALUSER -- run local username through ruleset 5 for final redirection
**
** Parameters:
** a -- the address to map (but just the user name part).
** sendq -- the sendq in which to install any replacement
** addresses.
** aliaslevel -- the alias nesting depth.
** e -- the envelope.
**
** Returns:
** none.
*/
void
register ADDRESS *a;
int aliaslevel;
ENVELOPE *e;
{
register char **pvp;
{
sm_dprintf("maplocaluser: ");
printaddr(sm_debug_file(), a, false);
}
false);
{
sm_dprintf("maplocaluser: cannot prescan %s\n",
a->q_user);
return;
}
{
sm_dprintf("maplocaluser: rewrite tempfail\n");
a->q_state = QS_QUEUEUP;
a->q_status = "4.4.3";
return;
}
{
sm_dprintf("maplocaluser: doesn't resolve\n");
return;
}
/*
** mark address as bad, S5 returned an error
** and we gave that back to the SMTP client.
*/
a->q_state = QS_DONTSEND;
/* if non-null, mailer destination specified -- has it changed? */
{
sm_dprintf("maplocaluser: address unchanged\n");
return;
}
/* make new address take on flags and print attributes of old */
/* mark old address as dead; insert new address */
a->q_state = QS_REPLACED;
{
sm_dprintf("maplocaluser: QS_REPLACED ");
printaddr(sm_debug_file(), a, false);
}
}
/*
** DEQUOTE_INIT -- initialize dequote map
**
** Parameters:
** map -- the internal map structure.
** args -- arguments.
**
** Returns:
** true.
*/
bool
char *args;
{
register char *p = args;
/* there is no check whether there is really an argument */
for (;;)
{
p++;
if (*p != '-')
break;
switch (*++p)
{
case 'a':
break;
case 'D':
break;
case 'S':
case 's':
map->map_spacesub = *++p;
break;
}
p++;
if (*p != '\0')
*p = '\0';
}
return true;
}
/*
** 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.
*/
/* ARGSUSED2 */
char *
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;
for (p = q = name; (c = *p++) != '\0'; )
{
if (bslashmode)
{
bslashmode = false;
*q++ = c;
continue;
}
c = spacesub;
switch (c)
{
case '\\':
bslashmode = true;
break;
case '(':
cmntcnt++;
break;
case ')':
if (cmntcnt-- <= 0)
return NULL;
break;
case ' ':
case '\t':
spacecnt++;
break;
}
if (cmntcnt > 0)
{
*q++ = c;
continue;
}
switch (c)
{
case '"':
quotecnt++;
continue;
case '<':
anglecnt++;
break;
case '>':
if (anglecnt-- <= 0)
return NULL;
break;
}
*q++ = c;
}
return NULL;
*q++ = '\0';
}
/*
** RSCHECK -- check string(s) for validity using rewriting sets
**
** Parameters:
** rwset -- the rewriting set to use.
** p1 -- the first string to check.
** p2 -- the second string to check -- may be null.
** e -- the current envelope.
** flags -- control some behavior, see RSF_ in sendmail.h
** logl -- logging level.
** host -- NULL or relay host.
** logid -- id for sm_syslog.
** addr -- if not NULL and ruleset returns $#error:
** store mailer triple here.
**
** Returns:
** EX_OK -- if the rwset doesn't resolve to $#error
** else -- the failure status (message printed)
*/
int
char *rwset;
char *p1;
char *p2;
ENVELOPE *e;
int flags;
int logl;
char *host;
char *logid;
{
char *volatile buf;
int saveexitstat;
char **pvp;
int rsno;
bool volatile discard = false;
bool saveQuickAbort = QuickAbort;
bool saveSuprErrs = SuprErrs;
bool quarantine = false;
extern char MsgBuf[];
if (rsno < 0)
return EX_OK;
{
else
{
}
}
else
{
else
{
}
}
{
SuprErrs = true;
QuickAbort = false;
{
sm_dprintf("rscheck: cannot prescan input\n");
/*
syserr("rscheck: cannot prescan input: \"%s\"",
shortenstring(buf, MAXSHORTSTR));
rstat = EX_DATAERR;
*/
goto finis;
}
SuprErrs = true;
{
goto finis;
}
{
sm_dprintf("rscheck: discard mailer selected\n");
e->e_flags |= EF_DISCARD;
discard = true;
}
{
rwset);
else
{
sizeof(ubuf), ' ', true);
ubuf);
}
quarantine = true;
}
else
{
int savelogusrerrs = LogUsrErrs;
static bool logged = false;
/* got an error -- process it */
LogUsrErrs = false;
{
}
if (!logged)
{
logged = true;
}
}
{
char *relay;
char *p;
p = lbuf;
{
", arg2=%s",
p2);
p += strlen(p);
}
else
{
", relay=%s", relay);
p += strlen(p);
}
*p = '\0';
if (discard)
"ruleset=%s, arg1=%s%s, discard",
else if (quarantine)
"ruleset=%s, arg1=%s%s, quarantine=%s",
else
"ruleset=%s, arg1=%s%s, reject=%s",
}
finis: ;
}
{
/* clean up */
}
/* rulesets don't set errno */
errno = 0;
return rstat;
}
/*
** RSCAP -- call rewriting set to return capabilities
**
** Parameters:
** rwset -- the rewriting set to use.
** p1 -- the first string to check.
** p2 -- the second string to check -- may be null.
** e -- the current envelope.
** pvp -- pointer to token vector.
** pvpbuf -- buffer space.
** size -- size of buffer space.
**
** Returns:
** EX_UNAVAILABLE -- ruleset doesn't exist.
** EX_DATAERR -- prescan() failed.
** EX_OK -- rewrite() was successful.
** else -- return status from rewrite().
*/
int
char *rwset;
char *p1;
char *p2;
ENVELOPE *e;
char ***pvp;
char *pvpbuf;
int size;
{
char *volatile buf;
int rsno;
bool saveQuickAbort = QuickAbort;
bool saveSuprErrs = SuprErrs;
extern char MsgBuf[];
if (rsno < 0)
return EX_UNAVAILABLE;
{
else
{
}
}
else
{
else
{
}
}
{
SuprErrs = true;
QuickAbort = false;
false);
else
{
sm_dprintf("rscap: cannot prescan input\n");
rstat = EX_DATAERR;
}
}
{
/* clean up */
/* prevent information leak, this may contain rewrite error */
MsgBuf[0] = '\0';
}
return rstat;
}