xref: /freebsd/contrib/sendmail/src/savemail.c (revision b6bacd31)
1 /*
2  * Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #include <sendmail.h>
15 
16 SM_RCSID("@(#)$Id: savemail.c,v 8.304 2004/10/06 21:36:06 ca Exp $")
17 
18 static void	errbody __P((MCI *, ENVELOPE *, char *));
19 static bool	pruneroute __P((char *));
20 
21 /*
22 **  SAVEMAIL -- Save mail on error
23 **
24 **	If mailing back errors, mail it back to the originator
25 **	together with an error message; otherwise, just put it in
26 **	dead.letter in the user's home directory (if he exists on
27 **	this machine).
28 **
29 **	Parameters:
30 **		e -- the envelope containing the message in error.
31 **		sendbody -- if true, also send back the body of the
32 **			message; otherwise just send the header.
33 **
34 **	Returns:
35 **		true if savemail panic'ed, (i.e., the data file should
36 **		be preserved by dropenvelope())
37 **
38 **	Side Effects:
39 **		Saves the letter, by writing or mailing it back to the
40 **		sender, or by putting it in dead.letter in her home
41 **		directory.
42 */
43 
44 /* defines for state machine */
45 #define ESM_REPORT		0	/* report to sender's terminal */
46 #define ESM_MAIL		1	/* mail back to sender */
47 #define ESM_QUIET		2	/* mail has already been returned */
48 #define ESM_DEADLETTER		3	/* save in ~/dead.letter */
49 #define ESM_POSTMASTER		4	/* return to postmaster */
50 #define ESM_DEADLETTERDROP	5	/* save in DeadLetterDrop */
51 #define ESM_PANIC		6	/* call loseqfile() */
52 #define ESM_DONE		7	/* message is successfully delivered */
53 
54 bool
55 savemail(e, sendbody)
56 	register ENVELOPE *e;
57 	bool sendbody;
58 {
59 	register SM_FILE_T *fp;
60 	bool panic = false;
61 	int state;
62 	auto ADDRESS *q = NULL;
63 	register char *p;
64 	MCI mcibuf;
65 	int flags;
66 	long sff;
67 	char buf[MAXLINE + 1];
68 	char dlbuf[MAXPATHLEN];
69 	SM_MBDB_T user;
70 
71 
72 	if (tTd(6, 1))
73 	{
74 		sm_dprintf("\nsavemail, errormode = %c, id = %s, ExitStat = %d\n  e_from=",
75 			e->e_errormode, e->e_id == NULL ? "NONE" : e->e_id,
76 			ExitStat);
77 		printaddr(sm_debug_file(), &e->e_from, false);
78 	}
79 
80 	if (e->e_id == NULL)
81 	{
82 		/* can't return a message with no id */
83 		return panic;
84 	}
85 
86 	/*
87 	**  In the unhappy event we don't know who to return the mail
88 	**  to, make someone up.
89 	*/
90 
91 	if (e->e_from.q_paddr == NULL)
92 	{
93 		e->e_sender = "Postmaster";
94 		if (parseaddr(e->e_sender, &e->e_from,
95 			      RF_COPYPARSE|RF_SENDERADDR,
96 			      '\0', NULL, e, false) == NULL)
97 		{
98 			syserr("553 5.3.5 Cannot parse Postmaster!");
99 			finis(true, true, EX_SOFTWARE);
100 		}
101 	}
102 	e->e_to = NULL;
103 
104 	/*
105 	**  Basic state machine.
106 	**
107 	**	This machine runs through the following states:
108 	**
109 	**	ESM_QUIET	Errors have already been printed iff the
110 	**			sender is local.
111 	**	ESM_REPORT	Report directly to the sender's terminal.
112 	**	ESM_MAIL	Mail response to the sender.
113 	**	ESM_DEADLETTER	Save response in ~/dead.letter.
114 	**	ESM_POSTMASTER	Mail response to the postmaster.
115 	**	ESM_DEADLETTERDROP
116 	**			If DeadLetterDrop set, save it there.
117 	**	ESM_PANIC	Save response anywhere possible.
118 	*/
119 
120 	/* determine starting state */
121 	switch (e->e_errormode)
122 	{
123 	  case EM_WRITE:
124 		state = ESM_REPORT;
125 		break;
126 
127 	  case EM_BERKNET:
128 	  case EM_MAIL:
129 		state = ESM_MAIL;
130 		break;
131 
132 	  case EM_PRINT:
133 	  case '\0':
134 		state = ESM_QUIET;
135 		break;
136 
137 	  case EM_QUIET:
138 		/* no need to return anything at all */
139 		return panic;
140 
141 	  default:
142 		syserr("554 5.3.0 savemail: bogus errormode x%x",
143 		       e->e_errormode);
144 		state = ESM_MAIL;
145 		break;
146 	}
147 
148 	/* if this is already an error response, send to postmaster */
149 	if (bitset(EF_RESPONSE, e->e_flags))
150 	{
151 		if (e->e_parent != NULL &&
152 		    bitset(EF_RESPONSE, e->e_parent->e_flags))
153 		{
154 			/* got an error sending a response -- can it */
155 			return panic;
156 		}
157 		state = ESM_POSTMASTER;
158 	}
159 
160 	while (state != ESM_DONE)
161 	{
162 		if (tTd(6, 5))
163 			sm_dprintf("  state %d\n", state);
164 
165 		switch (state)
166 		{
167 		  case ESM_QUIET:
168 			if (bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags))
169 				state = ESM_DEADLETTER;
170 			else
171 				state = ESM_MAIL;
172 			break;
173 
174 		  case ESM_REPORT:
175 
176 			/*
177 			**  If the user is still logged in on the same terminal,
178 			**  then write the error messages back to hir (sic).
179 			*/
180 
181 #if USE_TTYPATH
182 			p = ttypath();
183 #else /* USE_TTYPATH */
184 			p = NULL;
185 #endif /* USE_TTYPATH */
186 
187 			if (p == NULL || sm_io_reopen(SmFtStdio,
188 						      SM_TIME_DEFAULT,
189 						      p, SM_IO_WRONLY, NULL,
190 						      smioout) == NULL)
191 			{
192 				state = ESM_MAIL;
193 				break;
194 			}
195 
196 			expand("\201n", buf, sizeof buf, e);
197 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
198 					     "\r\nMessage from %s...\r\n", buf);
199 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
200 					     "Errors occurred while sending mail.\r\n");
201 			if (e->e_xfp != NULL)
202 			{
203 				(void) bfrewind(e->e_xfp);
204 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
205 						     "Transcript follows:\r\n");
206 				while (sm_io_fgets(e->e_xfp, SM_TIME_DEFAULT,
207 						   buf, sizeof buf) != NULL &&
208 				       !sm_io_error(smioout))
209 					(void) sm_io_fputs(smioout,
210 							   SM_TIME_DEFAULT,
211 							   buf);
212 			}
213 			else
214 			{
215 				syserr("Cannot open %s",
216 				       queuename(e, XSCRPT_LETTER));
217 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
218 						     "Transcript of session is unavailable.\r\n");
219 			}
220 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
221 					     "Original message will be saved in dead.letter.\r\n");
222 			state = ESM_DEADLETTER;
223 			break;
224 
225 		  case ESM_MAIL:
226 			/*
227 			**  If mailing back, do it.
228 			**	Throw away all further output.  Don't alias,
229 			**	since this could cause loops, e.g., if joe
230 			**	mails to joe@x, and for some reason the network
231 			**	for @x is down, then the response gets sent to
232 			**	joe@x, which gives a response, etc.  Also force
233 			**	the mail to be delivered even if a version of
234 			**	it has already been sent to the sender.
235 			**
236 			**  If this is a configuration or local software
237 			**	error, send to the local postmaster as well,
238 			**	since the originator can't do anything
239 			**	about it anyway.  Note that this is a full
240 			**	copy of the message (intentionally) so that
241 			**	the Postmaster can forward things along.
242 			*/
243 
244 			if (ExitStat == EX_CONFIG || ExitStat == EX_SOFTWARE)
245 			{
246 				(void) sendtolist("postmaster", NULLADDR,
247 						  &e->e_errorqueue, 0, e);
248 			}
249 			if (!emptyaddr(&e->e_from))
250 			{
251 				char from[TOBUFSIZE];
252 
253 				if (sm_strlcpy(from, e->e_from.q_paddr,
254 						sizeof from) >= sizeof from)
255 				{
256 					state = ESM_POSTMASTER;
257 					break;
258 				}
259 
260 				if (!DontPruneRoutes)
261 					(void) pruneroute(from);
262 
263 				(void) sendtolist(from, NULLADDR,
264 						  &e->e_errorqueue, 0, e);
265 			}
266 
267 			/*
268 			**  Deliver a non-delivery report to the
269 			**  Postmaster-designate (not necessarily
270 			**  Postmaster).  This does not include the
271 			**  body of the message, for privacy reasons.
272 			**  You really shouldn't need this.
273 			*/
274 
275 			e->e_flags |= EF_PM_NOTIFY;
276 
277 			/* check to see if there are any good addresses */
278 			for (q = e->e_errorqueue; q != NULL; q = q->q_next)
279 			{
280 				if (QS_IS_SENDABLE(q->q_state))
281 					break;
282 			}
283 			if (q == NULL)
284 			{
285 				/* this is an error-error */
286 				state = ESM_POSTMASTER;
287 				break;
288 			}
289 			if (returntosender(e->e_message, e->e_errorqueue,
290 					   sendbody ? RTSF_SEND_BODY
291 						    : RTSF_NO_BODY,
292 					   e) == 0)
293 			{
294 				state = ESM_DONE;
295 				break;
296 			}
297 
298 			/* didn't work -- return to postmaster */
299 			state = ESM_POSTMASTER;
300 			break;
301 
302 		  case ESM_POSTMASTER:
303 			/*
304 			**  Similar to previous case, but to system postmaster.
305 			*/
306 
307 			q = NULL;
308 			expand(DoubleBounceAddr, buf, sizeof buf, e);
309 
310 			/*
311 			**  Just drop it on the floor if DoubleBounceAddr
312 			**  expands to an empty string.
313 			*/
314 
315 			if (*buf == '\0')
316 			{
317 				state = ESM_DONE;
318 				break;
319 			}
320 			if (sendtolist(buf, NULLADDR, &q, 0, e) <= 0)
321 			{
322 				syserr("553 5.3.0 cannot parse %s!", buf);
323 				ExitStat = EX_SOFTWARE;
324 				state = ESM_DEADLETTERDROP;
325 				break;
326 			}
327 			flags = RTSF_PM_BOUNCE;
328 			if (sendbody)
329 				flags |= RTSF_SEND_BODY;
330 			if (returntosender(e->e_message, q, flags, e) == 0)
331 			{
332 				state = ESM_DONE;
333 				break;
334 			}
335 
336 			/* didn't work -- last resort */
337 			state = ESM_DEADLETTERDROP;
338 			break;
339 
340 		  case ESM_DEADLETTER:
341 			/*
342 			**  Save the message in dead.letter.
343 			**	If we weren't mailing back, and the user is
344 			**	local, we should save the message in
345 			**	~/dead.letter so that the poor person doesn't
346 			**	have to type it over again -- and we all know
347 			**	what poor typists UNIX users are.
348 			*/
349 
350 			p = NULL;
351 			if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
352 			{
353 				if (e->e_from.q_home != NULL)
354 					p = e->e_from.q_home;
355 				else if (sm_mbdb_lookup(e->e_from.q_user, &user)
356 					 == EX_OK &&
357 					 *user.mbdb_homedir != '\0')
358 					p = user.mbdb_homedir;
359 			}
360 			if (p == NULL || e->e_dfp == NULL)
361 			{
362 				/* no local directory or no data file */
363 				state = ESM_MAIL;
364 				break;
365 			}
366 
367 			/* we have a home directory; write dead.letter */
368 			macdefine(&e->e_macro, A_TEMP, 'z', p);
369 
370 			/* get the sender for the UnixFromLine */
371 			p = macvalue('g', e);
372 			macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
373 
374 			expand("\201z/dead.letter", dlbuf, sizeof dlbuf, e);
375 			sff = SFF_CREAT|SFF_REGONLY|SFF_RUNASREALUID;
376 			if (RealUid == 0)
377 				sff |= SFF_ROOTOK;
378 			e->e_to = dlbuf;
379 			if (writable(dlbuf, NULL, sff) &&
380 			    mailfile(dlbuf, FileMailer, NULL, sff, e) == EX_OK)
381 			{
382 				int oldverb = Verbose;
383 
384 				if (OpMode != MD_DAEMON && OpMode != MD_SMTP)
385 					Verbose = 1;
386 				if (Verbose > 0)
387 					message("Saved message in %s", dlbuf);
388 				Verbose = oldverb;
389 				macdefine(&e->e_macro, A_PERM, 'g', p);
390 				state = ESM_DONE;
391 				break;
392 			}
393 			macdefine(&e->e_macro, A_PERM, 'g', p);
394 			state = ESM_MAIL;
395 			break;
396 
397 		  case ESM_DEADLETTERDROP:
398 			/*
399 			**  Log the mail in DeadLetterDrop file.
400 			*/
401 
402 			if (e->e_class < 0)
403 			{
404 				state = ESM_DONE;
405 				break;
406 			}
407 
408 			if ((SafeFileEnv != NULL && SafeFileEnv[0] != '\0') ||
409 			    DeadLetterDrop == NULL ||
410 			    DeadLetterDrop[0] == '\0')
411 			{
412 				state = ESM_PANIC;
413 				break;
414 			}
415 
416 			sff = SFF_CREAT|SFF_REGONLY|SFF_ROOTOK|SFF_OPENASROOT|SFF_MUSTOWN;
417 			if (!writable(DeadLetterDrop, NULL, sff) ||
418 			    (fp = safefopen(DeadLetterDrop, O_WRONLY|O_APPEND,
419 					    FileMode, sff)) == NULL)
420 			{
421 				state = ESM_PANIC;
422 				break;
423 			}
424 
425 			memset(&mcibuf, '\0', sizeof mcibuf);
426 			mcibuf.mci_out = fp;
427 			mcibuf.mci_mailer = FileMailer;
428 			if (bitnset(M_7BITS, FileMailer->m_flags))
429 				mcibuf.mci_flags |= MCIF_7BIT;
430 
431 			/* get the sender for the UnixFromLine */
432 			p = macvalue('g', e);
433 			macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
434 
435 			putfromline(&mcibuf, e);
436 			(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER);
437 			(*e->e_putbody)(&mcibuf, e, NULL);
438 			putline("\n", &mcibuf); /* XXX EOL from FileMailer? */
439 			(void) sm_io_flush(fp, SM_TIME_DEFAULT);
440 			if (sm_io_error(fp) ||
441 			    sm_io_close(fp, SM_TIME_DEFAULT) < 0)
442 				state = ESM_PANIC;
443 			else
444 			{
445 				int oldverb = Verbose;
446 
447 				if (OpMode != MD_DAEMON && OpMode != MD_SMTP)
448 					Verbose = 1;
449 				if (Verbose > 0)
450 					message("Saved message in %s",
451 						DeadLetterDrop);
452 				Verbose = oldverb;
453 				if (LogLevel > 3)
454 					sm_syslog(LOG_NOTICE, e->e_id,
455 						  "Saved message in %s",
456 						  DeadLetterDrop);
457 				state = ESM_DONE;
458 			}
459 			macdefine(&e->e_macro, A_PERM, 'g', p);
460 			break;
461 
462 		  default:
463 			syserr("554 5.3.5 savemail: unknown state %d", state);
464 			/* FALLTHROUGH */
465 
466 		  case ESM_PANIC:
467 			/* leave the locked queue & transcript files around */
468 			loseqfile(e, "savemail panic");
469 			panic = true;
470 			errno = 0;
471 			syserr("554 savemail: cannot save rejected email anywhere");
472 			state = ESM_DONE;
473 			break;
474 		}
475 	}
476 	return panic;
477 }
478 /*
479 **  RETURNTOSENDER -- return a message to the sender with an error.
480 **
481 **	Parameters:
482 **		msg -- the explanatory message.
483 **		returnq -- the queue of people to send the message to.
484 **		flags -- flags tweaking the operation:
485 **			RTSF_SENDBODY -- include body of message (otherwise
486 **				just send the header).
487 **			RTSF_PMBOUNCE -- this is a postmaster bounce.
488 **		e -- the current envelope.
489 **
490 **	Returns:
491 **		zero -- if everything went ok.
492 **		else -- some error.
493 **
494 **	Side Effects:
495 **		Returns the current message to the sender via mail.
496 */
497 
498 #define MAXRETURNS	6	/* max depth of returning messages */
499 #define ERRORFUDGE	1024	/* nominal size of error message text */
500 
501 int
502 returntosender(msg, returnq, flags, e)
503 	char *msg;
504 	ADDRESS *returnq;
505 	int flags;
506 	register ENVELOPE *e;
507 {
508 	register ENVELOPE *ee;
509 	ENVELOPE *oldcur = CurEnv;
510 	ENVELOPE errenvelope;
511 	static int returndepth = 0;
512 	register ADDRESS *q;
513 	char *p;
514 	char buf[MAXNAME + 1];
515 
516 	if (returnq == NULL)
517 		return -1;
518 
519 	if (msg == NULL)
520 		msg = "Unable to deliver mail";
521 
522 	if (tTd(6, 1))
523 	{
524 		sm_dprintf("\n*** Return To Sender: msg=\"%s\", depth=%d, e=%p, returnq=",
525 			msg, returndepth, e);
526 		printaddr(sm_debug_file(), returnq, true);
527 		if (tTd(6, 20))
528 		{
529 			sm_dprintf("Sendq=");
530 			printaddr(sm_debug_file(), e->e_sendqueue, true);
531 		}
532 	}
533 
534 	if (++returndepth >= MAXRETURNS)
535 	{
536 		if (returndepth != MAXRETURNS)
537 			syserr("554 5.3.0 returntosender: infinite recursion on %s",
538 			       returnq->q_paddr);
539 		/* don't "unrecurse" and fake a clean exit */
540 		/* returndepth--; */
541 		return 0;
542 	}
543 
544 	macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
545 	macdefine(&e->e_macro, A_PERM, 'u', NULL);
546 
547 	/* initialize error envelope */
548 	ee = newenvelope(&errenvelope, e, sm_rpool_new_x(NULL));
549 	macdefine(&ee->e_macro, A_PERM, 'a', "\201b");
550 	macdefine(&ee->e_macro, A_PERM, 'r', "");
551 	macdefine(&ee->e_macro, A_PERM, 's', "localhost");
552 	macdefine(&ee->e_macro, A_PERM, '_', "localhost");
553 	clrsessenvelope(ee);
554 
555 	ee->e_puthdr = putheader;
556 	ee->e_putbody = errbody;
557 	ee->e_flags |= EF_RESPONSE|EF_METOO;
558 	if (!bitset(EF_OLDSTYLE, e->e_flags))
559 		ee->e_flags &= ~EF_OLDSTYLE;
560 	if (bitset(EF_DONT_MIME, e->e_flags))
561 	{
562 		ee->e_flags |= EF_DONT_MIME;
563 
564 		/*
565 		**  If we can't convert to MIME and we don't pass
566 		**  8-bit, we can't send the body.
567 		*/
568 
569 		if (bitset(EF_HAS8BIT, e->e_flags) &&
570 		    !bitset(MM_PASS8BIT, MimeMode))
571 			flags &= ~RTSF_SEND_BODY;
572 	}
573 
574 	ee->e_sendqueue = returnq;
575 	ee->e_msgsize = 0;
576 	if (bitset(RTSF_SEND_BODY, flags) &&
577 	    !bitset(PRIV_NOBODYRETN, PrivacyFlags))
578 		ee->e_msgsize = ERRORFUDGE + e->e_msgsize;
579 	else
580 		ee->e_flags |= EF_NO_BODY_RETN;
581 
582 	if (!setnewqueue(ee))
583 	{
584 		syserr("554 5.3.0 returntosender: cannot select queue for %s",
585 			       returnq->q_paddr);
586 		ExitStat = EX_UNAVAILABLE;
587 		returndepth--;
588 		return -1;
589 	}
590 	initsys(ee);
591 
592 #if NAMED_BIND
593 	_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
594 	_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
595 #endif /* NAMED_BIND */
596 	for (q = returnq; q != NULL; q = q->q_next)
597 	{
598 		if (QS_IS_BADADDR(q->q_state))
599 			continue;
600 
601 		q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
602 		q->q_flags |= QPINGONFAILURE;
603 
604 		if (!QS_IS_DEAD(q->q_state))
605 			ee->e_nrcpts++;
606 
607 		if (q->q_alias == NULL)
608 			addheader("To", q->q_paddr, 0, ee);
609 	}
610 
611 	if (LogLevel > 5)
612 	{
613 		if (bitset(EF_RESPONSE, e->e_flags))
614 			p = "return to sender";
615 		else if (bitset(EF_WARNING, e->e_flags))
616 			p = "sender notify";
617 		else if (bitset(RTSF_PM_BOUNCE, flags))
618 			p = "postmaster notify";
619 		else
620 			p = "DSN";
621 		sm_syslog(LOG_INFO, e->e_id, "%s: %s: %s",
622 			  ee->e_id, p, shortenstring(msg, MAXSHORTSTR));
623 	}
624 
625 	if (SendMIMEErrors)
626 	{
627 		addheader("MIME-Version", "1.0", 0, ee);
628 		(void) sm_snprintf(buf, sizeof buf, "%s.%ld/%.100s",
629 				ee->e_id, (long)curtime(), MyHostName);
630 		ee->e_msgboundary = sm_rpool_strdup_x(ee->e_rpool, buf);
631 		(void) sm_snprintf(buf, sizeof buf,
632 #if DSN
633 				"multipart/report; report-type=delivery-status;\n\tboundary=\"%s\"",
634 #else /* DSN */
635 				"multipart/mixed; boundary=\"%s\"",
636 #endif /* DSN */
637 				ee->e_msgboundary);
638 		addheader("Content-Type", buf, 0, ee);
639 
640 		p = hvalue("Content-Transfer-Encoding", e->e_header);
641 		if (p != NULL && sm_strcasecmp(p, "binary") != 0)
642 			p = NULL;
643 		if (p == NULL && bitset(EF_HAS8BIT, e->e_flags))
644 			p = "8bit";
645 		if (p != NULL)
646 			addheader("Content-Transfer-Encoding", p, 0, ee);
647 	}
648 	if (strncmp(msg, "Warning:", 8) == 0)
649 	{
650 		addheader("Subject", msg, 0, ee);
651 		p = "warning-timeout";
652 	}
653 	else if (strncmp(msg, "Postmaster warning:", 19) == 0)
654 	{
655 		addheader("Subject", msg, 0, ee);
656 		p = "postmaster-warning";
657 	}
658 	else if (strcmp(msg, "Return receipt") == 0)
659 	{
660 		addheader("Subject", msg, 0, ee);
661 		p = "return-receipt";
662 	}
663 	else if (bitset(RTSF_PM_BOUNCE, flags))
664 	{
665 		(void) sm_snprintf(buf, sizeof buf,
666 			 "Postmaster notify: see transcript for details");
667 		addheader("Subject", buf, 0, ee);
668 		p = "postmaster-notification";
669 	}
670 	else
671 	{
672 		(void) sm_snprintf(buf, sizeof buf,
673 			 "Returned mail: see transcript for details");
674 		addheader("Subject", buf, 0, ee);
675 		p = "failure";
676 	}
677 	(void) sm_snprintf(buf, sizeof buf, "auto-generated (%s)", p);
678 	addheader("Auto-Submitted", buf, 0, ee);
679 
680 	/* fake up an address header for the from person */
681 	expand("\201n", buf, sizeof buf, e);
682 	if (parseaddr(buf, &ee->e_from,
683 		      RF_COPYALL|RF_SENDERADDR, '\0', NULL, e, false) == NULL)
684 	{
685 		syserr("553 5.3.5 Can't parse myself!");
686 		ExitStat = EX_SOFTWARE;
687 		returndepth--;
688 		return -1;
689 	}
690 	ee->e_from.q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
691 	ee->e_from.q_flags |= QPINGONFAILURE;
692 	ee->e_sender = ee->e_from.q_paddr;
693 
694 	/* push state into submessage */
695 	CurEnv = ee;
696 	macdefine(&ee->e_macro, A_PERM, 'f', "\201n");
697 	macdefine(&ee->e_macro, A_PERM, 'x', "Mail Delivery Subsystem");
698 	eatheader(ee, true, true);
699 
700 	/* mark statistics */
701 	markstats(ee, NULLADDR, STATS_NORMAL);
702 
703 	/* actually deliver the error message */
704 	sendall(ee, SM_DELIVER);
705 
706 	/* restore state */
707 	dropenvelope(ee, true, false);
708 	sm_rpool_free(ee->e_rpool);
709 	CurEnv = oldcur;
710 	returndepth--;
711 
712 	/* check for delivery errors */
713 	if (ee->e_parent == NULL ||
714 	    !bitset(EF_RESPONSE, ee->e_parent->e_flags))
715 		return 0;
716 	for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
717 	{
718 		if (QS_IS_ATTEMPTED(q->q_state))
719 			return 0;
720 	}
721 	return -1;
722 }
723 /*
724 **  ERRBODY -- output the body of an error message.
725 **
726 **	Typically this is a copy of the transcript plus a copy of the
727 **	original offending message.
728 **
729 **	Parameters:
730 **		mci -- the mailer connection information.
731 **		e -- the envelope we are working in.
732 **		separator -- any possible MIME separator (unused).
733 **
734 **	Returns:
735 **		none
736 **
737 **	Side Effects:
738 **		Outputs the body of an error message.
739 */
740 
741 /* ARGSUSED2 */
742 static void
743 errbody(mci, e, separator)
744 	register MCI *mci;
745 	register ENVELOPE *e;
746 	char *separator;
747 {
748 	bool printheader;
749 	bool sendbody;
750 	bool pm_notify;
751 	int save_errno;
752 	register SM_FILE_T *xfile;
753 	char *p;
754 	register ADDRESS *q = NULL;
755 	char actual[MAXLINE];
756 	char buf[MAXLINE];
757 
758 	if (bitset(MCIF_INHEADER, mci->mci_flags))
759 	{
760 		putline("", mci);
761 		mci->mci_flags &= ~MCIF_INHEADER;
762 	}
763 	if (e->e_parent == NULL)
764 	{
765 		syserr("errbody: null parent");
766 		putline("   ----- Original message lost -----\n", mci);
767 		return;
768 	}
769 
770 	/*
771 	**  Output MIME header.
772 	*/
773 
774 	if (e->e_msgboundary != NULL)
775 	{
776 		putline("This is a MIME-encapsulated message", mci);
777 		putline("", mci);
778 		(void) sm_strlcpyn(buf, sizeof buf, 2, "--", e->e_msgboundary);
779 		putline(buf, mci);
780 		putline("", mci);
781 	}
782 
783 	/*
784 	**  Output introductory information.
785 	*/
786 
787 	pm_notify = false;
788 	p = hvalue("subject", e->e_header);
789 	if (p != NULL && strncmp(p, "Postmaster ", 11) == 0)
790 		pm_notify = true;
791 	else
792 	{
793 		for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
794 		{
795 			if (QS_IS_BADADDR(q->q_state))
796 				break;
797 		}
798 	}
799 	if (!pm_notify && q == NULL &&
800 	    !bitset(EF_FATALERRS|EF_SENDRECEIPT, e->e_parent->e_flags))
801 	{
802 		putline("    **********************************************",
803 			mci);
804 		putline("    **      THIS IS A WARNING MESSAGE ONLY      **",
805 			mci);
806 		putline("    **  YOU DO NOT NEED TO RESEND YOUR MESSAGE  **",
807 			mci);
808 		putline("    **********************************************",
809 			mci);
810 		putline("", mci);
811 	}
812 	(void) sm_snprintf(buf, sizeof buf,
813 		"The original message was received at %s",
814 		arpadate(ctime(&e->e_parent->e_ctime)));
815 	putline(buf, mci);
816 	expand("from \201_", buf, sizeof buf, e->e_parent);
817 	putline(buf, mci);
818 
819 	/* include id in postmaster copies */
820 	if (pm_notify && e->e_parent->e_id != NULL)
821 	{
822 		(void) sm_strlcpyn(buf, sizeof buf, 2, "with id ",
823 			e->e_parent->e_id);
824 		putline(buf, mci);
825 	}
826 	putline("", mci);
827 
828 	/*
829 	**  Output error message header (if specified and available).
830 	*/
831 
832 	if (ErrMsgFile != NULL &&
833 	    !bitset(EF_SENDRECEIPT, e->e_parent->e_flags))
834 	{
835 		if (*ErrMsgFile == '/')
836 		{
837 			long sff = SFF_ROOTOK|SFF_REGONLY;
838 
839 			if (DontLockReadFiles)
840 				sff |= SFF_NOLOCK;
841 			if (!bitnset(DBS_ERRORHEADERINUNSAFEDIRPATH,
842 				     DontBlameSendmail))
843 				sff |= SFF_SAFEDIRPATH;
844 			xfile = safefopen(ErrMsgFile, O_RDONLY, 0444, sff);
845 			if (xfile != NULL)
846 			{
847 				while (sm_io_fgets(xfile, SM_TIME_DEFAULT, buf,
848 						   sizeof buf) != NULL)
849 				{
850 					translate_dollars(buf);
851 					expand(buf, buf, sizeof buf, e);
852 					putline(buf, mci);
853 				}
854 				(void) sm_io_close(xfile, SM_TIME_DEFAULT);
855 				putline("\n", mci);
856 			}
857 		}
858 		else
859 		{
860 			expand(ErrMsgFile, buf, sizeof buf, e);
861 			putline(buf, mci);
862 			putline("", mci);
863 		}
864 	}
865 
866 	/*
867 	**  Output message introduction
868 	*/
869 
870 	/* permanent fatal errors */
871 	printheader = true;
872 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
873 	{
874 		if (!QS_IS_BADADDR(q->q_state) ||
875 		    !bitset(QPINGONFAILURE, q->q_flags))
876 			continue;
877 
878 		if (printheader)
879 		{
880 			putline("   ----- The following addresses had permanent fatal errors -----",
881 				mci);
882 			printheader = false;
883 		}
884 
885 		(void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR),
886 				  sizeof buf);
887 		putline(buf, mci);
888 		if (q->q_rstatus != NULL)
889 		{
890 			(void) sm_snprintf(buf, sizeof buf,
891 				"    (reason: %s)",
892 				shortenstring(exitstat(q->q_rstatus),
893 					      MAXSHORTSTR));
894 			putline(buf, mci);
895 		}
896 		if (q->q_alias != NULL)
897 		{
898 			(void) sm_snprintf(buf, sizeof buf,
899 				"    (expanded from: %s)",
900 				shortenstring(q->q_alias->q_paddr,
901 					      MAXSHORTSTR));
902 			putline(buf, mci);
903 		}
904 	}
905 	if (!printheader)
906 		putline("", mci);
907 
908 	/* transient non-fatal errors */
909 	printheader = true;
910 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
911 	{
912 		if (QS_IS_BADADDR(q->q_state) ||
913 		    !bitset(QPRIMARY, q->q_flags) ||
914 		    !bitset(QBYNDELAY, q->q_flags) ||
915 		    !bitset(QDELAYED, q->q_flags))
916 			continue;
917 
918 		if (printheader)
919 		{
920 			putline("   ----- The following addresses had transient non-fatal errors -----",
921 				mci);
922 			printheader = false;
923 		}
924 
925 		(void) sm_strlcpy(buf, shortenstring(q->q_paddr, MAXSHORTSTR),
926 				  sizeof buf);
927 		putline(buf, mci);
928 		if (q->q_alias != NULL)
929 		{
930 			(void) sm_snprintf(buf, sizeof buf,
931 				"    (expanded from: %s)",
932 				shortenstring(q->q_alias->q_paddr,
933 					      MAXSHORTSTR));
934 			putline(buf, mci);
935 		}
936 	}
937 	if (!printheader)
938 		putline("", mci);
939 
940 	/* successful delivery notifications */
941 	printheader = true;
942 	for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
943 	{
944 		if (QS_IS_BADADDR(q->q_state) ||
945 		    !bitset(QPRIMARY, q->q_flags) ||
946 		    bitset(QBYNDELAY, q->q_flags) ||
947 		    bitset(QDELAYED, q->q_flags))
948 			continue;
949 		else if (bitset(QBYNRELAY, q->q_flags))
950 			p = "Deliver-By notify: relayed";
951 		else if (bitset(QBYTRACE, q->q_flags))
952 			p = "Deliver-By trace: relayed";
953 		else if (!bitset(QPINGONSUCCESS, q->q_flags))
954 			continue;
955 		else if (bitset(QRELAYED, q->q_flags))
956 			p = "relayed to non-DSN-aware mailer";
957 		else if (bitset(QDELIVERED, q->q_flags))
958 		{
959 			if (bitset(QEXPANDED, q->q_flags))
960 				p = "successfully delivered to mailing list";
961 			else
962 				p = "successfully delivered to mailbox";
963 		}
964 		else if (bitset(QEXPANDED, q->q_flags))
965 			p = "expanded by alias";
966 		else
967 			continue;
968 
969 		if (printheader)
970 		{
971 			putline("   ----- The following addresses had successful delivery notifications -----",
972 				mci);
973 			printheader = false;
974 		}
975 
976 		(void) sm_snprintf(buf, sizeof buf, "%s  (%s)",
977 			 shortenstring(q->q_paddr, MAXSHORTSTR), p);
978 		putline(buf, mci);
979 		if (q->q_alias != NULL)
980 		{
981 			(void) sm_snprintf(buf, sizeof buf,
982 				"    (expanded from: %s)",
983 				shortenstring(q->q_alias->q_paddr,
984 					      MAXSHORTSTR));
985 			putline(buf, mci);
986 		}
987 	}
988 	if (!printheader)
989 		putline("", mci);
990 
991 	/*
992 	**  Output transcript of errors
993 	*/
994 
995 	(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
996 	if (e->e_parent->e_xfp == NULL)
997 	{
998 		putline("   ----- Transcript of session is unavailable -----\n",
999 			mci);
1000 	}
1001 	else
1002 	{
1003 		printheader = true;
1004 		(void) bfrewind(e->e_parent->e_xfp);
1005 		if (e->e_xfp != NULL)
1006 			(void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
1007 		while (sm_io_fgets(e->e_parent->e_xfp, SM_TIME_DEFAULT, buf,
1008 				   sizeof buf) != NULL)
1009 		{
1010 			if (printheader)
1011 				putline("   ----- Transcript of session follows -----\n",
1012 					mci);
1013 			printheader = false;
1014 			putline(buf, mci);
1015 		}
1016 	}
1017 	errno = 0;
1018 
1019 #if DSN
1020 	/*
1021 	**  Output machine-readable version.
1022 	*/
1023 
1024 	if (e->e_msgboundary != NULL)
1025 	{
1026 		putline("", mci);
1027 		(void) sm_strlcpyn(buf, sizeof buf, 2, "--", e->e_msgboundary);
1028 		putline(buf, mci);
1029 		putline("Content-Type: message/delivery-status", mci);
1030 		putline("", mci);
1031 
1032 		/*
1033 		**  Output per-message information.
1034 		*/
1035 
1036 		/* original envelope id from MAIL FROM: line */
1037 		if (e->e_parent->e_envid != NULL)
1038 		{
1039 			(void) sm_snprintf(buf, sizeof buf,
1040 					"Original-Envelope-Id: %.800s",
1041 					xuntextify(e->e_parent->e_envid));
1042 			putline(buf, mci);
1043 		}
1044 
1045 		/* Reporting-MTA: is us (required) */
1046 		(void) sm_snprintf(buf, sizeof buf,
1047 				   "Reporting-MTA: dns; %.800s", MyHostName);
1048 		putline(buf, mci);
1049 
1050 		/* DSN-Gateway: not relevant since we are not translating */
1051 
1052 		/* Received-From-MTA: shows where we got this message from */
1053 		if (RealHostName != NULL)
1054 		{
1055 			/* XXX use $s for type? */
1056 			if (e->e_parent->e_from.q_mailer == NULL ||
1057 			    (p = e->e_parent->e_from.q_mailer->m_mtatype) == NULL)
1058 				p = "dns";
1059 			(void) sm_snprintf(buf, sizeof buf,
1060 					"Received-From-MTA: %s; %.800s",
1061 					p, RealHostName);
1062 			putline(buf, mci);
1063 		}
1064 
1065 		/* Arrival-Date: -- when it arrived here */
1066 		(void) sm_strlcpyn(buf, sizeof buf, 2, "Arrival-Date: ",
1067 				arpadate(ctime(&e->e_parent->e_ctime)));
1068 		putline(buf, mci);
1069 
1070 		/* Deliver-By-Date: -- when it should have been delivered */
1071 		if (IS_DLVR_BY(e->e_parent))
1072 		{
1073 			time_t dbyd;
1074 
1075 			dbyd = e->e_parent->e_ctime + e->e_parent->e_deliver_by;
1076 			(void) sm_strlcpyn(buf, sizeof buf, 2,
1077 					"Deliver-By-Date: ",
1078 					arpadate(ctime(&dbyd)));
1079 			putline(buf, mci);
1080 		}
1081 
1082 		/*
1083 		**  Output per-address information.
1084 		*/
1085 
1086 		for (q = e->e_parent->e_sendqueue; q != NULL; q = q->q_next)
1087 		{
1088 			char *action;
1089 
1090 			if (QS_IS_BADADDR(q->q_state))
1091 			{
1092 				/* RFC 1891, 6.2.6 (b) */
1093 				if (bitset(QHASNOTIFY, q->q_flags) &&
1094 				    !bitset(QPINGONFAILURE, q->q_flags))
1095 					continue;
1096 				action = "failed";
1097 			}
1098 			else if (!bitset(QPRIMARY, q->q_flags))
1099 				continue;
1100 			else if (bitset(QDELIVERED, q->q_flags))
1101 			{
1102 				if (bitset(QEXPANDED, q->q_flags))
1103 					action = "delivered (to mailing list)";
1104 				else
1105 					action = "delivered (to mailbox)";
1106 			}
1107 			else if (bitset(QRELAYED, q->q_flags))
1108 				action = "relayed (to non-DSN-aware mailer)";
1109 			else if (bitset(QEXPANDED, q->q_flags))
1110 				action = "expanded (to multi-recipient alias)";
1111 			else if (bitset(QDELAYED, q->q_flags))
1112 				action = "delayed";
1113 			else if (bitset(QBYTRACE, q->q_flags))
1114 				action = "relayed (Deliver-By trace mode)";
1115 			else if (bitset(QBYNDELAY, q->q_flags))
1116 				action = "delayed (Deliver-By notify mode)";
1117 			else if (bitset(QBYNRELAY, q->q_flags))
1118 				action = "relayed (Deliver-By notify mode)";
1119 			else
1120 				continue;
1121 
1122 			putline("", mci);
1123 
1124 			/* Original-Recipient: -- passed from on high */
1125 			if (q->q_orcpt != NULL)
1126 			{
1127 				(void) sm_snprintf(buf, sizeof buf,
1128 						"Original-Recipient: %.800s",
1129 						q->q_orcpt);
1130 				putline(buf, mci);
1131 			}
1132 
1133 			/* Figure out actual recipient */
1134 			actual[0] = '\0';
1135 			if (q->q_user[0] != '\0')
1136 			{
1137 				if (q->q_mailer != NULL &&
1138 				    q->q_mailer->m_addrtype != NULL)
1139 					p = q->q_mailer->m_addrtype;
1140 				else
1141 					p = "rfc822";
1142 
1143 				if (sm_strcasecmp(p, "rfc822") == 0 &&
1144 				    strchr(q->q_user, '@') == NULL)
1145 				{
1146 					(void) sm_snprintf(actual,
1147 							   sizeof actual,
1148 							   "%s; %.700s@%.100s",
1149 							   p, q->q_user,
1150 							   MyHostName);
1151 				}
1152 				else
1153 				{
1154 					(void) sm_snprintf(actual,
1155 							   sizeof actual,
1156 							   "%s; %.800s",
1157 							   p, q->q_user);
1158 				}
1159 			}
1160 
1161 			/* Final-Recipient: -- the name from the RCPT command */
1162 			if (q->q_finalrcpt == NULL)
1163 			{
1164 				/* should never happen */
1165 				sm_syslog(LOG_ERR, e->e_id,
1166 					  "returntosender: q_finalrcpt is NULL");
1167 
1168 				/* try to fall back to the actual recipient */
1169 				if (actual[0] != '\0')
1170 					q->q_finalrcpt = sm_rpool_strdup_x(e->e_rpool,
1171 									   actual);
1172 			}
1173 
1174 			if (q->q_finalrcpt != NULL)
1175 			{
1176 				(void) sm_snprintf(buf, sizeof buf,
1177 						   "Final-Recipient: %s",
1178 						   q->q_finalrcpt);
1179 				putline(buf, mci);
1180 			}
1181 
1182 			/* X-Actual-Recipient: -- the real problem address */
1183 			if (actual[0] != '\0' &&
1184 			    q->q_finalrcpt != NULL &&
1185 #if _FFR_PRIV_NOACTUALRECIPIENT
1186 			    !bitset(PRIV_NOACTUALRECIPIENT, PrivacyFlags) &&
1187 #endif /* _FFR_PRIV_NOACTUALRECIPIENT */
1188 			    strcmp(actual, q->q_finalrcpt) != 0)
1189 			{
1190 				(void) sm_snprintf(buf, sizeof buf,
1191 						   "X-Actual-Recipient: %s",
1192 						   actual);
1193 				putline(buf, mci);
1194 			}
1195 
1196 			/* Action: -- what happened? */
1197 			(void) sm_strlcpyn(buf, sizeof buf, 2, "Action: ",
1198 				action);
1199 			putline(buf, mci);
1200 
1201 			/* Status: -- what _really_ happened? */
1202 			if (q->q_status != NULL)
1203 				p = q->q_status;
1204 			else if (QS_IS_BADADDR(q->q_state))
1205 				p = "5.0.0";
1206 			else if (QS_IS_QUEUEUP(q->q_state))
1207 				p = "4.0.0";
1208 			else
1209 				p = "2.0.0";
1210 			(void) sm_strlcpyn(buf, sizeof buf, 2, "Status: ", p);
1211 			putline(buf, mci);
1212 
1213 			/* Remote-MTA: -- who was I talking to? */
1214 			if (q->q_statmta != NULL)
1215 			{
1216 				if (q->q_mailer == NULL ||
1217 				    (p = q->q_mailer->m_mtatype) == NULL)
1218 					p = "dns";
1219 				(void) sm_snprintf(buf, sizeof buf,
1220 						"Remote-MTA: %s; %.800s",
1221 						p, q->q_statmta);
1222 				p = &buf[strlen(buf) - 1];
1223 				if (*p == '.')
1224 					*p = '\0';
1225 				putline(buf, mci);
1226 			}
1227 
1228 			/* Diagnostic-Code: -- actual result from other end */
1229 			if (q->q_rstatus != NULL)
1230 			{
1231 				p = q->q_mailer->m_diagtype;
1232 				if (p == NULL)
1233 					p = "smtp";
1234 				(void) sm_snprintf(buf, sizeof buf,
1235 						"Diagnostic-Code: %s; %.800s",
1236 						p, q->q_rstatus);
1237 				putline(buf, mci);
1238 			}
1239 
1240 			/* Last-Attempt-Date: -- fine granularity */
1241 			if (q->q_statdate == (time_t) 0L)
1242 				q->q_statdate = curtime();
1243 			(void) sm_strlcpyn(buf, sizeof buf, 2,
1244 					"Last-Attempt-Date: ",
1245 					arpadate(ctime(&q->q_statdate)));
1246 			putline(buf, mci);
1247 
1248 			/* Will-Retry-Until: -- for delayed messages only */
1249 			if (QS_IS_QUEUEUP(q->q_state))
1250 			{
1251 				time_t xdate;
1252 
1253 				xdate = e->e_parent->e_ctime +
1254 					TimeOuts.to_q_return[e->e_parent->e_timeoutclass];
1255 				(void) sm_strlcpyn(buf, sizeof buf, 2,
1256 					 "Will-Retry-Until: ",
1257 					 arpadate(ctime(&xdate)));
1258 				putline(buf, mci);
1259 			}
1260 		}
1261 	}
1262 #endif /* DSN */
1263 
1264 	/*
1265 	**  Output text of original message
1266 	*/
1267 
1268 	putline("", mci);
1269 	if (bitset(EF_HAS_DF, e->e_parent->e_flags))
1270 	{
1271 		sendbody = !bitset(EF_NO_BODY_RETN, e->e_parent->e_flags) &&
1272 			   !bitset(EF_NO_BODY_RETN, e->e_flags);
1273 
1274 		if (e->e_msgboundary == NULL)
1275 		{
1276 			if (sendbody)
1277 				putline("   ----- Original message follows -----\n", mci);
1278 			else
1279 				putline("   ----- Message header follows -----\n", mci);
1280 		}
1281 		else
1282 		{
1283 			(void) sm_strlcpyn(buf, sizeof buf, 2, "--",
1284 					e->e_msgboundary);
1285 
1286 			putline(buf, mci);
1287 			(void) sm_strlcpyn(buf, sizeof buf, 2, "Content-Type: ",
1288 					sendbody ? "message/rfc822"
1289 						 : "text/rfc822-headers");
1290 			putline(buf, mci);
1291 
1292 			p = hvalue("Content-Transfer-Encoding",
1293 				   e->e_parent->e_header);
1294 			if (p != NULL && sm_strcasecmp(p, "binary") != 0)
1295 				p = NULL;
1296 			if (p == NULL &&
1297 			    bitset(EF_HAS8BIT, e->e_parent->e_flags))
1298 				p = "8bit";
1299 			if (p != NULL)
1300 			{
1301 				(void) sm_snprintf(buf, sizeof buf,
1302 						"Content-Transfer-Encoding: %s",
1303 						p);
1304 				putline(buf, mci);
1305 			}
1306 		}
1307 		putline("", mci);
1308 		save_errno = errno;
1309 		putheader(mci, e->e_parent->e_header, e->e_parent, M87F_OUTER);
1310 		errno = save_errno;
1311 		if (sendbody)
1312 			putbody(mci, e->e_parent, e->e_msgboundary);
1313 		else if (e->e_msgboundary == NULL)
1314 		{
1315 			putline("", mci);
1316 			putline("   ----- Message body suppressed -----", mci);
1317 		}
1318 	}
1319 	else if (e->e_msgboundary == NULL)
1320 	{
1321 		putline("  ----- No message was collected -----\n", mci);
1322 	}
1323 
1324 	if (e->e_msgboundary != NULL)
1325 	{
1326 		putline("", mci);
1327 		(void) sm_strlcpyn(buf, sizeof buf, 3, "--", e->e_msgboundary,
1328 				   "--");
1329 		putline(buf, mci);
1330 	}
1331 	putline("", mci);
1332 	(void) sm_io_flush(mci->mci_out, SM_TIME_DEFAULT);
1333 
1334 	/*
1335 	**  Cleanup and exit
1336 	*/
1337 
1338 	if (errno != 0)
1339 		syserr("errbody: I/O error");
1340 }
1341 /*
1342 **  SMTPTODSN -- convert SMTP to DSN status code
1343 **
1344 **	Parameters:
1345 **		smtpstat -- the smtp status code (e.g., 550).
1346 **
1347 **	Returns:
1348 **		The DSN version of the status code.
1349 **
1350 **	Storage Management:
1351 **		smtptodsn() returns a pointer to a character string literal,
1352 **		which will remain valid forever, and thus does not need to
1353 **		be copied.  Current code relies on this property.
1354 */
1355 
1356 char *
1357 smtptodsn(smtpstat)
1358 	int smtpstat;
1359 {
1360 	if (smtpstat < 0)
1361 		return "4.4.2";
1362 
1363 	switch (smtpstat)
1364 	{
1365 	  case 450:	/* Req mail action not taken: mailbox unavailable */
1366 		return "4.2.0";
1367 
1368 	  case 451:	/* Req action aborted: local error in processing */
1369 		return "4.3.0";
1370 
1371 	  case 452:	/* Req action not taken: insufficient sys storage */
1372 		return "4.3.1";
1373 
1374 	  case 500:	/* Syntax error, command unrecognized */
1375 		return "5.5.2";
1376 
1377 	  case 501:	/* Syntax error in parameters or arguments */
1378 		return "5.5.4";
1379 
1380 	  case 502:	/* Command not implemented */
1381 		return "5.5.1";
1382 
1383 	  case 503:	/* Bad sequence of commands */
1384 		return "5.5.1";
1385 
1386 	  case 504:	/* Command parameter not implemented */
1387 		return "5.5.4";
1388 
1389 	  case 550:	/* Req mail action not taken: mailbox unavailable */
1390 		return "5.2.0";
1391 
1392 	  case 551:	/* User not local; please try <...> */
1393 		return "5.1.6";
1394 
1395 	  case 552:	/* Req mail action aborted: exceeded storage alloc */
1396 		return "5.2.2";
1397 
1398 	  case 553:	/* Req action not taken: mailbox name not allowed */
1399 		return "5.1.0";
1400 
1401 	  case 554:	/* Transaction failed */
1402 		return "5.0.0";
1403 	}
1404 
1405 	if ((smtpstat / 100) == 2)
1406 		return "2.0.0";
1407 	if ((smtpstat / 100) == 4)
1408 		return "4.0.0";
1409 	return "5.0.0";
1410 }
1411 /*
1412 **  XTEXTIFY -- take regular text and turn it into DSN-style xtext
1413 **
1414 **	Parameters:
1415 **		t -- the text to convert.
1416 **		taboo -- additional characters that must be encoded.
1417 **
1418 **	Returns:
1419 **		The xtext-ified version of the same string.
1420 */
1421 
1422 char *
1423 xtextify(t, taboo)
1424 	register char *t;
1425 	char *taboo;
1426 {
1427 	register char *p;
1428 	int l;
1429 	int nbogus;
1430 	static char *bp = NULL;
1431 	static int bplen = 0;
1432 
1433 	if (taboo == NULL)
1434 		taboo = "";
1435 
1436 	/* figure out how long this xtext will have to be */
1437 	nbogus = l = 0;
1438 	for (p = t; *p != '\0'; p++)
1439 	{
1440 		register int c = (*p & 0xff);
1441 
1442 		/* ASCII dependence here -- this is the way the spec words it */
1443 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' ||
1444 		    strchr(taboo, c) != NULL)
1445 			nbogus++;
1446 		l++;
1447 	}
1448 	if (nbogus < 0)
1449 	{
1450 		/* since nbogus is ssize_t and wrapped, 2 * size_t would wrap */
1451 		syserr("!xtextify string too long");
1452 	}
1453 	if (nbogus == 0)
1454 		return t;
1455 	l += nbogus * 2 + 1;
1456 
1457 	/* now allocate space if necessary for the new string */
1458 	if (l > bplen)
1459 	{
1460 		if (bp != NULL)
1461 			sm_free(bp); /* XXX */
1462 		bp = sm_pmalloc_x(l);
1463 		bplen = l;
1464 	}
1465 
1466 	/* ok, copy the text with byte expansion */
1467 	for (p = bp; *t != '\0'; )
1468 	{
1469 		register int c = (*t++ & 0xff);
1470 
1471 		/* ASCII dependence here -- this is the way the spec words it */
1472 		if (c < '!' || c > '~' || c == '+' || c == '\\' || c == '(' ||
1473 		    strchr(taboo, c) != NULL)
1474 		{
1475 			*p++ = '+';
1476 			*p++ = "0123456789ABCDEF"[c >> 4];
1477 			*p++ = "0123456789ABCDEF"[c & 0xf];
1478 		}
1479 		else
1480 			*p++ = c;
1481 	}
1482 	*p = '\0';
1483 	return bp;
1484 }
1485 /*
1486 **  XUNTEXTIFY -- take xtext and turn it into plain text
1487 **
1488 **	Parameters:
1489 **		t -- the xtextified text.
1490 **
1491 **	Returns:
1492 **		The decoded text.  No attempt is made to deal with
1493 **		null strings in the resulting text.
1494 */
1495 
1496 char *
1497 xuntextify(t)
1498 	register char *t;
1499 {
1500 	register char *p;
1501 	int l;
1502 	static char *bp = NULL;
1503 	static int bplen = 0;
1504 
1505 	/* heuristic -- if no plus sign, just return the input */
1506 	if (strchr(t, '+') == NULL)
1507 		return t;
1508 
1509 	/* xtext is always longer than decoded text */
1510 	l = strlen(t);
1511 	if (l > bplen)
1512 	{
1513 		if (bp != NULL)
1514 			sm_free(bp); /* XXX */
1515 		bp = xalloc(l);
1516 		bplen = l;
1517 	}
1518 
1519 	/* ok, copy the text with byte compression */
1520 	for (p = bp; *t != '\0'; t++)
1521 	{
1522 		register int c = *t & 0xff;
1523 
1524 		if (c != '+')
1525 		{
1526 			*p++ = c;
1527 			continue;
1528 		}
1529 
1530 		c = *++t & 0xff;
1531 		if (!isascii(c) || !isxdigit(c))
1532 		{
1533 			/* error -- first digit is not hex */
1534 			usrerr("bogus xtext: +%c", c);
1535 			t--;
1536 			continue;
1537 		}
1538 		if (isdigit(c))
1539 			c -= '0';
1540 		else if (isupper(c))
1541 			c -= 'A' - 10;
1542 		else
1543 			c -= 'a' - 10;
1544 		*p = c << 4;
1545 
1546 		c = *++t & 0xff;
1547 		if (!isascii(c) || !isxdigit(c))
1548 		{
1549 			/* error -- second digit is not hex */
1550 			usrerr("bogus xtext: +%x%c", *p >> 4, c);
1551 			t--;
1552 			continue;
1553 		}
1554 		if (isdigit(c))
1555 			c -= '0';
1556 		else if (isupper(c))
1557 			c -= 'A' - 10;
1558 		else
1559 			c -= 'a' - 10;
1560 		*p++ |= c;
1561 	}
1562 	*p = '\0';
1563 	return bp;
1564 }
1565 /*
1566 **  XTEXTOK -- check if a string is legal xtext
1567 **
1568 **	Xtext is used in Delivery Status Notifications.  The spec was
1569 **	taken from RFC 1891, ``SMTP Service Extension for Delivery
1570 **	Status Notifications''.
1571 **
1572 **	Parameters:
1573 **		s -- the string to check.
1574 **
1575 **	Returns:
1576 **		true -- if 's' is legal xtext.
1577 **		false -- if it has any illegal characters in it.
1578 */
1579 
1580 bool
1581 xtextok(s)
1582 	char *s;
1583 {
1584 	int c;
1585 
1586 	while ((c = *s++) != '\0')
1587 	{
1588 		if (c == '+')
1589 		{
1590 			c = *s++;
1591 			if (!isascii(c) || !isxdigit(c))
1592 				return false;
1593 			c = *s++;
1594 			if (!isascii(c) || !isxdigit(c))
1595 				return false;
1596 		}
1597 		else if (c < '!' || c > '~' || c == '=')
1598 			return false;
1599 	}
1600 	return true;
1601 }
1602 /*
1603 **  PRUNEROUTE -- prune an RFC-822 source route
1604 **
1605 **	Trims down a source route to the last internet-registered hop.
1606 **	This is encouraged by RFC 1123 section 5.3.3.
1607 **
1608 **	Parameters:
1609 **		addr -- the address
1610 **
1611 **	Returns:
1612 **		true -- address was modified
1613 **		false -- address could not be pruned
1614 **
1615 **	Side Effects:
1616 **		modifies addr in-place
1617 */
1618 
1619 static bool
1620 pruneroute(addr)
1621 	char *addr;
1622 {
1623 #if NAMED_BIND
1624 	char *start, *at, *comma;
1625 	char c;
1626 	int braclev;
1627 	int rcode;
1628 	int i;
1629 	char hostbuf[BUFSIZ];
1630 	char *mxhosts[MAXMXHOSTS + 1];
1631 
1632 	/* check to see if this is really a route-addr */
1633 	if (*addr != '<' || addr[1] != '@' || addr[strlen(addr) - 1] != '>')
1634 		return false;
1635 
1636 	/*
1637 	**  Can't simply find the first ':' is the address might be in the
1638 	**  form:  "<@[IPv6:::1]:user@host>" and the first ':' in inside
1639 	**  the IPv6 address.
1640 	*/
1641 
1642 	start = addr;
1643 	braclev = 0;
1644 	while (*start != '\0')
1645 	{
1646 		if (*start == ':' && braclev <= 0)
1647 			break;
1648 		else if (*start == '[')
1649 			braclev++;
1650 		else if (*start == ']' && braclev > 0)
1651 			braclev--;
1652 		start++;
1653 	}
1654 	if (braclev > 0 || *start != ':')
1655 		return false;
1656 
1657 	at = strrchr(addr, '@');
1658 	if (at == NULL || at < start)
1659 		return false;
1660 
1661 	/* slice off the angle brackets */
1662 	i = strlen(at + 1);
1663 	if (i >= sizeof hostbuf)
1664 		return false;
1665 	(void) sm_strlcpy(hostbuf, at + 1, sizeof hostbuf);
1666 	hostbuf[i - 1] = '\0';
1667 
1668 	while (start != NULL)
1669 	{
1670 		if (getmxrr(hostbuf, mxhosts, NULL, false,
1671 			    &rcode, true, NULL) > 0)
1672 		{
1673 			(void) sm_strlcpy(addr + 1, start + 1,
1674 					  strlen(addr) - 1);
1675 			return true;
1676 		}
1677 		c = *start;
1678 		*start = '\0';
1679 		comma = strrchr(addr, ',');
1680 		if (comma != NULL && comma[1] == '@' &&
1681 		    strlen(comma + 2) < sizeof hostbuf)
1682 			(void) sm_strlcpy(hostbuf, comma + 2, sizeof hostbuf);
1683 		else
1684 			comma = NULL;
1685 		*start = c;
1686 		start = comma;
1687 	}
1688 #endif /* NAMED_BIND */
1689 	return false;
1690 }
1691