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[] = "@(#)savemail.c	8.74 (Berkeley) 06/11/95";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 
15 /*
16 **  SAVEMAIL -- Save mail on error
17 **
18 **	If mailing back errors, mail it back to the originator
19 **	together with an error message; otherwise, just put it in
20 **	dead.letter in the user's home directory (if he exists on
21 **	this machine).
22 **
23 **	Parameters:
24 **		e -- the envelope containing the message in error.
25 **		sendbody -- if TRUE, also send back the body of the
26 **			message; otherwise just send the header.
27 **
28 **	Returns:
29 **		none
30 **
31 **	Side Effects:
32 **		Saves the letter, by writing or mailing it back to the
33 **		sender, or by putting it in dead.letter in her home
34 **		directory.
35 */
36 
37 /* defines for state machine */
38 # define ESM_REPORT	0	/* report to sender's terminal */
39 # define ESM_MAIL	1	/* mail back to sender */
40 # define ESM_QUIET	2	/* messages have already been returned */
41 # define ESM_DEADLETTER	3	/* save in ~/dead.letter */
42 # define ESM_POSTMASTER	4	/* return to postmaster */
43 # define ESM_USRTMP	5	/* save in /usr/tmp/dead.letter */
44 # define ESM_PANIC	6	/* leave the locked queue/transcript files */
45 # define ESM_DONE	7	/* the message is successfully delivered */
46 
47 # ifndef _PATH_VARTMP
48 #  define _PATH_VARTMP	"/usr/tmp/"
49 # endif
50 
51 
52 void
53 savemail(e, sendbody)
54 	register ENVELOPE *e;
55 	bool sendbody;
56 {
57 	register struct passwd *pw;
58 	register FILE *fp;
59 	int state;
60 	auto ADDRESS *q = NULL;
61 	register char *p;
62 	MCI mcibuf;
63 	int sfflags;
64 	char buf[MAXLINE+1];
65 	extern char *ttypath();
66 	typedef int (*fnptr)();
67 	extern bool writable();
68 
69 	if (tTd(6, 1))
70 	{
71 		printf("\nsavemail, errormode = %c, id = %s, ExitStat = %d\n  e_from=",
72 			e->e_errormode, e->e_id == NULL ? "NONE" : e->e_id,
73 			ExitStat);
74 		printaddr(&e->e_from, FALSE);
75 	}
76 
77 	if (e->e_id == NULL)
78 	{
79 		/* can't return a message with no id */
80 		return;
81 	}
82 
83 	/*
84 	**  In the unhappy event we don't know who to return the mail
85 	**  to, make someone up.
86 	*/
87 
88 	if (e->e_from.q_paddr == NULL)
89 	{
90 		e->e_sender = "Postmaster";
91 		if (parseaddr(e->e_sender, &e->e_from,
92 			      RF_COPYPARSE|RF_SENDERADDR, '\0', NULL, e) == NULL)
93 		{
94 			syserr("553 Cannot parse Postmaster!");
95 			ExitStat = EX_SOFTWARE;
96 			finis();
97 		}
98 	}
99 	e->e_to = NULL;
100 
101 	/*
102 	**  Basic state machine.
103 	**
104 	**	This machine runs through the following states:
105 	**
106 	**	ESM_QUIET	Errors have already been printed iff the
107 	**			sender is local.
108 	**	ESM_REPORT	Report directly to the sender's terminal.
109 	**	ESM_MAIL	Mail response to the sender.
110 	**	ESM_DEADLETTER	Save response in ~/dead.letter.
111 	**	ESM_POSTMASTER	Mail response to the postmaster.
112 	**	ESM_PANIC	Save response anywhere possible.
113 	*/
114 
115 	/* determine starting state */
116 	switch (e->e_errormode)
117 	{
118 	  case EM_WRITE:
119 		state = ESM_REPORT;
120 		break;
121 
122 	  case EM_BERKNET:
123 	  case EM_MAIL:
124 		state = ESM_MAIL;
125 		break;
126 
127 	  case EM_PRINT:
128 	  case '\0':
129 		state = ESM_QUIET;
130 		break;
131 
132 	  case EM_QUIET:
133 		/* no need to return anything at all */
134 		return;
135 
136 	  default:
137 		syserr("554 savemail: bogus errormode x%x\n", e->e_errormode);
138 		state = ESM_MAIL;
139 		break;
140 	}
141 
142 	/* if this is already an error response, send to postmaster */
143 	if (bitset(EF_RESPONSE, e->e_flags))
144 	{
145 		if (e->e_parent != NULL &&
146 		    bitset(EF_RESPONSE, e->e_parent->e_flags))
147 		{
148 			/* got an error sending a response -- can it */
149 			return;
150 		}
151 		state = ESM_POSTMASTER;
152 	}
153 
154 	while (state != ESM_DONE)
155 	{
156 		if (tTd(6, 5))
157 			printf("  state %d\n", state);
158 
159 		switch (state)
160 		{
161 		  case ESM_QUIET:
162 			if (bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags))
163 				state = ESM_DEADLETTER;
164 			else
165 				state = ESM_MAIL;
166 			break;
167 
168 		  case ESM_REPORT:
169 
170 			/*
171 			**  If the user is still logged in on the same terminal,
172 			**  then write the error messages back to hir (sic).
173 			*/
174 
175 			p = ttypath();
176 			if (p == NULL || freopen(p, "w", stdout) == NULL)
177 			{
178 				state = ESM_MAIL;
179 				break;
180 			}
181 
182 			expand("\201n", buf, sizeof buf, e);
183 			printf("\r\nMessage from %s...\r\n", buf);
184 			printf("Errors occurred while sending mail.\r\n");
185 			if (e->e_xfp != NULL)
186 			{
187 				(void) fflush(e->e_xfp);
188 				fp = fopen(queuename(e, 'x'), "r");
189 			}
190 			else
191 				fp = NULL;
192 			if (fp == NULL)
193 			{
194 				syserr("Cannot open %s", queuename(e, 'x'));
195 				printf("Transcript of session is unavailable.\r\n");
196 			}
197 			else
198 			{
199 				printf("Transcript follows:\r\n");
200 				while (fgets(buf, sizeof buf, fp) != NULL &&
201 				       !ferror(stdout))
202 					fputs(buf, stdout);
203 				(void) xfclose(fp, "savemail transcript", e->e_id);
204 			}
205 			printf("Original message will be saved in dead.letter.\r\n");
206 			state = ESM_DEADLETTER;
207 			break;
208 
209 		  case ESM_MAIL:
210 			/*
211 			**  If mailing back, do it.
212 			**	Throw away all further output.  Don't alias,
213 			**	since this could cause loops, e.g., if joe
214 			**	mails to joe@x, and for some reason the network
215 			**	for @x is down, then the response gets sent to
216 			**	joe@x, which gives a response, etc.  Also force
217 			**	the mail to be delivered even if a version of
218 			**	it has already been sent to the sender.
219 			**
220 			**  If this is a configuration or local software
221 			**	error, send to the local postmaster as well,
222 			**	since the originator can't do anything
223 			**	about it anyway.  Note that this is a full
224 			**	copy of the message (intentionally) so that
225 			**	the Postmaster can forward things along.
226 			*/
227 
228 			if (ExitStat == EX_CONFIG || ExitStat == EX_SOFTWARE)
229 			{
230 				(void) sendtolist("postmaster",
231 					  NULLADDR, &e->e_errorqueue, 0, e);
232 			}
233 			if (!emptyaddr(&e->e_from))
234 			{
235 				(void) sendtolist(e->e_from.q_paddr,
236 					  NULLADDR, &e->e_errorqueue, 0, e);
237 			}
238 
239 			/*
240 			**  Deliver a non-delivery report to the
241 			**  Postmaster-designate (not necessarily
242 			**  Postmaster).  This does not include the
243 			**  body of the message, for privacy reasons.
244 			**  You really shouldn't need this.
245 			*/
246 
247 			e->e_flags |= EF_PM_NOTIFY;
248 
249 			/* check to see if there are any good addresses */
250 			for (q = e->e_errorqueue; q != NULL; q = q->q_next)
251 				if (!bitset(QBADADDR|QDONTSEND, q->q_flags))
252 					break;
253 			if (q == NULL)
254 			{
255 				/* this is an error-error */
256 				state = ESM_POSTMASTER;
257 				break;
258 			}
259 			if (returntosender(e->e_message, e->e_errorqueue,
260 					   sendbody, e) == 0)
261 			{
262 				state = ESM_DONE;
263 				break;
264 			}
265 
266 			/* didn't work -- return to postmaster */
267 			state = ESM_POSTMASTER;
268 			break;
269 
270 		  case ESM_POSTMASTER:
271 			/*
272 			**  Similar to previous case, but to system postmaster.
273 			*/
274 
275 			q = NULL;
276 			if (sendtolist("postmaster", NULL, &q, 0, e) <= 0)
277 			{
278 				syserr("553 cannot parse postmaster!");
279 				ExitStat = EX_SOFTWARE;
280 				state = ESM_USRTMP;
281 				break;
282 			}
283 			if (returntosender(e->e_message, q, sendbody, e) == 0)
284 			{
285 				state = ESM_DONE;
286 				break;
287 			}
288 
289 			/* didn't work -- last resort */
290 			state = ESM_USRTMP;
291 			break;
292 
293 		  case ESM_DEADLETTER:
294 			/*
295 			**  Save the message in dead.letter.
296 			**	If we weren't mailing back, and the user is
297 			**	local, we should save the message in
298 			**	~/dead.letter so that the poor person doesn't
299 			**	have to type it over again -- and we all know
300 			**	what poor typists UNIX users are.
301 			*/
302 
303 			p = NULL;
304 			if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
305 			{
306 				if (e->e_from.q_home != NULL)
307 					p = e->e_from.q_home;
308 				else if ((pw = sm_getpwnam(e->e_from.q_user)) != NULL)
309 					p = pw->pw_dir;
310 			}
311 			if (p == NULL || e->e_dfp == NULL)
312 			{
313 				/* no local directory or no data file */
314 				state = ESM_MAIL;
315 				break;
316 			}
317 
318 			/* we have a home directory; write dead.letter */
319 			define('z', p, e);
320 			expand("\201z/dead.letter", buf, sizeof buf, e);
321 			sfflags = SFF_NOSLINK|SFF_CREAT|SFF_REGONLY|SFF_RUNASREALUID;
322 			e->e_to = buf;
323 			if (mailfile(buf, NULL, sfflags, e) == EX_OK)
324 			{
325 				bool oldverb = Verbose;
326 
327 				Verbose = TRUE;
328 				message("Saved message in %s", buf);
329 				Verbose = oldverb;
330 				state = ESM_DONE;
331 				break;
332 			}
333 			state = ESM_MAIL;
334 			break;
335 
336 		  case ESM_USRTMP:
337 			/*
338 			**  Log the mail in /usr/tmp/dead.letter.
339 			*/
340 
341 			if (e->e_class < 0)
342 			{
343 				state = ESM_DONE;
344 				break;
345 			}
346 
347 			if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
348 			{
349 				state = ESM_PANIC;
350 				break;
351 			}
352 
353 			strcpy(buf, _PATH_VARTMP);
354 			strcat(buf, "dead.letter");
355 			sfflags = SFF_NOSLINK|SFF_CREAT|SFF_REGONLY;
356 
357 			if (!writable(buf, NULL, sfflags) ||
358 			    (fp = safefopen(buf, O_WRONLY|O_CREAT|O_APPEND,
359 					    FileMode, sfflags)) == NULL)
360 			{
361 				state = ESM_PANIC;
362 				break;
363 			}
364 
365 			bzero(&mcibuf, sizeof mcibuf);
366 			mcibuf.mci_out = fp;
367 			mcibuf.mci_mailer = FileMailer;
368 			if (bitnset(M_7BITS, FileMailer->m_flags))
369 				mcibuf.mci_flags |= MCIF_7BIT;
370 
371 			putfromline(&mcibuf, e);
372 			(*e->e_puthdr)(&mcibuf, e->e_header, e);
373 			(*e->e_putbody)(&mcibuf, e, NULL);
374 			putline("\n", &mcibuf);
375 			(void) fflush(fp);
376 			if (!ferror(fp))
377 			{
378 				bool oldverb = Verbose;
379 
380 				Verbose = TRUE;
381 				message("Saved message in %s", buf);
382 				Verbose = oldverb;
383 				state = ESM_DONE;
384 			}
385 			state = ESM_PANIC;
386 			(void) xfclose(fp, "savemail", buf);
387 			break;
388 
389 		  default:
390 			syserr("554 savemail: unknown state %d", state);
391 
392 			/* fall through ... */
393 
394 		  case ESM_PANIC:
395 			/* leave the locked queue & transcript files around */
396 			loseqfile(e, "savemail panic");
397 			syserr("!554 savemail: cannot save rejected email anywhere");
398 		}
399 	}
400 }
401 /*
402 **  RETURNTOSENDER -- return a message to the sender with an error.
403 **
404 **	Parameters:
405 **		msg -- the explanatory message.
406 **		returnq -- the queue of people to send the message to.
407 **		sendbody -- if TRUE, also send back the body of the
408 **			message; otherwise just send the header.
409 **		e -- the current envelope.
410 **
411 **	Returns:
412 **		zero -- if everything went ok.
413 **		else -- some error.
414 **
415 **	Side Effects:
416 **		Returns the current message to the sender via
417 **		mail.
418 */
419 
420 #define MAXRETURNS	6	/* max depth of returning messages */
421 #define ERRORFUDGE	100	/* nominal size of error message text */
422 
423 int
424 returntosender(msg, returnq, sendbody, e)
425 	char *msg;
426 	ADDRESS *returnq;
427 	bool sendbody;
428 	register ENVELOPE *e;
429 {
430 	register ENVELOPE *ee;
431 	ENVELOPE *oldcur = CurEnv;
432 	ENVELOPE errenvelope;
433 	static int returndepth;
434 	register ADDRESS *q;
435 	char *p;
436 	char buf[MAXNAME + 1];
437 	extern void errbody __P((MCI *, ENVELOPE *, char *));
438 
439 	if (returnq == NULL)
440 		return (-1);
441 
442 	if (msg == NULL)
443 		msg = "Unable to deliver mail";
444 
445 	if (tTd(6, 1))
446 	{
447 		printf("\n*** Return To Sender: msg=\"%s\", depth=%d, e=%x, returnq=",
448 		       msg, returndepth, e);
449 		printaddr(returnq, TRUE);
450 		if (tTd(6, 20))
451 		{
452 			printf("Sendq=");
453 			printaddr(e->e_sendqueue, TRUE);
454 		}
455 	}
456 
457 	if (++returndepth >= MAXRETURNS)
458 	{
459 		if (returndepth != MAXRETURNS)
460 			syserr("554 returntosender: infinite recursion on %s", returnq->q_paddr);
461 		/* don't "unrecurse" and fake a clean exit */
462 		/* returndepth--; */
463 		return (0);
464 	}
465 
466 	define('g', e->e_from.q_paddr, e);
467 	define('u', NULL, e);
468 
469 	/* initialize error envelope */
470 	ee = newenvelope(&errenvelope, e);
471 	define('a', "\201b", ee);
472 	define('r', "internal", ee);
473 	define('s', "localhost", ee);
474 	define('_', "localhost", ee);
475 	ee->e_puthdr = putheader;
476 	ee->e_putbody = errbody;
477 	ee->e_flags |= EF_RESPONSE|EF_METOO;
478 	if (!bitset(EF_OLDSTYLE, e->e_flags))
479 		ee->e_flags &= ~EF_OLDSTYLE;
480 	ee->e_sendqueue = returnq;
481 	ee->e_msgsize = ERRORFUDGE;
482 	if (sendbody)
483 		ee->e_msgsize += e->e_msgsize;
484 	else
485 		ee->e_flags |= EF_NO_BODY_RETN;
486 	initsys(ee);
487 	for (q = returnq; q != NULL; q = q->q_next)
488 	{
489 		if (bitset(QBADADDR, q->q_flags))
490 			continue;
491 
492 		if (!DontPruneRoutes && pruneroute(q->q_paddr))
493 		{
494 			register ADDRESS *p;
495 
496 			parseaddr(q->q_paddr, q, RF_COPYPARSE, '\0', NULL, e);
497 			for (p = returnq; p != NULL; p = p->q_next)
498 			{
499 				if (p != q && sameaddr(p, q))
500 					q->q_flags |= QDONTSEND;
501 			}
502 		}
503 
504 		if (!bitset(QDONTSEND, q->q_flags))
505 			ee->e_nrcpts++;
506 
507 		if (q->q_alias == NULL)
508 			addheader("To", q->q_paddr, &ee->e_header);
509 	}
510 
511 # ifdef LOG
512 	if (LogLevel > 5)
513 		syslog(LOG_INFO, "%s: %s: return to sender: %s",
514 			e->e_id, ee->e_id, msg);
515 # endif
516 
517 	if (SendMIMEErrors)
518 	{
519 		addheader("MIME-Version", "1.0", &ee->e_header);
520 		(void) sprintf(buf, "%s.%ld/%s",
521 			ee->e_id, curtime(), MyHostName);
522 		ee->e_msgboundary = newstr(buf);
523 		(void) sprintf(buf,
524 #if DSN
525 			"multipart/report; report-type=X-delivery-status-03 (Draft of May 5, 1995);\n\tboundary=\"%s\"",
526 #else
527 			"multipart/mixed; boundary=\"%s\"",
528 #endif
529 			ee->e_msgboundary);
530 		addheader("Content-Type", buf, &ee->e_header);
531 	}
532 	if (strncmp(msg, "Warning:", 8) == 0)
533 	{
534 		addheader("Subject", msg, &ee->e_header);
535 		p = "warning-timeout";
536 	}
537 	else if (strcmp(msg, "Return receipt") == 0)
538 	{
539 		addheader("Subject", msg, &ee->e_header);
540 		p = "return-receipt";
541 	}
542 	else
543 	{
544 		sprintf(buf, "Returned mail: %.*s", sizeof buf - 20, msg);
545 		addheader("Subject", buf, &ee->e_header);
546 		p = "failure";
547 	}
548 	(void) sprintf(buf, "auto-generated (%s)", p);
549 	addheader("Auto-Submitted", buf, &ee->e_header);
550 
551 	/* fake up an address header for the from person */
552 	expand("\201n", buf, sizeof buf, e);
553 	if (parseaddr(buf, &ee->e_from, RF_COPYALL|RF_SENDERADDR, '\0', NULL, e) == NULL)
554 	{
555 		syserr("553 Can't parse myself!");
556 		ExitStat = EX_SOFTWARE;
557 		returndepth--;
558 		return (-1);
559 	}
560 	ee->e_sender = ee->e_from.q_paddr;
561 
562 	/* push state into submessage */
563 	CurEnv = ee;
564 	define('f', "\201n", ee);
565 	define('x', "Mail Delivery Subsystem", ee);
566 	eatheader(ee, TRUE);
567 
568 	/* mark statistics */
569 	markstats(ee, NULLADDR);
570 
571 	/* actually deliver the error message */
572 	sendall(ee, SM_DEFAULT);
573 
574 	/* restore state */
575 	dropenvelope(ee);
576 	CurEnv = oldcur;
577 	returndepth--;
578 
579 	/* should check for delivery errors here */
580 	return (0);
581 }
582 /*
583 **  ERRBODY -- output the body of an error message.
584 **
585 **	Typically this is a copy of the transcript plus a copy of the
586 **	original offending message.
587 **
588 **	Parameters:
589 **		mci -- the mailer connection information.
590 **		e -- the envelope we are working in.
591 **		separator -- any possible MIME separator.
592 **		flags -- to modify the behaviour.
593 **
594 **	Returns:
595 **		none
596 **
597 **	Side Effects:
598 **		Outputs the body of an error message.
599 */
600 
601 void
602 errbody(mci, e, separator)
603 	register MCI *mci;
604 	register ENVELOPE *e;
605 	char *separator;
606 {
607 	register FILE *xfile;
608 	char *p;
609 	register ADDRESS *q;
610 	bool printheader;
611 	bool sendbody;
612 	char buf[MAXLINE];
613 	extern char *xuntextify();
614 
615 	if (bitset(MCIF_INHEADER, mci->mci_flags))
616 	{
617 		putline("", mci);
618 		mci->mci_flags &= ~MCIF_INHEADER;
619 	}
620 	if (e->e_parent == NULL)
621 	{
622 		syserr("errbody: null parent");
623 		putline("   ----- Original message lost -----\n", mci);
624 		return;
625 	}
626 
627 	/*
628 	**  Output MIME header.
629 	*/
630 
631 	if (e->e_msgboundary != NULL)
632 	{
633 		putline("This is a MIME-encapsulated message", mci);
634 		putline("", mci);
635 		(void) sprintf(buf, "--%s", e->e_msgboundary);
636 		putline(buf, mci);
637 		putline("", mci);
638 	}
639 
640 	/*
641 	**  Output introductory information.
642 	*/
643 
644 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
645 		if (bitset(QBADADDR, q->q_flags))
646 			break;
647 	if (q == NULL &&
648 	    !bitset(EF_FATALERRS|EF_SENDRECEIPT, e->e_parent->e_flags))
649 	{
650 		putline("    **********************************************",
651 			mci);
652 		putline("    **      THIS IS A WARNING MESSAGE ONLY      **",
653 			mci);
654 		putline("    **  YOU DO NOT NEED TO RESEND YOUR MESSAGE  **",
655 			mci);
656 		putline("    **********************************************",
657 			mci);
658 		putline("", mci);
659 	}
660 	sprintf(buf, "The original message was received at %s",
661 		arpadate(ctime(&e->e_parent->e_ctime)));
662 	putline(buf, mci);
663 	expand("from \201_", buf, sizeof buf, e->e_parent);
664 	putline(buf, mci);
665 	putline("", mci);
666 
667 	/*
668 	**  Output error message header (if specified and available).
669 	*/
670 
671 	if (ErrMsgFile != NULL && !bitset(EF_SENDRECEIPT, e->e_parent->e_flags))
672 	{
673 		if (*ErrMsgFile == '/')
674 		{
675 			xfile = fopen(ErrMsgFile, "r");
676 			if (xfile != NULL)
677 			{
678 				while (fgets(buf, sizeof buf, xfile) != NULL)
679 				{
680 					expand(buf, buf, sizeof buf, e);
681 					putline(buf, mci);
682 				}
683 				(void) fclose(xfile);
684 				putline("\n", mci);
685 			}
686 		}
687 		else
688 		{
689 			expand(ErrMsgFile, buf, sizeof buf, e);
690 			putline(buf, mci);
691 			putline("", mci);
692 		}
693 	}
694 
695 	/*
696 	**  Output message introduction
697 	*/
698 
699 	printheader = TRUE;
700 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
701 	{
702 		if (bitset(QBADADDR, q->q_flags))
703 		{
704 			if (!bitset(QPINGONFAILURE, q->q_flags))
705 				continue;
706 			p = "unrecoverable error";
707 		}
708 		else if (!bitset(QPRIMARY, q->q_flags))
709 			continue;
710 		else if (bitset(QRELAYED, q->q_flags))
711 			p = "relayed to non-DSN-aware mailer";
712 		else if (bitset(QDELIVERED, q->q_flags))
713 		{
714 			if (bitset(QEXPANDED, q->q_flags))
715 				p = "successfully delivered to mailing list";
716 			else
717 				p = "successfully delivered to mailbox";
718 		}
719 		else if (bitset(QEXPANDED, q->q_flags))
720 			p = "expanded by alias";
721 		else if (bitset(QDELAYED, q->q_flags))
722 			p = "transient failure";
723 		else
724 			continue;
725 
726 		if (printheader)
727 		{
728 			putline("   ----- The following addresses have delivery notifications -----",
729 				mci);
730 			printheader = FALSE;
731 		}
732 
733 		sprintf(buf, "%s  (%s)", q->q_paddr, p);
734 		putline(buf, mci);
735 		if (q->q_alias != NULL)
736 		{
737 			strcpy(buf, "    (expanded from: ");
738 			strcat(buf, q->q_alias->q_paddr);
739 			strcat(buf, ")");
740 			putline(buf, mci);
741 		}
742 	}
743 	if (!printheader)
744 		putline("\n", mci);
745 
746 	/*
747 	**  Output transcript of errors
748 	*/
749 
750 	(void) fflush(stdout);
751 	p = queuename(e->e_parent, 'x');
752 	if ((xfile = fopen(p, "r")) == NULL)
753 	{
754 		syserr("Cannot open %s", p);
755 		putline("   ----- Transcript of session is unavailable -----\n", mci);
756 	}
757 	else
758 	{
759 		printheader = TRUE;
760 		if (e->e_xfp != NULL)
761 			(void) fflush(e->e_xfp);
762 		while (fgets(buf, sizeof buf, xfile) != NULL)
763 		{
764 			if (printheader)
765 				putline("   ----- Transcript of session follows -----\n", mci);
766 			printheader = FALSE;
767 			putline(buf, mci);
768 		}
769 		(void) xfclose(xfile, "errbody xscript", p);
770 	}
771 	errno = 0;
772 
773 #if DSN
774 	/*
775 	**  Output machine-readable version.
776 	*/
777 
778 	if (e->e_msgboundary != NULL)
779 	{
780 		putline("", mci);
781 		(void) sprintf(buf, "--%s", e->e_msgboundary);
782 		putline(buf, mci);
783 		putline("Content-Type: message/X-delivery-status-05 (Draft of May 29, 1995)", mci);
784 		putline("", mci);
785 
786 		/*
787 		**  Output per-message information.
788 		*/
789 
790 		/* original envelope id from MAIL FROM: line */
791 		if (e->e_parent->e_envid != NULL)
792 		{
793 			(void) sprintf(buf, "Original-Envelope-Id: %s",
794 				xuntextify(e->e_parent->e_envid));
795 			putline(buf, mci);
796 		}
797 
798 		/* Reporting-MTA: is us (required) */
799 		(void) sprintf(buf, "Reporting-MTA: dns; %s", MyHostName);
800 		putline(buf, mci);
801 
802 		/* DSN-Gateway: not relevant since we are not translating */
803 
804 		/* Received-From-MTA: shows where we got this message from */
805 		if (RealHostName != NULL)
806 		{
807 			/* XXX use $s for type? */
808 			p = e->e_parent->e_from.q_mailer->m_mtatype;
809 			if (p == NULL)
810 				p = "dns";
811 			(void) sprintf(buf, "Received-From-MTA: %s; %s",
812 				p, RealHostName);
813 			putline(buf, mci);
814 		}
815 
816 		/* Arrival-Date: -- when it arrived here */
817 		(void) sprintf(buf, "Arrival-Date: %s",
818 			arpadate(ctime(&e->e_parent->e_ctime)));
819 		putline(buf, mci);
820 
821 		/*
822 		**  Output per-address information.
823 		*/
824 
825 		for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
826 		{
827 			register ADDRESS *r;
828 			char *action;
829 
830 			if (bitset(QBADADDR, q->q_flags))
831 				action = "failed";
832 			else if (!bitset(QPRIMARY, q->q_flags))
833 				continue;
834 			else if (bitset(QDELIVERED, q->q_flags))
835 			{
836 				if (bitset(QEXPANDED, q->q_flags))
837 					action = "delivered (to mailing list)";
838 				else
839 					action = "delivered (to mailbox)";
840 			}
841 			else if (bitset(QRELAYED, q->q_flags))
842 				action = "relayed (to non-DSN-aware mailer)";
843 			else if (bitset(QEXPANDED, q->q_flags))
844 				action = "expanded (to multi-recipient alias)";
845 			else if (bitset(QDELAYED, q->q_flags))
846 				action = "delayed";
847 			else
848 				continue;
849 
850 			putline("", mci);
851 
852 			/* Original-Recipient: -- passed from on high */
853 			if (q->q_orcpt != NULL)
854 			{
855 				(void) sprintf(buf, "Original-Recipient: %s",
856 					q->q_orcpt);
857 				putline(buf, mci);
858 			}
859 
860 			/* Final-Recipient: -- the name from the RCPT command */
861 			p = e->e_parent->e_from.q_mailer->m_addrtype;
862 			if (p == NULL)
863 				p = "rfc822";
864 			for (r = q; r->q_alias != NULL; r = r->q_alias)
865 				continue;
866 			if (strchr(r->q_user, '@') == NULL)
867 			{
868 				(void) sprintf(buf, "Final-Recipient: %s; %s@",
869 					p, r->q_user);
870 				strcat(buf, MyHostName);
871 			}
872 			else
873 			{
874 				(void) sprintf(buf, "Final-Recipient: %s; %s",
875 					p, r->q_user);
876 			}
877 			putline(buf, mci);
878 
879 			/* X-Actual-Recipient: -- the real problem address */
880 			if (r != q)
881 			{
882 				if (strchr(q->q_user, '@') == NULL)
883 				{
884 					(void) sprintf(buf, "X-Actual-Recipient: %s; %s@",
885 						p, q->q_user);
886 					strcat(buf, MyHostName);
887 				}
888 				else
889 				{
890 					(void) sprintf(buf, "X-Actual-Recipient: %s; %s",
891 						p, q->q_user);
892 				}
893 				putline(buf, mci);
894 			}
895 
896 			/* Action: -- what happened? */
897 			sprintf(buf, "Action: %s", action);
898 			putline(buf, mci);
899 
900 			/* Status: -- what _really_ happened? */
901 			strcpy(buf, "Status: ");
902 			if (q->q_status != NULL)
903 				strcat(buf, q->q_status);
904 			else if (bitset(QBADADDR, q->q_flags))
905 				strcat(buf, "5.0.0");
906 			else if (bitset(QQUEUEUP, q->q_flags))
907 				strcat(buf, "4.0.0");
908 			else
909 				strcat(buf, "2.0.0");
910 			putline(buf, mci);
911 
912 			/* Remote-MTA: -- who was I talking to? */
913 			p = q->q_mailer->m_mtatype;
914 			if (p == NULL)
915 				p = "dns";
916 			(void) sprintf(buf, "Remote-MTA: %s; ", p);
917 			if (q->q_statmta != NULL)
918 				p = q->q_statmta;
919 			else if (q->q_host != NULL && q->q_host[0] != '\0')
920 				p = q->q_host;
921 			else
922 				p = NULL;
923 			if (p != NULL)
924 			{
925 				strcat(buf, p);
926 				p = &buf[strlen(buf) - 1];
927 				if (*p == '.')
928 					*p = '\0';
929 				putline(buf, mci);
930 			}
931 
932 			/* Diagnostic-Code: -- actual result from other end */
933 			if (q->q_rstatus != NULL)
934 			{
935 				p = q->q_mailer->m_diagtype;
936 				if (p == NULL)
937 					p = "smtp";
938 				(void) sprintf(buf, "Diagnostic-Code: %s; %s",
939 					p, q->q_rstatus);
940 				putline(buf, mci);
941 			}
942 
943 			/* Last-Attempt-Date: -- fine granularity */
944 			if (q->q_statdate == (time_t) 0L)
945 				q->q_statdate = curtime();
946 			(void) sprintf(buf, "Last-Attempt-Date: %s",
947 				arpadate(ctime(&q->q_statdate)));
948 			putline(buf, mci);
949 
950 			/* Will-Retry-Until: -- for delayed messages only */
951 			if (bitset(QQUEUEUP, q->q_flags) &&
952 			    !bitset(QBADADDR, q->q_flags))
953 			{
954 				time_t xdate;
955 
956 				xdate = e->e_ctime + TimeOuts.to_q_return[e->e_timeoutclass];
957 				sprintf(buf, "Will-Retry-Until: %s",
958 					arpadate(ctime(&xdate)));
959 				putline(buf, mci);
960 			}
961 		}
962 	}
963 #endif
964 
965 	/*
966 	**  Output text of original message
967 	*/
968 
969 	putline("", mci);
970 	if (bitset(EF_HAS_DF, e->e_parent->e_flags))
971 	{
972 		sendbody = !bitset(EF_NO_BODY_RETN, e->e_parent->e_flags) &&
973 			   !bitset(EF_NO_BODY_RETN, e->e_flags);
974 
975 		if (e->e_msgboundary == NULL)
976 		{
977 			if (sendbody)
978 				putline("   ----- Original message follows -----\n", mci);
979 			else
980 				putline("   ----- Message header follows -----\n", mci);
981 			(void) fflush(mci->mci_out);
982 		}
983 		else
984 		{
985 			(void) sprintf(buf, "--%s", e->e_msgboundary);
986 			putline(buf, mci);
987 			(void) sprintf(buf, "Content-Type: %s",
988 				sendbody ? "message/rfc822"
989 					 : "text/rfc822-headers");
990 			putline(buf, mci);
991 		}
992 		putline("", mci);
993 		putheader(mci, e->e_parent->e_header, e->e_parent);
994 		if (sendbody)
995 			putbody(mci, e->e_parent, e->e_msgboundary);
996 		else if (e->e_msgboundary == NULL)
997 		{
998 			putline("", mci);
999 			putline("   ----- Message body suppressed -----", mci);
1000 		}
1001 	}
1002 	else if (e->e_msgboundary == NULL)
1003 	{
1004 		putline("  ----- No message was collected -----\n", mci);
1005 	}
1006 
1007 	if (e->e_msgboundary != NULL)
1008 	{
1009 		putline("", mci);
1010 		(void) sprintf(buf, "--%s--", e->e_msgboundary);
1011 		putline(buf, mci);
1012 	}
1013 	putline("", mci);
1014 
1015 	/*
1016 	**  Cleanup and exit
1017 	*/
1018 
1019 	if (errno != 0)
1020 		syserr("errbody: I/O error");
1021 }
1022 /*
1023 **  SMTPTODSN -- convert SMTP to DSN status code
1024 **
1025 **	Parameters:
1026 **		smtpstat -- the smtp status code (e.g., 550).
1027 **
1028 **	Returns:
1029 **		The DSN version of the status code.
1030 */
1031 
1032 char *
1033 smtptodsn(smtpstat)
1034 	int smtpstat;
1035 {
1036 	if (smtpstat < 0)
1037 		return "4.4.2";
1038 
1039 	switch (smtpstat)
1040 	{
1041 	  case 450:	/* Req mail action not taken: mailbox unavailable */
1042 		return "4.2.0";
1043 
1044 	  case 451:	/* Req action aborted: local error in processing */
1045 		return "4.3.0";
1046 
1047 	  case 452:	/* Req action not taken: insufficient sys storage */
1048 		return "4.3.1";
1049 
1050 	  case 500:	/* Syntax error, command unrecognized */
1051 		return "5.5.2";
1052 
1053 	  case 501:	/* Syntax error in parameters or arguments */
1054 		return "5.5.4";
1055 
1056 	  case 502:	/* Command not implemented */
1057 		return "5.5.1";
1058 
1059 	  case 503:	/* Bad sequence of commands */
1060 		return "5.5.1";
1061 
1062 	  case 504:	/* Command parameter not implemented */
1063 		return "5.5.4";
1064 
1065 	  case 550:	/* Req mail action not taken: mailbox unavailable */
1066 		return "5.2.0";
1067 
1068 	  case 551:	/* User not local; please try <...> */
1069 		return "5.1.6";
1070 
1071 	  case 552:	/* Req mail action aborted: exceeded storage alloc */
1072 		return "5.2.2";
1073 
1074 	  case 553:	/* Req action not taken: mailbox name not allowed */
1075 		return "5.1.3";
1076 
1077 	  case 554:	/* Transaction failed */
1078 		return "5.0.0";
1079 	}
1080 
1081 	if ((smtpstat / 100) == 2)
1082 		return "2.0.0";
1083 	if ((smtpstat / 100) == 4)
1084 		return "4.0.0";
1085 	return "5.0.0";
1086 }
1087 /*
1088 **  XTEXTIFY -- take regular text and turn it into DSN-style xtext
1089 **
1090 **	Parameters:
1091 **		t -- the text to convert.
1092 **
1093 **	Returns:
1094 **		The xtext-ified version of the same string.
1095 */
1096 
1097 char *
1098 xtextify(t)
1099 	register char *t;
1100 {
1101 	register char *p;
1102 	int l;
1103 	int nbogus;
1104 	static char *bp = NULL;
1105 	static int bplen = 0;
1106 
1107 	/* figure out how long this xtext will have to be */
1108 	nbogus = l = 0;
1109 	for (p = t; *p != '\0'; p++)
1110 	{
1111 		register int c = (*p & 0xff);
1112 
1113 		/* ASCII dependence here -- this is the way the spec words it */
1114 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(')
1115 			nbogus++;
1116 		l++;
1117 	}
1118 	if (nbogus == 0)
1119 		return t;
1120 	l += nbogus * 2 + 1;
1121 
1122 	/* now allocate space if necessary for the new string */
1123 	if (l > bplen)
1124 	{
1125 		if (bp != NULL)
1126 			free(bp);
1127 		bp = xalloc(l);
1128 		bplen = l;
1129 	}
1130 
1131 	/* ok, copy the text with byte expansion */
1132 	for (p = bp; *t != '\0'; )
1133 	{
1134 		register int c = (*t++ & 0xff);
1135 
1136 		/* ASCII dependence here -- this is the way the spec words it */
1137 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(')
1138 		{
1139 			*p++ = '+';
1140 			*p++ = "0123456789abcdef"[c >> 4];
1141 			*p++ = "0123456789abcdef"[c & 0xf];
1142 		}
1143 		else
1144 			*p++ = c;
1145 	}
1146 	*p = '\0';
1147 	return bp;
1148 }
1149 /*
1150 **  XUNTEXTIFY -- take xtext and turn it into plain text
1151 **
1152 **	Parameters:
1153 **		t -- the xtextified text.
1154 **
1155 **	Returns:
1156 **		The decoded text.  No attempt is made to deal with
1157 **		null strings in the resulting text.
1158 */
1159 
1160 char *
1161 xuntextify(t)
1162 	register char *t;
1163 {
1164 	register char *p;
1165 	int l;
1166 	static char *bp = NULL;
1167 	static int bplen = 0;
1168 
1169 	/* heuristic -- if no plus sign, just return the input */
1170 	if (strchr(t, '+') == NULL)
1171 		return t;
1172 
1173 	/* xtext is always longer than decoded text */
1174 	l = strlen(t);
1175 	if (l > bplen)
1176 	{
1177 		if (bp != NULL)
1178 			free(bp);
1179 		bp = xalloc(l);
1180 		bplen = l;
1181 	}
1182 
1183 	/* ok, copy the text with byte compression */
1184 	for (p = bp; *t != '\0'; t++)
1185 	{
1186 		register int c = *t & 0xff;
1187 
1188 		if (c != '+')
1189 		{
1190 			*p++ = c;
1191 			continue;
1192 		}
1193 
1194 		c = *++t & 0xff;
1195 		if (!isascii(c) || !isxdigit(c))
1196 		{
1197 			/* error -- first digit is not hex */
1198 			usrerr("bogus xtext: +%c", c);
1199 			t--;
1200 			continue;
1201 		}
1202 		if (isdigit(c))
1203 			c -= '0';
1204 		else if (isupper(c))
1205 			c -= 'A' - 10;
1206 		else
1207 			c -= 'a' - 10;
1208 		*p = c << 4;
1209 
1210 		c = *++t & 0xff;
1211 		if (!isascii(c) || !isxdigit(c))
1212 		{
1213 			/* error -- second digit is not hex */
1214 			usrerr("bogus xtext: +%x%c", *p >> 4, c);
1215 			t--;
1216 			continue;
1217 		}
1218 		if (isdigit(c))
1219 			c -= '0';
1220 		else if (isupper(c))
1221 			c -= 'A' - 10;
1222 		else
1223 			c -= 'a' - 10;
1224 		*p++ |= c;
1225 	}
1226 	return bp;
1227 }
1228 /*
1229 **  XTEXTOK -- check if a string is legal xtext
1230 **
1231 **	Xtext is used in Delivery Status Notifications.  The spec was
1232 **	taken from draft-ietf-notary-mime-delivery-04.txt.
1233 **
1234 **	Parameters:
1235 **		s -- the string to check.
1236 **
1237 **	Returns:
1238 **		TRUE -- if 's' is legal xtext.
1239 **		FALSE -- if it has any illegal characters in it.
1240 */
1241 
1242 bool
1243 xtextok(s)
1244 	char *s;
1245 {
1246 	int c;
1247 
1248 	while ((c = *s++) != '\0')
1249 	{
1250 		if (c == '+')
1251 		{
1252 			c = *s++;
1253 			if (!isascii(c) || !isxdigit(c))
1254 				return FALSE;
1255 			c = *s++;
1256 			if (!isascii(c) || !isxdigit(c))
1257 				return FALSE;
1258 		}
1259 		else if (c < '!' || c > '~' || c == '\\' || c == '(')
1260 			return FALSE;
1261 	}
1262 	return TRUE;
1263 }
1264 /*
1265 **  PRUNEROUTE -- prune an RFC-822 source route
1266 **
1267 **	Trims down a source route to the last internet-registered hop.
1268 **	This is encouraged by RFC 1123 section 5.3.3.
1269 **
1270 **	Parameters:
1271 **		addr -- the address
1272 **
1273 **	Returns:
1274 **		TRUE -- address was modified
1275 **		FALSE -- address could not be pruned
1276 **
1277 **	Side Effects:
1278 **		modifies addr in-place
1279 */
1280 
1281 bool
1282 pruneroute(addr)
1283 	char *addr;
1284 {
1285 #if NAMED_BIND
1286 	char *start, *at, *comma;
1287 	char c;
1288 	int rcode;
1289 	char hostbuf[BUFSIZ];
1290 	char *mxhosts[MAXMXHOSTS + 1];
1291 
1292 	/* check to see if this is really a route-addr */
1293 	if (*addr != '<' || addr[1] != '@' || addr[strlen(addr) - 1] != '>')
1294 		return FALSE;
1295 	start = strchr(addr, ':');
1296 	at = strrchr(addr, '@');
1297 	if (start == NULL || at == NULL || at < start)
1298 		return FALSE;
1299 
1300 	/* slice off the angle brackets */
1301 	strcpy(hostbuf, at + 1);
1302 	hostbuf[strlen(hostbuf) - 1] = '\0';
1303 
1304 	while (start)
1305 	{
1306 		if (getmxrr(hostbuf, mxhosts, FALSE, &rcode) > 0)
1307 		{
1308 			strcpy(addr + 1, start + 1);
1309 			return TRUE;
1310 		}
1311 		c = *start;
1312 		*start = '\0';
1313 		comma = strrchr(addr, ',');
1314 		if (comma && comma[1] == '@')
1315 			strcpy(hostbuf, comma + 2);
1316 		else
1317 			comma = 0;
1318 		*start = c;
1319 		start = comma;
1320 	}
1321 #endif
1322 	return FALSE;
1323 }
1324