xref: /freebsd/contrib/sendmail/src/deliver.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Copyright (c) 1998-2001 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 #ifndef lint
15 static char id[] = "@(#)$Id: deliver.c,v 8.600.2.1.2.81 2001/05/23 02:15:42 ca Exp $";
16 #endif /* ! lint */
17 
18 #include <sendmail.h>
19 
20 
21 #if HASSETUSERCONTEXT
22 # include <login_cap.h>
23 #endif /* HASSETUSERCONTEXT */
24 
25 #if STARTTLS || (SASL && SFIO)
26 # include "sfsasl.h"
27 #endif /* STARTTLS || (SASL && SFIO) */
28 
29 static int	deliver __P((ENVELOPE *, ADDRESS *));
30 static void	dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));
31 static void	mailfiletimeout __P((void));
32 static void	markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int, bool));
33 static int	parse_hostsignature __P((char *, char **, MAILER *));
34 static void	sendenvelope __P((ENVELOPE *, int));
35 static char	*hostsignature __P((MAILER *, char *));
36 
37 #if SMTP
38 # if STARTTLS
39 static int	starttls __P((MAILER *, MCI *, ENVELOPE *));
40 # endif /* STARTTLS */
41 #endif /* SMTP */
42 
43 /*
44 **  SENDALL -- actually send all the messages.
45 **
46 **	Parameters:
47 **		e -- the envelope to send.
48 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
49 **			the current e->e_sendmode.
50 **
51 **	Returns:
52 **		none.
53 **
54 **	Side Effects:
55 **		Scans the send lists and sends everything it finds.
56 **		Delivers any appropriate error messages.
57 **		If we are running in a non-interactive mode, takes the
58 **			appropriate action.
59 */
60 
61 void
62 sendall(e, mode)
63 	ENVELOPE *e;
64 	int mode;
65 {
66 	register ADDRESS *q;
67 	char *owner;
68 	int otherowners;
69 	int save_errno;
70 	register ENVELOPE *ee;
71 	ENVELOPE *splitenv = NULL;
72 	int oldverbose = Verbose;
73 	bool somedeliveries = FALSE, expensive = FALSE;
74 	pid_t pid;
75 
76 	/*
77 	**  If this message is to be discarded, don't bother sending
78 	**  the message at all.
79 	*/
80 
81 	if (bitset(EF_DISCARD, e->e_flags))
82 	{
83 		if (tTd(13, 1))
84 			dprintf("sendall: discarding id %s\n", e->e_id);
85 		e->e_flags |= EF_CLRQUEUE;
86 		if (LogLevel > 4)
87 			sm_syslog(LOG_INFO, e->e_id, "discarded");
88 		markstats(e, NULL, TRUE);
89 		return;
90 	}
91 
92 	/*
93 	**  If we have had global, fatal errors, don't bother sending
94 	**  the message at all if we are in SMTP mode.  Local errors
95 	**  (e.g., a single address failing) will still cause the other
96 	**  addresses to be sent.
97 	*/
98 
99 	if (bitset(EF_FATALERRS, e->e_flags) &&
100 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
101 	{
102 		e->e_flags |= EF_CLRQUEUE;
103 		return;
104 	}
105 
106 	/* determine actual delivery mode */
107 	if (mode == SM_DEFAULT)
108 	{
109 		mode = e->e_sendmode;
110 		if (mode != SM_VERIFY && mode != SM_DEFER &&
111 		    shouldqueue(e->e_msgpriority, e->e_ctime))
112 			mode = SM_QUEUE;
113 	}
114 
115 	if (tTd(13, 1))
116 	{
117 		dprintf("\n===== SENDALL: mode %c, id %s, e_from ",
118 			mode, e->e_id);
119 		printaddr(&e->e_from, FALSE);
120 		dprintf("\te_flags = ");
121 		printenvflags(e);
122 		dprintf("sendqueue:\n");
123 		printaddr(e->e_sendqueue, TRUE);
124 	}
125 
126 	/*
127 	**  Do any preprocessing necessary for the mode we are running.
128 	**	Check to make sure the hop count is reasonable.
129 	**	Delete sends to the sender in mailing lists.
130 	*/
131 
132 	CurEnv = e;
133 	if (tTd(62, 1))
134 		checkfds(NULL);
135 
136 	if (e->e_hopcount > MaxHopCount)
137 	{
138 		char *recip;
139 
140 		if (e->e_sendqueue != NULL &&
141 		    e->e_sendqueue->q_paddr != NULL)
142 			recip = e->e_sendqueue->q_paddr;
143 		else
144 			recip = "(nobody)";
145 
146 		errno = 0;
147 #if QUEUE
148 		queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
149 #endif /* QUEUE */
150 		e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
151 		ExitStat = EX_UNAVAILABLE;
152 		syserr("554 5.4.6 Too many hops %d (%d max): from %s via %s, to %s",
153 		       e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
154 		       RealHostName == NULL ? "localhost" : RealHostName,
155 		       recip);
156 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
157 		{
158 			if (QS_IS_DEAD(q->q_state))
159 				continue;
160 			q->q_state = QS_BADADDR;
161 			q->q_status = "5.4.6";
162 			q->q_rstatus = "554 5.4.6 Too many hops";
163 		}
164 		return;
165 	}
166 
167 	/*
168 	**  Do sender deletion.
169 	**
170 	**	If the sender should be queued up, skip this.
171 	**	This can happen if the name server is hosed when you
172 	**	are trying to send mail.  The result is that the sender
173 	**	is instantiated in the queue as a recipient.
174 	*/
175 
176 	if (!bitset(EF_METOO, e->e_flags) &&
177 	    !QS_IS_QUEUEUP(e->e_from.q_state))
178 	{
179 		if (tTd(13, 5))
180 		{
181 			dprintf("sendall: QS_SENDER ");
182 			printaddr(&e->e_from, FALSE);
183 		}
184 		e->e_from.q_state = QS_SENDER;
185 		(void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
186 	}
187 
188 	/*
189 	**  Handle alias owners.
190 	**
191 	**	We scan up the q_alias chain looking for owners.
192 	**	We discard owners that are the same as the return path.
193 	*/
194 
195 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
196 	{
197 		register struct address *a;
198 
199 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
200 			continue;
201 		if (a != NULL)
202 			q->q_owner = a->q_owner;
203 
204 		if (q->q_owner != NULL &&
205 		    !QS_IS_DEAD(q->q_state) &&
206 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
207 			q->q_owner = NULL;
208 	}
209 
210 	if (tTd(13, 25))
211 	{
212 		dprintf("\nAfter first owner pass, sendq =\n");
213 		printaddr(e->e_sendqueue, TRUE);
214 	}
215 
216 	owner = "";
217 	otherowners = 1;
218 	while (owner != NULL && otherowners > 0)
219 	{
220 		if (tTd(13, 28))
221 			dprintf("owner = \"%s\", otherowners = %d\n",
222 				owner, otherowners);
223 		owner = NULL;
224 		otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;
225 
226 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
227 		{
228 			if (tTd(13, 30))
229 			{
230 				dprintf("Checking ");
231 				printaddr(q, FALSE);
232 			}
233 			if (QS_IS_DEAD(q->q_state))
234 			{
235 				if (tTd(13, 30))
236 					dprintf("    ... QS_IS_DEAD\n");
237 				continue;
238 			}
239 			if (tTd(13, 29) && !tTd(13, 30))
240 			{
241 				dprintf("Checking ");
242 				printaddr(q, FALSE);
243 			}
244 
245 			if (q->q_owner != NULL)
246 			{
247 				if (owner == NULL)
248 				{
249 					if (tTd(13, 40))
250 						dprintf("    ... First owner = \"%s\"\n",
251 							q->q_owner);
252 					owner = q->q_owner;
253 				}
254 				else if (owner != q->q_owner)
255 				{
256 					if (strcmp(owner, q->q_owner) == 0)
257 					{
258 						if (tTd(13, 40))
259 							dprintf("    ... Same owner = \"%s\"\n",
260 								owner);
261 
262 						/* make future comparisons cheap */
263 						q->q_owner = owner;
264 					}
265 					else
266 					{
267 						if (tTd(13, 40))
268 							dprintf("    ... Another owner \"%s\"\n",
269 								q->q_owner);
270 						otherowners++;
271 					}
272 					owner = q->q_owner;
273 				}
274 				else if (tTd(13, 40))
275 					dprintf("    ... Same owner = \"%s\"\n",
276 						owner);
277 			}
278 			else
279 			{
280 				if (tTd(13, 40))
281 					dprintf("    ... Null owner\n");
282 				otherowners++;
283 			}
284 
285 			if (QS_IS_BADADDR(q->q_state))
286 			{
287 				if (tTd(13, 30))
288 					dprintf("    ... QS_IS_BADADDR\n");
289 				continue;
290 			}
291 
292 			if (QS_IS_QUEUEUP(q->q_state))
293 			{
294 				MAILER *m = q->q_mailer;
295 
296 				/*
297 				**  If we have temporary address failures
298 				**  (e.g., dns failure) and a fallback MX is
299 				**  set, send directly to the fallback MX host.
300 				*/
301 
302 				if (FallBackMX != NULL &&
303 				    !wordinclass(FallBackMX, 'w') &&
304 				    mode != SM_VERIFY &&
305 				    (strcmp(m->m_mailer, "[IPC]") == 0 ||
306 				     strcmp(m->m_mailer, "[TCP]") == 0) &&
307 				    m->m_argv[0] != NULL &&
308 				    (strcmp(m->m_argv[0], "TCP") == 0 ||
309 				     strcmp(m->m_argv[0], "IPC") == 0))
310 				{
311 					int len;
312 					char *p;
313 
314 					if (tTd(13, 30))
315 						dprintf("    ... FallBackMX\n");
316 
317 					len = strlen(FallBackMX) + 3;
318 					p = xalloc(len);
319 					snprintf(p, len, "[%s]", FallBackMX);
320 					q->q_state = QS_OK;
321 					q->q_host = p;
322 				}
323 				else
324 				{
325 					if (tTd(13, 30))
326 						dprintf("    ... QS_IS_QUEUEUP\n");
327 					continue;
328 				}
329 			}
330 
331 			/*
332 			**  If this mailer is expensive, and if we don't
333 			**  want to make connections now, just mark these
334 			**  addresses and return.  This is useful if we
335 			**  want to batch connections to reduce load.  This
336 			**  will cause the messages to be queued up, and a
337 			**  daemon will come along to send the messages later.
338 			*/
339 
340 			if (NoConnect && !Verbose &&
341 			    bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
342 			{
343 				if (tTd(13, 30))
344 					dprintf("    ... expensive\n");
345 				q->q_state = QS_QUEUEUP;
346 				expensive = TRUE;
347 			}
348 			else if (bitnset(M_HOLD, q->q_mailer->m_flags) &&
349 				 QueueLimitId == NULL &&
350 				 QueueLimitSender == NULL &&
351 				 QueueLimitRecipient == NULL)
352 			{
353 				if (tTd(13, 30))
354 					dprintf("    ... hold\n");
355 				q->q_state = QS_QUEUEUP;
356 				expensive = TRUE;
357 			}
358 			else
359 			{
360 				if (tTd(13, 30))
361 					dprintf("    ... deliverable\n");
362 				somedeliveries = TRUE;
363 			}
364 		}
365 
366 		if (owner != NULL && otherowners > 0)
367 		{
368 			/*
369 			**  Split this envelope into two.
370 			*/
371 
372 			ee = (ENVELOPE *) xalloc(sizeof *ee);
373 			*ee = *e;
374 			ee->e_message = NULL;
375 			ee->e_id = NULL;
376 			assign_queueid(ee);
377 
378 			if (tTd(13, 1))
379 				dprintf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
380 					e->e_id, ee->e_id, owner, otherowners);
381 
382 			ee->e_header = copyheader(e->e_header);
383 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
384 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
385 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
386 			ee->e_flags |= EF_NORECEIPT;
387 			setsender(owner, ee, NULL, '\0', TRUE);
388 			if (tTd(13, 5))
389 			{
390 				dprintf("sendall(split): QS_SENDER ");
391 				printaddr(&ee->e_from, FALSE);
392 			}
393 			ee->e_from.q_state = QS_SENDER;
394 			ee->e_dfp = NULL;
395 			ee->e_lockfp = NULL;
396 			ee->e_xfp = NULL;
397 			ee->e_queuedir = e->e_queuedir;
398 			ee->e_errormode = EM_MAIL;
399 			ee->e_sibling = splitenv;
400 			ee->e_statmsg = NULL;
401 			splitenv = ee;
402 
403 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
404 			{
405 				if (q->q_owner == owner)
406 				{
407 					q->q_state = QS_CLONED;
408 					if (tTd(13, 6))
409 						dprintf("\t... stripping %s from original envelope\n",
410 							q->q_paddr);
411 				}
412 			}
413 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
414 			{
415 				if (q->q_owner != owner)
416 				{
417 					q->q_state = QS_CLONED;
418 					if (tTd(13, 6))
419 						dprintf("\t... dropping %s from cloned envelope\n",
420 							q->q_paddr);
421 				}
422 				else
423 				{
424 					/* clear DSN parameters */
425 					q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
426 					q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
427 					if (tTd(13, 6))
428 						dprintf("\t... moving %s to cloned envelope\n",
429 							q->q_paddr);
430 				}
431 			}
432 
433 			if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
434 				dup_queue_file(e, ee, 'd');
435 
436 			/*
437 			**  Give the split envelope access to the parent
438 			**  transcript file for errors obtained while
439 			**  processing the recipients (done before the
440 			**  envelope splitting).
441 			*/
442 
443 			if (e->e_xfp != NULL)
444 				ee->e_xfp = bfdup(e->e_xfp);
445 
446 			/* failed to dup e->e_xfp, start a new transcript */
447 			if (ee->e_xfp == NULL)
448 				openxscript(ee);
449 
450 			if (mode != SM_VERIFY && LogLevel > 4)
451 				sm_syslog(LOG_INFO, ee->e_id,
452 					  "clone %s, owner=%s",
453 					  e->e_id, owner);
454 		}
455 	}
456 
457 	if (owner != NULL)
458 	{
459 		setsender(owner, e, NULL, '\0', TRUE);
460 		if (tTd(13, 5))
461 		{
462 			dprintf("sendall(owner): QS_SENDER ");
463 			printaddr(&e->e_from, FALSE);
464 		}
465 		e->e_from.q_state = QS_SENDER;
466 		e->e_errormode = EM_MAIL;
467 		e->e_flags |= EF_NORECEIPT;
468 		e->e_flags &= ~EF_FATALERRS;
469 	}
470 
471 	/* if nothing to be delivered, just queue up everything */
472 	if (!somedeliveries && mode != SM_QUEUE && mode != SM_DEFER &&
473 	    mode != SM_VERIFY)
474 	{
475 		time_t now = curtime();
476 
477 		if (tTd(13, 29))
478 			dprintf("No deliveries: auto-queuing\n");
479 		mode = SM_QUEUE;
480 
481 		/* treat this as a delivery in terms of counting tries */
482 		e->e_dtime = now;
483 		if (!expensive)
484 			e->e_ntries++;
485 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
486 		{
487 			ee->e_dtime = now;
488 			if (!expensive)
489 				ee->e_ntries++;
490 		}
491 	}
492 
493 #if QUEUE
494 	if ((mode == SM_QUEUE || mode == SM_DEFER || mode == SM_FORK ||
495 	     (mode != SM_VERIFY && SuperSafe)) &&
496 	    (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
497 	{
498 		/*
499 		**  Be sure everything is instantiated in the queue.
500 		**  Split envelopes first in case the machine crashes.
501 		**  If the original were done first, we may lose
502 		**  recipients.
503 		*/
504 
505 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
506 			queueup(ee, mode == SM_QUEUE || mode == SM_DEFER);
507 		queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
508 	}
509 #endif /* QUEUE */
510 
511 	if (tTd(62, 10))
512 		checkfds("after envelope splitting");
513 
514 	/*
515 	**  If we belong in background, fork now.
516 	*/
517 
518 	if (tTd(13, 20))
519 	{
520 		dprintf("sendall: final mode = %c\n", mode);
521 		if (tTd(13, 21))
522 		{
523 			dprintf("\n================ Final Send Queue(s) =====================\n");
524 			dprintf("\n  *** Envelope %s, e_from=%s ***\n",
525 				e->e_id, e->e_from.q_paddr);
526 			printaddr(e->e_sendqueue, TRUE);
527 			for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
528 			{
529 				dprintf("\n  *** Envelope %s, e_from=%s ***\n",
530 					ee->e_id, ee->e_from.q_paddr);
531 				printaddr(ee->e_sendqueue, TRUE);
532 			}
533 			dprintf("==========================================================\n\n");
534 		}
535 	}
536 	switch (mode)
537 	{
538 	  case SM_VERIFY:
539 		Verbose = 2;
540 		break;
541 
542 	  case SM_QUEUE:
543 	  case SM_DEFER:
544 #if HASFLOCK
545   queueonly:
546 #endif /* HASFLOCK */
547 		if (e->e_nrcpts > 0)
548 			e->e_flags |= EF_INQUEUE;
549 		dropenvelope(e, splitenv != NULL);
550 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
551 		{
552 			if (ee->e_nrcpts > 0)
553 				ee->e_flags |= EF_INQUEUE;
554 			dropenvelope(ee, FALSE);
555 		}
556 		return;
557 
558 	  case SM_FORK:
559 		if (e->e_xfp != NULL)
560 			(void) fflush(e->e_xfp);
561 
562 #if !HASFLOCK
563 		/*
564 		**  Since fcntl locking has the interesting semantic that
565 		**  the lock is owned by a process, not by an open file
566 		**  descriptor, we have to flush this to the queue, and
567 		**  then restart from scratch in the child.
568 		*/
569 
570 		{
571 			/* save id for future use */
572 			char *qid = e->e_id;
573 
574 			/* now drop the envelope in the parent */
575 			e->e_flags |= EF_INQUEUE;
576 			dropenvelope(e, splitenv != NULL);
577 
578 			/* arrange to reacquire lock after fork */
579 			e->e_id = qid;
580 		}
581 
582 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
583 		{
584 			/* save id for future use */
585 			char *qid = ee->e_id;
586 
587 			/* drop envelope in parent */
588 			ee->e_flags |= EF_INQUEUE;
589 			dropenvelope(ee, FALSE);
590 
591 			/* and save qid for reacquisition */
592 			ee->e_id = qid;
593 		}
594 
595 #endif /* !HASFLOCK */
596 
597 		/*
598 		**  Since the delivery may happen in a child and the parent
599 		**  does not wait, the parent may close the maps thereby
600 		**  removing any shared memory used by the map.  Therefore,
601 		**  close the maps now so the child will dynamically open
602 		**  them if necessary.
603 		*/
604 
605 		closemaps();
606 
607 		pid = fork();
608 		if (pid < 0)
609 		{
610 			syserr("deliver: fork 1");
611 #if HASFLOCK
612 			goto queueonly;
613 #else /* HASFLOCK */
614 			e->e_id = NULL;
615 			for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
616 				ee->e_id = NULL;
617 			return;
618 #endif /* HASFLOCK */
619 		}
620 		else if (pid > 0)
621 		{
622 #if HASFLOCK
623 			/* be sure we leave the temp files to our child */
624 			/* close any random open files in the envelope */
625 			closexscript(e);
626 			if (e->e_dfp != NULL)
627 				(void) bfclose(e->e_dfp);
628 			e->e_dfp = NULL;
629 			e->e_flags &= ~EF_HAS_DF;
630 
631 			/* can't call unlockqueue to avoid unlink of xfp */
632 			if (e->e_lockfp != NULL)
633 				(void) fclose(e->e_lockfp);
634 			else
635 				syserr("%s: sendall: null lockfp", e->e_id);
636 			e->e_lockfp = NULL;
637 #endif /* HASFLOCK */
638 
639 			/* make sure the parent doesn't own the envelope */
640 			e->e_id = NULL;
641 
642 			/* catch intermediate zombie */
643 			(void) waitfor(pid);
644 			return;
645 		}
646 
647 		/* Reset global flags */
648 		RestartRequest = NULL;
649 		ShutdownRequest = NULL;
650 		PendingSignal = 0;
651 
652 		/*
653 		**  Since we have accepted responsbility for the message,
654 		**  change the SIGTERM handler.  intsig() (the old handler)
655 		**  would remove the envelope if this was a command line
656 		**  message submission.
657 		*/
658 
659 		(void) setsignal(SIGTERM, SIG_DFL);
660 
661 		/* double fork to avoid zombies */
662 		pid = fork();
663 		if (pid > 0)
664 			exit(EX_OK);
665 		save_errno = errno;
666 
667 		/* be sure we are immune from the terminal */
668 		disconnect(2, e);
669 		clearstats();
670 
671 		/* prevent parent from waiting if there was an error */
672 		if (pid < 0)
673 		{
674 			errno = save_errno;
675 			syserr("deliver: fork 2");
676 #if HASFLOCK
677 			e->e_flags |= EF_INQUEUE;
678 #else /* HASFLOCK */
679 			e->e_id = NULL;
680 #endif /* HASFLOCK */
681 			finis(TRUE, ExitStat);
682 		}
683 
684 		/* be sure to give error messages in child */
685 		QuickAbort = FALSE;
686 
687 		/*
688 		**  Close any cached connections.
689 		**
690 		**	We don't send the QUIT protocol because the parent
691 		**	still knows about the connection.
692 		**
693 		**	This should only happen when delivering an error
694 		**	message.
695 		*/
696 
697 		mci_flush(FALSE, NULL);
698 
699 #if HASFLOCK
700 		break;
701 #else /* HASFLOCK */
702 
703 		/*
704 		**  Now reacquire and run the various queue files.
705 		*/
706 
707 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
708 		{
709 			ENVELOPE *sibling = ee->e_sibling;
710 
711 			(void) dowork(ee->e_queuedir, ee->e_id,
712 				      FALSE, FALSE, ee);
713 			ee->e_sibling = sibling;
714 		}
715 		(void) dowork(e->e_queuedir, e->e_id,
716 			      FALSE, FALSE, e);
717 		finis(TRUE, ExitStat);
718 #endif /* HASFLOCK */
719 	}
720 
721 	sendenvelope(e, mode);
722 	dropenvelope(e, TRUE);
723 	for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
724 	{
725 		CurEnv = ee;
726 		if (mode != SM_VERIFY)
727 			openxscript(ee);
728 		sendenvelope(ee, mode);
729 		dropenvelope(ee, TRUE);
730 	}
731 	CurEnv = e;
732 
733 	Verbose = oldverbose;
734 	if (mode == SM_FORK)
735 		finis(TRUE, ExitStat);
736 }
737 
738 static void
739 sendenvelope(e, mode)
740 	register ENVELOPE *e;
741 	int mode;
742 {
743 	register ADDRESS *q;
744 	bool didany;
745 
746 	if (tTd(13, 10))
747 		dprintf("sendenvelope(%s) e_flags=0x%lx\n",
748 			e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
749 			e->e_flags);
750 	if (LogLevel > 80)
751 		sm_syslog(LOG_DEBUG, e->e_id,
752 			  "sendenvelope, flags=0x%lx",
753 			  e->e_flags);
754 
755 	/*
756 	**  If we have had global, fatal errors, don't bother sending
757 	**  the message at all if we are in SMTP mode.  Local errors
758 	**  (e.g., a single address failing) will still cause the other
759 	**  addresses to be sent.
760 	*/
761 
762 	if (bitset(EF_FATALERRS, e->e_flags) &&
763 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
764 	{
765 		e->e_flags |= EF_CLRQUEUE;
766 		return;
767 	}
768 
769 	/* Don't attempt deliveries if we want to bounce now */
770 	if (!bitset(EF_RESPONSE, e->e_flags) &&
771 	    TimeOuts.to_q_return[e->e_timeoutclass] == NOW)
772 		return;
773 
774 	/*
775 	**  Run through the list and send everything.
776 	**
777 	**	Set EF_GLOBALERRS so that error messages during delivery
778 	**	result in returned mail.
779 	*/
780 
781 	e->e_nsent = 0;
782 	e->e_flags |= EF_GLOBALERRS;
783 
784 	define(macid("{envid}", NULL), e->e_envid, e);
785 	define(macid("{bodytype}", NULL), e->e_bodytype, e);
786 	didany = FALSE;
787 
788 	/* now run through the queue */
789 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
790 	{
791 #if XDEBUG
792 		char wbuf[MAXNAME + 20];
793 
794 		(void) snprintf(wbuf, sizeof wbuf, "sendall(%.*s)",
795 			MAXNAME, q->q_paddr);
796 		checkfd012(wbuf);
797 #endif /* XDEBUG */
798 		if (mode == SM_VERIFY)
799 		{
800 			e->e_to = q->q_paddr;
801 			if (QS_IS_SENDABLE(q->q_state))
802 			{
803 				if (q->q_host != NULL && q->q_host[0] != '\0')
804 					message("deliverable: mailer %s, host %s, user %s",
805 						q->q_mailer->m_name,
806 						q->q_host,
807 						q->q_user);
808 				else
809 					message("deliverable: mailer %s, user %s",
810 						q->q_mailer->m_name,
811 						q->q_user);
812 			}
813 		}
814 		else if (QS_IS_OK(q->q_state))
815 		{
816 #if QUEUE
817 			/*
818 			**  Checkpoint the send list every few addresses
819 			*/
820 
821 			if (CheckpointInterval > 0 &&
822 			    e->e_nsent >= CheckpointInterval)
823 			{
824 				queueup(e, FALSE);
825 				e->e_nsent = 0;
826 			}
827 #endif /* QUEUE */
828 			(void) deliver(e, q);
829 			didany = TRUE;
830 		}
831 	}
832 	if (didany)
833 	{
834 		e->e_dtime = curtime();
835 		e->e_ntries++;
836 	}
837 
838 #if XDEBUG
839 	checkfd012("end of sendenvelope");
840 #endif /* XDEBUG */
841 }
842 /*
843 **  DUP_QUEUE_FILE -- duplicate a queue file into a split queue
844 **
845 **	Parameters:
846 **		e -- the existing envelope
847 **		ee -- the new envelope
848 **		type -- the queue file type (e.g., 'd')
849 **
850 **	Returns:
851 **		none
852 */
853 
854 static void
855 dup_queue_file(e, ee, type)
856 	struct envelope *e, *ee;
857 	int type;
858 {
859 	char f1buf[MAXPATHLEN], f2buf[MAXPATHLEN];
860 
861 	ee->e_dfp = NULL;
862 	ee->e_xfp = NULL;
863 
864 	/*
865 	**  Make sure both are in the same directory.
866 	*/
867 
868 	snprintf(f1buf, sizeof f1buf, "%s", queuename(e, type));
869 	snprintf(f2buf, sizeof f2buf, "%s", queuename(ee, type));
870 	if (link(f1buf, f2buf) < 0)
871 	{
872 		int save_errno = errno;
873 
874 		syserr("sendall: link(%s, %s)", f1buf, f2buf);
875 		if (save_errno == EEXIST)
876 		{
877 			if (unlink(f2buf) < 0)
878 			{
879 				syserr("!sendall: unlink(%s): permanent",
880 					f2buf);
881 				/* NOTREACHED */
882 			}
883 			if (link(f1buf, f2buf) < 0)
884 			{
885 				syserr("!sendall: link(%s, %s): permanent",
886 					f1buf, f2buf);
887 				/* NOTREACHED */
888 			}
889 		}
890 	}
891 }
892 /*
893 **  DOFORK -- do a fork, retrying a couple of times on failure.
894 **
895 **	This MUST be a macro, since after a vfork we are running
896 **	two processes on the same stack!!!
897 **
898 **	Parameters:
899 **		none.
900 **
901 **	Returns:
902 **		From a macro???  You've got to be kidding!
903 **
904 **	Side Effects:
905 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
906 **			pid of child in parent, zero in child.
907 **			-1 on unrecoverable error.
908 **
909 **	Notes:
910 **		I'm awfully sorry this looks so awful.  That's
911 **		vfork for you.....
912 */
913 
914 #define NFORKTRIES	5
915 
916 #ifndef FORK
917 # define FORK	fork
918 #endif /* ! FORK */
919 
920 #define DOFORK(fORKfN) \
921 {\
922 	register int i;\
923 \
924 	for (i = NFORKTRIES; --i >= 0; )\
925 	{\
926 		pid = fORKfN();\
927 		if (pid >= 0)\
928 			break;\
929 		if (i > 0)\
930 			(void) sleep((unsigned) NFORKTRIES - i);\
931 	}\
932 }
933 /*
934 **  DOFORK -- simple fork interface to DOFORK.
935 **
936 **	Parameters:
937 **		none.
938 **
939 **	Returns:
940 **		pid of child in parent.
941 **		zero in child.
942 **		-1 on error.
943 **
944 **	Side Effects:
945 **		returns twice, once in parent and once in child.
946 */
947 
948 pid_t
949 dofork()
950 {
951 	register pid_t pid = -1;
952 
953 	DOFORK(fork);
954 	return pid;
955 }
956 /*
957 **  DELIVER -- Deliver a message to a list of addresses.
958 **
959 **	This routine delivers to everyone on the same host as the
960 **	user on the head of the list.  It is clever about mailers
961 **	that don't handle multiple users.  It is NOT guaranteed
962 **	that it will deliver to all these addresses however -- so
963 **	deliver should be called once for each address on the
964 **	list.
965 **
966 **	Parameters:
967 **		e -- the envelope to deliver.
968 **		firstto -- head of the address list to deliver to.
969 **
970 **	Returns:
971 **		zero -- successfully delivered.
972 **		else -- some failure, see ExitStat for more info.
973 **
974 **	Side Effects:
975 **		The standard input is passed off to someone.
976 */
977 
978 #ifndef NO_UID
979 # define NO_UID		-1
980 #endif /* ! NO_UID */
981 #ifndef NO_GID
982 # define NO_GID		-1
983 #endif /* ! NO_GID */
984 
985 static int
986 deliver(e, firstto)
987 	register ENVELOPE *e;
988 	ADDRESS *firstto;
989 {
990 	char *host;			/* host being sent to */
991 	char *user;			/* user being sent to */
992 	char **pvp;
993 	register char **mvp;
994 	register char *p;
995 	register MAILER *m;		/* mailer for this recipient */
996 	ADDRESS *volatile ctladdr;
997 	ADDRESS *volatile contextaddr = NULL;
998 	register MCI *volatile mci;
999 	register ADDRESS *to = firstto;
1000 	volatile bool clever = FALSE;	/* running user smtp to this mailer */
1001 	ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
1002 	int rcode;			/* response code */
1003 	int lmtp_rcode = EX_OK;
1004 	int nummxhosts = 0;		/* number of MX hosts available */
1005 	int hostnum = 0;		/* current MX host index */
1006 	char *firstsig;			/* signature of firstto */
1007 	pid_t pid = -1;
1008 	char *volatile curhost;
1009 	register u_short port = 0;
1010 #if NETUNIX
1011 	char *mux_path = NULL;		/* path to UNIX domain socket */
1012 #endif /* NETUNIX */
1013 	time_t xstart;
1014 	bool suidwarn;
1015 	bool anyok;			/* at least one address was OK */
1016 	bool goodmxfound = FALSE;	/* at least one MX was OK */
1017 	bool ovr;
1018 #if _FFR_DYNAMIC_TOBUF
1019 	int strsize;
1020 	int rcptcount;
1021 	static int tobufsize = 0;
1022 	static char *tobuf = NULL;
1023 #else /* _FFR_DYNAMIC_TOBUF */
1024 	char tobuf[TOBUFSIZE];		/* text line of to people */
1025 #endif /* _FFR_DYNAMIC_TOBUF */
1026 	int mpvect[2];
1027 	int rpvect[2];
1028 	char *mxhosts[MAXMXHOSTS + 1];
1029 	char *pv[MAXPV + 1];
1030 	char buf[MAXNAME + 1];
1031 	char rpathbuf[MAXNAME + 1];	/* translated return path */
1032 
1033 	errno = 0;
1034 	if (!QS_IS_OK(to->q_state))
1035 		return 0;
1036 
1037 	suidwarn = geteuid() == 0;
1038 
1039 	m = to->q_mailer;
1040 	host = to->q_host;
1041 	CurEnv = e;			/* just in case */
1042 	e->e_statmsg = NULL;
1043 #if SMTP
1044 	SmtpError[0] = '\0';
1045 #endif /* SMTP */
1046 	xstart = curtime();
1047 
1048 	if (tTd(10, 1))
1049 		dprintf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
1050 			e->e_id, m->m_name, host, to->q_user);
1051 	if (tTd(10, 100))
1052 		printopenfds(FALSE);
1053 
1054 	/*
1055 	**  Clear $&{client_*} macros if this is a bounce message to
1056 	**  prevent rejection by check_compat ruleset.
1057 	*/
1058 
1059 	if (bitset(EF_RESPONSE, e->e_flags))
1060 	{
1061 		define(macid("{client_name}", NULL), "", e);
1062 		define(macid("{client_addr}", NULL), "", e);
1063 		define(macid("{client_port}", NULL), "", e);
1064 	}
1065 
1066 	/*
1067 	**  Do initial argv setup.
1068 	**	Insert the mailer name.  Notice that $x expansion is
1069 	**	NOT done on the mailer name.  Then, if the mailer has
1070 	**	a picky -f flag, we insert it as appropriate.  This
1071 	**	code does not check for 'pv' overflow; this places a
1072 	**	manifest lower limit of 4 for MAXPV.
1073 	**		The from address rewrite is expected to make
1074 	**		the address relative to the other end.
1075 	*/
1076 
1077 	/* rewrite from address, using rewriting rules */
1078 	rcode = EX_OK;
1079 	if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
1080 		p = e->e_sender;
1081 	else
1082 		p = e->e_from.q_paddr;
1083 	p = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
1084 	if (strlen(p) >= (SIZE_T) sizeof rpathbuf)
1085 	{
1086 		p = shortenstring(p, MAXSHORTSTR);
1087 		syserr("remotename: huge return %s", p);
1088 	}
1089 	snprintf(rpathbuf, sizeof rpathbuf, "%s", p);
1090 	define('g', rpathbuf, e);		/* translated return path */
1091 	define('h', host, e);			/* to host */
1092 	Errors = 0;
1093 	pvp = pv;
1094 	*pvp++ = m->m_argv[0];
1095 
1096 	/* insert -f or -r flag as appropriate */
1097 	if (FromFlag &&
1098 	    (bitnset(M_FOPT, m->m_flags) ||
1099 	     bitnset(M_ROPT, m->m_flags)))
1100 	{
1101 		if (bitnset(M_FOPT, m->m_flags))
1102 			*pvp++ = "-f";
1103 		else
1104 			*pvp++ = "-r";
1105 		*pvp++ = newstr(rpathbuf);
1106 	}
1107 
1108 	/*
1109 	**  Append the other fixed parts of the argv.  These run
1110 	**  up to the first entry containing "$u".  There can only
1111 	**  be one of these, and there are only a few more slots
1112 	**  in the pv after it.
1113 	*/
1114 
1115 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
1116 	{
1117 		/* can't use strchr here because of sign extension problems */
1118 		while (*p != '\0')
1119 		{
1120 			if ((*p++ & 0377) == MACROEXPAND)
1121 			{
1122 				if (*p == 'u')
1123 					break;
1124 			}
1125 		}
1126 
1127 		if (*p != '\0')
1128 			break;
1129 
1130 		/* this entry is safe -- go ahead and process it */
1131 		expand(*mvp, buf, sizeof buf, e);
1132 		*pvp++ = newstr(buf);
1133 		if (pvp >= &pv[MAXPV - 3])
1134 		{
1135 			syserr("554 5.3.5 Too many parameters to %s before $u",
1136 			       pv[0]);
1137 			return -1;
1138 		}
1139 	}
1140 
1141 	/*
1142 	**  If we have no substitution for the user name in the argument
1143 	**  list, we know that we must supply the names otherwise -- and
1144 	**  SMTP is the answer!!
1145 	*/
1146 
1147 	if (*mvp == NULL)
1148 	{
1149 		/* running LMTP or SMTP */
1150 #if SMTP
1151 		clever = TRUE;
1152 		*pvp = NULL;
1153 #else /* SMTP */
1154 		/* oops!  we don't implement SMTP */
1155 		syserr("554 5.3.5 SMTP style mailer not implemented");
1156 		return EX_SOFTWARE;
1157 #endif /* SMTP */
1158 	}
1159 	else if (bitnset(M_LMTP, m->m_flags))
1160 	{
1161 		/* not running LMTP */
1162 		sm_syslog(LOG_ERR, NULL,
1163 			  "Warning: mailer %s: LMTP flag (F=z) turned off",
1164 			  m->m_name);
1165 		clrbitn(M_LMTP, m->m_flags);
1166 	}
1167 
1168 	/*
1169 	**  At this point *mvp points to the argument with $u.  We
1170 	**  run through our address list and append all the addresses
1171 	**  we can.  If we run out of space, do not fret!  We can
1172 	**  always send another copy later.
1173 	*/
1174 
1175 #if _FFR_DYNAMIC_TOBUF
1176 	e->e_to = NULL;
1177 	strsize = 2;
1178 	rcptcount = 0;
1179 #else /* _FFR_DYNAMIC_TOBUF */
1180 	tobuf[0] = '\0';
1181 	e->e_to = tobuf;
1182 #endif /* _FFR_DYNAMIC_TOBUF */
1183 
1184 	ctladdr = NULL;
1185 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host);
1186 	for (; to != NULL; to = to->q_next)
1187 	{
1188 		/* avoid sending multiple recipients to dumb mailers */
1189 #if _FFR_DYNAMIC_TOBUF
1190 		if (tochain != NULL && !bitnset(M_MUSER, m->m_flags))
1191 			break;
1192 #else /* _FFR_DYNAMIC_TOBUF */
1193 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
1194 			break;
1195 #endif /* _FFR_DYNAMIC_TOBUF */
1196 
1197 		/* if already sent or not for this host, don't send */
1198 		if (!QS_IS_OK(to->q_state) ||
1199 		    to->q_mailer != firstto->q_mailer ||
1200 		    strcmp(hostsignature(to->q_mailer, to->q_host),
1201 			   firstsig) != 0)
1202 			continue;
1203 
1204 		/* avoid overflowing tobuf */
1205 #if _FFR_DYNAMIC_TOBUF
1206 		strsize += strlen(to->q_paddr) + 1;
1207 		if (!clever && strsize > TOBUFSIZE)
1208 			break;
1209 
1210 		if (++rcptcount > to->q_mailer->m_maxrcpt)
1211 			break;
1212 #else /* _FFR_DYNAMIC_TOBUF */
1213 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
1214 			break;
1215 #endif /* _FFR_DYNAMIC_TOBUF */
1216 
1217 		if (tTd(10, 1))
1218 		{
1219 			dprintf("\nsend to ");
1220 			printaddr(to, FALSE);
1221 		}
1222 
1223 		/* compute effective uid/gid when sending */
1224 		if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
1225 			contextaddr = ctladdr = getctladdr(to);
1226 
1227 		if (tTd(10, 2))
1228 		{
1229 			dprintf("ctladdr=");
1230 			printaddr(ctladdr, FALSE);
1231 		}
1232 
1233 		user = to->q_user;
1234 		e->e_to = to->q_paddr;
1235 
1236 		/*
1237 		**  Check to see that these people are allowed to
1238 		**  talk to each other.
1239 		**  Check also for overflow of e_msgsize.
1240 		*/
1241 
1242 		if (m->m_maxsize != 0 &&
1243 		    (e->e_msgsize > m->m_maxsize || e->e_msgsize < 0))
1244 		{
1245 			e->e_flags |= EF_NO_BODY_RETN;
1246 			if (bitnset(M_LOCALMAILER, to->q_mailer->m_flags))
1247 				to->q_status = "5.2.3";
1248 			else
1249 				to->q_status = "5.3.4";
1250 			/* set to->q_rstatus = NULL; or to the following? */
1251 			usrerrenh(to->q_status,
1252 				  "552 Message is too large; %ld bytes max",
1253 				  m->m_maxsize);
1254 			markfailure(e, to, NULL, EX_UNAVAILABLE, FALSE);
1255 			giveresponse(EX_UNAVAILABLE, to->q_status, m,
1256 				     NULL, ctladdr, xstart, e);
1257 			continue;
1258 		}
1259 #if NAMED_BIND
1260 		SM_SET_H_ERRNO(0);
1261 #endif /* NAMED_BIND */
1262 
1263 		ovr = TRUE;
1264 		/* do config file checking of compatibility */
1265 		rcode = rscheck("check_compat", e->e_from.q_paddr, to->q_paddr,
1266 				e, TRUE, TRUE, 4, NULL);
1267 		if (rcode == EX_OK)
1268 		{
1269 			/* do in-code checking if not discarding */
1270 			if (!bitset(EF_DISCARD, e->e_flags))
1271 			{
1272 				rcode = checkcompat(to, e);
1273 				ovr = FALSE;
1274 			}
1275 		}
1276 		if (rcode != EX_OK)
1277 		{
1278 			markfailure(e, to, NULL, rcode, ovr);
1279 			giveresponse(rcode, to->q_status, m,
1280 				     NULL, ctladdr, xstart, e);
1281 			continue;
1282 		}
1283 		if (bitset(EF_DISCARD, e->e_flags))
1284 		{
1285 			if (tTd(10, 5))
1286 			{
1287 				dprintf("deliver: discarding recipient ");
1288 				printaddr(to, FALSE);
1289 			}
1290 
1291 			/* pretend the message was sent */
1292 			/* XXX should we log something here? */
1293 			to->q_state = QS_DISCARDED;
1294 
1295 			/*
1296 			**  Remove discard bit to prevent discard of
1297 			**  future recipients.  This is safe because the
1298 			**  true "global discard" has been handled before
1299 			**  we get here.
1300 			*/
1301 
1302 			e->e_flags &= ~EF_DISCARD;
1303 			continue;
1304 		}
1305 
1306 		/*
1307 		**  Strip quote bits from names if the mailer is dumb
1308 		**	about them.
1309 		*/
1310 
1311 		if (bitnset(M_STRIPQ, m->m_flags))
1312 		{
1313 			stripquotes(user);
1314 			stripquotes(host);
1315 		}
1316 
1317 		/* hack attack -- delivermail compatibility */
1318 		if (m == ProgMailer && *user == '|')
1319 			user++;
1320 
1321 		/*
1322 		**  If an error message has already been given, don't
1323 		**	bother to send to this address.
1324 		**
1325 		**	>>>>>>>>>> This clause assumes that the local mailer
1326 		**	>> NOTE >> cannot do any further aliasing; that
1327 		**	>>>>>>>>>> function is subsumed by sendmail.
1328 		*/
1329 
1330 		if (!QS_IS_OK(to->q_state))
1331 			continue;
1332 
1333 		/*
1334 		**  See if this user name is "special".
1335 		**	If the user name has a slash in it, assume that this
1336 		**	is a file -- send it off without further ado.  Note
1337 		**	that this type of addresses is not processed along
1338 		**	with the others, so we fudge on the To person.
1339 		*/
1340 
1341 		if (strcmp(m->m_mailer, "[FILE]") == 0)
1342 		{
1343 			define('u', user, e);	/* to user */
1344 			p = to->q_home;
1345 			if (p == NULL && ctladdr != NULL)
1346 				p = ctladdr->q_home;
1347 			define('z', p, e);	/* user's home */
1348 			expand(m->m_argv[1], buf, sizeof buf, e);
1349 			if (strlen(buf) > 0)
1350 				rcode = mailfile(buf, m, ctladdr, SFF_CREAT, e);
1351 			else
1352 			{
1353 				syserr("empty filename specification for mailer %s",
1354 				       m->m_name);
1355 				rcode = EX_CONFIG;
1356 			}
1357 			giveresponse(rcode, to->q_status, m, NULL,
1358 				     ctladdr, xstart, e);
1359 			markfailure(e, to, NULL, rcode, TRUE);
1360 			e->e_nsent++;
1361 			if (rcode == EX_OK)
1362 			{
1363 				to->q_state = QS_SENT;
1364 				if (bitnset(M_LOCALMAILER, m->m_flags) &&
1365 				    bitset(QPINGONSUCCESS, to->q_flags))
1366 				{
1367 					to->q_flags |= QDELIVERED;
1368 					to->q_status = "2.1.5";
1369 					fprintf(e->e_xfp, "%s... Successfully delivered\n",
1370 						to->q_paddr);
1371 				}
1372 			}
1373 			to->q_statdate = curtime();
1374 			markstats(e, to, FALSE);
1375 			continue;
1376 		}
1377 
1378 		/*
1379 		**  Address is verified -- add this user to mailer
1380 		**  argv, and add it to the print list of recipients.
1381 		*/
1382 
1383 		/* link together the chain of recipients */
1384 		to->q_tchain = tochain;
1385 		tochain = to;
1386 
1387 #if _FFR_DYNAMIC_TOBUF
1388 		e->e_to = "[CHAIN]";
1389 #else /* _FFR_DYNAMIC_TOBUF */
1390 		/* create list of users for error messages */
1391 		(void) strlcat(tobuf, ",", sizeof tobuf);
1392 		(void) strlcat(tobuf, to->q_paddr, sizeof tobuf);
1393 #endif /* _FFR_DYNAMIC_TOBUF */
1394 
1395 		define('u', user, e);		/* to user */
1396 		p = to->q_home;
1397 		if (p == NULL && ctladdr != NULL)
1398 			p = ctladdr->q_home;
1399 		define('z', p, e);	/* user's home */
1400 
1401 		/* set the ${dsn_notify} macro if applicable */
1402 		if (bitset(QHASNOTIFY, to->q_flags))
1403 		{
1404 			char notify[MAXLINE];
1405 
1406 			notify[0] = '\0';
1407 			if (bitset(QPINGONSUCCESS, to->q_flags))
1408 				(void) strlcat(notify, "SUCCESS,",
1409 					       sizeof notify);
1410 			if (bitset(QPINGONFAILURE, to->q_flags))
1411 				(void) strlcat(notify, "FAILURE,",
1412 					       sizeof notify);
1413 			if (bitset(QPINGONDELAY, to->q_flags))
1414 				(void) strlcat(notify, "DELAY,", sizeof notify);
1415 
1416 			/* Set to NEVER or drop trailing comma */
1417 			if (notify[0] == '\0')
1418 				(void) strlcat(notify, "NEVER", sizeof notify);
1419 			else
1420 				notify[strlen(notify) - 1] = '\0';
1421 
1422 			define(macid("{dsn_notify}", NULL), newstr(notify), e);
1423 		}
1424 		else
1425 			define(macid("{dsn_notify}", NULL), NULL, e);
1426 
1427 		/*
1428 		**  Expand out this user into argument list.
1429 		*/
1430 
1431 		if (!clever)
1432 		{
1433 			expand(*mvp, buf, sizeof buf, e);
1434 			*pvp++ = newstr(buf);
1435 			if (pvp >= &pv[MAXPV - 2])
1436 			{
1437 				/* allow some space for trailing parms */
1438 				break;
1439 			}
1440 		}
1441 	}
1442 
1443 	/* see if any addresses still exist */
1444 #if _FFR_DYNAMIC_TOBUF
1445 	if (tochain == NULL)
1446 #else /* _FFR_DYNAMIC_TOBUF */
1447 	if (tobuf[0] == '\0')
1448 #endif /* _FFR_DYNAMIC_TOBUF */
1449 	{
1450 		define('g', (char *) NULL, e);
1451 		e->e_to = NULL;
1452 		return 0;
1453 	}
1454 
1455 	/* print out messages as full list */
1456 #if _FFR_DYNAMIC_TOBUF
1457 	{
1458 		int l = 1;
1459 		char *tobufptr;
1460 
1461 		for (to = tochain; to != NULL; to = to->q_tchain)
1462 			l += strlen(to->q_paddr) + 1;
1463 		if (l < TOBUFSIZE)
1464 			l = TOBUFSIZE;
1465 		if (l > tobufsize)
1466 		{
1467 			if (tobuf != NULL)
1468 				sm_free(tobuf);
1469 			tobufsize = l;
1470 			tobuf = xalloc(tobufsize);
1471 		}
1472 		tobufptr = tobuf;
1473 		*tobufptr = '\0';
1474 		for (to = tochain; to != NULL; to = to->q_tchain)
1475 		{
1476 			snprintf(tobufptr, tobufsize - (tobufptr - tobuf),
1477 				 ",%s", to->q_paddr);
1478 			tobufptr += strlen(tobufptr);
1479 		}
1480 	}
1481 #endif /* _FFR_DYNAMIC_TOBUF */
1482 	e->e_to = tobuf + 1;
1483 
1484 	/*
1485 	**  Fill out any parameters after the $u parameter.
1486 	*/
1487 
1488 	while (!clever && *++mvp != NULL)
1489 	{
1490 		expand(*mvp, buf, sizeof buf, e);
1491 		*pvp++ = newstr(buf);
1492 		if (pvp >= &pv[MAXPV])
1493 			syserr("554 5.3.0 deliver: pv overflow after $u for %s",
1494 			       pv[0]);
1495 	}
1496 	*pvp++ = NULL;
1497 
1498 	/*
1499 	**  Call the mailer.
1500 	**	The argument vector gets built, pipes
1501 	**	are created as necessary, and we fork & exec as
1502 	**	appropriate.
1503 	**	If we are running SMTP, we just need to clean up.
1504 	*/
1505 
1506 	/* XXX this seems a bit wierd */
1507 	if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
1508 	    bitset(QGOODUID, e->e_from.q_flags))
1509 		ctladdr = &e->e_from;
1510 
1511 #if NAMED_BIND
1512 	if (ConfigLevel < 2)
1513 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
1514 #endif /* NAMED_BIND */
1515 
1516 	if (tTd(11, 1))
1517 	{
1518 		dprintf("openmailer:");
1519 		printav(pv);
1520 	}
1521 	errno = 0;
1522 #if NAMED_BIND
1523 	SM_SET_H_ERRNO(0);
1524 #endif /* NAMED_BIND */
1525 
1526 	CurHostName = NULL;
1527 
1528 	/*
1529 	**  Deal with the special case of mail handled through an IPC
1530 	**  connection.
1531 	**	In this case we don't actually fork.  We must be
1532 	**	running SMTP for this to work.  We will return a
1533 	**	zero pid to indicate that we are running IPC.
1534 	**  We also handle a debug version that just talks to stdin/out.
1535 	*/
1536 
1537 	curhost = NULL;
1538 	SmtpPhase = NULL;
1539 	mci = NULL;
1540 
1541 #if XDEBUG
1542 	{
1543 		char wbuf[MAXLINE];
1544 
1545 		/* make absolutely certain 0, 1, and 2 are in use */
1546 		snprintf(wbuf, sizeof wbuf, "%s... openmailer(%s)",
1547 			shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1548 		checkfd012(wbuf);
1549 	}
1550 #endif /* XDEBUG */
1551 
1552 	/* check for 8-bit available */
1553 	if (bitset(EF_HAS8BIT, e->e_flags) &&
1554 	    bitnset(M_7BITS, m->m_flags) &&
1555 	    (bitset(EF_DONT_MIME, e->e_flags) ||
1556 	     !(bitset(MM_MIME8BIT, MimeMode) ||
1557 	       (bitset(EF_IS_MIME, e->e_flags) &&
1558 		bitset(MM_CVTMIME, MimeMode)))))
1559 	{
1560 		e->e_status = "5.6.3";
1561 		usrerrenh(e->e_status,
1562 		       "554 Cannot send 8-bit data to 7-bit destination");
1563 		rcode = EX_DATAERR;
1564 		goto give_up;
1565 	}
1566 
1567 	if (tTd(62, 8))
1568 		checkfds("before delivery");
1569 
1570 	/* check for Local Person Communication -- not for mortals!!! */
1571 	if (strcmp(m->m_mailer, "[LPC]") == 0)
1572 	{
1573 		mci = (MCI *) xalloc(sizeof *mci);
1574 		memset((char *) mci, '\0', sizeof *mci);
1575 		mci->mci_in = stdin;
1576 		mci->mci_out = stdout;
1577 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1578 		mci->mci_mailer = m;
1579 	}
1580 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
1581 		 strcmp(m->m_mailer, "[TCP]") == 0)
1582 	{
1583 #if DAEMON
1584 		register int i;
1585 
1586 		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1587 		{
1588 			syserr("null destination for %s mailer", m->m_mailer);
1589 			rcode = EX_CONFIG;
1590 			goto give_up;
1591 		}
1592 
1593 # if NETUNIX
1594 		if (strcmp(pv[0], "FILE") == 0)
1595 		{
1596 			curhost = CurHostName = "localhost";
1597 			mux_path = pv[1];
1598 		}
1599 		else
1600 # endif /* NETUNIX */
1601 		{
1602 			CurHostName = pv[1];
1603 			curhost = hostsignature(m, pv[1]);
1604 		}
1605 
1606 		if (curhost == NULL || curhost[0] == '\0')
1607 		{
1608 			syserr("null host signature for %s", pv[1]);
1609 			rcode = EX_CONFIG;
1610 			goto give_up;
1611 		}
1612 
1613 		if (!clever)
1614 		{
1615 			syserr("554 5.3.5 non-clever IPC");
1616 			rcode = EX_CONFIG;
1617 			goto give_up;
1618 		}
1619 		if (pv[2] != NULL
1620 # if NETUNIX
1621 		    && mux_path == NULL
1622 # endif /* NETUNIX */
1623 		    )
1624 		{
1625 			port = htons((u_short)atoi(pv[2]));
1626 			if (port == 0)
1627 			{
1628 # ifdef NO_GETSERVBYNAME
1629 				syserr("Invalid port number: %s", pv[2]);
1630 # else /* NO_GETSERVBYNAME */
1631 				struct servent *sp = getservbyname(pv[2], "tcp");
1632 
1633 				if (sp == NULL)
1634 					syserr("Service %s unknown", pv[2]);
1635 				else
1636 					port = sp->s_port;
1637 # endif /* NO_GETSERVBYNAME */
1638 			}
1639 		}
1640 
1641 		nummxhosts = parse_hostsignature(curhost, mxhosts, m);
1642 tryhost:
1643 		while (hostnum < nummxhosts)
1644 		{
1645 			char sep = ':';
1646 			char *endp;
1647 			static char hostbuf[MAXNAME + 1];
1648 
1649 # if NETINET6
1650 			if (*mxhosts[hostnum] == '[')
1651 			{
1652 				endp = strchr(mxhosts[hostnum] + 1, ']');
1653 				if (endp != NULL)
1654 					endp = strpbrk(endp + 1, ":,");
1655 			}
1656 			else
1657 				endp = strpbrk(mxhosts[hostnum], ":,");
1658 # else /* NETINET6 */
1659 			endp = strpbrk(mxhosts[hostnum], ":,");
1660 # endif /* NETINET6 */
1661 			if (endp != NULL)
1662 			{
1663 				sep = *endp;
1664 				*endp = '\0';
1665 			}
1666 
1667 			if (*mxhosts[hostnum] == '\0')
1668 			{
1669 				syserr("deliver: null host name in signature");
1670 				hostnum++;
1671 				if (endp != NULL)
1672 					*endp = sep;
1673 				continue;
1674 			}
1675 			(void) strlcpy(hostbuf, mxhosts[hostnum],
1676 				       sizeof hostbuf);
1677 			hostnum++;
1678 			if (endp != NULL)
1679 				*endp = sep;
1680 
1681 			/* see if we already know that this host is fried */
1682 			CurHostName = hostbuf;
1683 			mci = mci_get(hostbuf, m);
1684 			if (mci->mci_state != MCIS_CLOSED)
1685 			{
1686 				if (tTd(11, 1))
1687 				{
1688 					dprintf("openmailer: ");
1689 					mci_dump(mci, FALSE);
1690 				}
1691 				CurHostName = mci->mci_host;
1692 				message("Using cached %sSMTP connection to %s via %s...",
1693 					bitset(MCIF_ESMTP, mci->mci_flags) ? "E" : "",
1694 					hostbuf, m->m_name);
1695 				mci->mci_deliveries++;
1696 				break;
1697 			}
1698 			mci->mci_mailer = m;
1699 			if (mci->mci_exitstat != EX_OK)
1700 			{
1701 				if (mci->mci_exitstat == EX_TEMPFAIL)
1702 					goodmxfound = TRUE;
1703 				continue;
1704 			}
1705 
1706 			if (mci_lock_host(mci) != EX_OK)
1707 			{
1708 				mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
1709 				goodmxfound = TRUE;
1710 				continue;
1711 			}
1712 
1713 			/* try the connection */
1714 			sm_setproctitle(TRUE, e, "%s %s: %s",
1715 					qid_printname(e),
1716 					hostbuf, "user open");
1717 # if NETUNIX
1718 			if (mux_path != NULL)
1719 			{
1720 				message("Connecting to %s via %s...",
1721 					mux_path, m->m_name);
1722 				i = makeconnection_ds(mux_path, mci);
1723 			}
1724 			else
1725 # endif /* NETUNIX */
1726 			{
1727 				if (port == 0)
1728 					message("Connecting to %s via %s...",
1729 						hostbuf, m->m_name);
1730 				else
1731 					message("Connecting to %s port %d via %s...",
1732 						hostbuf, ntohs(port),
1733 						m->m_name);
1734 				i = makeconnection(hostbuf, port, mci, e);
1735 			}
1736 			mci->mci_errno = errno;
1737 			mci->mci_lastuse = curtime();
1738 			mci->mci_deliveries = 0;
1739 			mci->mci_exitstat = i;
1740 # if NAMED_BIND
1741 			mci->mci_herrno = h_errno;
1742 # endif /* NAMED_BIND */
1743 			if (i == EX_OK)
1744 			{
1745 				goodmxfound = TRUE;
1746 				mci->mci_state = MCIS_OPENING;
1747 				mci_cache(mci);
1748 				if (TrafficLogFile != NULL)
1749 					fprintf(TrafficLogFile, "%05d === CONNECT %s\n",
1750 						(int) getpid(), hostbuf);
1751 				break;
1752 			}
1753 			else
1754 			{
1755 				if (tTd(11, 1))
1756 					dprintf("openmailer: makeconnection => stat=%d, errno=%d\n",
1757 						i, errno);
1758 				if (i == EX_TEMPFAIL)
1759 					goodmxfound = TRUE;
1760 				mci_unlock_host(mci);
1761 			}
1762 
1763 			/* enter status of this host */
1764 			setstat(i);
1765 
1766 			/* should print some message here for -v mode */
1767 		}
1768 		if (mci == NULL)
1769 		{
1770 			syserr("deliver: no host name");
1771 			rcode = EX_SOFTWARE;
1772 			goto give_up;
1773 		}
1774 		mci->mci_pid = 0;
1775 #else /* DAEMON */
1776 		syserr("554 5.3.5 openmailer: no IPC");
1777 		if (tTd(11, 1))
1778 			dprintf("openmailer: NULL\n");
1779 		rcode = EX_UNAVAILABLE;
1780 		goto give_up;
1781 #endif /* DAEMON */
1782 	}
1783 	else
1784 	{
1785 		/* flush any expired connections */
1786 		(void) mci_scan(NULL);
1787 		mci = NULL;
1788 
1789 #if SMTP
1790 		if (bitnset(M_LMTP, m->m_flags))
1791 		{
1792 			/* try to get a cached connection */
1793 			mci = mci_get(m->m_name, m);
1794 			if (mci->mci_host == NULL)
1795 				mci->mci_host = m->m_name;
1796 			CurHostName = mci->mci_host;
1797 			if (mci->mci_state != MCIS_CLOSED)
1798 			{
1799 				message("Using cached LMTP connection for %s...",
1800 					m->m_name);
1801 				mci->mci_deliveries++;
1802 				goto do_transfer;
1803 			}
1804 		}
1805 #endif /* SMTP */
1806 
1807 		/* announce the connection to verbose listeners */
1808 		if (host == NULL || host[0] == '\0')
1809 			message("Connecting to %s...", m->m_name);
1810 		else
1811 			message("Connecting to %s via %s...", host, m->m_name);
1812 		if (TrafficLogFile != NULL)
1813 		{
1814 			char **av;
1815 
1816 			fprintf(TrafficLogFile, "%05d === EXEC", (int) getpid());
1817 			for (av = pv; *av != NULL; av++)
1818 				fprintf(TrafficLogFile, " %s", *av);
1819 			fprintf(TrafficLogFile, "\n");
1820 		}
1821 
1822 #if XDEBUG
1823 		checkfd012("before creating mail pipe");
1824 #endif /* XDEBUG */
1825 
1826 		/* create a pipe to shove the mail through */
1827 		if (pipe(mpvect) < 0)
1828 		{
1829 			syserr("%s... openmailer(%s): pipe (to mailer)",
1830 				shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1831 			if (tTd(11, 1))
1832 				dprintf("openmailer: NULL\n");
1833 			rcode = EX_OSERR;
1834 			goto give_up;
1835 		}
1836 
1837 #if XDEBUG
1838 		/* make sure we didn't get one of the standard I/O files */
1839 		if (mpvect[0] < 3 || mpvect[1] < 3)
1840 		{
1841 			syserr("%s... openmailer(%s): bogus mpvect %d %d",
1842 				shortenstring(e->e_to, MAXSHORTSTR), m->m_name,
1843 				mpvect[0], mpvect[1]);
1844 			printopenfds(TRUE);
1845 			if (tTd(11, 1))
1846 				dprintf("openmailer: NULL\n");
1847 			rcode = EX_OSERR;
1848 			goto give_up;
1849 		}
1850 
1851 		/* make sure system call isn't dead meat */
1852 		checkfdopen(mpvect[0], "mpvect[0]");
1853 		checkfdopen(mpvect[1], "mpvect[1]");
1854 		if (mpvect[0] == mpvect[1] ||
1855 		    (e->e_lockfp != NULL &&
1856 		     (mpvect[0] == fileno(e->e_lockfp) ||
1857 		      mpvect[1] == fileno(e->e_lockfp))))
1858 		{
1859 			if (e->e_lockfp == NULL)
1860 				syserr("%s... openmailer(%s): overlapping mpvect %d %d",
1861 					shortenstring(e->e_to, MAXSHORTSTR),
1862 					m->m_name, mpvect[0], mpvect[1]);
1863 			else
1864 				syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
1865 					shortenstring(e->e_to, MAXSHORTSTR),
1866 					m->m_name, mpvect[0], mpvect[1],
1867 					fileno(e->e_lockfp));
1868 		}
1869 #endif /* XDEBUG */
1870 
1871 		/* create a return pipe */
1872 		if (pipe(rpvect) < 0)
1873 		{
1874 			syserr("%s... openmailer(%s): pipe (from mailer)",
1875 				shortenstring(e->e_to, MAXSHORTSTR),
1876 				m->m_name);
1877 			(void) close(mpvect[0]);
1878 			(void) close(mpvect[1]);
1879 			if (tTd(11, 1))
1880 				dprintf("openmailer: NULL\n");
1881 			rcode = EX_OSERR;
1882 			goto give_up;
1883 		}
1884 #if XDEBUG
1885 		checkfdopen(rpvect[0], "rpvect[0]");
1886 		checkfdopen(rpvect[1], "rpvect[1]");
1887 #endif /* XDEBUG */
1888 
1889 		/*
1890 		**  Actually fork the mailer process.
1891 		**	DOFORK is clever about retrying.
1892 		**
1893 		**	Dispose of SIGCHLD signal catchers that may be laying
1894 		**	around so that endmailer will get it.
1895 		*/
1896 
1897 		if (e->e_xfp != NULL)
1898 			(void) fflush(e->e_xfp);	/* for debugging */
1899 		(void) fflush(stdout);
1900 		(void) setsignal(SIGCHLD, SIG_DFL);
1901 
1902 
1903 		DOFORK(FORK);
1904 		/* pid is set by DOFORK */
1905 
1906 		if (pid < 0)
1907 		{
1908 			/* failure */
1909 			syserr("%s... openmailer(%s): cannot fork",
1910 				shortenstring(e->e_to, MAXSHORTSTR), m->m_name);
1911 			(void) close(mpvect[0]);
1912 			(void) close(mpvect[1]);
1913 			(void) close(rpvect[0]);
1914 			(void) close(rpvect[1]);
1915 			if (tTd(11, 1))
1916 				dprintf("openmailer: NULL\n");
1917 			rcode = EX_OSERR;
1918 			goto give_up;
1919 		}
1920 		else if (pid == 0)
1921 		{
1922 			int i;
1923 			int save_errno;
1924 			int new_euid = NO_UID;
1925 			int new_ruid = NO_UID;
1926 			int new_gid = NO_GID;
1927 			struct stat stb;
1928 			extern int DtableSize;
1929 
1930 			/* Reset global flags */
1931 			RestartRequest = NULL;
1932 			ShutdownRequest = NULL;
1933 			PendingSignal = 0;
1934 
1935 			if (e->e_lockfp != NULL)
1936 				(void) close(fileno(e->e_lockfp));
1937 
1938 			/* child -- set up input & exec mailer */
1939 			(void) setsignal(SIGINT, SIG_IGN);
1940 			(void) setsignal(SIGHUP, SIG_IGN);
1941 			(void) setsignal(SIGTERM, SIG_DFL);
1942 
1943 			if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
1944 				stb.st_mode = 0;
1945 
1946 # if HASSETUSERCONTEXT
1947 			/*
1948 			**  Set user resources.
1949 			*/
1950 
1951 			if (contextaddr != NULL)
1952 			{
1953 				struct passwd *pwd;
1954 
1955 				if (contextaddr->q_ruser != NULL)
1956 					pwd = sm_getpwnam(contextaddr->q_ruser);
1957 				else
1958 					pwd = sm_getpwnam(contextaddr->q_user);
1959 				if (pwd != NULL)
1960 					(void) setusercontext(NULL,
1961 						pwd, pwd->pw_uid,
1962 						LOGIN_SETRESOURCES|LOGIN_SETPRIORITY);
1963 			}
1964 # endif /* HASSETUSERCONTEXT */
1965 
1966 			/* tweak niceness */
1967 			if (m->m_nice != 0)
1968 				(void) nice(m->m_nice);
1969 
1970 			/* reset group id */
1971 			if (bitnset(M_SPECIFIC_UID, m->m_flags))
1972 				new_gid = m->m_gid;
1973 			else if (bitset(S_ISGID, stb.st_mode))
1974 				new_gid = stb.st_gid;
1975 			else if (ctladdr != NULL && ctladdr->q_gid != 0)
1976 			{
1977 				if (!DontInitGroups)
1978 				{
1979 					char *u = ctladdr->q_ruser;
1980 
1981 					if (u == NULL)
1982 						u = ctladdr->q_user;
1983 
1984 					if (initgroups(u, ctladdr->q_gid) == -1 && suidwarn)
1985 					{
1986 						syserr("openmailer: initgroups(%s, %d) failed",
1987 							u, ctladdr->q_gid);
1988 						exit(EX_TEMPFAIL);
1989 					}
1990 				}
1991 				else
1992 				{
1993 					GIDSET_T gidset[1];
1994 
1995 					gidset[0] = ctladdr->q_gid;
1996 					if (setgroups(1, gidset) == -1 && suidwarn)
1997 					{
1998 						syserr("openmailer: setgroups() failed");
1999 						exit(EX_TEMPFAIL);
2000 					}
2001 				}
2002 				new_gid = ctladdr->q_gid;
2003 			}
2004 			else
2005 			{
2006 				if (!DontInitGroups)
2007 				{
2008 					if (initgroups(DefUser, DefGid) == -1 && suidwarn)
2009 					{
2010 						syserr("openmailer: initgroups(%s, %d) failed",
2011 							DefUser, DefGid);
2012 						exit(EX_TEMPFAIL);
2013 					}
2014 				}
2015 				else
2016 				{
2017 					GIDSET_T gidset[1];
2018 
2019 					gidset[0] = DefGid;
2020 					if (setgroups(1, gidset) == -1 && suidwarn)
2021 					{
2022 						syserr("openmailer: setgroups() failed");
2023 						exit(EX_TEMPFAIL);
2024 					}
2025 				}
2026 				if (m->m_gid == 0)
2027 					new_gid = DefGid;
2028 				else
2029 					new_gid = m->m_gid;
2030 			}
2031 			if (new_gid != NO_GID)
2032 			{
2033 				if (RunAsUid != 0 &&
2034 				    bitnset(M_SPECIFIC_UID, m->m_flags) &&
2035 				    new_gid != getgid() &&
2036 				    new_gid != getegid())
2037 				{
2038 					/* Only root can change the gid */
2039 					syserr("openmailer: insufficient privileges to change gid");
2040 					exit(EX_TEMPFAIL);
2041 				}
2042 
2043 				if (setgid(new_gid) < 0 && suidwarn)
2044 				{
2045 					syserr("openmailer: setgid(%ld) failed",
2046 					       (long) new_gid);
2047 					exit(EX_TEMPFAIL);
2048 				}
2049 			}
2050 
2051 			/* change root to some "safe" directory */
2052 			if (m->m_rootdir != NULL)
2053 			{
2054 				expand(m->m_rootdir, buf, sizeof buf, e);
2055 				if (tTd(11, 20))
2056 					dprintf("openmailer: chroot %s\n",
2057 						buf);
2058 				if (chroot(buf) < 0)
2059 				{
2060 					syserr("openmailer: Cannot chroot(%s)",
2061 					       buf);
2062 					exit(EX_TEMPFAIL);
2063 				}
2064 				if (chdir("/") < 0)
2065 				{
2066 					syserr("openmailer: cannot chdir(/)");
2067 					exit(EX_TEMPFAIL);
2068 				}
2069 			}
2070 
2071 			/* reset user id */
2072 			endpwent();
2073 			if (bitnset(M_SPECIFIC_UID, m->m_flags))
2074 				new_euid = m->m_uid;
2075 			else if (bitset(S_ISUID, stb.st_mode))
2076 				new_ruid = stb.st_uid;
2077 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
2078 				new_ruid = ctladdr->q_uid;
2079 			else if (m->m_uid != 0)
2080 				new_ruid = m->m_uid;
2081 			else
2082 				new_ruid = DefUid;
2083 			if (new_euid != NO_UID)
2084 			{
2085 				if (RunAsUid != 0 && new_euid != RunAsUid)
2086 				{
2087 					/* Only root can change the uid */
2088 					syserr("openmailer: insufficient privileges to change uid");
2089 					exit(EX_TEMPFAIL);
2090 				}
2091 
2092 				vendor_set_uid(new_euid);
2093 # if MAILER_SETUID_METHOD == USE_SETEUID
2094 				if (seteuid(new_euid) < 0 && suidwarn)
2095 				{
2096 					syserr("openmailer: seteuid(%ld) failed",
2097 						(long) new_euid);
2098 					exit(EX_TEMPFAIL);
2099 				}
2100 # endif /* MAILER_SETUID_METHOD == USE_SETEUID */
2101 # if MAILER_SETUID_METHOD == USE_SETREUID
2102 				if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
2103 				{
2104 					syserr("openmailer: setreuid(%ld, %ld) failed",
2105 						(long) new_ruid, (long) new_euid);
2106 					exit(EX_TEMPFAIL);
2107 				}
2108 # endif /* MAILER_SETUID_METHOD == USE_SETREUID */
2109 # if MAILER_SETUID_METHOD == USE_SETUID
2110 				if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
2111 				{
2112 					syserr("openmailer: setuid(%ld) failed",
2113 						(long) new_euid);
2114 					exit(EX_TEMPFAIL);
2115 				}
2116 # endif /* MAILER_SETUID_METHOD == USE_SETUID */
2117 			}
2118 			else if (new_ruid != NO_UID)
2119 			{
2120 				vendor_set_uid(new_ruid);
2121 				if (setuid(new_ruid) < 0 && suidwarn)
2122 				{
2123 					syserr("openmailer: setuid(%ld) failed",
2124 						(long) new_ruid);
2125 					exit(EX_TEMPFAIL);
2126 				}
2127 			}
2128 
2129 			if (tTd(11, 2))
2130 				dprintf("openmailer: running as r/euid=%d/%d, r/egid=%d/%d\n",
2131 					(int) getuid(), (int) geteuid(),
2132 					(int) getgid(), (int) getegid());
2133 
2134 			/* move into some "safe" directory */
2135 			if (m->m_execdir != NULL)
2136 			{
2137 				char *q;
2138 
2139 				for (p = m->m_execdir; p != NULL; p = q)
2140 				{
2141 					q = strchr(p, ':');
2142 					if (q != NULL)
2143 						*q = '\0';
2144 					expand(p, buf, sizeof buf, e);
2145 					if (q != NULL)
2146 						*q++ = ':';
2147 					if (tTd(11, 20))
2148 						dprintf("openmailer: trydir %s\n",
2149 							buf);
2150 					if (buf[0] != '\0' && chdir(buf) >= 0)
2151 						break;
2152 				}
2153 			}
2154 
2155 			/* arrange to filter std & diag output of command */
2156 			(void) close(rpvect[0]);
2157 			if (dup2(rpvect[1], STDOUT_FILENO) < 0)
2158 			{
2159 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
2160 				       shortenstring(e->e_to, MAXSHORTSTR),
2161 				       m->m_name, rpvect[1]);
2162 				_exit(EX_OSERR);
2163 			}
2164 			(void) close(rpvect[1]);
2165 
2166 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
2167 			{
2168 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
2169 					shortenstring(e->e_to, MAXSHORTSTR),
2170 					m->m_name);
2171 				_exit(EX_OSERR);
2172 			}
2173 
2174 			/* arrange to get standard input */
2175 			(void) close(mpvect[1]);
2176 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
2177 			{
2178 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
2179 					shortenstring(e->e_to, MAXSHORTSTR),
2180 					m->m_name, mpvect[0]);
2181 				_exit(EX_OSERR);
2182 			}
2183 			(void) close(mpvect[0]);
2184 
2185 			/* arrange for all the files to be closed */
2186 			for (i = 3; i < DtableSize; i++)
2187 			{
2188 				register int j;
2189 
2190 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
2191 					(void) fcntl(i, F_SETFD,
2192 						     j | FD_CLOEXEC);
2193 			}
2194 
2195 			/* run disconnected from terminal */
2196 			(void) setsid();
2197 
2198 			/* try to execute the mailer */
2199 			(void) execve(m->m_mailer, (ARGV_T) pv,
2200 				      (ARGV_T) UserEnviron);
2201 			save_errno = errno;
2202 			syserr("Cannot exec %s", m->m_mailer);
2203 			if (bitnset(M_LOCALMAILER, m->m_flags) ||
2204 			    transienterror(save_errno))
2205 				_exit(EX_OSERR);
2206 			_exit(EX_UNAVAILABLE);
2207 		}
2208 
2209 		/*
2210 		**  Set up return value.
2211 		*/
2212 
2213 		if (mci == NULL)
2214 		{
2215 			mci = (MCI *) xalloc(sizeof *mci);
2216 			memset((char *) mci, '\0', sizeof *mci);
2217 		}
2218 		mci->mci_mailer = m;
2219 		if (clever)
2220 		{
2221 			mci->mci_state = MCIS_OPENING;
2222 			mci_cache(mci);
2223 		}
2224 		else
2225 		{
2226 			mci->mci_state = MCIS_OPEN;
2227 		}
2228 		mci->mci_pid = pid;
2229 		(void) close(mpvect[0]);
2230 		mci->mci_out = fdopen(mpvect[1], "w");
2231 		if (mci->mci_out == NULL)
2232 		{
2233 			syserr("deliver: cannot create mailer output channel, fd=%d",
2234 				mpvect[1]);
2235 			(void) close(mpvect[1]);
2236 			(void) close(rpvect[0]);
2237 			(void) close(rpvect[1]);
2238 			rcode = EX_OSERR;
2239 			goto give_up;
2240 		}
2241 
2242 		(void) close(rpvect[1]);
2243 		mci->mci_in = fdopen(rpvect[0], "r");
2244 		if (mci->mci_in == NULL)
2245 		{
2246 			syserr("deliver: cannot create mailer input channel, fd=%d",
2247 			       mpvect[1]);
2248 			(void) close(rpvect[0]);
2249 			(void) fclose(mci->mci_out);
2250 			mci->mci_out = NULL;
2251 			rcode = EX_OSERR;
2252 			goto give_up;
2253 		}
2254 
2255 		/* Don't cache non-clever connections */
2256 		if (!clever)
2257 			mci->mci_flags |= MCIF_TEMP;
2258 	}
2259 
2260 	/*
2261 	**  If we are in SMTP opening state, send initial protocol.
2262 	*/
2263 
2264 	if (bitnset(M_7BITS, m->m_flags) &&
2265 	    (!clever || mci->mci_state == MCIS_OPENING))
2266 		mci->mci_flags |= MCIF_7BIT;
2267 #if SMTP
2268 	if (clever && mci->mci_state != MCIS_CLOSED)
2269 	{
2270 # if SASL && SFIO
2271 #  define DONE_AUTH(f)		bitset(MCIF_AUTHACT, f)
2272 # endif /* SASL && SFIO */
2273 # if STARTTLS
2274 #  define DONE_STARTTLS(f)	bitset(MCIF_TLSACT, f)
2275 # endif /* STARTTLS */
2276 # define ONLY_HELO(f)		bitset(MCIF_ONLY_EHLO, f)
2277 # define SET_HELO(f)		f |= MCIF_ONLY_EHLO
2278 # define CLR_HELO(f)		f &= ~MCIF_ONLY_EHLO
2279 
2280 
2281 # if STARTTLS || (SASL && SFIO)
2282 reconnect:	/* after switching to an authenticated connection */
2283 # endif /* STARTTLS || (SASL && SFIO) */
2284 
2285 # if SASL
2286 		mci->mci_saslcap = NULL;
2287 # endif /* SASL */
2288 		smtpinit(m, mci, e, ONLY_HELO(mci->mci_flags));
2289 		CLR_HELO(mci->mci_flags);
2290 
2291 # if STARTTLS
2292 		/* first TLS then AUTH to provide a security layer */
2293 		if (mci->mci_state != MCIS_CLOSED &&
2294 		    !DONE_STARTTLS(mci->mci_flags))
2295 		{
2296 			int olderrors;
2297 			int dotpos;
2298 			bool usetls;
2299 			bool saveQuickAbort = QuickAbort;
2300 			bool saveSuprErrs = SuprErrs;
2301 			char *host = NULL;
2302 #  if _FFR_TLS_CLT1
2303 			char *p;
2304 #  endif /* _FFR_TLS_CLT1 */
2305 			char *srvname;
2306 			extern SOCKADDR CurHostAddr;
2307 
2308 			rcode = EX_OK;
2309 			usetls = bitset(MCIF_TLS, mci->mci_flags);
2310 #  if _FFR_TLS_CLT1
2311 			if (usetls &&
2312 			    (p = macvalue(macid("{client_flags}", NULL), e))
2313 			    != NULL)
2314 			{
2315 				for (; *p != '\0'; p++)
2316 				{
2317 					/* look for just this one flag */
2318 					if (*p == D_CLTNOTLS)
2319 					{
2320 						usetls = FALSE;
2321 						break;
2322 					}
2323 				}
2324 			}
2325 #  endif /* _FFR_TLS_CLT1 */
2326 
2327 			if (mci->mci_host != NULL)
2328 			{
2329 				srvname = mci->mci_host;
2330 				dotpos = strlen(srvname) - 1;
2331 				if (dotpos >= 0)
2332 				{
2333 					if (srvname[dotpos] == '.')
2334 						srvname[dotpos] = '\0';
2335 					else
2336 						dotpos = -1;
2337 				}
2338 			}
2339 			else
2340 			{
2341 				srvname = "";
2342 				dotpos = -1;
2343 			}
2344 			define(macid("{server_name}", NULL),
2345 			       newstr(srvname), e);
2346 			if (CurHostAddr.sa.sa_family != 0)
2347 				define(macid("{server_addr}", NULL),
2348 				       newstr(anynet_ntoa(&CurHostAddr)), e);
2349 			else
2350 				define(macid("{server_addr}", NULL), NULL, e);
2351 			if (usetls)
2352 			{
2353 				host = macvalue(macid("{server_name}", NULL),
2354 						e);
2355 #  if _FFR_TLS_O_T
2356 				olderrors = Errors;
2357 				QuickAbort = FALSE;
2358 				SuprErrs = TRUE;
2359 				if (rscheck("try_tls", srvname, NULL,
2360 					    e, TRUE, FALSE, 8, host) != EX_OK
2361 				    || Errors > olderrors)
2362 					usetls = FALSE;
2363 				SuprErrs = saveSuprErrs;
2364 				QuickAbort = saveQuickAbort;
2365 #  endif /* _FFR_TLS_O_T */
2366 			}
2367 
2368 			/* undo change of srvname */
2369 			if (dotpos >= 0)
2370 				srvname[dotpos] = '.';
2371 			if (usetls)
2372 			{
2373 				if ((rcode = starttls(m, mci, e)) == EX_OK)
2374 				{
2375 					/* start again without STARTTLS */
2376 					mci->mci_flags |= MCIF_TLSACT;
2377 				}
2378 				else
2379 				{
2380 					char *s;
2381 
2382 					/*
2383 					**  TLS negotation failed, what to do?
2384 					**  fall back to unencrypted connection
2385 					**  or abort? How to decide?
2386 					**  set a macro and call a ruleset.
2387 					*/
2388 					mci->mci_flags &= ~MCIF_TLS;
2389 					switch (rcode)
2390 					{
2391 					  case EX_TEMPFAIL:
2392 						s = "TEMP";
2393 						break;
2394 					  case EX_USAGE:
2395 						s = "USAGE";
2396 						break;
2397 					  case EX_PROTOCOL:
2398 						s = "PROTOCOL";
2399 						break;
2400 					  case EX_SOFTWARE:
2401 						s = "SOFTWARE";
2402 						break;
2403 
2404 					  /* everything else is a failure */
2405 					  default:
2406 						s = "FAILURE";
2407 						rcode = EX_TEMPFAIL;
2408 					}
2409 					define(macid("{verify}", NULL),
2410 					       newstr(s), e);
2411 				}
2412 			}
2413 			else if (mci->mci_ssl != NULL)
2414 			{
2415 				/* active TLS connection, use that data */
2416 				(void) tls_get_info(mci->mci_ssl, e, FALSE,
2417 						    mci->mci_host, FALSE);
2418 			}
2419 			else
2420 				define(macid("{verify}", NULL), "NONE", e);
2421 			olderrors = Errors;
2422 			QuickAbort = FALSE;
2423 			SuprErrs = TRUE;
2424 
2425 			/*
2426 			**  rcode == EX_SOFTWARE is special:
2427 			**  the TLS negotation failed
2428 			**  we have to drop the connection no matter what
2429 			**  However, we call tls_server to give it the chance
2430 			**  to log the problem and return an appropriate
2431 			**  error code.
2432 			*/
2433 			if (rscheck("tls_server",
2434 				     macvalue(macid("{verify}", NULL), e),
2435 				     NULL, e, TRUE, TRUE, 6, host) != EX_OK ||
2436 			    Errors > olderrors ||
2437 			    rcode == EX_SOFTWARE)
2438 			{
2439 				char enhsc[ENHSCLEN];
2440 				extern char MsgBuf[];
2441 
2442 				if (ISSMTPCODE(MsgBuf) &&
2443 				    extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
2444 				{
2445 					p = newstr(MsgBuf);
2446 				}
2447 				else
2448 				{
2449 					p = "403 4.7.0 server not authenticated.";
2450 					(void) strlcpy(enhsc, "4.7.0",
2451 						       sizeof enhsc);
2452 				}
2453 				SuprErrs = saveSuprErrs;
2454 				QuickAbort = saveQuickAbort;
2455 
2456 				if (rcode == EX_SOFTWARE)
2457 				{
2458 					/* drop the connection */
2459 					mci->mci_state = MCIS_QUITING;
2460 					if (mci->mci_in != NULL)
2461 					{
2462 						(void) fclose(mci->mci_in);
2463 						mci->mci_in = NULL;
2464 					}
2465 					mci->mci_flags &= ~MCIF_TLSACT;
2466 					(void) endmailer(mci, e, pv);
2467 				}
2468 				else
2469 				{
2470 					/* abort transfer */
2471 					smtpquit(m, mci, e);
2472 				}
2473 
2474 				/* avoid bogus error msg */
2475 				mci->mci_errno = 0;
2476 
2477 				/* temp or permanent failure? */
2478 				rcode = (*p == '4') ? EX_TEMPFAIL
2479 						    : EX_UNAVAILABLE;
2480 				mci_setstat(mci, rcode, newstr(enhsc), p);
2481 
2482 				/*
2483 				**  hack to get the error message into
2484 				**  the envelope (done in giveresponse())
2485 				*/
2486 				(void) strlcpy(SmtpError, p, sizeof SmtpError);
2487 			}
2488 			QuickAbort = saveQuickAbort;
2489 			SuprErrs = saveSuprErrs;
2490 			if (DONE_STARTTLS(mci->mci_flags) &&
2491 			    mci->mci_state != MCIS_CLOSED)
2492 			{
2493 				SET_HELO(mci->mci_flags);
2494 				mci->mci_flags &= ~MCIF_EXTENS;
2495 				goto reconnect;
2496 			}
2497 		}
2498 		else if (mci->mci_ssl != NULL)
2499 		{
2500 			/* active TLS connection, use that data */
2501 			(void) tls_get_info(mci->mci_ssl, e, FALSE,
2502 					    mci->mci_host, FALSE);
2503 		}
2504 # endif /* STARTTLS */
2505 # if SASL
2506 		/* if other server supports authentication let's authenticate */
2507 		if (mci->mci_state != MCIS_CLOSED &&
2508 		    mci->mci_saslcap != NULL &&
2509 #  if SFIO
2510 		    !DONE_AUTH(mci->mci_flags) &&
2511 #  endif /* SFIO */
2512 		    SASLInfo != NULL)
2513 		{
2514 			/*
2515 			**  should we require some minimum authentication?
2516 			**  XXX ignore result?
2517 			*/
2518 			if (smtpauth(m, mci, e) == EX_OK)
2519 			{
2520 #  if SFIO
2521 				int result;
2522 				sasl_ssf_t *ssf;
2523 
2524 				/* get security strength (features) */
2525 				result = sasl_getprop(mci->mci_conn, SASL_SSF,
2526 						      (void **) &ssf);
2527 				if (LogLevel > 9)
2528 					sm_syslog(LOG_INFO, NOQID,
2529 						  "SASL: outgoing connection to %.64s: mech=%.16s, bits=%d",
2530 						  mci->mci_host,
2531 						  macvalue(macid("{auth_type}",
2532 								 NULL), e),
2533 						  result == SASL_OK ? *ssf
2534 						  		    : 0);
2535 
2536 				/*
2537 				**  only switch to encrypted connection
2538 				**  if a security layer has been negotiated
2539 				*/
2540 				if (result == SASL_OK && *ssf > 0)
2541 				{
2542 					/*
2543 					**  convert sfio stuff to use SASL
2544 					**  check return values
2545 					**  if the call fails,
2546 					**  fall back to unencrypted version
2547 					**  unless some cf option requires
2548 					**  encryption then the connection must
2549 					**  be aborted
2550 					*/
2551 					if (sfdcsasl(mci->mci_in, mci->mci_out,
2552 						     mci->mci_conn) == 0)
2553 					{
2554 						SET_HELO(mci->mci_flags);
2555 						mci->mci_flags &= ~MCIF_EXTENS;
2556 						mci->mci_flags |= MCIF_AUTHACT;
2557 						goto reconnect;
2558 					}
2559 					syserr("SASL TLS switch failed in client");
2560 				}
2561 				/* else? XXX */
2562 #  endif /* SFIO */
2563 				mci->mci_flags |= MCIF_AUTHACT;
2564 
2565 			}
2566 		}
2567 # endif /* SASL */
2568 	}
2569 
2570 #endif /* SMTP */
2571 
2572 do_transfer:
2573 	/* clear out per-message flags from connection structure */
2574 	mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
2575 
2576 	if (bitset(EF_HAS8BIT, e->e_flags) &&
2577 	    !bitset(EF_DONT_MIME, e->e_flags) &&
2578 	    bitnset(M_7BITS, m->m_flags))
2579 		mci->mci_flags |= MCIF_CVT8TO7;
2580 
2581 #if MIME7TO8
2582 	if (bitnset(M_MAKE8BIT, m->m_flags) &&
2583 	    !bitset(MCIF_7BIT, mci->mci_flags) &&
2584 	    (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
2585 	     (strcasecmp(p, "quoted-printable") == 0 ||
2586 	      strcasecmp(p, "base64") == 0) &&
2587 	    (p = hvalue("Content-Type", e->e_header)) != NULL)
2588 	{
2589 		/* may want to convert 7 -> 8 */
2590 		/* XXX should really parse it here -- and use a class XXX */
2591 		if (strncasecmp(p, "text/plain", 10) == 0 &&
2592 		    (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
2593 			mci->mci_flags |= MCIF_CVT7TO8;
2594 	}
2595 #endif /* MIME7TO8 */
2596 
2597 	if (tTd(11, 1))
2598 	{
2599 		dprintf("openmailer: ");
2600 		mci_dump(mci, FALSE);
2601 	}
2602 
2603 	if (mci->mci_state != MCIS_OPEN)
2604 	{
2605 		/* couldn't open the mailer */
2606 		rcode = mci->mci_exitstat;
2607 		errno = mci->mci_errno;
2608 #if NAMED_BIND
2609 		SM_SET_H_ERRNO(mci->mci_herrno);
2610 #endif /* NAMED_BIND */
2611 		if (rcode == EX_OK)
2612 		{
2613 			/* shouldn't happen */
2614 			syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
2615 				(u_long) mci, rcode, errno, mci->mci_state,
2616 				firstsig);
2617 			mci_dump_all(TRUE);
2618 			rcode = EX_SOFTWARE;
2619 		}
2620 #if DAEMON
2621 		else if (nummxhosts > hostnum)
2622 		{
2623 			/* try next MX site */
2624 			goto tryhost;
2625 		}
2626 #endif /* DAEMON */
2627 	}
2628 	else if (!clever)
2629 	{
2630 		/*
2631 		**  Format and send message.
2632 		*/
2633 
2634 		putfromline(mci, e);
2635 		(*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
2636 		(*e->e_putbody)(mci, e, NULL);
2637 
2638 		/* get the exit status */
2639 		rcode = endmailer(mci, e, pv);
2640 		if (rcode == EX_TEMPFAIL &&
2641 		    SmtpError[0] == '\0')
2642 		{
2643 			/*
2644 			**  Need an e_message for mailq display.
2645 			**  We set SmtpError as
2646 			*/
2647 
2648 			snprintf(SmtpError, sizeof SmtpError,
2649 				 "%s mailer (%s) exited with EX_TEMPFAIL",
2650 				 m->m_name, m->m_mailer);
2651 		}
2652 	}
2653 	else
2654 #if SMTP
2655 	{
2656 		/*
2657 		**  Send the MAIL FROM: protocol
2658 		*/
2659 
2660 		rcode = smtpmailfrom(m, mci, e);
2661 		if (rcode == EX_OK)
2662 		{
2663 			register char *t = tobuf;
2664 			register int i;
2665 
2666 			/* send the recipient list */
2667 			tobuf[0] = '\0';
2668 
2669 			for (to = tochain; to != NULL; to = to->q_tchain)
2670 			{
2671 				e->e_to = to->q_paddr;
2672 #if !_FFR_DYNAMIC_TOBUF
2673 				if (strlen(to->q_paddr) +
2674 				    (t - tobuf) + 2 > sizeof tobuf)
2675 				{
2676 					/* not enough room */
2677 					continue;
2678 				}
2679 #endif /* !_FFR_DYNAMIC_TOBUF */
2680 
2681 # if STARTTLS
2682 #  if _FFR_TLS_RCPT
2683 				i = rscheck("tls_rcpt", to->q_user, NULL, e,
2684 					    TRUE, TRUE, 4, mci->mci_host);
2685 				if (i != EX_OK)
2686 				{
2687 					/* avoid bogus error msg */
2688 					errno = 0;
2689 					markfailure(e, to, mci, i, FALSE);
2690 					giveresponse(i, to->q_status,  m,
2691 						     mci, ctladdr, xstart, e);
2692 					continue;
2693 				}
2694 #  endif /* _FFR_TLS_RCPT */
2695 # endif /* STARTTLS */
2696 
2697 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
2698 				{
2699 					markfailure(e, to, mci, i, FALSE);
2700 					giveresponse(i, to->q_status,  m,
2701 						     mci, ctladdr, xstart, e);
2702 				}
2703 				else
2704 				{
2705 					*t++ = ',';
2706 					for (p = to->q_paddr; *p; *t++ = *p++)
2707 						continue;
2708 					*t = '\0';
2709 				}
2710 			}
2711 
2712 			/* now send the data */
2713 			if (tobuf[0] == '\0')
2714 			{
2715 				rcode = EX_OK;
2716 				e->e_to = NULL;
2717 				if (bitset(MCIF_CACHED, mci->mci_flags))
2718 					smtprset(m, mci, e);
2719 			}
2720 			else
2721 			{
2722 				e->e_to = tobuf + 1;
2723 				rcode = smtpdata(m, mci, e);
2724 			}
2725 		}
2726 # if DAEMON
2727 		if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
2728 		{
2729 			/* try next MX site */
2730 			goto tryhost;
2731 		}
2732 # endif /* DAEMON */
2733 	}
2734 #else /* SMTP */
2735 	{
2736 		syserr("554 5.3.5 deliver: need SMTP compiled to use clever mailer");
2737 		rcode = EX_CONFIG;
2738 		goto give_up;
2739 	}
2740 #endif /* SMTP */
2741 #if NAMED_BIND
2742 	if (ConfigLevel < 2)
2743 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
2744 #endif /* NAMED_BIND */
2745 
2746 	if (tTd(62, 1))
2747 		checkfds("after delivery");
2748 
2749 	/*
2750 	**  Do final status disposal.
2751 	**	We check for something in tobuf for the SMTP case.
2752 	**	If we got a temporary failure, arrange to queue the
2753 	**		addressees.
2754 	*/
2755 
2756   give_up:
2757 #if SMTP
2758 	if (bitnset(M_LMTP, m->m_flags))
2759 	{
2760 		lmtp_rcode = rcode;
2761 		tobuf[0] = '\0';
2762 		anyok = FALSE;
2763 	}
2764 	else
2765 #endif /* SMTP */
2766 		anyok = rcode == EX_OK;
2767 
2768 	for (to = tochain; to != NULL; to = to->q_tchain)
2769 	{
2770 		/* see if address already marked */
2771 		if (!QS_IS_OK(to->q_state))
2772 			continue;
2773 
2774 #if SMTP
2775 		/* if running LMTP, get the status for each address */
2776 		if (bitnset(M_LMTP, m->m_flags))
2777 		{
2778 			if (lmtp_rcode == EX_OK)
2779 				rcode = smtpgetstat(m, mci, e);
2780 			if (rcode == EX_OK)
2781 			{
2782 #if _FFR_DYNAMIC_TOBUF
2783 				(void) strlcat(tobuf, ",", tobufsize);
2784 				(void) strlcat(tobuf, to->q_paddr, tobufsize);
2785 #else /* _FFR_DYNAMIC_TOBUF */
2786 				if (strlen(to->q_paddr) +
2787 				    strlen(tobuf) + 2 > sizeof tobuf)
2788 				{
2789 					syserr("LMTP tobuf overflow");
2790 				}
2791 				else
2792 				{
2793 					(void) strlcat(tobuf, ",",
2794 						       sizeof tobuf);
2795 					(void) strlcat(tobuf, to->q_paddr,
2796 						       sizeof tobuf);
2797 				}
2798 #endif /* _FFR_DYNAMIC_TOBUF */
2799 				anyok = TRUE;
2800 			}
2801 			else
2802 			{
2803 				e->e_to = to->q_paddr;
2804 				markfailure(e, to, mci, rcode, TRUE);
2805 				giveresponse(rcode, to->q_status, m, mci,
2806 					     ctladdr, xstart, e);
2807 				e->e_to = tobuf + 1;
2808 				continue;
2809 			}
2810 		}
2811 		else
2812 #endif /* SMTP */
2813 		{
2814 			/* mark bad addresses */
2815 			if (rcode != EX_OK)
2816 			{
2817 				if (goodmxfound && rcode == EX_NOHOST)
2818 					rcode = EX_TEMPFAIL;
2819 				markfailure(e, to, mci, rcode, TRUE);
2820 				continue;
2821 			}
2822 		}
2823 
2824 		/* successful delivery */
2825 		to->q_state = QS_SENT;
2826 		to->q_statdate = curtime();
2827 		e->e_nsent++;
2828 
2829 #if QUEUE
2830 		/*
2831 		**  Checkpoint the send list every few addresses
2832 		*/
2833 
2834 		if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
2835 		{
2836 			queueup(e, FALSE);
2837 			e->e_nsent = 0;
2838 		}
2839 #endif /* QUEUE */
2840 
2841 		if (bitnset(M_LOCALMAILER, m->m_flags) &&
2842 		    bitset(QPINGONSUCCESS, to->q_flags))
2843 		{
2844 			to->q_flags |= QDELIVERED;
2845 			to->q_status = "2.1.5";
2846 			fprintf(e->e_xfp, "%s... Successfully delivered\n",
2847 				to->q_paddr);
2848 		}
2849 		else if (bitset(QPINGONSUCCESS, to->q_flags) &&
2850 			 bitset(QPRIMARY, to->q_flags) &&
2851 			 !bitset(MCIF_DSN, mci->mci_flags))
2852 		{
2853 			to->q_flags |= QRELAYED;
2854 			fprintf(e->e_xfp, "%s... relayed; expect no further notifications\n",
2855 				to->q_paddr);
2856 		}
2857 	}
2858 
2859 #if SMTP
2860 	if (bitnset(M_LMTP, m->m_flags))
2861 	{
2862 		/*
2863 		**  Global information applies to the last recipient only;
2864 		**  clear it out to avoid bogus errors.
2865 		*/
2866 
2867 		rcode = EX_OK;
2868 		e->e_statmsg = NULL;
2869 
2870 		/* reset the mci state for the next transaction */
2871 		if (mci != NULL && mci->mci_state == MCIS_ACTIVE)
2872 			mci->mci_state = MCIS_OPEN;
2873 	}
2874 #endif /* SMTP */
2875 
2876 	if (tobuf[0] != '\0')
2877 		giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e);
2878 	if (anyok)
2879 		markstats(e, tochain, FALSE);
2880 	mci_store_persistent(mci);
2881 
2882 #if SMTP
2883 	/* now close the connection */
2884 	if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
2885 	    !bitset(MCIF_CACHED, mci->mci_flags))
2886 		smtpquit(m, mci, e);
2887 #endif /* SMTP */
2888 
2889 	/*
2890 	**  Restore state and return.
2891 	*/
2892 
2893 #if XDEBUG
2894 	{
2895 		char wbuf[MAXLINE];
2896 
2897 		/* make absolutely certain 0, 1, and 2 are in use */
2898 		snprintf(wbuf, sizeof wbuf, "%s... end of deliver(%s)",
2899 			e->e_to == NULL ? "NO-TO-LIST"
2900 					: shortenstring(e->e_to, MAXSHORTSTR),
2901 			m->m_name);
2902 		checkfd012(wbuf);
2903 	}
2904 #endif /* XDEBUG */
2905 
2906 	errno = 0;
2907 	define('g', (char *) NULL, e);
2908 	e->e_to = NULL;
2909 	return rcode;
2910 }
2911 
2912 /*
2913 **  MARKFAILURE -- mark a failure on a specific address.
2914 **
2915 **	Parameters:
2916 **		e -- the envelope we are sending.
2917 **		q -- the address to mark.
2918 **		mci -- mailer connection information.
2919 **		rcode -- the code signifying the particular failure.
2920 **		ovr -- override an existing code?
2921 **
2922 **	Returns:
2923 **		none.
2924 **
2925 **	Side Effects:
2926 **		marks the address (and possibly the envelope) with the
2927 **			failure so that an error will be returned or
2928 **			the message will be queued, as appropriate.
2929 */
2930 
2931 static void
2932 markfailure(e, q, mci, rcode, ovr)
2933 	register ENVELOPE *e;
2934 	register ADDRESS *q;
2935 	register MCI *mci;
2936 	int rcode;
2937 	bool ovr;
2938 {
2939 	char *status = NULL;
2940 	char *rstatus = NULL;
2941 
2942 	switch (rcode)
2943 	{
2944 	  case EX_OK:
2945 		break;
2946 
2947 	  case EX_TEMPFAIL:
2948 	  case EX_IOERR:
2949 	  case EX_OSERR:
2950 		q->q_state = QS_QUEUEUP;
2951 		break;
2952 
2953 	  default:
2954 		q->q_state = QS_BADADDR;
2955 		break;
2956 	}
2957 
2958 	/* find most specific error code possible */
2959 	if (mci != NULL && mci->mci_status != NULL)
2960 	{
2961 		status = mci->mci_status;
2962 		if (mci->mci_rstatus != NULL)
2963 			rstatus = newstr(mci->mci_rstatus);
2964 		else
2965 			rstatus = NULL;
2966 	}
2967 	else if (e->e_status != NULL)
2968 	{
2969 		status = e->e_status;
2970 		rstatus = NULL;
2971 	}
2972 	else
2973 	{
2974 		switch (rcode)
2975 		{
2976 		  case EX_USAGE:
2977 			status = "5.5.4";
2978 			break;
2979 
2980 		  case EX_DATAERR:
2981 			status = "5.5.2";
2982 			break;
2983 
2984 		  case EX_NOUSER:
2985 			status = "5.1.1";
2986 			break;
2987 
2988 		  case EX_NOHOST:
2989 			status = "5.1.2";
2990 			break;
2991 
2992 		  case EX_NOINPUT:
2993 		  case EX_CANTCREAT:
2994 		  case EX_NOPERM:
2995 			status = "5.3.0";
2996 			break;
2997 
2998 		  case EX_UNAVAILABLE:
2999 		  case EX_SOFTWARE:
3000 		  case EX_OSFILE:
3001 		  case EX_PROTOCOL:
3002 		  case EX_CONFIG:
3003 			status = "5.5.0";
3004 			break;
3005 
3006 		  case EX_OSERR:
3007 		  case EX_IOERR:
3008 			status = "4.5.0";
3009 			break;
3010 
3011 		  case EX_TEMPFAIL:
3012 			status = "4.2.0";
3013 			break;
3014 		}
3015 	}
3016 
3017 	/* new status? */
3018 	if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3019 	    *q->q_status == '\0' || *q->q_status < *status))
3020 	{
3021 		q->q_status = status;
3022 		q->q_rstatus = rstatus;
3023 	}
3024 	if (rcode != EX_OK && q->q_rstatus == NULL &&
3025 	    q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3026 	    strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3027 	{
3028 		char buf[16];
3029 
3030 		(void) snprintf(buf, sizeof buf, "%d", rcode);
3031 		q->q_rstatus = newstr(buf);
3032 	}
3033 
3034 	q->q_statdate = curtime();
3035 	if (CurHostName != NULL && CurHostName[0] != '\0' &&
3036 	    mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3037 		q->q_statmta = newstr(CurHostName);
3038 }
3039 /*
3040 **  ENDMAILER -- Wait for mailer to terminate.
3041 **
3042 **	We should never get fatal errors (e.g., segmentation
3043 **	violation), so we report those specially.  For other
3044 **	errors, we choose a status message (into statmsg),
3045 **	and if it represents an error, we print it.
3046 **
3047 **	Parameters:
3048 **		pid -- pid of mailer.
3049 **		e -- the current envelope.
3050 **		pv -- the parameter vector that invoked the mailer
3051 **			(for error messages).
3052 **
3053 **	Returns:
3054 **		exit code of mailer.
3055 **
3056 **	Side Effects:
3057 **		none.
3058 */
3059 
3060 static jmp_buf	EndWaitTimeout;
3061 
3062 static void
3063 endwaittimeout()
3064 {
3065 	/*
3066 	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3067 	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3068 	**	DOING.
3069 	*/
3070 
3071 	errno = ETIMEDOUT;
3072 	longjmp(EndWaitTimeout, 1);
3073 }
3074 
3075 int
3076 endmailer(mci, e, pv)
3077 	register MCI *mci;
3078 	register ENVELOPE *e;
3079 	char **pv;
3080 {
3081 	int st;
3082 	int save_errno = errno;
3083 	char buf[MAXLINE];
3084 	EVENT *ev = NULL;
3085 
3086 
3087 	mci_unlock_host(mci);
3088 
3089 	/* close output to mailer */
3090 	if (mci->mci_out != NULL)
3091 		(void) fclose(mci->mci_out);
3092 
3093 	/* copy any remaining input to transcript */
3094 	if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3095 	    e->e_xfp != NULL)
3096 	{
3097 		while (sfgets(buf, sizeof buf, mci->mci_in,
3098 		       TimeOuts.to_quit, "Draining Input") != NULL)
3099 			(void) fputs(buf, e->e_xfp);
3100 	}
3101 
3102 #if SASL
3103 	/* shutdown SASL */
3104 	if (bitset(MCIF_AUTHACT, mci->mci_flags))
3105 	{
3106 		sasl_dispose(&mci->mci_conn);
3107 		mci->mci_flags &= ~MCIF_AUTHACT;
3108 	}
3109 #endif /* SASL */
3110 
3111 #if STARTTLS
3112 	/* shutdown TLS */
3113 	(void) endtlsclt(mci);
3114 #endif /* STARTTLS */
3115 
3116 	/* now close the input */
3117 	if (mci->mci_in != NULL)
3118 		(void) fclose(mci->mci_in);
3119 	mci->mci_in = mci->mci_out = NULL;
3120 	mci->mci_state = MCIS_CLOSED;
3121 
3122 	errno = save_errno;
3123 
3124 	/* in the IPC case there is nothing to wait for */
3125 	if (mci->mci_pid == 0)
3126 		return EX_OK;
3127 
3128 	/* put a timeout around the wait */
3129 	if (mci->mci_mailer->m_wait > 0)
3130 	{
3131 		if (setjmp(EndWaitTimeout) == 0)
3132 			ev = setevent(mci->mci_mailer->m_wait,
3133 				      endwaittimeout, 0);
3134 		else
3135 		{
3136 			syserr("endmailer %s: wait timeout (%ld)",
3137 			       mci->mci_mailer->m_name,
3138 			       (long) mci->mci_mailer->m_wait);
3139 			return EX_TEMPFAIL;
3140 		}
3141 	}
3142 
3143 	/* wait for the mailer process, collect status */
3144 	st = waitfor(mci->mci_pid);
3145 	save_errno = errno;
3146 	if (ev != NULL)
3147 		clrevent(ev);
3148 	errno = save_errno;
3149 
3150 	if (st == -1)
3151 	{
3152 		syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3153 		return EX_SOFTWARE;
3154 	}
3155 
3156 	if (WIFEXITED(st))
3157 	{
3158 		/* normal death -- return status */
3159 		return (WEXITSTATUS(st));
3160 	}
3161 
3162 	/* it died a horrid death */
3163 	syserr("451 4.3.0 mailer %s died with signal %d%s",
3164 		mci->mci_mailer->m_name, WTERMSIG(st),
3165 		WCOREDUMP(st) ? " (core dumped)" :
3166 		(WIFSTOPPED(st) ? " (stopped)" : ""));
3167 
3168 	/* log the arguments */
3169 	if (pv != NULL && e->e_xfp != NULL)
3170 	{
3171 		register char **av;
3172 
3173 		fprintf(e->e_xfp, "Arguments:");
3174 		for (av = pv; *av != NULL; av++)
3175 			fprintf(e->e_xfp, " %s", *av);
3176 		fprintf(e->e_xfp, "\n");
3177 	}
3178 
3179 	ExitStat = EX_TEMPFAIL;
3180 	return EX_TEMPFAIL;
3181 }
3182 /*
3183 **  GIVERESPONSE -- Interpret an error response from a mailer
3184 **
3185 **	Parameters:
3186 **		status -- the status code from the mailer (high byte
3187 **			only; core dumps must have been taken care of
3188 **			already).
3189 **		dsn -- the DSN associated with the address, if any.
3190 **		m -- the mailer info for this mailer.
3191 **		mci -- the mailer connection info -- can be NULL if the
3192 **			response is given before the connection is made.
3193 **		ctladdr -- the controlling address for the recipient
3194 **			address(es).
3195 **		xstart -- the transaction start time, for computing
3196 **			transaction delays.
3197 **		e -- the current envelope.
3198 **
3199 **	Returns:
3200 **		none.
3201 **
3202 **	Side Effects:
3203 **		Errors may be incremented.
3204 **		ExitStat may be set.
3205 */
3206 
3207 void
3208 giveresponse(status, dsn, m, mci, ctladdr, xstart, e)
3209 	int status;
3210 	char *dsn;
3211 	register MAILER *m;
3212 	register MCI *mci;
3213 	ADDRESS *ctladdr;
3214 	time_t xstart;
3215 	ENVELOPE *e;
3216 {
3217 	register const char *statmsg;
3218 	extern char *SysExMsg[];
3219 	register int i;
3220 	int errnum = errno;
3221 	int off = 4;
3222 	extern int N_SysEx;
3223 	char dsnbuf[ENHSCLEN];
3224 	char buf[MAXLINE];
3225 
3226 	if (e == NULL)
3227 		syserr("giveresponse: null envelope");
3228 
3229 	/*
3230 	**  Compute status message from code.
3231 	*/
3232 
3233 	i = status - EX__BASE;
3234 	if (status == 0)
3235 	{
3236 		statmsg = "250 2.0.0 Sent";
3237 		if (e->e_statmsg != NULL)
3238 		{
3239 			(void) snprintf(buf, sizeof buf, "%s (%s)",
3240 					statmsg,
3241 					shortenstring(e->e_statmsg, 403));
3242 			statmsg = buf;
3243 		}
3244 	}
3245 	else if (i < 0 || i >= N_SysEx)
3246 	{
3247 		(void) snprintf(buf, sizeof buf,
3248 				"554 5.3.0 unknown mailer error %d",
3249 				status);
3250 		status = EX_UNAVAILABLE;
3251 		statmsg = buf;
3252 	}
3253 	else if (status == EX_TEMPFAIL)
3254 	{
3255 		char *bp = buf;
3256 
3257 		snprintf(bp, SPACELEFT(buf, bp), "%s", SysExMsg[i] + 1);
3258 		bp += strlen(bp);
3259 #if NAMED_BIND
3260 		if (h_errno == TRY_AGAIN)
3261 			statmsg = errstring(h_errno+E_DNSBASE);
3262 		else
3263 #endif /* NAMED_BIND */
3264 		{
3265 			if (errnum != 0)
3266 				statmsg = errstring(errnum);
3267 			else
3268 			{
3269 #if SMTP
3270 				statmsg = SmtpError;
3271 #else /* SMTP */
3272 				statmsg = NULL;
3273 #endif /* SMTP */
3274 			}
3275 		}
3276 		if (statmsg != NULL && statmsg[0] != '\0')
3277 		{
3278 			switch (errnum)
3279 			{
3280 #ifdef ENETDOWN
3281 			  case ENETDOWN:	/* Network is down */
3282 #endif /* ENETDOWN */
3283 #ifdef ENETUNREACH
3284 			  case ENETUNREACH:	/* Network is unreachable */
3285 #endif /* ENETUNREACH */
3286 #ifdef ENETRESET
3287 			  case ENETRESET:	/* Network dropped connection on reset */
3288 #endif /* ENETRESET */
3289 #ifdef ECONNABORTED
3290 			  case ECONNABORTED:	/* Software caused connection abort */
3291 #endif /* ECONNABORTED */
3292 #ifdef EHOSTDOWN
3293 			  case EHOSTDOWN:	/* Host is down */
3294 #endif /* EHOSTDOWN */
3295 #ifdef EHOSTUNREACH
3296 			  case EHOSTUNREACH:	/* No route to host */
3297 #endif /* EHOSTUNREACH */
3298 				if (mci->mci_host != NULL)
3299 				{
3300 					snprintf(bp, SPACELEFT(buf, bp),
3301 						 ": %s", mci->mci_host);
3302 					bp += strlen(bp);
3303 				}
3304 				break;
3305 			}
3306 			snprintf(bp, SPACELEFT(buf, bp), ": %s", statmsg);
3307 		}
3308 		statmsg = buf;
3309 	}
3310 #if NAMED_BIND
3311 	else if (status == EX_NOHOST && h_errno != 0)
3312 	{
3313 		statmsg = errstring(h_errno + E_DNSBASE);
3314 		(void) snprintf(buf, sizeof buf, "%s (%s)",
3315 			SysExMsg[i] + 1, statmsg);
3316 		statmsg = buf;
3317 	}
3318 #endif /* NAMED_BIND */
3319 	else
3320 	{
3321 		statmsg = SysExMsg[i];
3322 		if (*statmsg++ == ':' && errnum != 0)
3323 		{
3324 			(void) snprintf(buf, sizeof buf, "%s: %s",
3325 				statmsg, errstring(errnum));
3326 			statmsg = buf;
3327 		}
3328 	}
3329 
3330 	/*
3331 	**  Print the message as appropriate
3332 	*/
3333 
3334 	if (status == EX_OK || status == EX_TEMPFAIL)
3335 	{
3336 		extern char MsgBuf[];
3337 
3338 		if ((off = isenhsc(statmsg + 4, ' ')) > 0)
3339 		{
3340 			if (dsn == NULL)
3341 			{
3342 				snprintf(dsnbuf, sizeof dsnbuf,
3343 					 "%.*s", off, statmsg + 4);
3344 				dsn = dsnbuf;
3345 			}
3346 			off += 5;
3347 		}
3348 		else
3349 		{
3350 			off = 4;
3351 		}
3352 		message("%s", statmsg + off);
3353 		if (status == EX_TEMPFAIL && e->e_xfp != NULL)
3354 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
3355 	}
3356 	else
3357 	{
3358 		char mbuf[ENHSCLEN + 4];
3359 
3360 		Errors++;
3361 		if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
3362 		    off < sizeof mbuf - 4)
3363 		{
3364 			if (dsn == NULL)
3365 			{
3366 				snprintf(dsnbuf, sizeof dsnbuf,
3367 					 "%.*s", off, statmsg + 4);
3368 				dsn = dsnbuf;
3369 			}
3370 			off += 5;
3371 			(void) strlcpy(mbuf, statmsg, off);
3372 			(void) strlcat(mbuf, " %s", sizeof mbuf);
3373 		}
3374 		else
3375 		{
3376 			dsnbuf[0] = '\0';
3377 			(void) snprintf(mbuf, sizeof mbuf, "%.3s %%s", statmsg);
3378 			off = 4;
3379 		}
3380 		usrerr(mbuf, &statmsg[off]);
3381 	}
3382 
3383 	/*
3384 	**  Final cleanup.
3385 	**	Log a record of the transaction.  Compute the new
3386 	**	ExitStat -- if we already had an error, stick with
3387 	**	that.
3388 	*/
3389 
3390 	if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
3391 	    LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
3392 		logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e);
3393 
3394 	if (tTd(11, 2))
3395 		dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s\n",
3396 			status,
3397 			dsn == NULL ? "<NULL>" : dsn,
3398 			e->e_message == NULL ? "<NULL>" : e->e_message);
3399 
3400 	if (status != EX_TEMPFAIL)
3401 		setstat(status);
3402 	if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
3403 	{
3404 		if (e->e_message != NULL)
3405 			sm_free(e->e_message);
3406 		e->e_message = newstr(statmsg + off);
3407 	}
3408 	errno = 0;
3409 #if NAMED_BIND
3410 	SM_SET_H_ERRNO(0);
3411 #endif /* NAMED_BIND */
3412 }
3413 /*
3414 **  LOGDELIVERY -- log the delivery in the system log
3415 **
3416 **	Care is taken to avoid logging lines that are too long, because
3417 **	some versions of syslog have an unfortunate proclivity for core
3418 **	dumping.  This is a hack, to be sure, that is at best empirical.
3419 **
3420 **	Parameters:
3421 **		m -- the mailer info.  Can be NULL for initial queue.
3422 **		mci -- the mailer connection info -- can be NULL if the
3423 **			log is occurring when no connection is active.
3424 **		dsn -- the DSN attached to the status.
3425 **		status -- the message to print for the status.
3426 **		ctladdr -- the controlling address for the to list.
3427 **		xstart -- the transaction start time, used for
3428 **			computing transaction delay.
3429 **		e -- the current envelope.
3430 **
3431 **	Returns:
3432 **		none
3433 **
3434 **	Side Effects:
3435 **		none
3436 */
3437 
3438 void
3439 logdelivery(m, mci, dsn, status, ctladdr, xstart, e)
3440 	MAILER *m;
3441 	register MCI *mci;
3442 	char *dsn;
3443 	const char *status;
3444 	ADDRESS *ctladdr;
3445 	time_t xstart;
3446 	register ENVELOPE *e;
3447 {
3448 	register char *bp;
3449 	register char *p;
3450 	int l;
3451 	time_t now;
3452 	char buf[1024];
3453 
3454 #if (SYSLOG_BUFSIZE) >= 256
3455 	/* ctladdr: max 106 bytes */
3456 	bp = buf;
3457 	if (ctladdr != NULL)
3458 	{
3459 		snprintf(bp, SPACELEFT(buf, bp), ", ctladdr=%s",
3460 			 shortenstring(ctladdr->q_paddr, 83));
3461 		bp += strlen(bp);
3462 		if (bitset(QGOODUID, ctladdr->q_flags))
3463 		{
3464 			(void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
3465 					(int) ctladdr->q_uid,
3466 					(int) ctladdr->q_gid);
3467 			bp += strlen(bp);
3468 		}
3469 	}
3470 
3471 	/* delay & xdelay: max 41 bytes */
3472 	now = curtime();
3473 	snprintf(bp, SPACELEFT(buf, bp), ", delay=%s",
3474 		 pintvl(now - e->e_ctime, TRUE));
3475 	bp += strlen(bp);
3476 
3477 	if (xstart != (time_t) 0)
3478 	{
3479 		snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
3480 			 pintvl(now - xstart, TRUE));
3481 		bp += strlen(bp);
3482 	}
3483 
3484 	/* mailer: assume about 19 bytes (max 10 byte mailer name) */
3485 	if (m != NULL)
3486 	{
3487 		snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
3488 		bp += strlen(bp);
3489 	}
3490 
3491 	/* pri: changes with each delivery attempt */
3492 	snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld", e->e_msgpriority);
3493 	bp += strlen(bp);
3494 
3495 	/* relay: max 66 bytes for IPv4 addresses */
3496 	if (mci != NULL && mci->mci_host != NULL)
3497 	{
3498 # if DAEMON
3499 		extern SOCKADDR CurHostAddr;
3500 # endif /* DAEMON */
3501 
3502 		snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
3503 			 shortenstring(mci->mci_host, 40));
3504 		bp += strlen(bp);
3505 
3506 # if DAEMON
3507 		if (CurHostAddr.sa.sa_family != 0)
3508 		{
3509 			snprintf(bp, SPACELEFT(buf, bp), " [%s]",
3510 				 anynet_ntoa(&CurHostAddr));
3511 		}
3512 # endif /* DAEMON */
3513 	}
3514 	else if (strcmp(status, "queued") != 0)
3515 	{
3516 		p = macvalue('h', e);
3517 		if (p != NULL && p[0] != '\0')
3518 		{
3519 			snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
3520 				 shortenstring(p, 40));
3521 		}
3522 	}
3523 	bp += strlen(bp);
3524 
3525 	/* dsn */
3526 	if (dsn != NULL && *dsn != '\0')
3527 	{
3528 		snprintf(bp, SPACELEFT(buf, bp), ", dsn=%s",
3529 			 shortenstring(dsn, ENHSCLEN));
3530 		bp += strlen(bp);
3531 	}
3532 
3533 # define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
3534 # if (STATLEN) < 63
3535 #  undef STATLEN
3536 #  define STATLEN	63
3537 # endif /* (STATLEN) < 63 */
3538 # if (STATLEN) > 203
3539 #  undef STATLEN
3540 #  define STATLEN	203
3541 # endif /* (STATLEN) > 203 */
3542 
3543 	/* stat: max 210 bytes */
3544 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
3545 	{
3546 		/* desperation move -- truncate data */
3547 		bp = buf + sizeof buf - ((STATLEN) + 17);
3548 		(void) strlcpy(bp, "...", SPACELEFT(buf, bp));
3549 		bp += 3;
3550 	}
3551 
3552 	(void) strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
3553 	bp += strlen(bp);
3554 
3555 	(void) strlcpy(bp, shortenstring(status, STATLEN), SPACELEFT(buf, bp));
3556 
3557 	/* id, to: max 13 + TOBUFSIZE bytes */
3558 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
3559 	p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
3560 	while (strlen(p) >= (SIZE_T) l)
3561 	{
3562 		register char *q;
3563 
3564 #if _FFR_DYNAMIC_TOBUF
3565 		for (q = p + l; q > p; q--)
3566 		{
3567 			if (*q == ',')
3568 				break;
3569 		}
3570 		if (p == q)
3571 			break;
3572 #else /* _FFR_DYNAMIC_TOBUF */
3573 		q = strchr(p + l, ',');
3574 		if (q == NULL)
3575 			break;
3576 #endif /* _FFR_DYNAMIC_TOBUF */
3577 
3578 		sm_syslog(LOG_INFO, e->e_id,
3579 			  "to=%.*s [more]%s",
3580 			  (int) (++q - p), p, buf);
3581 		p = q;
3582 	}
3583 #if _FFR_DYNAMIC_TOBUF
3584 	sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
3585 #else /* _FFR_DYNAMIC_TOBUF */
3586 	sm_syslog(LOG_INFO, e->e_id, "to=%s%s", p, buf);
3587 #endif /* _FFR_DYNAMIC_TOBUF */
3588 
3589 #else /* (SYSLOG_BUFSIZE) >= 256 */
3590 
3591 	l = SYSLOG_BUFSIZE - 85;
3592 	p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
3593 	while (strlen(p) >= (SIZE_T) l)
3594 	{
3595 		register char *q;
3596 
3597 #if _FFR_DYNAMIC_TOBUF
3598 		for (q = p + l; q > p; q--)
3599 		{
3600 			if (*q == ',')
3601 				break;
3602 		}
3603 		if (p == q)
3604 			break;
3605 #else /* _FFR_DYNAMIC_TOBUF */
3606 		q = strchr(p + l, ',');
3607 		if (q == NULL)
3608 			break;
3609 #endif /* _FFR_DYNAMIC_TOBUF */
3610 
3611 		sm_syslog(LOG_INFO, e->e_id,
3612 			  "to=%.*s [more]",
3613 			  (int) (++q - p), p);
3614 		p = q;
3615 	}
3616 #if _FFR_DYNAMIC_TOBUF
3617 	sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
3618 #else /* _FFR_DYNAMIC_TOBUF */
3619 	sm_syslog(LOG_INFO, e->e_id, "to=%s", p);
3620 #endif /* _FFR_DYNAMIC_TOBUF */
3621 
3622 	if (ctladdr != NULL)
3623 	{
3624 		bp = buf;
3625 		snprintf(bp, SPACELEFT(buf, bp), "ctladdr=%s",
3626 			 shortenstring(ctladdr->q_paddr, 83));
3627 		bp += strlen(bp);
3628 		if (bitset(QGOODUID, ctladdr->q_flags))
3629 		{
3630 			(void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
3631 					ctladdr->q_uid, ctladdr->q_gid);
3632 			bp += strlen(bp);
3633 		}
3634 		sm_syslog(LOG_INFO, e->e_id, "%s", buf);
3635 	}
3636 	bp = buf;
3637 	snprintf(bp, SPACELEFT(buf, bp), "delay=%s",
3638 		 pintvl(now - e->e_ctime, TRUE));
3639 	bp += strlen(bp);
3640 	if (xstart != (time_t) 0)
3641 	{
3642 		snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
3643 			 pintvl(now - xstart, TRUE));
3644 		bp += strlen(bp);
3645 	}
3646 
3647 	if (m != NULL)
3648 	{
3649 		snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
3650 		bp += strlen(bp);
3651 	}
3652 	sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
3653 
3654 	buf[0] = '\0';
3655 	bp = buf;
3656 	if (mci != NULL && mci->mci_host != NULL)
3657 	{
3658 # if DAEMON
3659 		extern SOCKADDR CurHostAddr;
3660 # endif /* DAEMON */
3661 
3662 		snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s", mci->mci_host);
3663 		bp += strlen(bp);
3664 
3665 # if DAEMON
3666 		if (CurHostAddr.sa.sa_family != 0)
3667 			snprintf(bp, SPACELEFT(buf, bp), " [%.100s]",
3668 				anynet_ntoa(&CurHostAddr));
3669 # endif /* DAEMON */
3670 	}
3671 	else if (strcmp(status, "queued") != 0)
3672 	{
3673 		p = macvalue('h', e);
3674 		if (p != NULL && p[0] != '\0')
3675 			snprintf(buf, sizeof buf, "relay=%.100s", p);
3676 	}
3677 	if (buf[0] != '\0')
3678 		sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
3679 
3680 	sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
3681 #endif /* (SYSLOG_BUFSIZE) >= 256 */
3682 }
3683 /*
3684 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
3685 **
3686 **	This can be made an arbitrary message separator by changing $l
3687 **
3688 **	One of the ugliest hacks seen by human eyes is contained herein:
3689 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
3690 **	does a well-meaning programmer such as myself have to deal with
3691 **	this kind of antique garbage????
3692 **
3693 **	Parameters:
3694 **		mci -- the connection information.
3695 **		e -- the envelope.
3696 **
3697 **	Returns:
3698 **		none
3699 **
3700 **	Side Effects:
3701 **		outputs some text to fp.
3702 */
3703 
3704 void
3705 putfromline(mci, e)
3706 	register MCI *mci;
3707 	ENVELOPE *e;
3708 {
3709 	char *template = UnixFromLine;
3710 	char buf[MAXLINE];
3711 	char xbuf[MAXLINE];
3712 
3713 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
3714 		return;
3715 
3716 	mci->mci_flags |= MCIF_INHEADER;
3717 
3718 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
3719 	{
3720 		char *bang;
3721 
3722 		expand("\201g", buf, sizeof buf, e);
3723 		bang = strchr(buf, '!');
3724 		if (bang == NULL)
3725 		{
3726 			char *at;
3727 			char hname[MAXNAME];
3728 
3729 			/*
3730 			**  If we can construct a UUCP path, do so
3731 			*/
3732 
3733 			at = strrchr(buf, '@');
3734 			if (at == NULL)
3735 			{
3736 				expand("\201k", hname, sizeof hname, e);
3737 				at = hname;
3738 			}
3739 			else
3740 				*at++ = '\0';
3741 			(void) snprintf(xbuf, sizeof xbuf,
3742 				"From %.800s  \201d remote from %.100s\n",
3743 				buf, at);
3744 		}
3745 		else
3746 		{
3747 			*bang++ = '\0';
3748 			(void) snprintf(xbuf, sizeof xbuf,
3749 				"From %.800s  \201d remote from %.100s\n",
3750 				bang, buf);
3751 			template = xbuf;
3752 		}
3753 	}
3754 	expand(template, buf, sizeof buf, e);
3755 	putxline(buf, strlen(buf), mci, PXLF_HEADER);
3756 }
3757 /*
3758 **  PUTBODY -- put the body of a message.
3759 **
3760 **	Parameters:
3761 **		mci -- the connection information.
3762 **		e -- the envelope to put out.
3763 **		separator -- if non-NULL, a message separator that must
3764 **			not be permitted in the resulting message.
3765 **
3766 **	Returns:
3767 **		none.
3768 **
3769 **	Side Effects:
3770 **		The message is written onto fp.
3771 */
3772 
3773 /* values for output state variable */
3774 #define OS_HEAD		0	/* at beginning of line */
3775 #define OS_CR		1	/* read a carriage return */
3776 #define OS_INLINE	2	/* putting rest of line */
3777 
3778 void
3779 putbody(mci, e, separator)
3780 	register MCI *mci;
3781 	register ENVELOPE *e;
3782 	char *separator;
3783 {
3784 	bool dead = FALSE;
3785 	char buf[MAXLINE];
3786 	char *boundaries[MAXMIMENESTING + 1];
3787 
3788 	/*
3789 	**  Output the body of the message
3790 	*/
3791 
3792 	if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
3793 	{
3794 		char *df = queuename(e, 'd');
3795 
3796 		e->e_dfp = fopen(df, "r");
3797 		if (e->e_dfp == NULL)
3798 		{
3799 			char *msg = "!putbody: Cannot open %s for %s from %s";
3800 
3801 			if (errno == ENOENT)
3802 				msg++;
3803 			syserr(msg, df, e->e_to, e->e_from.q_paddr);
3804 		}
3805 	}
3806 	if (e->e_dfp == NULL)
3807 	{
3808 		if (bitset(MCIF_INHEADER, mci->mci_flags))
3809 		{
3810 			putline("", mci);
3811 			mci->mci_flags &= ~MCIF_INHEADER;
3812 		}
3813 		putline("<<< No Message Collected >>>", mci);
3814 		goto endofmessage;
3815 	}
3816 
3817 	if (e->e_dfino == (ino_t) 0)
3818 	{
3819 		struct stat stbuf;
3820 
3821 		if (fstat(fileno(e->e_dfp), &stbuf) < 0)
3822 			e->e_dfino = -1;
3823 		else
3824 		{
3825 			e->e_dfdev = stbuf.st_dev;
3826 			e->e_dfino = stbuf.st_ino;
3827 		}
3828 	}
3829 
3830 	/* paranoia: the df file should always be in a rewound state */
3831 	(void) bfrewind(e->e_dfp);
3832 
3833 #if MIME8TO7
3834 	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
3835 	{
3836 		/*
3837 		**  Do 8 to 7 bit MIME conversion.
3838 		*/
3839 
3840 		/* make sure it looks like a MIME message */
3841 		if (hvalue("MIME-Version", e->e_header) == NULL)
3842 			putline("MIME-Version: 1.0", mci);
3843 
3844 		if (hvalue("Content-Type", e->e_header) == NULL)
3845 		{
3846 			snprintf(buf, sizeof buf,
3847 				"Content-Type: text/plain; charset=%s",
3848 				defcharset(e));
3849 			putline(buf, mci);
3850 		}
3851 
3852 		/* now do the hard work */
3853 		boundaries[0] = NULL;
3854 		mci->mci_flags |= MCIF_INHEADER;
3855 		(void) mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
3856 	}
3857 # if MIME7TO8
3858 	else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
3859 	{
3860 		(void) mime7to8(mci, e->e_header, e);
3861 	}
3862 # endif /* MIME7TO8 */
3863 	else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
3864 	{
3865 		bool oldsuprerrs = SuprErrs;
3866 
3867 		/* Use mime8to7 to check multipart for MIME header overflows */
3868 		boundaries[0] = NULL;
3869 		mci->mci_flags |= MCIF_INHEADER;
3870 
3871 		/*
3872 		**  If EF_DONT_MIME is set, we have a broken MIME message
3873 		**  and don't want to generate a new bounce message whose
3874 		**  body propagates the broken MIME.  We can't just not call
3875 		**  mime8to7() as is done above since we need the security
3876 		**  checks.  The best we can do is suppress the errors.
3877 		*/
3878 
3879 		if (bitset(EF_DONT_MIME, e->e_flags))
3880 			SuprErrs = TRUE;
3881 
3882 		(void) mime8to7(mci, e->e_header, e, boundaries,
3883 				M87F_OUTER|M87F_NO8TO7);
3884 
3885 		/* restore SuprErrs */
3886 		SuprErrs = oldsuprerrs;
3887 	}
3888 	else
3889 #endif /* MIME8TO7 */
3890 	{
3891 		int ostate;
3892 		register char *bp;
3893 		register char *pbp;
3894 		register int c;
3895 		register char *xp;
3896 		int padc;
3897 		char *buflim;
3898 		int pos = 0;
3899 		char peekbuf[12];
3900 
3901 		if (bitset(MCIF_INHEADER, mci->mci_flags))
3902 		{
3903 			putline("", mci);
3904 			mci->mci_flags &= ~MCIF_INHEADER;
3905 		}
3906 
3907 		/* determine end of buffer; allow for short mailer lines */
3908 		buflim = &buf[sizeof buf - 1];
3909 		if (mci->mci_mailer->m_linelimit > 0 &&
3910 		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
3911 			buflim = &buf[mci->mci_mailer->m_linelimit - 1];
3912 
3913 		/* copy temp file to output with mapping */
3914 		ostate = OS_HEAD;
3915 		bp = buf;
3916 		pbp = peekbuf;
3917 		while (!ferror(mci->mci_out) && !dead)
3918 		{
3919 			if (pbp > peekbuf)
3920 				c = *--pbp;
3921 			else if ((c = getc(e->e_dfp)) == EOF)
3922 				break;
3923 			if (bitset(MCIF_7BIT, mci->mci_flags))
3924 				c &= 0x7f;
3925 			switch (ostate)
3926 			{
3927 			  case OS_HEAD:
3928 #if _FFR_NONULLS
3929 				if (c == '\0' &&
3930 				    bitnset(M_NONULLS, mci->mci_mailer->m_flags))
3931 					break;
3932 #endif /* _FFR_NONULLS */
3933 				if (c != '\r' && c != '\n' && bp < buflim)
3934 				{
3935 					*bp++ = c;
3936 					break;
3937 				}
3938 
3939 				/* check beginning of line for special cases */
3940 				*bp = '\0';
3941 				pos = 0;
3942 				padc = EOF;
3943 				if (buf[0] == 'F' &&
3944 				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
3945 				    strncmp(buf, "From ", 5) == 0)
3946 				{
3947 					padc = '>';
3948 				}
3949 				if (buf[0] == '-' && buf[1] == '-' &&
3950 				    separator != NULL)
3951 				{
3952 					/* possible separator */
3953 					int sl = strlen(separator);
3954 
3955 					if (strncmp(&buf[2], separator, sl) == 0)
3956 						padc = ' ';
3957 				}
3958 				if (buf[0] == '.' &&
3959 				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
3960 				{
3961 					padc = '.';
3962 				}
3963 
3964 				/* now copy out saved line */
3965 				if (TrafficLogFile != NULL)
3966 				{
3967 					fprintf(TrafficLogFile, "%05d >>> ",
3968 						(int) getpid());
3969 					if (padc != EOF)
3970 						(void) putc(padc,
3971 							    TrafficLogFile);
3972 					for (xp = buf; xp < bp; xp++)
3973 						(void) putc((unsigned char) *xp,
3974 							    TrafficLogFile);
3975 					if (c == '\n')
3976 						(void) fputs(mci->mci_mailer->m_eol,
3977 							     TrafficLogFile);
3978 				}
3979 				if (padc != EOF)
3980 				{
3981 					if (putc(padc, mci->mci_out) == EOF)
3982 					{
3983 						dead = TRUE;
3984 						continue;
3985 					}
3986 					else
3987 					{
3988 						/* record progress for DATA timeout */
3989 						DataProgress = TRUE;
3990 					}
3991 					pos++;
3992 				}
3993 				for (xp = buf; xp < bp; xp++)
3994 				{
3995 					if (putc((unsigned char) *xp,
3996 						 mci->mci_out) == EOF)
3997 					{
3998 						dead = TRUE;
3999 						break;
4000 					}
4001 					else
4002 					{
4003 						/* record progress for DATA timeout */
4004 						DataProgress = TRUE;
4005 					}
4006 				}
4007 				if (dead)
4008 					continue;
4009 				if (c == '\n')
4010 				{
4011 					if (fputs(mci->mci_mailer->m_eol,
4012 						  mci->mci_out) == EOF)
4013 						break;
4014 					else
4015 					{
4016 						/* record progress for DATA timeout */
4017 						DataProgress = TRUE;
4018 					}
4019 					pos = 0;
4020 				}
4021 				else
4022 				{
4023 					pos += bp - buf;
4024 					if (c != '\r')
4025 						*pbp++ = c;
4026 				}
4027 
4028 				bp = buf;
4029 
4030 				/* determine next state */
4031 				if (c == '\n')
4032 					ostate = OS_HEAD;
4033 				else if (c == '\r')
4034 					ostate = OS_CR;
4035 				else
4036 					ostate = OS_INLINE;
4037 				continue;
4038 
4039 			  case OS_CR:
4040 				if (c == '\n')
4041 				{
4042 					/* got CRLF */
4043 					if (fputs(mci->mci_mailer->m_eol,
4044 						  mci->mci_out) == EOF)
4045 						continue;
4046 					else
4047 					{
4048 						/* record progress for DATA timeout */
4049 						DataProgress = TRUE;
4050 					}
4051 
4052 					if (TrafficLogFile != NULL)
4053 					{
4054 						(void) fputs(mci->mci_mailer->m_eol,
4055 							     TrafficLogFile);
4056 					}
4057 					ostate = OS_HEAD;
4058 					continue;
4059 				}
4060 
4061 				/* had a naked carriage return */
4062 				*pbp++ = c;
4063 				c = '\r';
4064 				ostate = OS_INLINE;
4065 				goto putch;
4066 
4067 			  case OS_INLINE:
4068 				if (c == '\r')
4069 				{
4070 					ostate = OS_CR;
4071 					continue;
4072 				}
4073 #if _FFR_NONULLS
4074 				if (c == '\0' &&
4075 				    bitnset(M_NONULLS, mci->mci_mailer->m_flags))
4076 					break;
4077 #endif /* _FFR_NONULLS */
4078 putch:
4079 				if (mci->mci_mailer->m_linelimit > 0 &&
4080 				    pos >= mci->mci_mailer->m_linelimit - 1 &&
4081 				    c != '\n')
4082 				{
4083 					int d;
4084 
4085 					/* check next character for EOL */
4086 					if (pbp > peekbuf)
4087 						d = *(pbp - 1);
4088 					else if ((d = getc(e->e_dfp)) != EOF)
4089 						*pbp++ = d;
4090 
4091 					if (d == '\n' || d == EOF)
4092 					{
4093 						if (TrafficLogFile != NULL)
4094 							(void) putc((unsigned char) c,
4095 							    TrafficLogFile);
4096 						if (putc((unsigned char) c,
4097 							 mci->mci_out) == EOF)
4098 						{
4099 							dead = TRUE;
4100 							continue;
4101 						}
4102 						else
4103 						{
4104 							/* record progress for DATA timeout */
4105 							DataProgress = TRUE;
4106 						}
4107 						pos++;
4108 						continue;
4109 					}
4110 
4111 					if (putc('!', mci->mci_out) == EOF ||
4112 					    fputs(mci->mci_mailer->m_eol,
4113 						  mci->mci_out) == EOF)
4114 					{
4115 						dead = TRUE;
4116 						continue;
4117 					}
4118 					else
4119 					{
4120 						/* record progress for DATA timeout */
4121 						DataProgress = TRUE;
4122 					}
4123 
4124 					if (TrafficLogFile != NULL)
4125 					{
4126 						fprintf(TrafficLogFile, "!%s",
4127 							mci->mci_mailer->m_eol);
4128 					}
4129 					ostate = OS_HEAD;
4130 					*pbp++ = c;
4131 					continue;
4132 				}
4133 				if (c == '\n')
4134 				{
4135 					if (TrafficLogFile != NULL)
4136 						(void) fputs(mci->mci_mailer->m_eol,
4137 						      TrafficLogFile);
4138 					if (fputs(mci->mci_mailer->m_eol,
4139 						  mci->mci_out) == EOF)
4140 						continue;
4141 					else
4142 					{
4143 						/* record progress for DATA timeout */
4144 						DataProgress = TRUE;
4145 					}
4146 					pos = 0;
4147 					ostate = OS_HEAD;
4148 				}
4149 				else
4150 				{
4151 					if (TrafficLogFile != NULL)
4152 						(void) putc((unsigned char) c,
4153 							    TrafficLogFile);
4154 					if (putc((unsigned char) c,
4155 						 mci->mci_out) == EOF)
4156 					{
4157 						dead = TRUE;
4158 						continue;
4159 					}
4160 					else
4161 					{
4162 						/* record progress for DATA timeout */
4163 						DataProgress = TRUE;
4164 					}
4165 					pos++;
4166 					ostate = OS_INLINE;
4167 				}
4168 				break;
4169 			}
4170 		}
4171 
4172 		/* make sure we are at the beginning of a line */
4173 		if (bp > buf)
4174 		{
4175 			if (TrafficLogFile != NULL)
4176 			{
4177 				for (xp = buf; xp < bp; xp++)
4178 					(void) putc((unsigned char) *xp,
4179 						    TrafficLogFile);
4180 			}
4181 			for (xp = buf; xp < bp; xp++)
4182 			{
4183 				if (putc((unsigned char) *xp, mci->mci_out) ==
4184 				    EOF)
4185 				{
4186 					dead = TRUE;
4187 					break;
4188 				}
4189 				else
4190 				{
4191 					/* record progress for DATA timeout */
4192 					DataProgress = TRUE;
4193 				}
4194 			}
4195 			pos += bp - buf;
4196 		}
4197 		if (!dead && pos > 0)
4198 		{
4199 			if (TrafficLogFile != NULL)
4200 				(void) fputs(mci->mci_mailer->m_eol,
4201 					     TrafficLogFile);
4202 			(void) fputs(mci->mci_mailer->m_eol, mci->mci_out);
4203 
4204 			/* record progress for DATA timeout */
4205 			DataProgress = TRUE;
4206 		}
4207 	}
4208 
4209 	if (ferror(e->e_dfp))
4210 	{
4211 		syserr("putbody: %s/df%s: read error",
4212 		       qid_printqueue(e->e_queuedir), e->e_id);
4213 		ExitStat = EX_IOERR;
4214 	}
4215 
4216 endofmessage:
4217 	/*
4218 	**  Since mailfile() uses e_dfp in a child process,
4219 	**  the file offset in the stdio library for the
4220 	**  parent process will not agree with the in-kernel
4221 	**  file offset since the file descriptor is shared
4222 	**  between the processes.  Therefore, it is vital
4223 	**  that the file always be rewound.  This forces the
4224 	**  kernel offset (lseek) and stdio library (ftell)
4225 	**  offset to match.
4226 	*/
4227 
4228 	if (e->e_dfp != NULL)
4229 		(void) bfrewind(e->e_dfp);
4230 
4231 	/* some mailers want extra blank line at end of message */
4232 	if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
4233 	    buf[0] != '\0' && buf[0] != '\n')
4234 		putline("", mci);
4235 
4236 	(void) fflush(mci->mci_out);
4237 	if (ferror(mci->mci_out) && errno != EPIPE)
4238 	{
4239 		syserr("putbody: write error");
4240 		ExitStat = EX_IOERR;
4241 	}
4242 
4243 	errno = 0;
4244 }
4245 /*
4246 **  MAILFILE -- Send a message to a file.
4247 **
4248 **	If the file has the setuid/setgid bits set, but NO execute
4249 **	bits, sendmail will try to become the owner of that file
4250 **	rather than the real user.  Obviously, this only works if
4251 **	sendmail runs as root.
4252 **
4253 **	This could be done as a subordinate mailer, except that it
4254 **	is used implicitly to save messages in ~/dead.letter.  We
4255 **	view this as being sufficiently important as to include it
4256 **	here.  For example, if the system is dying, we shouldn't have
4257 **	to create another process plus some pipes to save the message.
4258 **
4259 **	Parameters:
4260 **		filename -- the name of the file to send to.
4261 **		mailer -- mailer definition for recipient -- if NULL,
4262 **			use FileMailer.
4263 **		ctladdr -- the controlling address header -- includes
4264 **			the userid/groupid to be when sending.
4265 **		sfflags -- flags for opening.
4266 **		e -- the current envelope.
4267 **
4268 **	Returns:
4269 **		The exit code associated with the operation.
4270 **
4271 **	Side Effects:
4272 **		none.
4273 */
4274 
4275 static jmp_buf	CtxMailfileTimeout;
4276 
4277 int
4278 mailfile(filename, mailer, ctladdr, sfflags, e)
4279 	char *volatile filename;
4280 	MAILER *volatile mailer;
4281 	ADDRESS *ctladdr;
4282 	volatile long sfflags;
4283 	register ENVELOPE *e;
4284 {
4285 	register FILE *f;
4286 	register pid_t pid = -1;
4287 	volatile int mode;
4288 	int len;
4289 	off_t curoff;
4290 	bool suidwarn = geteuid() == 0;
4291 	char *p;
4292 	char *volatile realfile;
4293 	EVENT *ev;
4294 	char buf[MAXLINE + 1];
4295 	char targetfile[MAXPATHLEN + 1];
4296 
4297 	if (tTd(11, 1))
4298 	{
4299 		dprintf("mailfile %s\n  ctladdr=", filename);
4300 		printaddr(ctladdr, FALSE);
4301 	}
4302 
4303 	if (mailer == NULL)
4304 		mailer = FileMailer;
4305 
4306 	if (e->e_xfp != NULL)
4307 		(void) fflush(e->e_xfp);
4308 
4309 	/*
4310 	**  Special case /dev/null.  This allows us to restrict file
4311 	**  delivery to regular files only.
4312 	*/
4313 
4314 	if (strcmp(filename, "/dev/null") == 0)
4315 		return EX_OK;
4316 
4317 	/* check for 8-bit available */
4318 	if (bitset(EF_HAS8BIT, e->e_flags) &&
4319 	    bitnset(M_7BITS, mailer->m_flags) &&
4320 	    (bitset(EF_DONT_MIME, e->e_flags) ||
4321 	     !(bitset(MM_MIME8BIT, MimeMode) ||
4322 	       (bitset(EF_IS_MIME, e->e_flags) &&
4323 		bitset(MM_CVTMIME, MimeMode)))))
4324 	{
4325 		e->e_status = "5.6.3";
4326 		usrerrenh(e->e_status,
4327 		       "554 Cannot send 8-bit data to 7-bit destination");
4328 		return EX_DATAERR;
4329 	}
4330 
4331 	/* Find the actual file */
4332 	if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
4333 	{
4334 		len = strlen(SafeFileEnv);
4335 
4336 		if (strncmp(SafeFileEnv, filename, len) == 0)
4337 			filename += len;
4338 
4339 		if (len + strlen(filename) + 1 > MAXPATHLEN)
4340 		{
4341 			syserr("mailfile: filename too long (%s/%s)",
4342 			       SafeFileEnv, filename);
4343 			return EX_CANTCREAT;
4344 		}
4345 		(void) strlcpy(targetfile, SafeFileEnv, sizeof targetfile);
4346 		realfile = targetfile + len;
4347 		if (targetfile[len - 1] != '/')
4348 			(void) strlcat(targetfile, "/", sizeof targetfile);
4349 		if (*filename == '/')
4350 			filename++;
4351 		(void) strlcat(targetfile, filename, sizeof targetfile);
4352 	}
4353 	else if (mailer->m_rootdir != NULL)
4354 	{
4355 		expand(mailer->m_rootdir, targetfile, sizeof targetfile, e);
4356 		len = strlen(targetfile);
4357 
4358 		if (strncmp(targetfile, filename, len) == 0)
4359 			filename += len;
4360 
4361 		if (len + strlen(filename) + 1 > MAXPATHLEN)
4362 		{
4363 			syserr("mailfile: filename too long (%s/%s)",
4364 			       targetfile, filename);
4365 			return EX_CANTCREAT;
4366 		}
4367 		realfile = targetfile + len;
4368 		if (targetfile[len - 1] != '/')
4369 			(void) strlcat(targetfile, "/", sizeof targetfile);
4370 		if (*filename == '/')
4371 			(void) strlcat(targetfile, filename + 1,
4372 				       sizeof targetfile);
4373 		else
4374 			(void) strlcat(targetfile, filename, sizeof targetfile);
4375 	}
4376 	else
4377 	{
4378 		if (strlen(filename) > MAXPATHLEN)
4379 		{
4380 			syserr("mailfile: filename too long (%s)", filename);
4381 			return EX_CANTCREAT;
4382 		}
4383 		(void) strlcpy(targetfile, filename, sizeof targetfile);
4384 		realfile = targetfile;
4385 	}
4386 
4387 	/*
4388 	**  Fork so we can change permissions here.
4389 	**	Note that we MUST use fork, not vfork, because of
4390 	**	the complications of calling subroutines, etc.
4391 	*/
4392 
4393 	DOFORK(fork);
4394 
4395 	if (pid < 0)
4396 		return EX_OSERR;
4397 	else if (pid == 0)
4398 	{
4399 		/* child -- actually write to file */
4400 		struct stat stb;
4401 		MCI mcibuf;
4402 		int err;
4403 		volatile int oflags = O_WRONLY|O_APPEND;
4404 
4405 		/* Reset global flags */
4406 		RestartRequest = NULL;
4407 		ShutdownRequest = NULL;
4408 		PendingSignal = 0;
4409 
4410 		if (e->e_lockfp != NULL)
4411 			(void) close(fileno(e->e_lockfp));
4412 
4413 		(void) setsignal(SIGINT, SIG_DFL);
4414 		(void) setsignal(SIGHUP, SIG_DFL);
4415 		(void) setsignal(SIGTERM, SIG_DFL);
4416 		(void) umask(OldUmask);
4417 		e->e_to = filename;
4418 		ExitStat = EX_OK;
4419 
4420 		if (setjmp(CtxMailfileTimeout) != 0)
4421 		{
4422 			exit(EX_TEMPFAIL);
4423 		}
4424 
4425 		if (TimeOuts.to_fileopen > 0)
4426 			ev = setevent(TimeOuts.to_fileopen,
4427 				      mailfiletimeout, 0);
4428 		else
4429 			ev = NULL;
4430 
4431 		/* check file mode to see if setuid */
4432 		if (stat(targetfile, &stb) < 0)
4433 			mode = FileMode;
4434 		else
4435 			mode = stb.st_mode;
4436 
4437 		/* limit the errors to those actually caused in the child */
4438 		errno = 0;
4439 		ExitStat = EX_OK;
4440 
4441 		/* Allow alias expansions to use the S_IS{U,G}ID bits */
4442 		if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
4443 		    bitset(SFF_RUNASREALUID, sfflags))
4444 		{
4445 			/* ignore setuid and setgid bits */
4446 			mode &= ~(S_ISGID|S_ISUID);
4447 			if (tTd(11, 20))
4448 				dprintf("mailfile: ignoring setuid/setgid bits\n");
4449 		}
4450 
4451 		/* we have to open the dfile BEFORE setuid */
4452 		if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4453 		{
4454 			char *df = queuename(e, 'd');
4455 
4456 			e->e_dfp = fopen(df, "r");
4457 			if (e->e_dfp == NULL)
4458 			{
4459 				syserr("mailfile: Cannot open %s for %s from %s",
4460 					df, e->e_to, e->e_from.q_paddr);
4461 			}
4462 		}
4463 
4464 		/* select a new user to run as */
4465 		if (!bitset(SFF_RUNASREALUID, sfflags))
4466 		{
4467 			if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
4468 			{
4469 				RealUserName = NULL;
4470 				RealUid = mailer->m_uid;
4471 				if (RunAsUid != 0 && RealUid != RunAsUid)
4472 				{
4473 					/* Only root can change the uid */
4474 					syserr("mailfile: insufficient privileges to change uid");
4475 					exit(EX_TEMPFAIL);
4476 				}
4477 			}
4478 			else if (bitset(S_ISUID, mode))
4479 			{
4480 				RealUserName = NULL;
4481 				RealUid = stb.st_uid;
4482 			}
4483 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
4484 			{
4485 				if (ctladdr->q_ruser != NULL)
4486 					RealUserName = ctladdr->q_ruser;
4487 				else
4488 					RealUserName = ctladdr->q_user;
4489 				RealUid = ctladdr->q_uid;
4490 			}
4491 			else if (mailer != NULL && mailer->m_uid != 0)
4492 			{
4493 				RealUserName = DefUser;
4494 				RealUid = mailer->m_uid;
4495 			}
4496 			else
4497 			{
4498 				RealUserName = DefUser;
4499 				RealUid = DefUid;
4500 			}
4501 
4502 			/* select a new group to run as */
4503 			if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
4504 			{
4505 				RealGid = mailer->m_gid;
4506 				if (RunAsUid != 0 &&
4507 				    (RealGid != getgid() ||
4508 				     RealGid != getegid()))
4509 				{
4510 					/* Only root can change the gid */
4511 					syserr("mailfile: insufficient privileges to change gid");
4512 					exit(EX_TEMPFAIL);
4513 				}
4514 			}
4515 			else if (bitset(S_ISGID, mode))
4516 				RealGid = stb.st_gid;
4517 			else if (ctladdr != NULL &&
4518 				 ctladdr->q_uid == DefUid &&
4519 				 ctladdr->q_gid == 0)
4520 			{
4521 				/*
4522 				**  Special case:  This means it is an
4523 				**  alias and we should act as DefaultUser.
4524 				**  See alias()'s comments.
4525 				*/
4526 
4527 				RealGid = DefGid;
4528 				RealUserName = DefUser;
4529 			}
4530 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
4531 				RealGid = ctladdr->q_gid;
4532 			else if (mailer != NULL && mailer->m_gid != 0)
4533 				RealGid = mailer->m_gid;
4534 			else
4535 				RealGid = DefGid;
4536 		}
4537 
4538 		/* last ditch */
4539 		if (!bitset(SFF_ROOTOK, sfflags))
4540 		{
4541 			if (RealUid == 0)
4542 				RealUid = DefUid;
4543 			if (RealGid == 0)
4544 				RealGid = DefGid;
4545 		}
4546 
4547 		/* set group id list (needs /etc/group access) */
4548 		if (RealUserName != NULL && !DontInitGroups)
4549 		{
4550 			if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
4551 			{
4552 				syserr("mailfile: initgroups(%s, %d) failed",
4553 					RealUserName, RealGid);
4554 				exit(EX_TEMPFAIL);
4555 			}
4556 		}
4557 		else
4558 		{
4559 			GIDSET_T gidset[1];
4560 
4561 			gidset[0] = RealGid;
4562 			if (setgroups(1, gidset) == -1 && suidwarn)
4563 			{
4564 				syserr("mailfile: setgroups() failed");
4565 				exit(EX_TEMPFAIL);
4566 			}
4567 		}
4568 
4569 		/*
4570 		**  If you have a safe environment, go into it.
4571 		*/
4572 
4573 		if (realfile != targetfile)
4574 		{
4575 			*realfile = '\0';
4576 			if (tTd(11, 20))
4577 				dprintf("mailfile: chroot %s\n", targetfile);
4578 			if (chroot(targetfile) < 0)
4579 			{
4580 				syserr("mailfile: Cannot chroot(%s)",
4581 				       targetfile);
4582 				exit(EX_CANTCREAT);
4583 			}
4584 			*realfile = '/';
4585 		}
4586 
4587 		if (tTd(11, 40))
4588 			dprintf("mailfile: deliver to %s\n", realfile);
4589 
4590 		if (chdir("/") < 0)
4591 		{
4592 			syserr("mailfile: cannot chdir(/)");
4593 			exit(EX_CANTCREAT);
4594 		}
4595 
4596 		/* now reset the group and user ids */
4597 		endpwent();
4598 		if (setgid(RealGid) < 0 && suidwarn)
4599 		{
4600 			syserr("mailfile: setgid(%ld) failed", (long) RealGid);
4601 			exit(EX_TEMPFAIL);
4602 		}
4603 		vendor_set_uid(RealUid);
4604 		if (setuid(RealUid) < 0 && suidwarn)
4605 		{
4606 			syserr("mailfile: setuid(%ld) failed", (long) RealUid);
4607 			exit(EX_TEMPFAIL);
4608 		}
4609 
4610 		if (tTd(11, 2))
4611 			dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n",
4612 				(int) getuid(), (int) geteuid(),
4613 				(int) getgid(), (int) getegid());
4614 
4615 
4616 		/* move into some "safe" directory */
4617 		if (mailer->m_execdir != NULL)
4618 		{
4619 			char *q;
4620 
4621 			for (p = mailer->m_execdir; p != NULL; p = q)
4622 			{
4623 				q = strchr(p, ':');
4624 				if (q != NULL)
4625 					*q = '\0';
4626 				expand(p, buf, sizeof buf, e);
4627 				if (q != NULL)
4628 					*q++ = ':';
4629 				if (tTd(11, 20))
4630 					dprintf("mailfile: trydir %s\n", buf);
4631 				if (buf[0] != '\0' && chdir(buf) >= 0)
4632 					break;
4633 			}
4634 		}
4635 
4636 		/*
4637 		**  Recheck the file after we have assumed the ID of the
4638 		**  delivery user to make sure we can deliver to it as
4639 		**  that user.  This is necessary if sendmail is running
4640 		**  as root and the file is on an NFS mount which treats
4641 		**  root as nobody.
4642 		*/
4643 
4644 #if HASLSTAT
4645 		if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
4646 			err = stat(realfile, &stb);
4647 		else
4648 			err = lstat(realfile, &stb);
4649 #else /* HASLSTAT */
4650 		err = stat(realfile, &stb);
4651 #endif /* HASLSTAT */
4652 
4653 		if (err < 0)
4654 		{
4655 			stb.st_mode = ST_MODE_NOFILE;
4656 			mode = FileMode;
4657 			oflags |= O_CREAT|O_EXCL;
4658 		}
4659 		else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
4660 			 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
4661 				   DontBlameSendmail) &&
4662 			  stb.st_nlink != 1) ||
4663 			 (realfile != targetfile && !S_ISREG(mode)))
4664 			exit(EX_CANTCREAT);
4665 		else
4666 			mode = stb.st_mode;
4667 
4668 		if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
4669 			sfflags |= SFF_NOSLINK;
4670 		if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
4671 			sfflags |= SFF_NOHLINK;
4672 		sfflags &= ~SFF_OPENASROOT;
4673 		f = safefopen(realfile, oflags, mode, sfflags);
4674 		if (f == NULL)
4675 		{
4676 			if (transienterror(errno))
4677 			{
4678 				usrerr("454 4.3.0 cannot open %s: %s",
4679 				       shortenstring(realfile, MAXSHORTSTR),
4680 				       errstring(errno));
4681 				exit(EX_TEMPFAIL);
4682 			}
4683 			else
4684 			{
4685 				usrerr("554 5.3.0 cannot open %s: %s",
4686 				       shortenstring(realfile, MAXSHORTSTR),
4687 				       errstring(errno));
4688 				exit(EX_CANTCREAT);
4689 			}
4690 		}
4691 		if (filechanged(realfile, fileno(f), &stb))
4692 		{
4693 			syserr("554 5.3.0 file changed after open");
4694 			exit(EX_CANTCREAT);
4695 		}
4696 		if (fstat(fileno(f), &stb) < 0)
4697 		{
4698 			syserr("554 5.3.0 cannot fstat %s", errstring(errno));
4699 			exit(EX_CANTCREAT);
4700 		}
4701 
4702 		curoff = stb.st_size;
4703 
4704 		if (ev != NULL)
4705 			clrevent(ev);
4706 
4707 		memset(&mcibuf, '\0', sizeof mcibuf);
4708 		mcibuf.mci_mailer = mailer;
4709 		mcibuf.mci_out = f;
4710 		if (bitnset(M_7BITS, mailer->m_flags))
4711 			mcibuf.mci_flags |= MCIF_7BIT;
4712 
4713 		/* clear out per-message flags from connection structure */
4714 		mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
4715 
4716 		if (bitset(EF_HAS8BIT, e->e_flags) &&
4717 		    !bitset(EF_DONT_MIME, e->e_flags) &&
4718 		    bitnset(M_7BITS, mailer->m_flags))
4719 			mcibuf.mci_flags |= MCIF_CVT8TO7;
4720 
4721 #if MIME7TO8
4722 		if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
4723 		    !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
4724 		    (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
4725 		    (strcasecmp(p, "quoted-printable") == 0 ||
4726 		     strcasecmp(p, "base64") == 0) &&
4727 		    (p = hvalue("Content-Type", e->e_header)) != NULL)
4728 		{
4729 			/* may want to convert 7 -> 8 */
4730 			/* XXX should really parse it here -- and use a class XXX */
4731 			if (strncasecmp(p, "text/plain", 10) == 0 &&
4732 			    (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
4733 				mcibuf.mci_flags |= MCIF_CVT7TO8;
4734 		}
4735 #endif /* MIME7TO8 */
4736 
4737 		putfromline(&mcibuf, e);
4738 		(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER);
4739 		(*e->e_putbody)(&mcibuf, e, NULL);
4740 		putline("\n", &mcibuf);
4741 		if (fflush(f) != 0 ||
4742 		    (SuperSafe && fsync(fileno(f)) < 0) ||
4743 		    ferror(f))
4744 		{
4745 			setstat(EX_IOERR);
4746 #if !NOFTRUNCATE
4747 			(void) ftruncate(fileno(f), curoff);
4748 #endif /* !NOFTRUNCATE */
4749 		}
4750 
4751 		/* reset ISUID & ISGID bits for paranoid systems */
4752 #if HASFCHMOD
4753 		(void) fchmod(fileno(f), (MODE_T) mode);
4754 #else /* HASFCHMOD */
4755 		(void) chmod(filename, (MODE_T) mode);
4756 #endif /* HASFCHMOD */
4757 		if (fclose(f) < 0)
4758 			setstat(EX_IOERR);
4759 		(void) fflush(stdout);
4760 		(void) setuid(RealUid);
4761 		exit(ExitStat);
4762 		/* NOTREACHED */
4763 	}
4764 	else
4765 	{
4766 		/* parent -- wait for exit status */
4767 		int st;
4768 
4769 		st = waitfor(pid);
4770 		if (st == -1)
4771 		{
4772 			syserr("mailfile: %s: wait", mailer->m_name);
4773 			return EX_SOFTWARE;
4774 		}
4775 		if (WIFEXITED(st))
4776 			return (WEXITSTATUS(st));
4777 		else
4778 		{
4779 			syserr("mailfile: %s: child died on signal %d",
4780 			       mailer->m_name, st);
4781 			return EX_UNAVAILABLE;
4782 		}
4783 		/* NOTREACHED */
4784 	}
4785 	return EX_UNAVAILABLE;	/* avoid compiler warning on IRIX */
4786 }
4787 
4788 static void
4789 mailfiletimeout()
4790 {
4791 	/*
4792 	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
4793 	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
4794 	**	DOING.
4795 	*/
4796 
4797 	errno = ETIMEDOUT;
4798 	longjmp(CtxMailfileTimeout, 1);
4799 }
4800 /*
4801 **  HOSTSIGNATURE -- return the "signature" for a host.
4802 **
4803 **	The signature describes how we are going to send this -- it
4804 **	can be just the hostname (for non-Internet hosts) or can be
4805 **	an ordered list of MX hosts.
4806 **
4807 **	Parameters:
4808 **		m -- the mailer describing this host.
4809 **		host -- the host name.
4810 **
4811 **	Returns:
4812 **		The signature for this host.
4813 **
4814 **	Side Effects:
4815 **		Can tweak the symbol table.
4816 */
4817 #define MAXHOSTSIGNATURE	8192	/* max len of hostsignature */
4818 
4819 static char *
4820 hostsignature(m, host)
4821 	register MAILER *m;
4822 	char *host;
4823 {
4824 	register char *p;
4825 	register STAB *s;
4826 #if NAMED_BIND
4827 	char sep = ':';
4828 	char prevsep = ':';
4829 	int i;
4830 	int len;
4831 	int nmx;
4832 	int hl;
4833 	time_t now;
4834 	char *hp;
4835 	char *endp;
4836 	int oldoptions = _res.options;
4837 	char *mxhosts[MAXMXHOSTS + 1];
4838 	u_short mxprefs[MAXMXHOSTS + 1];
4839 #endif /* NAMED_BIND */
4840 
4841 	if (tTd(17, 3))
4842 		dprintf("hostsignature(%s)\n", host);
4843 
4844 	/*
4845 	**  If local delivery (and not remote), just return a constant.
4846 	*/
4847 
4848 	p = m->m_mailer;
4849 	if (bitnset(M_LOCALMAILER, m->m_flags) &&
4850 	    strcmp(p, "[IPC]") != 0 &&
4851 	    strcmp(p, "[TCP]") != 0)
4852 		return "localhost";
4853 
4854 	/*
4855 	**  Check to see if this uses IPC -- if not, it can't have MX records.
4856 	*/
4857 
4858 	if (strcmp(p, "[IPC]") != 0 &&
4859 	    strcmp(p, "[TCP]") != 0)
4860 	{
4861 		/* just an ordinary mailer */
4862 		return host;
4863 	}
4864 #if NETUNIX
4865 	else if (m->m_argv[0] != NULL &&
4866 		 strcmp(m->m_argv[0], "FILE") == 0)
4867 	{
4868 		/* rendezvous in the file system, no MX records */
4869 		return host;
4870 	}
4871 #endif /* NETUNIX */
4872 
4873 	/*
4874 	**  Look it up in the symbol table.
4875 	*/
4876 
4877 	s = stab(host, ST_HOSTSIG, ST_ENTER);
4878 	if (s->s_hostsig != NULL)
4879 	{
4880 		if (tTd(17, 3))
4881 			dprintf("hostsignature(): stab(%s) found %s\n", host,
4882 				s->s_hostsig);
4883 		return s->s_hostsig;
4884 	}
4885 
4886 	/*
4887 	**  Not already there -- create a signature.
4888 	*/
4889 
4890 #if NAMED_BIND
4891 	if (ConfigLevel < 2)
4892 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
4893 
4894 	now = curtime();
4895 	for (hp = host; hp != NULL; hp = endp)
4896 	{
4897 #if NETINET6
4898 		if (*hp == '[')
4899 		{
4900 			endp = strchr(hp + 1, ']');
4901 			if (endp != NULL)
4902 				endp = strpbrk(endp + 1, ":,");
4903 		}
4904 		else
4905 			endp = strpbrk(hp, ":,");
4906 #else /* NETINET6 */
4907 		endp = strpbrk(hp, ":,");
4908 #endif /* NETINET6 */
4909 		if (endp != NULL)
4910 		{
4911 			sep = *endp;
4912 			*endp = '\0';
4913 		}
4914 
4915 		if (bitnset(M_NOMX, m->m_flags))
4916 		{
4917 			/* skip MX lookups */
4918 			nmx = 1;
4919 			mxhosts[0] = hp;
4920 		}
4921 		else
4922 		{
4923 			auto int rcode;
4924 
4925 			nmx = getmxrr(hp, mxhosts, mxprefs, TRUE, &rcode);
4926 			if (nmx <= 0)
4927 			{
4928 				register MCI *mci;
4929 
4930 				/* update the connection info for this host */
4931 				mci = mci_get(hp, m);
4932 				mci->mci_errno = errno;
4933 				mci->mci_herrno = h_errno;
4934 				mci->mci_lastuse = now;
4935 				if (rcode == EX_NOHOST)
4936 					mci_setstat(mci, rcode, "5.1.2",
4937 						"550 Host unknown");
4938 				else
4939 					mci_setstat(mci, rcode, NULL, NULL);
4940 
4941 				/* use the original host name as signature */
4942 				nmx = 1;
4943 				mxhosts[0] = hp;
4944 			}
4945 			if (tTd(17, 3))
4946 				dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
4947 					nmx, mxhosts[0]);
4948 		}
4949 
4950 		len = 0;
4951 		for (i = 0; i < nmx; i++)
4952 			len += strlen(mxhosts[i]) + 1;
4953 		if (s->s_hostsig != NULL)
4954 			len += strlen(s->s_hostsig) + 1;
4955 		if (len >= MAXHOSTSIGNATURE)
4956 		{
4957 			sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
4958 				  host, MAXHOSTSIGNATURE, len);
4959 			len = MAXHOSTSIGNATURE;
4960 		}
4961 		p = xalloc(len);
4962 		if (s->s_hostsig != NULL)
4963 		{
4964 			(void) strlcpy(p, s->s_hostsig, len);
4965 			sm_free(s->s_hostsig);
4966 			s->s_hostsig = p;
4967 			hl = strlen(p);
4968 			p += hl;
4969 			*p++ = prevsep;
4970 			len -= hl + 1;
4971 		}
4972 		else
4973 			s->s_hostsig = p;
4974 		for (i = 0; i < nmx; i++)
4975 		{
4976 			hl = strlen(mxhosts[i]);
4977 			if (len - 1 < hl || len <= 1)
4978 			{
4979 				/* force to drop out of outer loop */
4980 				len = -1;
4981 				break;
4982 			}
4983 			if (i != 0)
4984 			{
4985 				if (mxprefs[i] == mxprefs[i - 1])
4986 					*p++ = ',';
4987 				else
4988 					*p++ = ':';
4989 				len--;
4990 			}
4991 			(void) strlcpy(p, mxhosts[i], len);
4992 			p += hl;
4993 			len -= hl;
4994 		}
4995 
4996 		/*
4997 		**  break out of loop if len exceeded MAXHOSTSIGNATURE
4998 		**  because we won't have more space for further hosts
4999 		**  anyway (separated by : in the .cf file).
5000 		*/
5001 
5002 		if (len < 0)
5003 			break;
5004 		if (endp != NULL)
5005 			*endp++ = sep;
5006 		prevsep = sep;
5007 	}
5008 	makelower(s->s_hostsig);
5009 	if (ConfigLevel < 2)
5010 		_res.options = oldoptions;
5011 #else /* NAMED_BIND */
5012 	/* not using BIND -- the signature is just the host name */
5013 	s->s_hostsig = host;
5014 #endif /* NAMED_BIND */
5015 	if (tTd(17, 1))
5016 		dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig);
5017 	return s->s_hostsig;
5018 }
5019 /*
5020 **  PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5021 **
5022 **	The signature describes how we are going to send this -- it
5023 **	can be just the hostname (for non-Internet hosts) or can be
5024 **	an ordered list of MX hosts which must be randomized for equal
5025 **	MX preference values.
5026 **
5027 **	Parameters:
5028 **		sig -- the host signature.
5029 **		mxhosts -- array to populate.
5030 **
5031 **	Returns:
5032 **		The number of hosts inserted into mxhosts array.
5033 **
5034 **	Side Effects:
5035 **		Randomizes equal MX preference hosts in mxhosts.
5036 */
5037 
5038 static int
5039 parse_hostsignature(sig, mxhosts, mailer)
5040 	char *sig;
5041 	char **mxhosts;
5042 	MAILER *mailer;
5043 {
5044 	int nmx = 0;
5045 	int curpref = 0;
5046 	int i, j;
5047 	char *hp, *endp;
5048 	u_short prefer[MAXMXHOSTS];
5049 	long rndm[MAXMXHOSTS];
5050 
5051 	for (hp = sig; hp != NULL; hp = endp)
5052 	{
5053 		char sep = ':';
5054 
5055 #if NETINET6
5056 		if (*hp == '[')
5057 		{
5058 			endp = strchr(hp + 1, ']');
5059 			if (endp != NULL)
5060 				endp = strpbrk(endp + 1, ":,");
5061 		}
5062 		else
5063 			endp = strpbrk(hp, ":,");
5064 #else /* NETINET6 */
5065 		endp = strpbrk(hp, ":,");
5066 #endif /* NETINET6 */
5067 		if (endp != NULL)
5068 		{
5069 			sep = *endp;
5070 			*endp = '\0';
5071 		}
5072 
5073 		mxhosts[nmx] = hp;
5074 		prefer[nmx] = curpref;
5075 		if (mci_match(hp, mailer))
5076 			rndm[nmx] = 0;
5077 		else
5078 			rndm[nmx] = get_random();
5079 
5080 		if (endp != NULL)
5081 		{
5082 			/*
5083 			**  Since we don't have the original MX prefs,
5084 			**  make our own.  If the separator is a ':', that
5085 			**  means the preference for the next host will be
5086 			**  higher than this one, so simply increment curpref.
5087 			*/
5088 
5089 			if (sep == ':')
5090 				curpref++;
5091 
5092 			*endp++ = sep;
5093 		}
5094 		if (++nmx >= MAXMXHOSTS)
5095 			break;
5096 	}
5097 
5098 	/* sort the records using the random factor for equal preferences */
5099 	for (i = 0; i < nmx; i++)
5100 	{
5101 		for (j = i + 1; j < nmx; j++)
5102 		{
5103 			/*
5104 			**  List is already sorted by MX preference, only
5105 			**  need to look for equal preference MX records
5106 			*/
5107 
5108 			if (prefer[i] < prefer[j])
5109 				break;
5110 
5111 			if (prefer[i] > prefer[j] ||
5112 			    (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
5113 			{
5114 				register u_short tempp;
5115 				register long tempr;
5116 				register char *temp1;
5117 
5118 				tempp = prefer[i];
5119 				prefer[i] = prefer[j];
5120 				prefer[j] = tempp;
5121 				temp1 = mxhosts[i];
5122 				mxhosts[i] = mxhosts[j];
5123 				mxhosts[j] = temp1;
5124 				tempr = rndm[i];
5125 				rndm[i] = rndm[j];
5126 				rndm[j] = tempr;
5127 			}
5128 		}
5129 	}
5130 	return nmx;
5131 }
5132 
5133 #if SMTP
5134 # if STARTTLS
5135 static SSL_CTX	*clt_ctx = NULL;
5136 
5137 /*
5138 **  INITCLTTLS -- initialize client side TLS
5139 **
5140 **	Parameters:
5141 **		none.
5142 **
5143 **	Returns:
5144 **		succeeded?
5145 */
5146 
5147 bool
5148 initclttls()
5149 {
5150 	if (clt_ctx != NULL)
5151 		return TRUE;	/* already done */
5152 	return inittls(&clt_ctx, TLS_I_CLT, FALSE, CltCERTfile, Cltkeyfile,
5153 		       CACERTpath, CACERTfile, DHParams);
5154 }
5155 
5156 /*
5157 **  STARTTLS -- try to start secure connection (client side)
5158 **
5159 **	Parameters:
5160 **		m -- the mailer.
5161 **		mci -- the mailer connection info.
5162 **		e -- the envelope.
5163 **
5164 **	Returns:
5165 **		success?
5166 **		(maybe this should be some other code than EX_
5167 **		that denotes which stage failed.)
5168 */
5169 
5170 static int
5171 starttls(m, mci, e)
5172 	MAILER *m;
5173 	MCI *mci;
5174 	ENVELOPE *e;
5175 {
5176 	int smtpresult;
5177 	int result = 0;
5178 	int rfd, wfd;
5179 	SSL *clt_ssl = NULL;
5180 
5181 	if (clt_ctx == NULL && !initclttls())
5182 		return EX_TEMPFAIL;
5183 	smtpmessage("STARTTLS", m, mci);
5184 
5185 	/* get the reply */
5186 	smtpresult = reply(m, mci, e, TimeOuts.to_datafinal, NULL, NULL);
5187 	/* which timeout? XXX */
5188 
5189 	/* check return code from server */
5190 	if (smtpresult == 454)
5191 		return EX_TEMPFAIL;
5192 	if (smtpresult == 501)
5193 		return EX_USAGE;
5194 	if (smtpresult == -1)
5195 		return smtpresult;
5196 	if (smtpresult != 220)
5197 		return EX_PROTOCOL;
5198 
5199 	if (LogLevel > 13)
5200 		sm_syslog(LOG_INFO, e->e_id, "TLS: start client");
5201 
5202 	/* start connection */
5203 	if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
5204 	{
5205 		if (LogLevel > 5)
5206 		{
5207 			sm_syslog(LOG_ERR, e->e_id,
5208 				  "TLS: error: client: SSL_new failed");
5209 			if (LogLevel > 9)
5210 				tlslogerr();
5211 		}
5212 		return EX_SOFTWARE;
5213 	}
5214 
5215 	rfd = fileno(mci->mci_in);
5216 	wfd = fileno(mci->mci_out);
5217 
5218 	/* SSL_clear(clt_ssl); ? */
5219 	if (rfd < 0 || wfd < 0 ||
5220 	    (result = SSL_set_rfd(clt_ssl, rfd)) <= 0 ||
5221 	    (result = SSL_set_wfd(clt_ssl, wfd)) <= 0)
5222 	{
5223 		if (LogLevel > 5)
5224 		{
5225 			sm_syslog(LOG_ERR, e->e_id,
5226 				  "TLS: error: SSL_set_xfd failed=%d", result);
5227 			if (LogLevel > 9)
5228 				tlslogerr();
5229 		}
5230 		return EX_SOFTWARE;
5231 	}
5232 	SSL_set_connect_state(clt_ssl);
5233 	if ((result = SSL_connect(clt_ssl)) <= 0)
5234 	{
5235 		int i;
5236 
5237 		/* what to do in this case? */
5238 		i = SSL_get_error(clt_ssl, result);
5239 		if (LogLevel > 5)
5240 		{
5241 			sm_syslog(LOG_ERR, e->e_id,
5242 				  "TLS: error: SSL_connect failed=%d (%d)",
5243 				  result, i);
5244 			if (LogLevel > 9)
5245 				tlslogerr();
5246 		}
5247 		SSL_free(clt_ssl);
5248 		clt_ssl = NULL;
5249 		return EX_SOFTWARE;
5250 	}
5251 	mci->mci_ssl = clt_ssl;
5252 	result = tls_get_info(clt_ssl, e, FALSE, mci->mci_host, TRUE);
5253 
5254 	/* switch to use SSL... */
5255 #if SFIO
5256 	if (sfdctls(mci->mci_in, mci->mci_out, mci->mci_ssl) == 0)
5257 		return EX_OK;
5258 #else /* SFIO */
5259 # if _FFR_TLS_TOREK
5260 	if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
5261 		return EX_OK;
5262 # endif /* _FFR_TLS_TOREK */
5263 #endif /* SFIO */
5264 
5265 	/* failure */
5266 	SSL_free(clt_ssl);
5267 	clt_ssl = NULL;
5268 	return EX_SOFTWARE;
5269 }
5270 
5271 /*
5272 **  ENDTLSCLT -- shutdown secure connection (client side)
5273 **
5274 **	Parameters:
5275 **		mci -- the mailer connection info.
5276 **
5277 **	Returns:
5278 **		success?
5279 */
5280 int
5281 endtlsclt(mci)
5282 	MCI *mci;
5283 {
5284 	int r;
5285 
5286 	if (!bitset(MCIF_TLSACT, mci->mci_flags))
5287 		return EX_OK;
5288 	r = endtls(mci->mci_ssl, "client");
5289 	mci->mci_flags &= ~MCIF_TLSACT;
5290 	return r;
5291 }
5292 /*
5293 **  ENDTLS -- shutdown secure connection
5294 **
5295 **	Parameters:
5296 **		ssl -- SSL connection information.
5297 **		side -- srv/clt (for logging).
5298 **
5299 **	Returns:
5300 **		success?
5301 */
5302 
5303 int
5304 endtls(ssl, side)
5305 	SSL *ssl;
5306 	char *side;
5307 {
5308 	int ret = EX_OK;
5309 
5310 	if (ssl != NULL)
5311 	{
5312 		int r;
5313 
5314 		if ((r = SSL_shutdown(ssl)) < 0)
5315 		{
5316 			if (LogLevel > 11)
5317 				sm_syslog(LOG_WARNING, NOQID,
5318 					  "SSL_shutdown %s failed: %d",
5319 					  side, r);
5320 			ret = EX_SOFTWARE;
5321 		}
5322 		else if (r == 0)
5323 		{
5324 			if (LogLevel > 13)
5325 				sm_syslog(LOG_WARNING, NOQID,
5326 					  "SSL_shutdown %s not done",
5327 					  side);
5328 			ret = EX_SOFTWARE;
5329 		}
5330 		SSL_free(ssl);
5331 		ssl = NULL;
5332 	}
5333 	return ret;
5334 }
5335 # endif /* STARTTLS */
5336 #endif /* SMTP */
5337