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