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