1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)parseaddr.c	8.24 (Berkeley) 12/11/93";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 
15 /*
16 **  PARSEADDR -- Parse an address
17 **
18 **	Parses an address and breaks it up into three parts: a
19 **	net to transmit the message on, the host to transmit it
20 **	to, and a user on that host.  These are loaded into an
21 **	ADDRESS header with the values squirreled away if necessary.
22 **	The "user" part may not be a real user; the process may
23 **	just reoccur on that machine.  For example, on a machine
24 **	with an arpanet connection, the address
25 **		csvax.bill@berkeley
26 **	will break up to a "user" of 'csvax.bill' and a host
27 **	of 'berkeley' -- to be transmitted over the arpanet.
28 **
29 **	Parameters:
30 **		addr -- the address to parse.
31 **		a -- a pointer to the address descriptor buffer.
32 **			If NULL, a header will be created.
33 **		flags -- describe detail for parsing.  See RF_ definitions
34 **			in sendmail.h.
35 **		delim -- the character to terminate the address, passed
36 **			to prescan.
37 **		delimptr -- if non-NULL, set to the location of the
38 **			delim character that was found.
39 **		e -- the envelope that will contain this address.
40 **
41 **	Returns:
42 **		A pointer to the address descriptor header (`a' if
43 **			`a' is non-NULL).
44 **		NULL on error.
45 **
46 **	Side Effects:
47 **		none
48 */
49 
50 /* following delimiters are inherent to the internal algorithms */
51 # define DELIMCHARS	"()<>,;\r\n"	/* default word delimiters */
52 
53 ADDRESS *
54 parseaddr(addr, a, flags, delim, delimptr, e)
55 	char *addr;
56 	register ADDRESS *a;
57 	int flags;
58 	int delim;
59 	char **delimptr;
60 	register ENVELOPE *e;
61 {
62 	register char **pvp;
63 	auto char *delimptrbuf;
64 	bool queueup;
65 	char pvpbuf[PSBUFSIZE];
66 	extern ADDRESS *buildaddr();
67 	extern bool invalidaddr();
68 
69 	/*
70 	**  Initialize and prescan address.
71 	*/
72 
73 	e->e_to = addr;
74 	if (tTd(20, 1))
75 		printf("\n--parseaddr(%s)\n", addr);
76 
77 	if (delimptr == NULL)
78 		delimptr = &delimptrbuf;
79 
80 	pvp = prescan(addr, delim, pvpbuf, sizeof pvpbuf, delimptr);
81 	if (pvp == NULL)
82 	{
83 		if (tTd(20, 1))
84 			printf("parseaddr-->NULL\n");
85 		return (NULL);
86 	}
87 
88 	if (invalidaddr(addr, delim == '\0' ? NULL : *delimptr))
89 	{
90 		if (tTd(20, 1))
91 			printf("parseaddr-->bad address\n");
92 		return NULL;
93 	}
94 
95 	/*
96 	**  Save addr if we are going to have to.
97 	**
98 	**	We have to do this early because there is a chance that
99 	**	the map lookups in the rewriting rules could clobber
100 	**	static memory somewhere.
101 	*/
102 
103 	if (bitset(RF_COPYPADDR, flags) && addr != NULL)
104 	{
105 		char savec = **delimptr;
106 
107 		if (savec != '\0')
108 			**delimptr = '\0';
109 		addr = newstr(addr);
110 		if (savec != '\0')
111 			**delimptr = savec;
112 	}
113 
114 	/*
115 	**  Apply rewriting rules.
116 	**	Ruleset 0 does basic parsing.  It must resolve.
117 	*/
118 
119 	queueup = FALSE;
120 	if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
121 		queueup = TRUE;
122 	if (rewrite(pvp, 0, 0, e) == EX_TEMPFAIL)
123 		queueup = TRUE;
124 
125 
126 	/*
127 	**  Build canonical address from pvp.
128 	*/
129 
130 	a = buildaddr(pvp, a, flags, e);
131 
132 	/*
133 	**  Make local copies of the host & user and then
134 	**  transport them out.
135 	*/
136 
137 	allocaddr(a, flags, addr);
138 	if (bitset(QBADADDR, a->q_flags))
139 		return a;
140 
141 	/*
142 	**  If there was a parsing failure, mark it for queueing.
143 	*/
144 
145 	if (queueup)
146 	{
147 		char *msg = "Transient parse error -- message queued for future delivery";
148 
149 		if (tTd(20, 1))
150 			printf("parseaddr: queuing message\n");
151 		message(msg);
152 		if (e->e_message == NULL)
153 			e->e_message = newstr(msg);
154 		a->q_flags |= QQUEUEUP;
155 	}
156 
157 	/*
158 	**  Compute return value.
159 	*/
160 
161 	if (tTd(20, 1))
162 	{
163 		printf("parseaddr-->");
164 		printaddr(a, FALSE);
165 	}
166 
167 	return (a);
168 }
169 /*
170 **  INVALIDADDR -- check for address containing meta-characters
171 **
172 **	Parameters:
173 **		addr -- the address to check.
174 **
175 **	Returns:
176 **		TRUE -- if the address has any "wierd" characters
177 **		FALSE -- otherwise.
178 */
179 
180 bool
181 invalidaddr(addr, delimptr)
182 	register char *addr;
183 	char *delimptr;
184 {
185 	char savedelim;
186 
187 	if (delimptr != NULL)
188 	{
189 		savedelim = *delimptr;
190 		if (savedelim != '\0')
191 			*delimptr = '\0';
192 	}
193 #if 0
194 	/* for testing.... */
195 	if (strcmp(addr, "INvalidADDR") == 0)
196 	{
197 		usrerr("553 INvalid ADDRess");
198 		goto addrfailure;
199 	}
200 #endif
201 	for (; *addr != '\0'; addr++)
202 	{
203 		if ((*addr & 0340) == 0200)
204 			break;
205 	}
206 	if (*addr == '\0')
207 	{
208 		if (savedelim != '\0' && delimptr != NULL)
209 			*delimptr = savedelim;
210 		return FALSE;
211 	}
212 	setstat(EX_USAGE);
213 	usrerr("553 Address contained invalid control characters");
214   addrfailure:
215 	if (savedelim != '\0' && delimptr != NULL)
216 		*delimptr = savedelim;
217 	return TRUE;
218 }
219 /*
220 **  ALLOCADDR -- do local allocations of address on demand.
221 **
222 **	Also lowercases the host name if requested.
223 **
224 **	Parameters:
225 **		a -- the address to reallocate.
226 **		flags -- the copy flag (see RF_ definitions in sendmail.h
227 **			for a description).
228 **		paddr -- the printname of the address.
229 **
230 **	Returns:
231 **		none.
232 **
233 **	Side Effects:
234 **		Copies portions of a into local buffers as requested.
235 */
236 
237 allocaddr(a, flags, paddr)
238 	register ADDRESS *a;
239 	int flags;
240 	char *paddr;
241 {
242 	if (tTd(24, 4))
243 		printf("allocaddr(flags=%o, paddr=%s)\n", flags, paddr);
244 
245 	a->q_paddr = paddr;
246 
247 	if (a->q_user == NULL)
248 		a->q_user = "";
249 	if (a->q_host == NULL)
250 		a->q_host = "";
251 
252 	if (bitset(RF_COPYPARSE, flags))
253 	{
254 		a->q_host = newstr(a->q_host);
255 		if (a->q_user != a->q_paddr)
256 			a->q_user = newstr(a->q_user);
257 	}
258 
259 	if (a->q_paddr == NULL)
260 		a->q_paddr = a->q_user;
261 }
262 /*
263 **  PRESCAN -- Prescan name and make it canonical
264 **
265 **	Scans a name and turns it into a set of tokens.  This process
266 **	deletes blanks and comments (in parentheses).
267 **
268 **	This routine knows about quoted strings and angle brackets.
269 **
270 **	There are certain subtleties to this routine.  The one that
271 **	comes to mind now is that backslashes on the ends of names
272 **	are silently stripped off; this is intentional.  The problem
273 **	is that some versions of sndmsg (like at LBL) set the kill
274 **	character to something other than @ when reading addresses;
275 **	so people type "csvax.eric\@berkeley" -- which screws up the
276 **	berknet mailer.
277 **
278 **	Parameters:
279 **		addr -- the name to chomp.
280 **		delim -- the delimiter for the address, normally
281 **			'\0' or ','; \0 is accepted in any case.
282 **			If '\t' then we are reading the .cf file.
283 **		pvpbuf -- place to put the saved text -- note that
284 **			the pointers are static.
285 **		pvpbsize -- size of pvpbuf.
286 **		delimptr -- if non-NULL, set to the location of the
287 **			terminating delimiter.
288 **
289 **	Returns:
290 **		A pointer to a vector of tokens.
291 **		NULL on error.
292 */
293 
294 /* states and character types */
295 # define OPR		0	/* operator */
296 # define ATM		1	/* atom */
297 # define QST		2	/* in quoted string */
298 # define SPC		3	/* chewing up spaces */
299 # define ONE		4	/* pick up one character */
300 
301 # define NSTATES	5	/* number of states */
302 # define TYPE		017	/* mask to select state type */
303 
304 /* meta bits for table */
305 # define M		020	/* meta character; don't pass through */
306 # define B		040	/* cause a break */
307 # define MB		M|B	/* meta-break */
308 
309 static short StateTab[NSTATES][NSTATES] =
310 {
311    /*	oldst	chtype>	OPR	ATM	QST	SPC	ONE	*/
312 	/*OPR*/		OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,
313 	/*ATM*/		OPR|B,	ATM,	QST|B,	SPC|MB,	ONE|B,
314 	/*QST*/		QST,	QST,	OPR,	QST,	QST,
315 	/*SPC*/		OPR,	ATM,	QST,	SPC|M,	ONE,
316 	/*ONE*/		OPR,	OPR,	OPR,	OPR,	OPR,
317 };
318 
319 /* token type table -- it gets modified with $o characters */
320 static TokTypeTab[256] =
321 {
322 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
323 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
324 	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM,ATM,SPC,ATM,ATM,ATM,ATM,ATM,ATM,
325 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
326 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
327 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
328 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
329 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
330 	OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
331 	OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
332 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
333 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
334 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
335 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
336 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
337 	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
338 };
339 
340 #define toktype(c)	((int) TokTypeTab[(c) & 0xff])
341 
342 
343 # define NOCHAR		-1	/* signal nothing in lookahead token */
344 
345 char **
346 prescan(addr, delim, pvpbuf, pvpbsize, delimptr)
347 	char *addr;
348 	char delim;
349 	char pvpbuf[];
350 	char **delimptr;
351 {
352 	register char *p;
353 	register char *q;
354 	register int c;
355 	char **avp;
356 	bool bslashmode;
357 	int cmntcnt;
358 	int anglecnt;
359 	char *tok;
360 	int state;
361 	int newstate;
362 	char *saveto = CurEnv->e_to;
363 	static char *av[MAXATOM+1];
364 	static char firsttime = TRUE;
365 	extern int errno;
366 
367 	if (firsttime)
368 	{
369 		/* initialize the token type table */
370 		char obuf[50];
371 
372 		firsttime = FALSE;
373 		expand("\201o", obuf, &obuf[sizeof obuf - sizeof DELIMCHARS], CurEnv);
374 		strcat(obuf, DELIMCHARS);
375 		for (p = obuf; *p != '\0'; p++)
376 		{
377 			if (TokTypeTab[*p & 0xff] == ATM)
378 				TokTypeTab[*p & 0xff] = OPR;
379 		}
380 	}
381 
382 	/* make sure error messages don't have garbage on them */
383 	errno = 0;
384 
385 	q = pvpbuf;
386 	bslashmode = FALSE;
387 	cmntcnt = 0;
388 	anglecnt = 0;
389 	avp = av;
390 	state = ATM;
391 	c = NOCHAR;
392 	p = addr;
393 	CurEnv->e_to = p;
394 	if (tTd(22, 11))
395 	{
396 		printf("prescan: ");
397 		xputs(p);
398 		(void) putchar('\n');
399 	}
400 
401 	do
402 	{
403 		/* read a token */
404 		tok = q;
405 		for (;;)
406 		{
407 			/* store away any old lookahead character */
408 			if (c != NOCHAR && !bslashmode)
409 			{
410 				/* see if there is room */
411 				if (q >= &pvpbuf[pvpbsize - 5])
412 				{
413 					usrerr("553 Address too long");
414 	returnnull:
415 					if (delimptr != NULL)
416 						*delimptr = p;
417 					CurEnv->e_to = saveto;
418 					return (NULL);
419 				}
420 
421 				/* squirrel it away */
422 				*q++ = c;
423 			}
424 
425 			/* read a new input character */
426 			c = *p++;
427 			if (c == '\0')
428 			{
429 				/* diagnose and patch up bad syntax */
430 				if (state == QST)
431 				{
432 					usrerr("653 Unbalanced '\"'");
433 					c = '"';
434 				}
435 				else if (cmntcnt > 0)
436 				{
437 					usrerr("653 Unbalanced '('");
438 					c = ')';
439 				}
440 				else if (anglecnt > 0)
441 				{
442 					c = '>';
443 					usrerr("653 Unbalanced '<'");
444 				}
445 				else
446 					break;
447 
448 				p--;
449 			}
450 			else if (c == delim && anglecnt <= 0 &&
451 					cmntcnt <= 0 && state != QST)
452 				break;
453 
454 			if (tTd(22, 101))
455 				printf("c=%c, s=%d; ", c, state);
456 
457 			/* chew up special characters */
458 			*q = '\0';
459 			if (bslashmode)
460 			{
461 				bslashmode = FALSE;
462 
463 				/* kludge \! for naive users */
464 				if (cmntcnt > 0)
465 				{
466 					c = NOCHAR;
467 					continue;
468 				}
469 				else if (c != '!' || state == QST)
470 				{
471 					*q++ = '\\';
472 					continue;
473 				}
474 			}
475 
476 			if (c == '\\')
477 			{
478 				bslashmode = TRUE;
479 			}
480 			else if (state == QST)
481 			{
482 				/* do nothing, just avoid next clauses */
483 			}
484 			else if (c == '(')
485 			{
486 				cmntcnt++;
487 				c = NOCHAR;
488 			}
489 			else if (c == ')')
490 			{
491 				if (cmntcnt <= 0)
492 				{
493 					usrerr("653 Unbalanced ')'");
494 					c = NOCHAR;
495 				}
496 				else
497 					cmntcnt--;
498 			}
499 			else if (cmntcnt > 0)
500 				c = NOCHAR;
501 			else if (c == '<')
502 				anglecnt++;
503 			else if (c == '>')
504 			{
505 				if (anglecnt <= 0)
506 				{
507 					usrerr("653 Unbalanced '>'");
508 					c = NOCHAR;
509 				}
510 				else
511 					anglecnt--;
512 			}
513 			else if (delim == ' ' && isascii(c) && isspace(c))
514 				c = ' ';
515 
516 			if (c == NOCHAR)
517 				continue;
518 
519 			/* see if this is end of input */
520 			if (c == delim && anglecnt <= 0 && state != QST)
521 				break;
522 
523 			newstate = StateTab[state][toktype(c)];
524 			if (tTd(22, 101))
525 				printf("ns=%02o\n", newstate);
526 			state = newstate & TYPE;
527 			if (bitset(M, newstate))
528 				c = NOCHAR;
529 			if (bitset(B, newstate))
530 				break;
531 		}
532 
533 		/* new token */
534 		if (tok != q)
535 		{
536 			*q++ = '\0';
537 			if (tTd(22, 36))
538 			{
539 				printf("tok=");
540 				xputs(tok);
541 				(void) putchar('\n');
542 			}
543 			if (avp >= &av[MAXATOM])
544 			{
545 				syserr("553 prescan: too many tokens");
546 				goto returnnull;
547 			}
548 			if (q - tok > MAXNAME)
549 			{
550 				syserr("553 prescan: token too long");
551 				goto returnnull;
552 			}
553 			*avp++ = tok;
554 		}
555 	} while (c != '\0' && (c != delim || anglecnt > 0));
556 	*avp = NULL;
557 	p--;
558 	if (delimptr != NULL)
559 		*delimptr = p;
560 	if (tTd(22, 12))
561 	{
562 		printf("prescan==>");
563 		printav(av);
564 	}
565 	CurEnv->e_to = saveto;
566 	if (av[0] == NULL)
567 	{
568 		if (tTd(22, 1))
569 			printf("prescan: null leading token\n");
570 		return (NULL);
571 	}
572 	return (av);
573 }
574 /*
575 **  REWRITE -- apply rewrite rules to token vector.
576 **
577 **	This routine is an ordered production system.  Each rewrite
578 **	rule has a LHS (called the pattern) and a RHS (called the
579 **	rewrite); 'rwr' points the the current rewrite rule.
580 **
581 **	For each rewrite rule, 'avp' points the address vector we
582 **	are trying to match against, and 'pvp' points to the pattern.
583 **	If pvp points to a special match value (MATCHZANY, MATCHANY,
584 **	MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
585 **	matched is saved away in the match vector (pointed to by 'mvp').
586 **
587 **	When a match between avp & pvp does not match, we try to
588 **	back out.  If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
589 **	we must also back out the match in mvp.  If we reach a
590 **	MATCHANY or MATCHZANY we just extend the match and start
591 **	over again.
592 **
593 **	When we finally match, we rewrite the address vector
594 **	and try over again.
595 **
596 **	Parameters:
597 **		pvp -- pointer to token vector.
598 **		ruleset -- the ruleset to use for rewriting.
599 **		reclevel -- recursion level (to catch loops).
600 **		e -- the current envelope.
601 **
602 **	Returns:
603 **		A status code.  If EX_TEMPFAIL, higher level code should
604 **			attempt recovery.
605 **
606 **	Side Effects:
607 **		pvp is modified.
608 */
609 
610 struct match
611 {
612 	char	**first;	/* first token matched */
613 	char	**last;		/* last token matched */
614 	char	**pattern;	/* pointer to pattern */
615 };
616 
617 # define MAXMATCH	9	/* max params per rewrite */
618 
619 
620 int
621 rewrite(pvp, ruleset, reclevel, e)
622 	char **pvp;
623 	int ruleset;
624 	int reclevel;
625 	register ENVELOPE *e;
626 {
627 	register char *ap;		/* address pointer */
628 	register char *rp;		/* rewrite pointer */
629 	register char **avp;		/* address vector pointer */
630 	register char **rvp;		/* rewrite vector pointer */
631 	register struct match *mlp;	/* cur ptr into mlist */
632 	register struct rewrite *rwr;	/* pointer to current rewrite rule */
633 	int ruleno;			/* current rule number */
634 	int rstat = EX_OK;		/* return status */
635 	int loopcount;
636 	struct match mlist[MAXMATCH];	/* stores match on LHS */
637 	char *npvp[MAXATOM+1];		/* temporary space for rebuild */
638 
639 	if (OpMode == MD_TEST || tTd(21, 2))
640 	{
641 		printf("rewrite: ruleset %2d   input:", ruleset);
642 		printav(pvp);
643 	}
644 	if (ruleset < 0 || ruleset >= MAXRWSETS)
645 	{
646 		syserr("554 rewrite: illegal ruleset number %d", ruleset);
647 		return EX_CONFIG;
648 	}
649 	if (reclevel++ > 50)
650 	{
651 		syserr("rewrite: infinite recursion, ruleset %d", ruleset);
652 		return EX_CONFIG;
653 	}
654 	if (pvp == NULL)
655 		return EX_USAGE;
656 
657 	/*
658 	**  Run through the list of rewrite rules, applying
659 	**	any that match.
660 	*/
661 
662 	ruleno = 1;
663 	loopcount = 0;
664 	for (rwr = RewriteRules[ruleset]; rwr != NULL; )
665 	{
666 		if (tTd(21, 12))
667 		{
668 			printf("-----trying rule:");
669 			printav(rwr->r_lhs);
670 		}
671 
672 		/* try to match on this rule */
673 		mlp = mlist;
674 		rvp = rwr->r_lhs;
675 		avp = pvp;
676 		if (++loopcount > 100)
677 		{
678 			syserr("554 Infinite loop in ruleset %d, rule %d",
679 				ruleset, ruleno);
680 			if (tTd(21, 1))
681 			{
682 				printf("workspace: ");
683 				printav(pvp);
684 			}
685 			break;
686 		}
687 
688 		while ((ap = *avp) != NULL || *rvp != NULL)
689 		{
690 			rp = *rvp;
691 			if (tTd(21, 35))
692 			{
693 				printf("ADVANCE rp=");
694 				xputs(rp);
695 				printf(", ap=");
696 				xputs(ap);
697 				printf("\n");
698 			}
699 			if (rp == NULL)
700 			{
701 				/* end-of-pattern before end-of-address */
702 				goto backup;
703 			}
704 			if (ap == NULL && (*rp & 0377) != MATCHZANY &&
705 			    (*rp & 0377) != MATCHZERO)
706 			{
707 				/* end-of-input with patterns left */
708 				goto backup;
709 			}
710 
711 			switch (*rp & 0377)
712 			{
713 				register STAB *s;
714 				char buf[MAXLINE];
715 
716 			  case MATCHCLASS:
717 				/* match any phrase in a class */
718 				mlp->pattern = rvp;
719 				mlp->first = avp;
720 	extendclass:
721 				ap = *avp;
722 				if (ap == NULL)
723 					goto backup;
724 				mlp->last = avp++;
725 				cataddr(mlp->first, mlp->last, buf, sizeof buf, '\0');
726 				s = stab(buf, ST_CLASS, ST_FIND);
727 				if (s == NULL || !bitnset(rp[1], s->s_class))
728 				{
729 					if (tTd(21, 36))
730 					{
731 						printf("EXTEND  rp=");
732 						xputs(rp);
733 						printf(", ap=");
734 						xputs(ap);
735 						printf("\n");
736 					}
737 					goto extendclass;
738 				}
739 				if (tTd(21, 36))
740 					printf("CLMATCH\n");
741 				mlp++;
742 				break;
743 
744 			  case MATCHNCLASS:
745 				/* match any token not in a class */
746 				s = stab(ap, ST_CLASS, ST_FIND);
747 				if (s != NULL && bitnset(rp[1], s->s_class))
748 					goto backup;
749 
750 				/* fall through */
751 
752 			  case MATCHONE:
753 			  case MATCHANY:
754 				/* match exactly one token */
755 				mlp->pattern = rvp;
756 				mlp->first = avp;
757 				mlp->last = avp++;
758 				mlp++;
759 				break;
760 
761 			  case MATCHZANY:
762 				/* match zero or more tokens */
763 				mlp->pattern = rvp;
764 				mlp->first = avp;
765 				mlp->last = avp - 1;
766 				mlp++;
767 				break;
768 
769 			  case MATCHZERO:
770 				/* match zero tokens */
771 				break;
772 
773 			  case MACRODEXPAND:
774 				/*
775 				**  Match against run-time macro.
776 				**  This algorithm is broken for the
777 				**  general case (no recursive macros,
778 				**  improper tokenization) but should
779 				**  work for the usual cases.
780 				*/
781 
782 				ap = macvalue(rp[1], e);
783 				mlp->first = avp;
784 				if (tTd(21, 2))
785 					printf("rewrite: LHS $&%c => \"%s\"\n",
786 						rp[1],
787 						ap == NULL ? "(NULL)" : ap);
788 
789 				if (ap == NULL)
790 					break;
791 				while (*ap != '\0')
792 				{
793 					if (*avp == NULL ||
794 					    strncasecmp(ap, *avp, strlen(*avp)) != 0)
795 					{
796 						/* no match */
797 						avp = mlp->first;
798 						goto backup;
799 					}
800 					ap += strlen(*avp++);
801 				}
802 
803 				/* match */
804 				break;
805 
806 			  default:
807 				/* must have exact match */
808 				if (strcasecmp(rp, ap))
809 					goto backup;
810 				avp++;
811 				break;
812 			}
813 
814 			/* successful match on this token */
815 			rvp++;
816 			continue;
817 
818 	  backup:
819 			/* match failed -- back up */
820 			while (--mlp >= mlist)
821 			{
822 				rvp = mlp->pattern;
823 				rp = *rvp;
824 				avp = mlp->last + 1;
825 				ap = *avp;
826 
827 				if (tTd(21, 36))
828 				{
829 					printf("BACKUP  rp=");
830 					xputs(rp);
831 					printf(", ap=");
832 					xputs(ap);
833 					printf("\n");
834 				}
835 
836 				if (ap == NULL)
837 				{
838 					/* run off the end -- back up again */
839 					continue;
840 				}
841 				if ((*rp & 0377) == MATCHANY ||
842 				    (*rp & 0377) == MATCHZANY)
843 				{
844 					/* extend binding and continue */
845 					mlp->last = avp++;
846 					rvp++;
847 					mlp++;
848 					break;
849 				}
850 				if ((*rp & 0377) == MATCHCLASS)
851 				{
852 					/* extend binding and try again */
853 					mlp->last = avp;
854 					goto extendclass;
855 				}
856 			}
857 
858 			if (mlp < mlist)
859 			{
860 				/* total failure to match */
861 				break;
862 			}
863 		}
864 
865 		/*
866 		**  See if we successfully matched
867 		*/
868 
869 		if (mlp < mlist || *rvp != NULL)
870 		{
871 			if (tTd(21, 10))
872 				printf("----- rule fails\n");
873 			rwr = rwr->r_next;
874 			ruleno++;
875 			loopcount = 0;
876 			continue;
877 		}
878 
879 		rvp = rwr->r_rhs;
880 		if (tTd(21, 12))
881 		{
882 			printf("-----rule matches:");
883 			printav(rvp);
884 		}
885 
886 		rp = *rvp;
887 		if ((*rp & 0377) == CANONUSER)
888 		{
889 			rvp++;
890 			rwr = rwr->r_next;
891 			ruleno++;
892 			loopcount = 0;
893 		}
894 		else if ((*rp & 0377) == CANONHOST)
895 		{
896 			rvp++;
897 			rwr = NULL;
898 		}
899 		else if ((*rp & 0377) == CANONNET)
900 			rwr = NULL;
901 
902 		/* substitute */
903 		for (avp = npvp; *rvp != NULL; rvp++)
904 		{
905 			register struct match *m;
906 			register char **pp;
907 
908 			rp = *rvp;
909 			if ((*rp & 0377) == MATCHREPL)
910 			{
911 				/* substitute from LHS */
912 				m = &mlist[rp[1] - '1'];
913 				if (m < mlist || m >= mlp)
914 				{
915 					syserr("554 rewrite: ruleset %d: replacement $%c out of bounds",
916 						ruleset, rp[1]);
917 					return EX_CONFIG;
918 				}
919 				if (tTd(21, 15))
920 				{
921 					printf("$%c:", rp[1]);
922 					pp = m->first;
923 					while (pp <= m->last)
924 					{
925 						printf(" %x=\"", *pp);
926 						(void) fflush(stdout);
927 						printf("%s\"", *pp++);
928 					}
929 					printf("\n");
930 				}
931 				pp = m->first;
932 				while (pp <= m->last)
933 				{
934 					if (avp >= &npvp[MAXATOM])
935 					{
936 						syserr("554 rewrite: expansion too long");
937 						return EX_DATAERR;
938 					}
939 					*avp++ = *pp++;
940 				}
941 			}
942 			else
943 			{
944 				/* vanilla replacement */
945 				if (avp >= &npvp[MAXATOM])
946 				{
947 	toolong:
948 					syserr("554 rewrite: expansion too long");
949 					return EX_DATAERR;
950 				}
951 				if ((*rp & 0377) != MACRODEXPAND)
952 					*avp++ = rp;
953 				else
954 				{
955 					*avp = macvalue(rp[1], e);
956 					if (tTd(21, 2))
957 						printf("rewrite: RHS $&%c => \"%s\"\n",
958 							rp[1],
959 							*avp == NULL ? "(NULL)" : *avp);
960 					if (*avp != NULL)
961 						avp++;
962 				}
963 			}
964 		}
965 		*avp++ = NULL;
966 
967 		/*
968 		**  Check for any hostname/keyword lookups.
969 		*/
970 
971 		for (rvp = npvp; *rvp != NULL; rvp++)
972 		{
973 			char **hbrvp;
974 			char **xpvp;
975 			int trsize;
976 			char *replac;
977 			int endtoken;
978 			STAB *map;
979 			char *mapname;
980 			char **key_rvp;
981 			char **arg_rvp;
982 			char **default_rvp;
983 			char buf[MAXNAME + 1];
984 			char *pvpb1[MAXATOM + 1];
985 			char *argvect[10];
986 			char pvpbuf[PSBUFSIZE];
987 			char *nullpvp[1];
988 
989 			if ((**rvp & 0377) != HOSTBEGIN &&
990 			    (**rvp & 0377) != LOOKUPBEGIN)
991 				continue;
992 
993 			/*
994 			**  Got a hostname/keyword lookup.
995 			**
996 			**	This could be optimized fairly easily.
997 			*/
998 
999 			hbrvp = rvp;
1000 			if ((**rvp & 0377) == HOSTBEGIN)
1001 			{
1002 				endtoken = HOSTEND;
1003 				mapname = "host";
1004 			}
1005 			else
1006 			{
1007 				endtoken = LOOKUPEND;
1008 				mapname = *++rvp;
1009 			}
1010 			map = stab(mapname, ST_MAP, ST_FIND);
1011 			if (map == NULL)
1012 				syserr("554 rewrite: map %s not found", mapname);
1013 
1014 			/* extract the match part */
1015 			key_rvp = ++rvp;
1016 			default_rvp = NULL;
1017 			arg_rvp = argvect;
1018 			xpvp = NULL;
1019 			replac = pvpbuf;
1020 			while (*rvp != NULL && (**rvp & 0377) != endtoken)
1021 			{
1022 				int nodetype = **rvp & 0377;
1023 
1024 				if (nodetype != CANONHOST && nodetype != CANONUSER)
1025 				{
1026 					rvp++;
1027 					continue;
1028 				}
1029 
1030 				*rvp++ = NULL;
1031 
1032 				if (xpvp != NULL)
1033 				{
1034 					cataddr(xpvp, NULL, replac,
1035 						&pvpbuf[sizeof pvpbuf] - replac,
1036 						'\0');
1037 					*++arg_rvp = replac;
1038 					replac += strlen(replac) + 1;
1039 					xpvp = NULL;
1040 				}
1041 				switch (nodetype)
1042 				{
1043 				  case CANONHOST:
1044 					xpvp = rvp;
1045 					break;
1046 
1047 				  case CANONUSER:
1048 					default_rvp = rvp;
1049 					break;
1050 				}
1051 			}
1052 			if (*rvp != NULL)
1053 				*rvp++ = NULL;
1054 			if (xpvp != NULL)
1055 			{
1056 				cataddr(xpvp, NULL, replac,
1057 					&pvpbuf[sizeof pvpbuf] - replac,
1058 					'\0');
1059 				*++arg_rvp = replac;
1060 			}
1061 			*++arg_rvp = NULL;
1062 
1063 			/* save the remainder of the input string */
1064 			trsize = (int) (avp - rvp + 1) * sizeof *rvp;
1065 			bcopy((char *) rvp, (char *) pvpb1, trsize);
1066 
1067 			/* look it up */
1068 			cataddr(key_rvp, NULL, buf, sizeof buf, '\0');
1069 			argvect[0] = buf;
1070 			if (map != NULL && bitset(MF_OPEN, map->s_map.map_mflags))
1071 			{
1072 				auto int stat = EX_OK;
1073 
1074 				/* XXX should try to auto-open the map here */
1075 
1076 				if (tTd(60, 1))
1077 					printf("map_lookup(%s, %s) => ",
1078 						mapname, buf);
1079 				replac = (*map->s_map.map_class->map_lookup)(&map->s_map,
1080 						buf, argvect, &stat);
1081 				if (tTd(60, 1))
1082 					printf("%s (%d)\n",
1083 						replac ? replac : "NOT FOUND",
1084 						stat);
1085 
1086 				/* should recover if stat == EX_TEMPFAIL */
1087 				if (stat == EX_TEMPFAIL)
1088 					rstat = stat;
1089 			}
1090 			else
1091 				replac = NULL;
1092 
1093 			/* if no replacement, use default */
1094 			if (replac == NULL && default_rvp != NULL)
1095 			{
1096 				/* create the default */
1097 				cataddr(default_rvp, NULL, buf, sizeof buf, '\0');
1098 				replac = buf;
1099 			}
1100 
1101 			if (replac == NULL)
1102 			{
1103 				xpvp = key_rvp;
1104 			}
1105 			else if (*replac == '\0')
1106 			{
1107 				/* null replacement */
1108 				nullpvp[0] = NULL;
1109 				xpvp = nullpvp;
1110 			}
1111 			else
1112 			{
1113 				/* scan the new replacement */
1114 				xpvp = prescan(replac, '\0', pvpbuf,
1115 					       sizeof pvpbuf, NULL);
1116 				if (xpvp == NULL)
1117 				{
1118 					/* prescan already printed error */
1119 					return EX_DATAERR;
1120 				}
1121 			}
1122 
1123 			/* append it to the token list */
1124 			for (avp = hbrvp; *xpvp != NULL; xpvp++)
1125 			{
1126 				*avp++ = newstr(*xpvp);
1127 				if (avp >= &npvp[MAXATOM])
1128 					goto toolong;
1129 			}
1130 
1131 			/* restore the old trailing information */
1132 			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
1133 				if (avp >= &npvp[MAXATOM])
1134 					goto toolong;
1135 
1136 			break;
1137 		}
1138 
1139 		/*
1140 		**  Check for subroutine calls.
1141 		*/
1142 
1143 		if (*npvp != NULL && (**npvp & 0377) == CALLSUBR)
1144 		{
1145 			int stat;
1146 
1147 			bcopy((char *) &npvp[2], (char *) pvp,
1148 				(int) (avp - npvp - 2) * sizeof *avp);
1149 			if (tTd(21, 3))
1150 				printf("-----callsubr %s\n", npvp[1]);
1151 			stat = rewrite(pvp, atoi(npvp[1]), reclevel, e);
1152 			if (rstat == EX_OK || stat == EX_TEMPFAIL)
1153 				rstat = stat;
1154 			if (*pvp != NULL && (**pvp & 0377) == CANONNET)
1155 				rwr = NULL;
1156 		}
1157 		else
1158 		{
1159 			bcopy((char *) npvp, (char *) pvp,
1160 				(int) (avp - npvp) * sizeof *avp);
1161 		}
1162 		if (tTd(21, 4))
1163 		{
1164 			printf("rewritten as:");
1165 			printav(pvp);
1166 		}
1167 	}
1168 
1169 	if (OpMode == MD_TEST || tTd(21, 2))
1170 	{
1171 		printf("rewrite: ruleset %2d returns:", ruleset);
1172 		printav(pvp);
1173 	}
1174 
1175 	return rstat;
1176 }
1177 /*
1178 **  BUILDADDR -- build address from token vector.
1179 **
1180 **	Parameters:
1181 **		tv -- token vector.
1182 **		a -- pointer to address descriptor to fill.
1183 **			If NULL, one will be allocated.
1184 **		flags -- info regarding whether this is a sender or
1185 **			a recipient.
1186 **		e -- the current envelope.
1187 **
1188 **	Returns:
1189 **		NULL if there was an error.
1190 **		'a' otherwise.
1191 **
1192 **	Side Effects:
1193 **		fills in 'a'
1194 */
1195 
1196 struct errcodes
1197 {
1198 	char	*ec_name;		/* name of error code */
1199 	int	ec_code;		/* numeric code */
1200 } ErrorCodes[] =
1201 {
1202 	"usage",	EX_USAGE,
1203 	"nouser",	EX_NOUSER,
1204 	"nohost",	EX_NOHOST,
1205 	"unavailable",	EX_UNAVAILABLE,
1206 	"software",	EX_SOFTWARE,
1207 	"tempfail",	EX_TEMPFAIL,
1208 	"protocol",	EX_PROTOCOL,
1209 #ifdef EX_CONFIG
1210 	"config",	EX_CONFIG,
1211 #endif
1212 	NULL,		EX_UNAVAILABLE,
1213 };
1214 
1215 ADDRESS *
1216 buildaddr(tv, a, flags, e)
1217 	register char **tv;
1218 	register ADDRESS *a;
1219 	int flags;
1220 	register ENVELOPE *e;
1221 {
1222 	struct mailer **mp;
1223 	register struct mailer *m;
1224 	char *bp;
1225 	int spaceleft;
1226 	static MAILER errormailer;
1227 	static char *errorargv[] = { "ERROR", NULL };
1228 	static char buf[MAXNAME];
1229 
1230 	if (tTd(24, 5))
1231 	{
1232 		printf("buildaddr, flags=%o, tv=", flags);
1233 		printav(tv);
1234 	}
1235 
1236 	if (a == NULL)
1237 		a = (ADDRESS *) xalloc(sizeof *a);
1238 	bzero((char *) a, sizeof *a);
1239 
1240 	/* figure out what net/mailer to use */
1241 	if (*tv == NULL || (**tv & 0377) != CANONNET)
1242 	{
1243 		syserr("554 buildaddr: no net");
1244 badaddr:
1245 		a->q_flags |= QBADADDR;
1246 		a->q_mailer = &errormailer;
1247 		if (errormailer.m_name == NULL)
1248 		{
1249 			/* initialize the bogus mailer */
1250 			errormailer.m_name = "*error*";
1251 			errormailer.m_mailer = "ERROR";
1252 			errormailer.m_argv = errorargv;
1253 		}
1254 		return a;
1255 	}
1256 	tv++;
1257 	if (strcasecmp(*tv, "error") == 0)
1258 	{
1259 		if ((**++tv & 0377) == CANONHOST)
1260 		{
1261 			register struct errcodes *ep;
1262 
1263 			if (isascii(**++tv) && isdigit(**tv))
1264 			{
1265 				setstat(atoi(*tv));
1266 			}
1267 			else
1268 			{
1269 				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
1270 					if (strcasecmp(ep->ec_name, *tv) == 0)
1271 						break;
1272 				setstat(ep->ec_code);
1273 			}
1274 			tv++;
1275 		}
1276 		else
1277 			setstat(EX_UNAVAILABLE);
1278 		if ((**tv & 0377) != CANONUSER)
1279 			syserr("554 buildaddr: error: no user");
1280 		cataddr(++tv, NULL, buf, sizeof buf, ' ');
1281 		stripquotes(buf);
1282 		if (isascii(buf[0]) && isdigit(buf[0]) &&
1283 		    isascii(buf[1]) && isdigit(buf[1]) &&
1284 		    isascii(buf[2]) && isdigit(buf[2]) &&
1285 		    buf[3] == ' ')
1286 		{
1287 			char fmt[10];
1288 
1289 			strncpy(fmt, buf, 3);
1290 			strcpy(&fmt[3], " %s");
1291 			usrerr(fmt, buf + 4);
1292 		}
1293 		else
1294 		{
1295 			usrerr("%s", buf);
1296 		}
1297 		goto badaddr;
1298 	}
1299 
1300 	for (mp = Mailer; (m = *mp++) != NULL; )
1301 	{
1302 		if (strcasecmp(m->m_name, *tv) == 0)
1303 			break;
1304 	}
1305 	if (m == NULL)
1306 	{
1307 		syserr("554 buildaddr: unknown mailer %s", *tv);
1308 		goto badaddr;
1309 	}
1310 	a->q_mailer = m;
1311 
1312 	/* figure out what host (if any) */
1313 	tv++;
1314 	if ((**tv & 0377) == CANONHOST)
1315 	{
1316 		bp = buf;
1317 		spaceleft = sizeof buf - 1;
1318 		while (*++tv != NULL && (**tv & 0377) != CANONUSER)
1319 		{
1320 			int i = strlen(*tv);
1321 
1322 			if (i > spaceleft)
1323 			{
1324 				/* out of space for this address */
1325 				if (spaceleft >= 0)
1326 					syserr("554 buildaddr: host too long (%.40s...)",
1327 						buf);
1328 				i = spaceleft;
1329 				spaceleft = 0;
1330 			}
1331 			if (i <= 0)
1332 				continue;
1333 			bcopy(*tv, bp, i);
1334 			bp += i;
1335 			spaceleft -= i;
1336 		}
1337 		*bp = '\0';
1338 		a->q_host = newstr(buf);
1339 	}
1340 	else
1341 	{
1342 		if (!bitnset(M_LOCALMAILER, m->m_flags))
1343 		{
1344 			syserr("554 buildaddr: no host");
1345 			goto badaddr;
1346 		}
1347 		a->q_host = NULL;
1348 	}
1349 
1350 	/* figure out the user */
1351 	if (*tv == NULL || (**tv & 0377) != CANONUSER)
1352 	{
1353 		syserr("554 buildaddr: no user");
1354 		goto badaddr;
1355 	}
1356 	tv++;
1357 
1358 	/* do special mapping for local mailer */
1359 	if (m == LocalMailer && *tv != NULL)
1360 	{
1361 		register char *p = *tv;
1362 
1363 		if (*p == '"')
1364 			p++;
1365 		if (*p == '|')
1366 			a->q_mailer = m = ProgMailer;
1367 		else if (*p == '/')
1368 			a->q_mailer = m = FileMailer;
1369 		else if (*p == ':')
1370 		{
1371 			/* may be :include: */
1372 			cataddr(tv, NULL, buf, sizeof buf, '\0');
1373 			stripquotes(buf);
1374 			if (strncasecmp(buf, ":include:", 9) == 0)
1375 			{
1376 				/* if :include:, don't need further rewriting */
1377 				a->q_mailer = m = InclMailer;
1378 				a->q_user = &buf[9];
1379 				return (a);
1380 			}
1381 		}
1382 	}
1383 
1384 	if (m == LocalMailer && *tv != NULL && strcmp(*tv, "@") == 0)
1385 	{
1386 		tv++;
1387 		a->q_flags |= QNOTREMOTE;
1388 	}
1389 
1390 	/* rewrite according recipient mailer rewriting rules */
1391 	define('h', a->q_host, e);
1392 	if (!bitset(RF_SENDERADDR|RF_HEADERADDR, flags))
1393 	{
1394 		/* sender addresses done later */
1395 		(void) rewrite(tv, 2, 0, e);
1396 		if (m->m_re_rwset > 0)
1397 		       (void) rewrite(tv, m->m_re_rwset, 0, e);
1398 	}
1399 	(void) rewrite(tv, 4, 0, e);
1400 
1401 	/* save the result for the command line/RCPT argument */
1402 	cataddr(tv, NULL, buf, sizeof buf, '\0');
1403 	a->q_user = buf;
1404 
1405 	/*
1406 	**  Do mapping to lower case as requested by mailer
1407 	*/
1408 
1409 	if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
1410 		makelower(a->q_host);
1411 	if (!bitnset(M_USR_UPPER, m->m_flags))
1412 		makelower(a->q_user);
1413 
1414 	return (a);
1415 }
1416 /*
1417 **  CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
1418 **
1419 **	Parameters:
1420 **		pvp -- parameter vector to rebuild.
1421 **		evp -- last parameter to include.  Can be NULL to
1422 **			use entire pvp.
1423 **		buf -- buffer to build the string into.
1424 **		sz -- size of buf.
1425 **		spacesub -- the space separator character; if null,
1426 **			use SpaceSub.
1427 **
1428 **	Returns:
1429 **		none.
1430 **
1431 **	Side Effects:
1432 **		Destroys buf.
1433 */
1434 
1435 cataddr(pvp, evp, buf, sz, spacesub)
1436 	char **pvp;
1437 	char **evp;
1438 	char *buf;
1439 	register int sz;
1440 	char spacesub;
1441 {
1442 	bool oatomtok = FALSE;
1443 	bool natomtok = FALSE;
1444 	register int i;
1445 	register char *p;
1446 
1447 	if (spacesub == '\0')
1448 		spacesub = SpaceSub;
1449 
1450 	if (pvp == NULL)
1451 	{
1452 		(void) strcpy(buf, "");
1453 		return;
1454 	}
1455 	p = buf;
1456 	sz -= 2;
1457 	while (*pvp != NULL && (i = strlen(*pvp)) < sz)
1458 	{
1459 		natomtok = (toktype(**pvp) == ATM);
1460 		if (oatomtok && natomtok)
1461 			*p++ = spacesub;
1462 		(void) strcpy(p, *pvp);
1463 		oatomtok = natomtok;
1464 		p += i;
1465 		sz -= i + 1;
1466 		if (pvp++ == evp)
1467 			break;
1468 	}
1469 	*p = '\0';
1470 }
1471 /*
1472 **  SAMEADDR -- Determine if two addresses are the same
1473 **
1474 **	This is not just a straight comparison -- if the mailer doesn't
1475 **	care about the host we just ignore it, etc.
1476 **
1477 **	Parameters:
1478 **		a, b -- pointers to the internal forms to compare.
1479 **
1480 **	Returns:
1481 **		TRUE -- they represent the same mailbox.
1482 **		FALSE -- they don't.
1483 **
1484 **	Side Effects:
1485 **		none.
1486 */
1487 
1488 bool
1489 sameaddr(a, b)
1490 	register ADDRESS *a;
1491 	register ADDRESS *b;
1492 {
1493 	/* if they don't have the same mailer, forget it */
1494 	if (a->q_mailer != b->q_mailer)
1495 		return (FALSE);
1496 
1497 	/* if the user isn't the same, we can drop out */
1498 	if (strcmp(a->q_user, b->q_user) != 0)
1499 		return (FALSE);
1500 
1501 	/* if we have good uids for both but the differ, these are different */
1502 	if (bitset(QGOODUID, a->q_flags & b->q_flags) && a->q_uid != b->q_uid)
1503 		return (FALSE);
1504 
1505 	/* otherwise compare hosts (but be careful for NULL ptrs) */
1506 	if (a->q_host == b->q_host)
1507 	{
1508 		/* probably both null pointers */
1509 		return (TRUE);
1510 	}
1511 	if (a->q_host == NULL || b->q_host == NULL)
1512 	{
1513 		/* only one is a null pointer */
1514 		return (FALSE);
1515 	}
1516 	if (strcmp(a->q_host, b->q_host) != 0)
1517 		return (FALSE);
1518 
1519 	return (TRUE);
1520 }
1521 /*
1522 **  PRINTADDR -- print address (for debugging)
1523 **
1524 **	Parameters:
1525 **		a -- the address to print
1526 **		follow -- follow the q_next chain.
1527 **
1528 **	Returns:
1529 **		none.
1530 **
1531 **	Side Effects:
1532 **		none.
1533 */
1534 
1535 printaddr(a, follow)
1536 	register ADDRESS *a;
1537 	bool follow;
1538 {
1539 	bool first = TRUE;
1540 	register MAILER *m;
1541 	MAILER pseudomailer;
1542 
1543 	while (a != NULL)
1544 	{
1545 		first = FALSE;
1546 		printf("%x=", a);
1547 		(void) fflush(stdout);
1548 
1549 		/* find the mailer -- carefully */
1550 		m = a->q_mailer;
1551 		if (m == NULL)
1552 		{
1553 			m = &pseudomailer;
1554 			m->m_mno = -1;
1555 			m->m_name = "NULL";
1556 		}
1557 
1558 		printf("%s:\n\tmailer %d (%s), host `%s', user `%s', ruser `%s'\n",
1559 		       a->q_paddr, m->m_mno, m->m_name,
1560 		       a->q_host, a->q_user,
1561 		       a->q_ruser ? a->q_ruser : "<null>");
1562 		printf("\tnext=%x, flags=%o, alias %x, uid %d, gid %d\n",
1563 		       a->q_next, a->q_flags, a->q_alias, a->q_uid, a->q_gid);
1564 		printf("\towner=%s, home=\"%s\", fullname=\"%s\"\n",
1565 		       a->q_owner == NULL ? "(none)" : a->q_owner,
1566 		       a->q_home == NULL ? "(none)" : a->q_home,
1567 		       a->q_fullname == NULL ? "(none)" : a->q_fullname);
1568 
1569 		if (!follow)
1570 			return;
1571 		a = a->q_next;
1572 	}
1573 	if (first)
1574 		printf("[NULL]\n");
1575 }
1576 
1577 /*
1578 **  REMOTENAME -- return the name relative to the current mailer
1579 **
1580 **	Parameters:
1581 **		name -- the name to translate.
1582 **		m -- the mailer that we want to do rewriting relative
1583 **			to.
1584 **		flags -- fine tune operations.
1585 **		pstat -- pointer to status word.
1586 **		e -- the current envelope.
1587 **
1588 **	Returns:
1589 **		the text string representing this address relative to
1590 **			the receiving mailer.
1591 **
1592 **	Side Effects:
1593 **		none.
1594 **
1595 **	Warnings:
1596 **		The text string returned is tucked away locally;
1597 **			copy it if you intend to save it.
1598 */
1599 
1600 char *
1601 remotename(name, m, flags, pstat, e)
1602 	char *name;
1603 	struct mailer *m;
1604 	int flags;
1605 	int *pstat;
1606 	register ENVELOPE *e;
1607 {
1608 	register char **pvp;
1609 	char *fancy;
1610 	char *oldg = macvalue('g', e);
1611 	int rwset;
1612 	static char buf[MAXNAME];
1613 	char lbuf[MAXNAME];
1614 	char pvpbuf[PSBUFSIZE];
1615 	extern char *crackaddr();
1616 
1617 	if (tTd(12, 1))
1618 		printf("remotename(%s)\n", name);
1619 
1620 	/* don't do anything if we are tagging it as special */
1621 	if (bitset(RF_SENDERADDR, flags))
1622 		rwset = bitset(RF_HEADERADDR, flags) ? m->m_sh_rwset
1623 						     : m->m_se_rwset;
1624 	else
1625 		rwset = bitset(RF_HEADERADDR, flags) ? m->m_rh_rwset
1626 						     : m->m_re_rwset;
1627 	if (rwset < 0)
1628 		return (name);
1629 
1630 	/*
1631 	**  Do a heuristic crack of this name to extract any comment info.
1632 	**	This will leave the name as a comment and a $g macro.
1633 	*/
1634 
1635 	if (bitset(RF_CANONICAL, flags) || bitnset(M_NOCOMMENT, m->m_flags))
1636 		fancy = "\201g";
1637 	else
1638 		fancy = crackaddr(name);
1639 
1640 	/*
1641 	**  Turn the name into canonical form.
1642 	**	Normally this will be RFC 822 style, i.e., "user@domain".
1643 	**	If this only resolves to "user", and the "C" flag is
1644 	**	specified in the sending mailer, then the sender's
1645 	**	domain will be appended.
1646 	*/
1647 
1648 	pvp = prescan(name, '\0', pvpbuf, sizeof pvpbuf, NULL);
1649 	if (pvp == NULL)
1650 		return (name);
1651 	if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
1652 		*pstat = EX_TEMPFAIL;
1653 	if (bitset(RF_ADDDOMAIN, flags) && e->e_fromdomain != NULL)
1654 	{
1655 		/* append from domain to this address */
1656 		register char **pxp = pvp;
1657 
1658 		/* see if there is an "@domain" in the current name */
1659 		while (*pxp != NULL && strcmp(*pxp, "@") != 0)
1660 			pxp++;
1661 		if (*pxp == NULL)
1662 		{
1663 			/* no.... append the "@domain" from the sender */
1664 			register char **qxq = e->e_fromdomain;
1665 
1666 			while ((*pxp++ = *qxq++) != NULL)
1667 				continue;
1668 			if (rewrite(pvp, 3, 0, e) == EX_TEMPFAIL)
1669 				*pstat = EX_TEMPFAIL;
1670 		}
1671 	}
1672 
1673 	/*
1674 	**  Do more specific rewriting.
1675 	**	Rewrite using ruleset 1 or 2 depending on whether this is
1676 	**		a sender address or not.
1677 	**	Then run it through any receiving-mailer-specific rulesets.
1678 	*/
1679 
1680 	if (bitset(RF_SENDERADDR, flags))
1681 	{
1682 		if (rewrite(pvp, 1, 0, e) == EX_TEMPFAIL)
1683 			*pstat = EX_TEMPFAIL;
1684 	}
1685 	else
1686 	{
1687 		if (rewrite(pvp, 2, 0, e) == EX_TEMPFAIL)
1688 			*pstat = EX_TEMPFAIL;
1689 	}
1690 	if (rwset > 0)
1691 	{
1692 		if (rewrite(pvp, rwset, 0, e) == EX_TEMPFAIL)
1693 			*pstat = EX_TEMPFAIL;
1694 	}
1695 
1696 	/*
1697 	**  Do any final sanitation the address may require.
1698 	**	This will normally be used to turn internal forms
1699 	**	(e.g., user@host.LOCAL) into external form.  This
1700 	**	may be used as a default to the above rules.
1701 	*/
1702 
1703 	if (rewrite(pvp, 4, 0, e) == EX_TEMPFAIL)
1704 		*pstat = EX_TEMPFAIL;
1705 
1706 	/*
1707 	**  Now restore the comment information we had at the beginning.
1708 	*/
1709 
1710 	cataddr(pvp, NULL, lbuf, sizeof lbuf, '\0');
1711 	define('g', lbuf, e);
1712 	expand(fancy, buf, &buf[sizeof buf - 1], e);
1713 	define('g', oldg, e);
1714 
1715 	if (tTd(12, 1))
1716 		printf("remotename => `%s'\n", buf);
1717 	return (buf);
1718 }
1719 /*
1720 **  MAPLOCALUSER -- run local username through ruleset 5 for final redirection
1721 **
1722 **	Parameters:
1723 **		a -- the address to map (but just the user name part).
1724 **		sendq -- the sendq in which to install any replacement
1725 **			addresses.
1726 **
1727 **	Returns:
1728 **		none.
1729 */
1730 
1731 maplocaluser(a, sendq, e)
1732 	register ADDRESS *a;
1733 	ADDRESS **sendq;
1734 	ENVELOPE *e;
1735 {
1736 	register char **pvp;
1737 	register ADDRESS *a1 = NULL;
1738 	auto char *delimptr;
1739 	char pvpbuf[PSBUFSIZE];
1740 
1741 	if (tTd(29, 1))
1742 	{
1743 		printf("maplocaluser: ");
1744 		printaddr(a, FALSE);
1745 	}
1746 	pvp = prescan(a->q_user, '\0', pvpbuf, sizeof pvpbuf, &delimptr);
1747 	if (pvp == NULL)
1748 		return;
1749 
1750 	(void) rewrite(pvp, 5, 0, e);
1751 	if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
1752 		return;
1753 
1754 	/* if non-null, mailer destination specified -- has it changed? */
1755 	a1 = buildaddr(pvp, NULL, 0, e);
1756 	if (a1 == NULL || sameaddr(a, a1))
1757 		return;
1758 
1759 	/* mark old address as dead; insert new address */
1760 	a->q_flags |= QDONTSEND;
1761 	if (tTd(29, 5))
1762 	{
1763 		printf("maplocaluser: QDONTSEND ");
1764 		printaddr(a, FALSE);
1765 	}
1766 	a1->q_alias = a;
1767 	allocaddr(a1, RF_COPYALL, NULL);
1768 	(void) recipient(a1, sendq, e);
1769 }
1770 /*
1771 **  DEQUOTE_INIT -- initialize dequote map
1772 **
1773 **	This is a no-op.
1774 **
1775 **	Parameters:
1776 **		map -- the internal map structure.
1777 **		args -- arguments.
1778 **
1779 **	Returns:
1780 **		TRUE.
1781 */
1782 
1783 bool
1784 dequote_init(map, args)
1785 	MAP *map;
1786 	char *args;
1787 {
1788 	register char *p = args;
1789 
1790 	for (;;)
1791 	{
1792 		while (isascii(*p) && isspace(*p))
1793 			p++;
1794 		if (*p != '-')
1795 			break;
1796 		switch (*++p)
1797 		{
1798 		  case 'a':
1799 			map->map_app = ++p;
1800 			break;
1801 		}
1802 		while (*p != '\0' && !(isascii(*p) && isspace(*p)))
1803 			p++;
1804 		if (*p != '\0')
1805 			*p = '\0';
1806 	}
1807 	if (map->map_app != NULL)
1808 		map->map_app = newstr(map->map_app);
1809 
1810 	return TRUE;
1811 }
1812 /*
1813 **  DEQUOTE_MAP -- unquote an address
1814 **
1815 **	Parameters:
1816 **		map -- the internal map structure (ignored).
1817 **		name -- the name to dequote.
1818 **		av -- arguments (ignored).
1819 **		statp -- pointer to status out-parameter.
1820 **
1821 **	Returns:
1822 **		NULL -- if there were no quotes, or if the resulting
1823 **			unquoted buffer would not be acceptable to prescan.
1824 **		else -- The dequoted buffer.
1825 */
1826 
1827 char *
1828 dequote_map(map, name, av, statp)
1829 	MAP *map;
1830 	char *name;
1831 	char **av;
1832 	int *statp;
1833 {
1834 	register char *p;
1835 	register char *q;
1836 	register char c;
1837 	int anglecnt;
1838 	int cmntcnt;
1839 	int quotecnt;
1840 	int spacecnt;
1841 	bool quotemode;
1842 	bool bslashmode;
1843 
1844 	anglecnt = 0;
1845 	cmntcnt = 0;
1846 	quotecnt = 0;
1847 	spacecnt = 0;
1848 	quotemode = FALSE;
1849 	bslashmode = FALSE;
1850 
1851 	for (p = q = name; (c = *p++) != '\0'; )
1852 	{
1853 		if (bslashmode)
1854 		{
1855 			bslashmode = FALSE;
1856 			*q++ = c;
1857 			continue;
1858 		}
1859 
1860 		switch (c)
1861 		{
1862 		  case '\\':
1863 			bslashmode = TRUE;
1864 			break;
1865 
1866 		  case '(':
1867 			cmntcnt++;
1868 			break;
1869 
1870 		  case ')':
1871 			if (cmntcnt-- <= 0)
1872 				return NULL;
1873 			break;
1874 
1875 		  case ' ':
1876 			spacecnt++;
1877 			break;
1878 		}
1879 
1880 		if (cmntcnt > 0)
1881 		{
1882 			*q++ = c;
1883 			continue;
1884 		}
1885 
1886 		switch (c)
1887 		{
1888 		  case '"':
1889 			quotemode = !quotemode;
1890 			quotecnt++;
1891 			continue;
1892 
1893 		  case '<':
1894 			anglecnt++;
1895 			break;
1896 
1897 		  case '>':
1898 			if (anglecnt-- <= 0)
1899 				return NULL;
1900 			break;
1901 		}
1902 		*q++ = c;
1903 	}
1904 
1905 	if (anglecnt != 0 || cmntcnt != 0 || bslashmode ||
1906 	    quotemode || quotecnt <= 0 || spacecnt != 0)
1907 		return NULL;
1908 	*q++ = '\0';
1909 	return name;
1910 }
1911