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