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