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