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