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