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