1 /*
2  * Copyright (c) 1983, 1995 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)deliver.c	8.160 (Berkeley) 06/21/95";
11 #endif /* not lint */
12 
13 #include "sendmail.h"
14 #include <errno.h>
15 #if NAMED_BIND
16 #include <resolv.h>
17 
18 extern int	h_errno;
19 #endif
20 
21 extern char	SmtpError[];
22 
23 /*
24 **  SENDALL -- actually send all the messages.
25 **
26 **	Parameters:
27 **		e -- the envelope to send.
28 **		mode -- the delivery mode to use.  If SM_DEFAULT, use
29 **			the current e->e_sendmode.
30 **
31 **	Returns:
32 **		none.
33 **
34 **	Side Effects:
35 **		Scans the send lists and sends everything it finds.
36 **		Delivers any appropriate error messages.
37 **		If we are running in a non-interactive mode, takes the
38 **			appropriate action.
39 */
40 
41 void
sendall(e,mode)42 sendall(e, mode)
43 	ENVELOPE *e;
44 	char mode;
45 {
46 	register ADDRESS *q;
47 	char *owner;
48 	int otherowners;
49 	register ENVELOPE *ee;
50 	ENVELOPE *splitenv = NULL;
51 	bool oldverbose = Verbose;
52 	bool somedeliveries = FALSE;
53 	int pid;
54 	extern void sendenvelope();
55 
56 	/*
57 	**  If we have had global, fatal errors, don't bother sending
58 	**  the message at all if we are in SMTP mode.  Local errors
59 	**  (e.g., a single address failing) will still cause the other
60 	**  addresses to be sent.
61 	*/
62 
63 	if (bitset(EF_FATALERRS, e->e_flags) &&
64 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
65 	{
66 		e->e_flags |= EF_CLRQUEUE;
67 		return;
68 	}
69 
70 	/* determine actual delivery mode */
71 	CurrentLA = getla();
72 	if (mode == SM_DEFAULT)
73 	{
74 		mode = e->e_sendmode;
75 		if (mode != SM_VERIFY &&
76 		    shouldqueue(e->e_msgpriority, e->e_ctime))
77 			mode = SM_QUEUE;
78 	}
79 
80 	if (tTd(13, 1))
81 	{
82 		extern void printenvflags();
83 
84 		printf("\n===== SENDALL: mode %c, id %s, e_from ",
85 			mode, e->e_id);
86 		printaddr(&e->e_from, FALSE);
87 		printf("\te_flags = ");
88 		printenvflags(e);
89 		printf("sendqueue:\n");
90 		printaddr(e->e_sendqueue, TRUE);
91 	}
92 
93 	/*
94 	**  Do any preprocessing necessary for the mode we are running.
95 	**	Check to make sure the hop count is reasonable.
96 	**	Delete sends to the sender in mailing lists.
97 	*/
98 
99 	CurEnv = e;
100 
101 	if (e->e_hopcount > MaxHopCount)
102 	{
103 		errno = 0;
104 		queueup(e, TRUE, mode == SM_QUEUE);
105 		e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
106 		syserr("554 Too many hops %d (%d max): from %s via %s, to %s",
107 			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
108 			RealHostName == NULL ? "localhost" : RealHostName,
109 			e->e_sendqueue->q_paddr);
110 		e->e_sendqueue->q_status = "5.4.6";
111 		return;
112 	}
113 
114 	/*
115 	**  Do sender deletion.
116 	**
117 	**	If the sender has the QQUEUEUP flag set, skip this.
118 	**	This can happen if the name server is hosed when you
119 	**	are trying to send mail.  The result is that the sender
120 	**	is instantiated in the queue as a recipient.
121 	*/
122 
123 	if (!bitset(EF_METOO, e->e_flags) &&
124 	    !bitset(QQUEUEUP, e->e_from.q_flags))
125 	{
126 		if (tTd(13, 5))
127 		{
128 			printf("sendall: QDONTSEND ");
129 			printaddr(&e->e_from, FALSE);
130 		}
131 		e->e_from.q_flags |= QDONTSEND;
132 		(void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
133 	}
134 
135 	/*
136 	**  Handle alias owners.
137 	**
138 	**	We scan up the q_alias chain looking for owners.
139 	**	We discard owners that are the same as the return path.
140 	*/
141 
142 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
143 	{
144 		register struct address *a;
145 
146 		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
147 			continue;
148 		if (a != NULL)
149 			q->q_owner = a->q_owner;
150 
151 		if (q->q_owner != NULL &&
152 		    !bitset(QDONTSEND, q->q_flags) &&
153 		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
154 			q->q_owner = NULL;
155 	}
156 
157 	owner = "";
158 	otherowners = 1;
159 	while (owner != NULL && otherowners > 0)
160 	{
161 		owner = NULL;
162 		otherowners = 0;
163 
164 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
165 		{
166 			if (bitset(QDONTSEND, q->q_flags))
167 				continue;
168 
169 			if (q->q_owner != NULL)
170 			{
171 				if (owner == NULL)
172 					owner = q->q_owner;
173 				else if (owner != q->q_owner)
174 				{
175 					if (strcmp(owner, q->q_owner) == 0)
176 					{
177 						/* make future comparisons cheap */
178 						q->q_owner = owner;
179 					}
180 					else
181 					{
182 						otherowners++;
183 					}
184 					owner = q->q_owner;
185 				}
186 			}
187 			else
188 			{
189 				otherowners++;
190 			}
191 
192 			/*
193 			**  If this mailer is expensive, and if we don't
194 			**  want to make connections now, just mark these
195 			**  addresses and return.  This is useful if we
196 			**  want to batch connections to reduce load.  This
197 			**  will cause the messages to be queued up, and a
198 			**  daemon will come along to send the messages later.
199 			*/
200 
201 			if (bitset(QBADADDR|QQUEUEUP, q->q_flags))
202 				continue;
203 			if (NoConnect && !Verbose &&
204 			    bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
205 			{
206 				q->q_flags |= QQUEUEUP;
207 				e->e_to = q->q_paddr;
208 				message("queued");
209 				if (LogLevel > 8)
210 					logdelivery(q->q_mailer, NULL,
211 						    "queued", NULL,
212 						    (time_t) 0, e);
213 				e->e_to = NULL;
214 			}
215 			else
216 			{
217 				somedeliveries = TRUE;
218 			}
219 		}
220 
221 		if (owner != NULL && otherowners > 0)
222 		{
223 			extern HDR *copyheader();
224 			extern ADDRESS *copyqueue();
225 
226 			/*
227 			**  Split this envelope into two.
228 			*/
229 
230 			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
231 			*ee = *e;
232 			ee->e_id = NULL;
233 			(void) queuename(ee, '\0');
234 
235 			if (tTd(13, 1))
236 				printf("sendall: split %s into %s\n",
237 					e->e_id, ee->e_id);
238 
239 			ee->e_header = copyheader(e->e_header);
240 			ee->e_sendqueue = copyqueue(e->e_sendqueue);
241 			ee->e_errorqueue = copyqueue(e->e_errorqueue);
242 			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
243 			ee->e_flags |= EF_NORECEIPT;
244 			setsender(owner, ee, NULL, TRUE);
245 			if (tTd(13, 5))
246 			{
247 				printf("sendall(split): QDONTSEND ");
248 				printaddr(&ee->e_from, FALSE);
249 			}
250 			ee->e_from.q_flags |= QDONTSEND;
251 			ee->e_dfp = NULL;
252 			ee->e_xfp = NULL;
253 			ee->e_errormode = EM_MAIL;
254 			ee->e_sibling = splitenv;
255 			splitenv = ee;
256 
257 			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
258 			{
259 				if (q->q_owner == owner)
260 				{
261 					q->q_flags |= QDONTSEND;
262 					q->q_flags &= ~QQUEUEUP;
263 				}
264 			}
265 			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
266 			{
267 				if (q->q_owner != owner)
268 				{
269 					q->q_flags |= QDONTSEND;
270 					q->q_flags &= ~QQUEUEUP;
271 				}
272 				else
273 				{
274 					/* clear DSN parameters */
275 					q->q_flags &= ~(QHASNOTIFY|QPINGONSUCCESS);
276 					q->q_flags |= QPINGONFAILURE|QPINGONDELAY;
277 				}
278 			}
279 
280 			if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
281 			{
282 				char df1buf[20], df2buf[20];
283 
284 				ee->e_dfp = NULL;
285 				strcpy(df1buf, queuename(e, 'd'));
286 				strcpy(df2buf, queuename(ee, 'd'));
287 				if (link(df1buf, df2buf) < 0)
288 				{
289 					syserr("sendall: link(%s, %s)",
290 						df1buf, df2buf);
291 				}
292 			}
293 #ifdef LOG
294 			if (LogLevel > 4)
295 				syslog(LOG_INFO, "%s: clone %s, owner=%s",
296 					ee->e_id, e->e_id, owner);
297 #endif
298 		}
299 	}
300 
301 	if (owner != NULL)
302 	{
303 		setsender(owner, e, NULL, TRUE);
304 		if (tTd(13, 5))
305 		{
306 			printf("sendall(owner): QDONTSEND ");
307 			printaddr(&e->e_from, FALSE);
308 		}
309 		e->e_from.q_flags |= QDONTSEND;
310 		e->e_errormode = EM_MAIL;
311 		e->e_flags |= EF_NORECEIPT;
312 	}
313 
314 	/* if nothing to be delivered, just queue up everything */
315 	if (!somedeliveries && mode != SM_QUEUE && mode != SM_VERIFY)
316 		mode = SM_QUEUE;
317 
318 # ifdef QUEUE
319 	if ((mode == SM_QUEUE || mode == SM_FORK ||
320 	     (mode != SM_VERIFY && SuperSafe)) &&
321 	    !bitset(EF_INQUEUE, e->e_flags))
322 	{
323 		/* be sure everything is instantiated in the queue */
324 		queueup(e, TRUE, mode == SM_QUEUE);
325 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
326 			queueup(ee, TRUE, mode == SM_QUEUE);
327 	}
328 #endif /* QUEUE */
329 
330 	/*
331 	**  If we belong in background, fork now.
332 	*/
333 
334 	switch (mode)
335 	{
336 	  case SM_VERIFY:
337 		Verbose = TRUE;
338 		break;
339 
340 	  case SM_QUEUE:
341   queueonly:
342 		if (e->e_nrcpts > 0)
343 			e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
344 		return;
345 
346 	  case SM_FORK:
347 		if (e->e_xfp != NULL)
348 			(void) fflush(e->e_xfp);
349 
350 # if !HASFLOCK
351 		/*
352 		**  Since fcntl locking has the interesting semantic that
353 		**  the lock is owned by a process, not by an open file
354 		**  descriptor, we have to flush this to the queue, and
355 		**  then restart from scratch in the child.
356 		*/
357 
358 		{
359 			/* save id for future use */
360 			char *qid = e->e_id;
361 
362 			/* now drop the envelope in the parent */
363 			e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
364 			dropenvelope(e);
365 
366 			/* and reacquire in the child */
367 			(void) dowork(qid, TRUE, FALSE, e);
368 		}
369 
370 		return;
371 
372 # else /* HASFLOCK */
373 
374 		pid = fork();
375 		if (pid < 0)
376 		{
377 			goto queueonly;
378 		}
379 		else if (pid > 0)
380 		{
381 			/* be sure we leave the temp files to our child */
382 			/* can't call unlockqueue to avoid unlink of xfp */
383 			if (e->e_lockfp != NULL)
384 				(void) xfclose(e->e_lockfp, "sendenvelope lockfp", e->e_id);
385 			e->e_lockfp = NULL;
386 
387 			/* close any random open files in the envelope */
388 			closexscript(e);
389 			if (e->e_dfp != NULL)
390 				(void) xfclose(e->e_dfp, "sendenvelope dfp", e->e_id);
391 			e->e_dfp = NULL;
392 			e->e_id = NULL;
393 			e->e_flags &= ~EF_HAS_DF;
394 
395 			/* catch intermediate zombie */
396 			(void) waitfor(pid);
397 			return;
398 		}
399 
400 		/* double fork to avoid zombies */
401 		pid = fork();
402 		if (pid > 0)
403 			exit(EX_OK);
404 
405 		/* be sure we are immune from the terminal */
406 		disconnect(1, e);
407 
408 		/* prevent parent from waiting if there was an error */
409 		if (pid < 0)
410 		{
411 			e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
412 			finis();
413 		}
414 
415 		/*
416 		**  Close any cached connections.
417 		**
418 		**	We don't send the QUIT protocol because the parent
419 		**	still knows about the connection.
420 		**
421 		**	This should only happen when delivering an error
422 		**	message.
423 		*/
424 
425 		mci_flush(FALSE, NULL);
426 
427 # endif /* HASFLOCK */
428 
429 		break;
430 	}
431 
432 	if (splitenv != NULL)
433 	{
434 		if (tTd(13, 1))
435 		{
436 			printf("\nsendall: Split queue; remaining queue:\n");
437 			printaddr(e->e_sendqueue, TRUE);
438 		}
439 
440 		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
441 		{
442 			CurEnv = ee;
443 			if (mode != SM_VERIFY)
444 				openxscript(ee);
445 			sendenvelope(ee, mode);
446 			dropenvelope(ee);
447 		}
448 
449 		CurEnv = e;
450 	}
451 	sendenvelope(e, mode);
452 	Verbose = oldverbose;
453 }
454 
455 void
sendenvelope(e,mode)456 sendenvelope(e, mode)
457 	register ENVELOPE *e;
458 	char mode;
459 {
460 	register ADDRESS *q;
461 	bool didany;
462 
463 	/*
464 	**  If we have had global, fatal errors, don't bother sending
465 	**  the message at all if we are in SMTP mode.  Local errors
466 	**  (e.g., a single address failing) will still cause the other
467 	**  addresses to be sent.
468 	*/
469 
470 	if (bitset(EF_FATALERRS, e->e_flags) &&
471 	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
472 	{
473 		e->e_flags |= EF_CLRQUEUE;
474 		return;
475 	}
476 
477 	/*
478 	**  Run through the list and send everything.
479 	**
480 	**	Set EF_GLOBALERRS so that error messages during delivery
481 	**	result in returned mail.
482 	*/
483 
484 	e->e_nsent = 0;
485 	e->e_flags |= EF_GLOBALERRS;
486 	didany = FALSE;
487 
488 	/* now run through the queue */
489 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
490 	{
491 #if XDEBUG
492 		char wbuf[MAXNAME + 20];
493 
494 		(void) sprintf(wbuf, "sendall(%s)", q->q_paddr);
495 		checkfd012(wbuf);
496 #endif
497 		if (mode == SM_VERIFY)
498 		{
499 			e->e_to = q->q_paddr;
500 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
501 			{
502 				if (q->q_host != NULL && q->q_host[0] != '\0')
503 					message("deliverable: mailer %s, host %s, user %s",
504 						q->q_mailer->m_name,
505 						q->q_host,
506 						q->q_user);
507 				else
508 					message("deliverable: mailer %s, user %s",
509 						q->q_mailer->m_name,
510 						q->q_user);
511 			}
512 		}
513 		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
514 		{
515 # ifdef QUEUE
516 			/*
517 			**  Checkpoint the send list every few addresses
518 			*/
519 
520 			if (e->e_nsent >= CheckpointInterval)
521 			{
522 				queueup(e, TRUE, FALSE);
523 				e->e_nsent = 0;
524 			}
525 # endif /* QUEUE */
526 			(void) deliver(e, q);
527 			didany = TRUE;
528 		}
529 	}
530 	if (didany)
531 	{
532 		e->e_dtime = curtime();
533 		e->e_ntries++;
534 	}
535 
536 #if XDEBUG
537 	checkfd012("end of sendenvelope");
538 #endif
539 
540 	if (mode == SM_FORK)
541 		finis();
542 }
543 /*
544 **  DOFORK -- do a fork, retrying a couple of times on failure.
545 **
546 **	This MUST be a macro, since after a vfork we are running
547 **	two processes on the same stack!!!
548 **
549 **	Parameters:
550 **		none.
551 **
552 **	Returns:
553 **		From a macro???  You've got to be kidding!
554 **
555 **	Side Effects:
556 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
557 **			pid of child in parent, zero in child.
558 **			-1 on unrecoverable error.
559 **
560 **	Notes:
561 **		I'm awfully sorry this looks so awful.  That's
562 **		vfork for you.....
563 */
564 
565 # define NFORKTRIES	5
566 
567 # ifndef FORK
568 # define FORK	fork
569 # endif
570 
571 # define DOFORK(fORKfN) \
572 {\
573 	register int i;\
574 \
575 	for (i = NFORKTRIES; --i >= 0; )\
576 	{\
577 		pid = fORKfN();\
578 		if (pid >= 0)\
579 			break;\
580 		if (i > 0)\
581 			sleep((unsigned) NFORKTRIES - i);\
582 	}\
583 }
584 /*
585 **  DOFORK -- simple fork interface to DOFORK.
586 **
587 **	Parameters:
588 **		none.
589 **
590 **	Returns:
591 **		pid of child in parent.
592 **		zero in child.
593 **		-1 on error.
594 **
595 **	Side Effects:
596 **		returns twice, once in parent and once in child.
597 */
598 
599 int
dofork()600 dofork()
601 {
602 	register int pid = -1;
603 
604 	DOFORK(fork);
605 	return (pid);
606 }
607 /*
608 **  DELIVER -- Deliver a message to a list of addresses.
609 **
610 **	This routine delivers to everyone on the same host as the
611 **	user on the head of the list.  It is clever about mailers
612 **	that don't handle multiple users.  It is NOT guaranteed
613 **	that it will deliver to all these addresses however -- so
614 **	deliver should be called once for each address on the
615 **	list.
616 **
617 **	Parameters:
618 **		e -- the envelope to deliver.
619 **		firstto -- head of the address list to deliver to.
620 **
621 **	Returns:
622 **		zero -- successfully delivered.
623 **		else -- some failure, see ExitStat for more info.
624 **
625 **	Side Effects:
626 **		The standard input is passed off to someone.
627 */
628 
629 int
deliver(e,firstto)630 deliver(e, firstto)
631 	register ENVELOPE *e;
632 	ADDRESS *firstto;
633 {
634 	char *host;			/* host being sent to */
635 	char *user;			/* user being sent to */
636 	char **pvp;
637 	register char **mvp;
638 	register char *p;
639 	register MAILER *m;		/* mailer for this recipient */
640 	ADDRESS *ctladdr;
641 	register MCI *mci;
642 	register ADDRESS *to = firstto;
643 	bool clever = FALSE;		/* running user smtp to this mailer */
644 	ADDRESS *tochain = NULL;	/* users chain in this mailer call */
645 	int rcode;			/* response code */
646 	char *firstsig;			/* signature of firstto */
647 	int pid = -1;
648 	char *curhost;
649 	time_t xstart;
650 	int mpvect[2];
651 	int rpvect[2];
652 	char *pv[MAXPV+1];
653 	char tobuf[TOBUFSIZE];		/* text line of to people */
654 	char buf[MAXNAME + 1];
655 	char rpathbuf[MAXNAME + 1];	/* translated return path */
656 	extern int checkcompat();
657 	extern void markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int));
658 
659 	errno = 0;
660 	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
661 		return (0);
662 
663 #if NAMED_BIND
664 	/* unless interactive, try twice, over a minute */
665 	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
666 	{
667 		_res.retrans = 30;
668 		_res.retry = 2;
669 	}
670 #endif
671 
672 	m = to->q_mailer;
673 	host = to->q_host;
674 	CurEnv = e;			/* just in case */
675 	e->e_statmsg = NULL;
676 	SmtpError[0] = '\0';
677 	xstart = curtime();
678 
679 	if (tTd(10, 1))
680 		printf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
681 			e->e_id, m->m_name, host, to->q_user);
682 	if (tTd(10, 100))
683 		printopenfds(FALSE);
684 
685 	/*
686 	**  Do initial argv setup.
687 	**	Insert the mailer name.  Notice that $x expansion is
688 	**	NOT done on the mailer name.  Then, if the mailer has
689 	**	a picky -f flag, we insert it as appropriate.  This
690 	**	code does not check for 'pv' overflow; this places a
691 	**	manifest lower limit of 4 for MAXPV.
692 	**		The from address rewrite is expected to make
693 	**		the address relative to the other end.
694 	*/
695 
696 	/* rewrite from address, using rewriting rules */
697 	rcode = EX_OK;
698 	if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
699 		p = e->e_sender;
700 	else
701 		p = e->e_from.q_paddr;
702 	(void) strcpy(rpathbuf, remotename(p, m,
703 					   RF_SENDERADDR|RF_CANONICAL,
704 					   &rcode, e));
705 	define('g', rpathbuf, e);		/* translated return path */
706 	define('h', host, e);			/* to host */
707 	Errors = 0;
708 	pvp = pv;
709 	*pvp++ = m->m_argv[0];
710 
711 	/* insert -f or -r flag as appropriate */
712 	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
713 	{
714 		if (bitnset(M_FOPT, m->m_flags))
715 			*pvp++ = "-f";
716 		else
717 			*pvp++ = "-r";
718 		*pvp++ = newstr(rpathbuf);
719 	}
720 
721 	/*
722 	**  Append the other fixed parts of the argv.  These run
723 	**  up to the first entry containing "$u".  There can only
724 	**  be one of these, and there are only a few more slots
725 	**  in the pv after it.
726 	*/
727 
728 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
729 	{
730 		/* can't use strchr here because of sign extension problems */
731 		while (*p != '\0')
732 		{
733 			if ((*p++ & 0377) == MACROEXPAND)
734 			{
735 				if (*p == 'u')
736 					break;
737 			}
738 		}
739 
740 		if (*p != '\0')
741 			break;
742 
743 		/* this entry is safe -- go ahead and process it */
744 		expand(*mvp, buf, sizeof buf, e);
745 		*pvp++ = newstr(buf);
746 		if (pvp >= &pv[MAXPV - 3])
747 		{
748 			syserr("554 Too many parameters to %s before $u", pv[0]);
749 			return (-1);
750 		}
751 	}
752 
753 	/*
754 	**  If we have no substitution for the user name in the argument
755 	**  list, we know that we must supply the names otherwise -- and
756 	**  SMTP is the answer!!
757 	*/
758 
759 	if (*mvp == NULL)
760 	{
761 		/* running SMTP */
762 # ifdef SMTP
763 		clever = TRUE;
764 		*pvp = NULL;
765 # else /* SMTP */
766 		/* oops!  we don't implement SMTP */
767 		syserr("554 SMTP style mailer not implemented");
768 		return (EX_SOFTWARE);
769 # endif /* SMTP */
770 	}
771 
772 	/*
773 	**  At this point *mvp points to the argument with $u.  We
774 	**  run through our address list and append all the addresses
775 	**  we can.  If we run out of space, do not fret!  We can
776 	**  always send another copy later.
777 	*/
778 
779 	tobuf[0] = '\0';
780 	e->e_to = tobuf;
781 	ctladdr = NULL;
782 	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
783 	for (; to != NULL; to = to->q_next)
784 	{
785 		/* avoid sending multiple recipients to dumb mailers */
786 		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
787 			break;
788 
789 		/* if already sent or not for this host, don't send */
790 		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
791 		    to->q_mailer != firstto->q_mailer ||
792 		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
793 			continue;
794 
795 		/* avoid overflowing tobuf */
796 		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
797 			break;
798 
799 		if (tTd(10, 1))
800 		{
801 			printf("\nsend to ");
802 			printaddr(to, FALSE);
803 		}
804 
805 		/* compute effective uid/gid when sending */
806 		if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
807 			ctladdr = getctladdr(to);
808 
809 		if (tTd(10, 2))
810 		{
811 			printf("ctladdr=");
812 			printaddr(ctladdr, FALSE);
813 		}
814 
815 		user = to->q_user;
816 		e->e_to = to->q_paddr;
817 		if (tTd(10, 5))
818 		{
819 			printf("deliver: QDONTSEND ");
820 			printaddr(to, FALSE);
821 		}
822 		to->q_flags |= QDONTSEND;
823 
824 		/*
825 		**  Check to see that these people are allowed to
826 		**  talk to each other.
827 		*/
828 
829 		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
830 		{
831 			e->e_flags |= EF_NO_BODY_RETN;
832 			to->q_status = "5.2.3";
833 			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
834 			giveresponse(EX_UNAVAILABLE, m, NULL, ctladdr, xstart, e);
835 			continue;
836 		}
837 #if NAMED_BIND
838 		h_errno = 0;
839 #endif
840 		rcode = checkcompat(to, e);
841 		if (rcode != EX_OK)
842 		{
843 			markfailure(e, to, NULL, rcode);
844 			giveresponse(rcode, m, NULL, ctladdr, xstart, e);
845 			continue;
846 		}
847 
848 		/*
849 		**  Strip quote bits from names if the mailer is dumb
850 		**	about them.
851 		*/
852 
853 		if (bitnset(M_STRIPQ, m->m_flags))
854 		{
855 			stripquotes(user);
856 			stripquotes(host);
857 		}
858 
859 		/* hack attack -- delivermail compatibility */
860 		if (m == ProgMailer && *user == '|')
861 			user++;
862 
863 		/*
864 		**  If an error message has already been given, don't
865 		**	bother to send to this address.
866 		**
867 		**	>>>>>>>>>> This clause assumes that the local mailer
868 		**	>> NOTE >> cannot do any further aliasing; that
869 		**	>>>>>>>>>> function is subsumed by sendmail.
870 		*/
871 
872 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
873 			continue;
874 
875 		/* save statistics.... */
876 		markstats(e, to);
877 
878 		/*
879 		**  See if this user name is "special".
880 		**	If the user name has a slash in it, assume that this
881 		**	is a file -- send it off without further ado.  Note
882 		**	that this type of addresses is not processed along
883 		**	with the others, so we fudge on the To person.
884 		*/
885 
886 		if (strcmp(m->m_mailer, "[FILE]") == 0)
887 		{
888 			rcode = mailfile(user, ctladdr, SFF_CREAT, e);
889 			giveresponse(rcode, m, NULL, ctladdr, xstart, e);
890 			e->e_nsent++;
891 			if (rcode == EX_OK)
892 			{
893 				to->q_flags |= QSENT;
894 				if (bitnset(M_LOCALMAILER, m->m_flags) &&
895 				    (e->e_receiptto != NULL ||
896 				     bitset(QPINGONSUCCESS, to->q_flags)))
897 				{
898 					to->q_flags |= QDELIVERED;
899 					to->q_status = "2.1.5";
900 					fprintf(e->e_xfp, "%s... Successfully delivered\n",
901 						to->q_paddr);
902 				}
903 			}
904 			to->q_statdate = curtime();
905 			continue;
906 		}
907 
908 		/*
909 		**  Address is verified -- add this user to mailer
910 		**  argv, and add it to the print list of recipients.
911 		*/
912 
913 		/* link together the chain of recipients */
914 		to->q_tchain = tochain;
915 		tochain = to;
916 
917 		/* create list of users for error messages */
918 		(void) strcat(tobuf, ",");
919 		(void) strcat(tobuf, to->q_paddr);
920 		define('u', user, e);		/* to user */
921 		p = to->q_home;
922 		if (p == NULL && ctladdr != NULL)
923 			p = ctladdr->q_home;
924 		define('z', p, e);	/* user's home */
925 
926 		/*
927 		**  Expand out this user into argument list.
928 		*/
929 
930 		if (!clever)
931 		{
932 			expand(*mvp, buf, sizeof buf, e);
933 			*pvp++ = newstr(buf);
934 			if (pvp >= &pv[MAXPV - 2])
935 			{
936 				/* allow some space for trailing parms */
937 				break;
938 			}
939 		}
940 	}
941 
942 	/* see if any addresses still exist */
943 	if (tobuf[0] == '\0')
944 	{
945 		define('g', (char *) NULL, e);
946 		return (0);
947 	}
948 
949 	/* print out messages as full list */
950 	e->e_to = tobuf + 1;
951 
952 	/*
953 	**  Fill out any parameters after the $u parameter.
954 	*/
955 
956 	while (!clever && *++mvp != NULL)
957 	{
958 		expand(*mvp, buf, sizeof buf, e);
959 		*pvp++ = newstr(buf);
960 		if (pvp >= &pv[MAXPV])
961 			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
962 	}
963 	*pvp++ = NULL;
964 
965 	/*
966 	**  Call the mailer.
967 	**	The argument vector gets built, pipes
968 	**	are created as necessary, and we fork & exec as
969 	**	appropriate.
970 	**	If we are running SMTP, we just need to clean up.
971 	*/
972 
973 	/*XXX this seems a bit wierd */
974 	if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
975 	    bitset(QGOODUID, e->e_from.q_flags))
976 		ctladdr = &e->e_from;
977 
978 #if NAMED_BIND
979 	if (ConfigLevel < 2)
980 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
981 #endif
982 
983 	if (tTd(11, 1))
984 	{
985 		printf("openmailer:");
986 		printav(pv);
987 	}
988 	errno = 0;
989 #if NAMED_BIND
990 	h_errno = 0;
991 #endif
992 
993 	CurHostName = NULL;
994 
995 	/*
996 	**  Deal with the special case of mail handled through an IPC
997 	**  connection.
998 	**	In this case we don't actually fork.  We must be
999 	**	running SMTP for this to work.  We will return a
1000 	**	zero pid to indicate that we are running IPC.
1001 	**  We also handle a debug version that just talks to stdin/out.
1002 	*/
1003 
1004 	curhost = NULL;
1005 	SmtpPhase = NULL;
1006 	mci = NULL;
1007 
1008 #if XDEBUG
1009 	{
1010 		char wbuf[MAXLINE];
1011 
1012 		/* make absolutely certain 0, 1, and 2 are in use */
1013 		sprintf(wbuf, "%s... openmailer(%s)", e->e_to, m->m_name);
1014 		checkfd012(wbuf);
1015 	}
1016 #endif
1017 
1018 	/* check for 8-bit available */
1019 	if (bitset(EF_HAS8BIT, e->e_flags) &&
1020 	    bitnset(M_7BITS, m->m_flags) &&
1021 	    (!bitset(MM_MIME8BIT, MimeMode) ||
1022 	     bitset(EF_DONT_MIME, e->e_flags)))
1023 	{
1024 		usrerr("554 Cannot send 8-bit data to 7-bit destination");
1025 		rcode = EX_DATAERR;
1026 		e->e_status = "5.6.3";
1027 		goto give_up;
1028 	}
1029 
1030 	/* check for Local Person Communication -- not for mortals!!! */
1031 	if (strcmp(m->m_mailer, "[LPC]") == 0)
1032 	{
1033 		mci = (MCI *) xalloc(sizeof *mci);
1034 		bzero((char *) mci, sizeof *mci);
1035 		mci->mci_in = stdin;
1036 		mci->mci_out = stdout;
1037 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1038 		mci->mci_mailer = m;
1039 	}
1040 	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
1041 		 strcmp(m->m_mailer, "[TCP]") == 0)
1042 	{
1043 #ifdef DAEMON
1044 		register int i;
1045 		register u_short port = 0;
1046 
1047 		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
1048 		{
1049 			syserr("null host name for %s mailer", m->m_mailer);
1050 			rcode = EX_CONFIG;
1051 			goto give_up;
1052 		}
1053 
1054 		CurHostName = pv[1];
1055 		curhost = hostsignature(m, pv[1], e);
1056 
1057 		if (curhost == NULL || curhost[0] == '\0')
1058 		{
1059 			syserr("null host signature for %s", pv[1]);
1060 			rcode = EX_CONFIG;
1061 			goto give_up;
1062 		}
1063 
1064 		if (!clever)
1065 		{
1066 			syserr("554 non-clever IPC");
1067 			rcode = EX_CONFIG;
1068 			goto give_up;
1069 		}
1070 		if (pv[2] != NULL)
1071 		{
1072 			port = htons(atoi(pv[2]));
1073 			if (port == 0)
1074 			{
1075 				struct servent *sp = getservbyname(pv[2], "tcp");
1076 
1077 				if (sp == NULL)
1078 					syserr("Service %s unknown", pv[2]);
1079 				else
1080 					port = sp->s_port;
1081 			}
1082 		}
1083 tryhost:
1084 		while (*curhost != '\0')
1085 		{
1086 			register char *p;
1087 			static char hostbuf[MAXNAME + 1];
1088 
1089 			/* pull the next host from the signature */
1090 			p = strchr(curhost, ':');
1091 			if (p == NULL)
1092 				p = &curhost[strlen(curhost)];
1093 			if (p == curhost)
1094 			{
1095 				syserr("deliver: null host name in signature");
1096 				curhost++;
1097 				continue;
1098 			}
1099 			strncpy(hostbuf, curhost, p - curhost);
1100 			hostbuf[p - curhost] = '\0';
1101 			if (*p != '\0')
1102 				p++;
1103 			curhost = p;
1104 
1105 			/* see if we already know that this host is fried */
1106 			CurHostName = hostbuf;
1107 			mci = mci_get(hostbuf, m);
1108 			if (mci->mci_state != MCIS_CLOSED)
1109 			{
1110 				if (tTd(11, 1))
1111 				{
1112 					printf("openmailer: ");
1113 					mci_dump(mci, FALSE);
1114 				}
1115 				CurHostName = mci->mci_host;
1116 				message("Using cached connection to %s via %s...",
1117 					hostbuf, m->m_name);
1118 				break;
1119 			}
1120 			mci->mci_mailer = m;
1121 			if (mci->mci_exitstat != EX_OK)
1122 				continue;
1123 
1124 			/* try the connection */
1125 			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
1126 			message("Connecting to %s via %s...",
1127 				hostbuf, m->m_name);
1128 			i = makeconnection(hostbuf, port, mci,
1129 				bitnset(M_SECURE_PORT, m->m_flags));
1130 			mci->mci_exitstat = i;
1131 			mci->mci_errno = errno;
1132 #if NAMED_BIND
1133 			mci->mci_herrno = h_errno;
1134 #endif
1135 			if (i == EX_OK)
1136 			{
1137 				mci->mci_state = MCIS_OPENING;
1138 				mci_cache(mci);
1139 				if (TrafficLogFile != NULL)
1140 					fprintf(TrafficLogFile, "%05d == CONNECT %s\n",
1141 						getpid(), hostbuf);
1142 				break;
1143 			}
1144 			else if (tTd(11, 1))
1145 				printf("openmailer: makeconnection => stat=%d, errno=%d\n",
1146 					i, errno);
1147 
1148 			/* enter status of this host */
1149 			setstat(i);
1150 
1151 			/* should print some message here for -v mode */
1152 		}
1153 		if (mci == NULL)
1154 		{
1155 			syserr("deliver: no host name");
1156 			rcode = EX_OSERR;
1157 			goto give_up;
1158 		}
1159 		mci->mci_pid = 0;
1160 #else /* no DAEMON */
1161 		syserr("554 openmailer: no IPC");
1162 		if (tTd(11, 1))
1163 			printf("openmailer: NULL\n");
1164 		rcode = EX_UNAVAILABLE;
1165 		goto give_up;
1166 #endif /* DAEMON */
1167 	}
1168 	else
1169 	{
1170 		/* flush any expired connections */
1171 		(void) mci_scan(NULL);
1172 
1173 		/* announce the connection to verbose listeners */
1174 		if (host == NULL || host[0] == '\0')
1175 			message("Connecting to %s...", m->m_name);
1176 		else
1177 			message("Connecting to %s via %s...", host, m->m_name);
1178 		if (TrafficLogFile != NULL)
1179 		{
1180 			char **av;
1181 
1182 			fprintf(TrafficLogFile, "%05d === EXEC", getpid());
1183 			for (av = pv; *av != NULL; av++)
1184 				fprintf(TrafficLogFile, " %s", *av);
1185 			fprintf(TrafficLogFile, "\n");
1186 		}
1187 
1188 		/* create a pipe to shove the mail through */
1189 		if (pipe(mpvect) < 0)
1190 		{
1191 			syserr("%s... openmailer(%s): pipe (to mailer)",
1192 				e->e_to, m->m_name);
1193 			if (tTd(11, 1))
1194 				printf("openmailer: NULL\n");
1195 			rcode = EX_OSERR;
1196 			goto give_up;
1197 		}
1198 
1199 		/* if this mailer speaks smtp, create a return pipe */
1200 		if (clever && pipe(rpvect) < 0)
1201 		{
1202 			syserr("%s... openmailer(%s): pipe (from mailer)",
1203 				e->e_to, m->m_name);
1204 			(void) close(mpvect[0]);
1205 			(void) close(mpvect[1]);
1206 			if (tTd(11, 1))
1207 				printf("openmailer: NULL\n");
1208 			rcode = EX_OSERR;
1209 			goto give_up;
1210 		}
1211 
1212 		/*
1213 		**  Actually fork the mailer process.
1214 		**	DOFORK is clever about retrying.
1215 		**
1216 		**	Dispose of SIGCHLD signal catchers that may be laying
1217 		**	around so that endmail will get it.
1218 		*/
1219 
1220 		if (e->e_xfp != NULL)
1221 			(void) fflush(e->e_xfp);		/* for debugging */
1222 		(void) fflush(stdout);
1223 # ifdef SIGCHLD
1224 		(void) setsignal(SIGCHLD, SIG_DFL);
1225 # endif /* SIGCHLD */
1226 		DOFORK(FORK);
1227 		/* pid is set by DOFORK */
1228 		if (pid < 0)
1229 		{
1230 			/* failure */
1231 			syserr("%s... openmailer(%s): cannot fork",
1232 				e->e_to, m->m_name);
1233 			(void) close(mpvect[0]);
1234 			(void) close(mpvect[1]);
1235 			if (clever)
1236 			{
1237 				(void) close(rpvect[0]);
1238 				(void) close(rpvect[1]);
1239 			}
1240 			if (tTd(11, 1))
1241 				printf("openmailer: NULL\n");
1242 			rcode = EX_OSERR;
1243 			goto give_up;
1244 		}
1245 		else if (pid == 0)
1246 		{
1247 			int i;
1248 			int saveerrno;
1249 			struct stat stb;
1250 			extern int DtableSize;
1251 
1252 			if (e->e_lockfp != NULL)
1253 				(void) close(fileno(e->e_lockfp));
1254 
1255 			/* child -- set up input & exec mailer */
1256 			(void) setsignal(SIGINT, SIG_IGN);
1257 			(void) setsignal(SIGHUP, SIG_IGN);
1258 			(void) setsignal(SIGTERM, SIG_DFL);
1259 
1260 			if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
1261 				stb.st_mode = 0;
1262 
1263 			/* tweak niceness */
1264 			if (m->m_nice != 0)
1265 				nice(m->m_nice);
1266 
1267 			/* reset group id */
1268 			if (bitnset(M_SPECIFIC_UID, m->m_flags))
1269 				(void) setgid(m->m_gid);
1270 			else if (bitset(S_ISGID, stb.st_mode))
1271 				(void) setgid(stb.st_gid);
1272 			else if (ctladdr != NULL && ctladdr->q_gid != 0)
1273 			{
1274 				(void) initgroups(ctladdr->q_ruser?
1275 					ctladdr->q_ruser: ctladdr->q_user,
1276 					ctladdr->q_gid);
1277 				(void) setgid(ctladdr->q_gid);
1278 			}
1279 			else
1280 			{
1281 				(void) initgroups(DefUser, DefGid);
1282 				if (m->m_gid == 0)
1283 					(void) setgid(DefGid);
1284 				else
1285 					(void) setgid(m->m_gid);
1286 			}
1287 
1288 			/* reset user id */
1289 			endpwent();
1290 			if (bitnset(M_SPECIFIC_UID, m->m_flags))
1291 				(void) setuid(m->m_uid);
1292 			else if (bitset(S_ISUID, stb.st_mode))
1293 				(void) setuid(stb.st_uid);
1294 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
1295 				(void) setuid(ctladdr->q_uid);
1296 			else
1297 			{
1298 				if (m->m_uid == 0)
1299 					(void) setuid(DefUid);
1300 				else
1301 					(void) setuid(m->m_uid);
1302 			}
1303 
1304 			if (tTd(11, 2))
1305 				printf("openmailer: running as r/euid=%d/%d\n",
1306 					getuid(), geteuid());
1307 
1308 			/* move into some "safe" directory */
1309 			if (m->m_execdir != NULL)
1310 			{
1311 				char *p, *q;
1312 				char buf[MAXLINE + 1];
1313 
1314 				for (p = m->m_execdir; p != NULL; p = q)
1315 				{
1316 					q = strchr(p, ':');
1317 					if (q != NULL)
1318 						*q = '\0';
1319 					expand(p, buf, sizeof buf, e);
1320 					if (q != NULL)
1321 						*q++ = ':';
1322 					if (tTd(11, 20))
1323 						printf("openmailer: trydir %s\n",
1324 							buf);
1325 					if (buf[0] != '\0' && chdir(buf) >= 0)
1326 						break;
1327 				}
1328 			}
1329 
1330 			/* arrange to filter std & diag output of command */
1331 			if (clever)
1332 			{
1333 				(void) close(rpvect[0]);
1334 				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
1335 				{
1336 					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
1337 						e->e_to, m->m_name, rpvect[1]);
1338 					_exit(EX_OSERR);
1339 				}
1340 				(void) close(rpvect[1]);
1341 			}
1342 			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON ||
1343 				  HoldErrs || DisConnected)
1344 			{
1345 				/* put mailer output in transcript */
1346 				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
1347 				{
1348 					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
1349 						e->e_to, m->m_name,
1350 						fileno(e->e_xfp));
1351 					_exit(EX_OSERR);
1352 				}
1353 			}
1354 			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1355 			{
1356 				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
1357 					e->e_to, m->m_name);
1358 				_exit(EX_OSERR);
1359 			}
1360 
1361 			/* arrange to get standard input */
1362 			(void) close(mpvect[1]);
1363 			if (dup2(mpvect[0], STDIN_FILENO) < 0)
1364 			{
1365 				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
1366 					e->e_to, m->m_name, mpvect[0]);
1367 				_exit(EX_OSERR);
1368 			}
1369 			(void) close(mpvect[0]);
1370 
1371 			/* arrange for all the files to be closed */
1372 			for (i = 3; i < DtableSize; i++)
1373 			{
1374 				register int j;
1375 
1376 				if ((j = fcntl(i, F_GETFD, 0)) != -1)
1377 					(void) fcntl(i, F_SETFD, j | 1);
1378 			}
1379 
1380 			/* run disconnected from terminal */
1381 			(void) setsid();
1382 
1383 			/* try to execute the mailer */
1384 			execve(m->m_mailer, (ARGV_T) pv, (ARGV_T) UserEnviron);
1385 			saveerrno = errno;
1386 			syserr("Cannot exec %s", m->m_mailer);
1387 			if (bitnset(M_LOCALMAILER, m->m_flags) ||
1388 			    transienterror(saveerrno))
1389 				_exit(EX_OSERR);
1390 			_exit(EX_UNAVAILABLE);
1391 		}
1392 
1393 		/*
1394 		**  Set up return value.
1395 		*/
1396 
1397 		mci = (MCI *) xalloc(sizeof *mci);
1398 		bzero((char *) mci, sizeof *mci);
1399 		mci->mci_mailer = m;
1400 		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
1401 		mci->mci_pid = pid;
1402 		(void) close(mpvect[0]);
1403 		mci->mci_out = fdopen(mpvect[1], "w");
1404 		if (mci->mci_out == NULL)
1405 		{
1406 			syserr("deliver: cannot create mailer output channel, fd=%d",
1407 				mpvect[1]);
1408 			(void) close(mpvect[1]);
1409 			if (clever)
1410 			{
1411 				(void) close(rpvect[0]);
1412 				(void) close(rpvect[1]);
1413 			}
1414 			rcode = EX_OSERR;
1415 			goto give_up;
1416 		}
1417 		if (clever)
1418 		{
1419 			(void) close(rpvect[1]);
1420 			mci->mci_in = fdopen(rpvect[0], "r");
1421 			if (mci->mci_in == NULL)
1422 			{
1423 				syserr("deliver: cannot create mailer input channel, fd=%d",
1424 					mpvect[1]);
1425 				(void) close(rpvect[0]);
1426 				fclose(mci->mci_out);
1427 				mci->mci_out = NULL;
1428 				rcode = EX_OSERR;
1429 				goto give_up;
1430 			}
1431 		}
1432 		else
1433 		{
1434 			mci->mci_flags |= MCIF_TEMP;
1435 			mci->mci_in = NULL;
1436 		}
1437 	}
1438 
1439 	/*
1440 	**  If we are in SMTP opening state, send initial protocol.
1441 	*/
1442 
1443 	if (clever && mci->mci_state != MCIS_CLOSED)
1444 	{
1445 		smtpinit(m, mci, e);
1446 	}
1447 
1448 	if (bitset(EF_HAS8BIT, e->e_flags) && bitnset(M_7BITS, m->m_flags))
1449 		mci->mci_flags |= MCIF_CVT8TO7;
1450 	else
1451 		mci->mci_flags &= ~MCIF_CVT8TO7;
1452 
1453 	if (tTd(11, 1))
1454 	{
1455 		printf("openmailer: ");
1456 		mci_dump(mci, FALSE);
1457 	}
1458 
1459 	if (mci->mci_state != MCIS_OPEN)
1460 	{
1461 		/* couldn't open the mailer */
1462 		rcode = mci->mci_exitstat;
1463 		errno = mci->mci_errno;
1464 #if NAMED_BIND
1465 		h_errno = mci->mci_herrno;
1466 #endif
1467 		if (rcode == EX_OK)
1468 		{
1469 			/* shouldn't happen */
1470 			syserr("554 deliver: rcode=%d, mci_state=%d, sig=%s",
1471 				rcode, mci->mci_state, firstsig);
1472 			rcode = EX_SOFTWARE;
1473 		}
1474 		else if (curhost != NULL && *curhost != '\0')
1475 		{
1476 			/* try next MX site */
1477 			goto tryhost;
1478 		}
1479 	}
1480 	else if (!clever)
1481 	{
1482 		/*
1483 		**  Format and send message.
1484 		*/
1485 
1486 		putfromline(mci, e);
1487 		(*e->e_puthdr)(mci, e->e_header, e);
1488 		(*e->e_putbody)(mci, e, NULL);
1489 
1490 		/* get the exit status */
1491 		rcode = endmailer(mci, e, pv);
1492 	}
1493 	else
1494 #ifdef SMTP
1495 	{
1496 		/*
1497 		**  Send the MAIL FROM: protocol
1498 		*/
1499 
1500 		rcode = smtpmailfrom(m, mci, e);
1501 		if (rcode == EX_OK)
1502 		{
1503 			register char *t = tobuf;
1504 			register int i;
1505 
1506 			/* send the recipient list */
1507 			tobuf[0] = '\0';
1508 			for (to = tochain; to != NULL; to = to->q_tchain)
1509 			{
1510 				e->e_to = to->q_paddr;
1511 				if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
1512 				{
1513 					markfailure(e, to, mci, i);
1514 					giveresponse(i, m, mci, ctladdr, xstart, e);
1515 				}
1516 				else
1517 				{
1518 					*t++ = ',';
1519 					for (p = to->q_paddr; *p; *t++ = *p++)
1520 						continue;
1521 					*t = '\0';
1522 				}
1523 			}
1524 
1525 			/* now send the data */
1526 			if (tobuf[0] == '\0')
1527 			{
1528 				rcode = EX_OK;
1529 				e->e_to = NULL;
1530 				if (bitset(MCIF_CACHED, mci->mci_flags))
1531 					smtprset(m, mci, e);
1532 			}
1533 			else
1534 			{
1535 				e->e_to = tobuf + 1;
1536 				rcode = smtpdata(m, mci, e);
1537 			}
1538 
1539 			/* now close the connection */
1540 			if (!bitset(MCIF_CACHED, mci->mci_flags))
1541 				smtpquit(m, mci, e);
1542 		}
1543 		if (rcode != EX_OK && curhost != NULL && *curhost != '\0')
1544 		{
1545 			/* try next MX site */
1546 			goto tryhost;
1547 		}
1548 	}
1549 #else /* not SMTP */
1550 	{
1551 		syserr("554 deliver: need SMTP compiled to use clever mailer");
1552 		rcode = EX_CONFIG;
1553 		goto give_up;
1554 	}
1555 #endif /* SMTP */
1556 #if NAMED_BIND
1557 	if (ConfigLevel < 2)
1558 		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
1559 #endif
1560 
1561 	/* arrange a return receipt if requested */
1562 	if (rcode == EX_OK && e->e_receiptto != NULL &&
1563 	    bitnset(M_LOCALMAILER, m->m_flags))
1564 	{
1565 		e->e_flags |= EF_SENDRECEIPT;
1566 		/* do we want to send back more info? */
1567 	}
1568 
1569 	/*
1570 	**  Do final status disposal.
1571 	**	We check for something in tobuf for the SMTP case.
1572 	**	If we got a temporary failure, arrange to queue the
1573 	**		addressees.
1574 	*/
1575 
1576   give_up:
1577 	if (tobuf[0] != '\0')
1578 		giveresponse(rcode, m, mci, ctladdr, xstart, e);
1579 	for (to = tochain; to != NULL; to = to->q_tchain)
1580 	{
1581 		if (rcode != EX_OK)
1582 			markfailure(e, to, mci, rcode);
1583 		else if (!bitset(QBADADDR|QQUEUEUP, to->q_flags))
1584 		{
1585 			to->q_flags |= QSENT;
1586 			to->q_statdate = curtime();
1587 			e->e_nsent++;
1588 			if (bitnset(M_LOCALMAILER, m->m_flags) &&
1589 			    (e->e_receiptto != NULL ||
1590 			     bitset(QPINGONSUCCESS, to->q_flags)))
1591 			{
1592 				to->q_flags |= QDELIVERED;
1593 				to->q_status = "2.1.5";
1594 				fprintf(e->e_xfp, "%s... Successfully delivered\n",
1595 					to->q_paddr);
1596 			}
1597 			else if (bitset(QPINGONSUCCESS, to->q_flags) &&
1598 				 bitset(QPRIMARY, to->q_flags) &&
1599 				 !bitset(MCIF_DSN, mci->mci_flags))
1600 			{
1601 				to->q_flags |= QRELAYED;
1602 				fprintf(e->e_xfp, "%s... relayed; expect no further notifications\n",
1603 					to->q_paddr);
1604 			}
1605 		}
1606 	}
1607 
1608 	/*
1609 	**  Restore state and return.
1610 	*/
1611 
1612 #if XDEBUG
1613 	{
1614 		char wbuf[MAXLINE];
1615 
1616 		/* make absolutely certain 0, 1, and 2 are in use */
1617 		sprintf(wbuf, "%s... end of deliver(%s)",
1618 			e->e_to == NULL ? "NO-TO-LIST" : e->e_to,
1619 			m->m_name);
1620 		checkfd012(wbuf);
1621 	}
1622 #endif
1623 
1624 	errno = 0;
1625 	define('g', (char *) NULL, e);
1626 	return (rcode);
1627 }
1628 /*
1629 **  MARKFAILURE -- mark a failure on a specific address.
1630 **
1631 **	Parameters:
1632 **		e -- the envelope we are sending.
1633 **		q -- the address to mark.
1634 **		mci -- mailer connection information.
1635 **		rcode -- the code signifying the particular failure.
1636 **
1637 **	Returns:
1638 **		none.
1639 **
1640 **	Side Effects:
1641 **		marks the address (and possibly the envelope) with the
1642 **			failure so that an error will be returned or
1643 **			the message will be queued, as appropriate.
1644 */
1645 
1646 void
markfailure(e,q,mci,rcode)1647 markfailure(e, q, mci, rcode)
1648 	register ENVELOPE *e;
1649 	register ADDRESS *q;
1650 	register MCI *mci;
1651 	int rcode;
1652 {
1653 	char *stat = NULL;
1654 
1655 	switch (rcode)
1656 	{
1657 	  case EX_OK:
1658 		break;
1659 
1660 	  case EX_TEMPFAIL:
1661 	  case EX_IOERR:
1662 	  case EX_OSERR:
1663 		q->q_flags |= QQUEUEUP;
1664 		break;
1665 
1666 	  default:
1667 		q->q_flags |= QBADADDR;
1668 		break;
1669 	}
1670 
1671 	/* find most specific error code possible */
1672 	if (q->q_status == NULL && mci != NULL)
1673 		q->q_status = mci->mci_status;
1674 	if (q->q_status == NULL)
1675 		q->q_status = e->e_status;
1676 	if (q->q_status == NULL)
1677 	{
1678 		switch (rcode)
1679 		{
1680 		  case EX_USAGE:
1681 			stat = "5.5.4";
1682 			break;
1683 
1684 		  case EX_DATAERR:
1685 			stat = "5.5.2";
1686 			break;
1687 
1688 		  case EX_NOUSER:
1689 			stat = "5.1.1";
1690 			break;
1691 
1692 		  case EX_NOHOST:
1693 			stat = "5.1.2";
1694 			break;
1695 
1696 		  case EX_NOINPUT:
1697 		  case EX_CANTCREAT:
1698 		  case EX_NOPERM:
1699 			stat = "5.3.0";
1700 			break;
1701 
1702 		  case EX_UNAVAILABLE:
1703 		  case EX_SOFTWARE:
1704 		  case EX_OSFILE:
1705 		  case EX_PROTOCOL:
1706 		  case EX_CONFIG:
1707 			stat = "5.5.0";
1708 			break;
1709 
1710 		  case EX_OSERR:
1711 		  case EX_IOERR:
1712 			stat = "4.5.0";
1713 			break;
1714 
1715 		  case EX_TEMPFAIL:
1716 			stat = "4.2.0";
1717 			break;
1718 		}
1719 		if (stat != NULL)
1720 			q->q_status = stat;
1721 	}
1722 
1723 	q->q_statdate = curtime();
1724 	if (CurHostName != NULL && CurHostName[0] != '\0')
1725 		q->q_statmta = newstr(CurHostName);
1726 	if (rcode != EX_OK && q->q_rstatus == NULL)
1727 	{
1728 		char buf[30];
1729 
1730 		(void) sprintf(buf, "%d", rcode);
1731 		q->q_rstatus = newstr(buf);
1732 	}
1733 }
1734 /*
1735 **  ENDMAILER -- Wait for mailer to terminate.
1736 **
1737 **	We should never get fatal errors (e.g., segmentation
1738 **	violation), so we report those specially.  For other
1739 **	errors, we choose a status message (into statmsg),
1740 **	and if it represents an error, we print it.
1741 **
1742 **	Parameters:
1743 **		pid -- pid of mailer.
1744 **		e -- the current envelope.
1745 **		pv -- the parameter vector that invoked the mailer
1746 **			(for error messages).
1747 **
1748 **	Returns:
1749 **		exit code of mailer.
1750 **
1751 **	Side Effects:
1752 **		none.
1753 */
1754 
1755 int
endmailer(mci,e,pv)1756 endmailer(mci, e, pv)
1757 	register MCI *mci;
1758 	register ENVELOPE *e;
1759 	char **pv;
1760 {
1761 	int st;
1762 
1763 	/* close any connections */
1764 	if (mci->mci_in != NULL)
1765 		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
1766 	if (mci->mci_out != NULL)
1767 		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
1768 	mci->mci_in = mci->mci_out = NULL;
1769 	mci->mci_state = MCIS_CLOSED;
1770 
1771 	/* in the IPC case there is nothing to wait for */
1772 	if (mci->mci_pid == 0)
1773 		return (EX_OK);
1774 
1775 	/* wait for the mailer process to die and collect status */
1776 	st = waitfor(mci->mci_pid);
1777 	if (st == -1)
1778 	{
1779 		syserr("endmailer %s: wait", pv[0]);
1780 		return (EX_SOFTWARE);
1781 	}
1782 
1783 	if (WIFEXITED(st))
1784 	{
1785 		/* normal death -- return status */
1786 		return (WEXITSTATUS(st));
1787 	}
1788 
1789 	/* it died a horrid death */
1790 	syserr("451 mailer %s died with signal %o",
1791 		mci->mci_mailer->m_name, st);
1792 
1793 	/* log the arguments */
1794 	if (pv != NULL && e->e_xfp != NULL)
1795 	{
1796 		register char **av;
1797 
1798 		fprintf(e->e_xfp, "Arguments:");
1799 		for (av = pv; *av != NULL; av++)
1800 			fprintf(e->e_xfp, " %s", *av);
1801 		fprintf(e->e_xfp, "\n");
1802 	}
1803 
1804 	ExitStat = EX_TEMPFAIL;
1805 	return (EX_TEMPFAIL);
1806 }
1807 /*
1808 **  GIVERESPONSE -- Interpret an error response from a mailer
1809 **
1810 **	Parameters:
1811 **		stat -- the status code from the mailer (high byte
1812 **			only; core dumps must have been taken care of
1813 **			already).
1814 **		m -- the mailer info for this mailer.
1815 **		mci -- the mailer connection info -- can be NULL if the
1816 **			response is given before the connection is made.
1817 **		ctladdr -- the controlling address for the recipient
1818 **			address(es).
1819 **		xstart -- the transaction start time, for computing
1820 **			transaction delays.
1821 **		e -- the current envelope.
1822 **
1823 **	Returns:
1824 **		none.
1825 **
1826 **	Side Effects:
1827 **		Errors may be incremented.
1828 **		ExitStat may be set.
1829 */
1830 
1831 void
giveresponse(stat,m,mci,ctladdr,xstart,e)1832 giveresponse(stat, m, mci, ctladdr, xstart, e)
1833 	int stat;
1834 	register MAILER *m;
1835 	register MCI *mci;
1836 	ADDRESS *ctladdr;
1837 	time_t xstart;
1838 	ENVELOPE *e;
1839 {
1840 	register const char *statmsg;
1841 	extern char *SysExMsg[];
1842 	register int i;
1843 	extern int N_SysEx;
1844 	char buf[MAXLINE];
1845 
1846 	/*
1847 	**  Compute status message from code.
1848 	*/
1849 
1850 	i = stat - EX__BASE;
1851 	if (stat == 0)
1852 	{
1853 		statmsg = "250 Sent";
1854 		if (e->e_statmsg != NULL)
1855 		{
1856 			(void) sprintf(buf, "%s (%s)", statmsg, e->e_statmsg);
1857 			statmsg = buf;
1858 		}
1859 	}
1860 	else if (i < 0 || i > N_SysEx)
1861 	{
1862 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
1863 		stat = EX_UNAVAILABLE;
1864 		statmsg = buf;
1865 	}
1866 	else if (stat == EX_TEMPFAIL)
1867 	{
1868 		(void) strcpy(buf, SysExMsg[i] + 1);
1869 #if NAMED_BIND
1870 		if (h_errno == TRY_AGAIN)
1871 			statmsg = errstring(h_errno+E_DNSBASE);
1872 		else
1873 #endif
1874 		{
1875 			if (errno != 0)
1876 				statmsg = errstring(errno);
1877 			else
1878 			{
1879 #ifdef SMTP
1880 				statmsg = SmtpError;
1881 #else /* SMTP */
1882 				statmsg = NULL;
1883 #endif /* SMTP */
1884 			}
1885 		}
1886 		if (statmsg != NULL && statmsg[0] != '\0')
1887 		{
1888 			(void) strcat(buf, ": ");
1889 			(void) strcat(buf, statmsg);
1890 		}
1891 		statmsg = buf;
1892 	}
1893 #if NAMED_BIND
1894 	else if (stat == EX_NOHOST && h_errno != 0)
1895 	{
1896 		statmsg = errstring(h_errno + E_DNSBASE);
1897 		(void) sprintf(buf, "%s (%s)", SysExMsg[i] + 1, statmsg);
1898 		statmsg = buf;
1899 	}
1900 #endif
1901 	else
1902 	{
1903 		statmsg = SysExMsg[i];
1904 		if (*statmsg++ == ':')
1905 		{
1906 			(void) sprintf(buf, "%s: %s", statmsg, errstring(errno));
1907 			statmsg = buf;
1908 		}
1909 	}
1910 
1911 	/*
1912 	**  Print the message as appropriate
1913 	*/
1914 
1915 	if (stat == EX_OK || stat == EX_TEMPFAIL)
1916 	{
1917 		extern char MsgBuf[];
1918 
1919 		message("%s", &statmsg[4]);
1920 		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
1921 			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
1922 	}
1923 	else
1924 	{
1925 		char mbuf[8];
1926 
1927 		Errors++;
1928 		sprintf(mbuf, "%.3s %%s", statmsg);
1929 		usrerr(mbuf, &statmsg[4]);
1930 	}
1931 
1932 	/*
1933 	**  Final cleanup.
1934 	**	Log a record of the transaction.  Compute the new
1935 	**	ExitStat -- if we already had an error, stick with
1936 	**	that.
1937 	*/
1938 
1939 	if (LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
1940 		logdelivery(m, mci, &statmsg[4], ctladdr, xstart, e);
1941 
1942 	if (tTd(11, 2))
1943 		printf("giveresponse: stat=%d, e->e_message=%s\n",
1944 			stat, e->e_message == NULL ? "<NULL>" : e->e_message);
1945 
1946 	if (stat != EX_TEMPFAIL)
1947 		setstat(stat);
1948 	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
1949 	{
1950 		if (e->e_message != NULL)
1951 			free(e->e_message);
1952 		e->e_message = newstr(&statmsg[4]);
1953 	}
1954 	errno = 0;
1955 #if NAMED_BIND
1956 	h_errno = 0;
1957 #endif
1958 }
1959 /*
1960 **  LOGDELIVERY -- log the delivery in the system log
1961 **
1962 **	Care is taken to avoid logging lines that are too long, because
1963 **	some versions of syslog have an unfortunate proclivity for core
1964 **	dumping.  This is a hack, to be sure, that is at best empirical.
1965 **
1966 **	Parameters:
1967 **		m -- the mailer info.  Can be NULL for initial queue.
1968 **		mci -- the mailer connection info -- can be NULL if the
1969 **			log is occuring when no connection is active.
1970 **		stat -- the message to print for the status.
1971 **		ctladdr -- the controlling address for the to list.
1972 **		xstart -- the transaction start time, used for
1973 **			computing transaction delay.
1974 **		e -- the current envelope.
1975 **
1976 **	Returns:
1977 **		none
1978 **
1979 **	Side Effects:
1980 **		none
1981 */
1982 
1983 void
logdelivery(m,mci,stat,ctladdr,xstart,e)1984 logdelivery(m, mci, stat, ctladdr, xstart, e)
1985 	MAILER *m;
1986 	register MCI *mci;
1987 	const char *stat;
1988 	ADDRESS *ctladdr;
1989 	time_t xstart;
1990 	register ENVELOPE *e;
1991 {
1992 # ifdef LOG
1993 	register char *bp;
1994 	register char *p;
1995 	int l;
1996 	char buf[512];
1997 
1998 #  if (SYSLOG_BUFSIZE) >= 256
1999 	bp = buf;
2000 	if (ctladdr != NULL)
2001 	{
2002 		strcpy(bp, ", ctladdr=");
2003 		strcat(bp, shortenstring(ctladdr->q_paddr, 83));
2004 		bp += strlen(bp);
2005 		if (bitset(QGOODUID, ctladdr->q_flags))
2006 		{
2007 			(void) sprintf(bp, " (%d/%d)",
2008 					ctladdr->q_uid, ctladdr->q_gid);
2009 			bp += strlen(bp);
2010 		}
2011 	}
2012 
2013 	sprintf(bp, ", delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
2014 	bp += strlen(bp);
2015 
2016 	if (xstart != (time_t) 0)
2017 	{
2018 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
2019 		bp += strlen(bp);
2020 	}
2021 
2022 	if (m != NULL)
2023 	{
2024 		(void) strcpy(bp, ", mailer=");
2025 		(void) strcat(bp, m->m_name);
2026 		bp += strlen(bp);
2027 	}
2028 
2029 	if (mci != NULL && mci->mci_host != NULL)
2030 	{
2031 # ifdef DAEMON
2032 		extern SOCKADDR CurHostAddr;
2033 # endif
2034 
2035 		(void) strcpy(bp, ", relay=");
2036 		(void) strcat(bp, mci->mci_host);
2037 
2038 # ifdef DAEMON
2039 		(void) strcat(bp, " [");
2040 		(void) strcat(bp, anynet_ntoa(&CurHostAddr));
2041 		(void) strcat(bp, "]");
2042 # endif
2043 	}
2044 	else if (strcmp(stat, "queued") != 0)
2045 	{
2046 		char *p = macvalue('h', e);
2047 
2048 		if (p != NULL && p[0] != '\0')
2049 		{
2050 			(void) strcpy(bp, ", relay=");
2051 			(void) strcat(bp, p);
2052 		}
2053 	}
2054 	bp += strlen(bp);
2055 
2056 #define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
2057 #if (STATLEN) < 63
2058 # undef STATLEN
2059 # define STATLEN	63
2060 #endif
2061 #if (STATLEN) > 203
2062 # undef STATLEN
2063 # define STATLEN	203
2064 #endif
2065 
2066 	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
2067 	{
2068 		/* desperation move -- truncate data */
2069 		bp = buf + sizeof buf - ((STATLEN) + 17);
2070 		strcpy(bp, "...");
2071 		bp += 3;
2072 	}
2073 
2074 	(void) strcpy(bp, ", stat=");
2075 	bp += strlen(bp);
2076 
2077 	(void) strcpy(bp, shortenstring(stat, (STATLEN)));
2078 
2079 	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
2080 	p = e->e_to;
2081 	while (strlen(p) >= (SIZE_T) l)
2082 	{
2083 		register char *q = strchr(p + l, ',');
2084 
2085 		if (q == NULL)
2086 			break;
2087 		syslog(LOG_INFO, "%s: to=%.*s [more]%s",
2088 			e->e_id, ++q - p, p, buf);
2089 		p = q;
2090 	}
2091 	syslog(LOG_INFO, "%s: to=%s%s", e->e_id, p, buf);
2092 
2093 #  else		/* we have a very short log buffer size */
2094 
2095 	l = SYSLOG_BUFSIZE - 85;
2096 	p = e->e_to;
2097 	while (strlen(p) >= l)
2098 	{
2099 		register char *q = strchr(p + l, ',');
2100 
2101 		if (q == NULL)
2102 			break;
2103 		syslog(LOG_INFO, "%s: to=%.*s [more]",
2104 			e->e_id, ++q - p, p);
2105 		p = q;
2106 	}
2107 	syslog(LOG_INFO, "%s: to=%s", e->e_id, p);
2108 
2109 	if (ctladdr != NULL)
2110 	{
2111 		bp = buf;
2112 		strcpy(buf, "ctladdr=");
2113 		bp += strlen(buf);
2114 		strcpy(bp, shortenstring(ctladdr->q_paddr, 83));
2115 		bp += strlen(buf);
2116 		if (bitset(QGOODUID, ctladdr->q_flags))
2117 		{
2118 			(void) sprintf(bp, " (%d/%d)",
2119 					ctladdr->q_uid, ctladdr->q_gid);
2120 			bp += strlen(bp);
2121 		}
2122 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2123 	}
2124 	bp = buf;
2125 	sprintf(bp, "delay=%s", pintvl(curtime() - e->e_ctime, TRUE));
2126 	bp += strlen(bp);
2127 	if (xstart != (time_t) 0)
2128 	{
2129 		sprintf(bp, ", xdelay=%s", pintvl(curtime() - xstart, TRUE));
2130 		bp += strlen(bp);
2131 	}
2132 
2133 	if (m != NULL)
2134 	{
2135 		sprintf(bp, ", mailer=%s", m->m_name);
2136 		bp += strlen(bp);
2137 	}
2138 	syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2139 
2140 	buf[0] = '\0';
2141 	if (mci != NULL && mci->mci_host != NULL)
2142 	{
2143 # ifdef DAEMON
2144 		extern SOCKADDR CurHostAddr;
2145 # endif
2146 
2147 		sprintf(buf, "relay=%s", mci->mci_host);
2148 
2149 # ifdef DAEMON
2150 		(void) strcat(buf, " [");
2151 		(void) strcat(buf, anynet_ntoa(&CurHostAddr));
2152 		(void) strcat(buf, "]");
2153 # endif
2154 	}
2155 	else if (strcmp(stat, "queued") != 0)
2156 	{
2157 		char *p = macvalue('h', e);
2158 
2159 		if (p != NULL && p[0] != '\0')
2160 			sprintf(buf, "relay=%s", p);
2161 	}
2162 	if (buf[0] != '\0')
2163 		syslog(LOG_INFO, "%s: %s", e->e_id, buf);
2164 
2165 	syslog(LOG_INFO, "%s: stat=%s", e->e_id, shortenstring(stat, 63));
2166 #  endif /* short log buffer */
2167 # endif /* LOG */
2168 }
2169 /*
2170 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
2171 **
2172 **	This can be made an arbitrary message separator by changing $l
2173 **
2174 **	One of the ugliest hacks seen by human eyes is contained herein:
2175 **	UUCP wants those stupid "remote from <host>" lines.  Why oh why
2176 **	does a well-meaning programmer such as myself have to deal with
2177 **	this kind of antique garbage????
2178 **
2179 **	Parameters:
2180 **		mci -- the connection information.
2181 **		e -- the envelope.
2182 **
2183 **	Returns:
2184 **		none
2185 **
2186 **	Side Effects:
2187 **		outputs some text to fp.
2188 */
2189 
2190 void
putfromline(mci,e)2191 putfromline(mci, e)
2192 	register MCI *mci;
2193 	ENVELOPE *e;
2194 {
2195 	char *template = "\201l\n";
2196 	char buf[MAXLINE];
2197 
2198 	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
2199 		return;
2200 
2201 	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
2202 	{
2203 		char *bang;
2204 		char xbuf[MAXLINE];
2205 
2206 		expand("\201g", buf, sizeof buf, e);
2207 		bang = strchr(buf, '!');
2208 		if (bang == NULL)
2209 		{
2210 			errno = 0;
2211 			syserr("554 No ! in UUCP From address! (%s given)", buf);
2212 		}
2213 		else
2214 		{
2215 			*bang++ = '\0';
2216 			(void) sprintf(xbuf, "From %s  \201d remote from %s\n", bang, buf);
2217 			template = xbuf;
2218 		}
2219 	}
2220 	expand(template, buf, sizeof buf, e);
2221 	putxline(buf, mci, PXLF_NOTHINGSPECIAL);
2222 }
2223 /*
2224 **  PUTBODY -- put the body of a message.
2225 **
2226 **	Parameters:
2227 **		mci -- the connection information.
2228 **		e -- the envelope to put out.
2229 **		separator -- if non-NULL, a message separator that must
2230 **			not be permitted in the resulting message.
2231 **
2232 **	Returns:
2233 **		none.
2234 **
2235 **	Side Effects:
2236 **		The message is written onto fp.
2237 */
2238 
2239 /* values for output state variable */
2240 #define OS_HEAD		0	/* at beginning of line */
2241 #define OS_CR		1	/* read a carriage return */
2242 #define OS_INLINE	2	/* putting rest of line */
2243 
2244 void
putbody(mci,e,separator)2245 putbody(mci, e, separator)
2246 	register MCI *mci;
2247 	register ENVELOPE *e;
2248 	char *separator;
2249 {
2250 	char buf[MAXLINE];
2251 
2252 	/*
2253 	**  Output the body of the message
2254 	*/
2255 
2256 	if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
2257 	{
2258 		char *df = queuename(e, 'd');
2259 
2260 		e->e_dfp = fopen(df, "r");
2261 		if (e->e_dfp == NULL)
2262 			syserr("putbody: Cannot open %s for %s from %s",
2263 				df, e->e_to, e->e_from.q_paddr);
2264 	}
2265 	if (e->e_dfp == NULL)
2266 	{
2267 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2268 		{
2269 			putline("", mci);
2270 			mci->mci_flags &= ~MCIF_INHEADER;
2271 		}
2272 		putline("<<< No Message Collected >>>", mci);
2273 		goto endofmessage;
2274 	}
2275 	if (e->e_dfino == (ino_t) 0)
2276 	{
2277 		struct stat stbuf;
2278 
2279 		if (fstat(fileno(e->e_dfp), &stbuf) < 0)
2280 			e->e_dfino = -1;
2281 		else
2282 		{
2283 			e->e_dfdev = stbuf.st_dev;
2284 			e->e_dfino = stbuf.st_ino;
2285 		}
2286 	}
2287 	rewind(e->e_dfp);
2288 
2289 #if MIME8TO7
2290 	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
2291 	{
2292 		char *boundaries[MAXMIMENESTING + 1];
2293 
2294 		/*
2295 		**  Do 8 to 7 bit MIME conversion.
2296 		*/
2297 
2298 		/* make sure it looks like a MIME message */
2299 		if (hvalue("MIME-Version", e->e_header) == NULL)
2300 			putline("MIME-Version: 1.0", mci);
2301 
2302 		if (hvalue("Content-Type", e->e_header) == NULL)
2303 		{
2304 			sprintf(buf, "Content-Type: text/plain; charset=%s",
2305 				defcharset(e));
2306 			putline(buf, mci);
2307 		}
2308 
2309 		/* now do the hard work */
2310 		boundaries[0] = NULL;
2311 		mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
2312 	}
2313 	else
2314 #endif
2315 	{
2316 		int ostate;
2317 		register char *bp;
2318 		register char *pbp;
2319 		register int c;
2320 		int padc;
2321 		char *buflim;
2322 		int pos = 0;
2323 		char peekbuf[10];
2324 
2325 		/* we can pass it through unmodified */
2326 		if (bitset(MCIF_INHEADER, mci->mci_flags))
2327 		{
2328 			putline("", mci);
2329 			mci->mci_flags &= ~MCIF_INHEADER;
2330 		}
2331 
2332 		/* determine end of buffer; allow for short mailer lines */
2333 		buflim = &buf[sizeof buf - 1];
2334 		if (mci->mci_mailer->m_linelimit > 0 &&
2335 		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
2336 			buflim = &buf[mci->mci_mailer->m_linelimit - 1];
2337 
2338 		/* copy temp file to output with mapping */
2339 		ostate = OS_HEAD;
2340 		bp = buf;
2341 		pbp = peekbuf;
2342 		while (!ferror(mci->mci_out))
2343 		{
2344 			register char *xp;
2345 
2346 			if (pbp > peekbuf)
2347 				c = *--pbp;
2348 			else if ((c = getc(e->e_dfp)) == EOF)
2349 				break;
2350 			if (bitset(MCIF_7BIT, mci->mci_flags))
2351 				c &= 0x7f;
2352 			switch (ostate)
2353 			{
2354 			  case OS_HEAD:
2355 				if (c != '\r' && c != '\n' && bp < buflim)
2356 				{
2357 					*bp++ = c;
2358 					break;
2359 				}
2360 
2361 				/* check beginning of line for special cases */
2362 				*bp = '\0';
2363 				pos = 0;
2364 				padc = EOF;
2365 				if (buf[0] == 'F' &&
2366 				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
2367 				    strncmp(buf, "From ", 5) == 0)
2368 				{
2369 					padc = '>';
2370 				}
2371 				if (buf[0] == '-' && buf[1] == '-' &&
2372 				    separator != NULL)
2373 				{
2374 					/* possible separator */
2375 					int sl = strlen(separator);
2376 
2377 					if (strncmp(&buf[2], separator, sl) == 0)
2378 						padc = ' ';
2379 				}
2380 				if (buf[0] == '.' &&
2381 				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
2382 				{
2383 					padc = '.';
2384 				}
2385 
2386 				/* now copy out saved line */
2387 				if (TrafficLogFile != NULL)
2388 				{
2389 					fprintf(TrafficLogFile, "%05d >>> ", getpid());
2390 					if (padc != EOF)
2391 						putc(padc, TrafficLogFile);
2392 					for (xp = buf; xp < bp; xp++)
2393 						putc(*xp, TrafficLogFile);
2394 					if (c == '\n')
2395 						fputs(mci->mci_mailer->m_eol,
2396 						      TrafficLogFile);
2397 				}
2398 				if (padc != EOF)
2399 				{
2400 					putc(padc, mci->mci_out);
2401 					pos++;
2402 				}
2403 				for (xp = buf; xp < bp; xp++)
2404 					putc(*xp, mci->mci_out);
2405 				if (c == '\n')
2406 				{
2407 					fputs(mci->mci_mailer->m_eol,
2408 					      mci->mci_out);
2409 					pos = 0;
2410 				}
2411 				else
2412 				{
2413 					pos += bp - buf;
2414 					if (c != '\r')
2415 						*pbp++ = c;
2416 				}
2417 				bp = buf;
2418 
2419 				/* determine next state */
2420 				if (c == '\n')
2421 					ostate = OS_HEAD;
2422 				else if (c == '\r')
2423 					ostate = OS_CR;
2424 				else
2425 					ostate = OS_INLINE;
2426 				continue;
2427 
2428 			  case OS_CR:
2429 				if (c == '\n')
2430 				{
2431 					/* got CRLF */
2432 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2433 					if (TrafficLogFile != NULL)
2434 					{
2435 						fputs(mci->mci_mailer->m_eol,
2436 						      TrafficLogFile);
2437 					}
2438 					ostate = OS_HEAD;
2439 					continue;
2440 				}
2441 
2442 				/* had a naked carriage return */
2443 				*pbp++ = c;
2444 				c = '\r';
2445 				goto putch;
2446 
2447 			  case OS_INLINE:
2448 				if (c == '\r')
2449 				{
2450 					ostate = OS_CR;
2451 					continue;
2452 				}
2453 putch:
2454 				if (mci->mci_mailer->m_linelimit > 0 &&
2455 				    pos > mci->mci_mailer->m_linelimit &&
2456 				    c != '\n')
2457 				{
2458 					putc('!', mci->mci_out);
2459 					fputs(mci->mci_mailer->m_eol, mci->mci_out);
2460 					if (TrafficLogFile != NULL)
2461 					{
2462 						fprintf(TrafficLogFile, "!%s",
2463 							mci->mci_mailer->m_eol);
2464 					}
2465 					ostate = OS_HEAD;
2466 					*pbp++ = c;
2467 					continue;
2468 				}
2469 				if (TrafficLogFile != NULL)
2470 					putc(c, TrafficLogFile);
2471 				putc(c, mci->mci_out);
2472 				pos++;
2473 				ostate = c == '\n' ? OS_HEAD : OS_INLINE;
2474 				break;
2475 			}
2476 		}
2477 	}
2478 
2479 	if (ferror(e->e_dfp))
2480 	{
2481 		syserr("putbody: df%s: read error", e->e_id);
2482 		ExitStat = EX_IOERR;
2483 	}
2484 
2485 endofmessage:
2486 	/* some mailers want extra blank line at end of message */
2487 	if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
2488 	    buf[0] != '\0' && buf[0] != '\n')
2489 		putline("", mci);
2490 
2491 	(void) fflush(mci->mci_out);
2492 	if (ferror(mci->mci_out) && errno != EPIPE)
2493 	{
2494 		syserr("putbody: write error");
2495 		ExitStat = EX_IOERR;
2496 	}
2497 	errno = 0;
2498 }
2499 /*
2500 **  MAILFILE -- Send a message to a file.
2501 **
2502 **	If the file has the setuid/setgid bits set, but NO execute
2503 **	bits, sendmail will try to become the owner of that file
2504 **	rather than the real user.  Obviously, this only works if
2505 **	sendmail runs as root.
2506 **
2507 **	This could be done as a subordinate mailer, except that it
2508 **	is used implicitly to save messages in ~/dead.letter.  We
2509 **	view this as being sufficiently important as to include it
2510 **	here.  For example, if the system is dying, we shouldn't have
2511 **	to create another process plus some pipes to save the message.
2512 **
2513 **	Parameters:
2514 **		filename -- the name of the file to send to.
2515 **		ctladdr -- the controlling address header -- includes
2516 **			the userid/groupid to be when sending.
2517 **		sfflags -- flags for opening.
2518 **		e -- the current envelope.
2519 **
2520 **	Returns:
2521 **		The exit code associated with the operation.
2522 **
2523 **	Side Effects:
2524 **		none.
2525 */
2526 
2527 int
mailfile(filename,ctladdr,sfflags,e)2528 mailfile(filename, ctladdr, sfflags, e)
2529 	char *filename;
2530 	ADDRESS *ctladdr;
2531 	int sfflags;
2532 	register ENVELOPE *e;
2533 {
2534 	register FILE *f;
2535 	register int pid = -1;
2536 	int mode;
2537 
2538 	if (tTd(11, 1))
2539 	{
2540 		printf("mailfile %s\n  ctladdr=", filename);
2541 		printaddr(ctladdr, FALSE);
2542 	}
2543 
2544 	if (e->e_xfp != NULL)
2545 		fflush(e->e_xfp);
2546 
2547 	/*
2548 	**  Fork so we can change permissions here.
2549 	**	Note that we MUST use fork, not vfork, because of
2550 	**	the complications of calling subroutines, etc.
2551 	*/
2552 
2553 	DOFORK(fork);
2554 
2555 	if (pid < 0)
2556 		return (EX_OSERR);
2557 	else if (pid == 0)
2558 	{
2559 		/* child -- actually write to file */
2560 		struct stat stb;
2561 		struct stat fsb;
2562 		MCI mcibuf;
2563 		int oflags = O_WRONLY|O_APPEND;
2564 
2565 		if (e->e_lockfp != NULL)
2566 			(void) close(fileno(e->e_lockfp));
2567 
2568 		(void) setsignal(SIGINT, SIG_DFL);
2569 		(void) setsignal(SIGHUP, SIG_DFL);
2570 		(void) setsignal(SIGTERM, SIG_DFL);
2571 		(void) umask(OldUmask);
2572 		e->e_to = filename;
2573 		ExitStat = EX_OK;
2574 
2575 #ifdef HASLSTAT
2576 		if ((SafeFileEnv != NULL ? lstat(filename, &stb)
2577 					 : stat(filename, &stb)) < 0)
2578 #else
2579 		if (stat(filename, &stb) < 0)
2580 #endif
2581 		{
2582 			stb.st_mode = FileMode;
2583 			oflags |= O_CREAT|O_EXCL;
2584 		}
2585 		else if (bitset(0111, stb.st_mode) || stb.st_nlink != 1 ||
2586 			 (SafeFileEnv != NULL && !S_ISREG(stb.st_mode)))
2587 			exit(EX_CANTCREAT);
2588 		mode = stb.st_mode;
2589 
2590 		/* limit the errors to those actually caused in the child */
2591 		errno = 0;
2592 		ExitStat = EX_OK;
2593 
2594 		if (ctladdr != NULL || bitset(SFF_RUNASREALUID, sfflags))
2595 		{
2596 			/* ignore setuid and setgid bits */
2597 			mode &= ~(S_ISGID|S_ISUID);
2598 		}
2599 
2600 		/* we have to open the dfile BEFORE setuid */
2601 		if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
2602 		{
2603 			char *df = queuename(e, 'd');
2604 
2605 			e->e_dfp = fopen(df, "r");
2606 			if (e->e_dfp == NULL)
2607 			{
2608 				syserr("mailfile: Cannot open %s for %s from %s",
2609 					df, e->e_to, e->e_from.q_paddr);
2610 			}
2611 		}
2612 
2613 		if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
2614 		{
2615 			int i;
2616 
2617 			if (chroot(SafeFileEnv) < 0)
2618 			{
2619 				syserr("mailfile: Cannot chroot(%s)",
2620 					SafeFileEnv);
2621 				exit(EX_CANTCREAT);
2622 			}
2623 			i = strlen(SafeFileEnv);
2624 			if (strncmp(SafeFileEnv, filename, i) == 0)
2625 				filename += i;
2626 		}
2627 		if (chdir("/") < 0)
2628 			syserr("mailfile: cannot chdir(/)");
2629 
2630 		/* select a new user to run as */
2631 		if (!bitset(SFF_RUNASREALUID, sfflags))
2632 		{
2633 			if (bitset(S_ISUID, mode))
2634 			{
2635 				RealUserName = NULL;
2636 				RealUid = stb.st_uid;
2637 			}
2638 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
2639 			{
2640 				if (ctladdr->q_ruser != NULL)
2641 					RealUserName = ctladdr->q_ruser;
2642 				else
2643 					RealUserName = ctladdr->q_user;
2644 				RealUid = ctladdr->q_uid;
2645 			}
2646 			else if (FileMailer != NULL && FileMailer->m_uid != 0)
2647 			{
2648 				RealUserName = DefUser;
2649 				RealUid = FileMailer->m_uid;
2650 			}
2651 			else
2652 			{
2653 				RealUserName = DefUser;
2654 				RealUid = DefUid;
2655 			}
2656 
2657 			/* select a new group to run as */
2658 			if (bitset(S_ISGID, mode))
2659 				RealGid = stb.st_gid;
2660 			else if (ctladdr != NULL && ctladdr->q_uid != 0)
2661 				RealGid = ctladdr->q_gid;
2662 			else if (FileMailer != NULL && FileMailer->m_gid != 0)
2663 				RealGid = FileMailer->m_gid;
2664 			else
2665 				RealGid = DefGid;
2666 		}
2667 
2668 		/* last ditch */
2669 		if (!bitset(SFF_ROOTOK, sfflags))
2670 		{
2671 			if (RealUid == 0)
2672 				RealUid = DefUid;
2673 			if (RealGid == 0)
2674 				RealGid = DefGid;
2675 		}
2676 
2677 		/* now set the group and user ids */
2678 		endpwent();
2679 		if (RealUserName != NULL)
2680 			(void) initgroups(RealUserName, RealGid);
2681 		else
2682 			(void) setgid(RealGid);
2683 		(void) setuid(RealUid);
2684 
2685 		sfflags |= SFF_NOPATHCHECK;
2686 		sfflags &= ~SFF_OPENASROOT;
2687 		f = safefopen(filename, oflags, FileMode, sfflags);
2688 		if (f == NULL)
2689 		{
2690 			message("554 cannot open: %s", errstring(errno));
2691 			exit(EX_CANTCREAT);
2692 		}
2693 
2694 		bzero(&mcibuf, sizeof mcibuf);
2695 		mcibuf.mci_mailer = FileMailer;
2696 		mcibuf.mci_out = f;
2697 		if (bitnset(M_7BITS, FileMailer->m_flags))
2698 			mcibuf.mci_flags |= MCIF_7BIT;
2699 
2700 		putfromline(&mcibuf, e);
2701 		(*e->e_puthdr)(&mcibuf, e->e_header, e);
2702 		(*e->e_putbody)(&mcibuf, e, NULL);
2703 		putline("\n", &mcibuf);
2704 		if (ferror(f))
2705 		{
2706 			message("451 I/O error: %s", errstring(errno));
2707 			setstat(EX_IOERR);
2708 		}
2709 		(void) xfclose(f, "mailfile", filename);
2710 		(void) fflush(stdout);
2711 
2712 		/* reset ISUID & ISGID bits for paranoid systems */
2713 		(void) chmod(filename, (int) stb.st_mode);
2714 		exit(ExitStat);
2715 		/*NOTREACHED*/
2716 	}
2717 	else
2718 	{
2719 		/* parent -- wait for exit status */
2720 		int st;
2721 
2722 		st = waitfor(pid);
2723 		if (WIFEXITED(st))
2724 			return (WEXITSTATUS(st));
2725 		else
2726 		{
2727 			syserr("child died on signal %d", st);
2728 			return (EX_UNAVAILABLE);
2729 		}
2730 		/*NOTREACHED*/
2731 	}
2732 }
2733 /*
2734 **  HOSTSIGNATURE -- return the "signature" for a host.
2735 **
2736 **	The signature describes how we are going to send this -- it
2737 **	can be just the hostname (for non-Internet hosts) or can be
2738 **	an ordered list of MX hosts.
2739 **
2740 **	Parameters:
2741 **		m -- the mailer describing this host.
2742 **		host -- the host name.
2743 **		e -- the current envelope.
2744 **
2745 **	Returns:
2746 **		The signature for this host.
2747 **
2748 **	Side Effects:
2749 **		Can tweak the symbol table.
2750 */
2751 
2752 char *
hostsignature(m,host,e)2753 hostsignature(m, host, e)
2754 	register MAILER *m;
2755 	char *host;
2756 	ENVELOPE *e;
2757 {
2758 	register char *p;
2759 	register STAB *s;
2760 	int i;
2761 	int len;
2762 #if NAMED_BIND
2763 	int nmx;
2764 	auto int rcode;
2765 	char *hp;
2766 	char *endp;
2767 	int oldoptions = _res.options;
2768 	char *mxhosts[MAXMXHOSTS + 1];
2769 #endif
2770 
2771 	/*
2772 	**  Check to see if this uses IPC -- if not, it can't have MX records.
2773 	*/
2774 
2775 	p = m->m_mailer;
2776 	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
2777 	{
2778 		/* just an ordinary mailer */
2779 		return host;
2780 	}
2781 
2782 	/*
2783 	**  Look it up in the symbol table.
2784 	*/
2785 
2786 	s = stab(host, ST_HOSTSIG, ST_ENTER);
2787 	if (s->s_hostsig != NULL)
2788 		return s->s_hostsig;
2789 
2790 	/*
2791 	**  Not already there -- create a signature.
2792 	*/
2793 
2794 #if NAMED_BIND
2795 	if (ConfigLevel < 2)
2796 		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
2797 
2798 	for (hp = host; hp != NULL; hp = endp)
2799 	{
2800 		endp = strchr(hp, ':');
2801 		if (endp != NULL)
2802 			*endp = '\0';
2803 
2804 		nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
2805 
2806 		if (nmx <= 0)
2807 		{
2808 			register MCI *mci;
2809 
2810 			/* update the connection info for this host */
2811 			mci = mci_get(hp, m);
2812 			mci->mci_exitstat = rcode;
2813 			mci->mci_errno = errno;
2814 			mci->mci_herrno = h_errno;
2815 
2816 			/* and return the original host name as the signature */
2817 			nmx = 1;
2818 			mxhosts[0] = hp;
2819 		}
2820 
2821 		len = 0;
2822 		for (i = 0; i < nmx; i++)
2823 		{
2824 			len += strlen(mxhosts[i]) + 1;
2825 		}
2826 		if (s->s_hostsig != NULL)
2827 			len += strlen(s->s_hostsig) + 1;
2828 		p = xalloc(len);
2829 		if (s->s_hostsig != NULL)
2830 		{
2831 			(void) strcpy(p, s->s_hostsig);
2832 			free(s->s_hostsig);
2833 			s->s_hostsig = p;
2834 			p += strlen(p);
2835 			*p++ = ':';
2836 		}
2837 		else
2838 			s->s_hostsig = p;
2839 		for (i = 0; i < nmx; i++)
2840 		{
2841 			if (i != 0)
2842 				*p++ = ':';
2843 			strcpy(p, mxhosts[i]);
2844 			p += strlen(p);
2845 		}
2846 		if (endp != NULL)
2847 			*endp++ = ':';
2848 	}
2849 	makelower(s->s_hostsig);
2850 	if (ConfigLevel < 2)
2851 		_res.options = oldoptions;
2852 #else
2853 	/* not using BIND -- the signature is just the host name */
2854 	s->s_hostsig = host;
2855 #endif
2856 	if (tTd(17, 1))
2857 		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
2858 	return s->s_hostsig;
2859 }
2860