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