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