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.28 (Berkeley) 03/16/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 				replac = (*map->s_map.map_class->map_lookup)(&map->s_map,
918 						buf, sizeof buf - 1, argvect);
919 				if (replac != NULL && map->s_map.map_app != NULL)
920 					strcat(replac, map->s_map.map_app);
921 			}
922 			else
923 				replac = NULL;
924 
925 			/* if no replacement, use default */
926 			if (replac == NULL && default_rvp != NULL)
927 			{
928 				char buf2[sizeof buf];
929 
930 				/* rewrite the default with % translations */
931 				cataddr(default_rvp, buf2, sizeof buf2, '\0');
932 				map_rewrite(buf2, sizeof buf2, buf, sizeof buf,
933 					argvect);
934 				replac = buf;
935 			}
936 
937 			if (replac == NULL)
938 			{
939 				xpvp = key_rvp;
940 			}
941 			else
942 			{
943 				/* scan the new replacement */
944 				xpvp = prescan(replac, '\0', pvpbuf, NULL);
945 				if (xpvp == NULL)
946 				{
947 					/* prescan already printed error */
948 					return;
949 				}
950 			}
951 
952 			/* append it to the token list */
953 			for (avp = hbrvp; *xpvp != NULL; xpvp++)
954 			{
955 				*avp++ = newstr(*xpvp);
956 				if (avp >= &npvp[MAXATOM])
957 					goto toolong;
958 			}
959 
960 			/* restore the old trailing information */
961 			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
962 				if (avp >= &npvp[MAXATOM])
963 					goto toolong;
964 
965 			break;
966 		}
967 
968 		/*
969 		**  Check for subroutine calls.
970 		*/
971 
972 		if (*npvp != NULL && (**npvp & 0377) == CALLSUBR)
973 		{
974 			bcopy((char *) &npvp[2], (char *) pvp,
975 				(int) (avp - npvp - 2) * sizeof *avp);
976 			if (tTd(21, 3))
977 				printf("-----callsubr %s\n", npvp[1]);
978 			rewrite(pvp, atoi(npvp[1]));
979 		}
980 		else
981 		{
982 			bcopy((char *) npvp, (char *) pvp,
983 				(int) (avp - npvp) * sizeof *avp);
984 		}
985 		if (tTd(21, 4))
986 		{
987 			printf("rewritten as:");
988 			printav(pvp);
989 		}
990 	}
991 
992 	if (OpMode == MD_TEST || tTd(21, 2))
993 	{
994 		printf("rewrite: ruleset %2d returns:", ruleset);
995 		printav(pvp);
996 	}
997 }
998 /*
999 **  BUILDADDR -- build address from token vector.
1000 **
1001 **	Parameters:
1002 **		tv -- token vector.
1003 **		a -- pointer to address descriptor to fill.
1004 **			If NULL, one will be allocated.
1005 **
1006 **	Returns:
1007 **		NULL if there was an error.
1008 **		'a' otherwise.
1009 **
1010 **	Side Effects:
1011 **		fills in 'a'
1012 */
1013 
1014 struct errcodes
1015 {
1016 	char	*ec_name;		/* name of error code */
1017 	int	ec_code;		/* numeric code */
1018 } ErrorCodes[] =
1019 {
1020 	"usage",	EX_USAGE,
1021 	"nouser",	EX_NOUSER,
1022 	"nohost",	EX_NOHOST,
1023 	"unavailable",	EX_UNAVAILABLE,
1024 	"software",	EX_SOFTWARE,
1025 	"tempfail",	EX_TEMPFAIL,
1026 	"protocol",	EX_PROTOCOL,
1027 #ifdef EX_CONFIG
1028 	"config",	EX_CONFIG,
1029 #endif
1030 	NULL,		EX_UNAVAILABLE,
1031 };
1032 
1033 ADDRESS *
1034 buildaddr(tv, a)
1035 	register char **tv;
1036 	register ADDRESS *a;
1037 {
1038 	struct mailer **mp;
1039 	register struct mailer *m;
1040 	char *bp;
1041 	int spaceleft;
1042 	static char buf[MAXNAME];
1043 
1044 	if (a == NULL)
1045 		a = (ADDRESS *) xalloc(sizeof *a);
1046 	bzero((char *) a, sizeof *a);
1047 
1048 	/* figure out what net/mailer to use */
1049 	if ((**tv & 0377) != CANONNET)
1050 	{
1051 		syserr("554 buildaddr: no net");
1052 		return (NULL);
1053 	}
1054 	tv++;
1055 	if (strcasecmp(*tv, "error") == 0)
1056 	{
1057 		if ((**++tv & 0377) == CANONHOST)
1058 		{
1059 			register struct errcodes *ep;
1060 
1061 			if (isascii(**++tv) && isdigit(**tv))
1062 			{
1063 				setstat(atoi(*tv));
1064 			}
1065 			else
1066 			{
1067 				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
1068 					if (strcasecmp(ep->ec_name, *tv) == 0)
1069 						break;
1070 				setstat(ep->ec_code);
1071 			}
1072 			tv++;
1073 		}
1074 		if ((**tv & 0377) != CANONUSER)
1075 			syserr("554 buildaddr: error: no user");
1076 		cataddr(++tv, buf, sizeof buf, ' ');
1077 		stripquotes(buf);
1078 		usrerr(buf);
1079 		return (NULL);
1080 	}
1081 
1082 	for (mp = Mailer; (m = *mp++) != NULL; )
1083 	{
1084 		if (strcasecmp(m->m_name, *tv) == 0)
1085 			break;
1086 	}
1087 	if (m == NULL)
1088 	{
1089 		syserr("554 buildaddr: unknown mailer %s", *tv);
1090 		return (NULL);
1091 	}
1092 	a->q_mailer = m;
1093 
1094 	/* figure out what host (if any) */
1095 	tv++;
1096 	if ((**tv & 0377) == CANONHOST)
1097 	{
1098 		bp = buf;
1099 		spaceleft = sizeof buf - 1;
1100 		while (*++tv != NULL && (**tv & 0377) != CANONUSER)
1101 		{
1102 			int i = strlen(*tv);
1103 
1104 			if (i > spaceleft)
1105 			{
1106 				/* out of space for this address */
1107 				if (spaceleft >= 0)
1108 					syserr("554 buildaddr: host too long (%.40s...)",
1109 						buf);
1110 				i = spaceleft;
1111 				spaceleft = 0;
1112 			}
1113 			if (i <= 0)
1114 				continue;
1115 			bcopy(*tv, bp, i);
1116 			bp += i;
1117 			spaceleft -= i;
1118 		}
1119 		*bp = '\0';
1120 		a->q_host = newstr(buf);
1121 	}
1122 	else
1123 	{
1124 		if (!bitnset(M_LOCALMAILER, m->m_flags))
1125 		{
1126 			syserr("554 buildaddr: no host");
1127 			return (NULL);
1128 		}
1129 		a->q_host = NULL;
1130 	}
1131 
1132 	/* figure out the user */
1133 	if (*tv == NULL || (**tv & 0377) != CANONUSER)
1134 	{
1135 		syserr("554 buildaddr: no user");
1136 		return (NULL);
1137 	}
1138 	tv++;
1139 
1140 	/* do special mapping for local mailer */
1141 	if (m == LocalMailer && *tv != NULL)
1142 	{
1143 		register char *p = *tv;
1144 
1145 		if (*p == '"')
1146 			p++;
1147 		if (*p == '|')
1148 			a->q_mailer = m = ProgMailer;
1149 		else if (*p == '/')
1150 			a->q_mailer = m = FileMailer;
1151 		else if (*p == ':')
1152 		{
1153 			/* may be :include: */
1154 			cataddr(tv, buf, sizeof buf, '\0');
1155 			stripquotes(buf);
1156 			if (strncasecmp(buf, ":include:", 9) == 0)
1157 			{
1158 				/* if :include:, don't need further rewriting */
1159 				a->q_mailer = m = InclMailer;
1160 				a->q_user = &buf[9];
1161 				return (a);
1162 			}
1163 		}
1164 	}
1165 
1166 	if (m == LocalMailer && *tv != NULL && strcmp(*tv, "@") == 0)
1167 	{
1168 		tv++;
1169 		a->q_flags |= QNOTREMOTE;
1170 	}
1171 
1172 	/* do cleanup of final address */
1173 	rewrite(tv, 4);
1174 
1175 	/* save the result for the command line/RCPT argument */
1176 	cataddr(tv, buf, sizeof buf, '\0');
1177 	a->q_user = buf;
1178 
1179 	/*
1180 	**  Do mapping to lower case as requested by mailer
1181 	*/
1182 
1183 	if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
1184 		makelower(a->q_host);
1185 	if (!bitnset(M_USR_UPPER, m->m_flags))
1186 		makelower(a->q_user);
1187 
1188 	return (a);
1189 }
1190 /*
1191 **  CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
1192 **
1193 **	Parameters:
1194 **		pvp -- parameter vector to rebuild.
1195 **		buf -- buffer to build the string into.
1196 **		sz -- size of buf.
1197 **		spacesub -- the space separator character; if null,
1198 **			use SpaceSub.
1199 **
1200 **	Returns:
1201 **		none.
1202 **
1203 **	Side Effects:
1204 **		Destroys buf.
1205 */
1206 
1207 cataddr(pvp, buf, sz, spacesub)
1208 	char **pvp;
1209 	char *buf;
1210 	register int sz;
1211 	char spacesub;
1212 {
1213 	bool oatomtok = FALSE;
1214 	bool natomtok = FALSE;
1215 	register int i;
1216 	register char *p;
1217 
1218 	if (spacesub == '\0')
1219 		spacesub = SpaceSub;
1220 
1221 	if (pvp == NULL)
1222 	{
1223 		(void) strcpy(buf, "");
1224 		return;
1225 	}
1226 	p = buf;
1227 	sz -= 2;
1228 	while (*pvp != NULL && (i = strlen(*pvp)) < sz)
1229 	{
1230 		natomtok = (toktype(**pvp) == ATM);
1231 		if (oatomtok && natomtok)
1232 			*p++ = spacesub;
1233 		(void) strcpy(p, *pvp);
1234 		oatomtok = natomtok;
1235 		p += i;
1236 		sz -= i + 1;
1237 		pvp++;
1238 	}
1239 	*p = '\0';
1240 }
1241 /*
1242 **  SAMEADDR -- Determine if two addresses are the same
1243 **
1244 **	This is not just a straight comparison -- if the mailer doesn't
1245 **	care about the host we just ignore it, etc.
1246 **
1247 **	Parameters:
1248 **		a, b -- pointers to the internal forms to compare.
1249 **
1250 **	Returns:
1251 **		TRUE -- they represent the same mailbox.
1252 **		FALSE -- they don't.
1253 **
1254 **	Side Effects:
1255 **		none.
1256 */
1257 
1258 bool
1259 sameaddr(a, b)
1260 	register ADDRESS *a;
1261 	register ADDRESS *b;
1262 {
1263 	/* if they don't have the same mailer, forget it */
1264 	if (a->q_mailer != b->q_mailer)
1265 		return (FALSE);
1266 
1267 	/* if the user isn't the same, we can drop out */
1268 	if (strcmp(a->q_user, b->q_user) != 0)
1269 		return (FALSE);
1270 
1271 	/* if we have good uids for both but the differ, these are different */
1272 	if (bitset(QGOODUID, a->q_flags & b->q_flags) && a->q_uid != b->q_uid)
1273 		return (FALSE);
1274 
1275 	/* otherwise compare hosts (but be careful for NULL ptrs) */
1276 	if (a->q_host == b->q_host)
1277 	{
1278 		/* probably both null pointers */
1279 		return (TRUE);
1280 	}
1281 	if (a->q_host == NULL || b->q_host == NULL)
1282 	{
1283 		/* only one is a null pointer */
1284 		return (FALSE);
1285 	}
1286 	if (strcmp(a->q_host, b->q_host) != 0)
1287 		return (FALSE);
1288 
1289 	return (TRUE);
1290 }
1291 /*
1292 **  PRINTADDR -- print address (for debugging)
1293 **
1294 **	Parameters:
1295 **		a -- the address to print
1296 **		follow -- follow the q_next chain.
1297 **
1298 **	Returns:
1299 **		none.
1300 **
1301 **	Side Effects:
1302 **		none.
1303 */
1304 
1305 printaddr(a, follow)
1306 	register ADDRESS *a;
1307 	bool follow;
1308 {
1309 	bool first = TRUE;
1310 	register MAILER *m;
1311 	MAILER pseudomailer;
1312 
1313 	while (a != NULL)
1314 	{
1315 		first = FALSE;
1316 		printf("%x=", a);
1317 		(void) fflush(stdout);
1318 
1319 		/* find the mailer -- carefully */
1320 		m = a->q_mailer;
1321 		if (m == NULL)
1322 		{
1323 			m = &pseudomailer;
1324 			m->m_mno = -1;
1325 			m->m_name = "NULL";
1326 		}
1327 
1328 		printf("%s:\n\tmailer %d (%s), host `%s', user `%s', ruser `%s'\n",
1329 		       a->q_paddr, m->m_mno, m->m_name,
1330 		       a->q_host, a->q_user, a->q_ruser? a->q_ruser: "<null>");
1331 		printf("\tnext=%x, flags=%o, alias %x\n", a->q_next, a->q_flags,
1332 		       a->q_alias);
1333 		printf("\thome=\"%s\", fullname=\"%s\"\n", a->q_home,
1334 		       a->q_fullname);
1335 
1336 		if (!follow)
1337 			return;
1338 		a = a->q_next;
1339 	}
1340 	if (first)
1341 		printf("[NULL]\n");
1342 }
1343 
1344 /*
1345 **  REMOTENAME -- return the name relative to the current mailer
1346 **
1347 **	Parameters:
1348 **		name -- the name to translate.
1349 **		m -- the mailer that we want to do rewriting relative
1350 **			to.
1351 **		senderaddress -- if set, uses the sender rewriting rules
1352 **			rather than the recipient rewriting rules.
1353 **		header -- set if this address is in the header, rather
1354 **			than an envelope header.
1355 **		canonical -- if set, strip out any comment information,
1356 **			etc.
1357 **		adddomain -- if set, OK to do domain extension.
1358 **		e -- the current envelope.
1359 **
1360 **	Returns:
1361 **		the text string representing this address relative to
1362 **			the receiving mailer.
1363 **
1364 **	Side Effects:
1365 **		none.
1366 **
1367 **	Warnings:
1368 **		The text string returned is tucked away locally;
1369 **			copy it if you intend to save it.
1370 */
1371 
1372 char *
1373 remotename(name, m, senderaddress, header, canonical, adddomain, e)
1374 	char *name;
1375 	struct mailer *m;
1376 	bool senderaddress;
1377 	bool header;
1378 	bool canonical;
1379 	bool adddomain;
1380 	register ENVELOPE *e;
1381 {
1382 	register char **pvp;
1383 	char *fancy;
1384 	extern char *macvalue();
1385 	char *oldg = macvalue('g', e);
1386 	int rwset;
1387 	static char buf[MAXNAME];
1388 	char lbuf[MAXNAME];
1389 	char pvpbuf[PSBUFSIZE];
1390 	extern char **prescan();
1391 	extern char *crackaddr();
1392 
1393 	if (tTd(12, 1))
1394 		printf("remotename(%s)\n", name);
1395 
1396 	/* don't do anything if we are tagging it as special */
1397 	if (senderaddress)
1398 		rwset = header ? m->m_sh_rwset : m->m_se_rwset;
1399 	else
1400 		rwset = header ? m->m_rh_rwset : m->m_re_rwset;
1401 	if (rwset < 0)
1402 		return (name);
1403 
1404 	/*
1405 	**  Do a heuristic crack of this name to extract any comment info.
1406 	**	This will leave the name as a comment and a $g macro.
1407 	*/
1408 
1409 	if (canonical || bitnset(M_NOCOMMENT, m->m_flags))
1410 		fancy = "\201g";
1411 	else
1412 		fancy = crackaddr(name);
1413 
1414 	/*
1415 	**  Turn the name into canonical form.
1416 	**	Normally this will be RFC 822 style, i.e., "user@domain".
1417 	**	If this only resolves to "user", and the "C" flag is
1418 	**	specified in the sending mailer, then the sender's
1419 	**	domain will be appended.
1420 	*/
1421 
1422 	pvp = prescan(name, '\0', pvpbuf, NULL);
1423 	if (pvp == NULL)
1424 		return (name);
1425 	rewrite(pvp, 3);
1426 	if (adddomain && e->e_fromdomain != NULL)
1427 	{
1428 		/* append from domain to this address */
1429 		register char **pxp = pvp;
1430 
1431 		/* see if there is an "@domain" in the current name */
1432 		while (*pxp != NULL && strcmp(*pxp, "@") != 0)
1433 			pxp++;
1434 		if (*pxp == NULL)
1435 		{
1436 			/* no.... append the "@domain" from the sender */
1437 			register char **qxq = e->e_fromdomain;
1438 
1439 			while ((*pxp++ = *qxq++) != NULL)
1440 				continue;
1441 			rewrite(pvp, 3);
1442 		}
1443 	}
1444 
1445 	/*
1446 	**  Do more specific rewriting.
1447 	**	Rewrite using ruleset 1 or 2 depending on whether this is
1448 	**		a sender address or not.
1449 	**	Then run it through any receiving-mailer-specific rulesets.
1450 	*/
1451 
1452 	if (senderaddress)
1453 		rewrite(pvp, 1);
1454 	else
1455 		rewrite(pvp, 2);
1456 	if (rwset > 0)
1457 		rewrite(pvp, rwset);
1458 
1459 	/*
1460 	**  Do any final sanitation the address may require.
1461 	**	This will normally be used to turn internal forms
1462 	**	(e.g., user@host.LOCAL) into external form.  This
1463 	**	may be used as a default to the above rules.
1464 	*/
1465 
1466 	rewrite(pvp, 4);
1467 
1468 	/*
1469 	**  Now restore the comment information we had at the beginning.
1470 	*/
1471 
1472 	cataddr(pvp, lbuf, sizeof lbuf, '\0');
1473 	define('g', lbuf, e);
1474 	expand(fancy, buf, &buf[sizeof buf - 1], e);
1475 	define('g', oldg, e);
1476 
1477 	if (tTd(12, 1))
1478 		printf("remotename => `%s'\n", buf);
1479 	return (buf);
1480 }
1481 /*
1482 **  MAPLOCALUSER -- run local username through ruleset 5 for final redirection
1483 **
1484 **	Parameters:
1485 **		a -- the address to map (but just the user name part).
1486 **		sendq -- the sendq in which to install any replacement
1487 **			addresses.
1488 **
1489 **	Returns:
1490 **		none.
1491 */
1492 
1493 maplocaluser(a, sendq, e)
1494 	register ADDRESS *a;
1495 	ADDRESS **sendq;
1496 	ENVELOPE *e;
1497 {
1498 	register char **pvp;
1499 	register ADDRESS *a1 = NULL;
1500 	auto char *delimptr;
1501 	char pvpbuf[PSBUFSIZE];
1502 
1503 	if (tTd(29, 1))
1504 	{
1505 		printf("maplocaluser: ");
1506 		printaddr(a, FALSE);
1507 	}
1508 	pvp = prescan(a->q_user, '\0', pvpbuf, &delimptr);
1509 	if (pvp == NULL)
1510 		return;
1511 
1512 	rewrite(pvp, 5);
1513 	if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
1514 		return;
1515 
1516 	/* if non-null, mailer destination specified -- has it changed? */
1517 	a1 = buildaddr(pvp, NULL);
1518 	if (a1 == NULL || sameaddr(a, a1))
1519 		return;
1520 
1521 	/* mark old address as dead; insert new address */
1522 	a->q_flags |= QDONTSEND;
1523 	if (tTd(29, 5))
1524 	{
1525 		printf("maplocaluser: QDONTSEND ");
1526 		printaddr(a, FALSE);
1527 	}
1528 	a1->q_alias = a;
1529 	allocaddr(a1, 1, NULL, delimptr);
1530 	(void) recipient(a1, sendq, e);
1531 }
1532