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