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