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