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