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