parseaddr.c revision 102528
1/*
2 * Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers.
3 *	All rights reserved.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5 * Copyright (c) 1988, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
11 *
12 */
13
14#include <sendmail.h>
15
16SM_RCSID("@(#)$Id: parseaddr.c,v 8.359.2.2 2002/08/16 14:56:01 ca Exp $")
17
18static void	allocaddr __P((ADDRESS *, int, char *, ENVELOPE *));
19static int	callsubr __P((char**, int, ENVELOPE *));
20static char	*map_lookup __P((STAB *, char *, char **, int *, ENVELOPE *));
21static ADDRESS	*buildaddr __P((char **, ADDRESS *, int, ENVELOPE *));
22static bool	hasctrlchar __P((register char *, bool, bool));
23
24/* replacement for illegal characters in addresses */
25#define BAD_CHAR_REPLACEMENT	'?'
26
27/*
28**  PARSEADDR -- Parse an address
29**
30**	Parses an address and breaks it up into three parts: a
31**	net to transmit the message on, the host to transmit it
32**	to, and a user on that host.  These are loaded into an
33**	ADDRESS header with the values squirreled away if necessary.
34**	The "user" part may not be a real user; the process may
35**	just reoccur on that machine.  For example, on a machine
36**	with an arpanet connection, the address
37**		csvax.bill@berkeley
38**	will break up to a "user" of 'csvax.bill' and a host
39**	of 'berkeley' -- to be transmitted over the arpanet.
40**
41**	Parameters:
42**		addr -- the address to parse.
43**		a -- a pointer to the address descriptor buffer.
44**			If NULL, an address will be created.
45**		flags -- describe detail for parsing.  See RF_ definitions
46**			in sendmail.h.
47**		delim -- the character to terminate the address, passed
48**			to prescan.
49**		delimptr -- if non-NULL, set to the location of the
50**			delim character that was found.
51**		e -- the envelope that will contain this address.
52**		isrcpt -- true if the address denotes a recipient; false
53**			indicates a sender.
54**
55**	Returns:
56**		A pointer to the address descriptor header (`a' if
57**			`a' is non-NULL).
58**		NULL on error.
59**
60**	Side Effects:
61**		e->e_to = addr
62*/
63
64/* following delimiters are inherent to the internal algorithms */
65#define DELIMCHARS	"()<>,;\r\n"	/* default word delimiters */
66
67ADDRESS *
68parseaddr(addr, a, flags, delim, delimptr, e, isrcpt)
69	char *addr;
70	register ADDRESS *a;
71	int flags;
72	int delim;
73	char **delimptr;
74	register ENVELOPE *e;
75	bool isrcpt;
76{
77	char **pvp;
78	auto char *delimptrbuf;
79	bool qup;
80	char pvpbuf[PSBUFSIZE];
81
82	/*
83	**  Initialize and prescan address.
84	*/
85
86	e->e_to = addr;
87	if (tTd(20, 1))
88		sm_dprintf("\n--parseaddr(%s)\n", addr);
89
90	if (delimptr == NULL)
91		delimptr = &delimptrbuf;
92
93	pvp = prescan(addr, delim, pvpbuf, sizeof pvpbuf, delimptr, NULL);
94	if (pvp == NULL)
95	{
96		if (tTd(20, 1))
97			sm_dprintf("parseaddr-->NULL\n");
98		return NULL;
99	}
100
101	if (invalidaddr(addr, delim == '\0' ? NULL : *delimptr, isrcpt))
102	{
103		if (tTd(20, 1))
104			sm_dprintf("parseaddr-->bad address\n");
105		return NULL;
106	}
107
108	/*
109	**  Save addr if we are going to have to.
110	**
111	**	We have to do this early because there is a chance that
112	**	the map lookups in the rewriting rules could clobber
113	**	static memory somewhere.
114	*/
115
116	if (bitset(RF_COPYPADDR, flags) && addr != NULL)
117	{
118		char savec = **delimptr;
119
120		if (savec != '\0')
121			**delimptr = '\0';
122		e->e_to = addr = sm_rpool_strdup_x(e->e_rpool, addr);
123		if (savec != '\0')
124			**delimptr = savec;
125	}
126
127	/*
128	**  Apply rewriting rules.
129	**	Ruleset 0 does basic parsing.  It must resolve.
130	*/
131
132	qup = false;
133	if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
134		qup = true;
135	if (REWRITE(pvp, 0, e) == EX_TEMPFAIL)
136		qup = true;
137
138	/*
139	**  Build canonical address from pvp.
140	*/
141
142	a = buildaddr(pvp, a, flags, e);
143
144	if (hasctrlchar(a->q_user, isrcpt, true))
145	{
146		if (tTd(20, 1))
147			sm_dprintf("parseaddr-->bad q_user\n");
148
149		/*
150		**  Just mark the address as bad so DSNs work.
151		**  hasctrlchar() has to make sure that the address
152		**  has been sanitized, e.g., shortened.
153		*/
154
155		a->q_state = QS_BADADDR;
156	}
157
158	/*
159	**  Make local copies of the host & user and then
160	**  transport them out.
161	*/
162
163	allocaddr(a, flags, addr, e);
164	if (QS_IS_BADADDR(a->q_state))
165	{
166		/* weed out bad characters in the printable address too */
167		(void) hasctrlchar(a->q_paddr, isrcpt, false);
168		return a;
169	}
170
171	/*
172	**  Select a queue directory for recipient addresses.
173	**	This is done here and in split_across_queue_groups(),
174	**	but the latter applies to addresses after aliasing,
175	**	and only if splitting is done.
176	*/
177
178	if ((a->q_qgrp == NOAQGRP || a->q_qgrp == ENVQGRP) &&
179	    !bitset(RF_SENDERADDR|RF_HEADERADDR, flags) &&
180	    OpMode != MD_INITALIAS)
181	{
182		int r;
183
184		/* call ruleset which should return a queue group name */
185		r = rscap(RS_QUEUEGROUP, a->q_user, NULL, e, &pvp, pvpbuf,
186			  sizeof(pvpbuf));
187		if (r == EX_OK &&
188		    pvp != NULL && pvp[0] != NULL &&
189		    (pvp[0][0] & 0377) == CANONNET &&
190		    pvp[1] != NULL && pvp[1][0] != '\0')
191		{
192			r = name2qid(pvp[1]);
193			if (r == NOQGRP && LogLevel > 10)
194				sm_syslog(LOG_INFO, NOQID,
195					"can't find queue group name %s, selection ignored",
196					pvp[1]);
197			if (tTd(20, 4) && r != NOQGRP)
198				sm_syslog(LOG_INFO, NOQID,
199					"queue group name %s -> %d",
200					pvp[1], r);
201			a->q_qgrp = r == NOQGRP ? ENVQGRP : r;
202		}
203	}
204
205	/*
206	**  If there was a parsing failure, mark it for queueing.
207	*/
208
209	if (qup && OpMode != MD_INITALIAS)
210	{
211		char *msg = "Transient parse error -- message queued for future delivery";
212
213		if (e->e_sendmode == SM_DEFER)
214			msg = "Deferring message until queue run";
215		if (tTd(20, 1))
216			sm_dprintf("parseaddr: queuing message\n");
217		message(msg);
218		if (e->e_message == NULL && e->e_sendmode != SM_DEFER)
219			e->e_message = sm_rpool_strdup_x(e->e_rpool, msg);
220		a->q_state = QS_QUEUEUP;
221		a->q_status = "4.4.3";
222	}
223
224	/*
225	**  Compute return value.
226	*/
227
228	if (tTd(20, 1))
229	{
230		sm_dprintf("parseaddr-->");
231		printaddr(a, false);
232	}
233
234	return a;
235}
236/*
237**  INVALIDADDR -- check for address containing characters used for macros
238**
239**	Parameters:
240**		addr -- the address to check.
241**		delimptr -- if non-NULL: end of address to check, i.e.,
242**			a pointer in the address string.
243**		isrcpt -- true iff the address is for a recipient.
244**
245**	Returns:
246**		true -- if the address has characters that are reservered
247**			for macros or is too long.
248**		false -- otherwise.
249*/
250
251bool
252invalidaddr(addr, delimptr, isrcpt)
253	register char *addr;
254	char *delimptr;
255	bool isrcpt;
256{
257	bool result = false;
258	char savedelim = '\0';
259	char *b = addr;
260	int len = 0;
261
262	if (delimptr != NULL)
263	{
264		/* delimptr points to the end of the address to test */
265		savedelim = *delimptr;
266		if (savedelim != '\0')	/* if that isn't '\0' already: */
267			*delimptr = '\0';	/* set it */
268	}
269	for (; *addr != '\0'; addr++)
270	{
271		if ((*addr & 0340) == 0200)
272		{
273			setstat(EX_USAGE);
274			result = true;
275			*addr = BAD_CHAR_REPLACEMENT;
276		}
277		if (++len > MAXNAME - 1)
278		{
279			char saved = *addr;
280
281			*addr = '\0';
282			usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
283			       b, MAXNAME - 1);
284			*addr = saved;
285			result = true;
286			goto delim;
287		}
288	}
289	if (result)
290	{
291		if (isrcpt)
292			usrerr("501 5.1.3 8-bit character in mailbox address \"%s\"",
293			       b);
294		else
295			usrerr("501 5.1.7 8-bit character in mailbox address \"%s\"",
296			       b);
297	}
298delim:
299	if (delimptr != NULL && savedelim != '\0')
300		*delimptr = savedelim;	/* restore old character at delimptr */
301	return result;
302}
303/*
304**  HASCTRLCHAR -- check for address containing meta-characters
305**
306**  Checks that the address contains no meta-characters, and contains
307**  no "non-printable" characters unless they are quoted or escaped.
308**  Quoted or escaped characters are literals.
309**
310**	Parameters:
311**		addr -- the address to check.
312**		isrcpt -- true if the address is for a recipient; false
313**			indicates a from.
314**		complain -- true if an error should issued if the address
315**			is invalid and should be "repaired".
316**
317**	Returns:
318**		true -- if the address has any "wierd" characters or
319**			non-printable characters or if a quote is unbalanced.
320**		false -- otherwise.
321*/
322
323static bool
324hasctrlchar(addr, isrcpt, complain)
325	register char *addr;
326	bool isrcpt, complain;
327{
328	bool quoted = false;
329	int len = 0;
330	char *result = NULL;
331	char *b = addr;
332
333	if (addr == NULL)
334		return false;
335	for (; *addr != '\0'; addr++)
336	{
337		if (++len > MAXNAME - 1)
338		{
339			if (complain)
340			{
341				(void) shorten_rfc822_string(b, MAXNAME - 1);
342				usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
343				       b, MAXNAME - 1);
344				return true;
345			}
346			result = "too long";
347		}
348		if (!quoted && (*addr < 32 || *addr == 127))
349		{
350			result = "non-printable character";
351			*addr = BAD_CHAR_REPLACEMENT;
352			continue;
353		}
354		if (*addr == '"')
355			quoted = !quoted;
356		else if (*addr == '\\')
357		{
358			/* XXX Generic problem: no '\0' in strings. */
359			if (*++addr == '\0')
360			{
361				result = "trailing \\ character";
362				*--addr = BAD_CHAR_REPLACEMENT;
363				break;
364			}
365		}
366		if ((*addr & 0340) == 0200)
367		{
368			setstat(EX_USAGE);
369			result = "8-bit character";
370			*addr = BAD_CHAR_REPLACEMENT;
371			continue;
372		}
373	}
374	if (quoted)
375		result = "unbalanced quote"; /* unbalanced quote */
376	if (result != NULL && complain)
377	{
378		if (isrcpt)
379			usrerr("501 5.1.3 Syntax error in mailbox address \"%s\" (%s)",
380			       b, result);
381		else
382			usrerr("501 5.1.7 Syntax error in mailbox address \"%s\" (%s)",
383			       b, result);
384	}
385	return result != NULL;
386}
387/*
388**  ALLOCADDR -- do local allocations of address on demand.
389**
390**	Also lowercases the host name if requested.
391**
392**	Parameters:
393**		a -- the address to reallocate.
394**		flags -- the copy flag (see RF_ definitions in sendmail.h
395**			for a description).
396**		paddr -- the printname of the address.
397**		e -- envelope
398**
399**	Returns:
400**		none.
401**
402**	Side Effects:
403**		Copies portions of a into local buffers as requested.
404*/
405
406static void
407allocaddr(a, flags, paddr, e)
408	register ADDRESS *a;
409	int flags;
410	char *paddr;
411	ENVELOPE *e;
412{
413	if (tTd(24, 4))
414		sm_dprintf("allocaddr(flags=%x, paddr=%s)\n", flags, paddr);
415
416	a->q_paddr = paddr;
417
418	if (a->q_user == NULL)
419		a->q_user = "";
420	if (a->q_host == NULL)
421		a->q_host = "";
422
423	if (bitset(RF_COPYPARSE, flags))
424	{
425		a->q_host = sm_rpool_strdup_x(e->e_rpool, a->q_host);
426		if (a->q_user != a->q_paddr)
427			a->q_user = sm_rpool_strdup_x(e->e_rpool, a->q_user);
428	}
429
430	if (a->q_paddr == NULL)
431		a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user);
432	a->q_qgrp = NOAQGRP;
433}
434/*
435**  PRESCAN -- Prescan name and make it canonical
436**
437**	Scans a name and turns it into a set of tokens.  This process
438**	deletes blanks and comments (in parentheses) (if the token type
439**	for left paren is SPC).
440**
441**	This routine knows about quoted strings and angle brackets.
442**
443**	There are certain subtleties to this routine.  The one that
444**	comes to mind now is that backslashes on the ends of names
445**	are silently stripped off; this is intentional.  The problem
446**	is that some versions of sndmsg (like at LBL) set the kill
447**	character to something other than @ when reading addresses;
448**	so people type "csvax.eric\@berkeley" -- which screws up the
449**	berknet mailer.
450**
451**	Parameters:
452**		addr -- the name to chomp.
453**		delim -- the delimiter for the address, normally
454**			'\0' or ','; \0 is accepted in any case.
455**			If '\t' then we are reading the .cf file.
456**		pvpbuf -- place to put the saved text -- note that
457**			the pointers are static.
458**		pvpbsize -- size of pvpbuf.
459**		delimptr -- if non-NULL, set to the location of the
460**			terminating delimiter.
461**		toktab -- if set, a token table to use for parsing.
462**			If NULL, use the default table.
463**
464**	Returns:
465**		A pointer to a vector of tokens.
466**		NULL on error.
467*/
468
469/* states and character types */
470#define OPR		0	/* operator */
471#define ATM		1	/* atom */
472#define QST		2	/* in quoted string */
473#define SPC		3	/* chewing up spaces */
474#define ONE		4	/* pick up one character */
475#define ILL		5	/* illegal character */
476
477#define NSTATES	6	/* number of states */
478#define TYPE		017	/* mask to select state type */
479
480/* meta bits for table */
481#define M		020	/* meta character; don't pass through */
482#define B		040	/* cause a break */
483#define MB		M|B	/* meta-break */
484
485static short StateTab[NSTATES][NSTATES] =
486{
487   /*	oldst	chtype>	OPR	ATM	QST	SPC	ONE	ILL	*/
488	/*OPR*/	{	OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,	ILL|MB	},
489	/*ATM*/	{	OPR|B,	ATM,	QST|B,	SPC|MB,	ONE|B,	ILL|MB	},
490	/*QST*/	{	QST,	QST,	OPR,	QST,	QST,	QST	},
491	/*SPC*/	{	OPR,	ATM,	QST,	SPC|M,	ONE,	ILL|MB	},
492	/*ONE*/	{	OPR,	OPR,	OPR,	OPR,	OPR,	ILL|MB	},
493	/*ILL*/	{	OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,	ILL|M	},
494};
495
496/* token type table -- it gets modified with $o characters */
497static unsigned char	TokTypeTab[256] =
498{
499    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
500	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
501    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
502	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
503    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
504	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,ATM,ATM,ATM,ATM,
505    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
506	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
507    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
508	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
509    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
510	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
511    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
512	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
513    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
514	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
515
516    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
517	OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
518    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
519	OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
520    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
521	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
522    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
523	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
524    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
525	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
526    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
527	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
528    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
529	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
530    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
531	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
532};
533
534/* token type table for MIME parsing */
535unsigned char	MimeTokenTab[256] =
536{
537    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
538	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,SPC,SPC,SPC,SPC,SPC,ILL,ILL,
539    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
540	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
541    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
542	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,OPR,ATM,ATM,OPR,
543    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
544	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,OPR,OPR,OPR,OPR,OPR,OPR,
545    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
546	OPR,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
547    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
548	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,OPR,OPR,OPR,ATM,ATM,
549    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
550	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
551    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
552	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
553
554    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
555	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
556    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
557	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
558    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
559	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
560    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
561	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
562    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
563	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
564    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
565	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
566    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
567	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
568    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
569	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
570};
571
572/* token type table: don't strip comments */
573unsigned char	TokTypeNoC[256] =
574{
575    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
576	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
577    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
578	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
579    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
580	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, OPR,OPR,ATM,ATM,ATM,ATM,ATM,ATM,
581    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
582	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
583    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
584	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
585    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
586	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
587    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
588	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
589    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
590	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
591
592    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
593	OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
594    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
595	OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
596    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
597	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
598    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
599	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
600    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
601	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
602    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
603	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
604    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
605	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
606    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
607	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
608};
609
610
611#define NOCHAR		-1	/* signal nothing in lookahead token */
612
613char **
614prescan(addr, delim, pvpbuf, pvpbsize, delimptr, toktab)
615	char *addr;
616	int delim;
617	char pvpbuf[];
618	int pvpbsize;
619	char **delimptr;
620	unsigned char *toktab;
621{
622	register char *p;
623	register char *q;
624	register int c;
625	char **avp;
626	bool bslashmode;
627	bool route_syntax;
628	int cmntcnt;
629	int anglecnt;
630	char *tok;
631	int state;
632	int newstate;
633	char *saveto = CurEnv->e_to;
634	static char *av[MAXATOM + 1];
635	static bool firsttime = true;
636	extern int errno;
637
638	if (firsttime)
639	{
640		/* initialize the token type table */
641		char obuf[50];
642
643		firsttime = false;
644		if (OperatorChars == NULL)
645		{
646			if (ConfigLevel < 7)
647				OperatorChars = macvalue('o', CurEnv);
648			if (OperatorChars == NULL)
649				OperatorChars = ".:@[]";
650		}
651		expand(OperatorChars, obuf, sizeof obuf - sizeof DELIMCHARS,
652		       CurEnv);
653		(void) sm_strlcat(obuf, DELIMCHARS, sizeof obuf);
654		for (p = obuf; *p != '\0'; p++)
655		{
656			if (TokTypeTab[*p & 0xff] == ATM)
657				TokTypeTab[*p & 0xff] = OPR;
658			if (TokTypeNoC[*p & 0xff] == ATM)
659				TokTypeNoC[*p & 0xff] = OPR;
660		}
661	}
662	if (toktab == NULL)
663		toktab = TokTypeTab;
664
665	/* make sure error messages don't have garbage on them */
666	errno = 0;
667
668	q = pvpbuf;
669	bslashmode = false;
670	route_syntax = false;
671	cmntcnt = 0;
672	anglecnt = 0;
673	avp = av;
674	state = ATM;
675	c = NOCHAR;
676	p = addr;
677	CurEnv->e_to = p;
678	if (tTd(22, 11))
679	{
680		sm_dprintf("prescan: ");
681		xputs(p);
682		sm_dprintf("\n");
683	}
684
685	do
686	{
687		/* read a token */
688		tok = q;
689		for (;;)
690		{
691			/* store away any old lookahead character */
692			if (c != NOCHAR && !bslashmode)
693			{
694				/* see if there is room */
695				if (q >= &pvpbuf[pvpbsize - 5])
696				{
697					usrerr("553 5.1.1 Address too long");
698					if (strlen(addr) > MAXNAME)
699						addr[MAXNAME] = '\0';
700	returnnull:
701					if (delimptr != NULL)
702						*delimptr = p;
703					CurEnv->e_to = saveto;
704					return NULL;
705				}
706
707				/* squirrel it away */
708				*q++ = c;
709			}
710
711			/* read a new input character */
712			c = *p++;
713			if (c == '\0')
714			{
715				/* diagnose and patch up bad syntax */
716				if (state == QST)
717				{
718					usrerr("553 Unbalanced '\"'");
719					c = '"';
720				}
721				else if (cmntcnt > 0)
722				{
723					usrerr("553 Unbalanced '('");
724					c = ')';
725				}
726				else if (anglecnt > 0)
727				{
728					c = '>';
729					usrerr("553 Unbalanced '<'");
730				}
731				else
732					break;
733
734				p--;
735			}
736			else if (c == delim && cmntcnt <= 0 && state != QST)
737			{
738				if (anglecnt <= 0)
739					break;
740
741				/* special case for better error management */
742				if (delim == ',' && !route_syntax)
743				{
744					usrerr("553 Unbalanced '<'");
745					c = '>';
746					p--;
747				}
748			}
749
750			if (tTd(22, 101))
751				sm_dprintf("c=%c, s=%d; ", c, state);
752
753			/* chew up special characters */
754			*q = '\0';
755			if (bslashmode)
756			{
757				bslashmode = false;
758
759				/* kludge \! for naive users */
760				if (cmntcnt > 0)
761				{
762					c = NOCHAR;
763					continue;
764				}
765				else if (c != '!' || state == QST)
766				{
767					*q++ = '\\';
768					continue;
769				}
770			}
771
772			if (c == '\\')
773			{
774				bslashmode = true;
775			}
776			else if (state == QST)
777			{
778				/* EMPTY */
779				/* do nothing, just avoid next clauses */
780			}
781			else if (c == '(' && toktab['('] == SPC)
782			{
783				cmntcnt++;
784				c = NOCHAR;
785			}
786			else if (c == ')' && toktab['('] == SPC)
787			{
788				if (cmntcnt <= 0)
789				{
790					usrerr("553 Unbalanced ')'");
791					c = NOCHAR;
792				}
793				else
794					cmntcnt--;
795			}
796			else if (cmntcnt > 0)
797			{
798				c = NOCHAR;
799			}
800			else if (c == '<')
801			{
802				char *ptr = p;
803
804				anglecnt++;
805				while (isascii(*ptr) && isspace(*ptr))
806					ptr++;
807				if (*ptr == '@')
808					route_syntax = true;
809			}
810			else if (c == '>')
811			{
812				if (anglecnt <= 0)
813				{
814					usrerr("553 Unbalanced '>'");
815					c = NOCHAR;
816				}
817				else
818					anglecnt--;
819				route_syntax = false;
820			}
821			else if (delim == ' ' && isascii(c) && isspace(c))
822				c = ' ';
823
824			if (c == NOCHAR)
825				continue;
826
827			/* see if this is end of input */
828			if (c == delim && anglecnt <= 0 && state != QST)
829				break;
830
831			newstate = StateTab[state][toktab[c & 0xff]];
832			if (tTd(22, 101))
833				sm_dprintf("ns=%02o\n", newstate);
834			state = newstate & TYPE;
835			if (state == ILL)
836			{
837				if (isascii(c) && isprint(c))
838					usrerr("553 Illegal character %c", c);
839				else
840					usrerr("553 Illegal character 0x%02x",
841					       c & 0x0ff);
842			}
843			if (bitset(M, newstate))
844				c = NOCHAR;
845			if (bitset(B, newstate))
846				break;
847		}
848
849		/* new token */
850		if (tok != q)
851		{
852			*q++ = '\0';
853			if (tTd(22, 36))
854			{
855				sm_dprintf("tok=");
856				xputs(tok);
857				sm_dprintf("\n");
858			}
859			if (avp >= &av[MAXATOM])
860			{
861				usrerr("553 5.1.0 prescan: too many tokens");
862				goto returnnull;
863			}
864			if (q - tok > MAXNAME)
865			{
866				usrerr("553 5.1.0 prescan: token too long");
867				goto returnnull;
868			}
869			*avp++ = tok;
870		}
871	} while (c != '\0' && (c != delim || anglecnt > 0));
872	*avp = NULL;
873	p--;
874	if (delimptr != NULL)
875		*delimptr = p;
876	if (tTd(22, 12))
877	{
878		sm_dprintf("prescan==>");
879		printav(av);
880	}
881	CurEnv->e_to = saveto;
882	if (av[0] == NULL)
883	{
884		if (tTd(22, 1))
885			sm_dprintf("prescan: null leading token\n");
886		return NULL;
887	}
888	return av;
889}
890/*
891**  REWRITE -- apply rewrite rules to token vector.
892**
893**	This routine is an ordered production system.  Each rewrite
894**	rule has a LHS (called the pattern) and a RHS (called the
895**	rewrite); 'rwr' points the the current rewrite rule.
896**
897**	For each rewrite rule, 'avp' points the address vector we
898**	are trying to match against, and 'pvp' points to the pattern.
899**	If pvp points to a special match value (MATCHZANY, MATCHANY,
900**	MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
901**	matched is saved away in the match vector (pointed to by 'mvp').
902**
903**	When a match between avp & pvp does not match, we try to
904**	back out.  If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
905**	we must also back out the match in mvp.  If we reach a
906**	MATCHANY or MATCHZANY we just extend the match and start
907**	over again.
908**
909**	When we finally match, we rewrite the address vector
910**	and try over again.
911**
912**	Parameters:
913**		pvp -- pointer to token vector.
914**		ruleset -- the ruleset to use for rewriting.
915**		reclevel -- recursion level (to catch loops).
916**		e -- the current envelope.
917**		maxatom -- maximum length of buffer (usually MAXATOM)
918**
919**	Returns:
920**		A status code.  If EX_TEMPFAIL, higher level code should
921**			attempt recovery.
922**
923**	Side Effects:
924**		pvp is modified.
925*/
926
927struct match
928{
929	char	**match_first;		/* first token matched */
930	char	**match_last;		/* last token matched */
931	char	**match_pattern;	/* pointer to pattern */
932};
933
934int
935rewrite(pvp, ruleset, reclevel, e, maxatom)
936	char **pvp;
937	int ruleset;
938	int reclevel;
939	register ENVELOPE *e;
940	int maxatom;
941{
942	register char *ap;		/* address pointer */
943	register char *rp;		/* rewrite pointer */
944	register char *rulename;	/* ruleset name */
945	register char *prefix;
946	register char **avp;		/* address vector pointer */
947	register char **rvp;		/* rewrite vector pointer */
948	register struct match *mlp;	/* cur ptr into mlist */
949	register struct rewrite *rwr;	/* pointer to current rewrite rule */
950	int ruleno;			/* current rule number */
951	int rstat = EX_OK;		/* return status */
952	int loopcount;
953	struct match mlist[MAXMATCH];	/* stores match on LHS */
954	char *npvp[MAXATOM + 1];	/* temporary space for rebuild */
955	char buf[MAXLINE];
956	char name[6];
957
958	if (ruleset < 0 || ruleset >= MAXRWSETS)
959	{
960		syserr("554 5.3.5 rewrite: illegal ruleset number %d", ruleset);
961		return EX_CONFIG;
962	}
963	rulename = RuleSetNames[ruleset];
964	if (rulename == NULL)
965	{
966		(void) sm_snprintf(name, sizeof name, "%d", ruleset);
967		rulename = name;
968	}
969	if (OpMode == MD_TEST)
970		prefix = "";
971	else
972		prefix = "rewrite: ruleset ";
973	if (OpMode == MD_TEST)
974	{
975		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
976				     "%s%-16.16s   input:", prefix, rulename);
977		printav(pvp);
978	}
979	else if (tTd(21, 1))
980	{
981		sm_dprintf("%s%-16.16s   input:", prefix, rulename);
982		printav(pvp);
983	}
984	if (reclevel++ > MaxRuleRecursion)
985	{
986		syserr("rewrite: excessive recursion (max %d), ruleset %s",
987			MaxRuleRecursion, rulename);
988		return EX_CONFIG;
989	}
990	if (pvp == NULL)
991		return EX_USAGE;
992
993	/*
994	**  Run through the list of rewrite rules, applying
995	**	any that match.
996	*/
997
998	ruleno = 1;
999	loopcount = 0;
1000	for (rwr = RewriteRules[ruleset]; rwr != NULL; )
1001	{
1002		int status;
1003
1004		/* if already canonical, quit now */
1005		if (pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET)
1006			break;
1007
1008		if (tTd(21, 12))
1009		{
1010			if (tTd(21, 15))
1011				sm_dprintf("-----trying rule (line %d):",
1012				       rwr->r_line);
1013			else
1014				sm_dprintf("-----trying rule:");
1015			printav(rwr->r_lhs);
1016		}
1017
1018		/* try to match on this rule */
1019		mlp = mlist;
1020		rvp = rwr->r_lhs;
1021		avp = pvp;
1022		if (++loopcount > 100)
1023		{
1024			syserr("554 5.3.5 Infinite loop in ruleset %s, rule %d",
1025				rulename, ruleno);
1026			if (tTd(21, 1))
1027			{
1028				sm_dprintf("workspace: ");
1029				printav(pvp);
1030			}
1031			break;
1032		}
1033
1034		while ((ap = *avp) != NULL || *rvp != NULL)
1035		{
1036			rp = *rvp;
1037			if (tTd(21, 35))
1038			{
1039				sm_dprintf("ADVANCE rp=");
1040				xputs(rp);
1041				sm_dprintf(", ap=");
1042				xputs(ap);
1043				sm_dprintf("\n");
1044			}
1045			if (rp == NULL)
1046			{
1047				/* end-of-pattern before end-of-address */
1048				goto backup;
1049			}
1050			if (ap == NULL && (*rp & 0377) != MATCHZANY &&
1051			    (*rp & 0377) != MATCHZERO)
1052			{
1053				/* end-of-input with patterns left */
1054				goto backup;
1055			}
1056
1057			switch (*rp & 0377)
1058			{
1059			  case MATCHCLASS:
1060				/* match any phrase in a class */
1061				mlp->match_pattern = rvp;
1062				mlp->match_first = avp;
1063	extendclass:
1064				ap = *avp;
1065				if (ap == NULL)
1066					goto backup;
1067				mlp->match_last = avp++;
1068				cataddr(mlp->match_first, mlp->match_last,
1069					buf, sizeof buf, '\0');
1070				if (!wordinclass(buf, rp[1]))
1071				{
1072					if (tTd(21, 36))
1073					{
1074						sm_dprintf("EXTEND  rp=");
1075						xputs(rp);
1076						sm_dprintf(", ap=");
1077						xputs(ap);
1078						sm_dprintf("\n");
1079					}
1080					goto extendclass;
1081				}
1082				if (tTd(21, 36))
1083					sm_dprintf("CLMATCH\n");
1084				mlp++;
1085				break;
1086
1087			  case MATCHNCLASS:
1088				/* match any token not in a class */
1089				if (wordinclass(ap, rp[1]))
1090					goto backup;
1091
1092				/* FALLTHROUGH */
1093
1094			  case MATCHONE:
1095			  case MATCHANY:
1096				/* match exactly one token */
1097				mlp->match_pattern = rvp;
1098				mlp->match_first = avp;
1099				mlp->match_last = avp++;
1100				mlp++;
1101				break;
1102
1103			  case MATCHZANY:
1104				/* match zero or more tokens */
1105				mlp->match_pattern = rvp;
1106				mlp->match_first = avp;
1107				mlp->match_last = avp - 1;
1108				mlp++;
1109				break;
1110
1111			  case MATCHZERO:
1112				/* match zero tokens */
1113				break;
1114
1115			  case MACRODEXPAND:
1116				/*
1117				**  Match against run-time macro.
1118				**  This algorithm is broken for the
1119				**  general case (no recursive macros,
1120				**  improper tokenization) but should
1121				**  work for the usual cases.
1122				*/
1123
1124				ap = macvalue(rp[1], e);
1125				mlp->match_first = avp;
1126				if (tTd(21, 2))
1127					sm_dprintf("rewrite: LHS $&{%s} => \"%s\"\n",
1128						macname(rp[1]),
1129						ap == NULL ? "(NULL)" : ap);
1130
1131				if (ap == NULL)
1132					break;
1133				while (*ap != '\0')
1134				{
1135					if (*avp == NULL ||
1136					    sm_strncasecmp(ap, *avp,
1137							   strlen(*avp)) != 0)
1138					{
1139						/* no match */
1140						avp = mlp->match_first;
1141						goto backup;
1142					}
1143					ap += strlen(*avp++);
1144				}
1145
1146				/* match */
1147				break;
1148
1149			  default:
1150				/* must have exact match */
1151				if (sm_strcasecmp(rp, ap))
1152					goto backup;
1153				avp++;
1154				break;
1155			}
1156
1157			/* successful match on this token */
1158			rvp++;
1159			continue;
1160
1161	  backup:
1162			/* match failed -- back up */
1163			while (--mlp >= mlist)
1164			{
1165				rvp = mlp->match_pattern;
1166				rp = *rvp;
1167				avp = mlp->match_last + 1;
1168				ap = *avp;
1169
1170				if (tTd(21, 36))
1171				{
1172					sm_dprintf("BACKUP  rp=");
1173					xputs(rp);
1174					sm_dprintf(", ap=");
1175					xputs(ap);
1176					sm_dprintf("\n");
1177				}
1178
1179				if (ap == NULL)
1180				{
1181					/* run off the end -- back up again */
1182					continue;
1183				}
1184				if ((*rp & 0377) == MATCHANY ||
1185				    (*rp & 0377) == MATCHZANY)
1186				{
1187					/* extend binding and continue */
1188					mlp->match_last = avp++;
1189					rvp++;
1190					mlp++;
1191					break;
1192				}
1193				if ((*rp & 0377) == MATCHCLASS)
1194				{
1195					/* extend binding and try again */
1196					mlp->match_last = avp;
1197					goto extendclass;
1198				}
1199			}
1200
1201			if (mlp < mlist)
1202			{
1203				/* total failure to match */
1204				break;
1205			}
1206		}
1207
1208		/*
1209		**  See if we successfully matched
1210		*/
1211
1212		if (mlp < mlist || *rvp != NULL)
1213		{
1214			if (tTd(21, 10))
1215				sm_dprintf("----- rule fails\n");
1216			rwr = rwr->r_next;
1217			ruleno++;
1218			loopcount = 0;
1219			continue;
1220		}
1221
1222		rvp = rwr->r_rhs;
1223		if (tTd(21, 12))
1224		{
1225			sm_dprintf("-----rule matches:");
1226			printav(rvp);
1227		}
1228
1229		rp = *rvp;
1230		if (rp != NULL)
1231		{
1232			if ((*rp & 0377) == CANONUSER)
1233			{
1234				rvp++;
1235				rwr = rwr->r_next;
1236				ruleno++;
1237				loopcount = 0;
1238			}
1239			else if ((*rp & 0377) == CANONHOST)
1240			{
1241				rvp++;
1242				rwr = NULL;
1243			}
1244		}
1245
1246		/* substitute */
1247		for (avp = npvp; *rvp != NULL; rvp++)
1248		{
1249			register struct match *m;
1250			register char **pp;
1251
1252			rp = *rvp;
1253			if ((*rp & 0377) == MATCHREPL)
1254			{
1255				/* substitute from LHS */
1256				m = &mlist[rp[1] - '1'];
1257				if (m < mlist || m >= mlp)
1258				{
1259					syserr("554 5.3.5 rewrite: ruleset %s: replacement $%c out of bounds",
1260						rulename, rp[1]);
1261					return EX_CONFIG;
1262				}
1263				if (tTd(21, 15))
1264				{
1265					sm_dprintf("$%c:", rp[1]);
1266					pp = m->match_first;
1267					while (pp <= m->match_last)
1268					{
1269						sm_dprintf(" %p=\"", *pp);
1270						sm_dflush();
1271						sm_dprintf("%s\"", *pp++);
1272					}
1273					sm_dprintf("\n");
1274				}
1275				pp = m->match_first;
1276				while (pp <= m->match_last)
1277				{
1278					if (avp >= &npvp[maxatom])
1279					{
1280						syserr("554 5.3.0 rewrite: expansion too long");
1281						if (LogLevel > 9)
1282							sm_syslog(LOG_ERR,
1283								e->e_id,
1284								"rewrite: expansion too long, ruleset=%s, ruleno=%d",
1285								rulename,
1286								ruleno);
1287						return EX_DATAERR;
1288					}
1289					*avp++ = *pp++;
1290				}
1291			}
1292			else
1293			{
1294				/* some sort of replacement */
1295				if (avp >= &npvp[maxatom])
1296				{
1297	toolong:
1298					syserr("554 5.3.0 rewrite: expansion too long");
1299					if (LogLevel > 9)
1300						sm_syslog(LOG_ERR, e->e_id,
1301							"rewrite: expansion too long, ruleset=%s, ruleno=%d",
1302							rulename, ruleno);
1303					return EX_DATAERR;
1304				}
1305				if ((*rp & 0377) != MACRODEXPAND)
1306				{
1307					/* vanilla replacement */
1308					*avp++ = rp;
1309				}
1310				else
1311				{
1312					/* $&{x} replacement */
1313					char *mval = macvalue(rp[1], e);
1314					char **xpvp;
1315					int trsize = 0;
1316					static size_t pvpb1_size = 0;
1317					static char **pvpb1 = NULL;
1318					char pvpbuf[PSBUFSIZE];
1319
1320					if (tTd(21, 2))
1321						sm_dprintf("rewrite: RHS $&{%s} => \"%s\"\n",
1322							macname(rp[1]),
1323							mval == NULL ? "(NULL)" : mval);
1324					if (mval == NULL || *mval == '\0')
1325						continue;
1326
1327					/* save the remainder of the input */
1328					for (xpvp = pvp; *xpvp != NULL; xpvp++)
1329						trsize += sizeof *xpvp;
1330					if ((size_t) trsize > pvpb1_size)
1331					{
1332						if (pvpb1 != NULL)
1333							sm_free(pvpb1);
1334						pvpb1 = (char **)
1335							sm_pmalloc_x(trsize);
1336						pvpb1_size = trsize;
1337					}
1338
1339					memmove((char *) pvpb1,
1340						(char *) pvp,
1341						trsize);
1342
1343					/* scan the new replacement */
1344					xpvp = prescan(mval, '\0', pvpbuf,
1345						       sizeof pvpbuf, NULL,
1346						       NULL);
1347					if (xpvp == NULL)
1348					{
1349						/* prescan pre-printed error */
1350						return EX_DATAERR;
1351					}
1352
1353					/* insert it into the output stream */
1354					while (*xpvp != NULL)
1355					{
1356						if (tTd(21, 19))
1357							sm_dprintf(" ... %s\n",
1358								*xpvp);
1359						*avp++ = sm_rpool_strdup_x(
1360							e->e_rpool, *xpvp);
1361						if (avp >= &npvp[maxatom])
1362							goto toolong;
1363						xpvp++;
1364					}
1365					if (tTd(21, 19))
1366						sm_dprintf(" ... DONE\n");
1367
1368					/* restore the old trailing input */
1369					memmove((char *) pvp,
1370						(char *) pvpb1,
1371						trsize);
1372				}
1373			}
1374		}
1375		*avp++ = NULL;
1376
1377		/*
1378		**  Check for any hostname/keyword lookups.
1379		*/
1380
1381		for (rvp = npvp; *rvp != NULL; rvp++)
1382		{
1383			char **hbrvp;
1384			char **xpvp;
1385			int trsize;
1386			char *replac;
1387			int endtoken;
1388			STAB *map;
1389			char *mapname;
1390			char **key_rvp;
1391			char **arg_rvp;
1392			char **default_rvp;
1393			char cbuf[MAXNAME + 1];
1394			char *pvpb1[MAXATOM + 1];
1395			char *argvect[10];
1396			char pvpbuf[PSBUFSIZE];
1397			char *nullpvp[1];
1398
1399			if ((**rvp & 0377) != HOSTBEGIN &&
1400			    (**rvp & 0377) != LOOKUPBEGIN)
1401				continue;
1402
1403			/*
1404			**  Got a hostname/keyword lookup.
1405			**
1406			**	This could be optimized fairly easily.
1407			*/
1408
1409			hbrvp = rvp;
1410			if ((**rvp & 0377) == HOSTBEGIN)
1411			{
1412				endtoken = HOSTEND;
1413				mapname = "host";
1414			}
1415			else
1416			{
1417				endtoken = LOOKUPEND;
1418				mapname = *++rvp;
1419			}
1420			map = stab(mapname, ST_MAP, ST_FIND);
1421			if (map == NULL)
1422				syserr("554 5.3.0 rewrite: map %s not found", mapname);
1423
1424			/* extract the match part */
1425			key_rvp = ++rvp;
1426			default_rvp = NULL;
1427			arg_rvp = argvect;
1428			xpvp = NULL;
1429			replac = pvpbuf;
1430			while (*rvp != NULL && (**rvp & 0377) != endtoken)
1431			{
1432				int nodetype = **rvp & 0377;
1433
1434				if (nodetype != CANONHOST && nodetype != CANONUSER)
1435				{
1436					rvp++;
1437					continue;
1438				}
1439
1440				*rvp++ = NULL;
1441
1442				if (xpvp != NULL)
1443				{
1444					cataddr(xpvp, NULL, replac,
1445						&pvpbuf[sizeof pvpbuf] - replac,
1446						'\0');
1447					*++arg_rvp = replac;
1448					replac += strlen(replac) + 1;
1449					xpvp = NULL;
1450				}
1451				switch (nodetype)
1452				{
1453				  case CANONHOST:
1454					xpvp = rvp;
1455					break;
1456
1457				  case CANONUSER:
1458					default_rvp = rvp;
1459					break;
1460				}
1461			}
1462			if (*rvp != NULL)
1463				*rvp++ = NULL;
1464			if (xpvp != NULL)
1465			{
1466				cataddr(xpvp, NULL, replac,
1467					&pvpbuf[sizeof pvpbuf] - replac,
1468					'\0');
1469				*++arg_rvp = replac;
1470			}
1471			*++arg_rvp = NULL;
1472
1473			/* save the remainder of the input string */
1474			trsize = (int) (avp - rvp + 1) * sizeof *rvp;
1475			memmove((char *) pvpb1, (char *) rvp, trsize);
1476
1477			/* look it up */
1478			cataddr(key_rvp, NULL, cbuf, sizeof cbuf,
1479				map == NULL ? '\0' : map->s_map.map_spacesub);
1480			argvect[0] = cbuf;
1481			replac = map_lookup(map, cbuf, argvect, &rstat, e);
1482
1483			/* if no replacement, use default */
1484			if (replac == NULL && default_rvp != NULL)
1485			{
1486				/* create the default */
1487				cataddr(default_rvp, NULL, cbuf, sizeof cbuf, '\0');
1488				replac = cbuf;
1489			}
1490
1491			if (replac == NULL)
1492			{
1493				xpvp = key_rvp;
1494			}
1495			else if (*replac == '\0')
1496			{
1497				/* null replacement */
1498				nullpvp[0] = NULL;
1499				xpvp = nullpvp;
1500			}
1501			else
1502			{
1503				/* scan the new replacement */
1504				xpvp = prescan(replac, '\0', pvpbuf,
1505					       sizeof pvpbuf, NULL, NULL);
1506				if (xpvp == NULL)
1507				{
1508					/* prescan already printed error */
1509					return EX_DATAERR;
1510				}
1511			}
1512
1513			/* append it to the token list */
1514			for (avp = hbrvp; *xpvp != NULL; xpvp++)
1515			{
1516				*avp++ = sm_rpool_strdup_x(e->e_rpool, *xpvp);
1517				if (avp >= &npvp[maxatom])
1518					goto toolong;
1519			}
1520
1521			/* restore the old trailing information */
1522			rvp = avp - 1;
1523			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
1524				if (avp >= &npvp[maxatom])
1525					goto toolong;
1526		}
1527
1528		/*
1529		**  Check for subroutine calls.
1530		*/
1531
1532		status = callsubr(npvp, reclevel, e);
1533		if (rstat == EX_OK || status == EX_TEMPFAIL)
1534			rstat = status;
1535
1536		/* copy vector back into original space. */
1537		for (avp = npvp; *avp++ != NULL;)
1538			continue;
1539		memmove((char *) pvp, (char *) npvp,
1540		      (int) (avp - npvp) * sizeof *avp);
1541
1542		if (tTd(21, 4))
1543		{
1544			sm_dprintf("rewritten as:");
1545			printav(pvp);
1546		}
1547	}
1548
1549	if (OpMode == MD_TEST)
1550	{
1551		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1552				     "%s%-16.16s returns:", prefix, rulename);
1553		printav(pvp);
1554	}
1555	else if (tTd(21, 1))
1556	{
1557		sm_dprintf("%s%-16.16s returns:", prefix, rulename);
1558		printav(pvp);
1559	}
1560	return rstat;
1561}
1562/*
1563**  CALLSUBR -- call subroutines in rewrite vector
1564**
1565**	Parameters:
1566**		pvp -- pointer to token vector.
1567**		reclevel -- the current recursion level.
1568**		e -- the current envelope.
1569**
1570**	Returns:
1571**		The status from the subroutine call.
1572**
1573**	Side Effects:
1574**		pvp is modified.
1575*/
1576
1577static int
1578callsubr(pvp, reclevel, e)
1579	char **pvp;
1580	int reclevel;
1581	ENVELOPE *e;
1582{
1583	char **avp;
1584	register int i;
1585	int subr, j;
1586	int nsubr;
1587	int status;
1588	int rstat = EX_OK;
1589#define MAX_SUBR	16
1590	int subrnumber[MAX_SUBR];
1591	int subrindex[MAX_SUBR];
1592
1593	nsubr = 0;
1594
1595	/*
1596	**  Look for subroutine calls in pvp, collect them into subr*[]
1597	**  We will perform the calls in the next loop, because we will
1598	**  call the "last" subroutine first to avoid recursive calls
1599	**  and too much copying.
1600	*/
1601
1602	for (avp = pvp, j = 0; *avp != NULL; avp++, j++)
1603	{
1604		if ((**avp & 0377) == CALLSUBR && avp[1] != NULL)
1605		{
1606			stripquotes(avp[1]);
1607			subr = strtorwset(avp[1], NULL, ST_FIND);
1608			if (subr < 0)
1609			{
1610				syserr("554 5.3.5 Unknown ruleset %s", avp[1]);
1611				return EX_CONFIG;
1612			}
1613
1614			/*
1615			**  XXX instead of doing this we could optimize
1616			**  the rules after reading them: just remove
1617			**  calls to empty rulesets
1618			*/
1619
1620			/* subroutine is an empty ruleset?  don't call it */
1621			if (RewriteRules[subr] == NULL)
1622			{
1623				if (tTd(21, 3))
1624					sm_dprintf("-----skip subr %s (%d)\n",
1625						avp[1], subr);
1626				for (i = 2; avp[i] != NULL; i++)
1627					avp[i - 2] = avp[i];
1628				avp[i - 2] = NULL;
1629				continue;
1630			}
1631			if (++nsubr >= MAX_SUBR)
1632			{
1633				syserr("554 5.3.0 Too many subroutine calls (%d max)",
1634					MAX_SUBR);
1635				return EX_CONFIG;
1636			}
1637			subrnumber[nsubr] = subr;
1638			subrindex[nsubr] = j;
1639		}
1640	}
1641
1642	/*
1643	**  Perform the actual subroutines calls, "last" one first, i.e.,
1644	**  go from the right to the left through all calls,
1645	**  do the rewriting in place.
1646	*/
1647
1648	for (; nsubr > 0; nsubr--)
1649	{
1650		subr = subrnumber[nsubr];
1651		avp = pvp + subrindex[nsubr];
1652
1653		/* remove the subroutine call and name */
1654		for (i = 2; avp[i] != NULL; i++)
1655			avp[i - 2] = avp[i];
1656		avp[i - 2] = NULL;
1657
1658		/*
1659		**  Now we need to call the ruleset specified for
1660		**  the subroutine. we can do this inplace since
1661		**  we call the "last" subroutine first.
1662		*/
1663
1664		status = rewrite(avp, subr, reclevel, e,
1665				MAXATOM - subrindex[nsubr]);
1666		if (status != EX_OK && status != EX_TEMPFAIL)
1667			return status;
1668		if (rstat == EX_OK || status == EX_TEMPFAIL)
1669			rstat = status;
1670	}
1671	return rstat;
1672}
1673/*
1674**  MAP_LOOKUP -- do lookup in map
1675**
1676**	Parameters:
1677**		smap -- the map to use for the lookup.
1678**		key -- the key to look up.
1679**		argvect -- arguments to pass to the map lookup.
1680**		pstat -- a pointer to an integer in which to store the
1681**			status from the lookup.
1682**		e -- the current envelope.
1683**
1684**	Returns:
1685**		The result of the lookup.
1686**		NULL -- if there was no data for the given key.
1687*/
1688
1689static char *
1690map_lookup(smap, key, argvect, pstat, e)
1691	STAB *smap;
1692	char key[];
1693	char **argvect;
1694	int *pstat;
1695	ENVELOPE *e;
1696{
1697	auto int status = EX_OK;
1698	MAP *map;
1699	char *replac;
1700
1701	if (smap == NULL)
1702		return NULL;
1703
1704	map = &smap->s_map;
1705	DYNOPENMAP(map);
1706
1707	if (e->e_sendmode == SM_DEFER &&
1708	    bitset(MF_DEFER, map->map_mflags))
1709	{
1710		/* don't do any map lookups */
1711		if (tTd(60, 1))
1712			sm_dprintf("map_lookup(%s, %s) => DEFERRED\n",
1713				smap->s_name, key);
1714		*pstat = EX_TEMPFAIL;
1715		return NULL;
1716	}
1717
1718	if (!bitset(MF_KEEPQUOTES, map->map_mflags))
1719		stripquotes(key);
1720
1721	if (tTd(60, 1))
1722	{
1723		sm_dprintf("map_lookup(%s, %s", smap->s_name, key);
1724		if (tTd(60, 5))
1725		{
1726			int i;
1727
1728			for (i = 0; argvect[i] != NULL; i++)
1729				sm_dprintf(", %%%d=%s", i, argvect[i]);
1730		}
1731		sm_dprintf(") => ");
1732	}
1733	replac = (*map->map_class->map_lookup)(map, key, argvect, &status);
1734	if (tTd(60, 1))
1735		sm_dprintf("%s (%d)\n",
1736			replac != NULL ? replac : "NOT FOUND",
1737			status);
1738
1739	/* should recover if status == EX_TEMPFAIL */
1740	if (status == EX_TEMPFAIL && !bitset(MF_NODEFER, map->map_mflags))
1741	{
1742		*pstat = EX_TEMPFAIL;
1743		if (tTd(60, 1))
1744			sm_dprintf("map_lookup(%s, %s) tempfail: errno=%d\n",
1745				smap->s_name, key, errno);
1746		if (e->e_message == NULL)
1747		{
1748			char mbuf[320];
1749
1750			(void) sm_snprintf(mbuf, sizeof mbuf,
1751				"%.80s map: lookup (%s): deferred",
1752				smap->s_name,
1753				shortenstring(key, MAXSHORTSTR));
1754			e->e_message = sm_rpool_strdup_x(e->e_rpool, mbuf);
1755		}
1756	}
1757	if (status == EX_TEMPFAIL && map->map_tapp != NULL)
1758	{
1759		size_t i = strlen(key) + strlen(map->map_tapp) + 1;
1760		static char *rwbuf = NULL;
1761		static size_t rwbuflen = 0;
1762
1763		if (i > rwbuflen)
1764		{
1765			if (rwbuf != NULL)
1766				sm_free(rwbuf);
1767			rwbuflen = i;
1768			rwbuf = (char *) sm_pmalloc_x(rwbuflen);
1769		}
1770		(void) sm_strlcpyn(rwbuf, rwbuflen, 2, key, map->map_tapp);
1771		if (tTd(60, 4))
1772			sm_dprintf("map_lookup tempfail: returning \"%s\"\n",
1773				rwbuf);
1774		return rwbuf;
1775	}
1776	return replac;
1777}
1778/*
1779**  INITERRMAILERS -- initialize error and discard mailers
1780**
1781**	Parameters:
1782**		none.
1783**
1784**	Returns:
1785**		none.
1786**
1787**	Side Effects:
1788**		initializes error and discard mailers.
1789*/
1790
1791static MAILER discardmailer;
1792static MAILER errormailer;
1793static char *discardargv[] = { "DISCARD", NULL };
1794static char *errorargv[] = { "ERROR", NULL };
1795
1796void
1797initerrmailers()
1798{
1799	if (discardmailer.m_name == NULL)
1800	{
1801		/* initialize the discard mailer */
1802		discardmailer.m_name = "*discard*";
1803		discardmailer.m_mailer = "DISCARD";
1804		discardmailer.m_argv = discardargv;
1805	}
1806	if (errormailer.m_name == NULL)
1807	{
1808		/* initialize the bogus mailer */
1809		errormailer.m_name = "*error*";
1810		errormailer.m_mailer = "ERROR";
1811		errormailer.m_argv = errorargv;
1812	}
1813}
1814/*
1815**  BUILDADDR -- build address from token vector.
1816**
1817**	Parameters:
1818**		tv -- token vector.
1819**		a -- pointer to address descriptor to fill.
1820**			If NULL, one will be allocated.
1821**		flags -- info regarding whether this is a sender or
1822**			a recipient.
1823**		e -- the current envelope.
1824**
1825**	Returns:
1826**		NULL if there was an error.
1827**		'a' otherwise.
1828**
1829**	Side Effects:
1830**		fills in 'a'
1831*/
1832
1833static struct errcodes
1834{
1835	char	*ec_name;		/* name of error code */
1836	int	ec_code;		/* numeric code */
1837} ErrorCodes[] =
1838{
1839	{ "usage",		EX_USAGE	},
1840	{ "nouser",		EX_NOUSER	},
1841	{ "nohost",		EX_NOHOST	},
1842	{ "unavailable",	EX_UNAVAILABLE	},
1843	{ "software",		EX_SOFTWARE	},
1844	{ "tempfail",		EX_TEMPFAIL	},
1845	{ "protocol",		EX_PROTOCOL	},
1846	{ "config",		EX_CONFIG	},
1847	{ NULL,			EX_UNAVAILABLE	}
1848};
1849
1850static ADDRESS *
1851buildaddr(tv, a, flags, e)
1852	register char **tv;
1853	register ADDRESS *a;
1854	int flags;
1855	register ENVELOPE *e;
1856{
1857	bool tempfail = false;
1858	struct mailer **mp;
1859	register struct mailer *m;
1860	register char *p;
1861	char *mname;
1862	char **hostp;
1863	char hbuf[MAXNAME + 1];
1864	static char ubuf[MAXNAME + 2];
1865
1866	if (tTd(24, 5))
1867	{
1868		sm_dprintf("buildaddr, flags=%x, tv=", flags);
1869		printav(tv);
1870	}
1871
1872	if (a == NULL)
1873		a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof *a);
1874	memset((char *) a, '\0', sizeof *a);
1875	hbuf[0] = '\0';
1876
1877	/* set up default error return flags */
1878	a->q_flags |= DefaultNotify;
1879
1880	/* figure out what net/mailer to use */
1881	if (*tv == NULL || (**tv & 0377) != CANONNET)
1882	{
1883		syserr("554 5.3.5 buildaddr: no mailer in parsed address");
1884badaddr:
1885#if _FFR_ALLOW_S0_ERROR_4XX
1886		/*
1887		**  ExitStat may have been set by an earlier map open
1888		**  failure (to a permanent error (EX_OSERR) in syserr())
1889		**  so we also need to check if this particular $#error
1890		**  return wanted a 4XX failure.
1891		**
1892		**  XXX the real fix is probably to set ExitStat correctly,
1893		**  i.e., to EX_TEMPFAIL if the map open is just a temporary
1894		**  error.
1895		**
1896		**  tempfail is tested here even if _FFR_ALLOW_S0_ERROR_4XX
1897		**  is not set; that's ok because it is initialized to false.
1898		*/
1899#endif /* _FFR_ALLOW_S0_ERROR_4XX */
1900
1901		if (ExitStat == EX_TEMPFAIL || tempfail)
1902			a->q_state = QS_QUEUEUP;
1903		else
1904		{
1905			a->q_state = QS_BADADDR;
1906			a->q_mailer = &errormailer;
1907		}
1908		return a;
1909	}
1910	mname = *++tv;
1911
1912	/* extract host and user portions */
1913	if (*++tv != NULL && (**tv & 0377) == CANONHOST)
1914		hostp = ++tv;
1915	else
1916		hostp = NULL;
1917	while (*tv != NULL && (**tv & 0377) != CANONUSER)
1918		tv++;
1919	if (*tv == NULL)
1920	{
1921		syserr("554 5.3.5 buildaddr: no user");
1922		goto badaddr;
1923	}
1924	if (tv == hostp)
1925		hostp = NULL;
1926	else if (hostp != NULL)
1927		cataddr(hostp, tv - 1, hbuf, sizeof hbuf, '\0');
1928	cataddr(++tv, NULL, ubuf, sizeof ubuf, ' ');
1929
1930	/* save away the host name */
1931	if (sm_strcasecmp(mname, "error") == 0)
1932	{
1933		/* Set up triplet for use by -bv */
1934		a->q_mailer = &errormailer;
1935		a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf);
1936		/* XXX wrong place? */
1937
1938		if (hostp != NULL)
1939		{
1940			register struct errcodes *ep;
1941
1942			a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf);
1943			if (strchr(hbuf, '.') != NULL)
1944			{
1945				a->q_status = sm_rpool_strdup_x(e->e_rpool,
1946								hbuf);
1947				setstat(dsntoexitstat(hbuf));
1948			}
1949			else if (isascii(hbuf[0]) && isdigit(hbuf[0]))
1950			{
1951				setstat(atoi(hbuf));
1952			}
1953			else
1954			{
1955				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
1956					if (sm_strcasecmp(ep->ec_name, hbuf) == 0)
1957						break;
1958				setstat(ep->ec_code);
1959			}
1960		}
1961		else
1962		{
1963			a->q_host = NULL;
1964			setstat(EX_UNAVAILABLE);
1965		}
1966		stripquotes(ubuf);
1967		if (ISSMTPCODE(ubuf) && ubuf[3] == ' ')
1968		{
1969			char fmt[16];
1970			int off;
1971
1972			if ((off = isenhsc(ubuf + 4, ' ')) > 0)
1973			{
1974				ubuf[off + 4] = '\0';
1975				off += 5;
1976			}
1977			else
1978			{
1979				off = 4;
1980				ubuf[3] = '\0';
1981			}
1982			(void) sm_strlcpyn(fmt, sizeof fmt, 2, ubuf, " %s");
1983			if (off > 4)
1984				usrerr(fmt, ubuf + off);
1985			else if (isenhsc(hbuf, '\0') > 0)
1986				usrerrenh(hbuf, fmt, ubuf + off);
1987			else
1988				usrerr(fmt, ubuf + off);
1989			/* XXX ubuf[off - 1] = ' '; */
1990#if _FFR_ALLOW_S0_ERROR_4XX
1991			if (ubuf[0] == '4')
1992				tempfail = true;
1993#endif /* _FFR_ALLOW_S0_ERROR_4XX */
1994		}
1995		else
1996		{
1997			usrerr("553 5.3.0 %s", ubuf);
1998		}
1999		goto badaddr;
2000	}
2001
2002	for (mp = Mailer; (m = *mp++) != NULL; )
2003	{
2004		if (sm_strcasecmp(m->m_name, mname) == 0)
2005			break;
2006	}
2007	if (m == NULL)
2008	{
2009		syserr("554 5.3.5 buildaddr: unknown mailer %s", mname);
2010		goto badaddr;
2011	}
2012	a->q_mailer = m;
2013
2014	/* figure out what host (if any) */
2015	if (hostp == NULL)
2016	{
2017		if (!bitnset(M_LOCALMAILER, m->m_flags))
2018		{
2019			syserr("554 5.3.5 buildaddr: no host");
2020			goto badaddr;
2021		}
2022		a->q_host = NULL;
2023	}
2024	else
2025		a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf);
2026
2027	/* figure out the user */
2028	p = ubuf;
2029	if (bitnset(M_CHECKUDB, m->m_flags) && *p == '@')
2030	{
2031		p++;
2032		tv++;
2033		a->q_flags |= QNOTREMOTE;
2034	}
2035
2036	/* do special mapping for local mailer */
2037	if (*p == '"')
2038		p++;
2039	if (*p == '|' && bitnset(M_CHECKPROG, m->m_flags))
2040		a->q_mailer = m = ProgMailer;
2041	else if (*p == '/' && bitnset(M_CHECKFILE, m->m_flags))
2042		a->q_mailer = m = FileMailer;
2043	else if (*p == ':' && bitnset(M_CHECKINCLUDE, m->m_flags))
2044	{
2045		/* may be :include: */
2046		stripquotes(ubuf);
2047		if (sm_strncasecmp(ubuf, ":include:", 9) == 0)
2048		{
2049			/* if :include:, don't need further rewriting */
2050			a->q_mailer = m = InclMailer;
2051			a->q_user = sm_rpool_strdup_x(e->e_rpool, &ubuf[9]);
2052			return a;
2053		}
2054	}
2055
2056	/* rewrite according recipient mailer rewriting rules */
2057	macdefine(&e->e_macro, A_PERM, 'h', a->q_host);
2058
2059	if (ConfigLevel >= 10 ||
2060	    !bitset(RF_SENDERADDR|RF_HEADERADDR, flags))
2061	{
2062		/* sender addresses done later */
2063		(void) REWRITE(tv, 2, e);
2064		if (m->m_re_rwset > 0)
2065		       (void) REWRITE(tv, m->m_re_rwset, e);
2066	}
2067	(void) REWRITE(tv, 4, e);
2068
2069	/* save the result for the command line/RCPT argument */
2070	cataddr(tv, NULL, ubuf, sizeof ubuf, '\0');
2071	a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf);
2072
2073	/*
2074	**  Do mapping to lower case as requested by mailer
2075	*/
2076
2077	if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
2078		makelower(a->q_host);
2079	if (!bitnset(M_USR_UPPER, m->m_flags))
2080		makelower(a->q_user);
2081
2082	if (tTd(24, 6))
2083	{
2084		sm_dprintf("buildaddr => ");
2085		printaddr(a, false);
2086	}
2087	return a;
2088}
2089/*
2090**  CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
2091**
2092**	Parameters:
2093**		pvp -- parameter vector to rebuild.
2094**		evp -- last parameter to include.  Can be NULL to
2095**			use entire pvp.
2096**		buf -- buffer to build the string into.
2097**		sz -- size of buf.
2098**		spacesub -- the space separator character; if '\0',
2099**			use SpaceSub.
2100**
2101**	Returns:
2102**		none.
2103**
2104**	Side Effects:
2105**		Destroys buf.
2106*/
2107
2108void
2109cataddr(pvp, evp, buf, sz, spacesub)
2110	char **pvp;
2111	char **evp;
2112	char *buf;
2113	register int sz;
2114	int spacesub;
2115{
2116	bool oatomtok = false;
2117	bool natomtok = false;
2118	register int i;
2119	register char *p;
2120
2121	if (sz <= 0)
2122		return;
2123
2124	if (spacesub == '\0')
2125		spacesub = SpaceSub;
2126
2127	if (pvp == NULL)
2128	{
2129		*buf = '\0';
2130		return;
2131	}
2132	p = buf;
2133	sz -= 2;
2134	while (*pvp != NULL && sz > 0)
2135	{
2136		natomtok = (TokTypeTab[**pvp & 0xff] == ATM);
2137		if (oatomtok && natomtok)
2138		{
2139			*p++ = spacesub;
2140			if (--sz <= 0)
2141				break;
2142		}
2143		if ((i = sm_strlcpy(p, *pvp, sz)) >= sz)
2144			break;
2145		oatomtok = natomtok;
2146		p += i;
2147		sz -= i;
2148		if (pvp++ == evp)
2149			break;
2150	}
2151#if _FFR_CATCH_LONG_STRINGS
2152	/* Don't silently truncate long strings */
2153	if (*pvp != NULL)
2154		syserr("cataddr: string too long");
2155#endif /* _FFR_CATCH_LONG_STRINGS */
2156	*p = '\0';
2157}
2158/*
2159**  SAMEADDR -- Determine if two addresses are the same
2160**
2161**	This is not just a straight comparison -- if the mailer doesn't
2162**	care about the host we just ignore it, etc.
2163**
2164**	Parameters:
2165**		a, b -- pointers to the internal forms to compare.
2166**
2167**	Returns:
2168**		true -- they represent the same mailbox.
2169**		false -- they don't.
2170**
2171**	Side Effects:
2172**		none.
2173*/
2174
2175bool
2176sameaddr(a, b)
2177	register ADDRESS *a;
2178	register ADDRESS *b;
2179{
2180	register ADDRESS *ca, *cb;
2181
2182	/* if they don't have the same mailer, forget it */
2183	if (a->q_mailer != b->q_mailer)
2184		return false;
2185
2186	/* if the user isn't the same, we can drop out */
2187	if (strcmp(a->q_user, b->q_user) != 0)
2188		return false;
2189
2190	/* if we have good uids for both but they differ, these are different */
2191	if (a->q_mailer == ProgMailer)
2192	{
2193		ca = getctladdr(a);
2194		cb = getctladdr(b);
2195		if (ca != NULL && cb != NULL &&
2196		    bitset(QGOODUID, ca->q_flags & cb->q_flags) &&
2197		    ca->q_uid != cb->q_uid)
2198			return false;
2199	}
2200
2201	/* otherwise compare hosts (but be careful for NULL ptrs) */
2202	if (a->q_host == b->q_host)
2203	{
2204		/* probably both null pointers */
2205		return true;
2206	}
2207	if (a->q_host == NULL || b->q_host == NULL)
2208	{
2209		/* only one is a null pointer */
2210		return false;
2211	}
2212	if (strcmp(a->q_host, b->q_host) != 0)
2213		return false;
2214
2215	return true;
2216}
2217/*
2218**  PRINTADDR -- print address (for debugging)
2219**
2220**	Parameters:
2221**		a -- the address to print
2222**		follow -- follow the q_next chain.
2223**
2224**	Returns:
2225**		none.
2226**
2227**	Side Effects:
2228**		none.
2229*/
2230
2231struct qflags
2232{
2233	char		*qf_name;
2234	unsigned long	qf_bit;
2235};
2236
2237static struct qflags	AddressFlags[] =
2238{
2239	{ "QGOODUID",		QGOODUID	},
2240	{ "QPRIMARY",		QPRIMARY	},
2241	{ "QNOTREMOTE",		QNOTREMOTE	},
2242	{ "QSELFREF",		QSELFREF	},
2243	{ "QBOGUSSHELL",	QBOGUSSHELL	},
2244	{ "QUNSAFEADDR",	QUNSAFEADDR	},
2245	{ "QPINGONSUCCESS",	QPINGONSUCCESS	},
2246	{ "QPINGONFAILURE",	QPINGONFAILURE	},
2247	{ "QPINGONDELAY",	QPINGONDELAY	},
2248	{ "QHASNOTIFY",		QHASNOTIFY	},
2249	{ "QRELAYED",		QRELAYED	},
2250	{ "QEXPANDED",		QEXPANDED	},
2251	{ "QDELIVERED",		QDELIVERED	},
2252	{ "QDELAYED",		QDELAYED	},
2253	{ "QTHISPASS",		QTHISPASS	},
2254	{ "QRCPTOK",		QRCPTOK		},
2255	{ NULL,			0		}
2256};
2257
2258void
2259printaddr(a, follow)
2260	register ADDRESS *a;
2261	bool follow;
2262{
2263	register MAILER *m;
2264	MAILER pseudomailer;
2265	register struct qflags *qfp;
2266	bool firstone;
2267
2268	if (a == NULL)
2269	{
2270		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "[NULL]\n");
2271		return;
2272	}
2273
2274	while (a != NULL)
2275	{
2276		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%p=", a);
2277		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2278
2279		/* find the mailer -- carefully */
2280		m = a->q_mailer;
2281		if (m == NULL)
2282		{
2283			m = &pseudomailer;
2284			m->m_mno = -1;
2285			m->m_name = "NULL";
2286		}
2287
2288		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2289				     "%s:\n\tmailer %d (%s), host `%s'\n",
2290				     a->q_paddr == NULL ? "<null>" : a->q_paddr,
2291				     m->m_mno, m->m_name,
2292				     a->q_host == NULL ? "<null>" : a->q_host);
2293		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2294				     "\tuser `%s', ruser `%s'\n",
2295				     a->q_user,
2296				     a->q_ruser == NULL ? "<null>" : a->q_ruser);
2297		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\tstate=");
2298		switch (a->q_state)
2299		{
2300		  case QS_OK:
2301			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "OK");
2302			break;
2303
2304		  case QS_DONTSEND:
2305			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2306					     "DONTSEND");
2307			break;
2308
2309		  case QS_BADADDR:
2310			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2311					     "BADADDR");
2312			break;
2313
2314		  case QS_QUEUEUP:
2315			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2316					     "QUEUEUP");
2317			break;
2318
2319		  case QS_RETRY:
2320			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "RETRY");
2321			break;
2322
2323		  case QS_SENT:
2324			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "SENT");
2325			break;
2326
2327		  case QS_VERIFIED:
2328			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2329					     "VERIFIED");
2330			break;
2331
2332		  case QS_EXPANDED:
2333			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2334					     "EXPANDED");
2335			break;
2336
2337		  case QS_SENDER:
2338			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2339					     "SENDER");
2340			break;
2341
2342		  case QS_CLONED:
2343			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2344					     "CLONED");
2345			break;
2346
2347		  case QS_DISCARDED:
2348			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2349					     "DISCARDED");
2350			break;
2351
2352		  case QS_REPLACED:
2353			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2354					     "REPLACED");
2355			break;
2356
2357		  case QS_REMOVED:
2358			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2359					     "REMOVED");
2360			break;
2361
2362		  case QS_DUPLICATE:
2363			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2364					     "DUPLICATE");
2365			break;
2366
2367		  case QS_INCLUDED:
2368			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2369					     "INCLUDED");
2370			break;
2371
2372		  default:
2373			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2374					     "%d", a->q_state);
2375			break;
2376		}
2377		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2378				     ", next=%p, alias %p, uid %d, gid %d\n",
2379				     a->q_next, a->q_alias,
2380				     (int) a->q_uid, (int) a->q_gid);
2381		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\tflags=%lx<",
2382				     a->q_flags);
2383		firstone = true;
2384		for (qfp = AddressFlags; qfp->qf_name != NULL; qfp++)
2385		{
2386			if (!bitset(qfp->qf_bit, a->q_flags))
2387				continue;
2388			if (!firstone)
2389				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2390						     ",");
2391			firstone = false;
2392			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s",
2393					     qfp->qf_name);
2394		}
2395		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ">\n");
2396		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2397				     "\towner=%s, home=\"%s\", fullname=\"%s\"\n",
2398				     a->q_owner == NULL ? "(none)" : a->q_owner,
2399				     a->q_home == NULL ? "(none)" : a->q_home,
2400				     a->q_fullname == NULL ? "(none)" : a->q_fullname);
2401		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2402				     "\torcpt=\"%s\", statmta=%s, status=%s\n",
2403				     a->q_orcpt == NULL ? "(none)" : a->q_orcpt,
2404				     a->q_statmta == NULL ? "(none)" : a->q_statmta,
2405				     a->q_status == NULL ? "(none)" : a->q_status);
2406		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2407				     "\tfinalrcpt=\"%s\"\n",
2408				     a->q_finalrcpt == NULL ? "(none)" : a->q_finalrcpt);
2409		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2410				     "\trstatus=\"%s\"\n",
2411				     a->q_rstatus == NULL ? "(none)" : a->q_rstatus);
2412		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2413				     "\tstatdate=%s\n",
2414				     a->q_statdate == 0 ? "(none)" : ctime(&a->q_statdate));
2415
2416		if (!follow)
2417			return;
2418		a = a->q_next;
2419	}
2420}
2421/*
2422**  EMPTYADDR -- return true if this address is empty (``<>'')
2423**
2424**	Parameters:
2425**		a -- pointer to the address
2426**
2427**	Returns:
2428**		true -- if this address is "empty" (i.e., no one should
2429**			ever generate replies to it.
2430**		false -- if it is a "regular" (read: replyable) address.
2431*/
2432
2433bool
2434emptyaddr(a)
2435	register ADDRESS *a;
2436{
2437	return a->q_paddr == NULL || strcmp(a->q_paddr, "<>") == 0 ||
2438	       a->q_user == NULL || strcmp(a->q_user, "<>") == 0;
2439}
2440/*
2441**  REMOTENAME -- return the name relative to the current mailer
2442**
2443**	Parameters:
2444**		name -- the name to translate.
2445**		m -- the mailer that we want to do rewriting relative
2446**			to.
2447**		flags -- fine tune operations.
2448**		pstat -- pointer to status word.
2449**		e -- the current envelope.
2450**
2451**	Returns:
2452**		the text string representing this address relative to
2453**			the receiving mailer.
2454**
2455**	Side Effects:
2456**		none.
2457**
2458**	Warnings:
2459**		The text string returned is tucked away locally;
2460**			copy it if you intend to save it.
2461*/
2462
2463char *
2464remotename(name, m, flags, pstat, e)
2465	char *name;
2466	struct mailer *m;
2467	int flags;
2468	int *pstat;
2469	register ENVELOPE *e;
2470{
2471	register char **pvp;
2472	char *SM_NONVOLATILE fancy;
2473	char *oldg;
2474	int rwset;
2475	static char buf[MAXNAME + 1];
2476	char lbuf[MAXNAME + 1];
2477	char pvpbuf[PSBUFSIZE];
2478	char addrtype[4];
2479
2480	if (tTd(12, 1))
2481		sm_dprintf("remotename(%s)\n", name);
2482
2483	/* don't do anything if we are tagging it as special */
2484	if (bitset(RF_SENDERADDR, flags))
2485	{
2486		rwset = bitset(RF_HEADERADDR, flags) ? m->m_sh_rwset
2487						     : m->m_se_rwset;
2488		addrtype[2] = 's';
2489	}
2490	else
2491	{
2492		rwset = bitset(RF_HEADERADDR, flags) ? m->m_rh_rwset
2493						     : m->m_re_rwset;
2494		addrtype[2] = 'r';
2495	}
2496	if (rwset < 0)
2497		return name;
2498	addrtype[1] = ' ';
2499	addrtype[3] = '\0';
2500	addrtype[0] = bitset(RF_HEADERADDR, flags) ? 'h' : 'e';
2501	macdefine(&e->e_macro, A_TEMP, macid("{addr_type}"), addrtype);
2502
2503	/*
2504	**  Do a heuristic crack of this name to extract any comment info.
2505	**	This will leave the name as a comment and a $g macro.
2506	*/
2507
2508	if (bitset(RF_CANONICAL, flags) || bitnset(M_NOCOMMENT, m->m_flags))
2509		fancy = "\201g";
2510	else
2511		fancy = crackaddr(name);
2512
2513	/*
2514	**  Turn the name into canonical form.
2515	**	Normally this will be RFC 822 style, i.e., "user@domain".
2516	**	If this only resolves to "user", and the "C" flag is
2517	**	specified in the sending mailer, then the sender's
2518	**	domain will be appended.
2519	*/
2520
2521	pvp = prescan(name, '\0', pvpbuf, sizeof pvpbuf, NULL, NULL);
2522	if (pvp == NULL)
2523		return name;
2524	if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
2525		*pstat = EX_TEMPFAIL;
2526	if (bitset(RF_ADDDOMAIN, flags) && e->e_fromdomain != NULL)
2527	{
2528		/* append from domain to this address */
2529		register char **pxp = pvp;
2530		int l = MAXATOM;	/* size of buffer for pvp */
2531
2532		/* see if there is an "@domain" in the current name */
2533		while (*pxp != NULL && strcmp(*pxp, "@") != 0)
2534		{
2535			pxp++;
2536			--l;
2537		}
2538		if (*pxp == NULL)
2539		{
2540			/* no.... append the "@domain" from the sender */
2541			register char **qxq = e->e_fromdomain;
2542
2543			while ((*pxp++ = *qxq++) != NULL)
2544			{
2545				if (--l <= 0)
2546				{
2547					*--pxp = NULL;
2548					usrerr("553 5.1.0 remotename: too many tokens");
2549					*pstat = EX_UNAVAILABLE;
2550					break;
2551				}
2552			}
2553			if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
2554				*pstat = EX_TEMPFAIL;
2555		}
2556	}
2557
2558	/*
2559	**  Do more specific rewriting.
2560	**	Rewrite using ruleset 1 or 2 depending on whether this is
2561	**		a sender address or not.
2562	**	Then run it through any receiving-mailer-specific rulesets.
2563	*/
2564
2565	if (bitset(RF_SENDERADDR, flags))
2566	{
2567		if (REWRITE(pvp, 1, e) == EX_TEMPFAIL)
2568			*pstat = EX_TEMPFAIL;
2569	}
2570	else
2571	{
2572		if (REWRITE(pvp, 2, e) == EX_TEMPFAIL)
2573			*pstat = EX_TEMPFAIL;
2574	}
2575	if (rwset > 0)
2576	{
2577		if (REWRITE(pvp, rwset, e) == EX_TEMPFAIL)
2578			*pstat = EX_TEMPFAIL;
2579	}
2580
2581	/*
2582	**  Do any final sanitation the address may require.
2583	**	This will normally be used to turn internal forms
2584	**	(e.g., user@host.LOCAL) into external form.  This
2585	**	may be used as a default to the above rules.
2586	*/
2587
2588	if (REWRITE(pvp, 4, e) == EX_TEMPFAIL)
2589		*pstat = EX_TEMPFAIL;
2590
2591	/*
2592	**  Now restore the comment information we had at the beginning.
2593	*/
2594
2595	cataddr(pvp, NULL, lbuf, sizeof lbuf, '\0');
2596	oldg = macget(&e->e_macro, 'g');
2597	macset(&e->e_macro, 'g', lbuf);
2598
2599	SM_TRY
2600		/* need to make sure route-addrs have <angle brackets> */
2601		if (bitset(RF_CANONICAL, flags) && lbuf[0] == '@')
2602			expand("<\201g>", buf, sizeof buf, e);
2603		else
2604			expand(fancy, buf, sizeof buf, e);
2605	SM_FINALLY
2606		macset(&e->e_macro, 'g', oldg);
2607	SM_END_TRY
2608
2609	if (tTd(12, 1))
2610		sm_dprintf("remotename => `%s'\n", buf);
2611	return buf;
2612}
2613/*
2614**  MAPLOCALUSER -- run local username through ruleset 5 for final redirection
2615**
2616**	Parameters:
2617**		a -- the address to map (but just the user name part).
2618**		sendq -- the sendq in which to install any replacement
2619**			addresses.
2620**		aliaslevel -- the alias nesting depth.
2621**		e -- the envelope.
2622**
2623**	Returns:
2624**		none.
2625*/
2626
2627#define Q_COPYFLAGS	(QPRIMARY|QBOGUSSHELL|QUNSAFEADDR|\
2628			 Q_PINGFLAGS|QHASNOTIFY|\
2629			 QRELAYED|QEXPANDED|QDELIVERED|QDELAYED|\
2630			 QBYTRACE|QBYNDELAY|QBYNRELAY)
2631
2632void
2633maplocaluser(a, sendq, aliaslevel, e)
2634	register ADDRESS *a;
2635	ADDRESS **sendq;
2636	int aliaslevel;
2637	ENVELOPE *e;
2638{
2639	register char **pvp;
2640	register ADDRESS *SM_NONVOLATILE a1 = NULL;
2641	auto char *delimptr;
2642	char pvpbuf[PSBUFSIZE];
2643
2644	if (tTd(29, 1))
2645	{
2646		sm_dprintf("maplocaluser: ");
2647		printaddr(a, false);
2648	}
2649	pvp = prescan(a->q_user, '\0', pvpbuf, sizeof pvpbuf, &delimptr, NULL);
2650	if (pvp == NULL)
2651	{
2652		if (tTd(29, 9))
2653			sm_dprintf("maplocaluser: cannot prescan %s\n",
2654				a->q_user);
2655		return;
2656	}
2657
2658	macdefine(&e->e_macro, A_PERM, 'h', a->q_host);
2659	macdefine(&e->e_macro, A_PERM, 'u', a->q_user);
2660	macdefine(&e->e_macro, A_PERM, 'z', a->q_home);
2661
2662	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
2663	if (REWRITE(pvp, 5, e) == EX_TEMPFAIL)
2664	{
2665		if (tTd(29, 9))
2666			sm_dprintf("maplocaluser: rewrite tempfail\n");
2667		a->q_state = QS_QUEUEUP;
2668		a->q_status = "4.4.3";
2669		return;
2670	}
2671	if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
2672	{
2673		if (tTd(29, 9))
2674			sm_dprintf("maplocaluser: doesn't resolve\n");
2675		return;
2676	}
2677
2678	SM_TRY
2679		a1 = buildaddr(pvp, NULL, 0, e);
2680	SM_EXCEPT(exc, "E:mta.quickabort")
2681
2682		/*
2683		**  mark address as bad, S5 returned an error
2684		**	and we gave that back to the SMTP client.
2685		*/
2686
2687		a->q_state = QS_DONTSEND;
2688		sm_exc_raisenew_x(&EtypeQuickAbort, 2);
2689	SM_END_TRY
2690
2691	/* if non-null, mailer destination specified -- has it changed? */
2692	if (a1 == NULL || sameaddr(a, a1))
2693	{
2694		if (tTd(29, 9))
2695			sm_dprintf("maplocaluser: address unchanged\n");
2696		return;
2697	}
2698
2699	/* make new address take on flags and print attributes of old */
2700	a1->q_flags &= ~Q_COPYFLAGS;
2701	a1->q_flags |= a->q_flags & Q_COPYFLAGS;
2702	a1->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_paddr);
2703	a1->q_finalrcpt = a->q_finalrcpt;
2704	a1->q_orcpt = a->q_orcpt;
2705
2706	/* mark old address as dead; insert new address */
2707	a->q_state = QS_REPLACED;
2708	if (tTd(29, 5))
2709	{
2710		sm_dprintf("maplocaluser: QS_REPLACED ");
2711		printaddr(a, false);
2712	}
2713	a1->q_alias = a;
2714	allocaddr(a1, RF_COPYALL, sm_rpool_strdup_x(e->e_rpool, a->q_paddr), e);
2715	(void) recipient(a1, sendq, aliaslevel, e);
2716}
2717/*
2718**  DEQUOTE_INIT -- initialize dequote map
2719**
2720**	Parameters:
2721**		map -- the internal map structure.
2722**		args -- arguments.
2723**
2724**	Returns:
2725**		true.
2726*/
2727
2728bool
2729dequote_init(map, args)
2730	MAP *map;
2731	char *args;
2732{
2733	register char *p = args;
2734
2735	/* there is no check whether there is really an argument */
2736	map->map_mflags |= MF_KEEPQUOTES;
2737	for (;;)
2738	{
2739		while (isascii(*p) && isspace(*p))
2740			p++;
2741		if (*p != '-')
2742			break;
2743		switch (*++p)
2744		{
2745		  case 'a':
2746			map->map_app = ++p;
2747			break;
2748
2749		  case 'D':
2750			map->map_mflags |= MF_DEFER;
2751			break;
2752
2753		  case 'S':
2754		  case 's':
2755			map->map_spacesub = *++p;
2756			break;
2757		}
2758		while (*p != '\0' && !(isascii(*p) && isspace(*p)))
2759			p++;
2760		if (*p != '\0')
2761			*p = '\0';
2762	}
2763	if (map->map_app != NULL)
2764		map->map_app = newstr(map->map_app);
2765
2766	return true;
2767}
2768/*
2769**  DEQUOTE_MAP -- unquote an address
2770**
2771**	Parameters:
2772**		map -- the internal map structure (ignored).
2773**		name -- the name to dequote.
2774**		av -- arguments (ignored).
2775**		statp -- pointer to status out-parameter.
2776**
2777**	Returns:
2778**		NULL -- if there were no quotes, or if the resulting
2779**			unquoted buffer would not be acceptable to prescan.
2780**		else -- The dequoted buffer.
2781*/
2782
2783/* ARGSUSED2 */
2784char *
2785dequote_map(map, name, av, statp)
2786	MAP *map;
2787	char *name;
2788	char **av;
2789	int *statp;
2790{
2791	register char *p;
2792	register char *q;
2793	register char c;
2794	int anglecnt = 0;
2795	int cmntcnt = 0;
2796	int quotecnt = 0;
2797	int spacecnt = 0;
2798	bool quotemode = false;
2799	bool bslashmode = false;
2800	char spacesub = map->map_spacesub;
2801
2802	for (p = q = name; (c = *p++) != '\0'; )
2803	{
2804		if (bslashmode)
2805		{
2806			bslashmode = false;
2807			*q++ = c;
2808			continue;
2809		}
2810
2811		if (c == ' ' && spacesub != '\0')
2812			c = spacesub;
2813
2814		switch (c)
2815		{
2816		  case '\\':
2817			bslashmode = true;
2818			break;
2819
2820		  case '(':
2821			cmntcnt++;
2822			break;
2823
2824		  case ')':
2825			if (cmntcnt-- <= 0)
2826				return NULL;
2827			break;
2828
2829		  case ' ':
2830		  case '\t':
2831			spacecnt++;
2832			break;
2833		}
2834
2835		if (cmntcnt > 0)
2836		{
2837			*q++ = c;
2838			continue;
2839		}
2840
2841		switch (c)
2842		{
2843		  case '"':
2844			quotemode = !quotemode;
2845			quotecnt++;
2846			continue;
2847
2848		  case '<':
2849			anglecnt++;
2850			break;
2851
2852		  case '>':
2853			if (anglecnt-- <= 0)
2854				return NULL;
2855			break;
2856		}
2857		*q++ = c;
2858	}
2859
2860	if (anglecnt != 0 || cmntcnt != 0 || bslashmode ||
2861	    quotemode || quotecnt <= 0 || spacecnt != 0)
2862		return NULL;
2863	*q++ = '\0';
2864	return map_rewrite(map, name, strlen(name), NULL);
2865}
2866/*
2867**  RSCHECK -- check string(s) for validity using rewriting sets
2868**
2869**	Parameters:
2870**		rwset -- the rewriting set to use.
2871**		p1 -- the first string to check.
2872**		p2 -- the second string to check -- may be null.
2873**		e -- the current envelope.
2874**		flags -- control some behavior, see RSF_ in sendmail.h
2875**		logl -- logging level.
2876**		host -- NULL or relay host.
2877**		logid -- id for sm_syslog.
2878**
2879**	Returns:
2880**		EX_OK -- if the rwset doesn't resolve to $#error
2881**		else -- the failure status (message printed)
2882*/
2883
2884int
2885rscheck(rwset, p1, p2, e, flags, logl, host, logid)
2886	char *rwset;
2887	char *p1;
2888	char *p2;
2889	ENVELOPE *e;
2890	int flags;
2891	int logl;
2892	char *host;
2893	char *logid;
2894{
2895	char *volatile buf;
2896	int bufsize;
2897	int saveexitstat;
2898	int volatile rstat = EX_OK;
2899	char **pvp;
2900	int rsno;
2901	bool volatile discard = false;
2902	auto ADDRESS a1;
2903	bool saveQuickAbort = QuickAbort;
2904	bool saveSuprErrs = SuprErrs;
2905#if _FFR_QUARANTINE
2906	bool quarantine = false;
2907	char ubuf[BUFSIZ * 2];
2908#endif /* _FFR_QUARANTINE */
2909	char buf0[MAXLINE];
2910	char pvpbuf[PSBUFSIZE];
2911	extern char MsgBuf[];
2912
2913	if (tTd(48, 2))
2914		sm_dprintf("rscheck(%s, %s, %s)\n", rwset, p1,
2915			p2 == NULL ? "(NULL)" : p2);
2916
2917	rsno = strtorwset(rwset, NULL, ST_FIND);
2918	if (rsno < 0)
2919		return EX_OK;
2920
2921	if (p2 != NULL)
2922	{
2923		bufsize = strlen(p1) + strlen(p2) + 2;
2924		if (bufsize > sizeof buf0)
2925			buf = sm_malloc_x(bufsize);
2926		else
2927		{
2928			buf = buf0;
2929			bufsize = sizeof buf0;
2930		}
2931		(void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2);
2932	}
2933	else
2934	{
2935		bufsize = strlen(p1) + 1;
2936		if (bufsize > sizeof buf0)
2937			buf = sm_malloc_x(bufsize);
2938		else
2939		{
2940			buf = buf0;
2941			bufsize = sizeof buf0;
2942		}
2943		(void) sm_strlcpy(buf, p1, bufsize);
2944	}
2945	SM_TRY
2946	{
2947		SuprErrs = true;
2948		QuickAbort = false;
2949		pvp = prescan(buf, '\0', pvpbuf, sizeof pvpbuf, NULL,
2950			      bitset(RSF_RMCOMM, flags) ? NULL : TokTypeNoC);
2951		SuprErrs = saveSuprErrs;
2952		if (pvp == NULL)
2953		{
2954			if (tTd(48, 2))
2955				sm_dprintf("rscheck: cannot prescan input\n");
2956	/*
2957			syserr("rscheck: cannot prescan input: \"%s\"",
2958				shortenstring(buf, MAXSHORTSTR));
2959			rstat = EX_DATAERR;
2960	*/
2961			goto finis;
2962		}
2963		if (bitset(RSF_UNSTRUCTURED, flags))
2964			SuprErrs = true;
2965		(void) REWRITE(pvp, rsno, e);
2966		if (bitset(RSF_UNSTRUCTURED, flags))
2967			SuprErrs = saveSuprErrs;
2968		if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET ||
2969		    pvp[1] == NULL || (strcmp(pvp[1], "error") != 0 &&
2970				       strcmp(pvp[1], "discard") != 0))
2971		{
2972			goto finis;
2973		}
2974
2975		if (strcmp(pvp[1], "discard") == 0)
2976		{
2977			if (tTd(48, 2))
2978				sm_dprintf("rscheck: discard mailer selected\n");
2979			e->e_flags |= EF_DISCARD;
2980			discard = true;
2981		}
2982#if _FFR_QUARANTINE
2983		else if (strcmp(pvp[1], "error") == 0 &&
2984			 pvp[2] != NULL && (pvp[2][0] & 0377) == CANONHOST &&
2985			 pvp[3] != NULL && strcmp(pvp[3], "quarantine") == 0)
2986		{
2987			if (pvp[4] == NULL ||
2988			    (pvp[4][0] & 0377) != CANONUSER ||
2989			    pvp[5] == NULL)
2990				e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,
2991								 rwset);
2992			else
2993			{
2994				cataddr(&(pvp[5]), NULL, ubuf,
2995					sizeof ubuf, ' ');
2996				e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,
2997								 ubuf);
2998			}
2999			macdefine(&e->e_macro, A_PERM,
3000				  macid("{quarantine}"), e->e_quarmsg);
3001			quarantine = true;
3002		}
3003#endif /* _FFR_QUARANTINE */
3004		else
3005		{
3006			int savelogusrerrs = LogUsrErrs;
3007			static bool logged = false;
3008
3009			/* got an error -- process it */
3010			saveexitstat = ExitStat;
3011			LogUsrErrs = false;
3012			(void) buildaddr(pvp, &a1, 0, e);
3013			LogUsrErrs = savelogusrerrs;
3014			rstat = ExitStat;
3015			ExitStat = saveexitstat;
3016			if (!logged)
3017			{
3018				if (bitset(RSF_COUNT, flags))
3019					markstats(e, &a1, STATS_REJECT);
3020				logged = true;
3021			}
3022		}
3023
3024		if (LogLevel > logl)
3025		{
3026			char *relay;
3027			char *p;
3028			char lbuf[MAXLINE];
3029
3030			p = lbuf;
3031			if (p2 != NULL)
3032			{
3033				(void) sm_snprintf(p, SPACELEFT(lbuf, p),
3034					", arg2=%s",
3035					p2);
3036				p += strlen(p);
3037			}
3038
3039			if (host != NULL)
3040				relay = host;
3041			else
3042				relay = macvalue('_', e);
3043			if (relay != NULL)
3044			{
3045				(void) sm_snprintf(p, SPACELEFT(lbuf, p),
3046					", relay=%s", relay);
3047				p += strlen(p);
3048			}
3049			*p = '\0';
3050			if (discard)
3051				sm_syslog(LOG_NOTICE, logid,
3052					  "ruleset=%s, arg1=%s%s, discard",
3053					  rwset, p1, lbuf);
3054#if _FFR_QUARANTINE
3055			else if (quarantine)
3056				sm_syslog(LOG_NOTICE, logid,
3057					  "ruleset=%s, arg1=%s%s, quarantine=%s",
3058					  rwset, p1, lbuf, ubuf);
3059#endif /* _FFR_QUARANTINE */
3060			else
3061				sm_syslog(LOG_NOTICE, logid,
3062					  "ruleset=%s, arg1=%s%s, reject=%s",
3063					  rwset, p1, lbuf, MsgBuf);
3064		}
3065
3066	 finis: ;
3067	}
3068	SM_FINALLY
3069	{
3070		/* clean up */
3071		if (buf != buf0)
3072			sm_free(buf);
3073		QuickAbort = saveQuickAbort;
3074	}
3075	SM_END_TRY
3076
3077	setstat(rstat);
3078
3079	/* rulesets don't set errno */
3080	errno = 0;
3081	if (rstat != EX_OK && QuickAbort)
3082		sm_exc_raisenew_x(&EtypeQuickAbort, 2);
3083	return rstat;
3084}
3085/*
3086**  RSCAP -- call rewriting set to return capabilities
3087**
3088**	Parameters:
3089**		rwset -- the rewriting set to use.
3090**		p1 -- the first string to check.
3091**		p2 -- the second string to check -- may be null.
3092**		e -- the current envelope.
3093**		pvp -- pointer to token vector.
3094**		pvpbuf -- buffer space.
3095**
3096**	Returns:
3097**		EX_UNAVAILABLE -- ruleset doesn't exist.
3098**		EX_DATAERR -- prescan() failed.
3099**		EX_OK -- rewrite() was successful.
3100**		else -- return status from rewrite().
3101*/
3102
3103int
3104rscap(rwset, p1, p2, e, pvp, pvpbuf, size)
3105	char *rwset;
3106	char *p1;
3107	char *p2;
3108	ENVELOPE *e;
3109	char ***pvp;
3110	char *pvpbuf;
3111	int size;
3112{
3113	char *volatile buf;
3114	int bufsize;
3115	int volatile rstat = EX_OK;
3116	int rsno;
3117	bool saveQuickAbort = QuickAbort;
3118	bool saveSuprErrs = SuprErrs;
3119	char buf0[MAXLINE];
3120	extern char MsgBuf[];
3121
3122	if (tTd(48, 2))
3123		sm_dprintf("rscap(%s, %s, %s)\n", rwset, p1,
3124			p2 == NULL ? "(NULL)" : p2);
3125
3126	if (pvp != NULL)
3127		*pvp = NULL;
3128	rsno = strtorwset(rwset, NULL, ST_FIND);
3129	if (rsno < 0)
3130		return EX_UNAVAILABLE;
3131
3132	if (p2 != NULL)
3133	{
3134		bufsize = strlen(p1) + strlen(p2) + 2;
3135		if (bufsize > sizeof buf0)
3136			buf = sm_malloc_x(bufsize);
3137		else
3138		{
3139			buf = buf0;
3140			bufsize = sizeof buf0;
3141		}
3142		(void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2);
3143	}
3144	else
3145	{
3146		bufsize = strlen(p1) + 1;
3147		if (bufsize > sizeof buf0)
3148			buf = sm_malloc_x(bufsize);
3149		else
3150		{
3151			buf = buf0;
3152			bufsize = sizeof buf0;
3153		}
3154		(void) sm_strlcpy(buf, p1, bufsize);
3155	}
3156	SM_TRY
3157	{
3158		SuprErrs = true;
3159		QuickAbort = false;
3160		*pvp = prescan(buf, '\0', pvpbuf, size, NULL, NULL);
3161		if (*pvp != NULL)
3162			rstat = REWRITE(*pvp, rsno, e);
3163		else
3164		{
3165			if (tTd(48, 2))
3166				sm_dprintf("rscap: cannot prescan input\n");
3167			rstat = EX_DATAERR;
3168		}
3169	}
3170	SM_FINALLY
3171	{
3172		/* clean up */
3173		if (buf != buf0)
3174			sm_free(buf);
3175		SuprErrs = saveSuprErrs;
3176		QuickAbort = saveQuickAbort;
3177
3178		/* prevent information leak, this may contain rewrite error */
3179		MsgBuf[0] = '\0';
3180	}
3181	SM_END_TRY
3182	return rstat;
3183}
3184