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