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