1 /*
2  * Copyright (c) 1983, 1995 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)headers.c	8.67 (Berkeley) 05/28/95";
11 #endif /* not lint */
12 
13 # include <errno.h>
14 # include "sendmail.h"
15 
16 /*
17 **  CHOMPHEADER -- process and save a header line.
18 **
19 **	Called by collect and by readcf to deal with header lines.
20 **
21 **	Parameters:
22 **		line -- header as a text line.
23 **		def -- if set, this is a default value.
24 **		hdrp -- a pointer to the place to save the header.
25 **		e -- the envelope including this header.
26 **
27 **	Returns:
28 **		flags for this header.
29 **
30 **	Side Effects:
31 **		The header is saved on the header list.
32 **		Contents of 'line' are destroyed.
33 */
34 
35 int
36 chompheader(line, def, hdrp, e)
37 	char *line;
38 	bool def;
39 	HDR **hdrp;
40 	register ENVELOPE *e;
41 {
42 	register char *p;
43 	register HDR *h;
44 	HDR **hp;
45 	char *fname;
46 	char *fvalue;
47 	struct hdrinfo *hi;
48 	bool cond = FALSE;
49 	bool headeronly;
50 	BITMAP mopts;
51 	char buf[MAXNAME + 1];
52 
53 	if (tTd(31, 6))
54 	{
55 		printf("chompheader: ");
56 		xputs(line);
57 		printf("\n");
58 	}
59 
60 	headeronly = hdrp != NULL;
61 	if (!headeronly)
62 		hdrp = &e->e_header;
63 
64 	/* strip off options */
65 	clrbitmap(mopts);
66 	p = line;
67 	if (*p == '?')
68 	{
69 		/* have some */
70 		register char *q = strchr(p + 1, *p);
71 
72 		if (q != NULL)
73 		{
74 			*q++ = '\0';
75 			while (*++p != '\0')
76 				setbitn(*p, mopts);
77 			p = q;
78 		}
79 		else
80 			syserr("553 header syntax error, line \"%s\"", line);
81 		cond = TRUE;
82 	}
83 
84 	/* find canonical name */
85 	fname = p;
86 	while (isascii(*p) && isgraph(*p) && *p != ':')
87 		p++;
88 	fvalue = p;
89 	while (isascii(*p) && isspace(*p))
90 		p++;
91 	if (*p++ != ':' || fname == fvalue)
92 	{
93 		syserr("553 header syntax error, line \"%s\"", line);
94 		return (0);
95 	}
96 	*fvalue = '\0';
97 	fvalue = p;
98 
99 	/* strip field value on front */
100 	if (*fvalue == ' ')
101 		fvalue++;
102 
103 	/* see if it is a known type */
104 	for (hi = HdrInfo; hi->hi_field != NULL; hi++)
105 	{
106 		if (strcasecmp(hi->hi_field, fname) == 0)
107 			break;
108 	}
109 
110 	if (tTd(31, 9))
111 	{
112 		if (hi->hi_field == NULL)
113 			printf("no header match\n");
114 		else
115 			printf("header match, hi_flags=%x\n", hi->hi_flags);
116 	}
117 
118 	/* see if this is a resent message */
119 	if (!def && !headeronly && bitset(H_RESENT, hi->hi_flags))
120 		e->e_flags |= EF_RESENT;
121 
122 	/* if this is an Errors-To: header keep track of it now */
123 	if (UseErrorsTo && !def && !headeronly &&
124 	    bitset(H_ERRORSTO, hi->hi_flags))
125 		(void) sendtolist(fvalue, NULLADDR, &e->e_errorqueue, 0, e);
126 
127 	/* if this means "end of header" quit now */
128 	if (bitset(H_EOH, hi->hi_flags))
129 		return (hi->hi_flags);
130 
131 	/*
132 	**  Drop explicit From: if same as what we would generate.
133 	**  This is to make MH (which doesn't always give a full name)
134 	**  insert the full name information in all circumstances.
135 	*/
136 
137 	p = "resent-from";
138 	if (!bitset(EF_RESENT, e->e_flags))
139 		p += 7;
140 	if (!def && !headeronly && !bitset(EF_QUEUERUN, e->e_flags) &&
141 	    strcasecmp(fname, p) == 0)
142 	{
143 		if (tTd(31, 2))
144 		{
145 			printf("comparing header from (%s) against default (%s or %s)\n",
146 				fvalue, e->e_from.q_paddr, e->e_from.q_user);
147 		}
148 		if (e->e_from.q_paddr != NULL &&
149 		    (strcmp(fvalue, e->e_from.q_paddr) == 0 ||
150 		     strcmp(fvalue, e->e_from.q_user) == 0))
151 			return (hi->hi_flags);
152 #ifdef MAYBENEXTRELEASE		/* XXX UNTESTED XXX UNTESTED XXX UNTESTED XXX */
153 #if USERDB
154 		else
155 		{
156 			auto ADDRESS a;
157 			char *fancy;
158 			bool oldSuprErrs = SuprErrs;
159 			extern char *crackaddr();
160 			extern char *udbsender();
161 
162 			/*
163 			**  Try doing USERDB rewriting even on fully commented
164 			**  names; this saves the "comment" information (such
165 			**  as full name) and rewrites the electronic part.
166 			**
167 			** XXX	This code doesn't belong here -- parsing should
168 			** XXX	not be done during collect() phase because
169 			** XXX	error messages can confuse the SMTP phase.
170 			** XXX	Setting SuprErrs is a crude hack around this
171 			** XXX	problem.
172 			*/
173 
174 			if (OpMode == MD_SMTP || OpMode == MD_ARPAFTP)
175 				SuprErrs = TRUE;
176 			fancy = crackaddr(fvalue);
177 			if (parseaddr(fvalue, &a, RF_COPYNONE, '\0', NULL, e) != NULL &&
178 			    bitnset(M_CHECKUDB, a.q_mailer->m_flags) &&
179 			    (p = udbsender(a.q_user)) != NULL)
180 			{
181 				char *oldg = macvalue('g', e);
182 
183 				define('g', p, e);
184 				expand(fancy, buf, sizeof buf, e);
185 				define('g', oldg, e);
186 				fvalue = buf;
187 			}
188 			SuprErrs = oldSuprErrs;
189 		}
190 #endif
191 #endif
192 	}
193 
194 	/* delete default value for this header */
195 	for (hp = hdrp; (h = *hp) != NULL; hp = &h->h_link)
196 	{
197 		if (strcasecmp(fname, h->h_field) == 0 &&
198 		    bitset(H_DEFAULT, h->h_flags) &&
199 		    !bitset(H_FORCE, h->h_flags))
200 		{
201 			h->h_value = NULL;
202 			if (!cond)
203 			{
204 				/* copy conditions from default case */
205 				bcopy((char *)h->h_mflags, (char *)mopts,
206 						sizeof mopts);
207 			}
208 		}
209 	}
210 
211 	/* create a new node */
212 	h = (HDR *) xalloc(sizeof *h);
213 	h->h_field = newstr(fname);
214 	h->h_value = newstr(fvalue);
215 	h->h_link = NULL;
216 	bcopy((char *) mopts, (char *) h->h_mflags, sizeof mopts);
217 	*hp = h;
218 	h->h_flags = hi->hi_flags;
219 	if (def)
220 		h->h_flags |= H_DEFAULT;
221 	if (cond)
222 		h->h_flags |= H_CHECK;
223 
224 	/* hack to see if this is a new format message */
225 	if (!def && !headeronly && bitset(H_RCPT|H_FROM, h->h_flags) &&
226 	    (strchr(fvalue, ',') != NULL || strchr(fvalue, '(') != NULL ||
227 	     strchr(fvalue, '<') != NULL || strchr(fvalue, ';') != NULL))
228 	{
229 		e->e_flags &= ~EF_OLDSTYLE;
230 	}
231 
232 	return (h->h_flags);
233 }
234 /*
235 **  ADDHEADER -- add a header entry to the end of the queue.
236 **
237 **	This bypasses the special checking of chompheader.
238 **
239 **	Parameters:
240 **		field -- the name of the header field.
241 **		value -- the value of the field.
242 **		hp -- an indirect pointer to the header structure list.
243 **
244 **	Returns:
245 **		none.
246 **
247 **	Side Effects:
248 **		adds the field on the list of headers for this envelope.
249 */
250 
251 void
252 addheader(field, value, hdrlist)
253 	char *field;
254 	char *value;
255 	HDR **hdrlist;
256 {
257 	register HDR *h;
258 	register struct hdrinfo *hi;
259 	HDR **hp;
260 
261 	/* find info struct */
262 	for (hi = HdrInfo; hi->hi_field != NULL; hi++)
263 	{
264 		if (strcasecmp(field, hi->hi_field) == 0)
265 			break;
266 	}
267 
268 	/* find current place in list -- keep back pointer? */
269 	for (hp = hdrlist; (h = *hp) != NULL; hp = &h->h_link)
270 	{
271 		if (strcasecmp(field, h->h_field) == 0)
272 			break;
273 	}
274 
275 	/* allocate space for new header */
276 	h = (HDR *) xalloc(sizeof *h);
277 	h->h_field = field;
278 	h->h_value = newstr(value);
279 	h->h_link = *hp;
280 	h->h_flags = hi->hi_flags | H_DEFAULT;
281 	clrbitmap(h->h_mflags);
282 	*hp = h;
283 }
284 /*
285 **  HVALUE -- return value of a header.
286 **
287 **	Only "real" fields (i.e., ones that have not been supplied
288 **	as a default) are used.
289 **
290 **	Parameters:
291 **		field -- the field name.
292 **		header -- the header list.
293 **
294 **	Returns:
295 **		pointer to the value part.
296 **		NULL if not found.
297 **
298 **	Side Effects:
299 **		none.
300 */
301 
302 char *
303 hvalue(field, header)
304 	char *field;
305 	HDR *header;
306 {
307 	register HDR *h;
308 
309 	for (h = header; h != NULL; h = h->h_link)
310 	{
311 		if (!bitset(H_DEFAULT, h->h_flags) &&
312 		    strcasecmp(h->h_field, field) == 0)
313 			return (h->h_value);
314 	}
315 	return (NULL);
316 }
317 /*
318 **  ISHEADER -- predicate telling if argument is a header.
319 **
320 **	A line is a header if it has a single word followed by
321 **	optional white space followed by a colon.
322 **
323 **	Header fields beginning with two dashes, although technically
324 **	permitted by RFC822, are automatically rejected in order
325 **	to make MIME work out.  Without this we could have a technically
326 **	legal header such as ``--"foo:bar"'' that would also be a legal
327 **	MIME separator.
328 **
329 **	Parameters:
330 **		h -- string to check for possible headerness.
331 **
332 **	Returns:
333 **		TRUE if h is a header.
334 **		FALSE otherwise.
335 **
336 **	Side Effects:
337 **		none.
338 */
339 
340 bool
341 isheader(h)
342 	char *h;
343 {
344 	register char *s = h;
345 
346 	if (s[0] == '-' && s[1] == '-')
347 		return FALSE;
348 
349 	while (*s > ' ' && *s != ':' && *s != '\0')
350 		s++;
351 
352 	if (h == s)
353 		return FALSE;
354 
355 	/* following technically violates RFC822 */
356 	while (isascii(*s) && isspace(*s))
357 		s++;
358 
359 	return (*s == ':');
360 }
361 /*
362 **  EATHEADER -- run through the stored header and extract info.
363 **
364 **	Parameters:
365 **		e -- the envelope to process.
366 **		full -- if set, do full processing (e.g., compute
367 **			message priority).  This should not be set
368 **			when reading a queue file because some info
369 **			needed to compute the priority is wrong.
370 **
371 **	Returns:
372 **		none.
373 **
374 **	Side Effects:
375 **		Sets a bunch of global variables from information
376 **			in the collected header.
377 **		Aborts the message if the hop count is exceeded.
378 */
379 
380 void
381 eatheader(e, full)
382 	register ENVELOPE *e;
383 	bool full;
384 {
385 	register HDR *h;
386 	register char *p;
387 	int hopcnt = 0;
388 	char *msgid;
389 	char buf[MAXLINE];
390 
391 	/*
392 	**  Set up macros for possible expansion in headers.
393 	*/
394 
395 	define('f', e->e_sender, e);
396 	define('g', e->e_sender, e);
397 	if (e->e_origrcpt != NULL && *e->e_origrcpt != '\0')
398 		define('u', e->e_origrcpt, e);
399 	else
400 		define('u', NULL, e);
401 
402 	/* full name of from person */
403 	p = hvalue("full-name", e->e_header);
404 	if (p != NULL)
405 		define('x', p, e);
406 
407 	if (tTd(32, 1))
408 		printf("----- collected header -----\n");
409 	msgid = NULL;
410 	for (h = e->e_header; h != NULL; h = h->h_link)
411 	{
412 		if (h->h_value == NULL)
413 		{
414 			if (tTd(32, 1))
415 				printf("%s: <NULL>\n", h->h_field);
416 			continue;
417 		}
418 
419 		/* do early binding */
420 		if (bitset(H_DEFAULT, h->h_flags))
421 		{
422 			expand(h->h_value, buf, sizeof buf, e);
423 			if (buf[0] != '\0')
424 			{
425 				h->h_value = newstr(buf);
426 				h->h_flags &= ~H_DEFAULT;
427 			}
428 		}
429 
430 		if (tTd(32, 1))
431 		{
432 			printf("%s: ", h->h_field);
433 			xputs(h->h_value);
434 			printf("\n");
435 		}
436 
437 		/* count the number of times it has been processed */
438 		if (bitset(H_TRACE, h->h_flags))
439 			hopcnt++;
440 
441 		/* send to this person if we so desire */
442 		if (GrabTo && bitset(H_RCPT, h->h_flags) &&
443 		    !bitset(H_DEFAULT, h->h_flags) &&
444 		    (!bitset(EF_RESENT, e->e_flags) || bitset(H_RESENT, h->h_flags)))
445 		{
446 			int saveflags = e->e_flags;
447 
448 			(void) sendtolist(h->h_value, NULLADDR,
449 					  &e->e_sendqueue, 0, e);
450 
451 			/* delete fatal errors generated by this address */
452 			if (!GrabTo && !bitset(EF_FATALERRS, saveflags))
453 				e->e_flags &= ~EF_FATALERRS;
454 		}
455 
456 		/* save the message-id for logging */
457 		if (strcasecmp(h->h_field, "message-id") == 0)
458 		{
459 			msgid = h->h_value;
460 			while (isascii(*msgid) && isspace(*msgid))
461 				msgid++;
462 		}
463 
464 		/* see if this is a return-receipt header */
465 		if (bitset(H_RECEIPTTO, h->h_flags))
466 			e->e_receiptto = h->h_value;
467 	}
468 	if (tTd(32, 1))
469 		printf("----------------------------\n");
470 
471 	/* if we are just verifying (that is, sendmail -t -bv), drop out now */
472 	if (OpMode == MD_VERIFY)
473 		return;
474 
475 	/* store hop count */
476 	if (hopcnt > e->e_hopcount)
477 		e->e_hopcount = hopcnt;
478 
479 	/* message priority */
480 	p = hvalue("precedence", e->e_header);
481 	if (p != NULL)
482 		e->e_class = priencode(p);
483 	if (e->e_class < 0)
484 		e->e_timeoutclass = TOC_NONURGENT;
485 	else if (e->e_class > 0)
486 		e->e_timeoutclass = TOC_URGENT;
487 	if (full)
488 	{
489 		e->e_msgpriority = e->e_msgsize
490 				 - e->e_class * WkClassFact
491 				 + e->e_nrcpts * WkRecipFact;
492 	}
493 
494 	/* message timeout priority */
495 	p = hvalue("priority", e->e_header);
496 	if (p != NULL)
497 	{
498 		/* (this should be in the configuration file) */
499 		if (strcasecmp(p, "urgent"))
500 			e->e_timeoutclass = TOC_URGENT;
501 		else if (strcasecmp(p, "normal"))
502 			e->e_timeoutclass = TOC_NORMAL;
503 		else if (strcasecmp(p, "non-urgent"))
504 			e->e_timeoutclass = TOC_NONURGENT;
505 	}
506 
507 	/* date message originated */
508 	p = hvalue("posted-date", e->e_header);
509 	if (p == NULL)
510 		p = hvalue("date", e->e_header);
511 	if (p != NULL)
512 		define('a', p, e);
513 
514 	/* check to see if this is a MIME message */
515 	if ((e->e_bodytype != NULL &&
516 	     strcasecmp(e->e_bodytype, "8BITMIME") == 0) ||
517 	    hvalue("MIME-Version", e->e_header) != NULL)
518 	{
519 		e->e_flags |= EF_IS_MIME;
520 		if (HasEightBits)
521 			e->e_bodytype = "8BITMIME";
522 	}
523 
524 	/*
525 	**  From person in antiquated ARPANET mode
526 	**	required by UK Grey Book e-mail gateways (sigh)
527 	*/
528 
529 	if (OpMode == MD_ARPAFTP)
530 	{
531 		register struct hdrinfo *hi;
532 
533 		for (hi = HdrInfo; hi->hi_field != NULL; hi++)
534 		{
535 			if (bitset(H_FROM, hi->hi_flags) &&
536 			    (!bitset(H_RESENT, hi->hi_flags) ||
537 			     bitset(EF_RESENT, e->e_flags)) &&
538 			    (p = hvalue(hi->hi_field, e->e_header)) != NULL)
539 				break;
540 		}
541 		if (hi->hi_field != NULL)
542 		{
543 			if (tTd(32, 2))
544 				printf("eatheader: setsender(*%s == %s)\n",
545 					hi->hi_field, p);
546 			setsender(p, e, NULL, TRUE);
547 		}
548 	}
549 
550 	/*
551 	**  Log collection information.
552 	*/
553 
554 # ifdef LOG
555 	if (bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
556 		logsender(e, msgid);
557 # endif /* LOG */
558 	e->e_flags &= ~EF_LOGSENDER;
559 }
560 /*
561 **  LOGSENDER -- log sender information
562 **
563 **	Parameters:
564 **		e -- the envelope to log
565 **		msgid -- the message id
566 **
567 **	Returns:
568 **		none
569 */
570 
571 void
572 logsender(e, msgid)
573 	register ENVELOPE *e;
574 	char *msgid;
575 {
576 # ifdef LOG
577 	char *name;
578 	register char *sbp;
579 	register char *p;
580 	int l;
581 	char hbuf[MAXNAME + 1];
582 	char sbuf[MAXLINE + 1];
583 	char mbuf[MAXNAME + 1];
584 
585 	/* don't allow newlines in the message-id */
586 	if (msgid != NULL)
587 	{
588 		l = strlen(msgid);
589 		if (l > sizeof mbuf - 1)
590 			l = sizeof mbuf - 1;
591 		bcopy(msgid, mbuf, l);
592 		mbuf[l] = '\0';
593 		p = mbuf;
594 		while ((p = strchr(p, '\n')) != NULL)
595 			*p++ = ' ';
596 	}
597 
598 	if (bitset(EF_RESPONSE, e->e_flags))
599 		name = "[RESPONSE]";
600 	else if ((name = macvalue('_', e)) != NULL)
601 		;
602 	else if (RealHostName == NULL)
603 		name = "localhost";
604 	else if (RealHostName[0] == '[')
605 		name = RealHostName;
606 	else
607 	{
608 		name = hbuf;
609 		(void) sprintf(hbuf, "%.80s", RealHostName);
610 		if (RealHostAddr.sa.sa_family != 0)
611 		{
612 			p = &hbuf[strlen(hbuf)];
613 			(void) sprintf(p, " (%s)",
614 				anynet_ntoa(&RealHostAddr));
615 		}
616 	}
617 
618 	/* some versions of syslog only take 5 printf args */
619 #  if (SYSLOG_BUFSIZE) >= 256
620 	sbp = sbuf;
621 	sprintf(sbp, "from=%.200s, size=%ld, class=%d, pri=%ld, nrcpts=%d",
622 	    e->e_from.q_paddr == NULL ? "<NONE>" : e->e_from.q_paddr,
623 	    e->e_msgsize, e->e_class, e->e_msgpriority, e->e_nrcpts);
624 	sbp += strlen(sbp);
625 	if (msgid != NULL)
626 	{
627 		sprintf(sbp, ", msgid=%.100s", mbuf);
628 		sbp += strlen(sbp);
629 	}
630 	if (e->e_bodytype != NULL)
631 	{
632 		(void) sprintf(sbp, ", bodytype=%.20s", e->e_bodytype);
633 		sbp += strlen(sbp);
634 	}
635 	p = macvalue('r', e);
636 	if (p != NULL)
637 		(void) sprintf(sbp, ", proto=%.20s", p);
638 	syslog(LOG_INFO, "%s: %s, relay=%s",
639 	    e->e_id, sbuf, name);
640 
641 #  else			/* short syslog buffer */
642 
643 	syslog(LOG_INFO, "%s: from=%s",
644 		e->e_id, e->e_from.q_paddr == NULL ? "<NONE>" :
645 				shortenstring(e->e_from.q_paddr, 83));
646 	syslog(LOG_INFO, "%s: size=%ld, class=%ld, pri=%ld, nrcpts=%d",
647 		e->e_id, e->e_msgsize, e->e_class,
648 		e->e_msgpriority, e->e_nrcpts);
649 	if (msgid != NULL)
650 		syslog(LOG_INFO, "%s: msgid=%s", e->e_id, mbuf);
651 	sbp = sbuf;
652 	sprintf(sbp, "%s:", e->e_id);
653 	sbp += strlen(sbp);
654 	if (e->e_bodytype != NULL)
655 	{
656 		sprintf(sbp, " bodytype=%s,", e->e_bodytype);
657 		sbp += strlen(sbp);
658 	}
659 	p = macvalue('r', e);
660 	if (p != NULL)
661 	{
662 		sprintf(sbp, " proto=%s,", p);
663 		sbp += strlen(sbp);
664 	}
665 	syslog(LOG_INFO, "%s relay=%s", sbuf, name);
666 #  endif
667 # endif
668 }
669 /*
670 **  PRIENCODE -- encode external priority names into internal values.
671 **
672 **	Parameters:
673 **		p -- priority in ascii.
674 **
675 **	Returns:
676 **		priority as a numeric level.
677 **
678 **	Side Effects:
679 **		none.
680 */
681 
682 int
683 priencode(p)
684 	char *p;
685 {
686 	register int i;
687 
688 	for (i = 0; i < NumPriorities; i++)
689 	{
690 		if (!strcasecmp(p, Priorities[i].pri_name))
691 			return (Priorities[i].pri_val);
692 	}
693 
694 	/* unknown priority */
695 	return (0);
696 }
697 /*
698 **  CRACKADDR -- parse an address and turn it into a macro
699 **
700 **	This doesn't actually parse the address -- it just extracts
701 **	it and replaces it with "$g".  The parse is totally ad hoc
702 **	and isn't even guaranteed to leave something syntactically
703 **	identical to what it started with.  However, it does leave
704 **	something semantically identical.
705 **
706 **	This algorithm has been cleaned up to handle a wider range
707 **	of cases -- notably quoted and backslash escaped strings.
708 **	This modification makes it substantially better at preserving
709 **	the original syntax.
710 **
711 **	Parameters:
712 **		addr -- the address to be cracked.
713 **
714 **	Returns:
715 **		a pointer to the new version.
716 **
717 **	Side Effects:
718 **		none.
719 **
720 **	Warning:
721 **		The return value is saved in local storage and should
722 **		be copied if it is to be reused.
723 */
724 
725 char *
726 crackaddr(addr)
727 	register char *addr;
728 {
729 	register char *p;
730 	register char c;
731 	int cmtlev;
732 	int realcmtlev;
733 	int anglelev, realanglelev;
734 	int copylev;
735 	bool qmode;
736 	bool realqmode;
737 	bool skipping;
738 	bool putgmac = FALSE;
739 	bool quoteit = FALSE;
740 	bool gotangle = FALSE;
741 	bool gotcolon = FALSE;
742 	register char *bp;
743 	char *buflim;
744 	char *bufhead;
745 	char *addrhead;
746 	static char buf[MAXNAME + 1];
747 
748 	if (tTd(33, 1))
749 		printf("crackaddr(%s)\n", addr);
750 
751 	/* strip leading spaces */
752 	while (*addr != '\0' && isascii(*addr) && isspace(*addr))
753 		addr++;
754 
755 	/*
756 	**  Start by assuming we have no angle brackets.  This will be
757 	**  adjusted later if we find them.
758 	*/
759 
760 	bp = bufhead = buf;
761 	buflim = &buf[sizeof buf - 5];
762 	p = addrhead = addr;
763 	copylev = anglelev = realanglelev = cmtlev = realcmtlev = 0;
764 	qmode = realqmode = FALSE;
765 
766 	while ((c = *p++) != '\0')
767 	{
768 		/*
769 		**  If the buffer is overful, go into a special "skipping"
770 		**  mode that tries to keep legal syntax but doesn't actually
771 		**  output things.
772 		*/
773 
774 		skipping = bp >= buflim;
775 
776 		if (copylev > 0 && !skipping)
777 			*bp++ = c;
778 
779 		/* check for backslash escapes */
780 		if (c == '\\')
781 		{
782 			/* arrange to quote the address */
783 			if (cmtlev <= 0 && !qmode)
784 				quoteit = TRUE;
785 
786 			if ((c = *p++) == '\0')
787 			{
788 				/* too far */
789 				p--;
790 				goto putg;
791 			}
792 			if (copylev > 0 && !skipping)
793 				*bp++ = c;
794 			goto putg;
795 		}
796 
797 		/* check for quoted strings */
798 		if (c == '"' && cmtlev <= 0)
799 		{
800 			qmode = !qmode;
801 			if (copylev > 0 && !skipping)
802 				realqmode = !realqmode;
803 			continue;
804 		}
805 		if (qmode)
806 			goto putg;
807 
808 		/* check for comments */
809 		if (c == '(')
810 		{
811 			cmtlev++;
812 
813 			/* allow space for closing paren */
814 			if (!skipping)
815 			{
816 				buflim--;
817 				realcmtlev++;
818 				if (copylev++ <= 0)
819 				{
820 					*bp++ = ' ';
821 					*bp++ = c;
822 				}
823 			}
824 		}
825 		if (cmtlev > 0)
826 		{
827 			if (c == ')')
828 			{
829 				cmtlev--;
830 				copylev--;
831 				if (!skipping)
832 				{
833 					realcmtlev--;
834 					buflim++;
835 				}
836 			}
837 			continue;
838 		}
839 		else if (c == ')')
840 		{
841 			/* syntax error: unmatched ) */
842 			if (copylev > 0 && !skipping)
843 				bp--;
844 		}
845 
846 		/* check for group: list; syntax */
847 		if (c == ':' && anglelev <= 0 && !gotcolon && !ColonOkInAddr)
848 		{
849 			register char *q;
850 
851 			if (*p == ':')
852 			{
853 				/* special case -- :: syntax */
854 				if (cmtlev <= 0 && !qmode)
855 					quoteit = TRUE;
856 				if (copylev > 0 && !skipping)
857 				{
858 					*bp++ = c;
859 					*bp++ = c;
860 				}
861 				p++;
862 				goto putg;
863 			}
864 
865 			gotcolon = TRUE;
866 
867 			bp = bufhead;
868 			if (quoteit)
869 			{
870 				*bp++ = '"';
871 
872 				/* back up over the ':' and any spaces */
873 				--p;
874 				while (isascii(*--p) && isspace(*p))
875 					continue;
876 				p++;
877 			}
878 			for (q = addrhead; q < p; )
879 			{
880 				c = *q++;
881 				if (bp < buflim)
882 				{
883 					if (quoteit && c == '"')
884 						*bp++ = '\\';
885 					*bp++ = c;
886 				}
887 			}
888 			if (quoteit)
889 			{
890 				if (bp == &bufhead[1])
891 					bp--;
892 				else
893 					*bp++ = '"';
894 				while ((c = *p++) != ':')
895 				{
896 					if (bp < buflim)
897 						*bp++ = c;
898 				}
899 				*bp++ = c;
900 			}
901 
902 			/* any trailing white space is part of group: */
903 			while (isascii(*p) && isspace(*p) && bp < buflim)
904 				*bp++ = *p++;
905 			copylev = 0;
906 			putgmac = quoteit = FALSE;
907 			bufhead = bp;
908 			addrhead = p;
909 			continue;
910 		}
911 
912 		if (c == ';' && copylev <= 0 && !ColonOkInAddr)
913 		{
914 			if (bp < buflim)
915 				*bp++ = c;
916 		}
917 
918 		/* check for characters that may have to be quoted */
919 		if (strchr(".'@,;:\\()[]", c) != NULL)
920 		{
921 			/*
922 			**  If these occur as the phrase part of a <>
923 			**  construct, but are not inside of () or already
924 			**  quoted, they will have to be quoted.  Note that
925 			**  now (but don't actually do the quoting).
926 			*/
927 
928 			if (cmtlev <= 0 && !qmode)
929 				quoteit = TRUE;
930 		}
931 
932 		/* check for angle brackets */
933 		if (c == '<')
934 		{
935 			register char *q;
936 
937 			/* assume first of two angles is bogus */
938 			if (gotangle)
939 				quoteit = TRUE;
940 			gotangle = TRUE;
941 
942 			/* oops -- have to change our mind */
943 			anglelev = 1;
944 			if (!skipping)
945 				realanglelev = 1;
946 
947 			bp = bufhead;
948 			if (quoteit)
949 			{
950 				*bp++ = '"';
951 
952 				/* back up over the '<' and any spaces */
953 				--p;
954 				while (isascii(*--p) && isspace(*p))
955 					continue;
956 				p++;
957 			}
958 			for (q = addrhead; q < p; )
959 			{
960 				c = *q++;
961 				if (bp < buflim)
962 				{
963 					if (quoteit && c == '"')
964 						*bp++ = '\\';
965 					*bp++ = c;
966 				}
967 			}
968 			if (quoteit)
969 			{
970 				if (bp == &buf[1])
971 					bp--;
972 				else
973 					*bp++ = '"';
974 				while ((c = *p++) != '<')
975 				{
976 					if (bp < buflim)
977 						*bp++ = c;
978 				}
979 				*bp++ = c;
980 			}
981 			copylev = 0;
982 			putgmac = quoteit = FALSE;
983 			continue;
984 		}
985 
986 		if (c == '>')
987 		{
988 			if (anglelev > 0)
989 			{
990 				anglelev--;
991 				if (!skipping)
992 				{
993 					realanglelev--;
994 					buflim++;
995 				}
996 			}
997 			else if (!skipping)
998 			{
999 				/* syntax error: unmatched > */
1000 				if (copylev > 0)
1001 					bp--;
1002 				quoteit = TRUE;
1003 				continue;
1004 			}
1005 			if (copylev++ <= 0)
1006 				*bp++ = c;
1007 			continue;
1008 		}
1009 
1010 		/* must be a real address character */
1011 	putg:
1012 		if (copylev <= 0 && !putgmac)
1013 		{
1014 			*bp++ = MACROEXPAND;
1015 			*bp++ = 'g';
1016 			putgmac = TRUE;
1017 		}
1018 	}
1019 
1020 	/* repair any syntactic damage */
1021 	if (realqmode)
1022 		*bp++ = '"';
1023 	while (realcmtlev-- > 0)
1024 		*bp++ = ')';
1025 	while (realanglelev-- > 0)
1026 		*bp++ = '>';
1027 	*bp++ = '\0';
1028 
1029 	if (tTd(33, 1))
1030 		printf("crackaddr=>`%s'\n", buf);
1031 
1032 	return (buf);
1033 }
1034 /*
1035 **  PUTHEADER -- put the header part of a message from the in-core copy
1036 **
1037 **	Parameters:
1038 **		mci -- the connection information.
1039 **		h -- the header to put.
1040 **		e -- envelope to use.
1041 **
1042 **	Returns:
1043 **		none.
1044 **
1045 **	Side Effects:
1046 **		none.
1047 */
1048 
1049 /*
1050  * Macro for fast max (not available in e.g. DG/UX, 386/ix).
1051  */
1052 #ifndef MAX
1053 # define MAX(a,b) (((a)>(b))?(a):(b))
1054 #endif
1055 
1056 void
1057 putheader(mci, h, e)
1058 	register MCI *mci;
1059 	register HDR *h;
1060 	register ENVELOPE *e;
1061 {
1062 	char buf[MAX(MAXLINE,BUFSIZ)];
1063 	char obuf[MAXLINE];
1064 
1065 	if (tTd(34, 1))
1066 		printf("--- putheader, mailer = %s ---\n",
1067 			mci->mci_mailer->m_name);
1068 
1069 	mci->mci_flags |= MCIF_INHEADER;
1070 	for (; h != NULL; h = h->h_link)
1071 	{
1072 		register char *p = h->h_value;
1073 		extern bool bitintersect();
1074 
1075 		if (tTd(34, 11))
1076 		{
1077 			printf("  %s: ", h->h_field);
1078 			xputs(p);
1079 		}
1080 
1081 		/* suppress Content-Transfer-Encoding: if we are MIMEing */
1082 		if (bitset(H_CTE, h->h_flags) &&
1083 		    bitset(MCIF_CVT8TO7|MCIF_INMIME, mci->mci_flags))
1084 		{
1085 			if (tTd(34, 11))
1086 				printf(" (skipped (content-transfer-encoding))\n");
1087 			continue;
1088 		}
1089 
1090 		if (bitset(MCIF_INMIME, mci->mci_flags))
1091 			goto vanilla;
1092 
1093 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) &&
1094 		    !bitintersect(h->h_mflags, mci->mci_mailer->m_flags))
1095 		{
1096 			if (tTd(34, 11))
1097 				printf(" (skipped)\n");
1098 			continue;
1099 		}
1100 
1101 		/* handle Resent-... headers specially */
1102 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
1103 		{
1104 			if (tTd(34, 11))
1105 				printf(" (skipped (resent))\n");
1106 			continue;
1107 		}
1108 
1109 		/* suppress return receipts if requested */
1110 		if (bitset(H_RECEIPTTO, h->h_flags) &&
1111 		    bitset(EF_NORECEIPT, e->e_flags))
1112 		{
1113 			if (tTd(34, 11))
1114 				printf(" (skipped (receipt))\n");
1115 			continue;
1116 		}
1117 
1118 		/* macro expand value if generated internally */
1119 		if (bitset(H_DEFAULT, h->h_flags))
1120 		{
1121 			expand(p, buf, sizeof buf, e);
1122 			p = buf;
1123 			if (p == NULL || *p == '\0')
1124 			{
1125 				if (tTd(34, 11))
1126 					printf(" (skipped -- null value)\n");
1127 				continue;
1128 			}
1129 		}
1130 
1131 		if (tTd(34, 11))
1132 			printf("\n");
1133 
1134 		if (bitset(H_STRIPVAL, h->h_flags))
1135 		{
1136 			/* empty field */
1137 			(void) sprintf(obuf, "%s:", h->h_field);
1138 			putline(obuf, mci);
1139 		}
1140 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
1141 		{
1142 			/* address field */
1143 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
1144 
1145 			if (bitset(H_FROM, h->h_flags))
1146 				oldstyle = FALSE;
1147 			commaize(h, p, oldstyle, mci, e);
1148 		}
1149 		else
1150 		{
1151 			/* vanilla header line */
1152 			register char *nlp;
1153 
1154 vanilla:
1155 			(void) sprintf(obuf, "%s: ", h->h_field);
1156 			while ((nlp = strchr(p, '\n')) != NULL)
1157 			{
1158 				*nlp = '\0';
1159 				(void) strcat(obuf, p);
1160 				*nlp = '\n';
1161 				putline(obuf, mci);
1162 				p = ++nlp;
1163 				obuf[0] = '\0';
1164 			}
1165 			(void) strcat(obuf, p);
1166 			putline(obuf, mci);
1167 		}
1168 	}
1169 
1170 	/*
1171 	**  If we are converting this to a MIME message, add the
1172 	**  MIME headers.
1173 	*/
1174 
1175 #if MIME8TO7
1176 	if (bitset(MM_MIME8BIT, MimeMode) &&
1177 	    bitset(EF_HAS8BIT, e->e_flags) &&
1178 	    !bitnset(M_8BITS, mci->mci_mailer->m_flags) &&
1179 	    !bitset(MCIF_CVT8TO7, mci->mci_flags))
1180 	{
1181 		if (hvalue("MIME-Version", e->e_header) == NULL)
1182 			putline("MIME-Version: 1.0", mci);
1183 		if (hvalue("Content-Type", e->e_header) == NULL)
1184 		{
1185 			sprintf(obuf, "Content-Type: text/plain; charset=%s",
1186 				defcharset(e));
1187 			putline(obuf, mci);
1188 		}
1189 		if (hvalue("Content-Transfer-Encoding", e->e_header) == NULL)
1190 			putline("Content-Transfer-Encoding: 8bit", mci);
1191 	}
1192 #endif
1193 }
1194 /*
1195 **  COMMAIZE -- output a header field, making a comma-translated list.
1196 **
1197 **	Parameters:
1198 **		h -- the header field to output.
1199 **		p -- the value to put in it.
1200 **		oldstyle -- TRUE if this is an old style header.
1201 **		mci -- the connection information.
1202 **		e -- the envelope containing the message.
1203 **
1204 **	Returns:
1205 **		none.
1206 **
1207 **	Side Effects:
1208 **		outputs "p" to file "fp".
1209 */
1210 
1211 void
1212 commaize(h, p, oldstyle, mci, e)
1213 	register HDR *h;
1214 	register char *p;
1215 	bool oldstyle;
1216 	register MCI *mci;
1217 	register ENVELOPE *e;
1218 {
1219 	register char *obp;
1220 	int opos;
1221 	int omax;
1222 	bool firstone = TRUE;
1223 	char obuf[MAXLINE + 3];
1224 
1225 	/*
1226 	**  Output the address list translated by the
1227 	**  mailer and with commas.
1228 	*/
1229 
1230 	if (tTd(14, 2))
1231 		printf("commaize(%s: %s)\n", h->h_field, p);
1232 
1233 	obp = obuf;
1234 	(void) sprintf(obp, "%s: ", h->h_field);
1235 	opos = strlen(h->h_field) + 2;
1236 	obp += opos;
1237 	omax = mci->mci_mailer->m_linelimit - 2;
1238 	if (omax < 0 || omax > 78)
1239 		omax = 78;
1240 
1241 	/*
1242 	**  Run through the list of values.
1243 	*/
1244 
1245 	while (*p != '\0')
1246 	{
1247 		register char *name;
1248 		register int c;
1249 		char savechar;
1250 		int flags;
1251 		auto int stat;
1252 
1253 		/*
1254 		**  Find the end of the name.  New style names
1255 		**  end with a comma, old style names end with
1256 		**  a space character.  However, spaces do not
1257 		**  necessarily delimit an old-style name -- at
1258 		**  signs mean keep going.
1259 		*/
1260 
1261 		/* find end of name */
1262 		while ((isascii(*p) && isspace(*p)) || *p == ',')
1263 			p++;
1264 		name = p;
1265 		for (;;)
1266 		{
1267 			auto char *oldp;
1268 			char pvpbuf[PSBUFSIZE];
1269 
1270 			(void) prescan(p, oldstyle ? ' ' : ',', pvpbuf,
1271 				       sizeof pvpbuf, &oldp, NULL);
1272 			p = oldp;
1273 
1274 			/* look to see if we have an at sign */
1275 			while (*p != '\0' && isascii(*p) && isspace(*p))
1276 				p++;
1277 
1278 			if (*p != '@')
1279 			{
1280 				p = oldp;
1281 				break;
1282 			}
1283 			p += *p == '@' ? 1 : 2;
1284 			while (*p != '\0' && isascii(*p) && isspace(*p))
1285 				p++;
1286 		}
1287 		/* at the end of one complete name */
1288 
1289 		/* strip off trailing white space */
1290 		while (p >= name &&
1291 		       ((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
1292 			p--;
1293 		if (++p == name)
1294 			continue;
1295 		savechar = *p;
1296 		*p = '\0';
1297 
1298 		/* translate the name to be relative */
1299 		flags = RF_HEADERADDR|RF_ADDDOMAIN;
1300 		if (bitset(H_FROM, h->h_flags))
1301 			flags |= RF_SENDERADDR;
1302 #if USERDB
1303 		else if (e->e_from.q_mailer != NULL &&
1304 			 bitnset(M_UDBRECIPIENT, e->e_from.q_mailer->m_flags))
1305 		{
1306 			extern char *udbsender();
1307 
1308 			name = udbsender(name);
1309 		}
1310 #endif
1311 		stat = EX_OK;
1312 		name = remotename(name, mci->mci_mailer, flags, &stat, e);
1313 		if (*name == '\0')
1314 		{
1315 			*p = savechar;
1316 			continue;
1317 		}
1318 
1319 		/* output the name with nice formatting */
1320 		opos += strlen(name);
1321 		if (!firstone)
1322 			opos += 2;
1323 		if (opos > omax && !firstone)
1324 		{
1325 			(void) strcpy(obp, ",\n");
1326 			putline(obuf, mci);
1327 			obp = obuf;
1328 			(void) strcpy(obp, "        ");
1329 			opos = strlen(obp);
1330 			obp += opos;
1331 			opos += strlen(name);
1332 		}
1333 		else if (!firstone)
1334 		{
1335 			(void) strcpy(obp, ", ");
1336 			obp += 2;
1337 		}
1338 
1339 		while ((c = *name++) != '\0' && obp < &obuf[MAXLINE])
1340 			*obp++ = c;
1341 		firstone = FALSE;
1342 		*p = savechar;
1343 	}
1344 	(void) strcpy(obp, "\n");
1345 	putline(obuf, mci);
1346 }
1347 /*
1348 **  COPYHEADER -- copy header list
1349 **
1350 **	This routine is the equivalent of newstr for header lists
1351 **
1352 **	Parameters:
1353 **		header -- list of header structures to copy.
1354 **
1355 **	Returns:
1356 **		a copy of 'header'.
1357 **
1358 **	Side Effects:
1359 **		none.
1360 */
1361 
1362 HDR *
1363 copyheader(header)
1364 	register HDR *header;
1365 {
1366 	register HDR *newhdr;
1367 	HDR *ret;
1368 	register HDR **tail = &ret;
1369 
1370 	while (header != NULL)
1371 	{
1372 		newhdr = (HDR *) xalloc(sizeof(HDR));
1373 		STRUCTCOPY(*header, *newhdr);
1374 		*tail = newhdr;
1375 		tail = &newhdr->h_link;
1376 		header = header->h_link;
1377 	}
1378 	*tail = NULL;
1379 
1380 	return ret;
1381 }
1382