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