xref: /titanic_52/usr/src/cmd/sendmail/src/deliver.c (revision 6185db853e024a486ff8837e6784dd290d866112)
1 /*
2  * Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #pragma ident	"%Z%%M%	%I%	%E% SMI"
15 
16 #include <sendmail.h>
17 #include <sm/time.h>
18 
19 SM_RCSID("@(#)$Id: deliver.c,v 8.1003.2.1 2006/05/23 01:32:08 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 or a temporary failure occurred
1207 	**  and a FallbackSmartHost is defined (and we have not yet
1208 	**  tried it), then make one last try with it as the host.
1209 	*/
1210 
1211 	if ((status == EX_NOHOST || status == EX_TEMPFAIL) &&
1212 	    FallbackSmartHost != NULL && !*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 					  case EX_UNAVAILABLE:
2998 						s = "NONE";
2999 						break;
3000 
3001 					  /* everything else is a failure */
3002 					  default:
3003 						s = "FAILURE";
3004 						rcode = EX_TEMPFAIL;
3005 					}
3006 					macdefine(&e->e_macro, A_PERM,
3007 						  macid("{verify}"), s);
3008 				}
3009 			}
3010 			else
3011 				macdefine(&e->e_macro, A_PERM,
3012 					  macid("{verify}"), "NONE");
3013 			olderrors = Errors;
3014 			QuickAbort = false;
3015 			SuprErrs = true;
3016 
3017 			/*
3018 			**  rcode == EX_SOFTWARE is special:
3019 			**  the TLS negotation failed
3020 			**  we have to drop the connection no matter what
3021 			**  However, we call tls_server to give it the chance
3022 			**  to log the problem and return an appropriate
3023 			**  error code.
3024 			*/
3025 
3026 			if (rscheck("tls_server",
3027 				    macvalue(macid("{verify}"), e),
3028 				    NULL, e, RSF_RMCOMM|RSF_COUNT, 5,
3029 				    host, NOQID) != EX_OK ||
3030 			    Errors > olderrors ||
3031 			    rcode == EX_SOFTWARE)
3032 			{
3033 				char enhsc[ENHSCLEN];
3034 				extern char MsgBuf[];
3035 
3036 				if (ISSMTPCODE(MsgBuf) &&
3037 				    extenhsc(MsgBuf + 4, ' ', enhsc) > 0)
3038 				{
3039 					p = sm_rpool_strdup_x(e->e_rpool,
3040 							      MsgBuf);
3041 				}
3042 				else
3043 				{
3044 					p = "403 4.7.0 server not authenticated.";
3045 					(void) sm_strlcpy(enhsc, "4.7.0",
3046 							  sizeof enhsc);
3047 				}
3048 				SuprErrs = saveSuprErrs;
3049 				QuickAbort = saveQuickAbort;
3050 
3051 				if (rcode == EX_SOFTWARE)
3052 				{
3053 					/* drop the connection */
3054 					mci->mci_state = MCIS_QUITING;
3055 					if (mci->mci_in != NULL)
3056 					{
3057 						(void) sm_io_close(mci->mci_in,
3058 								   SM_TIME_DEFAULT);
3059 						mci->mci_in = NULL;
3060 					}
3061 					mci->mci_flags &= ~MCIF_TLSACT;
3062 					(void) endmailer(mci, e, pv);
3063 				}
3064 				else
3065 				{
3066 					/* abort transfer */
3067 					smtpquit(m, mci, e);
3068 				}
3069 
3070 				/* avoid bogus error msg */
3071 				mci->mci_errno = 0;
3072 
3073 				/* temp or permanent failure? */
3074 				rcode = (*p == '4') ? EX_TEMPFAIL
3075 						    : EX_UNAVAILABLE;
3076 				mci_setstat(mci, rcode, enhsc, p);
3077 
3078 				/*
3079 				**  hack to get the error message into
3080 				**  the envelope (done in giveresponse())
3081 				*/
3082 
3083 				(void) sm_strlcpy(SmtpError, p,
3084 						  sizeof SmtpError);
3085 			}
3086 			QuickAbort = saveQuickAbort;
3087 			SuprErrs = saveSuprErrs;
3088 			if (DONE_STARTTLS(mci->mci_flags) &&
3089 			    mci->mci_state != MCIS_CLOSED)
3090 			{
3091 				SET_HELO(mci->mci_flags);
3092 				mci->mci_flags &= ~MCIF_EXTENS;
3093 				goto reconnect;
3094 			}
3095 		}
3096 # endif /* STARTTLS */
3097 # if SASL
3098 		/* if other server supports authentication let's authenticate */
3099 		if (mci->mci_state != MCIS_CLOSED &&
3100 		    mci->mci_saslcap != NULL &&
3101 		    !DONE_AUTH(mci->mci_flags) && !iscltflgset(e, D_NOAUTH))
3102 		{
3103 			/* Should we require some minimum authentication? */
3104 			if ((ret = smtpauth(m, mci, e)) == EX_OK)
3105 			{
3106 				int result;
3107 				sasl_ssf_t *ssf = NULL;
3108 
3109 				/* Get security strength (features) */
3110 				result = sasl_getprop(mci->mci_conn, SASL_SSF,
3111 # if SASL >= 20000
3112 						      (const void **) &ssf);
3113 # else /* SASL >= 20000 */
3114 						      (void **) &ssf);
3115 # endif /* SASL >= 20000 */
3116 
3117 				/* XXX authid? */
3118 				if (LogLevel > 9)
3119 					sm_syslog(LOG_INFO, NOQID,
3120 						  "AUTH=client, relay=%.100s, mech=%.16s, bits=%d",
3121 						  mci->mci_host,
3122 						  macvalue(macid("{auth_type}"), e),
3123 						  result == SASL_OK ? *ssf : 0);
3124 
3125 				/*
3126 				**  Only switch to encrypted connection
3127 				**  if a security layer has been negotiated
3128 				*/
3129 
3130 				if (result == SASL_OK && *ssf > 0)
3131 				{
3132 					int tmo;
3133 
3134 					/*
3135 					**  Convert I/O layer to use SASL.
3136 					**  If the call fails, the connection
3137 					**  is aborted.
3138 					*/
3139 
3140 					tmo = DATA_PROGRESS_TIMEOUT * 1000;
3141 					if (sfdcsasl(&mci->mci_in,
3142 						     &mci->mci_out,
3143 						     mci->mci_conn, tmo) == 0)
3144 					{
3145 						mci->mci_flags &= ~MCIF_EXTENS;
3146 						mci->mci_flags |= MCIF_AUTHACT|
3147 								  MCIF_ONLY_EHLO;
3148 						goto reconnect;
3149 					}
3150 					syserr("AUTH TLS switch failed in client");
3151 				}
3152 				/* else? XXX */
3153 				mci->mci_flags |= MCIF_AUTHACT;
3154 
3155 			}
3156 			else if (ret == EX_TEMPFAIL)
3157 			{
3158 				if (LogLevel > 8)
3159 					sm_syslog(LOG_ERR, NOQID,
3160 						  "AUTH=client, relay=%.100s, temporary failure, connection abort",
3161 						  mci->mci_host);
3162 				smtpquit(m, mci, e);
3163 
3164 				/* avoid bogus error msg */
3165 				mci->mci_errno = 0;
3166 				rcode = EX_TEMPFAIL;
3167 				mci_setstat(mci, rcode, "4.3.0", p);
3168 
3169 				/*
3170 				**  hack to get the error message into
3171 				**  the envelope (done in giveresponse())
3172 				*/
3173 
3174 				(void) sm_strlcpy(SmtpError,
3175 						  "Temporary AUTH failure",
3176 						  sizeof SmtpError);
3177 			}
3178 		}
3179 # endif /* SASL */
3180 	}
3181 
3182 
3183 do_transfer:
3184 	/* clear out per-message flags from connection structure */
3185 	mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
3186 
3187 	if (bitset(EF_HAS8BIT, e->e_flags) &&
3188 	    !bitset(EF_DONT_MIME, e->e_flags) &&
3189 	    bitnset(M_7BITS, m->m_flags))
3190 		mci->mci_flags |= MCIF_CVT8TO7;
3191 
3192 #if MIME7TO8
3193 	if (bitnset(M_MAKE8BIT, m->m_flags) &&
3194 	    !bitset(MCIF_7BIT, mci->mci_flags) &&
3195 	    (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
3196 	     (sm_strcasecmp(p, "quoted-printable") == 0 ||
3197 	      sm_strcasecmp(p, "base64") == 0) &&
3198 	    (p = hvalue("Content-Type", e->e_header)) != NULL)
3199 	{
3200 		/* may want to convert 7 -> 8 */
3201 		/* XXX should really parse it here -- and use a class XXX */
3202 		if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
3203 		    (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
3204 			mci->mci_flags |= MCIF_CVT7TO8;
3205 	}
3206 #endif /* MIME7TO8 */
3207 
3208 	if (tTd(11, 1))
3209 	{
3210 		sm_dprintf("openmailer: ");
3211 		mci_dump(sm_debug_file(), mci, false);
3212 	}
3213 
3214 #if _FFR_CLIENT_SIZE
3215 	/*
3216 	**  See if we know the maximum size and
3217 	**  abort if the message is too big.
3218 	**
3219 	**  NOTE: _FFR_CLIENT_SIZE is untested.
3220 	*/
3221 
3222 	if (bitset(MCIF_SIZE, mci->mci_flags) &&
3223 	    mci->mci_maxsize > 0 &&
3224 	    e->e_msgsize > mci->mci_maxsize)
3225 	{
3226 		e->e_flags |= EF_NO_BODY_RETN;
3227 		if (bitnset(M_LOCALMAILER, m->m_flags))
3228 			e->e_status = "5.2.3";
3229 		else
3230 			e->e_status = "5.3.4";
3231 
3232 		usrerrenh(e->e_status,
3233 			  "552 Message is too large; %ld bytes max",
3234 			  mci->mci_maxsize);
3235 		rcode = EX_DATAERR;
3236 
3237 		/* Need an e_message for error */
3238 		(void) sm_snprintf(SmtpError, sizeof SmtpError,
3239 				   "Message is too large; %ld bytes max",
3240 				   mci->mci_maxsize);
3241 		goto give_up;
3242 	}
3243 #endif /* _FFR_CLIENT_SIZE */
3244 
3245 	if (mci->mci_state != MCIS_OPEN)
3246 	{
3247 		/* couldn't open the mailer */
3248 		rcode = mci->mci_exitstat;
3249 		errno = mci->mci_errno;
3250 		SM_SET_H_ERRNO(mci->mci_herrno);
3251 		if (rcode == EX_OK)
3252 		{
3253 			/* shouldn't happen */
3254 			syserr("554 5.3.5 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
3255 			       (unsigned long) mci, rcode, errno,
3256 			       mci->mci_state, firstsig);
3257 			mci_dump_all(smioout, true);
3258 			rcode = EX_SOFTWARE;
3259 		}
3260 		else if (nummxhosts > hostnum)
3261 		{
3262 			/* try next MX site */
3263 			goto tryhost;
3264 		}
3265 	}
3266 	else if (!clever)
3267 	{
3268 		bool ok;
3269 
3270 		/*
3271 		**  Format and send message.
3272 		*/
3273 
3274 		rcode = EX_OK;
3275 		errno = 0;
3276 		ok = putfromline(mci, e);
3277 		if (ok)
3278 			ok = (*e->e_puthdr)(mci, e->e_header, e, M87F_OUTER);
3279 		if (ok)
3280 			ok = (*e->e_putbody)(mci, e, NULL);
3281 
3282 		/*
3283 		**  Ignore an I/O error that was caused by EPIPE.
3284 		**  Some broken mailers don't read the entire body
3285 		**  but just exit() thus causing an I/O error.
3286 		*/
3287 
3288 		if (!ok && (sm_io_error(mci->mci_out) && errno == EPIPE))
3289 			ok = true;
3290 
3291 		/* (always) get the exit status */
3292 		rcode = endmailer(mci, e, pv);
3293 		if (!ok)
3294 			rcode = EX_TEMPFAIL;
3295 		if (rcode == EX_TEMPFAIL && SmtpError[0] == '\0')
3296 		{
3297 			/*
3298 			**  Need an e_message for mailq display.
3299 			**  We set SmtpError as
3300 			*/
3301 
3302 			(void) sm_snprintf(SmtpError, sizeof SmtpError,
3303 					   "%s mailer (%s) exited with EX_TEMPFAIL",
3304 					   m->m_name, m->m_mailer);
3305 		}
3306 	}
3307 	else
3308 	{
3309 		/*
3310 		**  Send the MAIL FROM: protocol
3311 		*/
3312 
3313 		/* XXX this isn't pipelined... */
3314 		rcode = smtpmailfrom(m, mci, e);
3315 		if (rcode == EX_OK)
3316 		{
3317 			register int i;
3318 # if PIPELINING
3319 			ADDRESS *volatile pchain;
3320 # endif /* PIPELINING */
3321 
3322 			/* send the recipient list */
3323 			tobuf[0] = '\0';
3324 			mci->mci_retryrcpt = false;
3325 			mci->mci_tolist = tobuf;
3326 # if PIPELINING
3327 			pchain = NULL;
3328 			mci->mci_nextaddr = NULL;
3329 # endif /* PIPELINING */
3330 
3331 			for (to = tochain; to != NULL; to = to->q_tchain)
3332 			{
3333 				if (!QS_IS_UNMARKED(to->q_state))
3334 					continue;
3335 
3336 				/* mark recipient state as "ok so far" */
3337 				to->q_state = QS_OK;
3338 				e->e_to = to->q_paddr;
3339 # if STARTTLS
3340 				i = rscheck("tls_rcpt", to->q_user, NULL, e,
3341 					    RSF_RMCOMM|RSF_COUNT, 3,
3342 					    mci->mci_host, e->e_id);
3343 				if (i != EX_OK)
3344 				{
3345 					markfailure(e, to, mci, i, false);
3346 					giveresponse(i, to->q_status,  m, mci,
3347 						     ctladdr, xstart, e, to);
3348 					if (i == EX_TEMPFAIL)
3349 					{
3350 						mci->mci_retryrcpt = true;
3351 						to->q_state = QS_RETRY;
3352 					}
3353 					continue;
3354 				}
3355 # endif /* STARTTLS */
3356 
3357 				i = smtprcpt(to, m, mci, e, ctladdr, xstart);
3358 # if PIPELINING
3359 				if (i == EX_OK &&
3360 				    bitset(MCIF_PIPELINED, mci->mci_flags))
3361 				{
3362 					/*
3363 					**  Add new element to list of
3364 					**  recipients for pipelining.
3365 					*/
3366 
3367 					to->q_pchain = NULL;
3368 					if (mci->mci_nextaddr == NULL)
3369 						mci->mci_nextaddr = to;
3370 					if (pchain == NULL)
3371 						pchain = to;
3372 					else
3373 					{
3374 						pchain->q_pchain = to;
3375 						pchain = pchain->q_pchain;
3376 					}
3377 				}
3378 # endif /* PIPELINING */
3379 				if (i != EX_OK)
3380 				{
3381 					markfailure(e, to, mci, i, false);
3382 					giveresponse(i, to->q_status, m, mci,
3383 						     ctladdr, xstart, e, to);
3384 					if (i == EX_TEMPFAIL)
3385 						to->q_state = QS_RETRY;
3386 				}
3387 			}
3388 
3389 			/* No recipients in list and no missing responses? */
3390 			if (tobuf[0] == '\0'
3391 # if PIPELINING
3392 			    && mci->mci_nextaddr == NULL
3393 # endif /* PIPELINING */
3394 			   )
3395 			{
3396 				rcode = EX_OK;
3397 				e->e_to = NULL;
3398 				if (bitset(MCIF_CACHED, mci->mci_flags))
3399 					smtprset(m, mci, e);
3400 			}
3401 			else
3402 			{
3403 				e->e_to = tobuf + 1;
3404 				rcode = smtpdata(m, mci, e, ctladdr, xstart);
3405 			}
3406 		}
3407 		if (rcode == EX_TEMPFAIL && nummxhosts > hostnum)
3408 		{
3409 			/* try next MX site */
3410 			goto tryhost;
3411 		}
3412 	}
3413 #if NAMED_BIND
3414 	if (ConfigLevel < 2)
3415 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
3416 #endif /* NAMED_BIND */
3417 
3418 	if (tTd(62, 1))
3419 		checkfds("after delivery");
3420 
3421 	/*
3422 	**  Do final status disposal.
3423 	**	We check for something in tobuf for the SMTP case.
3424 	**	If we got a temporary failure, arrange to queue the
3425 	**		addressees.
3426 	*/
3427 
3428   give_up:
3429 	if (bitnset(M_LMTP, m->m_flags))
3430 	{
3431 		lmtp_rcode = rcode;
3432 		tobuf[0] = '\0';
3433 		anyok = false;
3434 		strsize = 0;
3435 	}
3436 	else
3437 		anyok = rcode == EX_OK;
3438 
3439 	for (to = tochain; to != NULL; to = to->q_tchain)
3440 	{
3441 		/* see if address already marked */
3442 		if (!QS_IS_OK(to->q_state))
3443 			continue;
3444 
3445 		/* if running LMTP, get the status for each address */
3446 		if (bitnset(M_LMTP, m->m_flags))
3447 		{
3448 			if (lmtp_rcode == EX_OK)
3449 				rcode = smtpgetstat(m, mci, e);
3450 			if (rcode == EX_OK)
3451 			{
3452 				strsize += sm_strlcat2(tobuf + strsize, ",",
3453 						to->q_paddr,
3454 						tobufsize - strsize);
3455 				SM_ASSERT(strsize < tobufsize);
3456 				anyok = true;
3457 			}
3458 			else
3459 			{
3460 				e->e_to = to->q_paddr;
3461 				markfailure(e, to, mci, rcode, true);
3462 				giveresponse(rcode, to->q_status, m, mci,
3463 					     ctladdr, xstart, e, to);
3464 				e->e_to = tobuf + 1;
3465 				continue;
3466 			}
3467 		}
3468 		else
3469 		{
3470 			/* mark bad addresses */
3471 			if (rcode != EX_OK)
3472 			{
3473 				if (goodmxfound && rcode == EX_NOHOST)
3474 					rcode = EX_TEMPFAIL;
3475 				markfailure(e, to, mci, rcode, true);
3476 				continue;
3477 			}
3478 		}
3479 
3480 		/* successful delivery */
3481 		to->q_state = QS_SENT;
3482 		to->q_statdate = curtime();
3483 		e->e_nsent++;
3484 
3485 		/*
3486 		**  Checkpoint the send list every few addresses
3487 		*/
3488 
3489 		if (CheckpointInterval > 0 && e->e_nsent >= CheckpointInterval)
3490 		{
3491 			queueup(e, false, false);
3492 			e->e_nsent = 0;
3493 		}
3494 
3495 		if (bitnset(M_LOCALMAILER, m->m_flags) &&
3496 		    bitset(QPINGONSUCCESS, to->q_flags))
3497 		{
3498 			to->q_flags |= QDELIVERED;
3499 			to->q_status = "2.1.5";
3500 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3501 					     "%s... Successfully delivered\n",
3502 					     to->q_paddr);
3503 		}
3504 		else if (bitset(QPINGONSUCCESS, to->q_flags) &&
3505 			 bitset(QPRIMARY, to->q_flags) &&
3506 			 !bitset(MCIF_DSN, mci->mci_flags))
3507 		{
3508 			to->q_flags |= QRELAYED;
3509 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3510 					     "%s... relayed; expect no further notifications\n",
3511 					     to->q_paddr);
3512 		}
3513 		else if (IS_DLVR_NOTIFY(e) &&
3514 			 !bitset(MCIF_DLVR_BY, mci->mci_flags) &&
3515 			 bitset(QPRIMARY, to->q_flags) &&
3516 			 (!bitset(QHASNOTIFY, to->q_flags) ||
3517 			  bitset(QPINGONSUCCESS, to->q_flags) ||
3518 			  bitset(QPINGONFAILURE, to->q_flags) ||
3519 			  bitset(QPINGONDELAY, to->q_flags)))
3520 		{
3521 			/* RFC 2852, 4.1.4.2: no NOTIFY, or not NEVER */
3522 			to->q_flags |= QBYNRELAY;
3523 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3524 					     "%s... Deliver-by notify: relayed\n",
3525 					     to->q_paddr);
3526 		}
3527 		else if (IS_DLVR_TRACE(e) &&
3528 			 (!bitset(QHASNOTIFY, to->q_flags) ||
3529 			  bitset(QPINGONSUCCESS, to->q_flags) ||
3530 			  bitset(QPINGONFAILURE, to->q_flags) ||
3531 			  bitset(QPINGONDELAY, to->q_flags)) &&
3532 			 bitset(QPRIMARY, to->q_flags))
3533 		{
3534 			/* RFC 2852, 4.1.4: no NOTIFY, or not NEVER */
3535 			to->q_flags |= QBYTRACE;
3536 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
3537 					     "%s... Deliver-By trace: relayed\n",
3538 					     to->q_paddr);
3539 		}
3540 	}
3541 
3542 	if (bitnset(M_LMTP, m->m_flags))
3543 	{
3544 		/*
3545 		**  Global information applies to the last recipient only;
3546 		**  clear it out to avoid bogus errors.
3547 		*/
3548 
3549 		rcode = EX_OK;
3550 		e->e_statmsg = NULL;
3551 
3552 		/* reset the mci state for the next transaction */
3553 		if (mci != NULL &&
3554 		    (mci->mci_state == MCIS_MAIL ||
3555 		     mci->mci_state == MCIS_RCPT ||
3556 		     mci->mci_state == MCIS_DATA))
3557 		{
3558 			mci->mci_state = MCIS_OPEN;
3559 			SmtpPhase = mci->mci_phase = "idle";
3560 			sm_setproctitle(true, e, "%s: %s", CurHostName,
3561 					mci->mci_phase);
3562 		}
3563 	}
3564 
3565 	if (tobuf[0] != '\0')
3566 	{
3567 		giveresponse(rcode, NULL, m, mci, ctladdr, xstart, e, tochain);
3568 #if 0
3569 		/*
3570 		**  This code is disabled for now because I am not
3571 		**  sure that copying status from the first recipient
3572 		**  to all non-status'ed recipients is a good idea.
3573 		*/
3574 
3575 		if (tochain->q_message != NULL &&
3576 		    !bitnset(M_LMTP, m->m_flags) && rcode != EX_OK)
3577 		{
3578 			for (to = tochain->q_tchain; to != NULL;
3579 			     to = to->q_tchain)
3580 			{
3581 				/* see if address already marked */
3582 				if (QS_IS_QUEUEUP(to->q_state) &&
3583 				    to->q_message == NULL)
3584 					to->q_message = sm_rpool_strdup_x(e->e_rpool,
3585 							tochain->q_message);
3586 			}
3587 		}
3588 #endif /* 0 */
3589 	}
3590 	if (anyok)
3591 		markstats(e, tochain, STATS_NORMAL);
3592 	mci_store_persistent(mci);
3593 
3594 	/* Some recipients were tempfailed, try them on the next host */
3595 	if (mci != NULL && mci->mci_retryrcpt && nummxhosts > hostnum)
3596 	{
3597 		/* try next MX site */
3598 		goto tryhost;
3599 	}
3600 
3601 	/* now close the connection */
3602 	if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
3603 	    !bitset(MCIF_CACHED, mci->mci_flags))
3604 		smtpquit(m, mci, e);
3605 
3606 cleanup: ;
3607 	}
3608 	SM_FINALLY
3609 	{
3610 		/*
3611 		**  Restore state and return.
3612 		*/
3613 #if XDEBUG
3614 		char wbuf[MAXLINE];
3615 
3616 		/* make absolutely certain 0, 1, and 2 are in use */
3617 		(void) sm_snprintf(wbuf, sizeof wbuf,
3618 				   "%s... end of deliver(%s)",
3619 				   e->e_to == NULL ? "NO-TO-LIST"
3620 						   : shortenstring(e->e_to,
3621 								   MAXSHORTSTR),
3622 				  m->m_name);
3623 		checkfd012(wbuf);
3624 #endif /* XDEBUG */
3625 
3626 		errno = 0;
3627 
3628 		/*
3629 		**  It was originally necessary to set macro 'g' to NULL
3630 		**  because it previously pointed to an auto buffer.
3631 		**  We don't do this any more, so this may be unnecessary.
3632 		*/
3633 
3634 		macdefine(&e->e_macro, A_PERM, 'g', (char *) NULL);
3635 		e->e_to = NULL;
3636 	}
3637 	SM_END_TRY
3638 	return rcode;
3639 }
3640 
3641 /*
3642 **  MARKFAILURE -- mark a failure on a specific address.
3643 **
3644 **	Parameters:
3645 **		e -- the envelope we are sending.
3646 **		q -- the address to mark.
3647 **		mci -- mailer connection information.
3648 **		rcode -- the code signifying the particular failure.
3649 **		ovr -- override an existing code?
3650 **
3651 **	Returns:
3652 **		none.
3653 **
3654 **	Side Effects:
3655 **		marks the address (and possibly the envelope) with the
3656 **			failure so that an error will be returned or
3657 **			the message will be queued, as appropriate.
3658 */
3659 
3660 void
3661 markfailure(e, q, mci, rcode, ovr)
3662 	register ENVELOPE *e;
3663 	register ADDRESS *q;
3664 	register MCI *mci;
3665 	int rcode;
3666 	bool ovr;
3667 {
3668 	int save_errno = errno;
3669 	char *status = NULL;
3670 	char *rstatus = NULL;
3671 
3672 	switch (rcode)
3673 	{
3674 	  case EX_OK:
3675 		break;
3676 
3677 	  case EX_TEMPFAIL:
3678 	  case EX_IOERR:
3679 	  case EX_OSERR:
3680 		q->q_state = QS_QUEUEUP;
3681 		break;
3682 
3683 	  default:
3684 		q->q_state = QS_BADADDR;
3685 		break;
3686 	}
3687 
3688 	/* find most specific error code possible */
3689 	if (mci != NULL && mci->mci_status != NULL)
3690 	{
3691 		status = sm_rpool_strdup_x(e->e_rpool, mci->mci_status);
3692 		if (mci->mci_rstatus != NULL)
3693 			rstatus = sm_rpool_strdup_x(e->e_rpool,
3694 						    mci->mci_rstatus);
3695 		else
3696 			rstatus = NULL;
3697 	}
3698 	else if (e->e_status != NULL)
3699 	{
3700 		status = e->e_status;
3701 		rstatus = NULL;
3702 	}
3703 	else
3704 	{
3705 		switch (rcode)
3706 		{
3707 		  case EX_USAGE:
3708 			status = "5.5.4";
3709 			break;
3710 
3711 		  case EX_DATAERR:
3712 			status = "5.5.2";
3713 			break;
3714 
3715 		  case EX_NOUSER:
3716 			status = "5.1.1";
3717 			break;
3718 
3719 		  case EX_NOHOST:
3720 			status = "5.1.2";
3721 			break;
3722 
3723 		  case EX_NOINPUT:
3724 		  case EX_CANTCREAT:
3725 		  case EX_NOPERM:
3726 			status = "5.3.0";
3727 			break;
3728 
3729 		  case EX_UNAVAILABLE:
3730 		  case EX_SOFTWARE:
3731 		  case EX_OSFILE:
3732 		  case EX_PROTOCOL:
3733 		  case EX_CONFIG:
3734 			status = "5.5.0";
3735 			break;
3736 
3737 		  case EX_OSERR:
3738 		  case EX_IOERR:
3739 			status = "4.5.0";
3740 			break;
3741 
3742 		  case EX_TEMPFAIL:
3743 			status = "4.2.0";
3744 			break;
3745 		}
3746 	}
3747 
3748 	/* new status? */
3749 	if (status != NULL && *status != '\0' && (ovr || q->q_status == NULL ||
3750 	    *q->q_status == '\0' || *q->q_status < *status))
3751 	{
3752 		q->q_status = status;
3753 		q->q_rstatus = rstatus;
3754 	}
3755 	if (rcode != EX_OK && q->q_rstatus == NULL &&
3756 	    q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
3757 	    sm_strcasecmp(q->q_mailer->m_diagtype, "X-UNIX") == 0)
3758 	{
3759 		char buf[16];
3760 
3761 		(void) sm_snprintf(buf, sizeof buf, "%d", rcode);
3762 		q->q_rstatus = sm_rpool_strdup_x(e->e_rpool, buf);
3763 	}
3764 
3765 	q->q_statdate = curtime();
3766 	if (CurHostName != NULL && CurHostName[0] != '\0' &&
3767 	    mci != NULL && !bitset(M_LOCALMAILER, mci->mci_flags))
3768 		q->q_statmta = sm_rpool_strdup_x(e->e_rpool, CurHostName);
3769 
3770 	/* restore errno */
3771 	errno = save_errno;
3772 }
3773 /*
3774 **  ENDMAILER -- Wait for mailer to terminate.
3775 **
3776 **	We should never get fatal errors (e.g., segmentation
3777 **	violation), so we report those specially.  For other
3778 **	errors, we choose a status message (into statmsg),
3779 **	and if it represents an error, we print it.
3780 **
3781 **	Parameters:
3782 **		mci -- the mailer connection info.
3783 **		e -- the current envelope.
3784 **		pv -- the parameter vector that invoked the mailer
3785 **			(for error messages).
3786 **
3787 **	Returns:
3788 **		exit code of mailer.
3789 **
3790 **	Side Effects:
3791 **		none.
3792 */
3793 
3794 static jmp_buf	EndWaitTimeout;
3795 
3796 static void
3797 endwaittimeout(ignore)
3798 	int ignore;
3799 {
3800 	/*
3801 	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3802 	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3803 	**	DOING.
3804 	*/
3805 
3806 	errno = ETIMEDOUT;
3807 	longjmp(EndWaitTimeout, 1);
3808 }
3809 
3810 int
3811 endmailer(mci, e, pv)
3812 	register MCI *mci;
3813 	register ENVELOPE *e;
3814 	char **pv;
3815 {
3816 	int st;
3817 	int save_errno = errno;
3818 	char buf[MAXLINE];
3819 	SM_EVENT *ev = NULL;
3820 
3821 
3822 	mci_unlock_host(mci);
3823 
3824 	/* close output to mailer */
3825 	if (mci->mci_out != NULL)
3826 	{
3827 		(void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3828 		mci->mci_out = NULL;
3829 	}
3830 
3831 	/* copy any remaining input to transcript */
3832 	if (mci->mci_in != NULL && mci->mci_state != MCIS_ERROR &&
3833 	    e->e_xfp != NULL)
3834 	{
3835 		while (sfgets(buf, sizeof buf, mci->mci_in,
3836 			      TimeOuts.to_quit, "Draining Input") != NULL)
3837 			(void) sm_io_fputs(e->e_xfp, SM_TIME_DEFAULT, buf);
3838 	}
3839 
3840 #if SASL
3841 	/* close SASL connection */
3842 	if (bitset(MCIF_AUTHACT, mci->mci_flags))
3843 	{
3844 		sasl_dispose(&mci->mci_conn);
3845 		mci->mci_flags &= ~MCIF_AUTHACT;
3846 	}
3847 #endif /* SASL */
3848 
3849 #if STARTTLS
3850 	/* shutdown TLS */
3851 	(void) endtlsclt(mci);
3852 #endif /* STARTTLS */
3853 
3854 	/* now close the input */
3855 	if (mci->mci_in != NULL)
3856 	{
3857 		(void) sm_io_close(mci->mci_in, SM_TIME_DEFAULT);
3858 		mci->mci_in = NULL;
3859 	}
3860 	mci->mci_state = MCIS_CLOSED;
3861 
3862 	errno = save_errno;
3863 
3864 	/* in the IPC case there is nothing to wait for */
3865 	if (mci->mci_pid == 0)
3866 		return EX_OK;
3867 
3868 	/* put a timeout around the wait */
3869 	if (mci->mci_mailer->m_wait > 0)
3870 	{
3871 		if (setjmp(EndWaitTimeout) == 0)
3872 			ev = sm_setevent(mci->mci_mailer->m_wait,
3873 					 endwaittimeout, 0);
3874 		else
3875 		{
3876 			syserr("endmailer %s: wait timeout (%ld)",
3877 			       mci->mci_mailer->m_name,
3878 			       (long) mci->mci_mailer->m_wait);
3879 			return EX_TEMPFAIL;
3880 		}
3881 	}
3882 
3883 	/* wait for the mailer process, collect status */
3884 	st = waitfor(mci->mci_pid);
3885 	save_errno = errno;
3886 	if (ev != NULL)
3887 		sm_clrevent(ev);
3888 	errno = save_errno;
3889 
3890 	if (st == -1)
3891 	{
3892 		syserr("endmailer %s: wait", mci->mci_mailer->m_name);
3893 		return EX_SOFTWARE;
3894 	}
3895 
3896 	if (WIFEXITED(st))
3897 	{
3898 		/* normal death -- return status */
3899 		return (WEXITSTATUS(st));
3900 	}
3901 
3902 	/* it died a horrid death */
3903 	syserr("451 4.3.0 mailer %s died with signal %d%s",
3904 		mci->mci_mailer->m_name, WTERMSIG(st),
3905 		WCOREDUMP(st) ? " (core dumped)" :
3906 		(WIFSTOPPED(st) ? " (stopped)" : ""));
3907 
3908 	/* log the arguments */
3909 	if (pv != NULL && e->e_xfp != NULL)
3910 	{
3911 		register char **av;
3912 
3913 		(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "Arguments:");
3914 		for (av = pv; *av != NULL; av++)
3915 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, " %s",
3916 					     *av);
3917 		(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "\n");
3918 	}
3919 
3920 	ExitStat = EX_TEMPFAIL;
3921 	return EX_TEMPFAIL;
3922 }
3923 /*
3924 **  GIVERESPONSE -- Interpret an error response from a mailer
3925 **
3926 **	Parameters:
3927 **		status -- the status code from the mailer (high byte
3928 **			only; core dumps must have been taken care of
3929 **			already).
3930 **		dsn -- the DSN associated with the address, if any.
3931 **		m -- the mailer info for this mailer.
3932 **		mci -- the mailer connection info -- can be NULL if the
3933 **			response is given before the connection is made.
3934 **		ctladdr -- the controlling address for the recipient
3935 **			address(es).
3936 **		xstart -- the transaction start time, for computing
3937 **			transaction delays.
3938 **		e -- the current envelope.
3939 **		to -- the current recipient (NULL if none).
3940 **
3941 **	Returns:
3942 **		none.
3943 **
3944 **	Side Effects:
3945 **		Errors may be incremented.
3946 **		ExitStat may be set.
3947 */
3948 
3949 void
3950 giveresponse(status, dsn, m, mci, ctladdr, xstart, e, to)
3951 	int status;
3952 	char *dsn;
3953 	register MAILER *m;
3954 	register MCI *mci;
3955 	ADDRESS *ctladdr;
3956 	time_t xstart;
3957 	ENVELOPE *e;
3958 	ADDRESS *to;
3959 {
3960 	register const char *statmsg;
3961 	int errnum = errno;
3962 	int off = 4;
3963 	bool usestat = false;
3964 	char dsnbuf[ENHSCLEN];
3965 	char buf[MAXLINE];
3966 	char *exmsg;
3967 
3968 	if (e == NULL)
3969 	{
3970 		syserr("giveresponse: null envelope");
3971 		/* NOTREACHED */
3972 		SM_ASSERT(0);
3973 	}
3974 
3975 	/*
3976 	**  Compute status message from code.
3977 	*/
3978 
3979 	exmsg = sm_sysexmsg(status);
3980 	if (status == 0)
3981 	{
3982 		statmsg = "250 2.0.0 Sent";
3983 		if (e->e_statmsg != NULL)
3984 		{
3985 			(void) sm_snprintf(buf, sizeof buf, "%s (%s)",
3986 					   statmsg,
3987 					   shortenstring(e->e_statmsg, 403));
3988 			statmsg = buf;
3989 		}
3990 	}
3991 	else if (exmsg == NULL)
3992 	{
3993 		(void) sm_snprintf(buf, sizeof buf,
3994 				   "554 5.3.0 unknown mailer error %d",
3995 				   status);
3996 		status = EX_UNAVAILABLE;
3997 		statmsg = buf;
3998 		usestat = true;
3999 	}
4000 	else if (status == EX_TEMPFAIL)
4001 	{
4002 		char *bp = buf;
4003 
4004 		(void) sm_strlcpy(bp, exmsg + 1, SPACELEFT(buf, bp));
4005 		bp += strlen(bp);
4006 #if NAMED_BIND
4007 		if (h_errno == TRY_AGAIN)
4008 			statmsg = sm_errstring(h_errno + E_DNSBASE);
4009 		else
4010 #endif /* NAMED_BIND */
4011 		{
4012 			if (errnum != 0)
4013 				statmsg = sm_errstring(errnum);
4014 			else
4015 				statmsg = SmtpError;
4016 		}
4017 		if (statmsg != NULL && statmsg[0] != '\0')
4018 		{
4019 			switch (errnum)
4020 			{
4021 #ifdef ENETDOWN
4022 			  case ENETDOWN:	/* Network is down */
4023 #endif /* ENETDOWN */
4024 #ifdef ENETUNREACH
4025 			  case ENETUNREACH:	/* Network is unreachable */
4026 #endif /* ENETUNREACH */
4027 #ifdef ENETRESET
4028 			  case ENETRESET:	/* Network dropped connection on reset */
4029 #endif /* ENETRESET */
4030 #ifdef ECONNABORTED
4031 			  case ECONNABORTED:	/* Software caused connection abort */
4032 #endif /* ECONNABORTED */
4033 #ifdef EHOSTDOWN
4034 			  case EHOSTDOWN:	/* Host is down */
4035 #endif /* EHOSTDOWN */
4036 #ifdef EHOSTUNREACH
4037 			  case EHOSTUNREACH:	/* No route to host */
4038 #endif /* EHOSTUNREACH */
4039 				if (mci != NULL && mci->mci_host != NULL)
4040 				{
4041 					(void) sm_strlcpyn(bp,
4042 							   SPACELEFT(buf, bp),
4043 							   2, ": ",
4044 							   mci->mci_host);
4045 					bp += strlen(bp);
4046 				}
4047 				break;
4048 			}
4049 			(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ": ",
4050 					   statmsg);
4051 			usestat = true;
4052 		}
4053 		statmsg = buf;
4054 	}
4055 #if NAMED_BIND
4056 	else if (status == EX_NOHOST && h_errno != 0)
4057 	{
4058 		statmsg = sm_errstring(h_errno + E_DNSBASE);
4059 		(void) sm_snprintf(buf, sizeof buf, "%s (%s)", exmsg + 1,
4060 				   statmsg);
4061 		statmsg = buf;
4062 		usestat = true;
4063 	}
4064 #endif /* NAMED_BIND */
4065 	else
4066 	{
4067 		statmsg = exmsg;
4068 		if (*statmsg++ == ':' && errnum != 0)
4069 		{
4070 			(void) sm_snprintf(buf, sizeof buf, "%s: %s", statmsg,
4071 					   sm_errstring(errnum));
4072 			statmsg = buf;
4073 			usestat = true;
4074 		}
4075 		else if (bitnset(M_LMTP, m->m_flags) && e->e_statmsg != NULL)
4076 		{
4077 			(void) sm_snprintf(buf, sizeof buf, "%s (%s)", statmsg,
4078 					   shortenstring(e->e_statmsg, 403));
4079 			statmsg = buf;
4080 			usestat = true;
4081 		}
4082 	}
4083 
4084 	/*
4085 	**  Print the message as appropriate
4086 	*/
4087 
4088 	if (status == EX_OK || status == EX_TEMPFAIL)
4089 	{
4090 		extern char MsgBuf[];
4091 
4092 		if ((off = isenhsc(statmsg + 4, ' ')) > 0)
4093 		{
4094 			if (dsn == NULL)
4095 			{
4096 				(void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4097 						   "%.*s", off, statmsg + 4);
4098 				dsn = dsnbuf;
4099 			}
4100 			off += 5;
4101 		}
4102 		else
4103 		{
4104 			off = 4;
4105 		}
4106 		message("%s", statmsg + off);
4107 		if (status == EX_TEMPFAIL && e->e_xfp != NULL)
4108 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT, "%s\n",
4109 					     &MsgBuf[4]);
4110 	}
4111 	else
4112 	{
4113 		char mbuf[ENHSCLEN + 4];
4114 
4115 		Errors++;
4116 		if ((off = isenhsc(statmsg + 4, ' ')) > 0 &&
4117 		    off < sizeof mbuf - 4)
4118 		{
4119 			if (dsn == NULL)
4120 			{
4121 				(void) sm_snprintf(dsnbuf, sizeof dsnbuf,
4122 						   "%.*s", off, statmsg + 4);
4123 				dsn = dsnbuf;
4124 			}
4125 			off += 5;
4126 
4127 			/* copy only part of statmsg to mbuf */
4128 			(void) sm_strlcpy(mbuf, statmsg, off);
4129 			(void) sm_strlcat(mbuf, " %s", sizeof mbuf);
4130 		}
4131 		else
4132 		{
4133 			dsnbuf[0] = '\0';
4134 			(void) sm_snprintf(mbuf, sizeof mbuf, "%.3s %%s",
4135 					   statmsg);
4136 			off = 4;
4137 		}
4138 		usrerr(mbuf, &statmsg[off]);
4139 	}
4140 
4141 	/*
4142 	**  Final cleanup.
4143 	**	Log a record of the transaction.  Compute the new
4144 	**	ExitStat -- if we already had an error, stick with
4145 	**	that.
4146 	*/
4147 
4148 	if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
4149 	    LogLevel > ((status == EX_TEMPFAIL) ? 8 : (status == EX_OK) ? 7 : 6))
4150 		logdelivery(m, mci, dsn, statmsg + off, ctladdr, xstart, e);
4151 
4152 	if (tTd(11, 2))
4153 		sm_dprintf("giveresponse: status=%d, dsn=%s, e->e_message=%s, errnum=%d\n",
4154 			   status,
4155 			   dsn == NULL ? "<NULL>" : dsn,
4156 			   e->e_message == NULL ? "<NULL>" : e->e_message,
4157 			   errnum);
4158 
4159 	if (status != EX_TEMPFAIL)
4160 		setstat(status);
4161 	if (status != EX_OK && (status != EX_TEMPFAIL || e->e_message == NULL))
4162 		e->e_message = sm_rpool_strdup_x(e->e_rpool, statmsg + off);
4163 	if (status != EX_OK && to != NULL && to->q_message == NULL)
4164 	{
4165 		if (!usestat && e->e_message != NULL)
4166 			to->q_message = sm_rpool_strdup_x(e->e_rpool,
4167 							  e->e_message);
4168 		else
4169 			to->q_message = sm_rpool_strdup_x(e->e_rpool,
4170 							  statmsg + off);
4171 	}
4172 	errno = 0;
4173 	SM_SET_H_ERRNO(0);
4174 }
4175 /*
4176 **  LOGDELIVERY -- log the delivery in the system log
4177 **
4178 **	Care is taken to avoid logging lines that are too long, because
4179 **	some versions of syslog have an unfortunate proclivity for core
4180 **	dumping.  This is a hack, to be sure, that is at best empirical.
4181 **
4182 **	Parameters:
4183 **		m -- the mailer info.  Can be NULL for initial queue.
4184 **		mci -- the mailer connection info -- can be NULL if the
4185 **			log is occurring when no connection is active.
4186 **		dsn -- the DSN attached to the status.
4187 **		status -- the message to print for the status.
4188 **		ctladdr -- the controlling address for the to list.
4189 **		xstart -- the transaction start time, used for
4190 **			computing transaction delay.
4191 **		e -- the current envelope.
4192 **
4193 **	Returns:
4194 **		none
4195 **
4196 **	Side Effects:
4197 **		none
4198 */
4199 
4200 void
4201 logdelivery(m, mci, dsn, status, ctladdr, xstart, e)
4202 	MAILER *m;
4203 	register MCI *mci;
4204 	char *dsn;
4205 	const char *status;
4206 	ADDRESS *ctladdr;
4207 	time_t xstart;
4208 	register ENVELOPE *e;
4209 {
4210 	register char *bp;
4211 	register char *p;
4212 	int l;
4213 	time_t now = curtime();
4214 	char buf[1024];
4215 
4216 #if (SYSLOG_BUFSIZE) >= 256
4217 	/* ctladdr: max 106 bytes */
4218 	bp = buf;
4219 	if (ctladdr != NULL)
4220 	{
4221 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", ctladdr=",
4222 				   shortenstring(ctladdr->q_paddr, 83));
4223 		bp += strlen(bp);
4224 		if (bitset(QGOODUID, ctladdr->q_flags))
4225 		{
4226 			(void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4227 					   (int) ctladdr->q_uid,
4228 					   (int) ctladdr->q_gid);
4229 			bp += strlen(bp);
4230 		}
4231 	}
4232 
4233 	/* delay & xdelay: max 41 bytes */
4234 	(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", delay=",
4235 			   pintvl(now - e->e_ctime, true));
4236 	bp += strlen(bp);
4237 
4238 	if (xstart != (time_t) 0)
4239 	{
4240 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4241 				   pintvl(now - xstart, true));
4242 		bp += strlen(bp);
4243 	}
4244 
4245 	/* mailer: assume about 19 bytes (max 10 byte mailer name) */
4246 	if (m != NULL)
4247 	{
4248 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4249 				   m->m_name);
4250 		bp += strlen(bp);
4251 	}
4252 
4253 	/* pri: changes with each delivery attempt */
4254 	(void) sm_snprintf(bp, SPACELEFT(buf, bp), ", pri=%ld",
4255 		e->e_msgpriority);
4256 	bp += strlen(bp);
4257 
4258 	/* relay: max 66 bytes for IPv4 addresses */
4259 	if (mci != NULL && mci->mci_host != NULL)
4260 	{
4261 		extern SOCKADDR CurHostAddr;
4262 
4263 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", relay=",
4264 				   shortenstring(mci->mci_host, 40));
4265 		bp += strlen(bp);
4266 
4267 		if (CurHostAddr.sa.sa_family != 0)
4268 		{
4269 			(void) sm_snprintf(bp, SPACELEFT(buf, bp), " [%s]",
4270 					   anynet_ntoa(&CurHostAddr));
4271 		}
4272 	}
4273 	else if (strcmp(status, "quarantined") == 0)
4274 	{
4275 		if (e->e_quarmsg != NULL)
4276 			(void) sm_snprintf(bp, SPACELEFT(buf, bp),
4277 					   ", quarantine=%s",
4278 					   shortenstring(e->e_quarmsg, 40));
4279 	}
4280 	else if (strcmp(status, "queued") != 0)
4281 	{
4282 		p = macvalue('h', e);
4283 		if (p != NULL && p[0] != '\0')
4284 		{
4285 			(void) sm_snprintf(bp, SPACELEFT(buf, bp),
4286 					   ", relay=%s", shortenstring(p, 40));
4287 		}
4288 	}
4289 	bp += strlen(bp);
4290 
4291 	/* dsn */
4292 	if (dsn != NULL && *dsn != '\0')
4293 	{
4294 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", dsn=",
4295 				   shortenstring(dsn, ENHSCLEN));
4296 		bp += strlen(bp);
4297 	}
4298 
4299 #if _FFR_LOG_NTRIES
4300 	/* ntries */
4301 	if (e->e_ntries >= 0)
4302 	{
4303 		(void) sm_snprintf(bp, SPACELEFT(buf, bp),
4304 				   ", ntries=%d", e->e_ntries + 1);
4305 		bp += strlen(bp);
4306 	}
4307 #endif /* _FFR_LOG_NTRIES */
4308 
4309 # define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
4310 # if (STATLEN) < 63
4311 #  undef STATLEN
4312 #  define STATLEN	63
4313 # endif /* (STATLEN) < 63 */
4314 # if (STATLEN) > 203
4315 #  undef STATLEN
4316 #  define STATLEN	203
4317 # endif /* (STATLEN) > 203 */
4318 
4319 	/* stat: max 210 bytes */
4320 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
4321 	{
4322 		/* desperation move -- truncate data */
4323 		bp = buf + sizeof buf - ((STATLEN) + 17);
4324 		(void) sm_strlcpy(bp, "...", SPACELEFT(buf, bp));
4325 		bp += 3;
4326 	}
4327 
4328 	(void) sm_strlcpy(bp, ", stat=", SPACELEFT(buf, bp));
4329 	bp += strlen(bp);
4330 
4331 	(void) sm_strlcpy(bp, shortenstring(status, STATLEN),
4332 			  SPACELEFT(buf, bp));
4333 
4334 	/* id, to: max 13 + TOBUFSIZE bytes */
4335 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
4336 	if (l < 0)
4337 		l = 0;
4338 	p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4339 	while (strlen(p) >= l)
4340 	{
4341 		register char *q;
4342 
4343 		for (q = p + l; q > p; q--)
4344 		{
4345 			if (*q == ',')
4346 				break;
4347 		}
4348 		if (p == q)
4349 			break;
4350 		sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]%s",
4351 			  (int) (++q - p), p, buf);
4352 		p = q;
4353 	}
4354 	sm_syslog(LOG_INFO, e->e_id, "to=%.*s%s", l, p, buf);
4355 
4356 #else /* (SYSLOG_BUFSIZE) >= 256 */
4357 
4358 	l = SYSLOG_BUFSIZE - 85;
4359 	if (l < 0)
4360 		l = 0;
4361 	p = e->e_to == NULL ? "NO-TO-LIST" : e->e_to;
4362 	while (strlen(p) >= l)
4363 	{
4364 		register char *q;
4365 
4366 		for (q = p + l; q > p; q--)
4367 		{
4368 			if (*q == ',')
4369 				break;
4370 		}
4371 		if (p == q)
4372 			break;
4373 
4374 		sm_syslog(LOG_INFO, e->e_id, "to=%.*s [more]",
4375 			  (int) (++q - p), p);
4376 		p = q;
4377 	}
4378 	sm_syslog(LOG_INFO, e->e_id, "to=%.*s", l, p);
4379 
4380 	if (ctladdr != NULL)
4381 	{
4382 		bp = buf;
4383 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "ctladdr=",
4384 				   shortenstring(ctladdr->q_paddr, 83));
4385 		bp += strlen(bp);
4386 		if (bitset(QGOODUID, ctladdr->q_flags))
4387 		{
4388 			(void) sm_snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
4389 					   ctladdr->q_uid, ctladdr->q_gid);
4390 			bp += strlen(bp);
4391 		}
4392 		sm_syslog(LOG_INFO, e->e_id, "%s", buf);
4393 	}
4394 	bp = buf;
4395 	(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, "delay=",
4396 			   pintvl(now - e->e_ctime, true));
4397 	bp += strlen(bp);
4398 	if (xstart != (time_t) 0)
4399 	{
4400 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", xdelay=",
4401 				   pintvl(now - xstart, true));
4402 		bp += strlen(bp);
4403 	}
4404 
4405 	if (m != NULL)
4406 	{
4407 		(void) sm_strlcpyn(bp, SPACELEFT(buf, bp), 2, ", mailer=",
4408 				   m->m_name);
4409 		bp += strlen(bp);
4410 	}
4411 	sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4412 
4413 	buf[0] = '\0';
4414 	bp = buf;
4415 	if (mci != NULL && mci->mci_host != NULL)
4416 	{
4417 		extern SOCKADDR CurHostAddr;
4418 
4419 		(void) sm_snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s",
4420 				   mci->mci_host);
4421 		bp += strlen(bp);
4422 
4423 		if (CurHostAddr.sa.sa_family != 0)
4424 			(void) sm_snprintf(bp, SPACELEFT(buf, bp),
4425 					   " [%.100s]",
4426 					   anynet_ntoa(&CurHostAddr));
4427 	}
4428 	else if (strcmp(status, "quarantined") == 0)
4429 	{
4430 		if (e->e_quarmsg != NULL)
4431 			(void) sm_snprintf(bp, SPACELEFT(buf, bp),
4432 					   ", quarantine=%.100s",
4433 					   e->e_quarmsg);
4434 	}
4435 	else if (strcmp(status, "queued") != 0)
4436 	{
4437 		p = macvalue('h', e);
4438 		if (p != NULL && p[0] != '\0')
4439 			(void) sm_snprintf(buf, sizeof buf, "relay=%.100s", p);
4440 	}
4441 	if (buf[0] != '\0')
4442 		sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);
4443 
4444 	sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(status, 63));
4445 #endif /* (SYSLOG_BUFSIZE) >= 256 */
4446 }
4447 /*
4448 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
4449 **
4450 **	This can be made an arbitrary message separator by changing $l
4451 **
4452 **	One of the ugliest hacks seen by human eyes is contained herein:
4453 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
4454 **	does a well-meaning programmer such as myself have to deal with
4455 **	this kind of antique garbage????
4456 **
4457 **	Parameters:
4458 **		mci -- the connection information.
4459 **		e -- the envelope.
4460 **
4461 **	Returns:
4462 **		true iff line was written successfully
4463 **
4464 **	Side Effects:
4465 **		outputs some text to fp.
4466 */
4467 
4468 bool
4469 putfromline(mci, e)
4470 	register MCI *mci;
4471 	ENVELOPE *e;
4472 {
4473 	char *template = UnixFromLine;
4474 	char buf[MAXLINE];
4475 	char xbuf[MAXLINE];
4476 
4477 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
4478 		return true;
4479 
4480 	mci->mci_flags |= MCIF_INHEADER;
4481 
4482 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
4483 	{
4484 		char *bang;
4485 
4486 		expand("\201g", buf, sizeof buf, e);
4487 		bang = strchr(buf, '!');
4488 		if (bang == NULL)
4489 		{
4490 			char *at;
4491 			char hname[MAXNAME];
4492 
4493 			/*
4494 			**  If we can construct a UUCP path, do so
4495 			*/
4496 
4497 			at = strrchr(buf, '@');
4498 			if (at == NULL)
4499 			{
4500 				expand("\201k", hname, sizeof hname, e);
4501 				at = hname;
4502 			}
4503 			else
4504 				*at++ = '\0';
4505 			(void) sm_snprintf(xbuf, sizeof xbuf,
4506 					   "From %.800s  \201d remote from %.100s\n",
4507 					   buf, at);
4508 		}
4509 		else
4510 		{
4511 			*bang++ = '\0';
4512 			(void) sm_snprintf(xbuf, sizeof xbuf,
4513 					   "From %.800s  \201d remote from %.100s\n",
4514 					   bang, buf);
4515 			template = xbuf;
4516 		}
4517 	}
4518 	expand(template, buf, sizeof buf, e);
4519 	return putxline(buf, strlen(buf), mci, PXLF_HEADER);
4520 }
4521 
4522 /*
4523 **  PUTBODY -- put the body of a message.
4524 **
4525 **	Parameters:
4526 **		mci -- the connection information.
4527 **		e -- the envelope to put out.
4528 **		separator -- if non-NULL, a message separator that must
4529 **			not be permitted in the resulting message.
4530 **
4531 **	Returns:
4532 **		true iff message was written successfully
4533 **
4534 **	Side Effects:
4535 **		The message is written onto fp.
4536 */
4537 
4538 /* values for output state variable */
4539 #define OSTATE_HEAD	0	/* at beginning of line */
4540 #define OSTATE_CR	1	/* read a carriage return */
4541 #define OSTATE_INLINE	2	/* putting rest of line */
4542 
4543 bool
4544 putbody(mci, e, separator)
4545 	register MCI *mci;
4546 	register ENVELOPE *e;
4547 	char *separator;
4548 {
4549 	bool dead = false;
4550 	bool ioerr = false;
4551 	int save_errno;
4552 	char buf[MAXLINE];
4553 #if MIME8TO7
4554 	char *boundaries[MAXMIMENESTING + 1];
4555 #endif /* MIME8TO7 */
4556 
4557 	/*
4558 	**  Output the body of the message
4559 	*/
4560 
4561 	if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
4562 	{
4563 		char *df = queuename(e, DATAFL_LETTER);
4564 
4565 		e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
4566 				      SM_IO_RDONLY_B, NULL);
4567 		if (e->e_dfp == NULL)
4568 		{
4569 			char *msg = "!putbody: Cannot open %s for %s from %s";
4570 
4571 			if (errno == ENOENT)
4572 				msg++;
4573 			syserr(msg, df, e->e_to, e->e_from.q_paddr);
4574 		}
4575 
4576 	}
4577 	if (e->e_dfp == NULL)
4578 	{
4579 		if (bitset(MCIF_INHEADER, mci->mci_flags))
4580 		{
4581 			if (!putline("", mci))
4582 				goto writeerr;
4583 			mci->mci_flags &= ~MCIF_INHEADER;
4584 		}
4585 		if (!putline("<<< No Message Collected >>>", mci))
4586 			goto writeerr;
4587 		goto endofmessage;
4588 	}
4589 
4590 	if (e->e_dfino == (ino_t) 0)
4591 	{
4592 		struct stat stbuf;
4593 
4594 		if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &stbuf)
4595 		    < 0)
4596 			e->e_dfino = -1;
4597 		else
4598 		{
4599 			e->e_dfdev = stbuf.st_dev;
4600 			e->e_dfino = stbuf.st_ino;
4601 		}
4602 	}
4603 
4604 	/* paranoia: the data file should always be in a rewound state */
4605 	(void) bfrewind(e->e_dfp);
4606 
4607 	/* simulate an I/O timeout when used as source */
4608 	if (tTd(84, 101))
4609 		sleep(319);
4610 
4611 #if MIME8TO7
4612 	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
4613 	{
4614 		/*
4615 		**  Do 8 to 7 bit MIME conversion.
4616 		*/
4617 
4618 		/* make sure it looks like a MIME message */
4619 		if (hvalue("MIME-Version", e->e_header) == NULL &&
4620 		    !putline("MIME-Version: 1.0", mci))
4621 			goto writeerr;
4622 
4623 		if (hvalue("Content-Type", e->e_header) == NULL)
4624 		{
4625 			(void) sm_snprintf(buf, sizeof buf,
4626 					   "Content-Type: text/plain; charset=%s",
4627 					   defcharset(e));
4628 			if (!putline(buf, mci))
4629 				goto writeerr;
4630 		}
4631 
4632 		/* now do the hard work */
4633 		boundaries[0] = NULL;
4634 		mci->mci_flags |= MCIF_INHEADER;
4635 		if (mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER, 0) ==
4636 								SM_IO_EOF)
4637 			goto writeerr;
4638 	}
4639 # if MIME7TO8
4640 	else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
4641 	{
4642 		if (!mime7to8(mci, e->e_header, e))
4643 			goto writeerr;
4644 	}
4645 # endif /* MIME7TO8 */
4646 	else if (MaxMimeHeaderLength > 0 || MaxMimeFieldLength > 0)
4647 	{
4648 		bool oldsuprerrs = SuprErrs;
4649 
4650 		/* Use mime8to7 to check multipart for MIME header overflows */
4651 		boundaries[0] = NULL;
4652 		mci->mci_flags |= MCIF_INHEADER;
4653 
4654 		/*
4655 		**  If EF_DONT_MIME is set, we have a broken MIME message
4656 		**  and don't want to generate a new bounce message whose
4657 		**  body propagates the broken MIME.  We can't just not call
4658 		**  mime8to7() as is done above since we need the security
4659 		**  checks.  The best we can do is suppress the errors.
4660 		*/
4661 
4662 		if (bitset(EF_DONT_MIME, e->e_flags))
4663 			SuprErrs = true;
4664 
4665 		if (mime8to7(mci, e->e_header, e, boundaries,
4666 				M87F_OUTER|M87F_NO8TO7, 0) == SM_IO_EOF)
4667 			goto writeerr;
4668 
4669 		/* restore SuprErrs */
4670 		SuprErrs = oldsuprerrs;
4671 	}
4672 	else
4673 #endif /* MIME8TO7 */
4674 	{
4675 		int ostate;
4676 		register char *bp;
4677 		register char *pbp;
4678 		register int c;
4679 		register char *xp;
4680 		int padc;
4681 		char *buflim;
4682 		int pos = 0;
4683 		char peekbuf[12];
4684 
4685 		if (bitset(MCIF_INHEADER, mci->mci_flags))
4686 		{
4687 			if (!putline("", mci))
4688 				goto writeerr;
4689 			mci->mci_flags &= ~MCIF_INHEADER;
4690 		}
4691 
4692 		/* determine end of buffer; allow for short mailer lines */
4693 		buflim = &buf[sizeof buf - 1];
4694 		if (mci->mci_mailer->m_linelimit > 0 &&
4695 		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
4696 			buflim = &buf[mci->mci_mailer->m_linelimit - 1];
4697 
4698 		/* copy temp file to output with mapping */
4699 		ostate = OSTATE_HEAD;
4700 		bp = buf;
4701 		pbp = peekbuf;
4702 		while (!sm_io_error(mci->mci_out) && !dead)
4703 		{
4704 			if (pbp > peekbuf)
4705 				c = *--pbp;
4706 			else if ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT))
4707 				 == SM_IO_EOF)
4708 				break;
4709 			if (bitset(MCIF_7BIT, mci->mci_flags))
4710 				c &= 0x7f;
4711 			switch (ostate)
4712 			{
4713 			  case OSTATE_HEAD:
4714 				if (c == '\0' &&
4715 				    bitnset(M_NONULLS,
4716 					    mci->mci_mailer->m_flags))
4717 					break;
4718 				if (c != '\r' && c != '\n' && bp < buflim)
4719 				{
4720 					*bp++ = c;
4721 					break;
4722 				}
4723 
4724 				/* check beginning of line for special cases */
4725 				*bp = '\0';
4726 				pos = 0;
4727 				padc = SM_IO_EOF;
4728 				if (buf[0] == 'F' &&
4729 				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags)
4730 				    && strncmp(buf, "From ", 5) == 0)
4731 				{
4732 					padc = '>';
4733 				}
4734 				if (buf[0] == '-' && buf[1] == '-' &&
4735 				    separator != NULL)
4736 				{
4737 					/* possible separator */
4738 					int sl = strlen(separator);
4739 
4740 					if (strncmp(&buf[2], separator, sl)
4741 					    == 0)
4742 						padc = ' ';
4743 				}
4744 				if (buf[0] == '.' &&
4745 				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
4746 				{
4747 					padc = '.';
4748 				}
4749 
4750 				/* now copy out saved line */
4751 				if (TrafficLogFile != NULL)
4752 				{
4753 					(void) sm_io_fprintf(TrafficLogFile,
4754 							     SM_TIME_DEFAULT,
4755 							     "%05d >>> ",
4756 							     (int) CurrentPid);
4757 					if (padc != SM_IO_EOF)
4758 						(void) sm_io_putc(TrafficLogFile,
4759 								  SM_TIME_DEFAULT,
4760 								  padc);
4761 					for (xp = buf; xp < bp; xp++)
4762 						(void) sm_io_putc(TrafficLogFile,
4763 								  SM_TIME_DEFAULT,
4764 								  (unsigned char) *xp);
4765 					if (c == '\n')
4766 						(void) sm_io_fputs(TrafficLogFile,
4767 								   SM_TIME_DEFAULT,
4768 								   mci->mci_mailer->m_eol);
4769 				}
4770 				if (padc != SM_IO_EOF)
4771 				{
4772 					if (sm_io_putc(mci->mci_out,
4773 						       SM_TIME_DEFAULT, padc)
4774 					    == SM_IO_EOF)
4775 					{
4776 						dead = true;
4777 						continue;
4778 					}
4779 					pos++;
4780 				}
4781 				for (xp = buf; xp < bp; xp++)
4782 				{
4783 					if (sm_io_putc(mci->mci_out,
4784 						       SM_TIME_DEFAULT,
4785 						       (unsigned char) *xp)
4786 					    == SM_IO_EOF)
4787 					{
4788 						dead = true;
4789 						break;
4790 					}
4791 				}
4792 				if (dead)
4793 					continue;
4794 				if (c == '\n')
4795 				{
4796 					if (sm_io_fputs(mci->mci_out,
4797 							SM_TIME_DEFAULT,
4798 							mci->mci_mailer->m_eol)
4799 							== SM_IO_EOF)
4800 						break;
4801 					pos = 0;
4802 				}
4803 				else
4804 				{
4805 					pos += bp - buf;
4806 					if (c != '\r')
4807 					{
4808 						SM_ASSERT(pbp < peekbuf +
4809 								sizeof(peekbuf));
4810 						*pbp++ = c;
4811 					}
4812 				}
4813 
4814 				bp = buf;
4815 
4816 				/* determine next state */
4817 				if (c == '\n')
4818 					ostate = OSTATE_HEAD;
4819 				else if (c == '\r')
4820 					ostate = OSTATE_CR;
4821 				else
4822 					ostate = OSTATE_INLINE;
4823 				continue;
4824 
4825 			  case OSTATE_CR:
4826 				if (c == '\n')
4827 				{
4828 					/* got CRLF */
4829 					if (sm_io_fputs(mci->mci_out,
4830 							SM_TIME_DEFAULT,
4831 							mci->mci_mailer->m_eol)
4832 							== SM_IO_EOF)
4833 						continue;
4834 
4835 					if (TrafficLogFile != NULL)
4836 					{
4837 						(void) sm_io_fputs(TrafficLogFile,
4838 								   SM_TIME_DEFAULT,
4839 								   mci->mci_mailer->m_eol);
4840 					}
4841 					ostate = OSTATE_HEAD;
4842 					continue;
4843 				}
4844 
4845 				/* had a naked carriage return */
4846 				SM_ASSERT(pbp < peekbuf + sizeof(peekbuf));
4847 				*pbp++ = c;
4848 				c = '\r';
4849 				ostate = OSTATE_INLINE;
4850 				goto putch;
4851 
4852 			  case OSTATE_INLINE:
4853 				if (c == '\r')
4854 				{
4855 					ostate = OSTATE_CR;
4856 					continue;
4857 				}
4858 				if (c == '\0' &&
4859 				    bitnset(M_NONULLS,
4860 					    mci->mci_mailer->m_flags))
4861 					break;
4862 putch:
4863 				if (mci->mci_mailer->m_linelimit > 0 &&
4864 				    pos >= mci->mci_mailer->m_linelimit - 1 &&
4865 				    c != '\n')
4866 				{
4867 					int d;
4868 
4869 					/* check next character for EOL */
4870 					if (pbp > peekbuf)
4871 						d = *(pbp - 1);
4872 					else if ((d = sm_io_getc(e->e_dfp,
4873 								 SM_TIME_DEFAULT))
4874 						 != SM_IO_EOF)
4875 					{
4876 						SM_ASSERT(pbp < peekbuf +
4877 								sizeof(peekbuf));
4878 						*pbp++ = d;
4879 					}
4880 
4881 					if (d == '\n' || d == SM_IO_EOF)
4882 					{
4883 						if (TrafficLogFile != NULL)
4884 							(void) sm_io_putc(TrafficLogFile,
4885 									  SM_TIME_DEFAULT,
4886 									  (unsigned char) c);
4887 						if (sm_io_putc(mci->mci_out,
4888 							       SM_TIME_DEFAULT,
4889 							       (unsigned char) c)
4890 							       == SM_IO_EOF)
4891 						{
4892 							dead = true;
4893 							continue;
4894 						}
4895 						pos++;
4896 						continue;
4897 					}
4898 
4899 					if (sm_io_putc(mci->mci_out,
4900 						       SM_TIME_DEFAULT, '!')
4901 					    == SM_IO_EOF ||
4902 					    sm_io_fputs(mci->mci_out,
4903 							SM_TIME_DEFAULT,
4904 							mci->mci_mailer->m_eol)
4905 					    == SM_IO_EOF)
4906 					{
4907 						dead = true;
4908 						continue;
4909 					}
4910 
4911 					if (TrafficLogFile != NULL)
4912 					{
4913 						(void) sm_io_fprintf(TrafficLogFile,
4914 								     SM_TIME_DEFAULT,
4915 								     "!%s",
4916 								     mci->mci_mailer->m_eol);
4917 					}
4918 					ostate = OSTATE_HEAD;
4919 					SM_ASSERT(pbp < peekbuf +
4920 							sizeof(peekbuf));
4921 					*pbp++ = c;
4922 					continue;
4923 				}
4924 				if (c == '\n')
4925 				{
4926 					if (TrafficLogFile != NULL)
4927 						(void) sm_io_fputs(TrafficLogFile,
4928 								   SM_TIME_DEFAULT,
4929 								   mci->mci_mailer->m_eol);
4930 					if (sm_io_fputs(mci->mci_out,
4931 							SM_TIME_DEFAULT,
4932 							mci->mci_mailer->m_eol)
4933 							== SM_IO_EOF)
4934 						continue;
4935 					pos = 0;
4936 					ostate = OSTATE_HEAD;
4937 				}
4938 				else
4939 				{
4940 					if (TrafficLogFile != NULL)
4941 						(void) sm_io_putc(TrafficLogFile,
4942 								  SM_TIME_DEFAULT,
4943 								  (unsigned char) c);
4944 					if (sm_io_putc(mci->mci_out,
4945 						       SM_TIME_DEFAULT,
4946 						       (unsigned char) c)
4947 					    == SM_IO_EOF)
4948 					{
4949 						dead = true;
4950 						continue;
4951 					}
4952 					pos++;
4953 					ostate = OSTATE_INLINE;
4954 				}
4955 				break;
4956 			}
4957 		}
4958 
4959 		/* make sure we are at the beginning of a line */
4960 		if (bp > buf)
4961 		{
4962 			if (TrafficLogFile != NULL)
4963 			{
4964 				for (xp = buf; xp < bp; xp++)
4965 					(void) sm_io_putc(TrafficLogFile,
4966 							  SM_TIME_DEFAULT,
4967 							  (unsigned char) *xp);
4968 			}
4969 			for (xp = buf; xp < bp; xp++)
4970 			{
4971 				if (sm_io_putc(mci->mci_out, SM_TIME_DEFAULT,
4972 					       (unsigned char) *xp)
4973 				    == SM_IO_EOF)
4974 				{
4975 					dead = true;
4976 					break;
4977 				}
4978 			}
4979 			pos += bp - buf;
4980 		}
4981 		if (!dead && pos > 0)
4982 		{
4983 			if (TrafficLogFile != NULL)
4984 				(void) sm_io_fputs(TrafficLogFile,
4985 						   SM_TIME_DEFAULT,
4986 						   mci->mci_mailer->m_eol);
4987 			if (sm_io_fputs(mci->mci_out, SM_TIME_DEFAULT,
4988 					   mci->mci_mailer->m_eol) == SM_IO_EOF)
4989 				goto writeerr;
4990 		}
4991 	}
4992 
4993 	if (sm_io_error(e->e_dfp))
4994 	{
4995 		syserr("putbody: %s/%cf%s: read error",
4996 		       qid_printqueue(e->e_dfqgrp, e->e_dfqdir),
4997 		       DATAFL_LETTER, e->e_id);
4998 		ExitStat = EX_IOERR;
4999 		ioerr = true;
5000 	}
5001 
5002 endofmessage:
5003 	/*
5004 	**  Since mailfile() uses e_dfp in a child process,
5005 	**  the file offset in the stdio library for the
5006 	**  parent process will not agree with the in-kernel
5007 	**  file offset since the file descriptor is shared
5008 	**  between the processes.  Therefore, it is vital
5009 	**  that the file always be rewound.  This forces the
5010 	**  kernel offset (lseek) and stdio library (ftell)
5011 	**  offset to match.
5012 	*/
5013 
5014 	save_errno = errno;
5015 	if (e->e_dfp != NULL)
5016 		(void) bfrewind(e->e_dfp);
5017 
5018 	/* some mailers want extra blank line at end of message */
5019 	if (!dead && bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
5020 	    buf[0] != '\0' && buf[0] != '\n')
5021 	{
5022 		if (!putline("", mci))
5023 			goto writeerr;
5024 	}
5025 
5026 	if (!dead &&
5027 	    (sm_io_flush(mci->mci_out, SM_TIME_DEFAULT) == SM_IO_EOF ||
5028 	     (sm_io_error(mci->mci_out) && errno != EPIPE)))
5029 	{
5030 		save_errno = errno;
5031 		syserr("putbody: write error");
5032 		ExitStat = EX_IOERR;
5033 		ioerr = true;
5034 	}
5035 
5036 	errno = save_errno;
5037 	return !dead && !ioerr;
5038 
5039   writeerr:
5040 	return false;
5041 }
5042 
5043 /*
5044 **  MAILFILE -- Send a message to a file.
5045 **
5046 **	If the file has the set-user-ID/set-group-ID bits set, but NO
5047 **	execute bits, sendmail will try to become the owner of that file
5048 **	rather than the real user.  Obviously, this only works if
5049 **	sendmail runs as root.
5050 **
5051 **	This could be done as a subordinate mailer, except that it
5052 **	is used implicitly to save messages in ~/dead.letter.  We
5053 **	view this as being sufficiently important as to include it
5054 **	here.  For example, if the system is dying, we shouldn't have
5055 **	to create another process plus some pipes to save the message.
5056 **
5057 **	Parameters:
5058 **		filename -- the name of the file to send to.
5059 **		mailer -- mailer definition for recipient -- if NULL,
5060 **			use FileMailer.
5061 **		ctladdr -- the controlling address header -- includes
5062 **			the userid/groupid to be when sending.
5063 **		sfflags -- flags for opening.
5064 **		e -- the current envelope.
5065 **
5066 **	Returns:
5067 **		The exit code associated with the operation.
5068 **
5069 **	Side Effects:
5070 **		none.
5071 */
5072 
5073 # define RETURN(st)			exit(st);
5074 
5075 static jmp_buf	CtxMailfileTimeout;
5076 
5077 int
5078 mailfile(filename, mailer, ctladdr, sfflags, e)
5079 	char *volatile filename;
5080 	MAILER *volatile mailer;
5081 	ADDRESS *ctladdr;
5082 	volatile long sfflags;
5083 	register ENVELOPE *e;
5084 {
5085 	register SM_FILE_T *f;
5086 	register pid_t pid = -1;
5087 	volatile int mode;
5088 	int len;
5089 	off_t curoff;
5090 	bool suidwarn = geteuid() == 0;
5091 	char *p;
5092 	char *volatile realfile;
5093 	SM_EVENT *ev;
5094 	char buf[MAXPATHLEN];
5095 	char targetfile[MAXPATHLEN];
5096 
5097 	if (tTd(11, 1))
5098 	{
5099 		sm_dprintf("mailfile %s\n  ctladdr=", filename);
5100 		printaddr(sm_debug_file(), ctladdr, false);
5101 	}
5102 
5103 	if (mailer == NULL)
5104 		mailer = FileMailer;
5105 
5106 	if (e->e_xfp != NULL)
5107 		(void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
5108 
5109 	/*
5110 	**  Special case /dev/null.  This allows us to restrict file
5111 	**  delivery to regular files only.
5112 	*/
5113 
5114 	if (sm_path_isdevnull(filename))
5115 		return EX_OK;
5116 
5117 	/* check for 8-bit available */
5118 	if (bitset(EF_HAS8BIT, e->e_flags) &&
5119 	    bitnset(M_7BITS, mailer->m_flags) &&
5120 	    (bitset(EF_DONT_MIME, e->e_flags) ||
5121 	     !(bitset(MM_MIME8BIT, MimeMode) ||
5122 	       (bitset(EF_IS_MIME, e->e_flags) &&
5123 		bitset(MM_CVTMIME, MimeMode)))))
5124 	{
5125 		e->e_status = "5.6.3";
5126 		usrerrenh(e->e_status,
5127 			  "554 Cannot send 8-bit data to 7-bit destination");
5128 		errno = 0;
5129 		return EX_DATAERR;
5130 	}
5131 
5132 	/* Find the actual file */
5133 	if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
5134 	{
5135 		len = strlen(SafeFileEnv);
5136 
5137 		if (strncmp(SafeFileEnv, filename, len) == 0)
5138 			filename += len;
5139 
5140 		if (len + strlen(filename) + 1 >= sizeof targetfile)
5141 		{
5142 			syserr("mailfile: filename too long (%s/%s)",
5143 			       SafeFileEnv, filename);
5144 			return EX_CANTCREAT;
5145 		}
5146 		(void) sm_strlcpy(targetfile, SafeFileEnv, sizeof targetfile);
5147 		realfile = targetfile + len;
5148 		if (*filename == '/')
5149 			filename++;
5150 		if (*filename != '\0')
5151 		{
5152 			/* paranoia: trailing / should be removed in readcf */
5153 			if (targetfile[len - 1] != '/')
5154 				(void) sm_strlcat(targetfile,
5155 						  "/", sizeof targetfile);
5156 			(void) sm_strlcat(targetfile, filename,
5157 					  sizeof targetfile);
5158 		}
5159 	}
5160 	else if (mailer->m_rootdir != NULL)
5161 	{
5162 		expand(mailer->m_rootdir, targetfile, sizeof targetfile, e);
5163 		len = strlen(targetfile);
5164 
5165 		if (strncmp(targetfile, filename, len) == 0)
5166 			filename += len;
5167 
5168 		if (len + strlen(filename) + 1 >= sizeof targetfile)
5169 		{
5170 			syserr("mailfile: filename too long (%s/%s)",
5171 			       targetfile, filename);
5172 			return EX_CANTCREAT;
5173 		}
5174 		realfile = targetfile + len;
5175 		if (targetfile[len - 1] != '/')
5176 			(void) sm_strlcat(targetfile, "/", sizeof targetfile);
5177 		if (*filename == '/')
5178 			(void) sm_strlcat(targetfile, filename + 1,
5179 					  sizeof targetfile);
5180 		else
5181 			(void) sm_strlcat(targetfile, filename,
5182 					  sizeof targetfile);
5183 	}
5184 	else
5185 	{
5186 		if (sm_strlcpy(targetfile, filename, sizeof targetfile) >=
5187 		    sizeof targetfile)
5188 		{
5189 			syserr("mailfile: filename too long (%s)", filename);
5190 			return EX_CANTCREAT;
5191 		}
5192 		realfile = targetfile;
5193 	}
5194 
5195 	/*
5196 	**  Fork so we can change permissions here.
5197 	**	Note that we MUST use fork, not vfork, because of
5198 	**	the complications of calling subroutines, etc.
5199 	*/
5200 
5201 
5202 	/*
5203 	**  Dispose of SIGCHLD signal catchers that may be laying
5204 	**  around so that the waitfor() below will get it.
5205 	*/
5206 
5207 	(void) sm_signal(SIGCHLD, SIG_DFL);
5208 
5209 	DOFORK(fork);
5210 
5211 	if (pid < 0)
5212 		return EX_OSERR;
5213 	else if (pid == 0)
5214 	{
5215 		/* child -- actually write to file */
5216 		struct stat stb;
5217 		MCI mcibuf;
5218 		int err;
5219 		volatile int oflags = O_WRONLY|O_APPEND;
5220 
5221 		/* Reset global flags */
5222 		RestartRequest = NULL;
5223 		RestartWorkGroup = false;
5224 		ShutdownRequest = NULL;
5225 		PendingSignal = 0;
5226 		CurrentPid = getpid();
5227 
5228 		if (e->e_lockfp != NULL)
5229 		{
5230 			int fd;
5231 
5232 			fd = sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL);
5233 			/* SM_ASSERT(fd >= 0); */
5234 			if (fd >= 0)
5235 				(void) close(fd);
5236 		}
5237 
5238 		(void) sm_signal(SIGINT, SIG_DFL);
5239 		(void) sm_signal(SIGHUP, SIG_DFL);
5240 		(void) sm_signal(SIGTERM, SIG_DFL);
5241 		(void) umask(OldUmask);
5242 		e->e_to = filename;
5243 		ExitStat = EX_OK;
5244 
5245 		if (setjmp(CtxMailfileTimeout) != 0)
5246 		{
5247 			RETURN(EX_TEMPFAIL);
5248 		}
5249 
5250 		if (TimeOuts.to_fileopen > 0)
5251 			ev = sm_setevent(TimeOuts.to_fileopen, mailfiletimeout,
5252 					 0);
5253 		else
5254 			ev = NULL;
5255 
5256 		/* check file mode to see if set-user-ID */
5257 		if (stat(targetfile, &stb) < 0)
5258 			mode = FileMode;
5259 		else
5260 			mode = stb.st_mode;
5261 
5262 		/* limit the errors to those actually caused in the child */
5263 		errno = 0;
5264 		ExitStat = EX_OK;
5265 
5266 		/* Allow alias expansions to use the S_IS{U,G}ID bits */
5267 		if ((ctladdr != NULL && !bitset(QALIAS, ctladdr->q_flags)) ||
5268 		    bitset(SFF_RUNASREALUID, sfflags))
5269 		{
5270 			/* ignore set-user-ID and set-group-ID bits */
5271 			mode &= ~(S_ISGID|S_ISUID);
5272 			if (tTd(11, 20))
5273 				sm_dprintf("mailfile: ignoring set-user-ID/set-group-ID bits\n");
5274 		}
5275 
5276 		/* we have to open the data file BEFORE setuid() */
5277 		if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
5278 		{
5279 			char *df = queuename(e, DATAFL_LETTER);
5280 
5281 			e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, df,
5282 					      SM_IO_RDONLY_B, NULL);
5283 			if (e->e_dfp == NULL)
5284 			{
5285 				syserr("mailfile: Cannot open %s for %s from %s",
5286 					df, e->e_to, e->e_from.q_paddr);
5287 			}
5288 		}
5289 
5290 		/* select a new user to run as */
5291 		if (!bitset(SFF_RUNASREALUID, sfflags))
5292 		{
5293 			if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5294 			{
5295 				RealUserName = NULL;
5296 				if (mailer->m_uid == NO_UID)
5297 					RealUid = RunAsUid;
5298 				else
5299 					RealUid = mailer->m_uid;
5300 				if (RunAsUid != 0 && RealUid != RunAsUid)
5301 				{
5302 					/* Only root can change the uid */
5303 					syserr("mailfile: insufficient privileges to change uid, RunAsUid=%d, RealUid=%d",
5304 						(int) RunAsUid, (int) RealUid);
5305 					RETURN(EX_TEMPFAIL);
5306 				}
5307 			}
5308 			else if (bitset(S_ISUID, mode))
5309 			{
5310 				RealUserName = NULL;
5311 				RealUid = stb.st_uid;
5312 			}
5313 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
5314 			{
5315 				if (ctladdr->q_ruser != NULL)
5316 					RealUserName = ctladdr->q_ruser;
5317 				else
5318 					RealUserName = ctladdr->q_user;
5319 				RealUid = ctladdr->q_uid;
5320 			}
5321 			else if (mailer != NULL && mailer->m_uid != NO_UID)
5322 			{
5323 				RealUserName = DefUser;
5324 				RealUid = mailer->m_uid;
5325 			}
5326 			else
5327 			{
5328 				RealUserName = DefUser;
5329 				RealUid = DefUid;
5330 			}
5331 
5332 			/* select a new group to run as */
5333 			if (bitnset(M_SPECIFIC_UID, mailer->m_flags))
5334 			{
5335 				if (mailer->m_gid == NO_GID)
5336 					RealGid = RunAsGid;
5337 				else
5338 					RealGid = mailer->m_gid;
5339 				if (RunAsUid != 0 &&
5340 				    (RealGid != getgid() ||
5341 				     RealGid != getegid()))
5342 				{
5343 					/* Only root can change the gid */
5344 					syserr("mailfile: insufficient privileges to change gid, RealGid=%d, RunAsUid=%d, gid=%d, egid=%d",
5345 					       (int) RealGid, (int) RunAsUid,
5346 					       (int) getgid(), (int) getegid());
5347 					RETURN(EX_TEMPFAIL);
5348 				}
5349 			}
5350 			else if (bitset(S_ISGID, mode))
5351 				RealGid = stb.st_gid;
5352 			else if (ctladdr != NULL &&
5353 				 ctladdr->q_uid == DefUid &&
5354 				 ctladdr->q_gid == 0)
5355 			{
5356 				/*
5357 				**  Special case:  This means it is an
5358 				**  alias and we should act as DefaultUser.
5359 				**  See alias()'s comments.
5360 				*/
5361 
5362 				RealGid = DefGid;
5363 				RealUserName = DefUser;
5364 			}
5365 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
5366 				RealGid = ctladdr->q_gid;
5367 			else if (mailer != NULL && mailer->m_gid != NO_GID)
5368 				RealGid = mailer->m_gid;
5369 			else
5370 				RealGid = DefGid;
5371 		}
5372 
5373 		/* last ditch */
5374 		if (!bitset(SFF_ROOTOK, sfflags))
5375 		{
5376 			if (RealUid == 0)
5377 				RealUid = DefUid;
5378 			if (RealGid == 0)
5379 				RealGid = DefGid;
5380 		}
5381 
5382 		/* set group id list (needs /etc/group access) */
5383 		if (RealUserName != NULL && !DontInitGroups)
5384 		{
5385 			if (initgroups(RealUserName, RealGid) == -1 && suidwarn)
5386 			{
5387 				syserr("mailfile: initgroups(%s, %d) failed",
5388 					RealUserName, RealGid);
5389 				RETURN(EX_TEMPFAIL);
5390 			}
5391 		}
5392 		else
5393 		{
5394 			GIDSET_T gidset[1];
5395 
5396 			gidset[0] = RealGid;
5397 			if (setgroups(1, gidset) == -1 && suidwarn)
5398 			{
5399 				syserr("mailfile: setgroups() failed");
5400 				RETURN(EX_TEMPFAIL);
5401 			}
5402 		}
5403 
5404 		/*
5405 		**  If you have a safe environment, go into it.
5406 		*/
5407 
5408 		if (realfile != targetfile)
5409 		{
5410 			char save;
5411 
5412 			save = *realfile;
5413 			*realfile = '\0';
5414 			if (tTd(11, 20))
5415 				sm_dprintf("mailfile: chroot %s\n", targetfile);
5416 			if (chroot(targetfile) < 0)
5417 			{
5418 				syserr("mailfile: Cannot chroot(%s)",
5419 				       targetfile);
5420 				RETURN(EX_CANTCREAT);
5421 			}
5422 			*realfile = save;
5423 		}
5424 
5425 		if (tTd(11, 40))
5426 			sm_dprintf("mailfile: deliver to %s\n", realfile);
5427 
5428 		if (chdir("/") < 0)
5429 		{
5430 			syserr("mailfile: cannot chdir(/)");
5431 			RETURN(EX_CANTCREAT);
5432 		}
5433 
5434 		/* now reset the group and user ids */
5435 		endpwent();
5436 		sm_mbdb_terminate();
5437 		if (setgid(RealGid) < 0 && suidwarn)
5438 		{
5439 			syserr("mailfile: setgid(%ld) failed", (long) RealGid);
5440 			RETURN(EX_TEMPFAIL);
5441 		}
5442 		vendor_set_uid(RealUid);
5443 		if (setuid(RealUid) < 0 && suidwarn)
5444 		{
5445 			syserr("mailfile: setuid(%ld) failed", (long) RealUid);
5446 			RETURN(EX_TEMPFAIL);
5447 		}
5448 
5449 		if (tTd(11, 2))
5450 			sm_dprintf("mailfile: running as r/euid=%d/%d, r/egid=%d/%d\n",
5451 				(int) getuid(), (int) geteuid(),
5452 				(int) getgid(), (int) getegid());
5453 
5454 
5455 		/* move into some "safe" directory */
5456 		if (mailer->m_execdir != NULL)
5457 		{
5458 			char *q;
5459 
5460 			for (p = mailer->m_execdir; p != NULL; p = q)
5461 			{
5462 				q = strchr(p, ':');
5463 				if (q != NULL)
5464 					*q = '\0';
5465 				expand(p, buf, sizeof buf, e);
5466 				if (q != NULL)
5467 					*q++ = ':';
5468 				if (tTd(11, 20))
5469 					sm_dprintf("mailfile: trydir %s\n",
5470 						   buf);
5471 				if (buf[0] != '\0' && chdir(buf) >= 0)
5472 					break;
5473 			}
5474 		}
5475 
5476 		/*
5477 		**  Recheck the file after we have assumed the ID of the
5478 		**  delivery user to make sure we can deliver to it as
5479 		**  that user.  This is necessary if sendmail is running
5480 		**  as root and the file is on an NFS mount which treats
5481 		**  root as nobody.
5482 		*/
5483 
5484 #if HASLSTAT
5485 		if (bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5486 			err = stat(realfile, &stb);
5487 		else
5488 			err = lstat(realfile, &stb);
5489 #else /* HASLSTAT */
5490 		err = stat(realfile, &stb);
5491 #endif /* HASLSTAT */
5492 
5493 		if (err < 0)
5494 		{
5495 			stb.st_mode = ST_MODE_NOFILE;
5496 			mode = FileMode;
5497 			oflags |= O_CREAT|O_EXCL;
5498 		}
5499 		else if (bitset(S_IXUSR|S_IXGRP|S_IXOTH, mode) ||
5500 			 (!bitnset(DBS_FILEDELIVERYTOHARDLINK,
5501 				   DontBlameSendmail) &&
5502 			  stb.st_nlink != 1) ||
5503 			 (realfile != targetfile && !S_ISREG(mode)))
5504 			exit(EX_CANTCREAT);
5505 		else
5506 			mode = stb.st_mode;
5507 
5508 		if (!bitnset(DBS_FILEDELIVERYTOSYMLINK, DontBlameSendmail))
5509 			sfflags |= SFF_NOSLINK;
5510 		if (!bitnset(DBS_FILEDELIVERYTOHARDLINK, DontBlameSendmail))
5511 			sfflags |= SFF_NOHLINK;
5512 		sfflags &= ~SFF_OPENASROOT;
5513 		f = safefopen(realfile, oflags, mode, sfflags);
5514 		if (f == NULL)
5515 		{
5516 			if (transienterror(errno))
5517 			{
5518 				usrerr("454 4.3.0 cannot open %s: %s",
5519 				       shortenstring(realfile, MAXSHORTSTR),
5520 				       sm_errstring(errno));
5521 				RETURN(EX_TEMPFAIL);
5522 			}
5523 			else
5524 			{
5525 				usrerr("554 5.3.0 cannot open %s: %s",
5526 				       shortenstring(realfile, MAXSHORTSTR),
5527 				       sm_errstring(errno));
5528 				RETURN(EX_CANTCREAT);
5529 			}
5530 		}
5531 		if (filechanged(realfile, sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5532 		    &stb))
5533 		{
5534 			syserr("554 5.3.0 file changed after open");
5535 			RETURN(EX_CANTCREAT);
5536 		}
5537 		if (fstat(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL), &stb) < 0)
5538 		{
5539 			syserr("554 5.3.0 cannot fstat %s",
5540 				sm_errstring(errno));
5541 			RETURN(EX_CANTCREAT);
5542 		}
5543 
5544 		curoff = stb.st_size;
5545 
5546 		if (ev != NULL)
5547 			sm_clrevent(ev);
5548 
5549 		memset(&mcibuf, '\0', sizeof mcibuf);
5550 		mcibuf.mci_mailer = mailer;
5551 		mcibuf.mci_out = f;
5552 		if (bitnset(M_7BITS, mailer->m_flags))
5553 			mcibuf.mci_flags |= MCIF_7BIT;
5554 
5555 		/* clear out per-message flags from connection structure */
5556 		mcibuf.mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);
5557 
5558 		if (bitset(EF_HAS8BIT, e->e_flags) &&
5559 		    !bitset(EF_DONT_MIME, e->e_flags) &&
5560 		    bitnset(M_7BITS, mailer->m_flags))
5561 			mcibuf.mci_flags |= MCIF_CVT8TO7;
5562 
5563 #if MIME7TO8
5564 		if (bitnset(M_MAKE8BIT, mailer->m_flags) &&
5565 		    !bitset(MCIF_7BIT, mcibuf.mci_flags) &&
5566 		    (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
5567 		    (sm_strcasecmp(p, "quoted-printable") == 0 ||
5568 		     sm_strcasecmp(p, "base64") == 0) &&
5569 		    (p = hvalue("Content-Type", e->e_header)) != NULL)
5570 		{
5571 			/* may want to convert 7 -> 8 */
5572 			/* XXX should really parse it here -- and use a class XXX */
5573 			if (sm_strncasecmp(p, "text/plain", 10) == 0 &&
5574 			    (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
5575 				mcibuf.mci_flags |= MCIF_CVT7TO8;
5576 		}
5577 #endif /* MIME7TO8 */
5578 
5579 		if (!putfromline(&mcibuf, e) ||
5580 		    !(*e->e_puthdr)(&mcibuf, e->e_header, e, M87F_OUTER) ||
5581 		    !(*e->e_putbody)(&mcibuf, e, NULL) ||
5582 		    !putline("\n", &mcibuf) ||
5583 		    (sm_io_flush(f, SM_TIME_DEFAULT) != 0 ||
5584 		    (SuperSafe != SAFE_NO &&
5585 		     fsync(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL)) < 0) ||
5586 		    sm_io_error(f)))
5587 		{
5588 			setstat(EX_IOERR);
5589 #if !NOFTRUNCATE
5590 			(void) ftruncate(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5591 					 curoff);
5592 #endif /* !NOFTRUNCATE */
5593 		}
5594 
5595 		/* reset ISUID & ISGID bits for paranoid systems */
5596 #if HASFCHMOD
5597 		(void) fchmod(sm_io_getinfo(f, SM_IO_WHAT_FD, NULL),
5598 			      (MODE_T) mode);
5599 #else /* HASFCHMOD */
5600 		(void) chmod(filename, (MODE_T) mode);
5601 #endif /* HASFCHMOD */
5602 		if (sm_io_close(f, SM_TIME_DEFAULT) < 0)
5603 			setstat(EX_IOERR);
5604 		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
5605 		(void) setuid(RealUid);
5606 		exit(ExitStat);
5607 		/* NOTREACHED */
5608 	}
5609 	else
5610 	{
5611 		/* parent -- wait for exit status */
5612 		int st;
5613 
5614 		st = waitfor(pid);
5615 		if (st == -1)
5616 		{
5617 			syserr("mailfile: %s: wait", mailer->m_name);
5618 			return EX_SOFTWARE;
5619 		}
5620 		if (WIFEXITED(st))
5621 		{
5622 			errno = 0;
5623 			return (WEXITSTATUS(st));
5624 		}
5625 		else
5626 		{
5627 			syserr("mailfile: %s: child died on signal %d",
5628 			       mailer->m_name, st);
5629 			return EX_UNAVAILABLE;
5630 		}
5631 		/* NOTREACHED */
5632 	}
5633 	return EX_UNAVAILABLE;	/* avoid compiler warning on IRIX */
5634 }
5635 
5636 static void
5637 mailfiletimeout(ignore)
5638 	int ignore;
5639 {
5640 	/*
5641 	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
5642 	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
5643 	**	DOING.
5644 	*/
5645 
5646 	errno = ETIMEDOUT;
5647 	longjmp(CtxMailfileTimeout, 1);
5648 }
5649 /*
5650 **  HOSTSIGNATURE -- return the "signature" for a host.
5651 **
5652 **	The signature describes how we are going to send this -- it
5653 **	can be just the hostname (for non-Internet hosts) or can be
5654 **	an ordered list of MX hosts.
5655 **
5656 **	Parameters:
5657 **		m -- the mailer describing this host.
5658 **		host -- the host name.
5659 **
5660 **	Returns:
5661 **		The signature for this host.
5662 **
5663 **	Side Effects:
5664 **		Can tweak the symbol table.
5665 */
5666 
5667 #define MAXHOSTSIGNATURE	8192	/* max len of hostsignature */
5668 
5669 char *
5670 hostsignature(m, host)
5671 	register MAILER *m;
5672 	char *host;
5673 {
5674 	register char *p;
5675 	register STAB *s;
5676 	time_t now;
5677 #if NAMED_BIND
5678 	char sep = ':';
5679 	char prevsep = ':';
5680 	int i;
5681 	int len;
5682 	int nmx;
5683 	int hl;
5684 	char *hp;
5685 	char *endp;
5686 	int oldoptions = _res.options;
5687 	char *mxhosts[MAXMXHOSTS + 1];
5688 	unsigned short mxprefs[MAXMXHOSTS + 1];
5689 #endif /* NAMED_BIND */
5690 
5691 	if (tTd(17, 3))
5692 		sm_dprintf("hostsignature(%s)\n", host);
5693 
5694 	/*
5695 	**  If local delivery (and not remote), just return a constant.
5696 	*/
5697 
5698 	if (bitnset(M_LOCALMAILER, m->m_flags) &&
5699 	    strcmp(m->m_mailer, "[IPC]") != 0 &&
5700 	    !(m->m_argv[0] != NULL && strcmp(m->m_argv[0], "TCP") == 0))
5701 		return "localhost";
5702 
5703 	/* an empty host does not have MX records */
5704 	if (*host == '\0')
5705 		return "_empty_";
5706 
5707 	/*
5708 	**  Check to see if this uses IPC -- if not, it can't have MX records.
5709 	*/
5710 
5711 	if (strcmp(m->m_mailer, "[IPC]") != 0 ||
5712 	    CurEnv->e_sendmode == SM_DEFER)
5713 	{
5714 		/* just an ordinary mailer or deferred mode */
5715 		return host;
5716 	}
5717 #if NETUNIX
5718 	else if (m->m_argv[0] != NULL &&
5719 		 strcmp(m->m_argv[0], "FILE") == 0)
5720 	{
5721 		/* rendezvous in the file system, no MX records */
5722 		return host;
5723 	}
5724 #endif /* NETUNIX */
5725 
5726 	/*
5727 	**  Look it up in the symbol table.
5728 	*/
5729 
5730 	now = curtime();
5731 	s = stab(host, ST_HOSTSIG, ST_ENTER);
5732 	if (s->s_hostsig.hs_sig != NULL)
5733 	{
5734 		if (s->s_hostsig.hs_exp >= now)
5735 		{
5736 			if (tTd(17, 3))
5737 				sm_dprintf("hostsignature(): stab(%s) found %s\n", host,
5738 					   s->s_hostsig.hs_sig);
5739 			return s->s_hostsig.hs_sig;
5740 		}
5741 
5742 		/* signature is expired: clear it */
5743 		sm_free(s->s_hostsig.hs_sig);
5744 		s->s_hostsig.hs_sig = NULL;
5745 	}
5746 
5747 	/* set default TTL */
5748 	s->s_hostsig.hs_exp = now + SM_DEFAULT_TTL;
5749 
5750 	/*
5751 	**  Not already there or expired -- create a signature.
5752 	*/
5753 
5754 #if NAMED_BIND
5755 	if (ConfigLevel < 2)
5756 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
5757 
5758 	for (hp = host; hp != NULL; hp = endp)
5759 	{
5760 #if NETINET6
5761 		if (*hp == '[')
5762 		{
5763 			endp = strchr(hp + 1, ']');
5764 			if (endp != NULL)
5765 				endp = strpbrk(endp + 1, ":,");
5766 		}
5767 		else
5768 			endp = strpbrk(hp, ":,");
5769 #else /* NETINET6 */
5770 		endp = strpbrk(hp, ":,");
5771 #endif /* NETINET6 */
5772 		if (endp != NULL)
5773 		{
5774 			sep = *endp;
5775 			*endp = '\0';
5776 		}
5777 
5778 		if (bitnset(M_NOMX, m->m_flags))
5779 		{
5780 			/* skip MX lookups */
5781 			nmx = 1;
5782 			mxhosts[0] = hp;
5783 		}
5784 		else
5785 		{
5786 			auto int rcode;
5787 			int ttl;
5788 
5789 			nmx = getmxrr(hp, mxhosts, mxprefs, true, &rcode, true,
5790 				      &ttl);
5791 			if (nmx <= 0)
5792 			{
5793 				int save_errno;
5794 				register MCI *mci;
5795 
5796 				/* update the connection info for this host */
5797 				save_errno = errno;
5798 				mci = mci_get(hp, m);
5799 				mci->mci_errno = save_errno;
5800 				mci->mci_herrno = h_errno;
5801 				mci->mci_lastuse = now;
5802 				if (rcode == EX_NOHOST)
5803 					mci_setstat(mci, rcode, "5.1.2",
5804 						    "550 Host unknown");
5805 				else
5806 					mci_setstat(mci, rcode, NULL, NULL);
5807 
5808 				/* use the original host name as signature */
5809 				nmx = 1;
5810 				mxhosts[0] = hp;
5811 			}
5812 			if (tTd(17, 3))
5813 				sm_dprintf("hostsignature(): getmxrr() returned %d, mxhosts[0]=%s\n",
5814 					   nmx, mxhosts[0]);
5815 
5816 			/*
5817 			**  Set new TTL: we use only one!
5818 			**	We could try to use the minimum instead.
5819 			*/
5820 
5821 			s->s_hostsig.hs_exp = now + SM_MIN(ttl, SM_DEFAULT_TTL);
5822 		}
5823 
5824 		len = 0;
5825 		for (i = 0; i < nmx; i++)
5826 			len += strlen(mxhosts[i]) + 1;
5827 		if (s->s_hostsig.hs_sig != NULL)
5828 			len += strlen(s->s_hostsig.hs_sig) + 1;
5829 		if (len < 0 || len >= MAXHOSTSIGNATURE)
5830 		{
5831 			sm_syslog(LOG_WARNING, NOQID, "hostsignature for host '%s' exceeds maxlen (%d): %d",
5832 				  host, MAXHOSTSIGNATURE, len);
5833 			len = MAXHOSTSIGNATURE;
5834 		}
5835 		p = sm_pmalloc_x(len);
5836 		if (s->s_hostsig.hs_sig != NULL)
5837 		{
5838 			(void) sm_strlcpy(p, s->s_hostsig.hs_sig, len);
5839 			sm_free(s->s_hostsig.hs_sig); /* XXX */
5840 			s->s_hostsig.hs_sig = p;
5841 			hl = strlen(p);
5842 			p += hl;
5843 			*p++ = prevsep;
5844 			len -= hl + 1;
5845 		}
5846 		else
5847 			s->s_hostsig.hs_sig = p;
5848 		for (i = 0; i < nmx; i++)
5849 		{
5850 			hl = strlen(mxhosts[i]);
5851 			if (len - 1 < hl || len <= 1)
5852 			{
5853 				/* force to drop out of outer loop */
5854 				len = -1;
5855 				break;
5856 			}
5857 			if (i != 0)
5858 			{
5859 				if (mxprefs[i] == mxprefs[i - 1])
5860 					*p++ = ',';
5861 				else
5862 					*p++ = ':';
5863 				len--;
5864 			}
5865 			(void) sm_strlcpy(p, mxhosts[i], len);
5866 			p += hl;
5867 			len -= hl;
5868 		}
5869 
5870 		/*
5871 		**  break out of loop if len exceeded MAXHOSTSIGNATURE
5872 		**  because we won't have more space for further hosts
5873 		**  anyway (separated by : in the .cf file).
5874 		*/
5875 
5876 		if (len < 0)
5877 			break;
5878 		if (endp != NULL)
5879 			*endp++ = sep;
5880 		prevsep = sep;
5881 	}
5882 	makelower(s->s_hostsig.hs_sig);
5883 	if (ConfigLevel < 2)
5884 		_res.options = oldoptions;
5885 #else /* NAMED_BIND */
5886 	/* not using BIND -- the signature is just the host name */
5887 	/*
5888 	**  'host' points to storage that will be freed after we are
5889 	**  done processing the current envelope, so we copy it.
5890 	*/
5891 	s->s_hostsig.hs_sig = sm_pstrdup_x(host);
5892 #endif /* NAMED_BIND */
5893 	if (tTd(17, 1))
5894 		sm_dprintf("hostsignature(%s) = %s\n", host, s->s_hostsig.hs_sig);
5895 	return s->s_hostsig.hs_sig;
5896 }
5897 /*
5898 **  PARSE_HOSTSIGNATURE -- parse the "signature" and return MX host array.
5899 **
5900 **	The signature describes how we are going to send this -- it
5901 **	can be just the hostname (for non-Internet hosts) or can be
5902 **	an ordered list of MX hosts which must be randomized for equal
5903 **	MX preference values.
5904 **
5905 **	Parameters:
5906 **		sig -- the host signature.
5907 **		mxhosts -- array to populate.
5908 **		mailer -- mailer.
5909 **
5910 **	Returns:
5911 **		The number of hosts inserted into mxhosts array.
5912 **
5913 **	Side Effects:
5914 **		Randomizes equal MX preference hosts in mxhosts.
5915 */
5916 
5917 static int
5918 parse_hostsignature(sig, mxhosts, mailer)
5919 	char *sig;
5920 	char **mxhosts;
5921 	MAILER *mailer;
5922 {
5923 	unsigned short curpref = 0;
5924 	int nmx = 0, i, j;	/* NOTE: i, j, and nmx must have same type */
5925 	char *hp, *endp;
5926 	unsigned short prefer[MAXMXHOSTS];
5927 	long rndm[MAXMXHOSTS];
5928 
5929 	for (hp = sig; hp != NULL; hp = endp)
5930 	{
5931 		char sep = ':';
5932 
5933 #if NETINET6
5934 		if (*hp == '[')
5935 		{
5936 			endp = strchr(hp + 1, ']');
5937 			if (endp != NULL)
5938 				endp = strpbrk(endp + 1, ":,");
5939 		}
5940 		else
5941 			endp = strpbrk(hp, ":,");
5942 #else /* NETINET6 */
5943 		endp = strpbrk(hp, ":,");
5944 #endif /* NETINET6 */
5945 		if (endp != NULL)
5946 		{
5947 			sep = *endp;
5948 			*endp = '\0';
5949 		}
5950 
5951 		mxhosts[nmx] = hp;
5952 		prefer[nmx] = curpref;
5953 		if (mci_match(hp, mailer))
5954 			rndm[nmx] = 0;
5955 		else
5956 			rndm[nmx] = get_random();
5957 
5958 		if (endp != NULL)
5959 		{
5960 			/*
5961 			**  Since we don't have the original MX prefs,
5962 			**  make our own.  If the separator is a ':', that
5963 			**  means the preference for the next host will be
5964 			**  higher than this one, so simply increment curpref.
5965 			*/
5966 
5967 			if (sep == ':')
5968 				curpref++;
5969 
5970 			*endp++ = sep;
5971 		}
5972 		if (++nmx >= MAXMXHOSTS)
5973 			break;
5974 	}
5975 
5976 	/* sort the records using the random factor for equal preferences */
5977 	for (i = 0; i < nmx; i++)
5978 	{
5979 		for (j = i + 1; j < nmx; j++)
5980 		{
5981 			/*
5982 			**  List is already sorted by MX preference, only
5983 			**  need to look for equal preference MX records
5984 			*/
5985 
5986 			if (prefer[i] < prefer[j])
5987 				break;
5988 
5989 			if (prefer[i] > prefer[j] ||
5990 			    (prefer[i] == prefer[j] && rndm[i] > rndm[j]))
5991 			{
5992 				register unsigned short tempp;
5993 				register long tempr;
5994 				register char *temp1;
5995 
5996 				tempp = prefer[i];
5997 				prefer[i] = prefer[j];
5998 				prefer[j] = tempp;
5999 				temp1 = mxhosts[i];
6000 				mxhosts[i] = mxhosts[j];
6001 				mxhosts[j] = temp1;
6002 				tempr = rndm[i];
6003 				rndm[i] = rndm[j];
6004 				rndm[j] = tempr;
6005 			}
6006 		}
6007 	}
6008 	return nmx;
6009 }
6010 
6011 # if STARTTLS
6012 static SSL_CTX	*clt_ctx = NULL;
6013 static bool	tls_ok_clt = true;
6014 
6015 /*
6016 **  SETCLTTLS -- client side TLS: allow/disallow.
6017 **
6018 **	Parameters:
6019 **		tls_ok -- should tls be done?
6020 **
6021 **	Returns:
6022 **		none.
6023 **
6024 **	Side Effects:
6025 **		sets tls_ok_clt (static variable in this module)
6026 */
6027 
6028 void
6029 setclttls(tls_ok)
6030 	bool tls_ok;
6031 {
6032 	tls_ok_clt = tls_ok;
6033 	return;
6034 }
6035 /*
6036 **  INITCLTTLS -- initialize client side TLS
6037 **
6038 **	Parameters:
6039 **		tls_ok -- should tls initialization be done?
6040 **
6041 **	Returns:
6042 **		succeeded?
6043 **
6044 **	Side Effects:
6045 **		sets tls_ok_clt (static variable in this module)
6046 */
6047 
6048 bool
6049 initclttls(tls_ok)
6050 	bool tls_ok;
6051 {
6052 	if (!tls_ok_clt)
6053 		return false;
6054 	tls_ok_clt = tls_ok;
6055 	if (!tls_ok_clt)
6056 		return false;
6057 	if (clt_ctx != NULL)
6058 		return true;	/* already done */
6059 	tls_ok_clt = inittls(&clt_ctx, TLS_I_CLT, false, CltCertFile,
6060 			     CltKeyFile, CACertPath, CACertFile, DHParams);
6061 	return tls_ok_clt;
6062 }
6063 
6064 /*
6065 **  STARTTLS -- try to start secure connection (client side)
6066 **
6067 **	Parameters:
6068 **		m -- the mailer.
6069 **		mci -- the mailer connection info.
6070 **		e -- the envelope.
6071 **
6072 **	Returns:
6073 **		success?
6074 **		(maybe this should be some other code than EX_
6075 **		that denotes which stage failed.)
6076 */
6077 
6078 static int
6079 starttls(m, mci, e)
6080 	MAILER *m;
6081 	MCI *mci;
6082 	ENVELOPE *e;
6083 {
6084 	int smtpresult;
6085 	int result = 0;
6086 	int rfd, wfd;
6087 	SSL *clt_ssl = NULL;
6088 	time_t tlsstart;
6089 
6090 	if (clt_ctx == NULL && !initclttls(true))
6091 		return EX_TEMPFAIL;
6092 	smtpmessage("STARTTLS", m, mci);
6093 
6094 	/* get the reply */
6095 	smtpresult = reply(m, mci, e, TimeOuts.to_starttls, NULL, NULL,
6096 			XS_STARTTLS);
6097 
6098 	/* check return code from server */
6099 	if (REPLYTYPE(smtpresult) == 4)
6100 		return EX_TEMPFAIL;
6101 	if (smtpresult == 501)
6102 		return EX_USAGE;
6103 	if (smtpresult == -1)
6104 		return smtpresult;
6105 
6106 	/* not an expected reply but we have to deal with it */
6107 	if (REPLYTYPE(smtpresult) == 5)
6108 		return EX_UNAVAILABLE;
6109 	if (smtpresult != 220)
6110 		return EX_PROTOCOL;
6111 
6112 	if (LogLevel > 13)
6113 		sm_syslog(LOG_INFO, NOQID, "STARTTLS=client, start=ok");
6114 
6115 	/* start connection */
6116 	if ((clt_ssl = SSL_new(clt_ctx)) == NULL)
6117 	{
6118 		if (LogLevel > 5)
6119 		{
6120 			sm_syslog(LOG_ERR, NOQID,
6121 				  "STARTTLS=client, error: SSL_new failed");
6122 			if (LogLevel > 9)
6123 				tlslogerr("client");
6124 		}
6125 		return EX_SOFTWARE;
6126 	}
6127 
6128 	rfd = sm_io_getinfo(mci->mci_in, SM_IO_WHAT_FD, NULL);
6129 	wfd = sm_io_getinfo(mci->mci_out, SM_IO_WHAT_FD, NULL);
6130 
6131 	/* SSL_clear(clt_ssl); ? */
6132 	if (rfd < 0 || wfd < 0 ||
6133 	    (result = SSL_set_rfd(clt_ssl, rfd)) != 1 ||
6134 	    (result = SSL_set_wfd(clt_ssl, wfd)) != 1)
6135 	{
6136 		if (LogLevel > 5)
6137 		{
6138 			sm_syslog(LOG_ERR, NOQID,
6139 				  "STARTTLS=client, error: SSL_set_xfd failed=%d",
6140 				  result);
6141 			if (LogLevel > 9)
6142 				tlslogerr("client");
6143 		}
6144 		return EX_SOFTWARE;
6145 	}
6146 	SSL_set_connect_state(clt_ssl);
6147 	tlsstart = curtime();
6148 
6149 ssl_retry:
6150 	if ((result = SSL_connect(clt_ssl)) <= 0)
6151 	{
6152 		int i, ssl_err;
6153 
6154 		ssl_err = SSL_get_error(clt_ssl, result);
6155 		i = tls_retry(clt_ssl, rfd, wfd, tlsstart,
6156 			TimeOuts.to_starttls, ssl_err, "client");
6157 		if (i > 0)
6158 			goto ssl_retry;
6159 
6160 		if (LogLevel > 5)
6161 		{
6162 			sm_syslog(LOG_WARNING, NOQID,
6163 				  "STARTTLS=client, error: connect failed=%d, SSL_error=%d, errno=%d, retry=%d",
6164 				  result, ssl_err, errno, i);
6165 			if (LogLevel > 8)
6166 				tlslogerr("client");
6167 		}
6168 
6169 		SSL_free(clt_ssl);
6170 		clt_ssl = NULL;
6171 		return EX_SOFTWARE;
6172 	}
6173 	mci->mci_ssl = clt_ssl;
6174 	result = tls_get_info(mci->mci_ssl, false, mci->mci_host,
6175 			      &mci->mci_macro, true);
6176 
6177 	/* switch to use TLS... */
6178 	if (sfdctls(&mci->mci_in, &mci->mci_out, mci->mci_ssl) == 0)
6179 		return EX_OK;
6180 
6181 	/* failure */
6182 	SSL_free(clt_ssl);
6183 	clt_ssl = NULL;
6184 	return EX_SOFTWARE;
6185 }
6186 /*
6187 **  ENDTLSCLT -- shutdown secure connection (client side)
6188 **
6189 **	Parameters:
6190 **		mci -- the mailer connection info.
6191 **
6192 **	Returns:
6193 **		success?
6194 */
6195 
6196 static int
6197 endtlsclt(mci)
6198 	MCI *mci;
6199 {
6200 	int r;
6201 
6202 	if (!bitset(MCIF_TLSACT, mci->mci_flags))
6203 		return EX_OK;
6204 	r = endtls(mci->mci_ssl, "client");
6205 	mci->mci_flags &= ~MCIF_TLSACT;
6206 	return r;
6207 }
6208 # endif /* STARTTLS */
6209 # if STARTTLS || SASL
6210 /*
6211 **  ISCLTFLGSET -- check whether client flag is set.
6212 **
6213 **	Parameters:
6214 **		e -- envelope.
6215 **		flag -- flag to check in {client_flags}
6216 **
6217 **	Returns:
6218 **		true iff flag is set.
6219 */
6220 
6221 static bool
6222 iscltflgset(e, flag)
6223 	ENVELOPE *e;
6224 	int flag;
6225 {
6226 	char *p;
6227 
6228 	p = macvalue(macid("{client_flags}"), e);
6229 	if (p == NULL)
6230 		return false;
6231 	for (; *p != '\0'; p++)
6232 	{
6233 		/* look for just this one flag */
6234 		if (*p == (char) flag)
6235 			return true;
6236 	}
6237 	return false;
6238 }
6239 # endif /* STARTTLS || SASL */
6240