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