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