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