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.26 (Berkeley) 03/14/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 (copyf > 0 && paddr != NULL)
199 	{
200 		char savec = *delimptr;
201 
202 		*delimptr = '\0';
203 		a->q_paddr = newstr(paddr);
204 		*delimptr = savec;
205 	}
206 	else
207 		a->q_paddr = paddr;
208 
209 	if (a->q_user == NULL)
210 		a->q_user = "";
211 	if (a->q_host == NULL)
212 		a->q_host = "";
213 
214 	if (copyf >= 0)
215 	{
216 		a->q_host = newstr(a->q_host);
217 		if (a->q_user != a->q_paddr)
218 			a->q_user = newstr(a->q_user);
219 	}
220 
221 	if (a->q_paddr == NULL)
222 		a->q_paddr = a->q_user;
223 }
224 /*
225 **  PRESCAN -- Prescan name and make it canonical
226 **
227 **	Scans a name and turns it into a set of tokens.  This process
228 **	deletes blanks and comments (in parentheses).
229 **
230 **	This routine knows about quoted strings and angle brackets.
231 **
232 **	There are certain subtleties to this routine.  The one that
233 **	comes to mind now is that backslashes on the ends of names
234 **	are silently stripped off; this is intentional.  The problem
235 **	is that some versions of sndmsg (like at LBL) set the kill
236 **	character to something other than @ when reading addresses;
237 **	so people type "csvax.eric\@berkeley" -- which screws up the
238 **	berknet mailer.
239 **
240 **	Parameters:
241 **		addr -- the name to chomp.
242 **		delim -- the delimiter for the address, normally
243 **			'\0' or ','; \0 is accepted in any case.
244 **			If '\t' then we are reading the .cf file.
245 **		pvpbuf -- place to put the saved text -- note that
246 **			the pointers are static.
247 **		delimptr -- if non-NULL, set to the location of the
248 **			terminating delimiter.
249 **
250 **	Returns:
251 **		A pointer to a vector of tokens.
252 **		NULL on error.
253 */
254 
255 /* states and character types */
256 # define OPR		0	/* operator */
257 # define ATM		1	/* atom */
258 # define QST		2	/* in quoted string */
259 # define SPC		3	/* chewing up spaces */
260 # define ONE		4	/* pick up one character */
261 
262 # define NSTATES	5	/* number of states */
263 # define TYPE		017	/* mask to select state type */
264 
265 /* meta bits for table */
266 # define M		020	/* meta character; don't pass through */
267 # define B		040	/* cause a break */
268 # define MB		M|B	/* meta-break */
269 
270 static short StateTab[NSTATES][NSTATES] =
271 {
272    /*	oldst	chtype>	OPR	ATM	QST	SPC	ONE	*/
273 	/*OPR*/		OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,
274 	/*ATM*/		OPR|B,	ATM,	QST|B,	SPC|MB,	ONE|B,
275 	/*QST*/		QST,	QST,	OPR,	QST,	QST,
276 	/*SPC*/		OPR,	ATM,	QST,	SPC|M,	ONE,
277 	/*ONE*/		OPR,	OPR,	OPR,	OPR,	OPR,
278 };
279 
280 # define NOCHAR		-1	/* signal nothing in lookahead token */
281 
282 char **
283 prescan(addr, delim, pvpbuf, delimptr)
284 	char *addr;
285 	char delim;
286 	char pvpbuf[];
287 	char **delimptr;
288 {
289 	register char *p;
290 	register char *q;
291 	register int c;
292 	char **avp;
293 	bool bslashmode;
294 	int cmntcnt;
295 	int anglecnt;
296 	char *tok;
297 	int state;
298 	int newstate;
299 	static char *av[MAXATOM+1];
300 	extern int errno;
301 
302 	/* make sure error messages don't have garbage on them */
303 	errno = 0;
304 
305 	q = pvpbuf;
306 	bslashmode = FALSE;
307 	cmntcnt = 0;
308 	anglecnt = 0;
309 	avp = av;
310 	state = ATM;
311 	c = NOCHAR;
312 	p = addr;
313 	if (tTd(22, 11))
314 	{
315 		printf("prescan: ");
316 		xputs(p);
317 		(void) putchar('\n');
318 	}
319 
320 	do
321 	{
322 		/* read a token */
323 		tok = q;
324 		for (;;)
325 		{
326 			/* store away any old lookahead character */
327 			if (c != NOCHAR)
328 			{
329 				/* see if there is room */
330 				if (q >= &pvpbuf[PSBUFSIZE - 5])
331 				{
332 					usrerr("553 Address too long");
333 					if (delimptr != NULL)
334 						*delimptr = p;
335 					return (NULL);
336 				}
337 
338 				/* squirrel it away */
339 				*q++ = c;
340 			}
341 
342 			/* read a new input character */
343 			c = *p++;
344 			if (c == '\0')
345 			{
346 				/* diagnose and patch up bad syntax */
347 				if (state == QST)
348 				{
349 					usrerr("553 Unbalanced '\"'");
350 					c = '"';
351 				}
352 				else if (cmntcnt > 0)
353 				{
354 					usrerr("553 Unbalanced '('");
355 					c = ')';
356 				}
357 				else if (anglecnt > 0)
358 				{
359 					c = '>';
360 					usrerr("553 Unbalanced '<'");
361 				}
362 				else
363 					break;
364 
365 				p--;
366 			}
367 			else if (c == delim && anglecnt <= 0 &&
368 					cmntcnt <= 0 && state != QST)
369 				break;
370 
371 			if (tTd(22, 101))
372 				printf("c=%c, s=%d; ", c, state);
373 
374 			/* chew up special characters */
375 			*q = '\0';
376 			if (bslashmode)
377 			{
378 				/* kludge \! for naive users */
379 				if (cmntcnt > 0)
380 					c = NOCHAR;
381 				else if (c != '!')
382 					*q++ = '\\';
383 				bslashmode = FALSE;
384 				continue;
385 			}
386 
387 			if (c == '\\')
388 			{
389 				bslashmode = TRUE;
390 				c = NOCHAR;
391 				continue;
392 			}
393 			else if (state == QST)
394 			{
395 				/* do nothing, just avoid next clauses */
396 			}
397 			else if (c == '(')
398 			{
399 				cmntcnt++;
400 				c = NOCHAR;
401 			}
402 			else if (c == ')')
403 			{
404 				if (cmntcnt <= 0)
405 				{
406 					usrerr("553 Unbalanced ')'");
407 					if (delimptr != NULL)
408 						*delimptr = p;
409 					return (NULL);
410 				}
411 				else
412 					cmntcnt--;
413 			}
414 			else if (cmntcnt > 0)
415 				c = NOCHAR;
416 			else if (c == '<')
417 				anglecnt++;
418 			else if (c == '>')
419 			{
420 				if (anglecnt <= 0)
421 				{
422 					usrerr("553 Unbalanced '>'");
423 					if (delimptr != NULL)
424 						*delimptr = p;
425 					return (NULL);
426 				}
427 				anglecnt--;
428 			}
429 			else if (delim == ' ' && isascii(c) && isspace(c))
430 				c = ' ';
431 
432 			if (c == NOCHAR)
433 				continue;
434 
435 			/* see if this is end of input */
436 			if (c == delim && anglecnt <= 0 && state != QST)
437 				break;
438 
439 			newstate = StateTab[state][toktype(c)];
440 			if (tTd(22, 101))
441 				printf("ns=%02o\n", newstate);
442 			state = newstate & TYPE;
443 			if (bitset(M, newstate))
444 				c = NOCHAR;
445 			if (bitset(B, newstate))
446 				break;
447 		}
448 
449 		/* new token */
450 		if (tok != q)
451 		{
452 			*q++ = '\0';
453 			if (tTd(22, 36))
454 			{
455 				printf("tok=");
456 				xputs(tok);
457 				(void) putchar('\n');
458 			}
459 			if (avp >= &av[MAXATOM])
460 			{
461 				syserr("553 prescan: too many tokens");
462 				if (delimptr != NULL)
463 					*delimptr = p;
464 				return (NULL);
465 			}
466 			*avp++ = tok;
467 		}
468 	} while (c != '\0' && (c != delim || anglecnt > 0));
469 	*avp = NULL;
470 	p--;
471 	if (delimptr != NULL)
472 		*delimptr = p;
473 	if (tTd(22, 12))
474 	{
475 		printf("prescan==>");
476 		printav(av);
477 	}
478 	if (av[0] == NULL)
479 		return (NULL);
480 	return (av);
481 }
482 /*
483 **  TOKTYPE -- return token type
484 **
485 **	Parameters:
486 **		c -- the character in question.
487 **
488 **	Returns:
489 **		Its type.
490 **
491 **	Side Effects:
492 **		none.
493 */
494 
495 toktype(c)
496 	register int c;
497 {
498 	static char buf[50];
499 	static bool firstime = TRUE;
500 
501 	if (firstime)
502 	{
503 		firstime = FALSE;
504 		expand("\201o", buf, &buf[sizeof buf - 1], CurEnv);
505 		(void) strcat(buf, DELIMCHARS);
506 	}
507 	c &= 0377;
508 	if (c == MATCHCLASS || c == MATCHREPL || c == MATCHNCLASS)
509 		return (ONE);
510 	if (c == '"')
511 		return (QST);
512 	if ((c & 0340) == 0200)
513 		return (OPR);
514 	if (!isascii(c))
515 		return (ATM);
516 	if (isspace(c) || c == ')')
517 		return (SPC);
518 	if (strchr(buf, c) != NULL)
519 		return (OPR);
520 	return (ATM);
521 }
522 /*
523 **  REWRITE -- apply rewrite rules to token vector.
524 **
525 **	This routine is an ordered production system.  Each rewrite
526 **	rule has a LHS (called the pattern) and a RHS (called the
527 **	rewrite); 'rwr' points the the current rewrite rule.
528 **
529 **	For each rewrite rule, 'avp' points the address vector we
530 **	are trying to match against, and 'pvp' points to the pattern.
531 **	If pvp points to a special match value (MATCHZANY, MATCHANY,
532 **	MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
533 **	matched is saved away in the match vector (pointed to by 'mvp').
534 **
535 **	When a match between avp & pvp does not match, we try to
536 **	back out.  If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
537 **	we must also back out the match in mvp.  If we reach a
538 **	MATCHANY or MATCHZANY we just extend the match and start
539 **	over again.
540 **
541 **	When we finally match, we rewrite the address vector
542 **	and try over again.
543 **
544 **	Parameters:
545 **		pvp -- pointer to token vector.
546 **
547 **	Returns:
548 **		none.
549 **
550 **	Side Effects:
551 **		pvp is modified.
552 */
553 
554 struct match
555 {
556 	char	**first;	/* first token matched */
557 	char	**last;		/* last token matched */
558 };
559 
560 # define MAXMATCH	9	/* max params per rewrite */
561 
562 
563 rewrite(pvp, ruleset)
564 	char **pvp;
565 	int ruleset;
566 {
567 	register char *ap;		/* address pointer */
568 	register char *rp;		/* rewrite pointer */
569 	register char **avp;		/* address vector pointer */
570 	register char **rvp;		/* rewrite vector pointer */
571 	register struct match *mlp;	/* cur ptr into mlist */
572 	register struct rewrite *rwr;	/* pointer to current rewrite rule */
573 	struct match mlist[MAXMATCH];	/* stores match on LHS */
574 	char *npvp[MAXATOM+1];		/* temporary space for rebuild */
575 
576 	if (OpMode == MD_TEST || tTd(21, 2))
577 	{
578 		printf("rewrite: ruleset %2d   input:", ruleset);
579 		printav(pvp);
580 	}
581 	if (ruleset < 0 || ruleset >= MAXRWSETS)
582 	{
583 		syserr("554 rewrite: illegal ruleset number %d", ruleset);
584 		return;
585 	}
586 	if (pvp == NULL)
587 		return;
588 
589 	/*
590 	**  Run through the list of rewrite rules, applying
591 	**	any that match.
592 	*/
593 
594 	for (rwr = RewriteRules[ruleset]; rwr != NULL; )
595 	{
596 		int loopcount = 0;
597 
598 		if (tTd(21, 12))
599 		{
600 			printf("-----trying rule:");
601 			printav(rwr->r_lhs);
602 		}
603 
604 		/* try to match on this rule */
605 		mlp = mlist;
606 		rvp = rwr->r_lhs;
607 		avp = pvp;
608 		while ((ap = *avp) != NULL || *rvp != NULL)
609 		{
610 			if (++loopcount > 100)
611 			{
612 				syserr("554 Infinite loop in ruleset %d", ruleset);
613 				printf("workspace: ");
614 				printav(pvp);
615 				break;
616 			}
617 			rp = *rvp;
618 			if (tTd(21, 35))
619 			{
620 				printf("rp=");
621 				xputs(rp);
622 				printf(", ap=");
623 				xputs(ap);
624 				printf("\n");
625 			}
626 			if (rp == NULL)
627 			{
628 				/* end-of-pattern before end-of-address */
629 				goto backup;
630 			}
631 			if (ap == NULL && (*rp & 0377) != MATCHZANY &&
632 			    (*rp & 0377) != CANONHOST)
633 			{
634 				/* end-of-input */
635 				break;
636 			}
637 
638 			switch (*rp & 0377)
639 			{
640 				register STAB *s;
641 
642 			  case MATCHCLASS:
643 			  case MATCHNCLASS:
644 				/* match any token in (not in) a class */
645 				s = stab(ap, ST_CLASS, ST_FIND);
646 				if (s == NULL || !bitnset(rp[1], s->s_class))
647 				{
648 					if ((*rp & 0377) == MATCHCLASS)
649 						goto backup;
650 				}
651 				else if ((*rp & 0377) == MATCHNCLASS)
652 					goto backup;
653 
654 				/* explicit fall-through */
655 
656 			  case MATCHONE:
657 			  case MATCHANY:
658 				/* match exactly one token */
659 				mlp->first = avp;
660 				mlp->last = avp++;
661 				mlp++;
662 				break;
663 
664 			  case MATCHZANY:
665 				/* match zero or more tokens */
666 				mlp->first = avp;
667 				mlp->last = avp - 1;
668 				mlp++;
669 				break;
670 
671 			  case CANONHOST:
672 				/* match zero tokens */
673 				break;
674 
675 			  default:
676 				/* must have exact match */
677 				if (strcasecmp(rp, ap))
678 					goto backup;
679 				avp++;
680 				break;
681 			}
682 
683 			/* successful match on this token */
684 			rvp++;
685 			continue;
686 
687 		  backup:
688 			/* match failed -- back up */
689 			while (--rvp >= rwr->r_lhs)
690 			{
691 				rp = *rvp;
692 				if ((*rp & 0377) == MATCHANY ||
693 				    (*rp & 0377) == MATCHZANY)
694 				{
695 					/* extend binding and continue */
696 					avp = ++mlp[-1].last;
697 					avp++;
698 					rvp++;
699 					break;
700 				}
701 				avp--;
702 				if ((*rp & 0377) == MATCHONE ||
703 				    (*rp & 0377) == MATCHCLASS ||
704 				    (*rp & 0377) == MATCHNCLASS)
705 				{
706 					/* back out binding */
707 					mlp--;
708 				}
709 			}
710 
711 			if (rvp < rwr->r_lhs)
712 			{
713 				/* total failure to match */
714 				break;
715 			}
716 		}
717 
718 		/*
719 		**  See if we successfully matched
720 		*/
721 
722 		if (rvp < rwr->r_lhs || *rvp != NULL)
723 		{
724 			if (tTd(21, 10))
725 				printf("----- rule fails\n");
726 			rwr = rwr->r_next;
727 			continue;
728 		}
729 
730 		rvp = rwr->r_rhs;
731 		if (tTd(21, 12))
732 		{
733 			printf("-----rule matches:");
734 			printav(rvp);
735 		}
736 
737 		rp = *rvp;
738 		if ((*rp & 0377) == CANONUSER)
739 		{
740 			rvp++;
741 			rwr = rwr->r_next;
742 		}
743 		else if ((*rp & 0377) == CANONHOST)
744 		{
745 			rvp++;
746 			rwr = NULL;
747 		}
748 		else if ((*rp & 0377) == CANONNET)
749 			rwr = NULL;
750 
751 		/* substitute */
752 		for (avp = npvp; *rvp != NULL; rvp++)
753 		{
754 			register struct match *m;
755 			register char **pp;
756 
757 			rp = *rvp;
758 			if ((*rp & 0377) == MATCHREPL)
759 			{
760 				/* substitute from LHS */
761 				m = &mlist[rp[1] - '1'];
762 				if (m < mlist || m >= mlp)
763 				{
764 					syserr("554 rewrite: ruleset %d: replacement $%c out of bounds",
765 						ruleset, rp[1]);
766 					return;
767 				}
768 				if (tTd(21, 15))
769 				{
770 					printf("$%c:", rp[1]);
771 					pp = m->first;
772 					while (pp <= m->last)
773 					{
774 						printf(" %x=\"", *pp);
775 						(void) fflush(stdout);
776 						printf("%s\"", *pp++);
777 					}
778 					printf("\n");
779 				}
780 				pp = m->first;
781 				while (pp <= m->last)
782 				{
783 					if (avp >= &npvp[MAXATOM])
784 					{
785 						syserr("554 rewrite: expansion too long");
786 						return;
787 					}
788 					*avp++ = *pp++;
789 				}
790 			}
791 			else
792 			{
793 				/* vanilla replacement */
794 				if (avp >= &npvp[MAXATOM])
795 				{
796 	toolong:
797 					syserr("554 rewrite: expansion too long");
798 					return;
799 				}
800 				*avp++ = rp;
801 			}
802 		}
803 		*avp++ = NULL;
804 
805 		/*
806 		**  Check for any hostname/keyword lookups.
807 		*/
808 
809 		for (rvp = npvp; *rvp != NULL; rvp++)
810 		{
811 			char **hbrvp;
812 			char **xpvp;
813 			int trsize;
814 			char *olddelimchar;
815 			char *replac;
816 			int endtoken;
817 			STAB *map;
818 			char *mapname;
819 			char **key_rvp;
820 			char **arg_rvp;
821 			char **default_rvp;
822 			char buf[MAXNAME + 1];
823 			char *pvpb1[MAXATOM + 1];
824 			char *argvect[10];
825 			char pvpbuf[PSBUFSIZE];
826 
827 			if ((**rvp & 0377) != HOSTBEGIN &&
828 			    (**rvp & 0377) != LOOKUPBEGIN)
829 				continue;
830 
831 			/*
832 			**  Got a hostname/keyword lookup.
833 			**
834 			**	This could be optimized fairly easily.
835 			*/
836 
837 			hbrvp = rvp;
838 			if ((**rvp & 0377) == HOSTBEGIN)
839 			{
840 				endtoken = HOSTEND;
841 				mapname = "host";
842 			}
843 			else
844 			{
845 				endtoken = LOOKUPEND;
846 				mapname = *++rvp;
847 			}
848 			map = stab(mapname, ST_MAP, ST_FIND);
849 			if (map == NULL)
850 				syserr("554 rewrite: map %s not found", mapname);
851 
852 			/* extract the match part */
853 			key_rvp = ++rvp;
854 			default_rvp = NULL;
855 			arg_rvp = argvect;
856 			xpvp = NULL;
857 			replac = pvpbuf;
858 			while (*rvp != NULL && (**rvp & 0377) != endtoken)
859 			{
860 				int nodetype = **rvp & 0377;
861 
862 				if (nodetype != CANONHOST && nodetype != CANONUSER)
863 				{
864 					rvp++;
865 					continue;
866 				}
867 
868 				*rvp++ = NULL;
869 
870 				if (xpvp != NULL)
871 				{
872 					cataddr(xpvp, replac,
873 						&pvpbuf[sizeof pvpbuf] - replac,
874 						'\0');
875 					*++arg_rvp = replac;
876 					replac += strlen(replac) + 1;
877 					xpvp = NULL;
878 				}
879 				switch (nodetype)
880 				{
881 				  case CANONHOST:
882 					xpvp = rvp;
883 					break;
884 
885 				  case CANONUSER:
886 					default_rvp = rvp;
887 					break;
888 				}
889 			}
890 			if (*rvp != NULL)
891 				*rvp++ = NULL;
892 			if (xpvp != NULL)
893 			{
894 				cataddr(xpvp, replac,
895 					&pvpbuf[sizeof pvpbuf] - replac,
896 					'\0');
897 				*++arg_rvp = replac;
898 			}
899 			*++arg_rvp = NULL;
900 
901 			/* save the remainder of the input string */
902 			trsize = (int) (avp - rvp + 1) * sizeof *rvp;
903 			bcopy((char *) rvp, (char *) pvpb1, trsize);
904 
905 			/* look it up */
906 			cataddr(key_rvp, buf, sizeof buf, '\0');
907 			argvect[0] = buf;
908 			if (map != NULL && bitset(MF_VALID, map->s_map.map_flags))
909 			{
910 				int bsize = sizeof buf - 1;
911 
912 				if (map->s_map.map_app != NULL)
913 					bsize -= strlen(map->s_map.map_app);
914 				replac = (*map->s_map.map_class->map_lookup)(&map->s_map,
915 						buf, sizeof buf - 1, argvect);
916 				if (replac != NULL && map->s_map.map_app != NULL)
917 					strcat(replac, map->s_map.map_app);
918 			}
919 			else
920 				replac = NULL;
921 
922 			/* if no replacement, use default */
923 			if (replac == NULL && default_rvp != NULL)
924 			{
925 				char buf2[sizeof buf];
926 
927 				/* rewrite the default with % translations */
928 				cataddr(default_rvp, buf2, sizeof buf2, '\0');
929 				map_rewrite(buf2, sizeof buf2, buf, sizeof buf,
930 					argvect);
931 				replac = buf;
932 			}
933 
934 			if (replac == NULL)
935 			{
936 				xpvp = key_rvp;
937 			}
938 			else
939 			{
940 				/* scan the new replacement */
941 				xpvp = prescan(replac, '\0', pvpbuf, NULL);
942 				if (xpvp == NULL)
943 				{
944 					/* prescan already printed error */
945 					return;
946 				}
947 			}
948 
949 			/* append it to the token list */
950 			for (avp = hbrvp; *xpvp != NULL; xpvp++)
951 			{
952 				*avp++ = newstr(*xpvp);
953 				if (avp >= &npvp[MAXATOM])
954 					goto toolong;
955 			}
956 
957 			/* restore the old trailing information */
958 			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
959 				if (avp >= &npvp[MAXATOM])
960 					goto toolong;
961 
962 			break;
963 		}
964 
965 		/*
966 		**  Check for subroutine calls.
967 		*/
968 
969 		if (*npvp != NULL && (**npvp & 0377) == CALLSUBR)
970 		{
971 			bcopy((char *) &npvp[2], (char *) pvp,
972 				(int) (avp - npvp - 2) * sizeof *avp);
973 			if (tTd(21, 3))
974 				printf("-----callsubr %s\n", npvp[1]);
975 			rewrite(pvp, atoi(npvp[1]));
976 		}
977 		else
978 		{
979 			bcopy((char *) npvp, (char *) pvp,
980 				(int) (avp - npvp) * sizeof *avp);
981 		}
982 		if (tTd(21, 4))
983 		{
984 			printf("rewritten as:");
985 			printav(pvp);
986 		}
987 	}
988 
989 	if (OpMode == MD_TEST || tTd(21, 2))
990 	{
991 		printf("rewrite: ruleset %2d returns:", ruleset);
992 		printav(pvp);
993 	}
994 }
995 /*
996 **  BUILDADDR -- build address from token vector.
997 **
998 **	Parameters:
999 **		tv -- token vector.
1000 **		a -- pointer to address descriptor to fill.
1001 **			If NULL, one will be allocated.
1002 **
1003 **	Returns:
1004 **		NULL if there was an error.
1005 **		'a' otherwise.
1006 **
1007 **	Side Effects:
1008 **		fills in 'a'
1009 */
1010 
1011 struct errcodes
1012 {
1013 	char	*ec_name;		/* name of error code */
1014 	int	ec_code;		/* numeric code */
1015 } ErrorCodes[] =
1016 {
1017 	"usage",	EX_USAGE,
1018 	"nouser",	EX_NOUSER,
1019 	"nohost",	EX_NOHOST,
1020 	"unavailable",	EX_UNAVAILABLE,
1021 	"software",	EX_SOFTWARE,
1022 	"tempfail",	EX_TEMPFAIL,
1023 	"protocol",	EX_PROTOCOL,
1024 #ifdef EX_CONFIG
1025 	"config",	EX_CONFIG,
1026 #endif
1027 	NULL,		EX_UNAVAILABLE,
1028 };
1029 
1030 ADDRESS *
1031 buildaddr(tv, a)
1032 	register char **tv;
1033 	register ADDRESS *a;
1034 {
1035 	struct mailer **mp;
1036 	register struct mailer *m;
1037 	char *bp;
1038 	int spaceleft;
1039 	static char buf[MAXNAME];
1040 
1041 	if (a == NULL)
1042 		a = (ADDRESS *) xalloc(sizeof *a);
1043 	bzero((char *) a, sizeof *a);
1044 
1045 	/* figure out what net/mailer to use */
1046 	if ((**tv & 0377) != CANONNET)
1047 	{
1048 		syserr("554 buildaddr: no net");
1049 		return (NULL);
1050 	}
1051 	tv++;
1052 	if (!strcasecmp(*tv, "error"))
1053 	{
1054 		if ((**++tv & 0377) == CANONHOST)
1055 		{
1056 			register struct errcodes *ep;
1057 
1058 			if (isascii(**++tv) && isdigit(**tv))
1059 			{
1060 				setstat(atoi(*tv));
1061 			}
1062 			else
1063 			{
1064 				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
1065 					if (strcasecmp(ep->ec_name, *tv) == 0)
1066 						break;
1067 				setstat(ep->ec_code);
1068 			}
1069 			tv++;
1070 		}
1071 		if ((**tv & 0377) != CANONUSER)
1072 			syserr("554 buildaddr: error: no user");
1073 		cataddr(++tv, buf, sizeof buf, ' ');
1074 		stripquotes(buf);
1075 		usrerr(buf);
1076 		return (NULL);
1077 	}
1078 
1079 	for (mp = Mailer; (m = *mp++) != NULL; )
1080 	{
1081 		if (!strcasecmp(m->m_name, *tv))
1082 			break;
1083 	}
1084 	if (m == NULL)
1085 	{
1086 		syserr("554 buildaddr: unknown mailer %s", *tv);
1087 		return (NULL);
1088 	}
1089 	a->q_mailer = m;
1090 
1091 	/* figure out what host (if any) */
1092 	tv++;
1093 	if ((**tv & 0377) == CANONHOST)
1094 	{
1095 		bp = buf;
1096 		spaceleft = sizeof buf - 1;
1097 		while (*++tv != NULL && (**tv & 0377) != CANONUSER)
1098 		{
1099 			int i = strlen(*tv);
1100 
1101 			if (i > spaceleft)
1102 			{
1103 				/* out of space for this address */
1104 				if (spaceleft >= 0)
1105 					syserr("554 buildaddr: host too long (%.40s...)",
1106 						buf);
1107 				i = spaceleft;
1108 				spaceleft = 0;
1109 			}
1110 			if (i <= 0)
1111 				continue;
1112 			bcopy(*tv, bp, i);
1113 			bp += i;
1114 			spaceleft -= i;
1115 		}
1116 		*bp = '\0';
1117 		a->q_host = newstr(buf);
1118 	}
1119 	else
1120 	{
1121 		if (!bitnset(M_LOCALMAILER, m->m_flags))
1122 		{
1123 			syserr("554 buildaddr: no host");
1124 			return (NULL);
1125 		}
1126 		a->q_host = NULL;
1127 	}
1128 
1129 	/* figure out the user */
1130 	if (*tv == NULL || (**tv & 0377) != CANONUSER)
1131 	{
1132 		syserr("554 buildaddr: no user");
1133 		return (NULL);
1134 	}
1135 	tv++;
1136 
1137 	/* do special mapping for local mailer */
1138 	if (m == LocalMailer && *tv != NULL)
1139 	{
1140 		register char *p = *tv;
1141 
1142 		if (*p == '"')
1143 			p++;
1144 		if (*p == '|')
1145 			a->q_mailer = m = ProgMailer;
1146 		else if (*p == '/')
1147 			a->q_mailer = m = FileMailer;
1148 		else if (*p == ':')
1149 		{
1150 			/* may be :include: */
1151 			cataddr(tv, buf, sizeof buf, '\0');
1152 			stripquotes(buf);
1153 			if (strncasecmp(buf, ":include:", 9) == 0)
1154 			{
1155 				/* if :include:, don't need further rewriting */
1156 				a->q_mailer = m = InclMailer;
1157 				a->q_user = &buf[9];
1158 				return (a);
1159 			}
1160 		}
1161 	}
1162 
1163 	if (m == LocalMailer && *tv != NULL && strcmp(*tv, "@") == 0)
1164 	{
1165 		tv++;
1166 		a->q_flags |= QNOTREMOTE;
1167 	}
1168 
1169 	/* rewrite according recipient mailer rewriting rules */
1170 	rewrite(tv, 2);
1171 	if (m->m_re_rwset > 0)
1172 		rewrite(tv, m->m_re_rwset);
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: mailer %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