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