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.61 (Berkeley) 05/05/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 &&
503 	     strcasecmp(e->e_bodytype, "8BITMIME") == 0) ||
504 	    hvalue("MIME-Version", e->e_header) != NULL)
505 	{
506 		e->e_flags |= EF_IS_MIME;
507 		if (HasEightBits)
508 			e->e_bodytype = "8BITMIME";
509 	}
510 
511 	/*
512 	**  From person in antiquated ARPANET mode
513 	**	required by UK Grey Book e-mail gateways (sigh)
514 	*/
515 
516 	if (OpMode == MD_ARPAFTP)
517 	{
518 		register struct hdrinfo *hi;
519 
520 		for (hi = HdrInfo; hi->hi_field != NULL; hi++)
521 		{
522 			if (bitset(H_FROM, hi->hi_flags) &&
523 			    (!bitset(H_RESENT, hi->hi_flags) ||
524 			     bitset(EF_RESENT, e->e_flags)) &&
525 			    (p = hvalue(hi->hi_field, e->e_header)) != NULL)
526 				break;
527 		}
528 		if (hi->hi_field != NULL)
529 		{
530 			if (tTd(32, 2))
531 				printf("eatheader: setsender(*%s == %s)\n",
532 					hi->hi_field, p);
533 			setsender(p, e, NULL, TRUE);
534 		}
535 	}
536 
537 	/*
538 	**  Log collection information.
539 	*/
540 
541 # ifdef LOG
542 	if (bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
543 		logsender(e, msgid);
544 # endif /* LOG */
545 	e->e_flags &= ~EF_LOGSENDER;
546 }
547 /*
548 **  LOGSENDER -- log sender information
549 **
550 **	Parameters:
551 **		e -- the envelope to log
552 **		msgid -- the message id
553 **
554 **	Returns:
555 **		none
556 */
557 
558 logsender(e, msgid)
559 	register ENVELOPE *e;
560 	char *msgid;
561 {
562 # ifdef LOG
563 	char *name;
564 	register char *sbp;
565 	register char *p;
566 	int l;
567 	char hbuf[MAXNAME + 1];
568 	char sbuf[MAXLINE + 1];
569 	char mbuf[MAXNAME + 1];
570 
571 	/* don't allow newlines in the message-id */
572 	if (msgid != NULL)
573 	{
574 		l = strlen(msgid);
575 		if (l > sizeof mbuf - 1)
576 			l = sizeof mbuf - 1;
577 		bcopy(msgid, mbuf, l);
578 		mbuf[l] = '\0';
579 		p = mbuf;
580 		while ((p = strchr(p, '\n')) != NULL)
581 			*p++ = ' ';
582 	}
583 
584 	if (bitset(EF_RESPONSE, e->e_flags))
585 		name = "[RESPONSE]";
586 	else if ((name = macvalue('_', e)) != NULL)
587 		;
588 	else if (RealHostName == NULL)
589 		name = "localhost";
590 	else if (RealHostName[0] == '[')
591 		name = RealHostName;
592 	else
593 	{
594 		name = hbuf;
595 		(void) sprintf(hbuf, "%.80s", RealHostName);
596 		if (RealHostAddr.sa.sa_family != 0)
597 		{
598 			p = &hbuf[strlen(hbuf)];
599 			(void) sprintf(p, " (%s)",
600 				anynet_ntoa(&RealHostAddr));
601 		}
602 	}
603 
604 	/* some versions of syslog only take 5 printf args */
605 #  if (SYSLOG_BUFSIZE) >= 256
606 	sbp = sbuf;
607 	sprintf(sbp, "from=%.200s, size=%ld, class=%d, pri=%ld, nrcpts=%d",
608 	    e->e_from.q_paddr == NULL ? "<NONE>" : e->e_from.q_paddr,
609 	    e->e_msgsize, e->e_class, e->e_msgpriority, e->e_nrcpts);
610 	sbp += strlen(sbp);
611 	if (msgid != NULL)
612 	{
613 		sprintf(sbp, ", msgid=%.100s", mbuf);
614 		sbp += strlen(sbp);
615 	}
616 	if (e->e_bodytype != NULL)
617 	{
618 		(void) sprintf(sbp, ", bodytype=%.20s", e->e_bodytype);
619 		sbp += strlen(sbp);
620 	}
621 	p = macvalue('r', e);
622 	if (p != NULL)
623 		(void) sprintf(sbp, ", proto=%.20s", p);
624 	syslog(LOG_INFO, "%s: %s, relay=%s",
625 	    e->e_id, sbuf, name);
626 
627 #  else			/* short syslog buffer */
628 
629 	syslog(LOG_INFO, "%s: from=%s",
630 		e->e_id, e->e_from.q_paddr == NULL ? "<NONE>" :
631 				shortenstring(e->e_from.q_paddr, 83));
632 	syslog(LOG_INFO, "%s: size=%ld, class=%ld, pri=%ld, nrcpts=%d",
633 		e->e_id, e->e_msgsize, e->e_class,
634 		e->e_msgpriority, e->e_nrcpts);
635 	if (msgid != NULL)
636 		syslog(LOG_INFO, "%s: msgid=%s", e->e_id, mbuf);
637 	sbp = sbuf;
638 	sprintf(sbp, "%s:", e->e_id);
639 	sbp += strlen(sbp);
640 	if (e->e_bodytype != NULL)
641 	{
642 		sprintf(sbp, " bodytype=%s,", e->e_bodytype);
643 		sbp += strlen(sbp);
644 	}
645 	p = macvalue('r', e);
646 	if (p != NULL)
647 	{
648 		sprintf(sbp, " proto=%s,", p);
649 		sbp += strlen(sbp);
650 	}
651 	syslog(LOG_INFO, "%s relay=%s", sbuf, name);
652 #  endif
653 # endif
654 }
655 /*
656 **  PRIENCODE -- encode external priority names into internal values.
657 **
658 **	Parameters:
659 **		p -- priority in ascii.
660 **
661 **	Returns:
662 **		priority as a numeric level.
663 **
664 **	Side Effects:
665 **		none.
666 */
667 
668 priencode(p)
669 	char *p;
670 {
671 	register int i;
672 
673 	for (i = 0; i < NumPriorities; i++)
674 	{
675 		if (!strcasecmp(p, Priorities[i].pri_name))
676 			return (Priorities[i].pri_val);
677 	}
678 
679 	/* unknown priority */
680 	return (0);
681 }
682 /*
683 **  CRACKADDR -- parse an address and turn it into a macro
684 **
685 **	This doesn't actually parse the address -- it just extracts
686 **	it and replaces it with "$g".  The parse is totally ad hoc
687 **	and isn't even guaranteed to leave something syntactically
688 **	identical to what it started with.  However, it does leave
689 **	something semantically identical.
690 **
691 **	This algorithm has been cleaned up to handle a wider range
692 **	of cases -- notably quoted and backslash escaped strings.
693 **	This modification makes it substantially better at preserving
694 **	the original syntax.
695 **
696 **	Parameters:
697 **		addr -- the address to be cracked.
698 **
699 **	Returns:
700 **		a pointer to the new version.
701 **
702 **	Side Effects:
703 **		none.
704 **
705 **	Warning:
706 **		The return value is saved in local storage and should
707 **		be copied if it is to be reused.
708 */
709 
710 char *
711 crackaddr(addr)
712 	register char *addr;
713 {
714 	register char *p;
715 	register char c;
716 	int cmtlev;
717 	int realcmtlev;
718 	int anglelev, realanglelev;
719 	int copylev;
720 	bool qmode;
721 	bool realqmode;
722 	bool skipping;
723 	bool putgmac = FALSE;
724 	bool quoteit = FALSE;
725 	bool gotangle = FALSE;
726 	bool gotcolon = FALSE;
727 	register char *bp;
728 	char *buflim;
729 	char *bufhead;
730 	char *addrhead;
731 	static char buf[MAXNAME + 1];
732 
733 	if (tTd(33, 1))
734 		printf("crackaddr(%s)\n", addr);
735 
736 	/* strip leading spaces */
737 	while (*addr != '\0' && isascii(*addr) && isspace(*addr))
738 		addr++;
739 
740 	/*
741 	**  Start by assuming we have no angle brackets.  This will be
742 	**  adjusted later if we find them.
743 	*/
744 
745 	bp = bufhead = buf;
746 	buflim = &buf[sizeof buf - 5];
747 	p = addrhead = addr;
748 	copylev = anglelev = realanglelev = cmtlev = realcmtlev = 0;
749 	qmode = realqmode = FALSE;
750 
751 	while ((c = *p++) != '\0')
752 	{
753 		/*
754 		**  If the buffer is overful, go into a special "skipping"
755 		**  mode that tries to keep legal syntax but doesn't actually
756 		**  output things.
757 		*/
758 
759 		skipping = bp >= buflim;
760 
761 		if (copylev > 0 && !skipping)
762 			*bp++ = c;
763 
764 		/* check for backslash escapes */
765 		if (c == '\\')
766 		{
767 			/* arrange to quote the address */
768 			if (cmtlev <= 0 && !qmode)
769 				quoteit = TRUE;
770 
771 			if ((c = *p++) == '\0')
772 			{
773 				/* too far */
774 				p--;
775 				goto putg;
776 			}
777 			if (copylev > 0 && !skipping)
778 				*bp++ = c;
779 			goto putg;
780 		}
781 
782 		/* check for quoted strings */
783 		if (c == '"' && cmtlev <= 0)
784 		{
785 			qmode = !qmode;
786 			if (copylev > 0 && !skipping)
787 				realqmode = !realqmode;
788 			continue;
789 		}
790 		if (qmode)
791 			goto putg;
792 
793 		/* check for comments */
794 		if (c == '(')
795 		{
796 			cmtlev++;
797 
798 			/* allow space for closing paren */
799 			if (!skipping)
800 			{
801 				buflim--;
802 				realcmtlev++;
803 				if (copylev++ <= 0)
804 				{
805 					*bp++ = ' ';
806 					*bp++ = c;
807 				}
808 			}
809 		}
810 		if (cmtlev > 0)
811 		{
812 			if (c == ')')
813 			{
814 				cmtlev--;
815 				copylev--;
816 				if (!skipping)
817 				{
818 					realcmtlev--;
819 					buflim++;
820 				}
821 			}
822 			continue;
823 		}
824 		else if (c == ')')
825 		{
826 			/* syntax error: unmatched ) */
827 			if (copylev > 0 && !skipping)
828 				bp--;
829 		}
830 
831 		/* check for group: list; syntax */
832 		if (c == ':' && anglelev <= 0 && !gotcolon && !ColonOkInAddr)
833 		{
834 			register char *q;
835 
836 			if (*p == ':')
837 			{
838 				/* special case -- :: syntax */
839 				if (cmtlev <= 0 && !qmode)
840 					quoteit = TRUE;
841 				if (copylev > 0 && !skipping)
842 				{
843 					*bp++ = c;
844 					*bp++ = c;
845 				}
846 				p++;
847 				goto putg;
848 			}
849 
850 			gotcolon = TRUE;
851 
852 			bp = bufhead;
853 			if (quoteit)
854 			{
855 				*bp++ = '"';
856 
857 				/* back up over the ':' and any spaces */
858 				--p;
859 				while (isascii(*--p) && isspace(*p))
860 					continue;
861 				p++;
862 			}
863 			for (q = addrhead; q < p; )
864 			{
865 				c = *q++;
866 				if (bp < buflim)
867 				{
868 					if (quoteit && c == '"')
869 						*bp++ = '\\';
870 					*bp++ = c;
871 				}
872 			}
873 			if (quoteit)
874 			{
875 				if (bp == &bufhead[1])
876 					bp--;
877 				else
878 					*bp++ = '"';
879 				while ((c = *p++) != ':')
880 				{
881 					if (bp < buflim)
882 						*bp++ = c;
883 				}
884 				*bp++ = c;
885 			}
886 
887 			/* any trailing white space is part of group: */
888 			while (isascii(*p) && isspace(*p) && bp < buflim)
889 				*bp++ = *p++;
890 			copylev = 0;
891 			putgmac = quoteit = FALSE;
892 			bufhead = bp;
893 			addrhead = p;
894 			continue;
895 		}
896 
897 		if (c == ';' && copylev <= 0 && !ColonOkInAddr)
898 		{
899 			register char *q = p;
900 
901 			if (bp < buflim)
902 				*bp++ = c;
903 		}
904 
905 		/* check for characters that may have to be quoted */
906 		if (strchr(".'@,;:\\()[]", c) != NULL)
907 		{
908 			/*
909 			**  If these occur as the phrase part of a <>
910 			**  construct, but are not inside of () or already
911 			**  quoted, they will have to be quoted.  Note that
912 			**  now (but don't actually do the quoting).
913 			*/
914 
915 			if (cmtlev <= 0 && !qmode)
916 				quoteit = TRUE;
917 		}
918 
919 		/* check for angle brackets */
920 		if (c == '<')
921 		{
922 			register char *q;
923 
924 			/* assume first of two angles is bogus */
925 			if (gotangle)
926 				quoteit = TRUE;
927 			gotangle = TRUE;
928 
929 			/* oops -- have to change our mind */
930 			anglelev = 1;
931 			if (!skipping)
932 				realanglelev = 1;
933 
934 			bp = bufhead;
935 			if (quoteit)
936 			{
937 				*bp++ = '"';
938 
939 				/* back up over the '<' and any spaces */
940 				--p;
941 				while (isascii(*--p) && isspace(*p))
942 					continue;
943 				p++;
944 			}
945 			for (q = addrhead; q < p; )
946 			{
947 				c = *q++;
948 				if (bp < buflim)
949 				{
950 					if (quoteit && c == '"')
951 						*bp++ = '\\';
952 					*bp++ = c;
953 				}
954 			}
955 			if (quoteit)
956 			{
957 				if (bp == &buf[1])
958 					bp--;
959 				else
960 					*bp++ = '"';
961 				while ((c = *p++) != '<')
962 				{
963 					if (bp < buflim)
964 						*bp++ = c;
965 				}
966 				*bp++ = c;
967 			}
968 			copylev = 0;
969 			putgmac = quoteit = FALSE;
970 			continue;
971 		}
972 
973 		if (c == '>')
974 		{
975 			if (anglelev > 0)
976 			{
977 				anglelev--;
978 				if (!skipping)
979 				{
980 					realanglelev--;
981 					buflim++;
982 				}
983 			}
984 			else if (!skipping)
985 			{
986 				/* syntax error: unmatched > */
987 				if (copylev > 0)
988 					bp--;
989 				quoteit = TRUE;
990 				continue;
991 			}
992 			if (copylev++ <= 0)
993 				*bp++ = c;
994 			continue;
995 		}
996 
997 		/* must be a real address character */
998 	putg:
999 		if (copylev <= 0 && !putgmac)
1000 		{
1001 			*bp++ = MACROEXPAND;
1002 			*bp++ = 'g';
1003 			putgmac = TRUE;
1004 		}
1005 	}
1006 
1007 	/* repair any syntactic damage */
1008 	if (realqmode)
1009 		*bp++ = '"';
1010 	while (realcmtlev-- > 0)
1011 		*bp++ = ')';
1012 	while (realanglelev-- > 0)
1013 		*bp++ = '>';
1014 	*bp++ = '\0';
1015 
1016 	if (tTd(33, 1))
1017 		printf("crackaddr=>`%s'\n", buf);
1018 
1019 	return (buf);
1020 }
1021 /*
1022 **  PUTHEADER -- put the header part of a message from the in-core copy
1023 **
1024 **	Parameters:
1025 **		mci -- the connection information.
1026 **		h -- the header to put.
1027 **		e -- envelope to use.
1028 **
1029 **	Returns:
1030 **		none.
1031 **
1032 **	Side Effects:
1033 **		none.
1034 */
1035 
1036 /*
1037  * Macro for fast max (not available in e.g. DG/UX, 386/ix).
1038  */
1039 #ifndef MAX
1040 # define MAX(a,b) (((a)>(b))?(a):(b))
1041 #endif
1042 
1043 putheader(mci, h, e)
1044 	register MCI *mci;
1045 	register HDR *h;
1046 	register ENVELOPE *e;
1047 {
1048 	char buf[MAX(MAXLINE,BUFSIZ)];
1049 	char obuf[MAXLINE];
1050 
1051 	if (tTd(34, 1))
1052 		printf("--- putheader, mailer = %s ---\n",
1053 			mci->mci_mailer->m_name);
1054 
1055 	mci->mci_flags |= MCIF_INHEADER;
1056 	for (; h != NULL; h = h->h_link)
1057 	{
1058 		register char *p;
1059 		extern bool bitintersect();
1060 
1061 		if (tTd(34, 11))
1062 		{
1063 			printf("  %s: ", h->h_field);
1064 			xputs(h->h_value);
1065 		}
1066 
1067 		/* suppress Content-Transfer-Encoding: if we are MIMEing */
1068 		if (bitset(H_CTE, h->h_flags) &&
1069 		    bitset(MCIF_CVT8TO7|MCIF_INMIME, mci->mci_flags))
1070 		{
1071 			if (tTd(34, 11))
1072 				printf(" (skipped (content-transfer-encoding))\n");
1073 			continue;
1074 		}
1075 
1076 		if (bitset(MCIF_INMIME, mci->mci_flags))
1077 			goto vanilla;
1078 
1079 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) &&
1080 		    !bitintersect(h->h_mflags, mci->mci_mailer->m_flags))
1081 		{
1082 			if (tTd(34, 11))
1083 				printf(" (skipped)\n");
1084 			continue;
1085 		}
1086 
1087 		/* handle Resent-... headers specially */
1088 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
1089 		{
1090 			if (tTd(34, 11))
1091 				printf(" (skipped (resent))\n");
1092 			continue;
1093 		}
1094 
1095 		/* suppress return receipts if requested */
1096 		if (bitset(H_RECEIPTTO, h->h_flags) &&
1097 		    bitset(EF_NORECEIPT, e->e_flags))
1098 		{
1099 			if (tTd(34, 11))
1100 				printf(" (skipped (receipt))\n");
1101 			continue;
1102 		}
1103 
1104 		/* macro expand value if generated internally */
1105 		p = h->h_value;
1106 		if (bitset(H_DEFAULT, h->h_flags))
1107 		{
1108 			expand(p, buf, sizeof buf, e);
1109 			p = buf;
1110 			if (p == NULL || *p == '\0')
1111 			{
1112 				if (tTd(34, 11))
1113 					printf(" (skipped -- null value)\n");
1114 				continue;
1115 			}
1116 		}
1117 
1118 		if (tTd(34, 11))
1119 			printf("\n");
1120 
1121 		if (bitset(H_STRIPVAL, h->h_flags))
1122 		{
1123 			/* empty field */
1124 			(void) sprintf(obuf, "%s:", h->h_field);
1125 			putline(obuf, mci);
1126 		}
1127 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
1128 		{
1129 			/* address field */
1130 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
1131 
1132 			if (bitset(H_FROM, h->h_flags))
1133 				oldstyle = FALSE;
1134 			commaize(h, p, oldstyle, mci, e);
1135 		}
1136 		else
1137 		{
1138 			/* vanilla header line */
1139 			register char *nlp;
1140 
1141 vanilla:
1142 			(void) sprintf(obuf, "%s: ", h->h_field);
1143 			while ((nlp = strchr(p, '\n')) != NULL)
1144 			{
1145 				*nlp = '\0';
1146 				(void) strcat(obuf, p);
1147 				*nlp = '\n';
1148 				putline(obuf, mci);
1149 				p = ++nlp;
1150 				obuf[0] = '\0';
1151 			}
1152 			(void) strcat(obuf, p);
1153 			putline(obuf, mci);
1154 		}
1155 	}
1156 
1157 	/*
1158 	**  If we are converting this to a MIME message, add the
1159 	**  MIME headers.
1160 	*/
1161 
1162 	if (bitset(MM_MIME8BIT, MimeMode) &&
1163 	    bitset(EF_HAS8BIT, e->e_flags) &&
1164 	    !bitnset(M_8BITS, mci->mci_mailer->m_flags) &&
1165 	    !bitset(MCIF_CVT8TO7, mci->mci_flags))
1166 	{
1167 		if (hvalue("MIME-Version", e->e_header) == NULL)
1168 			putline("MIME-Version: 1.0", mci);
1169 		if (hvalue("Content-Type", e->e_header) == NULL)
1170 		{
1171 			sprintf(obuf, "Content-Type: text/plain; charset=%s",
1172 				defcharset(e));
1173 			putline(obuf, mci);
1174 		}
1175 		if (hvalue("Content-Transfer-Encoding", e->e_header) == NULL)
1176 			putline("Content-Transfer-Encoding: 8bit", mci);
1177 	}
1178 }
1179 /*
1180 **  COMMAIZE -- output a header field, making a comma-translated list.
1181 **
1182 **	Parameters:
1183 **		h -- the header field to output.
1184 **		p -- the value to put in it.
1185 **		oldstyle -- TRUE if this is an old style header.
1186 **		mci -- the connection information.
1187 **		e -- the envelope containing the message.
1188 **
1189 **	Returns:
1190 **		none.
1191 **
1192 **	Side Effects:
1193 **		outputs "p" to file "fp".
1194 */
1195 
1196 void
1197 commaize(h, p, oldstyle, mci, e)
1198 	register HDR *h;
1199 	register char *p;
1200 	bool oldstyle;
1201 	register MCI *mci;
1202 	register ENVELOPE *e;
1203 {
1204 	register char *obp;
1205 	int opos;
1206 	int omax;
1207 	bool firstone = TRUE;
1208 	char obuf[MAXLINE + 3];
1209 
1210 	/*
1211 	**  Output the address list translated by the
1212 	**  mailer and with commas.
1213 	*/
1214 
1215 	if (tTd(14, 2))
1216 		printf("commaize(%s: %s)\n", h->h_field, p);
1217 
1218 	obp = obuf;
1219 	(void) sprintf(obp, "%s: ", h->h_field);
1220 	opos = strlen(h->h_field) + 2;
1221 	obp += opos;
1222 	omax = mci->mci_mailer->m_linelimit - 2;
1223 	if (omax < 0 || omax > 78)
1224 		omax = 78;
1225 
1226 	/*
1227 	**  Run through the list of values.
1228 	*/
1229 
1230 	while (*p != '\0')
1231 	{
1232 		register char *name;
1233 		register int c;
1234 		char savechar;
1235 		int flags;
1236 		auto int stat;
1237 
1238 		/*
1239 		**  Find the end of the name.  New style names
1240 		**  end with a comma, old style names end with
1241 		**  a space character.  However, spaces do not
1242 		**  necessarily delimit an old-style name -- at
1243 		**  signs mean keep going.
1244 		*/
1245 
1246 		/* find end of name */
1247 		while ((isascii(*p) && isspace(*p)) || *p == ',')
1248 			p++;
1249 		name = p;
1250 		for (;;)
1251 		{
1252 			auto char *oldp;
1253 			char pvpbuf[PSBUFSIZE];
1254 
1255 			(void) prescan(p, oldstyle ? ' ' : ',', pvpbuf,
1256 				       sizeof pvpbuf, &oldp, NULL);
1257 			p = oldp;
1258 
1259 			/* look to see if we have an at sign */
1260 			while (*p != '\0' && isascii(*p) && isspace(*p))
1261 				p++;
1262 
1263 			if (*p != '@')
1264 			{
1265 				p = oldp;
1266 				break;
1267 			}
1268 			p += *p == '@' ? 1 : 2;
1269 			while (*p != '\0' && isascii(*p) && isspace(*p))
1270 				p++;
1271 		}
1272 		/* at the end of one complete name */
1273 
1274 		/* strip off trailing white space */
1275 		while (p >= name &&
1276 		       ((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
1277 			p--;
1278 		if (++p == name)
1279 			continue;
1280 		savechar = *p;
1281 		*p = '\0';
1282 
1283 		/* translate the name to be relative */
1284 		flags = RF_HEADERADDR|RF_ADDDOMAIN;
1285 		if (bitset(H_FROM, h->h_flags))
1286 			flags |= RF_SENDERADDR;
1287 #ifdef USERDB
1288 		else if (e->e_from.q_mailer != NULL &&
1289 			 bitnset(M_UDBRECIPIENT, e->e_from.q_mailer->m_flags))
1290 		{
1291 			extern char *udbsender();
1292 
1293 			name = udbsender(name);
1294 		}
1295 #endif
1296 		stat = EX_OK;
1297 		name = remotename(name, mci->mci_mailer, flags, &stat, e);
1298 		if (*name == '\0')
1299 		{
1300 			*p = savechar;
1301 			continue;
1302 		}
1303 
1304 		/* output the name with nice formatting */
1305 		opos += strlen(name);
1306 		if (!firstone)
1307 			opos += 2;
1308 		if (opos > omax && !firstone)
1309 		{
1310 			(void) strcpy(obp, ",\n");
1311 			putline(obuf, mci);
1312 			obp = obuf;
1313 			(void) strcpy(obp, "        ");
1314 			opos = strlen(obp);
1315 			obp += opos;
1316 			opos += strlen(name);
1317 		}
1318 		else if (!firstone)
1319 		{
1320 			(void) strcpy(obp, ", ");
1321 			obp += 2;
1322 		}
1323 
1324 		while ((c = *name++) != '\0' && obp < &obuf[MAXLINE])
1325 			*obp++ = c;
1326 		firstone = FALSE;
1327 		*p = savechar;
1328 	}
1329 	(void) strcpy(obp, "\n");
1330 	putline(obuf, mci);
1331 }
1332 /*
1333 **  COPYHEADER -- copy header list
1334 **
1335 **	This routine is the equivalent of newstr for header lists
1336 **
1337 **	Parameters:
1338 **		header -- list of header structures to copy.
1339 **
1340 **	Returns:
1341 **		a copy of 'header'.
1342 **
1343 **	Side Effects:
1344 **		none.
1345 */
1346 
1347 HDR *
1348 copyheader(header)
1349 	register HDR *header;
1350 {
1351 	register HDR *newhdr;
1352 	HDR *ret;
1353 	register HDR **tail = &ret;
1354 
1355 	while (header != NULL)
1356 	{
1357 		newhdr = (HDR *) xalloc(sizeof(HDR));
1358 		STRUCTCOPY(*header, *newhdr);
1359 		*tail = newhdr;
1360 		tail = &newhdr->h_link;
1361 		header = header->h_link;
1362 	}
1363 	*tail = NULL;
1364 
1365 	return ret;
1366 }
1367