xref: /illumos-gate/usr/src/cmd/sendmail/src/savemail.c (revision e9af4bc0)
1 /*
2  * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #include <sendmail.h>
15 
16 SM_RCSID("@(#)$Id: savemail.c,v 8.314 2009/12/18 17:08:01 ca Exp $")
17 
18 static bool	errbody __P((MCI *, ENVELOPE *, char *));
19 static bool	pruneroute __P((char *));
20 
21 /*
22 **  SAVEMAIL -- Save mail on error
23 **
24 **	If mailing back errors, mail it back to the originator
25 **	together with an error message; otherwise, just put it in
26 **	dead.letter in the user's home directory (if he exists on
27 **	this machine).
28 **
29 **	Parameters:
30 **		e -- the envelope containing the message in error.
31 **		sendbody -- if true, also send back the body of the
32 **			message; otherwise just send the header.
33 **
34 **	Returns:
35 **		true if savemail panic'ed, (i.e., the data file should
36 **		be preserved by dropenvelope())
37 **
38 **	Side Effects:
39 **		Saves the letter, by writing or mailing it back to the
40 **		sender, or by putting it in dead.letter in her home
41 **		directory.
42 */
43 
44 /* defines for state machine */
45 #define ESM_REPORT		0	/* report to sender's terminal */
46 #define ESM_MAIL		1	/* mail back to sender */
47 #define ESM_QUIET		2	/* mail has already been returned */
48 #define ESM_DEADLETTER		3	/* save in ~/dead.letter */
49 #define ESM_POSTMASTER		4	/* return to postmaster */
50 #define ESM_DEADLETTERDROP	5	/* save in DeadLetterDrop */
51 #define ESM_PANIC		6	/* call loseqfile() */
52 #define ESM_DONE		7	/* message is successfully delivered */
53 
54 bool
55 savemail(e, sendbody)
56 	register ENVELOPE *e;
57 	bool sendbody;
58 {
59 	register SM_FILE_T *fp;
60 	bool panic = false;
61 	int state;
62 	auto ADDRESS *q = NULL;
63 	register char *p;
64 	MCI mcibuf;
65 	int flags;
66 	long sff;
67 	char buf[MAXLINE + 1];
68 	char dlbuf[MAXPATHLEN];
69 	SM_MBDB_T user;
70 
71 
72 	if (tTd(6, 1))
73 	{
74 		sm_dprintf("\nsavemail, errormode = %c, id = %s, ExitStat = %d\n  e_from=",
75 			e->e_errormode, e->e_id == NULL ? "NONE" : e->e_id,
76 			ExitStat);
77 		printaddr(sm_debug_file(), &e->e_from, false);
78 	}
79 
80 	if (e->e_id == NULL)
81 	{
82 		/* can't return a message with no id */
83 		return panic;
84 	}
85 
86 	/*
87 	**  In the unhappy event we don't know who to return the mail
88 	**  to, make someone up.
89 	*/
90 
91 	if (e->e_from.q_paddr == NULL)
92 	{
93 		e->e_sender = "Postmaster";
94 		if (parseaddr(e->e_sender, &e->e_from,
95 			      RF_COPYPARSE|RF_SENDERADDR,
96 			      '\0', NULL, e, false) == NULL)
97 		{
98 			syserr("553 5.3.5 Cannot parse Postmaster!");
99 			finis(true, true, EX_SOFTWARE);
100 		}
101 	}
102 	e->e_to = NULL;
103 
104 	/*
105 	**  Basic state machine.
106 	**
107 	**	This machine runs through the following states:
108 	**
109 	**	ESM_QUIET	Errors have already been printed iff the
110 	**			sender is local.
111 	**	ESM_REPORT	Report directly to the sender's terminal.
112 	**	ESM_MAIL	Mail response to the sender.
113 	**	ESM_DEADLETTER	Save response in ~/dead.letter.
114 	**	ESM_POSTMASTER	Mail response to the postmaster.
115 	**	ESM_DEADLETTERDROP
116 	**			If DeadLetterDrop set, save it there.
117 	**	ESM_PANIC	Save response anywhere possible.
118 	*/
119 
120 	/* determine starting state */
121 	switch (e->e_errormode)
122 	{
123 	  case EM_WRITE:
124 		state = ESM_REPORT;
125 		break;
126 
127 	  case EM_BERKNET:
128 	  case EM_MAIL:
129 		state = ESM_MAIL;
130 		break;
131 
132 	  case EM_PRINT:
133 	  case '\0':
134 		state = ESM_QUIET;
135 		break;
136 
137 	  case EM_QUIET:
138 		/* no need to return anything at all */
139 		return panic;
140 
141 	  default:
142 		syserr("554 5.3.0 savemail: bogus errormode x%x",
143 		       e->e_errormode);
144 		state = ESM_MAIL;
145 		break;
146 	}
147 
148 	/* if this is already an error response, send to postmaster */
149 	if (bitset(EF_RESPONSE, e->e_flags))
150 	{
151 		if (e->e_parent != NULL &&
152 		    bitset(EF_RESPONSE, e->e_parent->e_flags))
153 		{
154 			/* got an error sending a response -- can it */
155 			return panic;
156 		}
157 		state = ESM_POSTMASTER;
158 	}
159 
160 	while (state != ESM_DONE)
161 	{
162 		if (tTd(6, 5))
163 			sm_dprintf("  state %d\n", state);
164 
165 		switch (state)
166 		{
167 		  case ESM_QUIET:
168 			if (bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags))
169 				state = ESM_DEADLETTER;
170 			else
171 				state = ESM_MAIL;
172 			break;
173 
174 		  case ESM_REPORT:
175 
176 			/*
177 			**  If the user is still logged in on the same terminal,
178 			**  then write the error messages back to hir (sic).
179 			*/
180 
181 #if USE_TTYPATH
182 			p = ttypath();
183 #else /* USE_TTYPATH */
184 			p = NULL;
185 #endif /* USE_TTYPATH */
186 
187 			if (p == NULL || sm_io_reopen(SmFtStdio,
188 						      SM_TIME_DEFAULT,
189 						      p, SM_IO_WRONLY, NULL,
190 						      smioout) == NULL)
191 			{
192 				state = ESM_MAIL;
193 				break;
194 			}
195 
196 			expand("\201n", buf, sizeof(buf), e);
197 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
198 					     "\r\nMessage from %s...\r\n", buf);
199 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
200 					     "Errors occurred while sending mail.\r\n");
201 			if (e->e_xfp != NULL)
202 			{
203 				(void) bfrewind(e->e_xfp);
204 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
205 						     "Transcript follows:\r\n");
206 				while (sm_io_fgets(e->e_xfp, SM_TIME_DEFAULT,
207 						   buf, sizeof(buf)) != NULL &&
208 				       !sm_io_error(smioout))
209 					(void) sm_io_fputs(smioout,
210 							   SM_TIME_DEFAULT,
211 							   buf);
212 			}
213 			else
214 			{
215 				syserr("Cannot open %s",
216 				       queuename(e, XSCRPT_LETTER));
217 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
218 						     "Transcript of session is unavailable.\r\n");
219 			}
220 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
221 					     "Original message will be saved in dead.letter.\r\n");
222 			state = ESM_DEADLETTER;
223 			break;
224 
225 		  case ESM_MAIL:
226 			/*
227 			**  If mailing back, do it.
228 			**	Throw away all further output.  Don't alias,
229 			**	since this could cause loops, e.g., if joe
230 			**	mails to joe@x, and for some reason the network
231 			**	for @x is down, then the response gets sent to
232 			**	joe@x, which gives a response, etc.  Also force
233 			**	the mail to be delivered even if a version of
234 			**	it has already been sent to the sender.
235 			**
236 			**  If this is a configuration or local software
237 			**	error, send to the local postmaster as well,
238 			**	since the originator can't do anything
239 			**	about it anyway.  Note that this is a full
240 			**	copy of the message (intentionally) so that
241 			**	the Postmaster can forward things along.
242 			*/
243 
244 			if (ExitStat == EX_CONFIG || ExitStat == EX_SOFTWARE)
245 			{
246 				(void) sendtolist("postmaster", NULLADDR,
247 						  &e->e_errorqueue, 0, e);
248 			}
249 			if (!emptyaddr(&e->e_from))
250 			{
251 				char from[TOBUFSIZE];
252 
253 				if (sm_strlcpy(from, e->e_from.q_paddr,
254 						sizeof(from)) >= sizeof(from))
255 				{
256 					state = ESM_POSTMASTER;
257 					break;
258 				}
259 
260 				if (!DontPruneRoutes)
261 					(void) pruneroute(from);
262 
263 				(void) sendtolist(from, NULLADDR,
264 						  &e->e_errorqueue, 0, e);
265 			}
266 
267 			/*
268 			**  Deliver a non-delivery report to the
269 			**  Postmaster-designate (not necessarily
270 			**  Postmaster).  This does not include the
271 			**  body of the message, for privacy reasons.
272 			**  You really shouldn't need this.
273 			*/
274 
275 			e->e_flags |= EF_PM_NOTIFY;
276 
277 			/* check to see if there are any good addresses */
278 			for (q = e->e_errorqueue; q != NULL; q = q->q_next)
279 			{
280 				if (QS_IS_SENDABLE(q->q_state))
281 					break;
282 			}
283 			if (q == NULL)
284 			{
285 				/* this is an error-error */
286 				state = ESM_POSTMASTER;
287 				break;
288 			}
289 			if (returntosender(e->e_message, e->e_errorqueue,
290 					   sendbody ? RTSF_SEND_BODY
291 						    : RTSF_NO_BODY,
292 					   e) == 0)
293 			{
294 				state = ESM_DONE;
295 				break;
296 			}
297 
298 			/* didn't work -- return to postmaster */
299 			state = ESM_POSTMASTER;
300 			break;
301 
302 		  case ESM_POSTMASTER:
303 			/*
304 			**  Similar to previous case, but to system postmaster.
305 			*/
306 
307 			q = NULL;
308 			expand(DoubleBounceAddr, buf, sizeof(buf), e);
309 
310 			/*
311 			**  Just drop it on the floor if DoubleBounceAddr
312 			**  expands to an empty string.
313 			*/
314 
315 			if (*buf == '\0')
316 			{
317 				state = ESM_DONE;
318 				break;
319 			}
320 			if (sendtolist(buf, NULLADDR, &q, 0, e) <= 0)
321 			{
322 				syserr("553 5.3.0 cannot parse %s!", buf);
323 				ExitStat = EX_SOFTWARE;
324 				state = ESM_DEADLETTERDROP;
325 				break;
326 			}
327 			flags = RTSF_PM_BOUNCE;
328 			if (sendbody)
329 				flags |= RTSF_SEND_BODY;
330 			if (returntosender(e->e_message, q, flags, e) == 0)
331 			{
332 				state = ESM_DONE;
333 				break;
334 			}
335 
336 			/* didn't work -- last resort */
337 			state = ESM_DEADLETTERDROP;
338 			break;
339 
340 		  case ESM_DEADLETTER:
341 			/*
342 			**  Save the message in dead.letter.
343 			**	If we weren't mailing back, and the user is
344 			**	local, we should save the message in
345 			**	~/dead.letter so that the poor person doesn't
346 			**	have to type it over again -- and we all know
347 			**	what poor typists UNIX users are.
348 			*/
349 
350 			p = NULL;
351 			if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
352 			{
353 				if (e->e_from.q_home != NULL)
354 					p = e->e_from.q_home;
355 				else if (sm_mbdb_lookup(e->e_from.q_user, &user)
356 					 == EX_OK &&
357 					 *user.mbdb_homedir != '\0')
358 					p = user.mbdb_homedir;
359 			}
360 			if (p == NULL || e->e_dfp == NULL)
361 			{
362 				/* no local directory or no data file */
363 				state = ESM_MAIL;
364 				break;
365 			}
366 
367 			/* we have a home directory; write dead.letter */
368 			macdefine(&e->e_macro, A_TEMP, 'z', p);
369 
370 			/* get the sender for the UnixFromLine */
371 			p = macvalue('g', e);
372 			macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
373 
374 			expand("\201z/dead.letter", dlbuf, sizeof(dlbuf), e);
375 			sff = SFF_CREAT|SFF_REGONLY|SFF_RUNASREALUID;
376 			if (RealUid == 0)
377 				sff |= SFF_ROOTOK;
378 			e->e_to = dlbuf;
379 			if (writable(dlbuf, NULL, sff) &&
380 			    mailfile(dlbuf, FileMailer, NULL, sff, e) == EX_OK)
381 			{
382 				int oldverb = Verbose;
383 
384 				if (OpMode != MD_DAEMON && OpMode != MD_SMTP)
385 					Verbose = 1;
386 				if (Verbose > 0)
387 					message("Saved message in %s", dlbuf);
388 				Verbose = oldverb;
389 				macdefine(&e->e_macro, A_PERM, 'g', p);
390 				state = ESM_DONE;
391 				break;
392 			}
393 			macdefine(&e->e_macro, A_PERM, 'g', p);
394 			state = ESM_MAIL;
395 			break;
396 
397 		  case ESM_DEADLETTERDROP:
398 			/*
399 			**  Log the mail in DeadLetterDrop file.
400 			*/
401 
402 			if (e->e_class < 0)
403 			{
404 				state = ESM_DONE;
405 				break;
406 			}
407 
408 			if ((SafeFileEnv != NULL && SafeFileEnv[0] != '\0') ||
409 			    DeadLetterDrop == NULL ||
410 			    DeadLetterDrop[0] == '\0')
411 			{
412 				state = ESM_PANIC;
413 				break;
414 			}
415 
416 			sff = SFF_CREAT|SFF_REGONLY|SFF_ROOTOK|SFF_OPENASROOT|SFF_MUSTOWN;
417 			if (!writable(DeadLetterDrop, NULL, sff) ||
418 			    (fp = safefopen(DeadLetterDrop, O_WRONLY|O_APPEND,
419 					    FileMode, sff)) == NULL)
420 			{
421 				state = ESM_PANIC;
422 				break;
423 			}
424 
425 			memset(&mcibuf, '\0', sizeof(mcibuf));
426 			mcibuf.mci_out = fp;
427 			mcibuf.mci_mailer = FileMailer;
428 			if (bitnset(M_7BITS, FileMailer->m_flags))
429 				mcibuf.mci_flags |= MCIF_7BIT;
430 
431 			/* get the sender for the UnixFromLine */
432 			p = macvalue('g', e);
433 			macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
434 
435 			if (!putfromline(&mcibuf, e) ||
436 			    !(*e->e_puthdr)(&mcibuf, e->e_header, e,
437 					M87F_OUTER) ||
438 			    !(*e->e_putbody)(&mcibuf, e, NULL) ||
439 			    !putline("\n", &mcibuf) ||
440 			    sm_io_flush(fp, SM_TIME_DEFAULT) == SM_IO_EOF ||
441 			    sm_io_error(fp) ||
442 			    sm_io_close(fp, SM_TIME_DEFAULT) < 0)
443 				state = ESM_PANIC;
444 			else
445 			{
446 				int oldverb = Verbose;
447 
448 				if (OpMode != MD_DAEMON && OpMode != MD_SMTP)
449 					Verbose = 1;
450 				if (Verbose > 0)
451 					message("Saved message in %s",
452 						DeadLetterDrop);
453 				Verbose = oldverb;
454 				if (LogLevel > 3)
455 					sm_syslog(LOG_NOTICE, e->e_id,
456 						  "Saved message in %s",
457 						  DeadLetterDrop);
458 				state = ESM_DONE;
459 			}
460 			macdefine(&e->e_macro, A_PERM, 'g', p);
461 			break;
462 
463 		  default:
464 			syserr("554 5.3.5 savemail: unknown state %d", state);
465 			/* FALLTHROUGH */
466 
467 		  case ESM_PANIC:
468 			/* leave the locked queue & transcript files around */
469 			loseqfile(e, "savemail panic");
470 			panic = true;
471 			errno = 0;
472 			syserr("554 savemail: cannot save rejected email anywhere");
473 			state = ESM_DONE;
474 			break;
475 		}
476 	}
477 	return panic;
478 }
479 /*
480 **  RETURNTOSENDER -- return a message to the sender with an error.
481 **
482 **	Parameters:
483 **		msg -- the explanatory message.
484 **		returnq -- the queue of people to send the message to.
485 **		flags -- flags tweaking the operation:
486 **			RTSF_SENDBODY -- include body of message (otherwise
487 **				just send the header).
488 **			RTSF_PMBOUNCE -- this is a postmaster bounce.
489 **		e -- the current envelope.
490 **
491 **	Returns:
492 **		zero -- if everything went ok.
493 **		else -- some error.
494 **
495 **	Side Effects:
496 **		Returns the current message to the sender via mail.
497 */
498 
499 #define MAXRETURNS	6	/* max depth of returning messages */
500 #define ERRORFUDGE	1024	/* nominal size of error message text */
501 
502 int
503 returntosender(msg, returnq, flags, e)
504 	char *msg;
505 	ADDRESS *returnq;
506 	int flags;
507 	register ENVELOPE *e;
508 {
509 	register ENVELOPE *ee;
510 	ENVELOPE *oldcur = CurEnv;
511 	ENVELOPE errenvelope;
512 	static int returndepth = 0;
513 	register ADDRESS *q;
514 	char *p;
515 	char buf[MAXNAME + 1];
516 
517 	if (returnq == NULL)
518 		return -1;
519 
520 	if (msg == NULL)
521 		msg = "Unable to deliver mail";
522 
523 	if (tTd(6, 1))
524 	{
525 		sm_dprintf("\n*** Return To Sender: msg=\"%s\", depth=%d, e=%p, returnq=",
526 			msg, returndepth, e);
527 		printaddr(sm_debug_file(), returnq, true);
528 		if (tTd(6, 20))
529 		{
530 			sm_dprintf("Sendq=");
531 			printaddr(sm_debug_file(), e->e_sendqueue, true);
532 		}
533 	}
534 
535 	if (++returndepth >= MAXRETURNS)
536 	{
537 		if (returndepth != MAXRETURNS)
538 			syserr("554 5.3.0 returntosender: infinite recursion on %s",
539 			       returnq->q_paddr);
540 		/* don't "unrecurse" and fake a clean exit */
541 		/* returndepth--; */
542 		return 0;
543 	}
544 
545 	macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
546 	macdefine(&e->e_macro, A_PERM, 'u', NULL);
547 
548 	/* initialize error envelope */
549 	ee = newenvelope(&errenvelope, e, sm_rpool_new_x(NULL));
550 	macdefine(&ee->e_macro, A_PERM, 'a', "\201b");
551 	macdefine(&ee->e_macro, A_PERM, 'r', "");
552 	macdefine(&ee->e_macro, A_PERM, 's', "localhost");
553 	macdefine(&ee->e_macro, A_PERM, '_', "localhost");
554 	clrsessenvelope(ee);
555 
556 	ee->e_puthdr = putheader;
557 	ee->e_putbody = errbody;
558 	ee->e_flags |= EF_RESPONSE|EF_METOO;
559 	if (!bitset(EF_OLDSTYLE, e->e_flags))
560 		ee->e_flags &= ~EF_OLDSTYLE;
561 	if (bitset(EF_DONT_MIME, e->e_flags))
562 	{
563 		ee->e_flags |= EF_DONT_MIME;
564 
565 		/*
566 		**  If we can't convert to MIME and we don't pass
567 		**  8-bit, we can't send the body.
568 		*/
569 
570 		if (bitset(EF_HAS8BIT, e->e_flags) &&
571 		    !bitset(MM_PASS8BIT, MimeMode))
572 			flags &= ~RTSF_SEND_BODY;
573 	}
574 
575 	ee->e_sendqueue = returnq;
576 	ee->e_msgsize = 0;
577 	if (bitset(RTSF_SEND_BODY, flags) &&
578 	    !bitset(PRIV_NOBODYRETN, PrivacyFlags))
579 		ee->e_msgsize = ERRORFUDGE + e->e_msgsize;
580 	else
581 		ee->e_flags |= EF_NO_BODY_RETN;
582 
583 	if (!setnewqueue(ee))
584 	{
585 		syserr("554 5.3.0 returntosender: cannot select queue for %s",
586 			       returnq->q_paddr);
587 		ExitStat = EX_UNAVAILABLE;
588 		returndepth--;
589 		return -1;
590 	}
591 	initsys(ee);
592 
593 #if NAMED_BIND
594 	_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
595 	_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
596 #endif /* NAMED_BIND */
597 	for (q = returnq; q != NULL; q = q->q_next)
598 	{
599 		if (QS_IS_BADADDR(q->q_state))
600 			continue;
601 
602 		q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
603 		q->q_flags |= QPINGONFAILURE;
604 
605 		if (!QS_IS_DEAD(q->q_state))
606 			ee->e_nrcpts++;
607 
608 		if (q->q_alias == NULL)
609 			addheader("To", q->q_paddr, 0, ee, true);
610 	}
611 
612 	if (LogLevel > 5)
613 	{
614 		if (bitset(EF_RESPONSE, e->e_flags))
615 			p = "return to sender";
616 		else if (bitset(EF_WARNING, e->e_flags))
617 			p = "sender notify";
618 		else if (bitset(RTSF_PM_BOUNCE, flags))
619 			p = "postmaster notify";
620 		else
621 			p = "DSN";
622 		sm_syslog(LOG_INFO, e->e_id, "%s: %s: %s",
623 			  ee->e_id, p, shortenstring(msg, MAXSHORTSTR));
624 	}
625 
626 	if (SendMIMEErrors)
627 	{
628 		addheader("MIME-Version", "1.0", 0, ee, true);
629 		(void) sm_snprintf(buf, sizeof(buf), "%s.%ld/%.100s",
630 				ee->e_id, (long)curtime(), MyHostName);
631 		ee->e_msgboundary = sm_rpool_strdup_x(ee->e_rpool, buf);
632 		(void) sm_snprintf(buf, sizeof(buf),
633 #if DSN
634 				"multipart/report; report-type=delivery-status;\n\tboundary=\"%s\"",
635 #else /* DSN */
636 				"multipart/mixed; boundary=\"%s\"",
637 #endif /* DSN */
638 				ee->e_msgboundary);
639 		addheader("Content-Type", buf, 0, ee, true);
640 
641 		p = hvalue("Content-Transfer-Encoding", e->e_header);
642 		if (p != NULL && sm_strcasecmp(p, "binary") != 0)
643 			p = NULL;
644 		if (p == NULL && bitset(EF_HAS8BIT, e->e_flags))
645 			p = "8bit";
646 		if (p != NULL)
647 			addheader("Content-Transfer-Encoding", p, 0, ee, true);
648 	}
649 	if (strncmp(msg, "Warning:", 8) == 0)
650 	{
651 		addheader("Subject", msg, 0, ee, true);
652 		p = "warning-timeout";
653 	}
654 	else if (strncmp(msg, "Postmaster warning:", 19) == 0)
655 	{
656 		addheader("Subject", msg, 0, ee, true);
657 		p = "postmaster-warning";
658 	}
659 	else if (strcmp(msg, "Return receipt") == 0)
660 	{
661 		addheader("Subject", msg, 0, ee, true);
662 		p = "return-receipt";
663 	}
664 	else if (bitset(RTSF_PM_BOUNCE, flags))
665 	{
666 		(void) sm_snprintf(buf, sizeof(buf),
667 			 "Postmaster notify: see transcript for details");
668 		addheader("Subject", buf, 0, ee, true);
669 		p = "postmaster-notification";
670 	}
671 	else
672 	{
673 		(void) sm_snprintf(buf, sizeof(buf),
674 			 "Returned mail: see transcript for details");
675 		addheader("Subject", buf, 0, ee, true);
676 		p = "failure";
677 	}
678 	(void) sm_snprintf(buf, sizeof(buf), "auto-generated (%s)", p);
679 	addheader("Auto-Submitted", buf, 0, ee, true);
680 
681 	/* fake up an address header for the from person */
682 	expand("\201n", buf, sizeof(buf), e);
683 	if (parseaddr(buf, &ee->e_from,
684 		      RF_COPYALL|RF_SENDERADDR, '\0', NULL, e, false) == NULL)
685 	{
686 		syserr("553 5.3.5 Can't parse myself!");
687 		ExitStat = EX_SOFTWARE;
688 		returndepth--;
689 		return -1;
690 	}
691 	ee->e_from.q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
692 	ee->e_from.q_flags |= QPINGONFAILURE;
693 	ee->e_sender = ee->e_from.q_paddr;
694 
695 	/* push state into submessage */
696 	CurEnv = ee;
697 	macdefine(&ee->e_macro, A_PERM, 'f', "\201n");
698 	macdefine(&ee->e_macro, A_PERM, 'x', "Mail Delivery Subsystem");
699 	eatheader(ee, true, true);
700 
701 	/* mark statistics */
702 	markstats(ee, NULLADDR, STATS_NORMAL);
703 
704 	/* actually deliver the error message */
705 	sendall(ee, SM_DELIVER);
706 
707 	/* restore state */
708 	(void) dropenvelope(ee, true, false);
709 	sm_rpool_free(ee->e_rpool);
710 	CurEnv = oldcur;
711 	returndepth--;
712 
713 	/* check for delivery errors */
714 	if (ee->e_parent == NULL ||
715 	    !bitset(EF_RESPONSE, ee->e_parent->e_flags))
716 		return 0;
717 	for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
718 	{
719 		if (QS_IS_ATTEMPTED(q->q_state))
720 			return 0;
721 	}
722 	return -1;
723 }
724 /*
725 **  ERRBODY -- output the body of an error message.
726 **
727 **	Typically this is a copy of the transcript plus a copy of the
728 **	original offending message.
729 **
730 **	Parameters:
731 **		mci -- the mailer connection information.
732 **		e -- the envelope we are working in.
733 **		separator -- any possible MIME separator (unused).
734 **
735 **	Returns:
736 **		true iff body was written successfully
737 **
738 **	Side Effects:
739 **		Outputs the body of an error message.
740 */
741 
742 /* ARGSUSED2 */
743 static bool
744 errbody(mci, e, separator)
745 	register MCI *mci;
746 	register ENVELOPE *e;
747 	char *separator;
748 {
749 	bool printheader;
750 	bool sendbody;
751 	bool pm_notify;
752 	int save_errno;
753 	register SM_FILE_T *xfile;
754 	char *p;
755 	register ADDRESS *q = NULL;
756 	char actual[MAXLINE];
757 	char buf[MAXLINE];
758 
759 	if (bitset(MCIF_INHEADER, mci->mci_flags))
760 	{
761 		if (!putline("", mci))
762 			goto writeerr;
763 		mci->mci_flags &= ~MCIF_INHEADER;
764 	}
765 	if (e->e_parent == NULL)
766 	{
767 		syserr("errbody: null parent");
768 		if (!putline("   ----- Original message lost -----\n", mci))
769 			goto writeerr;
770 		return true;
771 	}
772 
773 	/*
774 	**  Output MIME header.
775 	*/
776 
777 	if (e->e_msgboundary != NULL)
778 	{
779 		(void) sm_strlcpyn(buf, sizeof(buf), 2, "--", e->e_msgboundary);
780 		if (!putline("This is a MIME-encapsulated message", mci) ||
781 		    !putline("", mci) ||
782 		    !putline(buf, mci) ||
783 		    !putline("", mci))
784 			goto writeerr;
785 	}
786 
787 	/*
788 	**  Output introductory information.
789 	*/
790 
791 	pm_notify = false;
792 	p = hvalue("subject", e->e_header);
793 	if (p != NULL && strncmp(p, "Postmaster ", 11) == 0)
794 		pm_notify = true;
795 	else
796 	{
797 		for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
798 		{
799 			if (QS_IS_BADADDR(q->q_state))
800 				break;
801 		}
802 	}
803 	if (!pm_notify && q == NULL &&
804 	    !bitset(EF_FATALERRS|EF_SENDRECEIPT, e->e_parent->e_flags))
805 	{
806 		if (!putline("    **********************************************",
807 			mci) ||
808 		    !putline("    **      THIS IS A WARNING MESSAGE ONLY      **",
809 			mci) ||
810 		    !putline("    **  YOU DO NOT NEED TO RESEND YOUR MESSAGE  **",
811 			mci) ||
812 		    !putline("    **********************************************",
813 			mci) ||
814 		    !putline("", mci))
815 			goto writeerr;
816 	}
817 	(void) sm_snprintf(buf, sizeof(buf),
818 		"The original message was received at %s",
819 		arpadate(ctime(&e->e_parent->e_ctime)));
820 	if (!putline(buf, mci))
821 		goto writeerr;
822 	expand("from \201_", buf, sizeof(buf), e->e_parent);
823 	if (!putline(buf, mci))
824 		goto writeerr;
825 
826 	/* include id in postmaster copies */
827 	if (pm_notify && e->e_parent->e_id != NULL)
828 	{
829 		(void) sm_strlcpyn(buf, sizeof(buf), 2, "with id ",
830 			e->e_parent->e_id);
831 		if (!putline(buf, mci))
832 			goto writeerr;
833 	}
834 	if (!putline("", mci))
835 		goto writeerr;
836 
837 	/*
838 	**  Output error message header (if specified and available).
839 	*/
840 
841 	if (ErrMsgFile != NULL &&
842 	    !bitset(EF_SENDRECEIPT, e->e_parent->e_flags))
843 	{
844 		if (*ErrMsgFile == '/')
845 		{
846 			long sff = SFF_ROOTOK|SFF_REGONLY;
847 
848 			if (DontLockReadFiles)
849 				sff |= SFF_NOLOCK;
850 			if (!bitnset(DBS_ERRORHEADERINUNSAFEDIRPATH,
851 				     DontBlameSendmail))
852 				sff |= SFF_SAFEDIRPATH;
853 			xfile = safefopen(ErrMsgFile, O_RDONLY, 0444, sff);
854 			if (xfile != NULL)
855 			{
856 				while (sm_io_fgets(xfile, SM_TIME_DEFAULT, buf,
857 						   sizeof(buf)) != NULL)
858 				{
859 					int lbs;
860 					bool putok;
861 					char *lbp;
862 
863 					lbs = sizeof(buf);
864 					lbp = translate_dollars(buf, buf, &lbs);
865 					expand(lbp, lbp, lbs, e);
866 					putok = putline(lbp, mci);
867 					if (lbp != buf)
868 						sm_free(lbp);
869 					if (!putok)
870 						goto writeerr;
871 				}
872 				(void) sm_io_close(xfile, SM_TIME_DEFAULT);
873 				if (!putline("\n", mci))
874 					goto writeerr;
875 			}
876 		}
877 		else
878 		{
879 			expand(ErrMsgFile, buf, sizeof(buf), e);
880 			if (!putline(buf, mci) || !putline("", mci))
881 				goto writeerr;
882 		}
883 	}
884 
885 	/*
886 	**  Output message introduction
887 	*/
888 
889 	/* permanent fatal errors */
890 	printheader = true;
891 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
892 	{
893 		if (!QS_IS_BADADDR(q->q_state) ||
894 		    !bitset(QPINGONFAILURE, q->q_flags))
895 			continue;
896 
897 		if (printheader)
898 		{
899 			if (!putline("   ----- The following addresses had permanent fatal errors -----",
900 					mci))
901 				goto writeerr;
902 			printheader = false;
903 		}
904 
905 		(void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR),
906 				  sizeof(buf));
907 		if (!putline(buf, mci))
908 			goto writeerr;
909 		if (q->q_rstatus != NULL)
910 		{
911 			(void) sm_snprintf(buf, sizeof(buf),
912 				"    (reason: %s)",
913 				shortenstring(exitstat(q->q_rstatus),
914 					      MAXSHORTSTR));
915 			if (!putline(buf, mci))
916 				goto writeerr;
917 		}
918 		if (q->q_alias != NULL)
919 		{
920 			(void) sm_snprintf(buf, sizeof(buf),
921 				"    (expanded from: %s)",
922 				shortenstring(q->q_alias->q_paddr,
923 					      MAXSHORTSTR));
924 			if (!putline(buf, mci))
925 				goto writeerr;
926 		}
927 	}
928 	if (!printheader && !putline("", mci))
929 		goto writeerr;
930 
931 	/* transient non-fatal errors */
932 	printheader = true;
933 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
934 	{
935 		if (QS_IS_BADADDR(q->q_state) ||
936 		    !bitset(QPRIMARY, q->q_flags) ||
937 		    !bitset(QBYNDELAY, q->q_flags) ||
938 		    !bitset(QDELAYED, q->q_flags))
939 			continue;
940 
941 		if (printheader)
942 		{
943 			if (!putline("   ----- The following addresses had transient non-fatal errors -----",
944 					mci))
945 				goto writeerr;
946 			printheader = false;
947 		}
948 
949 		(void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR),
950 				  sizeof(buf));
951 		if (!putline(buf, mci))
952 			goto writeerr;
953 		if (q->q_alias != NULL)
954 		{
955 			(void) sm_snprintf(buf, sizeof(buf),
956 				"    (expanded from: %s)",
957 				shortenstring(q->q_alias->q_paddr,
958 					      MAXSHORTSTR));
959 			if (!putline(buf, mci))
960 				goto writeerr;
961 		}
962 	}
963 	if (!printheader && !putline("", mci))
964 		goto writeerr;
965 
966 	/* successful delivery notifications */
967 	printheader = true;
968 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
969 	{
970 		if (QS_IS_BADADDR(q->q_state) ||
971 		    !bitset(QPRIMARY, q->q_flags) ||
972 		    bitset(QBYNDELAY, q->q_flags) ||
973 		    bitset(QDELAYED, q->q_flags))
974 			continue;
975 		else if (bitset(QBYNRELAY, q->q_flags))
976 			p = "Deliver-By notify: relayed";
977 		else if (bitset(QBYTRACE, q->q_flags))
978 			p = "Deliver-By trace: relayed";
979 		else if (!bitset(QPINGONSUCCESS, q->q_flags))
980 			continue;
981 		else if (bitset(QRELAYED, q->q_flags))
982 			p = "relayed to non-DSN-aware mailer";
983 		else if (bitset(QDELIVERED, q->q_flags))
984 		{
985 			if (bitset(QEXPANDED, q->q_flags))
986 				p = "successfully delivered to mailing list";
987 			else
988 				p = "successfully delivered to mailbox";
989 		}
990 		else if (bitset(QEXPANDED, q->q_flags))
991 			p = "expanded by alias";
992 		else
993 			continue;
994 
995 		if (printheader)
996 		{
997 			if (!putline("   ----- The following addresses had successful delivery notifications -----",
998 					mci))
999 				goto writeerr;
1000 			printheader = false;
1001 		}
1002 
1003 		(void) sm_snprintf(buf, sizeof(buf), "%s  (%s)",
1004 			 shortenstring(q->q_paddr, MAXSHORTSTR), p);
1005 		if (!putline(buf, mci))
1006 			goto writeerr;
1007 		if (q->q_alias != NULL)
1008 		{
1009 			(void) sm_snprintf(buf, sizeof(buf),
1010 				"    (expanded from: %s)",
1011 				shortenstring(q->q_alias->q_paddr,
1012 					      MAXSHORTSTR));
1013 			if (!putline(buf, mci))
1014 				goto writeerr;
1015 		}
1016 	}
1017 	if (!printheader && !putline("", mci))
1018 		goto writeerr;
1019 
1020 	/*
1021 	**  Output transcript of errors
1022 	*/
1023 
1024 	(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1025 	if (e->e_parent->e_xfp == NULL)
1026 	{
1027 		if (!putline("   ----- Transcript of session is unavailable -----\n",
1028 				mci))
1029 			goto writeerr;
1030 	}
1031 	else
1032 	{
1033 		printheader = true;
1034 		(void) bfrewind(e->e_parent->e_xfp);
1035 		if (e->e_xfp != NULL)
1036 			(void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
1037 		while (sm_io_fgets(e->e_parent->e_xfp, SM_TIME_DEFAULT, buf,
1038 				   sizeof(buf)) != NULL)
1039 		{
1040 			if (printheader && !putline("   ----- Transcript of session follows -----\n",
1041 						mci))
1042 				goto writeerr;
1043 			printheader = false;
1044 			if (!putline(buf, mci))
1045 				goto writeerr;
1046 		}
1047 	}
1048 	errno = 0;
1049 
1050 #if DSN
1051 	/*
1052 	**  Output machine-readable version.
1053 	*/
1054 
1055 	if (e->e_msgboundary != NULL)
1056 	{
1057 		(void) sm_strlcpyn(buf, sizeof(buf), 2, "--", e->e_msgboundary);
1058 		if (!putline("", mci) ||
1059 		    !putline(buf, mci) ||
1060 		    !putline("Content-Type: message/delivery-status", mci) ||
1061 		    !putline("", mci))
1062 			goto writeerr;
1063 
1064 		/*
1065 		**  Output per-message information.
1066 		*/
1067 
1068 		/* original envelope id from MAIL FROM: line */
1069 		if (e->e_parent->e_envid != NULL)
1070 		{
1071 			(void) sm_snprintf(buf, sizeof(buf),
1072 					"Original-Envelope-Id: %.800s",
1073 					xuntextify(e->e_parent->e_envid));
1074 			if (!putline(buf, mci))
1075 				goto writeerr;
1076 		}
1077 
1078 		/* Reporting-MTA: is us (required) */
1079 		(void) sm_snprintf(buf, sizeof(buf),
1080 				   "Reporting-MTA: dns; %.800s", MyHostName);
1081 		if (!putline(buf, mci))
1082 			goto writeerr;
1083 
1084 		/* DSN-Gateway: not relevant since we are not translating */
1085 
1086 		/* Received-From-MTA: shows where we got this message from */
1087 		if (RealHostName != NULL)
1088 		{
1089 			/* XXX use $s for type? */
1090 			if (e->e_parent->e_from.q_mailer == NULL ||
1091 			    (p = e->e_parent->e_from.q_mailer->m_mtatype) == NULL)
1092 				p = "dns";
1093 			(void) sm_snprintf(buf, sizeof(buf),
1094 					"Received-From-MTA: %s; %.800s",
1095 					p, RealHostName);
1096 			if (!putline(buf, mci))
1097 				goto writeerr;
1098 		}
1099 
1100 		/* Arrival-Date: -- when it arrived here */
1101 		(void) sm_strlcpyn(buf, sizeof(buf), 2, "Arrival-Date: ",
1102 				arpadate(ctime(&e->e_parent->e_ctime)));
1103 		if (!putline(buf, mci))
1104 			goto writeerr;
1105 
1106 		/* Deliver-By-Date: -- when it should have been delivered */
1107 		if (IS_DLVR_BY(e->e_parent))
1108 		{
1109 			time_t dbyd;
1110 
1111 			dbyd = e->e_parent->e_ctime + e->e_parent->e_deliver_by;
1112 			(void) sm_strlcpyn(buf, sizeof(buf), 2,
1113 					"Deliver-By-Date: ",
1114 					arpadate(ctime(&dbyd)));
1115 			if (!putline(buf, mci))
1116 				goto writeerr;
1117 		}
1118 
1119 		/*
1120 		**  Output per-address information.
1121 		*/
1122 
1123 		for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
1124 		{
1125 			char *action;
1126 
1127 			if (QS_IS_BADADDR(q->q_state))
1128 			{
1129 				/* RFC 1891, 6.2.6 (b) */
1130 				if (bitset(QHASNOTIFY, q->q_flags) &&
1131 				    !bitset(QPINGONFAILURE, q->q_flags))
1132 					continue;
1133 				action = "failed";
1134 			}
1135 			else if (!bitset(QPRIMARY, q->q_flags))
1136 				continue;
1137 			else if (bitset(QDELIVERED, q->q_flags))
1138 			{
1139 				if (bitset(QEXPANDED, q->q_flags))
1140 					action = "delivered (to mailing list)";
1141 				else
1142 					action = "delivered (to mailbox)";
1143 			}
1144 			else if (bitset(QRELAYED, q->q_flags))
1145 				action = "relayed (to non-DSN-aware mailer)";
1146 			else if (bitset(QEXPANDED, q->q_flags))
1147 				action = "expanded (to multi-recipient alias)";
1148 			else if (bitset(QDELAYED, q->q_flags))
1149 				action = "delayed";
1150 			else if (bitset(QBYTRACE, q->q_flags))
1151 				action = "relayed (Deliver-By trace mode)";
1152 			else if (bitset(QBYNDELAY, q->q_flags))
1153 				action = "delayed (Deliver-By notify mode)";
1154 			else if (bitset(QBYNRELAY, q->q_flags))
1155 				action = "relayed (Deliver-By notify mode)";
1156 			else
1157 				continue;
1158 
1159 			if (!putline("", mci))
1160 				goto writeerr;
1161 
1162 			/* Original-Recipient: -- passed from on high */
1163 			if (q->q_orcpt != NULL)
1164 			{
1165 				(void) sm_snprintf(buf, sizeof(buf),
1166 						"Original-Recipient: %.800s",
1167 						q->q_orcpt);
1168 				if (!putline(buf, mci))
1169 					goto writeerr;
1170 			}
1171 
1172 			/* Figure out actual recipient */
1173 			actual[0] = '\0';
1174 			if (q->q_user[0] != '\0')
1175 			{
1176 				if (q->q_mailer != NULL &&
1177 				    q->q_mailer->m_addrtype != NULL)
1178 					p = q->q_mailer->m_addrtype;
1179 				else
1180 					p = "rfc822";
1181 
1182 				if (sm_strcasecmp(p, "rfc822") == 0 &&
1183 				    strchr(q->q_user, '@') == NULL)
1184 				{
1185 					(void) sm_snprintf(actual,
1186 							   sizeof(actual),
1187 							   "%s; %.700s@%.100s",
1188 							   p, q->q_user,
1189 							   MyHostName);
1190 				}
1191 				else
1192 				{
1193 					(void) sm_snprintf(actual,
1194 							   sizeof(actual),
1195 							   "%s; %.800s",
1196 							   p, q->q_user);
1197 				}
1198 			}
1199 
1200 			/* Final-Recipient: -- the name from the RCPT command */
1201 			if (q->q_finalrcpt == NULL)
1202 			{
1203 				/* should never happen */
1204 				sm_syslog(LOG_ERR, e->e_id,
1205 					  "returntosender: q_finalrcpt is NULL");
1206 
1207 				/* try to fall back to the actual recipient */
1208 				if (actual[0] != '\0')
1209 					q->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool,
1210 									   actual);
1211 			}
1212 
1213 			if (q->q_finalrcpt != NULL)
1214 			{
1215 				(void) sm_snprintf(buf, sizeof(buf),
1216 						   "Final-Recipient: %s",
1217 						   q->q_finalrcpt);
1218 				if (!putline(buf, mci))
1219 					goto writeerr;
1220 			}
1221 
1222 			/* X-Actual-Recipient: -- the real problem address */
1223 			if (actual[0] != '\0' &&
1224 			    q->q_finalrcpt != NULL &&
1225 			    !bitset(PRIV_NOACTUALRECIPIENT, PrivacyFlags) &&
1226 			    strcmp(actual, q->q_finalrcpt) != 0)
1227 			{
1228 				(void) sm_snprintf(buf, sizeof(buf),
1229 						   "X-Actual-Recipient: %s",
1230 						   actual);
1231 				if (!putline(buf, mci))
1232 					goto writeerr;
1233 			}
1234 
1235 			/* Action: -- what happened? */
1236 			(void) sm_strlcpyn(buf, sizeof(buf), 2, "Action: ",
1237 				action);
1238 			if (!putline(buf, mci))
1239 				goto writeerr;
1240 
1241 			/* Status: -- what _really_ happened? */
1242 			if (q->q_status != NULL)
1243 				p = q->q_status;
1244 			else if (QS_IS_BADADDR(q->q_state))
1245 				p = "5.0.0";
1246 			else if (QS_IS_QUEUEUP(q->q_state))
1247 				p = "4.0.0";
1248 			else
1249 				p = "2.0.0";
1250 			(void) sm_strlcpyn(buf, sizeof(buf), 2, "Status: ", p);
1251 			if (!putline(buf, mci))
1252 				goto writeerr;
1253 
1254 			/* Remote-MTA: -- who was I talking to? */
1255 			if (q->q_statmta != NULL)
1256 			{
1257 				if (q->q_mailer == NULL ||
1258 				    (p = q->q_mailer->m_mtatype) == NULL)
1259 					p = "dns";
1260 				(void) sm_snprintf(buf, sizeof(buf),
1261 						"Remote-MTA: %s; %.800s",
1262 						p, q->q_statmta);
1263 				p = &buf[strlen(buf) - 1];
1264 				if (*p == '.')
1265 					*p = '\0';
1266 				if (!putline(buf, mci))
1267 					goto writeerr;
1268 			}
1269 
1270 			/* Diagnostic-Code: -- actual result from other end */
1271 			if (q->q_rstatus != NULL)
1272 			{
1273 				if (q->q_mailer == NULL ||
1274 				    (p = q->q_mailer->m_diagtype) == NULL)
1275 					p = "smtp";
1276 				(void) sm_snprintf(buf, sizeof(buf),
1277 						"Diagnostic-Code: %s; %.800s",
1278 						p, q->q_rstatus);
1279 				if (!putline(buf, mci))
1280 					goto writeerr;
1281 			}
1282 
1283 			/* Last-Attempt-Date: -- fine granularity */
1284 			if (q->q_statdate == (time_t) 0L)
1285 				q->q_statdate = curtime();
1286 			(void) sm_strlcpyn(buf, sizeof(buf), 2,
1287 					"Last-Attempt-Date: ",
1288 					arpadate(ctime(&q->q_statdate)));
1289 			if (!putline(buf, mci))
1290 				goto writeerr;
1291 
1292 			/* Will-Retry-Until: -- for delayed messages only */
1293 			if (QS_IS_QUEUEUP(q->q_state))
1294 			{
1295 				time_t xdate;
1296 
1297 				xdate = e->e_parent->e_ctime +
1298 					TimeOuts.to_q_return[e->e_parent->e_timeoutclass];
1299 				(void) sm_strlcpyn(buf, sizeof(buf), 2,
1300 					 "Will-Retry-Until: ",
1301 					 arpadate(ctime(&xdate)));
1302 				if (!putline(buf, mci))
1303 					goto writeerr;
1304 			}
1305 		}
1306 	}
1307 #endif /* DSN */
1308 
1309 	/*
1310 	**  Output text of original message
1311 	*/
1312 
1313 	if (!putline("", mci))
1314 		goto writeerr;
1315 	if (bitset(EF_HAS_DF, e->e_parent->e_flags))
1316 	{
1317 		sendbody = !bitset(EF_NO_BODY_RETN, e->e_parent->e_flags) &&
1318 			   !bitset(EF_NO_BODY_RETN, e->e_flags);
1319 
1320 		if (e->e_msgboundary == NULL)
1321 		{
1322 			if (!putline(
1323 				sendbody
1324 				? "   ----- Original message follows -----\n"
1325 				: "   ----- Message header follows -----\n",
1326 				mci))
1327 			{
1328 				goto writeerr;
1329 			}
1330 		}
1331 		else
1332 		{
1333 			(void) sm_strlcpyn(buf, sizeof(buf), 2, "--",
1334 					e->e_msgboundary);
1335 
1336 			if (!putline(buf, mci))
1337 				goto writeerr;
1338 			(void) sm_strlcpyn(buf, sizeof(buf), 2, "Content-Type: ",
1339 					sendbody ? "message/rfc822"
1340 						 : "text/rfc822-headers");
1341 			if (!putline(buf, mci))
1342 				goto writeerr;
1343 
1344 			p = hvalue("Content-Transfer-Encoding",
1345 				   e->e_parent->e_header);
1346 			if (p != NULL && sm_strcasecmp(p, "binary") != 0)
1347 				p = NULL;
1348 			if (p == NULL &&
1349 			    bitset(EF_HAS8BIT, e->e_parent->e_flags))
1350 				p = "8bit";
1351 			if (p != NULL)
1352 			{
1353 				(void) sm_snprintf(buf, sizeof(buf),
1354 						"Content-Transfer-Encoding: %s",
1355 						p);
1356 				if (!putline(buf, mci))
1357 					goto writeerr;
1358 			}
1359 		}
1360 		if (!putline("", mci))
1361 			goto writeerr;
1362 		save_errno = errno;
1363 		if (!putheader(mci, e->e_parent->e_header, e->e_parent,
1364 				M87F_OUTER))
1365 			goto writeerr;
1366 		errno = save_errno;
1367 		if (sendbody)
1368 		{
1369 			if (!putbody(mci, e->e_parent, e->e_msgboundary))
1370 				goto writeerr;
1371 		}
1372 		else if (e->e_msgboundary == NULL)
1373 		{
1374 			if (!putline("", mci) ||
1375 			    !putline("   ----- Message body suppressed -----",
1376 					mci))
1377 			{
1378 				goto writeerr;
1379 			}
1380 		}
1381 	}
1382 	else if (e->e_msgboundary == NULL)
1383 	{
1384 		if (!putline("  ----- No message was collected -----\n", mci))
1385 			goto writeerr;
1386 	}
1387 
1388 	if (e->e_msgboundary != NULL)
1389 	{
1390 		(void) sm_strlcpyn(buf, sizeof(buf), 3, "--", e->e_msgboundary,
1391 				   "--");
1392 		if (!putline("", mci) || !putline(buf, mci))
1393 			goto writeerr;
1394 	}
1395 	if (!putline("", mci) ||
1396 	    sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF)
1397 			goto writeerr;
1398 
1399 	/*
1400 	**  Cleanup and exit
1401 	*/
1402 
1403 	if (errno != 0)
1404 	{
1405   writeerr:
1406 		syserr("errbody: I/O error");
1407 		return false;
1408 	}
1409 	return true;
1410 }
1411 
1412 /*
1413 **  SMTPTODSN -- convert SMTP to DSN status code
1414 **
1415 **	Parameters:
1416 **		smtpstat -- the smtp status code (e.g., 550).
1417 **
1418 **	Returns:
1419 **		The DSN version of the status code.
1420 **
1421 **	Storage Management:
1422 **		smtptodsn() returns a pointer to a character string literal,
1423 **		which will remain valid forever, and thus does not need to
1424 **		be copied.  Current code relies on this property.
1425 */
1426 
1427 char *
1428 smtptodsn(smtpstat)
1429 	int smtpstat;
1430 {
1431 	if (smtpstat < 0)
1432 		return "4.4.2";
1433 
1434 	switch (smtpstat)
1435 	{
1436 	  case 450:	/* Req mail action not taken: mailbox unavailable */
1437 		return "4.2.0";
1438 
1439 	  case 451:	/* Req action aborted: local error in processing */
1440 		return "4.3.0";
1441 
1442 	  case 452:	/* Req action not taken: insufficient sys storage */
1443 		return "4.3.1";
1444 
1445 	  case 500:	/* Syntax error, command unrecognized */
1446 		return "5.5.2";
1447 
1448 	  case 501:	/* Syntax error in parameters or arguments */
1449 		return "5.5.4";
1450 
1451 	  case 502:	/* Command not implemented */
1452 		return "5.5.1";
1453 
1454 	  case 503:	/* Bad sequence of commands */
1455 		return "5.5.1";
1456 
1457 	  case 504:	/* Command parameter not implemented */
1458 		return "5.5.4";
1459 
1460 	  case 550:	/* Req mail action not taken: mailbox unavailable */
1461 		return "5.2.0";
1462 
1463 	  case 551:	/* User not local; please try <...> */
1464 		return "5.1.6";
1465 
1466 	  case 552:	/* Req mail action aborted: exceeded storage alloc */
1467 		return "5.2.2";
1468 
1469 	  case 553:	/* Req action not taken: mailbox name not allowed */
1470 		return "5.1.0";
1471 
1472 	  case 554:	/* Transaction failed */
1473 		return "5.0.0";
1474 	}
1475 
1476 	if (REPLYTYPE(smtpstat) == 2)
1477 		return "2.0.0";
1478 	if (REPLYTYPE(smtpstat) == 4)
1479 		return "4.0.0";
1480 	return "5.0.0";
1481 }
1482 /*
1483 **  XTEXTIFY -- take regular text and turn it into DSN-style xtext
1484 **
1485 **	Parameters:
1486 **		t -- the text to convert.
1487 **		taboo -- additional characters that must be encoded.
1488 **
1489 **	Returns:
1490 **		The xtext-ified version of the same string.
1491 */
1492 
1493 char *
1494 xtextify(t, taboo)
1495 	register char *t;
1496 	char *taboo;
1497 {
1498 	register char *p;
1499 	int l;
1500 	int nbogus;
1501 	static char *bp = NULL;
1502 	static int bplen = 0;
1503 
1504 	if (taboo == NULL)
1505 		taboo = "";
1506 
1507 	/* figure out how long this xtext will have to be */
1508 	nbogus = l = 0;
1509 	for (p = t; *p != '\0'; p++)
1510 	{
1511 		register int c = (*p & 0xff);
1512 
1513 		/* ASCII dependence here -- this is the way the spec words it */
1514 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' ||
1515 		    strchr(taboo, c) != NULL)
1516 			nbogus++;
1517 		l++;
1518 	}
1519 	if (nbogus < 0)
1520 	{
1521 		/* since nbogus is ssize_t and wrapped, 2 * size_t would wrap */
1522 		syserr("!xtextify string too long");
1523 	}
1524 	if (nbogus == 0)
1525 		return t;
1526 	l += nbogus * 2 + 1;
1527 
1528 	/* now allocate space if necessary for the new string */
1529 	if (l > bplen)
1530 	{
1531 		if (bp != NULL)
1532 			sm_free(bp); /* XXX */
1533 		bp = sm_pmalloc_x(l);
1534 		bplen = l;
1535 	}
1536 
1537 	/* ok, copy the text with byte expansion */
1538 	for (p = bp; *t != '\0'; )
1539 	{
1540 		register int c = (*t++ & 0xff);
1541 
1542 		/* ASCII dependence here -- this is the way the spec words it */
1543 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' ||
1544 		    strchr(taboo, c) != NULL)
1545 		{
1546 			*p++ = '+';
1547 			*p++ = "0123456789ABCDEF"[c >> 4];
1548 			*p++ = "0123456789ABCDEF"[c & 0xf];
1549 		}
1550 		else
1551 			*p++ = c;
1552 	}
1553 	*p = '\0';
1554 	return bp;
1555 }
1556 /*
1557 **  XUNTEXTIFY -- take xtext and turn it into plain text
1558 **
1559 **	Parameters:
1560 **		t -- the xtextified text.
1561 **
1562 **	Returns:
1563 **		The decoded text.  No attempt is made to deal with
1564 **		null strings in the resulting text.
1565 */
1566 
1567 char *
1568 xuntextify(t)
1569 	register char *t;
1570 {
1571 	register char *p;
1572 	int l;
1573 	static char *bp = NULL;
1574 	static int bplen = 0;
1575 
1576 	/* heuristic -- if no plus sign, just return the input */
1577 	if (strchr(t, '+') == NULL)
1578 		return t;
1579 
1580 	/* xtext is always longer than decoded text */
1581 	l = strlen(t);
1582 	if (l > bplen)
1583 	{
1584 		if (bp != NULL)
1585 			sm_free(bp); /* XXX */
1586 		bp = xalloc(l);
1587 		bplen = l;
1588 	}
1589 
1590 	/* ok, copy the text with byte compression */
1591 	for (p = bp; *t != '\0'; t++)
1592 	{
1593 		register int c = *t & 0xff;
1594 
1595 		if (c != '+')
1596 		{
1597 			*p++ = c;
1598 			continue;
1599 		}
1600 
1601 		c = *++t & 0xff;
1602 		if (!isascii(c) || !isxdigit(c))
1603 		{
1604 			/* error -- first digit is not hex */
1605 			usrerr("bogus xtext: +%c", c);
1606 			t--;
1607 			continue;
1608 		}
1609 		if (isdigit(c))
1610 			c -= '0';
1611 		else if (isupper(c))
1612 			c -= 'A' - 10;
1613 		else
1614 			c -= 'a' - 10;
1615 		*p = c << 4;
1616 
1617 		c = *++t & 0xff;
1618 		if (!isascii(c) || !isxdigit(c))
1619 		{
1620 			/* error -- second digit is not hex */
1621 			usrerr("bogus xtext: +%x%c", *p >> 4, c);
1622 			t--;
1623 			continue;
1624 		}
1625 		if (isdigit(c))
1626 			c -= '0';
1627 		else if (isupper(c))
1628 			c -= 'A' - 10;
1629 		else
1630 			c -= 'a' - 10;
1631 		*p++ |= c;
1632 	}
1633 	*p = '\0';
1634 	return bp;
1635 }
1636 /*
1637 **  XTEXTOK -- check if a string is legal xtext
1638 **
1639 **	Xtext is used in Delivery Status Notifications.  The spec was
1640 **	taken from RFC 1891, ``SMTP Service Extension for Delivery
1641 **	Status Notifications''.
1642 **
1643 **	Parameters:
1644 **		s -- the string to check.
1645 **
1646 **	Returns:
1647 **		true -- if 's' is legal xtext.
1648 **		false -- if it has any illegal characters in it.
1649 */
1650 
1651 bool
1652 xtextok(s)
1653 	char *s;
1654 {
1655 	int c;
1656 
1657 	while ((c = *s++) != '\0')
1658 	{
1659 		if (c == '+')
1660 		{
1661 			c = *s++;
1662 			if (!isascii(c) || !isxdigit(c))
1663 				return false;
1664 			c = *s++;
1665 			if (!isascii(c) || !isxdigit(c))
1666 				return false;
1667 		}
1668 		else if (c < '!' || c > '~' || c == '=')
1669 			return false;
1670 	}
1671 	return true;
1672 }
1673 /*
1674 **  PRUNEROUTE -- prune an RFC-822 source route
1675 **
1676 **	Trims down a source route to the last internet-registered hop.
1677 **	This is encouraged by RFC 1123 section 5.3.3.
1678 **
1679 **	Parameters:
1680 **		addr -- the address
1681 **
1682 **	Returns:
1683 **		true -- address was modified
1684 **		false -- address could not be pruned
1685 **
1686 **	Side Effects:
1687 **		modifies addr in-place
1688 */
1689 
1690 static bool
1691 pruneroute(addr)
1692 	char *addr;
1693 {
1694 #if NAMED_BIND
1695 	char *start, *at, *comma;
1696 	char c;
1697 	int braclev;
1698 	int rcode;
1699 	int i;
1700 	char hostbuf[BUFSIZ];
1701 	char *mxhosts[MAXMXHOSTS + 1];
1702 
1703 	/* check to see if this is really a route-addr */
1704 	if (*addr != '<' || addr[1] != '@' || addr[strlen(addr) - 1] != '>')
1705 		return false;
1706 
1707 	/*
1708 	**  Can't simply find the first ':' is the address might be in the
1709 	**  form:  "<@[IPv6:::1]:user@host>" and the first ':' in inside
1710 	**  the IPv6 address.
1711 	*/
1712 
1713 	start = addr;
1714 	braclev = 0;
1715 	while (*start != '\0')
1716 	{
1717 		if (*start == ':' && braclev <= 0)
1718 			break;
1719 		else if (*start == '[')
1720 			braclev++;
1721 		else if (*start == ']' && braclev > 0)
1722 			braclev--;
1723 		start++;
1724 	}
1725 	if (braclev > 0 || *start != ':')
1726 		return false;
1727 
1728 	at = strrchr(addr, '@');
1729 	if (at == NULL || at < start)
1730 		return false;
1731 
1732 	/* slice off the angle brackets */
1733 	i = strlen(at + 1);
1734 	if (i >= sizeof(hostbuf))
1735 		return false;
1736 	(void) sm_strlcpy(hostbuf, at + 1, sizeof(hostbuf));
1737 	hostbuf[i - 1] = '\0';
1738 
1739 	while (start != NULL)
1740 	{
1741 		if (getmxrr(hostbuf, mxhosts, NULL, false,
1742 			    &rcode, true, NULL) > 0)
1743 		{
1744 			(void) sm_strlcpy(addr + 1, start + 1,
1745 					  strlen(addr) - 1);
1746 			return true;
1747 		}
1748 		c = *start;
1749 		*start = '\0';
1750 		comma = strrchr(addr, ',');
1751 		if (comma != NULL && comma[1] == '@' &&
1752 		    strlen(comma + 2) < sizeof(hostbuf))
1753 			(void) sm_strlcpy(hostbuf, comma + 2, sizeof(hostbuf));
1754 		else
1755 			comma = NULL;
1756 		*start = c;
1757 		start = comma;
1758 	}
1759 #endif /* NAMED_BIND */
1760 	return false;
1761 }
1762