1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)parseaddr.c	6.29 (Berkeley) 03/23/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 **		copyf -- determines what shall be copied:
34 **			-1 -- don't copy anything.  The printname
35 **				(q_paddr) is just addr, and the
36 **				user & host are allocated internally
37 **				to parse.
38 **			0 -- copy out the parsed user & host, but
39 **				don't copy the printname.
40 **			+1 -- copy everything.
41 **		delim -- the character to terminate the address, passed
42 **			to prescan.
43 **		delimptr -- if non-NULL, set to the location of the
44 **			delim character that was found.
45 **		e -- the envelope that will contain this address.
46 **
47 **	Returns:
48 **		A pointer to the address descriptor header (`a' if
49 **			`a' is non-NULL).
50 **		NULL on error.
51 **
52 **	Side Effects:
53 **		none
54 */
55 
56 /* following delimiters are inherent to the internal algorithms */
57 # define DELIMCHARS	"\201()<>,;\\\"\r\n"	/* word delimiters */
58 
59 ADDRESS *
60 parseaddr(addr, a, copyf, delim, delimptr, e)
61 	char *addr;
62 	register ADDRESS *a;
63 	int copyf;
64 	char delim;
65 	char **delimptr;
66 	register ENVELOPE *e;
67 {
68 	register char **pvp;
69 	auto char *delimptrbuf;
70 	char pvpbuf[PSBUFSIZE];
71 	extern char **prescan();
72 	extern ADDRESS *buildaddr();
73 	extern bool invalidaddr();
74 
75 	/*
76 	**  Initialize and prescan address.
77 	*/
78 
79 	e->e_to = addr;
80 	if (tTd(20, 1))
81 		printf("\n--parseaddr(%s)\n", addr);
82 
83 	if (invalidaddr(addr))
84 	{
85 		if (tTd(20, 1))
86 			printf("parseaddr-->bad address\n");
87 		return NULL;
88 	}
89 
90 	if (delimptr == NULL)
91 		delimptr = &delimptrbuf;
92 
93 	pvp = prescan(addr, delim, pvpbuf, delimptr);
94 	if (pvp == NULL)
95 	{
96 		if (tTd(20, 1))
97 			printf("parseaddr-->NULL\n");
98 		return (NULL);
99 	}
100 
101 	/*
102 	**  Apply rewriting rules.
103 	**	Ruleset 0 does basic parsing.  It must resolve.
104 	*/
105 
106 	rewrite(pvp, 3);
107 	rewrite(pvp, 0);
108 
109 	/*
110 	**  See if we resolved to a real mailer.
111 	*/
112 
113 	if ((pvp[0][0] & 0377) != CANONNET)
114 	{
115 		setstat(EX_USAGE);
116 		syserr("554 cannot resolve name");
117 		return (NULL);
118 	}
119 
120 	/*
121 	**  Build canonical address from pvp.
122 	*/
123 
124 	a = buildaddr(pvp, a);
125 	if (a == NULL)
126 		return (NULL);
127 
128 	/*
129 	**  Make local copies of the host & user and then
130 	**  transport them out.
131 	*/
132 
133 	allocaddr(a, copyf, addr, *delimptr);
134 
135 	/*
136 	**  Compute return value.
137 	*/
138 
139 	if (tTd(20, 1))
140 	{
141 		printf("parseaddr-->");
142 		printaddr(a, FALSE);
143 	}
144 
145 	return (a);
146 }
147 /*
148 **  INVALIDADDR -- check for address containing meta-characters
149 **
150 **	Parameters:
151 **		addr -- the address to check.
152 **
153 **	Returns:
154 **		TRUE -- if the address has any "wierd" characters
155 **		FALSE -- otherwise.
156 */
157 
158 bool
159 invalidaddr(addr)
160 	register char *addr;
161 {
162 	for (; *addr != '\0'; addr++)
163 	{
164 		if ((*addr & 0340) != 0200)
165 			continue;
166 		setstat(EX_USAGE);
167 		usrerr("553 Address contained invalid control characters");
168 		return TRUE;
169 	}
170 	return FALSE;
171 }
172 /*
173 **  ALLOCADDR -- do local allocations of address on demand.
174 **
175 **	Also lowercases the host name if requested.
176 **
177 **	Parameters:
178 **		a -- the address to reallocate.
179 **		copyf -- the copy flag (see parseaddr for description).
180 **		paddr -- the printname of the address.
181 **		delimptr -- a pointer to the address delimiter.  Must be set.
182 **
183 **	Returns:
184 **		none.
185 **
186 **	Side Effects:
187 **		Copies portions of a into local buffers as requested.
188 */
189 
190 allocaddr(a, copyf, paddr, delimptr)
191 	register ADDRESS *a;
192 	int copyf;
193 	char *paddr;
194 	char *delimptr;
195 {
196 	register MAILER *m = a->q_mailer;
197 
198 	if (tTd(24, 4))
199 		printf("allocaddr(copyf=%d, paddr=%s)\n", copyf, paddr);
200 
201 	if (copyf > 0 && paddr != NULL)
202 	{
203 		char savec = *delimptr;
204 
205 		*delimptr = '\0';
206 		a->q_paddr = newstr(paddr);
207 		*delimptr = savec;
208 	}
209 	else
210 		a->q_paddr = paddr;
211 
212 	if (a->q_user == NULL)
213 		a->q_user = "";
214 	if (a->q_host == NULL)
215 		a->q_host = "";
216 
217 	if (copyf >= 0)
218 	{
219 		a->q_host = newstr(a->q_host);
220 		if (a->q_user != a->q_paddr)
221 			a->q_user = newstr(a->q_user);
222 	}
223 
224 	if (a->q_paddr == NULL)
225 		a->q_paddr = a->q_user;
226 }
227 /*
228 **  PRESCAN -- Prescan name and make it canonical
229 **
230 **	Scans a name and turns it into a set of tokens.  This process
231 **	deletes blanks and comments (in parentheses).
232 **
233 **	This routine knows about quoted strings and angle brackets.
234 **
235 **	There are certain subtleties to this routine.  The one that
236 **	comes to mind now is that backslashes on the ends of names
237 **	are silently stripped off; this is intentional.  The problem
238 **	is that some versions of sndmsg (like at LBL) set the kill
239 **	character to something other than @ when reading addresses;
240 **	so people type "csvax.eric\@berkeley" -- which screws up the
241 **	berknet mailer.
242 **
243 **	Parameters:
244 **		addr -- the name to chomp.
245 **		delim -- the delimiter for the address, normally
246 **			'\0' or ','; \0 is accepted in any case.
247 **			If '\t' then we are reading the .cf file.
248 **		pvpbuf -- place to put the saved text -- note that
249 **			the pointers are static.
250 **		delimptr -- if non-NULL, set to the location of the
251 **			terminating delimiter.
252 **
253 **	Returns:
254 **		A pointer to a vector of tokens.
255 **		NULL on error.
256 */
257 
258 /* states and character types */
259 # define OPR		0	/* operator */
260 # define ATM		1	/* atom */
261 # define QST		2	/* in quoted string */
262 # define SPC		3	/* chewing up spaces */
263 # define ONE		4	/* pick up one character */
264 
265 # define NSTATES	5	/* number of states */
266 # define TYPE		017	/* mask to select state type */
267 
268 /* meta bits for table */
269 # define M		020	/* meta character; don't pass through */
270 # define B		040	/* cause a break */
271 # define MB		M|B	/* meta-break */
272 
273 static short StateTab[NSTATES][NSTATES] =
274 {
275    /*	oldst	chtype>	OPR	ATM	QST	SPC	ONE	*/
276 	/*OPR*/		OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,
277 	/*ATM*/		OPR|B,	ATM,	QST|B,	SPC|MB,	ONE|B,
278 	/*QST*/		QST,	QST,	OPR,	QST,	QST,
279 	/*SPC*/		OPR,	ATM,	QST,	SPC|M,	ONE,
280 	/*ONE*/		OPR,	OPR,	OPR,	OPR,	OPR,
281 };
282 
283 # define NOCHAR		-1	/* signal nothing in lookahead token */
284 
285 char **
286 prescan(addr, delim, pvpbuf, delimptr)
287 	char *addr;
288 	char delim;
289 	char pvpbuf[];
290 	char **delimptr;
291 {
292 	register char *p;
293 	register char *q;
294 	register int c;
295 	char **avp;
296 	bool bslashmode;
297 	int cmntcnt;
298 	int anglecnt;
299 	char *tok;
300 	int state;
301 	int newstate;
302 	static char *av[MAXATOM+1];
303 	extern int errno;
304 
305 	/* make sure error messages don't have garbage on them */
306 	errno = 0;
307 
308 	q = pvpbuf;
309 	bslashmode = FALSE;
310 	cmntcnt = 0;
311 	anglecnt = 0;
312 	avp = av;
313 	state = ATM;
314 	c = NOCHAR;
315 	p = addr;
316 	if (tTd(22, 11))
317 	{
318 		printf("prescan: ");
319 		xputs(p);
320 		(void) putchar('\n');
321 	}
322 
323 	do
324 	{
325 		/* read a token */
326 		tok = q;
327 		for (;;)
328 		{
329 			/* store away any old lookahead character */
330 			if (c != NOCHAR)
331 			{
332 				/* see if there is room */
333 				if (q >= &pvpbuf[PSBUFSIZE - 5])
334 				{
335 					usrerr("553 Address too long");
336 					if (delimptr != NULL)
337 						*delimptr = p;
338 					return (NULL);
339 				}
340 
341 				/* squirrel it away */
342 				*q++ = c;
343 			}
344 
345 			/* read a new input character */
346 			c = *p++;
347 			if (c == '\0')
348 			{
349 				/* diagnose and patch up bad syntax */
350 				if (state == QST)
351 				{
352 					usrerr("553 Unbalanced '\"'");
353 					c = '"';
354 				}
355 				else if (cmntcnt > 0)
356 				{
357 					usrerr("553 Unbalanced '('");
358 					c = ')';
359 				}
360 				else if (anglecnt > 0)
361 				{
362 					c = '>';
363 					usrerr("553 Unbalanced '<'");
364 				}
365 				else
366 					break;
367 
368 				p--;
369 			}
370 			else if (c == delim && anglecnt <= 0 &&
371 					cmntcnt <= 0 && state != QST)
372 				break;
373 
374 			if (tTd(22, 101))
375 				printf("c=%c, s=%d; ", c, state);
376 
377 			/* chew up special characters */
378 			*q = '\0';
379 			if (bslashmode)
380 			{
381 				/* kludge \! for naive users */
382 				if (cmntcnt > 0)
383 					c = NOCHAR;
384 				else if (c != '!')
385 					*q++ = '\\';
386 				bslashmode = FALSE;
387 				continue;
388 			}
389 
390 			if (c == '\\')
391 			{
392 				bslashmode = TRUE;
393 				c = NOCHAR;
394 				continue;
395 			}
396 			else if (state == QST)
397 			{
398 				/* do nothing, just avoid next clauses */
399 			}
400 			else if (c == '(')
401 			{
402 				cmntcnt++;
403 				c = NOCHAR;
404 			}
405 			else if (c == ')')
406 			{
407 				if (cmntcnt <= 0)
408 				{
409 					usrerr("553 Unbalanced ')'");
410 					if (delimptr != NULL)
411 						*delimptr = p;
412 					return (NULL);
413 				}
414 				else
415 					cmntcnt--;
416 			}
417 			else if (cmntcnt > 0)
418 				c = NOCHAR;
419 			else if (c == '<')
420 				anglecnt++;
421 			else if (c == '>')
422 			{
423 				if (anglecnt <= 0)
424 				{
425 					usrerr("553 Unbalanced '>'");
426 					if (delimptr != NULL)
427 						*delimptr = p;
428 					return (NULL);
429 				}
430 				anglecnt--;
431 			}
432 			else if (delim == ' ' && isascii(c) && isspace(c))
433 				c = ' ';
434 
435 			if (c == NOCHAR)
436 				continue;
437 
438 			/* see if this is end of input */
439 			if (c == delim && anglecnt <= 0 && state != QST)
440 				break;
441 
442 			newstate = StateTab[state][toktype(c)];
443 			if (tTd(22, 101))
444 				printf("ns=%02o\n", newstate);
445 			state = newstate & TYPE;
446 			if (bitset(M, newstate))
447 				c = NOCHAR;
448 			if (bitset(B, newstate))
449 				break;
450 		}
451 
452 		/* new token */
453 		if (tok != q)
454 		{
455 			*q++ = '\0';
456 			if (tTd(22, 36))
457 			{
458 				printf("tok=");
459 				xputs(tok);
460 				(void) putchar('\n');
461 			}
462 			if (avp >= &av[MAXATOM])
463 			{
464 				syserr("553 prescan: too many tokens");
465 				if (delimptr != NULL)
466 					*delimptr = p;
467 				return (NULL);
468 			}
469 			*avp++ = tok;
470 		}
471 	} while (c != '\0' && (c != delim || anglecnt > 0));
472 	*avp = NULL;
473 	p--;
474 	if (delimptr != NULL)
475 		*delimptr = p;
476 	if (tTd(22, 12))
477 	{
478 		printf("prescan==>");
479 		printav(av);
480 	}
481 	if (av[0] == NULL)
482 		return (NULL);
483 	return (av);
484 }
485 /*
486 **  TOKTYPE -- return token type
487 **
488 **	Parameters:
489 **		c -- the character in question.
490 **
491 **	Returns:
492 **		Its type.
493 **
494 **	Side Effects:
495 **		none.
496 */
497 
498 toktype(c)
499 	register int c;
500 {
501 	static char buf[50];
502 	static bool firstime = TRUE;
503 
504 	if (firstime)
505 	{
506 		firstime = FALSE;
507 		expand("\201o", buf, &buf[sizeof buf - 1], CurEnv);
508 		(void) strcat(buf, DELIMCHARS);
509 	}
510 	c &= 0377;
511 	if (c == MATCHCLASS || c == MATCHREPL || c == MATCHNCLASS)
512 		return (ONE);
513 	if (c == '"')
514 		return (QST);
515 	if ((c & 0340) == 0200)
516 		return (OPR);
517 	if (!isascii(c))
518 		return (ATM);
519 	if (isspace(c) || c == ')')
520 		return (SPC);
521 	if (strchr(buf, c) != NULL)
522 		return (OPR);
523 	return (ATM);
524 }
525 /*
526 **  REWRITE -- apply rewrite rules to token vector.
527 **
528 **	This routine is an ordered production system.  Each rewrite
529 **	rule has a LHS (called the pattern) and a RHS (called the
530 **	rewrite); 'rwr' points the the current rewrite rule.
531 **
532 **	For each rewrite rule, 'avp' points the address vector we
533 **	are trying to match against, and 'pvp' points to the pattern.
534 **	If pvp points to a special match value (MATCHZANY, MATCHANY,
535 **	MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
536 **	matched is saved away in the match vector (pointed to by 'mvp').
537 **
538 **	When a match between avp & pvp does not match, we try to
539 **	back out.  If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
540 **	we must also back out the match in mvp.  If we reach a
541 **	MATCHANY or MATCHZANY we just extend the match and start
542 **	over again.
543 **
544 **	When we finally match, we rewrite the address vector
545 **	and try over again.
546 **
547 **	Parameters:
548 **		pvp -- pointer to token vector.
549 **
550 **	Returns:
551 **		none.
552 **
553 **	Side Effects:
554 **		pvp is modified.
555 */
556 
557 struct match
558 {
559 	char	**first;	/* first token matched */
560 	char	**last;		/* last token matched */
561 };
562 
563 # define MAXMATCH	9	/* max params per rewrite */
564 
565 
566 rewrite(pvp, ruleset)
567 	char **pvp;
568 	int ruleset;
569 {
570 	register char *ap;		/* address pointer */
571 	register char *rp;		/* rewrite pointer */
572 	register char **avp;		/* address vector pointer */
573 	register char **rvp;		/* rewrite vector pointer */
574 	register struct match *mlp;	/* cur ptr into mlist */
575 	register struct rewrite *rwr;	/* pointer to current rewrite rule */
576 	struct match mlist[MAXMATCH];	/* stores match on LHS */
577 	char *npvp[MAXATOM+1];		/* temporary space for rebuild */
578 
579 	if (OpMode == MD_TEST || tTd(21, 2))
580 	{
581 		printf("rewrite: ruleset %2d   input:", ruleset);
582 		printav(pvp);
583 	}
584 	if (ruleset < 0 || ruleset >= MAXRWSETS)
585 	{
586 		syserr("554 rewrite: illegal ruleset number %d", ruleset);
587 		return;
588 	}
589 	if (pvp == NULL)
590 		return;
591 
592 	/*
593 	**  Run through the list of rewrite rules, applying
594 	**	any that match.
595 	*/
596 
597 	for (rwr = RewriteRules[ruleset]; rwr != NULL; )
598 	{
599 		int loopcount = 0;
600 
601 		if (tTd(21, 12))
602 		{
603 			printf("-----trying rule:");
604 			printav(rwr->r_lhs);
605 		}
606 
607 		/* try to match on this rule */
608 		mlp = mlist;
609 		rvp = rwr->r_lhs;
610 		avp = pvp;
611 		while ((ap = *avp) != NULL || *rvp != NULL)
612 		{
613 			if (++loopcount > 100)
614 			{
615 				syserr("554 Infinite loop in ruleset %d", ruleset);
616 				printf("workspace: ");
617 				printav(pvp);
618 				break;
619 			}
620 			rp = *rvp;
621 			if (tTd(21, 35))
622 			{
623 				printf("rp=");
624 				xputs(rp);
625 				printf(", ap=");
626 				xputs(ap);
627 				printf("\n");
628 			}
629 			if (rp == NULL)
630 			{
631 				/* end-of-pattern before end-of-address */
632 				goto backup;
633 			}
634 			if (ap == NULL && (*rp & 0377) != MATCHZANY &&
635 			    (*rp & 0377) != CANONHOST)
636 			{
637 				/* end-of-input */
638 				break;
639 			}
640 
641 			switch (*rp & 0377)
642 			{
643 				register STAB *s;
644 
645 			  case MATCHCLASS:
646 			  case MATCHNCLASS:
647 				/* match any token in (not in) a class */
648 				s = stab(ap, ST_CLASS, ST_FIND);
649 				if (s == NULL || !bitnset(rp[1], s->s_class))
650 				{
651 					if ((*rp & 0377) == MATCHCLASS)
652 						goto backup;
653 				}
654 				else if ((*rp & 0377) == MATCHNCLASS)
655 					goto backup;
656 
657 				/* explicit fall-through */
658 
659 			  case MATCHONE:
660 			  case MATCHANY:
661 				/* match exactly one token */
662 				mlp->first = avp;
663 				mlp->last = avp++;
664 				mlp++;
665 				break;
666 
667 			  case MATCHZANY:
668 				/* match zero or more tokens */
669 				mlp->first = avp;
670 				mlp->last = avp - 1;
671 				mlp++;
672 				break;
673 
674 			  case CANONHOST:
675 				/* match zero tokens */
676 				break;
677 
678 			  default:
679 				/* must have exact match */
680 				if (strcasecmp(rp, ap))
681 					goto backup;
682 				avp++;
683 				break;
684 			}
685 
686 			/* successful match on this token */
687 			rvp++;
688 			continue;
689 
690 		  backup:
691 			/* match failed -- back up */
692 			while (--rvp >= rwr->r_lhs)
693 			{
694 				rp = *rvp;
695 				if ((*rp & 0377) == MATCHANY ||
696 				    (*rp & 0377) == MATCHZANY)
697 				{
698 					/* extend binding and continue */
699 					avp = ++mlp[-1].last;
700 					avp++;
701 					rvp++;
702 					break;
703 				}
704 				avp--;
705 				if ((*rp & 0377) == MATCHONE ||
706 				    (*rp & 0377) == MATCHCLASS ||
707 				    (*rp & 0377) == MATCHNCLASS)
708 				{
709 					/* back out binding */
710 					mlp--;
711 				}
712 			}
713 
714 			if (rvp < rwr->r_lhs)
715 			{
716 				/* total failure to match */
717 				break;
718 			}
719 		}
720 
721 		/*
722 		**  See if we successfully matched
723 		*/
724 
725 		if (rvp < rwr->r_lhs || *rvp != NULL)
726 		{
727 			if (tTd(21, 10))
728 				printf("----- rule fails\n");
729 			rwr = rwr->r_next;
730 			continue;
731 		}
732 
733 		rvp = rwr->r_rhs;
734 		if (tTd(21, 12))
735 		{
736 			printf("-----rule matches:");
737 			printav(rvp);
738 		}
739 
740 		rp = *rvp;
741 		if ((*rp & 0377) == CANONUSER)
742 		{
743 			rvp++;
744 			rwr = rwr->r_next;
745 		}
746 		else if ((*rp & 0377) == CANONHOST)
747 		{
748 			rvp++;
749 			rwr = NULL;
750 		}
751 		else if ((*rp & 0377) == CANONNET)
752 			rwr = NULL;
753 
754 		/* substitute */
755 		for (avp = npvp; *rvp != NULL; rvp++)
756 		{
757 			register struct match *m;
758 			register char **pp;
759 
760 			rp = *rvp;
761 			if ((*rp & 0377) == MATCHREPL)
762 			{
763 				/* substitute from LHS */
764 				m = &mlist[rp[1] - '1'];
765 				if (m < mlist || m >= mlp)
766 				{
767 					syserr("554 rewrite: ruleset %d: replacement $%c out of bounds",
768 						ruleset, rp[1]);
769 					return;
770 				}
771 				if (tTd(21, 15))
772 				{
773 					printf("$%c:", rp[1]);
774 					pp = m->first;
775 					while (pp <= m->last)
776 					{
777 						printf(" %x=\"", *pp);
778 						(void) fflush(stdout);
779 						printf("%s\"", *pp++);
780 					}
781 					printf("\n");
782 				}
783 				pp = m->first;
784 				while (pp <= m->last)
785 				{
786 					if (avp >= &npvp[MAXATOM])
787 					{
788 						syserr("554 rewrite: expansion too long");
789 						return;
790 					}
791 					*avp++ = *pp++;
792 				}
793 			}
794 			else
795 			{
796 				/* vanilla replacement */
797 				if (avp >= &npvp[MAXATOM])
798 				{
799 	toolong:
800 					syserr("554 rewrite: expansion too long");
801 					return;
802 				}
803 				*avp++ = rp;
804 			}
805 		}
806 		*avp++ = NULL;
807 
808 		/*
809 		**  Check for any hostname/keyword lookups.
810 		*/
811 
812 		for (rvp = npvp; *rvp != NULL; rvp++)
813 		{
814 			char **hbrvp;
815 			char **xpvp;
816 			int trsize;
817 			char *olddelimchar;
818 			char *replac;
819 			int endtoken;
820 			STAB *map;
821 			char *mapname;
822 			char **key_rvp;
823 			char **arg_rvp;
824 			char **default_rvp;
825 			char buf[MAXNAME + 1];
826 			char *pvpb1[MAXATOM + 1];
827 			char *argvect[10];
828 			char pvpbuf[PSBUFSIZE];
829 
830 			if ((**rvp & 0377) != HOSTBEGIN &&
831 			    (**rvp & 0377) != LOOKUPBEGIN)
832 				continue;
833 
834 			/*
835 			**  Got a hostname/keyword lookup.
836 			**
837 			**	This could be optimized fairly easily.
838 			*/
839 
840 			hbrvp = rvp;
841 			if ((**rvp & 0377) == HOSTBEGIN)
842 			{
843 				endtoken = HOSTEND;
844 				mapname = "host";
845 			}
846 			else
847 			{
848 				endtoken = LOOKUPEND;
849 				mapname = *++rvp;
850 			}
851 			map = stab(mapname, ST_MAP, ST_FIND);
852 			if (map == NULL)
853 				syserr("554 rewrite: map %s not found", mapname);
854 
855 			/* extract the match part */
856 			key_rvp = ++rvp;
857 			default_rvp = NULL;
858 			arg_rvp = argvect;
859 			xpvp = NULL;
860 			replac = pvpbuf;
861 			while (*rvp != NULL && (**rvp & 0377) != endtoken)
862 			{
863 				int nodetype = **rvp & 0377;
864 
865 				if (nodetype != CANONHOST && nodetype != CANONUSER)
866 				{
867 					rvp++;
868 					continue;
869 				}
870 
871 				*rvp++ = NULL;
872 
873 				if (xpvp != NULL)
874 				{
875 					cataddr(xpvp, replac,
876 						&pvpbuf[sizeof pvpbuf] - replac,
877 						'\0');
878 					*++arg_rvp = replac;
879 					replac += strlen(replac) + 1;
880 					xpvp = NULL;
881 				}
882 				switch (nodetype)
883 				{
884 				  case CANONHOST:
885 					xpvp = rvp;
886 					break;
887 
888 				  case CANONUSER:
889 					default_rvp = rvp;
890 					break;
891 				}
892 			}
893 			if (*rvp != NULL)
894 				*rvp++ = NULL;
895 			if (xpvp != NULL)
896 			{
897 				cataddr(xpvp, replac,
898 					&pvpbuf[sizeof pvpbuf] - replac,
899 					'\0');
900 				*++arg_rvp = replac;
901 			}
902 			*++arg_rvp = NULL;
903 
904 			/* save the remainder of the input string */
905 			trsize = (int) (avp - rvp + 1) * sizeof *rvp;
906 			bcopy((char *) rvp, (char *) pvpb1, trsize);
907 
908 			/* look it up */
909 			cataddr(key_rvp, buf, sizeof buf, '\0');
910 			argvect[0] = buf;
911 			if (map != NULL && bitset(MF_VALID, map->s_map.map_flags))
912 			{
913 				int bsize = sizeof buf - 1;
914 
915 				if (map->s_map.map_app != NULL)
916 					bsize -= strlen(map->s_map.map_app);
917 				if (tTd(60, 1))
918 					printf("map_lookup(%s, %s) => ",
919 						mapname, buf);
920 				replac = (*map->s_map.map_class->map_lookup)(&map->s_map,
921 						buf, sizeof buf - 1, argvect);
922 				if (replac != NULL && map->s_map.map_app != NULL)
923 					strcat(replac, map->s_map.map_app);
924 				if (tTd(60, 1))
925 					printf("%s\n", replac ? replac : "NOT FOUND");
926 			}
927 			else
928 				replac = NULL;
929 
930 			/* if no replacement, use default */
931 			if (replac == NULL && default_rvp != NULL)
932 			{
933 				char buf2[sizeof buf];
934 
935 				/* rewrite the default with % translations */
936 				cataddr(default_rvp, buf2, sizeof buf2, '\0');
937 				map_rewrite(buf2, sizeof buf2, buf, sizeof buf,
938 					argvect);
939 				replac = buf;
940 			}
941 
942 			if (replac == NULL)
943 			{
944 				xpvp = key_rvp;
945 			}
946 			else
947 			{
948 				/* scan the new replacement */
949 				xpvp = prescan(replac, '\0', pvpbuf, NULL);
950 				if (xpvp == NULL)
951 				{
952 					/* prescan already printed error */
953 					return;
954 				}
955 			}
956 
957 			/* append it to the token list */
958 			for (avp = hbrvp; *xpvp != NULL; xpvp++)
959 			{
960 				*avp++ = newstr(*xpvp);
961 				if (avp >= &npvp[MAXATOM])
962 					goto toolong;
963 			}
964 
965 			/* restore the old trailing information */
966 			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
967 				if (avp >= &npvp[MAXATOM])
968 					goto toolong;
969 
970 			break;
971 		}
972 
973 		/*
974 		**  Check for subroutine calls.
975 		*/
976 
977 		if (*npvp != NULL && (**npvp & 0377) == CALLSUBR)
978 		{
979 			bcopy((char *) &npvp[2], (char *) pvp,
980 				(int) (avp - npvp - 2) * sizeof *avp);
981 			if (tTd(21, 3))
982 				printf("-----callsubr %s\n", npvp[1]);
983 			rewrite(pvp, atoi(npvp[1]));
984 		}
985 		else
986 		{
987 			bcopy((char *) npvp, (char *) pvp,
988 				(int) (avp - npvp) * sizeof *avp);
989 		}
990 		if (tTd(21, 4))
991 		{
992 			printf("rewritten as:");
993 			printav(pvp);
994 		}
995 	}
996 
997 	if (OpMode == MD_TEST || tTd(21, 2))
998 	{
999 		printf("rewrite: ruleset %2d returns:", ruleset);
1000 		printav(pvp);
1001 	}
1002 }
1003 /*
1004 **  BUILDADDR -- build address from token vector.
1005 **
1006 **	Parameters:
1007 **		tv -- token vector.
1008 **		a -- pointer to address descriptor to fill.
1009 **			If NULL, one will be allocated.
1010 **
1011 **	Returns:
1012 **		NULL if there was an error.
1013 **		'a' otherwise.
1014 **
1015 **	Side Effects:
1016 **		fills in 'a'
1017 */
1018 
1019 struct errcodes
1020 {
1021 	char	*ec_name;		/* name of error code */
1022 	int	ec_code;		/* numeric code */
1023 } ErrorCodes[] =
1024 {
1025 	"usage",	EX_USAGE,
1026 	"nouser",	EX_NOUSER,
1027 	"nohost",	EX_NOHOST,
1028 	"unavailable",	EX_UNAVAILABLE,
1029 	"software",	EX_SOFTWARE,
1030 	"tempfail",	EX_TEMPFAIL,
1031 	"protocol",	EX_PROTOCOL,
1032 #ifdef EX_CONFIG
1033 	"config",	EX_CONFIG,
1034 #endif
1035 	NULL,		EX_UNAVAILABLE,
1036 };
1037 
1038 ADDRESS *
1039 buildaddr(tv, a)
1040 	register char **tv;
1041 	register ADDRESS *a;
1042 {
1043 	struct mailer **mp;
1044 	register struct mailer *m;
1045 	char *bp;
1046 	int spaceleft;
1047 	static char buf[MAXNAME];
1048 
1049 	if (a == NULL)
1050 		a = (ADDRESS *) xalloc(sizeof *a);
1051 	bzero((char *) a, sizeof *a);
1052 
1053 	/* figure out what net/mailer to use */
1054 	if ((**tv & 0377) != CANONNET)
1055 	{
1056 		syserr("554 buildaddr: no net");
1057 		return (NULL);
1058 	}
1059 	tv++;
1060 	if (strcasecmp(*tv, "error") == 0)
1061 	{
1062 		if ((**++tv & 0377) == CANONHOST)
1063 		{
1064 			register struct errcodes *ep;
1065 
1066 			if (isascii(**++tv) && isdigit(**tv))
1067 			{
1068 				setstat(atoi(*tv));
1069 			}
1070 			else
1071 			{
1072 				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
1073 					if (strcasecmp(ep->ec_name, *tv) == 0)
1074 						break;
1075 				setstat(ep->ec_code);
1076 			}
1077 			tv++;
1078 		}
1079 		if ((**tv & 0377) != CANONUSER)
1080 			syserr("554 buildaddr: error: no user");
1081 		cataddr(++tv, buf, sizeof buf, ' ');
1082 		stripquotes(buf);
1083 		usrerr(buf);
1084 		return (NULL);
1085 	}
1086 
1087 	for (mp = Mailer; (m = *mp++) != NULL; )
1088 	{
1089 		if (strcasecmp(m->m_name, *tv) == 0)
1090 			break;
1091 	}
1092 	if (m == NULL)
1093 	{
1094 		syserr("554 buildaddr: unknown mailer %s", *tv);
1095 		return (NULL);
1096 	}
1097 	a->q_mailer = m;
1098 
1099 	/* figure out what host (if any) */
1100 	tv++;
1101 	if ((**tv & 0377) == CANONHOST)
1102 	{
1103 		bp = buf;
1104 		spaceleft = sizeof buf - 1;
1105 		while (*++tv != NULL && (**tv & 0377) != CANONUSER)
1106 		{
1107 			int i = strlen(*tv);
1108 
1109 			if (i > spaceleft)
1110 			{
1111 				/* out of space for this address */
1112 				if (spaceleft >= 0)
1113 					syserr("554 buildaddr: host too long (%.40s...)",
1114 						buf);
1115 				i = spaceleft;
1116 				spaceleft = 0;
1117 			}
1118 			if (i <= 0)
1119 				continue;
1120 			bcopy(*tv, bp, i);
1121 			bp += i;
1122 			spaceleft -= i;
1123 		}
1124 		*bp = '\0';
1125 		a->q_host = newstr(buf);
1126 	}
1127 	else
1128 	{
1129 		if (!bitnset(M_LOCALMAILER, m->m_flags))
1130 		{
1131 			syserr("554 buildaddr: no host");
1132 			return (NULL);
1133 		}
1134 		a->q_host = NULL;
1135 	}
1136 
1137 	/* figure out the user */
1138 	if (*tv == NULL || (**tv & 0377) != CANONUSER)
1139 	{
1140 		syserr("554 buildaddr: no user");
1141 		return (NULL);
1142 	}
1143 	tv++;
1144 
1145 	/* do special mapping for local mailer */
1146 	if (m == LocalMailer && *tv != NULL)
1147 	{
1148 		register char *p = *tv;
1149 
1150 		if (*p == '"')
1151 			p++;
1152 		if (*p == '|')
1153 			a->q_mailer = m = ProgMailer;
1154 		else if (*p == '/')
1155 			a->q_mailer = m = FileMailer;
1156 		else if (*p == ':')
1157 		{
1158 			/* may be :include: */
1159 			cataddr(tv, buf, sizeof buf, '\0');
1160 			stripquotes(buf);
1161 			if (strncasecmp(buf, ":include:", 9) == 0)
1162 			{
1163 				/* if :include:, don't need further rewriting */
1164 				a->q_mailer = m = InclMailer;
1165 				a->q_user = &buf[9];
1166 				return (a);
1167 			}
1168 		}
1169 	}
1170 
1171 	if (m == LocalMailer && *tv != NULL && strcmp(*tv, "@") == 0)
1172 	{
1173 		tv++;
1174 		a->q_flags |= QNOTREMOTE;
1175 	}
1176 
1177 	/* do cleanup of final address */
1178 	rewrite(tv, 4);
1179 
1180 	/* save the result for the command line/RCPT argument */
1181 	cataddr(tv, buf, sizeof buf, '\0');
1182 	a->q_user = buf;
1183 
1184 	/*
1185 	**  Do mapping to lower case as requested by mailer
1186 	*/
1187 
1188 	if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
1189 		makelower(a->q_host);
1190 	if (!bitnset(M_USR_UPPER, m->m_flags))
1191 		makelower(a->q_user);
1192 
1193 	return (a);
1194 }
1195 /*
1196 **  CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
1197 **
1198 **	Parameters:
1199 **		pvp -- parameter vector to rebuild.
1200 **		buf -- buffer to build the string into.
1201 **		sz -- size of buf.
1202 **		spacesub -- the space separator character; if null,
1203 **			use SpaceSub.
1204 **
1205 **	Returns:
1206 **		none.
1207 **
1208 **	Side Effects:
1209 **		Destroys buf.
1210 */
1211 
1212 cataddr(pvp, buf, sz, spacesub)
1213 	char **pvp;
1214 	char *buf;
1215 	register int sz;
1216 	char spacesub;
1217 {
1218 	bool oatomtok = FALSE;
1219 	bool natomtok = FALSE;
1220 	register int i;
1221 	register char *p;
1222 
1223 	if (spacesub == '\0')
1224 		spacesub = SpaceSub;
1225 
1226 	if (pvp == NULL)
1227 	{
1228 		(void) strcpy(buf, "");
1229 		return;
1230 	}
1231 	p = buf;
1232 	sz -= 2;
1233 	while (*pvp != NULL && (i = strlen(*pvp)) < sz)
1234 	{
1235 		natomtok = (toktype(**pvp) == ATM);
1236 		if (oatomtok && natomtok)
1237 			*p++ = spacesub;
1238 		(void) strcpy(p, *pvp);
1239 		oatomtok = natomtok;
1240 		p += i;
1241 		sz -= i + 1;
1242 		pvp++;
1243 	}
1244 	*p = '\0';
1245 }
1246 /*
1247 **  SAMEADDR -- Determine if two addresses are the same
1248 **
1249 **	This is not just a straight comparison -- if the mailer doesn't
1250 **	care about the host we just ignore it, etc.
1251 **
1252 **	Parameters:
1253 **		a, b -- pointers to the internal forms to compare.
1254 **
1255 **	Returns:
1256 **		TRUE -- they represent the same mailbox.
1257 **		FALSE -- they don't.
1258 **
1259 **	Side Effects:
1260 **		none.
1261 */
1262 
1263 bool
1264 sameaddr(a, b)
1265 	register ADDRESS *a;
1266 	register ADDRESS *b;
1267 {
1268 	/* if they don't have the same mailer, forget it */
1269 	if (a->q_mailer != b->q_mailer)
1270 		return (FALSE);
1271 
1272 	/* if the user isn't the same, we can drop out */
1273 	if (strcmp(a->q_user, b->q_user) != 0)
1274 		return (FALSE);
1275 
1276 	/* if we have good uids for both but the differ, these are different */
1277 	if (bitset(QGOODUID, a->q_flags & b->q_flags) && a->q_uid != b->q_uid)
1278 		return (FALSE);
1279 
1280 	/* otherwise compare hosts (but be careful for NULL ptrs) */
1281 	if (a->q_host == b->q_host)
1282 	{
1283 		/* probably both null pointers */
1284 		return (TRUE);
1285 	}
1286 	if (a->q_host == NULL || b->q_host == NULL)
1287 	{
1288 		/* only one is a null pointer */
1289 		return (FALSE);
1290 	}
1291 	if (strcmp(a->q_host, b->q_host) != 0)
1292 		return (FALSE);
1293 
1294 	return (TRUE);
1295 }
1296 /*
1297 **  PRINTADDR -- print address (for debugging)
1298 **
1299 **	Parameters:
1300 **		a -- the address to print
1301 **		follow -- follow the q_next chain.
1302 **
1303 **	Returns:
1304 **		none.
1305 **
1306 **	Side Effects:
1307 **		none.
1308 */
1309 
1310 printaddr(a, follow)
1311 	register ADDRESS *a;
1312 	bool follow;
1313 {
1314 	bool first = TRUE;
1315 	register MAILER *m;
1316 	MAILER pseudomailer;
1317 
1318 	while (a != NULL)
1319 	{
1320 		first = FALSE;
1321 		printf("%x=", a);
1322 		(void) fflush(stdout);
1323 
1324 		/* find the mailer -- carefully */
1325 		m = a->q_mailer;
1326 		if (m == NULL)
1327 		{
1328 			m = &pseudomailer;
1329 			m->m_mno = -1;
1330 			m->m_name = "NULL";
1331 		}
1332 
1333 		printf("%s:\n\tmailer %d (%s), host `%s', user `%s', ruser `%s'\n",
1334 		       a->q_paddr, m->m_mno, m->m_name,
1335 		       a->q_host, a->q_user, a->q_ruser? a->q_ruser: "<null>");
1336 		printf("\tnext=%x, flags=%o, alias %x\n", a->q_next, a->q_flags,
1337 		       a->q_alias);
1338 		printf("\thome=\"%s\", fullname=\"%s\"\n", a->q_home,
1339 		       a->q_fullname);
1340 
1341 		if (!follow)
1342 			return;
1343 		a = a->q_next;
1344 	}
1345 	if (first)
1346 		printf("[NULL]\n");
1347 }
1348 
1349 /*
1350 **  REMOTENAME -- return the name relative to the current mailer
1351 **
1352 **	Parameters:
1353 **		name -- the name to translate.
1354 **		m -- the mailer that we want to do rewriting relative
1355 **			to.
1356 **		senderaddress -- if set, uses the sender rewriting rules
1357 **			rather than the recipient rewriting rules.
1358 **		header -- set if this address is in the header, rather
1359 **			than an envelope header.
1360 **		canonical -- if set, strip out any comment information,
1361 **			etc.
1362 **		adddomain -- if set, OK to do domain extension.
1363 **		e -- the current envelope.
1364 **
1365 **	Returns:
1366 **		the text string representing this address relative to
1367 **			the receiving mailer.
1368 **
1369 **	Side Effects:
1370 **		none.
1371 **
1372 **	Warnings:
1373 **		The text string returned is tucked away locally;
1374 **			copy it if you intend to save it.
1375 */
1376 
1377 char *
1378 remotename(name, m, senderaddress, header, canonical, adddomain, e)
1379 	char *name;
1380 	struct mailer *m;
1381 	bool senderaddress;
1382 	bool header;
1383 	bool canonical;
1384 	bool adddomain;
1385 	register ENVELOPE *e;
1386 {
1387 	register char **pvp;
1388 	char *fancy;
1389 	extern char *macvalue();
1390 	char *oldg = macvalue('g', e);
1391 	int rwset;
1392 	static char buf[MAXNAME];
1393 	char lbuf[MAXNAME];
1394 	char pvpbuf[PSBUFSIZE];
1395 	extern char **prescan();
1396 	extern char *crackaddr();
1397 
1398 	if (tTd(12, 1))
1399 		printf("remotename(%s)\n", name);
1400 
1401 	/* don't do anything if we are tagging it as special */
1402 	if (senderaddress)
1403 		rwset = header ? m->m_sh_rwset : m->m_se_rwset;
1404 	else
1405 		rwset = header ? m->m_rh_rwset : m->m_re_rwset;
1406 	if (rwset < 0)
1407 		return (name);
1408 
1409 	/*
1410 	**  Do a heuristic crack of this name to extract any comment info.
1411 	**	This will leave the name as a comment and a $g macro.
1412 	*/
1413 
1414 	if (canonical || bitnset(M_NOCOMMENT, m->m_flags))
1415 		fancy = "\201g";
1416 	else
1417 		fancy = crackaddr(name);
1418 
1419 	/*
1420 	**  Turn the name into canonical form.
1421 	**	Normally this will be RFC 822 style, i.e., "user@domain".
1422 	**	If this only resolves to "user", and the "C" flag is
1423 	**	specified in the sending mailer, then the sender's
1424 	**	domain will be appended.
1425 	*/
1426 
1427 	pvp = prescan(name, '\0', pvpbuf, NULL);
1428 	if (pvp == NULL)
1429 		return (name);
1430 	rewrite(pvp, 3);
1431 	if (adddomain && e->e_fromdomain != NULL)
1432 	{
1433 		/* append from domain to this address */
1434 		register char **pxp = pvp;
1435 
1436 		/* see if there is an "@domain" in the current name */
1437 		while (*pxp != NULL && strcmp(*pxp, "@") != 0)
1438 			pxp++;
1439 		if (*pxp == NULL)
1440 		{
1441 			/* no.... append the "@domain" from the sender */
1442 			register char **qxq = e->e_fromdomain;
1443 
1444 			while ((*pxp++ = *qxq++) != NULL)
1445 				continue;
1446 			rewrite(pvp, 3);
1447 		}
1448 	}
1449 
1450 	/*
1451 	**  Do more specific rewriting.
1452 	**	Rewrite using ruleset 1 or 2 depending on whether this is
1453 	**		a sender address or not.
1454 	**	Then run it through any receiving-mailer-specific rulesets.
1455 	*/
1456 
1457 	if (senderaddress)
1458 		rewrite(pvp, 1);
1459 	else
1460 		rewrite(pvp, 2);
1461 	if (rwset > 0)
1462 		rewrite(pvp, rwset);
1463 
1464 	/*
1465 	**  Do any final sanitation the address may require.
1466 	**	This will normally be used to turn internal forms
1467 	**	(e.g., user@host.LOCAL) into external form.  This
1468 	**	may be used as a default to the above rules.
1469 	*/
1470 
1471 	rewrite(pvp, 4);
1472 
1473 	/*
1474 	**  Now restore the comment information we had at the beginning.
1475 	*/
1476 
1477 	cataddr(pvp, lbuf, sizeof lbuf, '\0');
1478 	define('g', lbuf, e);
1479 	expand(fancy, buf, &buf[sizeof buf - 1], e);
1480 	define('g', oldg, e);
1481 
1482 	if (tTd(12, 1))
1483 		printf("remotename => `%s'\n", buf);
1484 	return (buf);
1485 }
1486 /*
1487 **  MAPLOCALUSER -- run local username through ruleset 5 for final redirection
1488 **
1489 **	Parameters:
1490 **		a -- the address to map (but just the user name part).
1491 **		sendq -- the sendq in which to install any replacement
1492 **			addresses.
1493 **
1494 **	Returns:
1495 **		none.
1496 */
1497 
1498 maplocaluser(a, sendq, e)
1499 	register ADDRESS *a;
1500 	ADDRESS **sendq;
1501 	ENVELOPE *e;
1502 {
1503 	register char **pvp;
1504 	register ADDRESS *a1 = NULL;
1505 	auto char *delimptr;
1506 	char pvpbuf[PSBUFSIZE];
1507 
1508 	if (tTd(29, 1))
1509 	{
1510 		printf("maplocaluser: ");
1511 		printaddr(a, FALSE);
1512 	}
1513 	pvp = prescan(a->q_user, '\0', pvpbuf, &delimptr);
1514 	if (pvp == NULL)
1515 		return;
1516 
1517 	rewrite(pvp, 5);
1518 	if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
1519 		return;
1520 
1521 	/* if non-null, mailer destination specified -- has it changed? */
1522 	a1 = buildaddr(pvp, NULL);
1523 	if (a1 == NULL || sameaddr(a, a1))
1524 		return;
1525 
1526 	/* mark old address as dead; insert new address */
1527 	a->q_flags |= QDONTSEND;
1528 	if (tTd(29, 5))
1529 	{
1530 		printf("maplocaluser: QDONTSEND ");
1531 		printaddr(a, FALSE);
1532 	}
1533 	a1->q_alias = a;
1534 	allocaddr(a1, 1, NULL, delimptr);
1535 	(void) recipient(a1, sendq, e);
1536 }
1537