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