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[] = "@(#)savemail.c	8.10 (Berkeley) 08/17/93";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 # include <pwd.h>
15 
16 /*
17 **  SAVEMAIL -- Save mail on error
18 **
19 **	If mailing back errors, mail it back to the originator
20 **	together with an error message; otherwise, just put it in
21 **	dead.letter in the user's home directory (if he exists on
22 **	this machine).
23 **
24 **	Parameters:
25 **		e -- the envelope containing the message in error.
26 **
27 **	Returns:
28 **		none
29 **
30 **	Side Effects:
31 **		Saves the letter, by writing or mailing it back to the
32 **		sender, or by putting it in dead.letter in her home
33 **		directory.
34 */
35 
36 /* defines for state machine */
37 # define ESM_REPORT	0	/* report to sender's terminal */
38 # define ESM_MAIL	1	/* mail back to sender */
39 # define ESM_QUIET	2	/* messages have already been returned */
40 # define ESM_DEADLETTER	3	/* save in ~/dead.letter */
41 # define ESM_POSTMASTER	4	/* return to postmaster */
42 # define ESM_USRTMP	5	/* save in /usr/tmp/dead.letter */
43 # define ESM_PANIC	6	/* leave the locked queue/transcript files */
44 # define ESM_DONE	7	/* the message is successfully delivered */
45 
46 
47 savemail(e)
48 	register ENVELOPE *e;
49 {
50 	register struct passwd *pw;
51 	register FILE *fp;
52 	int state;
53 	auto ADDRESS *q = NULL;
54 	char buf[MAXLINE+1];
55 	extern struct passwd *getpwnam();
56 	register char *p;
57 	extern char *ttypath();
58 	typedef int (*fnptr)();
59 
60 	if (tTd(6, 1))
61 	{
62 		printf("\nsavemail, errormode = %c, id = %s\n  e_from=",
63 			e->e_errormode, e->e_id == NULL ? "NONE" : e->e_id);
64 		printaddr(&e->e_from, FALSE);
65 	}
66 
67 	if (e->e_id == NULL)
68 	{
69 		/* can't return a message with no id */
70 		return;
71 	}
72 
73 	e->e_flags &= ~EF_FATALERRS;
74 
75 	/*
76 	**  In the unhappy event we don't know who to return the mail
77 	**  to, make someone up.
78 	*/
79 
80 	if (e->e_from.q_paddr == NULL)
81 	{
82 		e->e_sender = "Postmaster";
83 		if (parseaddr(e->e_sender, &e->e_from,
84 			      RF_COPYPARSE|RF_SENDERADDR, '\0', NULL, e) == NULL)
85 		{
86 			syserr("553 Cannot parse Postmaster!");
87 			ExitStat = EX_SOFTWARE;
88 			finis();
89 		}
90 	}
91 	e->e_to = NULL;
92 
93 	/*
94 	**  Basic state machine.
95 	**
96 	**	This machine runs through the following states:
97 	**
98 	**	ESM_QUIET	Errors have already been printed iff the
99 	**			sender is local.
100 	**	ESM_REPORT	Report directly to the sender's terminal.
101 	**	ESM_MAIL	Mail response to the sender.
102 	**	ESM_DEADLETTER	Save response in ~/dead.letter.
103 	**	ESM_POSTMASTER	Mail response to the postmaster.
104 	**	ESM_PANIC	Save response anywhere possible.
105 	*/
106 
107 	/* determine starting state */
108 	switch (e->e_errormode)
109 	{
110 	  case EM_WRITE:
111 		state = ESM_REPORT;
112 		break;
113 
114 	  case EM_BERKNET:
115 		/* mail back, but return o.k. exit status */
116 		ExitStat = EX_OK;
117 
118 		/* fall through.... */
119 
120 	  case EM_MAIL:
121 		state = ESM_MAIL;
122 		break;
123 
124 	  case EM_PRINT:
125 	  case '\0':
126 		state = ESM_QUIET;
127 		break;
128 
129 	  case EM_QUIET:
130 		/* no need to return anything at all */
131 		return;
132 
133 	  default:
134 		syserr("554 savemail: bogus errormode x%x\n", e->e_errormode);
135 		state = ESM_MAIL;
136 		break;
137 	}
138 
139 	/* if this is already an error response, send to postmaster */
140 	if (bitset(EF_RESPONSE, e->e_flags))
141 	{
142 		if (e->e_parent != NULL &&
143 		    bitset(EF_RESPONSE, e->e_parent->e_flags))
144 		{
145 			/* got an error sending a response -- can it */
146 			return;
147 		}
148 		state = ESM_POSTMASTER;
149 	}
150 
151 	while (state != ESM_DONE)
152 	{
153 		if (tTd(6, 5))
154 			printf("  state %d\n", state);
155 
156 		switch (state)
157 		{
158 		  case ESM_QUIET:
159 			if (e->e_from.q_mailer == LocalMailer)
160 				state = ESM_DEADLETTER;
161 			else
162 				state = ESM_MAIL;
163 			break;
164 
165 		  case ESM_REPORT:
166 
167 			/*
168 			**  If the user is still logged in on the same terminal,
169 			**  then write the error messages back to hir (sic).
170 			*/
171 
172 			p = ttypath();
173 			if (p == NULL || freopen(p, "w", stdout) == NULL)
174 			{
175 				state = ESM_MAIL;
176 				break;
177 			}
178 
179 			expand("\201n", buf, &buf[sizeof buf - 1], e);
180 			printf("\r\nMessage from %s...\r\n", buf);
181 			printf("Errors occurred while sending mail.\r\n");
182 			if (e->e_xfp != NULL)
183 			{
184 				(void) fflush(e->e_xfp);
185 				fp = fopen(queuename(e, 'x'), "r");
186 			}
187 			else
188 				fp = NULL;
189 			if (fp == NULL)
190 			{
191 				syserr("Cannot open %s", queuename(e, 'x'));
192 				printf("Transcript of session is unavailable.\r\n");
193 			}
194 			else
195 			{
196 				printf("Transcript follows:\r\n");
197 				while (fgets(buf, sizeof buf, fp) != NULL &&
198 				       !ferror(stdout))
199 					fputs(buf, stdout);
200 				(void) xfclose(fp, "savemail transcript", e->e_id);
201 			}
202 			printf("Original message will be saved in dead.letter.\r\n");
203 			state = ESM_DEADLETTER;
204 			break;
205 
206 		  case ESM_MAIL:
207 			/*
208 			**  If mailing back, do it.
209 			**	Throw away all further output.  Don't alias,
210 			**	since this could cause loops, e.g., if joe
211 			**	mails to joe@x, and for some reason the network
212 			**	for @x is down, then the response gets sent to
213 			**	joe@x, which gives a response, etc.  Also force
214 			**	the mail to be delivered even if a version of
215 			**	it has already been sent to the sender.
216 			**
217 			**  If this is a configuration or local software
218 			**	error, send to the local postmaster as well,
219 			**	since the originator can't do anything
220 			**	about it anyway.  Note that this is a full
221 			**	copy of the message (intentionally) so that
222 			**	the Postmaster can forward things along.
223 			*/
224 
225 			if (ExitStat == EX_CONFIG || ExitStat == EX_SOFTWARE)
226 			{
227 				(void) sendtolist("postmaster",
228 					  NULLADDR, &e->e_errorqueue, e);
229 			}
230 			if (strcmp(e->e_from.q_paddr, "<>") != 0)
231 			{
232 				(void) sendtolist(e->e_from.q_paddr,
233 					  NULLADDR, &e->e_errorqueue, e);
234 			}
235 
236 			/*
237 			**  Deliver a non-delivery report to the
238 			**  Postmaster-designate (not necessarily
239 			**  Postmaster).  This does not include the
240 			**  body of the message, for privacy reasons.
241 			**  You really shouldn't need this.
242 			*/
243 
244 			e->e_flags |= EF_PM_NOTIFY;
245 
246 			q = e->e_errorqueue;
247 			if (q == NULL)
248 			{
249 				/* this is an error-error */
250 				state = ESM_POSTMASTER;
251 				break;
252 			}
253 			if (returntosender(e->e_message,
254 					   q, (e->e_class >= 0), e) == 0)
255 			{
256 				state = ESM_DONE;
257 				break;
258 			}
259 
260 			/* didn't work -- return to postmaster */
261 			state = ESM_POSTMASTER;
262 			break;
263 
264 		  case ESM_POSTMASTER:
265 			/*
266 			**  Similar to previous case, but to system postmaster.
267 			*/
268 
269 			q = NULL;
270 			if (sendtolist("postmaster", NULL, &q, e) <= 0)
271 			{
272 				syserr("553 cannot parse postmaster!");
273 				ExitStat = EX_SOFTWARE;
274 				state = ESM_USRTMP;
275 				break;
276 			}
277 			if (returntosender(e->e_message,
278 					   q, (e->e_class >= 0), e) == 0)
279 			{
280 				state = ESM_DONE;
281 				break;
282 			}
283 
284 			/* didn't work -- last resort */
285 			state = ESM_USRTMP;
286 			break;
287 
288 		  case ESM_DEADLETTER:
289 			/*
290 			**  Save the message in dead.letter.
291 			**	If we weren't mailing back, and the user is
292 			**	local, we should save the message in
293 			**	~/dead.letter so that the poor person doesn't
294 			**	have to type it over again -- and we all know
295 			**	what poor typists UNIX users are.
296 			*/
297 
298 			p = NULL;
299 			if (e->e_from.q_mailer == LocalMailer)
300 			{
301 				if (e->e_from.q_home != NULL)
302 					p = e->e_from.q_home;
303 				else if ((pw = getpwnam(e->e_from.q_user)) != NULL)
304 					p = pw->pw_dir;
305 			}
306 			if (p == NULL)
307 			{
308 				/* no local directory */
309 				state = ESM_MAIL;
310 				break;
311 			}
312 			if (e->e_dfp != NULL)
313 			{
314 				bool oldverb = Verbose;
315 
316 				/* we have a home directory; open dead.letter */
317 				define('z', p, e);
318 				expand("\201z/dead.letter", buf, &buf[sizeof buf - 1], e);
319 				Verbose = TRUE;
320 				message("Saving message in %s", buf);
321 				Verbose = oldverb;
322 				e->e_to = buf;
323 				q = NULL;
324 				(void) sendtolist(buf, &e->e_from, &q, e);
325 				if (deliver(e, q) == 0)
326 					state = ESM_DONE;
327 				else
328 					state = ESM_MAIL;
329 			}
330 			else
331 			{
332 				/* no data file -- try mailing back */
333 				state = ESM_MAIL;
334 			}
335 			break;
336 
337 		  case ESM_USRTMP:
338 			/*
339 			**  Log the mail in /usr/tmp/dead.letter.
340 			*/
341 
342 			if (e->e_class < 0)
343 			{
344 				state = ESM_DONE;
345 				break;
346 			}
347 
348 			fp = dfopen("/usr/tmp/dead.letter",
349 				    O_WRONLY|O_CREAT|O_APPEND, FileMode);
350 			if (fp == NULL)
351 			{
352 				state = ESM_PANIC;
353 				break;
354 			}
355 
356 			putfromline(fp, FileMailer, e);
357 			(*e->e_puthdr)(fp, FileMailer, e);
358 			putline("\n", fp, FileMailer);
359 			(*e->e_putbody)(fp, FileMailer, e, NULL);
360 			putline("\n", fp, FileMailer);
361 			(void) fflush(fp);
362 			state = ferror(fp) ? ESM_PANIC : ESM_DONE;
363 			(void) xfclose(fp, "savemail", "/usr/tmp/dead.letter");
364 			break;
365 
366 		  default:
367 			syserr("554 savemail: unknown state %d", state);
368 
369 			/* fall through ... */
370 
371 		  case ESM_PANIC:
372 			/* leave the locked queue & transcript files around */
373 			syserr("554 savemail: cannot save rejected email anywhere");
374 			exit(EX_SOFTWARE);
375 		}
376 	}
377 }
378 /*
379 **  RETURNTOSENDER -- return a message to the sender with an error.
380 **
381 **	Parameters:
382 **		msg -- the explanatory message.
383 **		returnq -- the queue of people to send the message to.
384 **		sendbody -- if TRUE, also send back the body of the
385 **			message; otherwise just send the header.
386 **		e -- the current envelope.
387 **
388 **	Returns:
389 **		zero -- if everything went ok.
390 **		else -- some error.
391 **
392 **	Side Effects:
393 **		Returns the current message to the sender via
394 **		mail.
395 */
396 
397 static bool	SendBody;
398 
399 #define MAXRETURNS	6	/* max depth of returning messages */
400 #define ERRORFUDGE	100	/* nominal size of error message text */
401 
402 returntosender(msg, returnq, sendbody, e)
403 	char *msg;
404 	ADDRESS *returnq;
405 	bool sendbody;
406 	register ENVELOPE *e;
407 {
408 	char buf[MAXNAME];
409 	extern putheader(), errbody();
410 	register ENVELOPE *ee;
411 	ENVELOPE *oldcur = CurEnv;
412 	ENVELOPE errenvelope;
413 	static int returndepth;
414 	register ADDRESS *q;
415 
416 	if (returnq == NULL)
417 		return (-1);
418 
419 	if (msg == NULL)
420 		msg = "Unable to deliver mail";
421 
422 	if (tTd(6, 1))
423 	{
424 		printf("Return To Sender: msg=\"%s\", depth=%d, e=%x, returnq=",
425 		       msg, returndepth, e);
426 		printaddr(returnq, TRUE);
427 	}
428 
429 	if (++returndepth >= MAXRETURNS)
430 	{
431 		if (returndepth != MAXRETURNS)
432 			syserr("554 returntosender: infinite recursion on %s", returnq->q_paddr);
433 		/* don't "unrecurse" and fake a clean exit */
434 		/* returndepth--; */
435 		return (0);
436 	}
437 
438 	SendBody = sendbody;
439 	define('g', e->e_from.q_paddr, e);
440 	ee = newenvelope(&errenvelope, e);
441 	define('a', "\201b", ee);
442 	define('r', "internal", ee);
443 	define('s', "localhost", ee);
444 	define('_', "localhost", ee);
445 	ee->e_puthdr = putheader;
446 	ee->e_putbody = errbody;
447 	ee->e_flags |= EF_RESPONSE|EF_METOO;
448 	if (!bitset(EF_OLDSTYLE, e->e_flags))
449 		ee->e_flags &= ~EF_OLDSTYLE;
450 	ee->e_sendqueue = returnq;
451 	ee->e_msgsize = e->e_msgsize + ERRORFUDGE;
452 	openxscript(ee);
453 	for (q = returnq; q != NULL; q = q->q_next)
454 	{
455 		if (bitset(QBADADDR, q->q_flags))
456 			continue;
457 
458 		if (!bitset(QDONTSEND, q->q_flags))
459 			ee->e_nrcpts++;
460 
461 		if (!DontPruneRoutes && pruneroute(q->q_paddr))
462 			parseaddr(q->q_paddr, q, RF_COPYPARSE, '\0', NULL, e);
463 
464 		if (q->q_alias == NULL)
465 			addheader("To", q->q_paddr, ee);
466 	}
467 
468 # ifdef LOG
469 	if (LogLevel > 5)
470 		syslog(LOG_INFO, "%s: %s: return to sender: %s",
471 			e->e_id, ee->e_id, msg);
472 # endif
473 
474 	(void) sprintf(buf, "Returned mail: %s", msg);
475 	addheader("Subject", buf, ee);
476 	if (SendMIMEErrors)
477 	{
478 		addheader("MIME-Version", "1.0", ee);
479 		(void) sprintf(buf, "%s.%ld/%s",
480 			ee->e_id, curtime(), MyHostName);
481 		ee->e_msgboundary = newstr(buf);
482 		(void) sprintf(buf, "multipart/mixed; boundary=\"%s\"",
483 					ee->e_msgboundary);
484 		addheader("Content-Type", buf, ee);
485 	}
486 
487 	/* fake up an address header for the from person */
488 	expand("\201n", buf, &buf[sizeof buf - 1], e);
489 	if (parseaddr(buf, &ee->e_from, RF_COPYALL|RF_SENDERADDR, '\0', NULL, e) == NULL)
490 	{
491 		syserr("553 Can't parse myself!");
492 		ExitStat = EX_SOFTWARE;
493 		returndepth--;
494 		return (-1);
495 	}
496 	ee->e_sender = ee->e_from.q_paddr;
497 
498 	/* push state into submessage */
499 	CurEnv = ee;
500 	define('f', "\201n", ee);
501 	define('x', "Mail Delivery Subsystem", ee);
502 	eatheader(ee, TRUE);
503 
504 	/* mark statistics */
505 	markstats(ee, NULLADDR);
506 
507 	/* actually deliver the error message */
508 	sendall(ee, SM_DEFAULT);
509 
510 	/* restore state */
511 	dropenvelope(ee);
512 	CurEnv = oldcur;
513 	returndepth--;
514 
515 	/* should check for delivery errors here */
516 	return (0);
517 }
518 /*
519 **  ERRBODY -- output the body of an error message.
520 **
521 **	Typically this is a copy of the transcript plus a copy of the
522 **	original offending message.
523 **
524 **	Parameters:
525 **		fp -- the output file.
526 **		m -- the mailer to output to.
527 **		e -- the envelope we are working in.
528 **
529 **	Returns:
530 **		none
531 **
532 **	Side Effects:
533 **		Outputs the body of an error message.
534 */
535 
536 errbody(fp, m, e)
537 	register FILE *fp;
538 	register struct mailer *m;
539 	register ENVELOPE *e;
540 {
541 	register FILE *xfile;
542 	char *p;
543 	register ADDRESS *q;
544 	bool printheader;
545 	char buf[MAXLINE];
546 
547 	if (e->e_parent == NULL)
548 	{
549 		syserr("errbody: null parent");
550 		putline("   ----- Original message lost -----\n", fp, m);
551 		return;
552 	}
553 
554 	/*
555 	**  Output MIME header.
556 	*/
557 
558 	if (e->e_msgboundary != NULL)
559 	{
560 		putline("This is a MIME-encapsulated message", fp, m);
561 		putline("", fp, m);
562 		(void) sprintf(buf, "--%s", e->e_msgboundary);
563 		putline(buf, fp, m);
564 		putline("", fp, m);
565 	}
566 
567 	/*
568 	**  Output introductory information.
569 	*/
570 
571 	sprintf(buf, "The original message was received at %s", arpadate(NULL));
572 	putline(buf, fp, m);
573 	expand("from \201_", buf, &buf[sizeof buf - 1], e->e_parent);
574 	putline(buf, fp, m);
575 	putline("", fp, m);
576 
577 	/*
578 	**  Output error message header (if specified and available).
579 	*/
580 
581 	if (ErrMsgFile != NULL)
582 	{
583 		if (*ErrMsgFile == '/')
584 		{
585 			xfile = fopen(ErrMsgFile, "r");
586 			if (xfile != NULL)
587 			{
588 				while (fgets(buf, sizeof buf, xfile) != NULL)
589 				{
590 					expand(buf, buf, &buf[sizeof buf - 1], e);
591 					putline(buf, fp, m);
592 				}
593 				(void) fclose(xfile);
594 				putline("\n", fp, m);
595 			}
596 		}
597 		else
598 		{
599 			expand(ErrMsgFile, buf, &buf[sizeof buf - 1], e);
600 			putline(buf, fp, m);
601 			putline("", fp, m);
602 		}
603 	}
604 
605 	/*
606 	**  Output message introduction
607 	*/
608 
609 	printheader = TRUE;
610 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
611 	{
612 		if (bitset(QBADADDR|QREPORT, q->q_flags))
613 		{
614 			if (printheader)
615 			{
616 				putline("   ----- The following addresses had delivery problems -----",
617 					fp, m);
618 				printheader = FALSE;
619 			}
620 			strcpy(buf, q->q_paddr);
621 			if (bitset(QBADADDR, q->q_flags))
622 				strcat(buf, "  (unrecoverable error)");
623 			else
624 				strcat(buf, "  (transient failure)");
625 			putline(buf, fp, m);
626 			if (q->q_alias != NULL)
627 			{
628 				strcpy(buf, "    (expanded from: ");
629 				strcat(buf, q->q_alias->q_paddr);
630 				strcat(buf, ")");
631 				putline(buf, fp, m);
632 			}
633 		}
634 	}
635 	if (!printheader)
636 		putline("\n", fp, m);
637 
638 	/*
639 	**  Output transcript of errors
640 	*/
641 
642 	(void) fflush(stdout);
643 	p = queuename(e->e_parent, 'x');
644 	if ((xfile = fopen(p, "r")) == NULL)
645 	{
646 		syserr("Cannot open %s", p);
647 		putline("   ----- Transcript of session is unavailable -----\n", fp, m);
648 	}
649 	else
650 	{
651 		putline("   ----- Transcript of session follows -----\n", fp, m);
652 		if (e->e_xfp != NULL)
653 			(void) fflush(e->e_xfp);
654 		while (fgets(buf, sizeof buf, xfile) != NULL)
655 			putline(buf, fp, m);
656 		(void) xfclose(xfile, "errbody xscript", p);
657 	}
658 	errno = 0;
659 
660 	/*
661 	**  Output text of original message
662 	*/
663 
664 	if (NoReturn)
665 		SendBody = FALSE;
666 	putline("", fp, m);
667 	if (e->e_parent->e_df != NULL)
668 	{
669 		if (SendBody)
670 			putline("   ----- Original message follows -----\n", fp, m);
671 		else
672 			putline("   ----- Message header follows -----\n", fp, m);
673 		(void) fflush(fp);
674 
675 		if (e->e_msgboundary != NULL)
676 		{
677 			putline("", fp, m);
678 			(void) sprintf(buf, "--%s", e->e_msgboundary);
679 			putline(buf, fp, m);
680 			putline("Content-Type: message/rfc822", fp, m);
681 			putline("", fp, m);
682 		}
683 		putheader(fp, m, e->e_parent);
684 		putline("", fp, m);
685 		if (SendBody)
686 			putbody(fp, m, e->e_parent, e->e_msgboundary);
687 		else
688 			putline("   ----- Message body suppressed -----", fp, m);
689 	}
690 	else
691 	{
692 		putline("  ----- No message was collected -----\n", fp, m);
693 	}
694 
695 	if (e->e_msgboundary != NULL)
696 	{
697 		putline("", fp, m);
698 		(void) sprintf(buf, "--%s--", e->e_msgboundary);
699 		putline(buf, fp, m);
700 	}
701 	putline("", fp, m);
702 
703 	/*
704 	**  Cleanup and exit
705 	*/
706 
707 	if (errno != 0)
708 		syserr("errbody: I/O error");
709 }
710 /*
711 **  PRUNEROUTE -- prune an RFC-822 source route
712 **
713 **	Trims down a source route to the last internet-registered hop.
714 **	This is encouraged by RFC 1123 section 5.3.3.
715 **
716 **	Parameters:
717 **		addr -- the address
718 **
719 **	Returns:
720 **		TRUE -- address was modified
721 **		FALSE -- address could not be pruned
722 **
723 **	Side Effects:
724 **		modifies addr in-place
725 */
726 
727 pruneroute(addr)
728 	char *addr;
729 {
730 #ifdef NAMED_BIND
731 	char *start, *at, *comma;
732 	char c;
733 	int rcode;
734 	char hostbuf[BUFSIZ];
735 	char *mxhosts[MAXMXHOSTS + 1];
736 
737 	/* check to see if this is really a route-addr */
738 	if (*addr != '<' || addr[1] != '@' || addr[strlen(addr) - 1] != '>')
739 		return FALSE;
740 	start = strchr(addr, ':');
741 	at = strrchr(addr, '@');
742 	if (start == NULL || at == NULL || at < start)
743 		return FALSE;
744 
745 	/* slice off the angle brackets */
746 	strcpy(hostbuf, at + 1);
747 	hostbuf[strlen(hostbuf) - 1] = '\0';
748 
749 	while (start)
750 	{
751 		if (getmxrr(hostbuf, mxhosts, FALSE, &rcode) > 0)
752 		{
753 			strcpy(addr + 1, start + 1);
754 			return TRUE;
755 		}
756 		c = *start;
757 		*start = '\0';
758 		comma = strrchr(addr, ',');
759 		if (comma && comma[1] == '@')
760 			strcpy(hostbuf, comma + 2);
761 		else
762 			comma = 0;
763 		*start = c;
764 		start = comma;
765 	}
766 #endif
767 	return FALSE;
768 }
769