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