1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 
6 SCCSID(@(#)deliver.c	3.97		08/08/82);
7 
8 /*
9 **  DELIVER -- Deliver a message to a list of addresses.
10 **
11 **	This routine delivers to everyone on the same host as the
12 **	user on the head of the list.  It is clever about mailers
13 **	that don't handle multiple users.  It is NOT guaranteed
14 **	that it will deliver to all these addresses however -- so
15 **	deliver should be called once for each address on the
16 **	list.
17 **
18 **	Parameters:
19 **		firstto -- head of the address list to deliver to.
20 **
21 **	Returns:
22 **		zero -- successfully delivered.
23 **		else -- some failure, see ExitStat for more info.
24 **
25 **	Side Effects:
26 **		The standard input is passed off to someone.
27 */
28 
29 deliver(firstto)
30 	ADDRESS *firstto;
31 {
32 	char *host;			/* host being sent to */
33 	char *user;			/* user being sent to */
34 	char **pvp;
35 	register char **mvp;
36 	register char *p;
37 	register struct mailer *m;	/* mailer for this recipient */
38 	register int i;
39 	extern bool checkcompat();
40 	char *pv[MAXPV+1];
41 	char tobuf[MAXLINE];		/* text line of to people */
42 	char buf[MAXNAME];
43 	ADDRESS *ctladdr;
44 	extern ADDRESS *getctladdr();
45 	char tfrombuf[MAXNAME];		/* translated from person */
46 	extern char **prescan();
47 	register ADDRESS *to = firstto;
48 	bool clever = FALSE;		/* running user smtp to this mailer */
49 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
50 	bool notopen = TRUE;		/* set if connection not quite open */
51 
52 	errno = 0;
53 	if (bitset(QDONTSEND, to->q_flags))
54 		return (0);
55 
56 	m = to->q_mailer;
57 	host = to->q_host;
58 
59 # ifdef DEBUG
60 	if (tTd(10, 1))
61 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
62 			m->m_mno, host, to->q_user);
63 # endif DEBUG
64 
65 	/*
66 	**  If this mailer is expensive, and if we don't want to make
67 	**  connections now, just mark these addresses and return.
68 	**	This is useful if we want to batch connections to
69 	**	reduce load.  This will cause the messages to be
70 	**	queued up, and a daemon will come along to send the
71 	**	messages later.
72 	**		This should be on a per-mailer basis.
73 	*/
74 
75 	if (NoConnect && !QueueRun && bitset(M_EXPENSIVE, m->m_flags))
76 	{
77 		for (; to != NULL; to = to->q_next)
78 			if (!bitset(QDONTSEND, to->q_flags))
79 				to->q_flags |= QQUEUEUP|QDONTSEND;
80 		return (0);
81 	}
82 
83 	/*
84 	**  Do initial argv setup.
85 	**	Insert the mailer name.  Notice that $x expansion is
86 	**	NOT done on the mailer name.  Then, if the mailer has
87 	**	a picky -f flag, we insert it as appropriate.  This
88 	**	code does not check for 'pv' overflow; this places a
89 	**	manifest lower limit of 4 for MAXPV.
90 	**		We rewrite the from address here, being careful
91 	**		to also rewrite it again using ruleset 2 to
92 	**		eliminate redundancies.
93 	*/
94 
95 	/* rewrite from address, using rewriting rules */
96 	expand(m->m_from, buf, &buf[sizeof buf - 1], CurEnv);
97 	mvp = prescan(buf, '\0');
98 	if (mvp == NULL)
99 	{
100 		syserr("bad mailer from translate \"%s\"", buf);
101 		return (EX_SOFTWARE);
102 	}
103 	rewrite(mvp, 2);
104 	cataddr(mvp, tfrombuf, sizeof tfrombuf);
105 
106 	define('g', tfrombuf);		/* translated sender address */
107 	define('h', host);		/* to host */
108 	Errors = 0;
109 	pvp = pv;
110 	*pvp++ = m->m_argv[0];
111 
112 	/* insert -f or -r flag as appropriate */
113 	if (bitset(M_FOPT|M_ROPT, m->m_flags) && FromFlag)
114 	{
115 		if (bitset(M_FOPT, m->m_flags))
116 			*pvp++ = "-f";
117 		else
118 			*pvp++ = "-r";
119 		expand("$g", buf, &buf[sizeof buf - 1], CurEnv);
120 		*pvp++ = newstr(buf);
121 	}
122 
123 	/*
124 	**  Append the other fixed parts of the argv.  These run
125 	**  up to the first entry containing "$u".  There can only
126 	**  be one of these, and there are only a few more slots
127 	**  in the pv after it.
128 	*/
129 
130 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
131 	{
132 		while ((p = index(p, '$')) != NULL)
133 			if (*++p == 'u')
134 				break;
135 		if (p != NULL)
136 			break;
137 
138 		/* this entry is safe -- go ahead and process it */
139 		expand(*mvp, buf, &buf[sizeof buf - 1], CurEnv);
140 		*pvp++ = newstr(buf);
141 		if (pvp >= &pv[MAXPV - 3])
142 		{
143 			syserr("Too many parameters to %s before $u", pv[0]);
144 			return (-1);
145 		}
146 	}
147 
148 	/*
149 	**  If we have no substitution for the user name in the argument
150 	**  list, we know that we must supply the names otherwise -- and
151 	**  SMTP is the answer!!
152 	*/
153 
154 	if (*mvp == NULL)
155 	{
156 		/* running SMTP */
157 # ifdef SMTP
158 		clever = TRUE;
159 		*pvp = NULL;
160 # else SMTP
161 		/* oops!  we don't implement SMTP */
162 		syserr("SMTP style mailer");
163 		return (EX_SOFTWARE);
164 # endif SMTP
165 	}
166 
167 	/*
168 	**  At this point *mvp points to the argument with $u.  We
169 	**  run through our address list and append all the addresses
170 	**  we can.  If we run out of space, do not fret!  We can
171 	**  always send another copy later.
172 	*/
173 
174 	tobuf[0] = '\0';
175 	CurEnv->e_to = tobuf;
176 	ctladdr = NULL;
177 	for (; to != NULL; to = to->q_next)
178 	{
179 		/* avoid sending multiple recipients to dumb mailers */
180 		if (tobuf[0] != '\0' && !bitset(M_MUSER, m->m_flags))
181 			break;
182 
183 		/* if already sent or not for this host, don't send */
184 		if (bitset(QDONTSEND, to->q_flags) ||
185 		    strcmp(to->q_host, host) != 0 ||
186 		    to->q_mailer != firstto->q_mailer)
187 			continue;
188 
189 # ifdef DEBUG
190 		if (tTd(10, 1))
191 		{
192 			printf("\nsend to ");
193 			printaddr(to, FALSE);
194 		}
195 # endif DEBUG
196 
197 		/* compute effective uid/gid when sending */
198 		if (to->q_mailer == ProgMailer)
199 			ctladdr = getctladdr(to);
200 
201 		user = to->q_user;
202 		CurEnv->e_to = to->q_paddr;
203 		to->q_flags |= QDONTSEND;
204 
205 		/*
206 		**  Check to see that these people are allowed to
207 		**  talk to each other.
208 		*/
209 
210 		if (!checkcompat(to))
211 		{
212 			giveresponse(EX_UNAVAILABLE, TRUE, m);
213 			continue;
214 		}
215 
216 		/*
217 		**  Strip quote bits from names if the mailer is dumb
218 		**	about them.
219 		*/
220 
221 		if (bitset(M_STRIPQ, m->m_flags))
222 		{
223 			stripquotes(user, TRUE);
224 			stripquotes(host, TRUE);
225 		}
226 		else
227 		{
228 			stripquotes(user, FALSE);
229 			stripquotes(host, FALSE);
230 		}
231 
232 		/*
233 		**  Do initial connection setup if needed.
234 		*/
235 
236 		if (notopen)
237 		{
238 			message(Arpa_Info, "Connecting to %s.%s...", host, m->m_name);
239 # ifdef SMTP
240 			if (clever)
241 			{
242 				/* send the initial SMTP protocol */
243 				i = smtpinit(m, pv, (ADDRESS *) NULL);
244 			}
245 # ifdef SMTP
246 			notopen = FALSE;
247 		}
248 
249 		/*
250 		**  Pass it to the other host if we are running SMTP.
251 		*/
252 
253 		if (clever)
254 		{
255 # ifdef SMTP
256 			i = smtprcpt(to);
257 			if (i != EX_OK)
258 			{
259 # ifdef QUEUE
260 				if (i == EX_TEMPFAIL)
261 					to->q_flags |= QQUEUEUP;
262 				else
263 # endif QUEUE
264 					to->q_flags |= QBADADDR;
265 				giveresponse(i, TRUE, m);
266 			}
267 # else SMTP
268 			syserr("trying to be clever");
269 # endif SMTP
270 		}
271 
272 		/*
273 		**  If an error message has already been given, don't
274 		**	bother to send to this address.
275 		**
276 		**	>>>>>>>>>> This clause assumes that the local mailer
277 		**	>> NOTE >> cannot do any further aliasing; that
278 		**	>>>>>>>>>> function is subsumed by sendmail.
279 		*/
280 
281 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
282 			continue;
283 
284 		/* save statistics.... */
285 		Stat.stat_nt[to->q_mailer->m_mno]++;
286 		Stat.stat_bt[to->q_mailer->m_mno] += kbytes(CurEnv->e_msgsize);
287 
288 		/*
289 		**  See if this user name is "special".
290 		**	If the user name has a slash in it, assume that this
291 		**	is a file -- send it off without further ado.  Note
292 		**	that this type of addresses is not processed along
293 		**	with the others, so we fudge on the To person.
294 		*/
295 
296 		if (m == LocalMailer)
297 		{
298 			if (user[0] == '/')
299 			{
300 				i = mailfile(user, getctladdr(to));
301 				giveresponse(i, TRUE, m);
302 				continue;
303 			}
304 		}
305 
306 		/*
307 		**  Address is verified -- add this user to mailer
308 		**  argv, and add it to the print list of recipients.
309 		*/
310 
311 		/* link together the chain of recipients */
312 		to->q_tchain = tochain;
313 		tochain = to;
314 
315 		/* create list of users for error messages */
316 		if (tobuf[0] != '\0')
317 			(void) strcat(tobuf, ",");
318 		(void) strcat(tobuf, to->q_paddr);
319 		define('u', user);		/* to user */
320 		define('z', to->q_home);	/* user's home */
321 
322 		/*
323 		**  Expand out this user into argument list.
324 		*/
325 
326 		if (!clever)
327 		{
328 			expand(*mvp, buf, &buf[sizeof buf - 1], CurEnv);
329 			*pvp++ = newstr(buf);
330 			if (pvp >= &pv[MAXPV - 2])
331 			{
332 				/* allow some space for trailing parms */
333 				break;
334 			}
335 		}
336 	}
337 
338 	/* see if any addresses still exist */
339 	if (tobuf[0] == '\0')
340 	{
341 # ifdef SMTP
342 		if (clever)
343 			smtpquit(pv[0], FALSE);
344 # endif SMTP
345 		define('g', (char *) NULL);
346 		return (0);
347 	}
348 
349 	/* print out messages as full list */
350 	CurEnv->e_to = tobuf;
351 
352 	/*
353 	**  Fill out any parameters after the $u parameter.
354 	*/
355 
356 	while (!clever && *++mvp != NULL)
357 	{
358 		expand(*mvp, buf, &buf[sizeof buf - 1], CurEnv);
359 		*pvp++ = newstr(buf);
360 		if (pvp >= &pv[MAXPV])
361 			syserr("deliver: pv overflow after $u for %s", pv[0]);
362 	}
363 	*pvp++ = NULL;
364 
365 	/*
366 	**  Call the mailer.
367 	**	The argument vector gets built, pipes
368 	**	are created as necessary, and we fork & exec as
369 	**	appropriate.
370 	**	If we are running SMTP, we just need to clean up.
371 	*/
372 
373 	if (ctladdr == NULL)
374 		ctladdr = &CurEnv->e_from;
375 # ifdef SMTP
376 	if (clever)
377 	{
378 		i = smtpfinish(m, CurEnv);
379 		smtpquit(pv[0], TRUE);
380 	}
381 	else
382 # endif SMTP
383 		i = sendoff(m, pv, ctladdr);
384 
385 	/*
386 	**  If we got a temporary failure, arrange to queue the
387 	**  addressees.
388 	*/
389 
390 # ifdef QUEUE
391 	if (i == EX_TEMPFAIL)
392 	{
393 		for (to = tochain; to != NULL; to = to->q_tchain)
394 			to->q_flags |= QQUEUEUP;
395 	}
396 # endif QUEUE
397 
398 	errno = 0;
399 	define('g', (char *) NULL);
400 	return (i);
401 }
402 /*
403 **  DOFORK -- do a fork, retrying a couple of times on failure.
404 **
405 **	This MUST be a macro, since after a vfork we are running
406 **	two processes on the same stack!!!
407 **
408 **	Parameters:
409 **		none.
410 **
411 **	Returns:
412 **		From a macro???  You've got to be kidding!
413 **
414 **	Side Effects:
415 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
416 **			pid of child in parent, zero in child.
417 **			-1 on unrecoverable error.
418 **
419 **	Notes:
420 **		I'm awfully sorry this looks so awful.  That's
421 **		vfork for you.....
422 */
423 
424 # define NFORKTRIES	5
425 # ifdef VFORK
426 # define XFORK	vfork
427 # else VFORK
428 # define XFORK	fork
429 # endif VFORK
430 
431 # define DOFORK(fORKfN) \
432 {\
433 	register int i;\
434 \
435 	for (i = NFORKTRIES; i-- > 0; )\
436 	{\
437 		pid = fORKfN();\
438 		if (pid >= 0)\
439 			break;\
440 		sleep(NFORKTRIES - i);\
441 	}\
442 }
443 /*
444 **  DOFORK -- simple fork interface to DOFORK.
445 **
446 **	Parameters:
447 **		none.
448 **
449 **	Returns:
450 **		pid of child in parent.
451 **		zero in child.
452 **		-1 on error.
453 **
454 **	Side Effects:
455 **		returns twice, once in parent and once in child.
456 */
457 
458 dofork()
459 {
460 	register int pid;
461 
462 	DOFORK(fork);
463 	return (pid);
464 }
465 /*
466 **  SENDOFF -- send off call to mailer & collect response.
467 **
468 **	Parameters:
469 **		m -- mailer descriptor.
470 **		pvp -- parameter vector to send to it.
471 **		ctladdr -- an address pointer controlling the
472 **			user/groupid etc. of the mailer.
473 **
474 **	Returns:
475 **		exit status of mailer.
476 **
477 **	Side Effects:
478 **		none.
479 */
480 
481 sendoff(m, pvp, ctladdr)
482 	struct mailer *m;
483 	char **pvp;
484 	ADDRESS *ctladdr;
485 {
486 	auto FILE *mfile;
487 	auto FILE *rfile;
488 	register int i;
489 	int pid;
490 
491 	/*
492 	**  Create connection to mailer.
493 	*/
494 
495 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
496 	if (pid < 0)
497 		return (-1);
498 
499 	/*
500 	**  Format and send message.
501 	*/
502 
503 	(void) signal(SIGPIPE, SIG_IGN);
504 	putfromline(mfile, m);
505 	(*CurEnv->e_puthdr)(mfile, m, CurEnv);
506 	fprintf(mfile, "\n");
507 	(*CurEnv->e_putbody)(mfile, m, FALSE);
508 	(void) fclose(mfile);
509 
510 	i = endmailer(pid, pvp[0]);
511 	giveresponse(i, TRUE, m);
512 
513 	/* arrange a return receipt if requested */
514 	if (CurEnv->e_retreceipt && bitset(M_LOCAL, m->m_flags) && i == EX_OK)
515 	{
516 		CurEnv->e_sendreceipt = TRUE;
517 		fprintf(Xscript, "%s... successfully delivered\n", CurEnv->e_to);
518 		/* do we want to send back more info? */
519 	}
520 
521 	return (i);
522 }
523 /*
524 **  ENDMAILER -- Wait for mailer to terminate.
525 **
526 **	We should never get fatal errors (e.g., segmentation
527 **	violation), so we report those specially.  For other
528 **	errors, we choose a status message (into statmsg),
529 **	and if it represents an error, we print it.
530 **
531 **	Parameters:
532 **		pid -- pid of mailer.
533 **		name -- name of mailer (for error messages).
534 **
535 **	Returns:
536 **		exit code of mailer.
537 **
538 **	Side Effects:
539 **		none.
540 */
541 
542 endmailer(pid, name)
543 	int pid;
544 	char *name;
545 {
546 	register int i;
547 	auto int st;
548 
549 	/* in the IPC case there is nothing to wait for */
550 	if (pid == 0)
551 		return (EX_OK);
552 
553 	/* wait for the mailer process to die and collect status */
554 	while ((i = wait(&st)) > 0 && i != pid)
555 		continue;
556 	if (i < 0)
557 	{
558 		syserr("wait");
559 		return (-1);
560 	}
561 
562 	/* see if it died a horrid death */
563 	if ((st & 0377) != 0)
564 	{
565 		syserr("%s: stat %o", name, st);
566 		ExitStat = EX_UNAVAILABLE;
567 		return (-1);
568 	}
569 
570 	/* normal death -- return status */
571 	i = (st >> 8) & 0377;
572 	return (i);
573 }
574 /*
575 **  OPENMAILER -- open connection to mailer.
576 **
577 **	Parameters:
578 **		m -- mailer descriptor.
579 **		pvp -- parameter vector to pass to mailer.
580 **		ctladdr -- controlling address for user.
581 **		clever -- create a full duplex connection.
582 **		pmfile -- pointer to mfile (to mailer) connection.
583 **		prfile -- pointer to rfile (from mailer) connection.
584 **
585 **	Returns:
586 **		pid of mailer ( > 0 ).
587 **		-1 on error.
588 **		zero on an IPC connection.
589 **
590 **	Side Effects:
591 **		creates a mailer in a subprocess.
592 */
593 
594 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
595 	struct mailer *m;
596 	char **pvp;
597 	ADDRESS *ctladdr;
598 	bool clever;
599 	FILE **pmfile;
600 	FILE **prfile;
601 {
602 	int pid;
603 	int mpvect[2];
604 	int rpvect[2];
605 	FILE *mfile;
606 	FILE *rfile;
607 	extern FILE *fdopen();
608 
609 # ifdef DEBUG
610 	if (tTd(11, 1))
611 	{
612 		printf("openmailer:\n");
613 		printav(pvp);
614 	}
615 # endif DEBUG
616 	errno = 0;
617 
618 # ifdef DAEMON
619 	/*
620 	**  Deal with the special case of mail handled through an IPC
621 	**  connection.
622 	**	In this case we don't actually fork.  We must be
623 	**	running SMTP for this to work.  We will return a
624 	**	zero pid to indicate that we are running IPC.
625 	*/
626 
627 	if (strcmp(m->m_mailer, "[IPC]") == 0)
628 	{
629 		register int i;
630 		register u_short port;
631 
632 		if (!clever)
633 			syserr("non-clever IPC");
634 		if (pvp[2] != NULL)
635 			port = atoi(pvp[2]);
636 		else
637 			port = 0;
638 		i = makeconnection(pvp[1], port, pmfile, prfile);
639 		if (i != EX_OK)
640 		{
641 			ExitStat = i;
642 			return (-1);
643 		}
644 		else
645 			return (0);
646 	}
647 # endif DAEMON
648 
649 	/* create a pipe to shove the mail through */
650 	if (pipe(mpvect) < 0)
651 	{
652 		syserr("pipe (to mailer)");
653 		return (-1);
654 	}
655 
656 # ifdef SMTP
657 	/* if this mailer speaks smtp, create a return pipe */
658 	if (clever && pipe(rpvect) < 0)
659 	{
660 		syserr("pipe (from mailer)");
661 		(void) close(mpvect[0]);
662 		(void) close(mpvect[1]);
663 		return (-1);
664 	}
665 # endif SMTP
666 
667 	/*
668 	**  Actually fork the mailer process.
669 	**	DOFORK is clever about retrying.
670 	*/
671 
672 	(void) fflush(Xscript);				/* for debugging */
673 	DOFORK(XFORK);
674 	/* pid is set by DOFORK */
675 	if (pid < 0)
676 	{
677 		/* failure */
678 		syserr("Cannot fork");
679 		(void) close(mpvect[0]);
680 		(void) close(mpvect[1]);
681 		if (clever)
682 		{
683 			(void) close(rpvect[0]);
684 			(void) close(rpvect[1]);
685 		}
686 		return (-1);
687 	}
688 	else if (pid == 0)
689 	{
690 		/* child -- set up input & exec mailer */
691 		/* make diagnostic output be standard output */
692 		(void) signal(SIGINT, SIG_IGN);
693 		(void) signal(SIGHUP, SIG_IGN);
694 		(void) signal(SIGTERM, SIG_DFL);
695 
696 		/* arrange to filter standard & diag output of command */
697 		if (clever)
698 		{
699 			(void) close(rpvect[0]);
700 			(void) close(1);
701 			(void) dup(rpvect[1]);
702 			(void) close(rpvect[1]);
703 		}
704 		else if (OutChannel != stdout)
705 		{
706 			(void) close(1);
707 			(void) dup(fileno(OutChannel));
708 		}
709 		(void) close(2);
710 		(void) dup(1);
711 
712 		/* arrange to get standard input */
713 		(void) close(mpvect[1]);
714 		(void) close(0);
715 		if (dup(mpvect[0]) < 0)
716 		{
717 			syserr("Cannot dup to zero!");
718 			_exit(EX_OSERR);
719 		}
720 		(void) close(mpvect[0]);
721 		if (!bitset(M_RESTR, m->m_flags))
722 		{
723 			if (ctladdr->q_uid == 0)
724 			{
725 				(void) setgid(DefGid);
726 				(void) setuid(DefUid);
727 			}
728 			else
729 			{
730 				(void) setgid(ctladdr->q_gid);
731 				(void) setuid(ctladdr->q_uid);
732 			}
733 		}
734 # ifndef VFORK
735 		/*
736 		**  We have to be careful with vfork - we can't mung up the
737 		**  memory but we don't want the mailer to inherit any extra
738 		**  open files.  Chances are the mailer won't
739 		**  care about an extra file, but then again you never know.
740 		**  Actually, we would like to close(fileno(pwf)), but it's
741 		**  declared static so we can't.  But if we fclose(pwf), which
742 		**  is what endpwent does, it closes it in the parent too and
743 		**  the next getpwnam will be slower.  If you have a weird
744 		**  mailer that chokes on the extra file you should do the
745 		**  endpwent().
746 		**
747 		**  Similar comments apply to log.  However, openlog is
748 		**  clever enough to set the FIOCLEX mode on the file,
749 		**  so it will be closed automatically on the exec.
750 		*/
751 
752 		endpwent();
753 # ifdef LOG
754 		closelog();
755 # endif LOG
756 # endif VFORK
757 
758 		/* try to execute the mailer */
759 		execv(m->m_mailer, pvp);
760 
761 		/* syserr fails because log is closed */
762 		/* syserr("Cannot exec %s", m->m_mailer); */
763 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
764 		(void) fflush(stdout);
765 		_exit(EX_UNAVAILABLE);
766 	}
767 
768 	/*
769 	**  Set up return value.
770 	*/
771 
772 	(void) close(mpvect[0]);
773 	mfile = fdopen(mpvect[1], "w");
774 	if (clever)
775 	{
776 		(void) close(rpvect[1]);
777 		rfile = fdopen(rpvect[0], "r");
778 	}
779 
780 	*pmfile = mfile;
781 	*prfile = rfile;
782 
783 	return (pid);
784 }
785 /*
786 **  GIVERESPONSE -- Interpret an error response from a mailer
787 **
788 **	Parameters:
789 **		stat -- the status code from the mailer (high byte
790 **			only; core dumps must have been taken care of
791 **			already).
792 **		force -- if set, force an error message output, even
793 **			if the mailer seems to like to print its own
794 **			messages.
795 **		m -- the mailer descriptor for this mailer.
796 **
797 **	Returns:
798 **		none.
799 **
800 **	Side Effects:
801 **		Errors may be incremented.
802 **		ExitStat may be set.
803 */
804 
805 giveresponse(stat, force, m)
806 	int stat;
807 	bool force;
808 	register struct mailer *m;
809 {
810 	register char *statmsg;
811 	extern char *SysExMsg[];
812 	register int i;
813 	extern int N_SysEx;
814 	char buf[30];
815 
816 	/*
817 	**  Compute status message from code.
818 	*/
819 
820 	i = stat - EX__BASE;
821 	if (i < 0 || i > N_SysEx)
822 		statmsg = NULL;
823 	else
824 		statmsg = SysExMsg[i];
825 	if (stat == 0)
826 	{
827 		if (bitset(M_LOCAL, m->m_flags))
828 			statmsg = "delivered";
829 		else
830 			statmsg = "queued";
831 		message(Arpa_Info, statmsg);
832 	}
833 # ifdef QUEUE
834 	else if (stat == EX_TEMPFAIL)
835 	{
836 		message(Arpa_Info, "transmission deferred");
837 	}
838 # endif QUEUE
839 	else
840 	{
841 		Errors++;
842 		FatalErrors = TRUE;
843 		if (statmsg == NULL && m->m_badstat != 0)
844 		{
845 			stat = m->m_badstat;
846 			i = stat - EX__BASE;
847 # ifdef DEBUG
848 			if (i < 0 || i >= N_SysEx)
849 				syserr("Bad m_badstat %d", stat);
850 			else
851 # endif DEBUG
852 				statmsg = SysExMsg[i];
853 		}
854 		if (statmsg == NULL)
855 			usrerr("unknown mailer response %d", stat);
856 		else if (force || !bitset(M_QUIET, m->m_flags) || Verbose)
857 			usrerr("%s", statmsg);
858 		else
859 			fprintf(Xscript, "%s\n", statmsg);
860 	}
861 
862 	/*
863 	**  Final cleanup.
864 	**	Log a record of the transaction.  Compute the new
865 	**	ExitStat -- if we already had an error, stick with
866 	**	that.
867 	*/
868 
869 	if (statmsg == NULL)
870 	{
871 		(void) sprintf(buf, "error %d", stat);
872 		statmsg = buf;
873 	}
874 
875 # ifdef LOG
876 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
877 		syslog(LOG_INFO, "%s: to=%s, stat=%s", MsgId, CurEnv->e_to, statmsg);
878 # endif LOG
879 # ifdef QUEUE
880 	if (stat != EX_TEMPFAIL)
881 # endif QUEUE
882 		setstat(stat);
883 }
884 /*
885 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
886 **
887 **	This can be made an arbitrary message separator by changing $l
888 **
889 **	One of the ugliest hacks seen by human eyes is
890 **	contained herein: UUCP wants those stupid
891 **	"remote from <host>" lines.  Why oh why does a
892 **	well-meaning programmer such as myself have to
893 **	deal with this kind of antique garbage????
894 **
895 **	Parameters:
896 **		fp -- the file to output to.
897 **		m -- the mailer describing this entry.
898 **
899 **	Returns:
900 **		none
901 **
902 **	Side Effects:
903 **		outputs some text to fp.
904 */
905 
906 putfromline(fp, m)
907 	register FILE *fp;
908 	register MAILER *m;
909 {
910 	char buf[MAXLINE];
911 
912 	if (bitset(M_NHDR, m->m_flags))
913 		return;
914 
915 # ifdef UGLYUUCP
916 	if (bitset(M_UGLYUUCP, m->m_flags))
917 	{
918 		extern char *macvalue();
919 		char *sys = macvalue('g');
920 		char *bang = index(sys, '!');
921 
922 		if (bang == NULL)
923 			syserr("No ! in UUCP! (%s)", sys);
924 		else
925 			*bang = '\0';
926 		expand("From $f  $d remote from $g\n", buf,
927 				&buf[sizeof buf - 1], CurEnv);
928 		*bang = '!';
929 	}
930 	else
931 # endif UGLYUUCP
932 		expand("$l\n", buf, &buf[sizeof buf - 1], CurEnv);
933 	putline(buf, fp, bitset(M_FULLSMTP, m->m_flags));
934 }
935 /*
936 **  PUTHEADER -- put the header part of a message from the in-core copy
937 **
938 **	Parameters:
939 **		fp -- file to put it on.
940 **		m -- mailer to use.
941 **		e -- envelope to use.
942 **
943 **	Returns:
944 **		none.
945 **
946 **	Side Effects:
947 **		none.
948 */
949 
950 putheader(fp, m, e)
951 	register FILE *fp;
952 	register struct mailer *m;
953 	register ENVELOPE *e;
954 {
955 	char buf[BUFSIZ];
956 	register HDR *h;
957 	extern char *arpadate();
958 	extern char *capitalize();
959 	extern char *hvalue();
960 	extern bool samefrom();
961 	char *of_line;
962 	char obuf[MAXLINE];
963 	register char *obp;
964 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
965 
966 	of_line = hvalue("original-from");
967 	for (h = e->e_header; h != NULL; h = h->h_link)
968 	{
969 		register char *p;
970 		char *origfrom = e->e_origfrom;
971 		bool nooutput;
972 
973 		nooutput = FALSE;
974 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
975 			nooutput = TRUE;
976 
977 		/* use From: line from message if generated is the same */
978 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
979 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
980 		{
981 			p = origfrom;
982 			origfrom = NULL;
983 		}
984 		else if (bitset(H_DEFAULT, h->h_flags))
985 		{
986 			/* macro expand value if generated internally */
987 			expand(h->h_value, buf, &buf[sizeof buf], e);
988 			p = buf;
989 		}
990 		else if (bitset(H_ADDR, h->h_flags))
991 		{
992 			register int opos;
993 			bool firstone = TRUE;
994 
995 			/*
996 			**  Output the address list translated by the
997 			**  mailer and with commas.
998 			*/
999 
1000 			p = h->h_value;
1001 			if (p == NULL || *p == '\0' || nooutput)
1002 				continue;
1003 			obp = obuf;
1004 			(void) sprintf(obp, "%s: ", capitalize(h->h_field));
1005 			opos = strlen(h->h_field) + 2;
1006 			obp += opos;
1007 
1008 			/*
1009 			**  Run through the list of values.
1010 			*/
1011 
1012 			while (*p != '\0')
1013 			{
1014 				register char *name;
1015 				extern char *remotename();
1016 				char savechar;
1017 
1018 				/*
1019 				**  Find the end of the name.  New style names
1020 				**  end with a comma, old style names end with
1021 				**  a space character.  However, spaces do not
1022 				**  necessarily delimit an old-style name -- at
1023 				**  signs mean keep going.
1024 				*/
1025 
1026 				/* clean up the leading trash in source */
1027 				while (*p != '\0' && (isspace(*p) || *p == ','))
1028 					p++;
1029 				name = p;
1030 
1031 				/* find end of name */
1032 				while (*p != '\0' && *p != ',')
1033 				{
1034 					extern bool isatword();
1035 					char *oldp;
1036 
1037 					if (!e->e_oldstyle || !isspace(*p))
1038 					{
1039 						p++;
1040 						continue;
1041 					}
1042 
1043 					/* look to see if we have an at sign */
1044 					oldp = p;
1045 					while (*p != '\0' && isspace(*p))
1046 						p++;
1047 
1048 					if (*p != '@' && !isatword(p))
1049 					{
1050 						p = oldp;
1051 						break;
1052 					}
1053 					p += *p == '@' ? 1 : 2;
1054 					while (*p != '\0' && isspace(*p))
1055 						p++;
1056 				}
1057 				/* at the end of one complete name */
1058 
1059 				/* strip off trailing white space */
1060 				while (p >= name && (isspace(*p) || *p == ','))
1061 					p--;
1062 				if (++p == name)
1063 					continue;
1064 				savechar = *p;
1065 				*p = '\0';
1066 
1067 				/* translate the name to be relative */
1068 				name = remotename(name, m, FALSE);
1069 				if (*name == '\0')
1070 				{
1071 					*p = savechar;
1072 					continue;
1073 				}
1074 
1075 				/* output the name with nice formatting */
1076 				opos += strlen(name);
1077 				if (!firstone)
1078 					opos += 2;
1079 				if (opos > 78 && !firstone)
1080 				{
1081 					(void) sprintf(obp, ",\n");
1082 					putline(obuf, fp, fullsmtp);
1083 					obp = obuf;
1084 					(void) sprintf(obp, "        ");
1085 					obp += strlen(obp);
1086 					opos = 8 + strlen(name);
1087 				}
1088 				else if (!firstone)
1089 				{
1090 					(void) sprintf(obp, ", ");
1091 					obp += 2;
1092 				}
1093 				(void) sprintf(obp, "%s", name);
1094 				obp += strlen(obp);
1095 				firstone = FALSE;
1096 				*p = savechar;
1097 			}
1098 			(void) strcpy(obp, "\n");
1099 			putline(obuf, fp, fullsmtp);
1100 			nooutput = TRUE;
1101 		}
1102 		else
1103 			p = h->h_value;
1104 		if (p == NULL || *p == '\0')
1105 			continue;
1106 
1107 		/* hack, hack -- output Original-From field if different */
1108 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
1109 		{
1110 			/* output new Original-From line if needed */
1111 			if (of_line == NULL && !samefrom(p, origfrom))
1112 			{
1113 				(void) sprintf(obuf, "Original-From: %s\n", origfrom);
1114 				putline(obuf, fp, fullsmtp);
1115 			}
1116 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
1117 			{
1118 				/* delete Original-From: line if redundant */
1119 				p = of_line;
1120 				of_line = NULL;
1121 			}
1122 		}
1123 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
1124 			nooutput = TRUE;
1125 
1126 		/* finally, output the header line */
1127 		if (!nooutput)
1128 		{
1129 			(void) sprintf(obuf, "%s: %s\n", capitalize(h->h_field), p);
1130 			putline(obuf, fp, fullsmtp);
1131 			h->h_flags |= H_USED;
1132 		}
1133 	}
1134 }
1135 /*
1136 **  PUTBODY -- put the body of a message.
1137 **
1138 **	Parameters:
1139 **		fp -- file to output onto.
1140 **		m -- a mailer descriptor.
1141 **		xdot -- if set, use SMTP hidden dot algorithm.
1142 **
1143 **	Returns:
1144 **		none.
1145 **
1146 **	Side Effects:
1147 **		The message is written onto fp.
1148 */
1149 
1150 putbody(fp, m, xdot)
1151 	FILE *fp;
1152 	struct mailer *m;
1153 	bool xdot;
1154 {
1155 	char buf[MAXLINE + 1];
1156 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
1157 
1158 	/*
1159 	**  Output the body of the message
1160 	*/
1161 
1162 #ifdef lint
1163 	/* m will be needed later for complete smtp emulation */
1164 	if (m == NULL)
1165 		return;
1166 #endif lint
1167 
1168 	if (TempFile != NULL)
1169 	{
1170 		rewind(TempFile);
1171 		buf[0] = '.';
1172 		while (!ferror(fp) && fgets(&buf[1], sizeof buf - 1, TempFile) != NULL)
1173 			putline((xdot && buf[1] == '.') ? buf : &buf[1], fp, fullsmtp);
1174 
1175 		if (ferror(TempFile))
1176 		{
1177 			syserr("putbody: read error");
1178 			ExitStat = EX_IOERR;
1179 		}
1180 	}
1181 
1182 	(void) fflush(fp);
1183 	if (ferror(fp) && errno != EPIPE)
1184 	{
1185 		syserr("putbody: write error");
1186 		ExitStat = EX_IOERR;
1187 	}
1188 	errno = 0;
1189 }
1190 /*
1191 **  ISATWORD -- tell if the word we are pointing to is "at".
1192 **
1193 **	Parameters:
1194 **		p -- word to check.
1195 **
1196 **	Returns:
1197 **		TRUE -- if p is the word at.
1198 **		FALSE -- otherwise.
1199 **
1200 **	Side Effects:
1201 **		none.
1202 */
1203 
1204 bool
1205 isatword(p)
1206 	register char *p;
1207 {
1208 	extern char lower();
1209 
1210 	if (lower(p[0]) == 'a' && lower(p[1]) == 't' &&
1211 	    p[2] != '\0' && isspace(p[2]))
1212 		return (TRUE);
1213 	return (FALSE);
1214 }
1215 /*
1216 **  SAMEFROM -- tell if two text addresses represent the same from address.
1217 **
1218 **	Parameters:
1219 **		ifrom -- internally generated form of from address.
1220 **		efrom -- external form of from address.
1221 **
1222 **	Returns:
1223 **		TRUE -- if they convey the same info.
1224 **		FALSE -- if any information has been lost.
1225 **
1226 **	Side Effects:
1227 **		none.
1228 */
1229 
1230 bool
1231 samefrom(ifrom, efrom)
1232 	char *ifrom;
1233 	char *efrom;
1234 {
1235 	register char *p;
1236 	char buf[MAXNAME + 4];
1237 
1238 # ifdef DEBUG
1239 	if (tTd(3, 8))
1240 		printf("samefrom(%s,%s)-->", ifrom, efrom);
1241 # endif DEBUG
1242 	if (strcmp(ifrom, efrom) == 0)
1243 		goto success;
1244 	p = index(ifrom, '@');
1245 	if (p == NULL)
1246 		goto failure;
1247 	*p = '\0';
1248 	(void) strcpy(buf, ifrom);
1249 	(void) strcat(buf, " at ");
1250 	*p++ = '@';
1251 	(void) strcat(buf, p);
1252 	if (strcmp(buf, efrom) == 0)
1253 		goto success;
1254 
1255   failure:
1256 # ifdef DEBUG
1257 	if (tTd(3, 8))
1258 		printf("FALSE\n");
1259 # endif DEBUG
1260 	return (FALSE);
1261 
1262   success:
1263 # ifdef DEBUG
1264 	if (tTd(3, 8))
1265 		printf("TRUE\n");
1266 # endif DEBUG
1267 	return (TRUE);
1268 }
1269 /*
1270 **  MAILFILE -- Send a message to a file.
1271 **
1272 **	If the file has the setuid/setgid bits set, but NO execute
1273 **	bits, sendmail will try to become the owner of that file
1274 **	rather than the real user.  Obviously, this only works if
1275 **	sendmail runs as root.
1276 **
1277 **	Parameters:
1278 **		filename -- the name of the file to send to.
1279 **		ctladdr -- the controlling address header -- includes
1280 **			the userid/groupid to be when sending.
1281 **
1282 **	Returns:
1283 **		The exit code associated with the operation.
1284 **
1285 **	Side Effects:
1286 **		none.
1287 */
1288 
1289 mailfile(filename, ctladdr)
1290 	char *filename;
1291 	ADDRESS *ctladdr;
1292 {
1293 	register FILE *f;
1294 	register int pid;
1295 
1296 	/*
1297 	**  Fork so we can change permissions here.
1298 	**	Note that we MUST use fork, not vfork, because of
1299 	**	the complications of calling subroutines, etc.
1300 	*/
1301 
1302 	DOFORK(fork);
1303 
1304 	if (pid < 0)
1305 		return (EX_OSERR);
1306 	else if (pid == 0)
1307 	{
1308 		/* child -- actually write to file */
1309 		struct stat stb;
1310 
1311 		(void) signal(SIGINT, SIG_DFL);
1312 		(void) signal(SIGHUP, SIG_DFL);
1313 		(void) signal(SIGTERM, SIG_DFL);
1314 		umask(OldUmask);
1315 		if (stat(filename, &stb) < 0)
1316 			stb.st_mode = 0666;
1317 		if (bitset(0111, stb.st_mode))
1318 			exit(EX_CANTCREAT);
1319 		if (ctladdr == NULL)
1320 			ctladdr = &CurEnv->e_from;
1321 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1322 		{
1323 			if (ctladdr->q_uid == 0)
1324 				(void) setgid(DefGid);
1325 			else
1326 				(void) setgid(ctladdr->q_gid);
1327 		}
1328 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1329 		{
1330 			if (ctladdr->q_uid == 0)
1331 				(void) setuid(DefUid);
1332 			else
1333 				(void) setuid(ctladdr->q_uid);
1334 		}
1335 		f = dfopen(filename, "a");
1336 		if (f == NULL)
1337 			exit(EX_CANTCREAT);
1338 
1339 		putfromline(f, Mailer[1]);
1340 		(*CurEnv->e_puthdr)(f, Mailer[1], CurEnv);
1341 		fputs("\n", f);
1342 		(*CurEnv->e_putbody)(f, Mailer[1], FALSE);
1343 		fputs("\n", f);
1344 		(void) fclose(f);
1345 		(void) fflush(stdout);
1346 
1347 		/* reset ISUID & ISGID bits for paranoid systems */
1348 		(void) chmod(filename, (int) stb.st_mode);
1349 		exit(EX_OK);
1350 		/*NOTREACHED*/
1351 	}
1352 	else
1353 	{
1354 		/* parent -- wait for exit status */
1355 		register int i;
1356 		auto int stat;
1357 
1358 		while ((i = wait(&stat)) != pid)
1359 		{
1360 			if (i < 0)
1361 			{
1362 				stat = EX_OSERR << 8;
1363 				break;
1364 			}
1365 		}
1366 		if ((stat & 0377) != 0)
1367 			stat = EX_UNAVAILABLE << 8;
1368 		return ((stat >> 8) & 0377);
1369 	}
1370 }
1371 /*
1372 **  SENDALL -- actually send all the messages.
1373 **
1374 **	Parameters:
1375 **		e -- the envelope to send.
1376 **		verifyonly -- if set, only give verification messages.
1377 **
1378 **	Returns:
1379 **		none.
1380 **
1381 **	Side Effects:
1382 **		Scans the send lists and sends everything it finds.
1383 **		Delivers any appropriate error messages.
1384 */
1385 
1386 sendall(e, verifyonly)
1387 	ENVELOPE *e;
1388 	bool verifyonly;
1389 {
1390 	register ADDRESS *q;
1391 
1392 # ifdef DEBUG
1393 	if (tTd(13, 2))
1394 	{
1395 		printf("\nSend Queue:\n");
1396 		printaddr(e->e_sendqueue, TRUE);
1397 	}
1398 # endif DEBUG
1399 
1400 	/*
1401 	**  Run through the list and send everything.
1402 	*/
1403 
1404 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1405 	{
1406 		if (verifyonly)
1407 		{
1408 			CurEnv->e_to = q->q_paddr;
1409 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1410 				message(Arpa_Info, "deliverable");
1411 		}
1412 		else
1413 			(void) deliver(q);
1414 	}
1415 
1416 	/*
1417 	**  Now run through and check for errors.
1418 	*/
1419 
1420 	if (verifyonly)
1421 		return;
1422 
1423 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1424 	{
1425 		register ADDRESS *qq;
1426 
1427 		if (bitset(QQUEUEUP, q->q_flags))
1428 			e->e_queueup = TRUE;
1429 		if (!bitset(QBADADDR, q->q_flags))
1430 			continue;
1431 
1432 		/* we have an address that failed -- find the parent */
1433 		for (qq = q; qq != NULL; qq = qq->q_alias)
1434 		{
1435 			char obuf[MAXNAME + 6];
1436 			extern char *aliaslookup();
1437 
1438 			/* we can only have owners for local addresses */
1439 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1440 				continue;
1441 
1442 			/* see if the owner list exists */
1443 			(void) strcpy(obuf, "owner-");
1444 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1445 				(void) strcat(obuf, "owner");
1446 			else
1447 				(void) strcat(obuf, qq->q_user);
1448 			if (aliaslookup(obuf) == NULL)
1449 				continue;
1450 
1451 			/* owner list exists -- add it to the error queue */
1452 			qq->q_flags &= ~QPRIMARY;
1453 			sendto(obuf, 1, qq, &e->e_errorqueue);
1454 			MailBack = TRUE;
1455 			break;
1456 		}
1457 
1458 		/* if we did not find an owner, send to the sender */
1459 		if (qq == NULL)
1460 			sendto(e->e_from.q_paddr, 1, qq, &e->e_errorqueue);
1461 	}
1462 }
1463 /*
1464 **  CHECKERRORS -- check a queue of addresses and process errors.
1465 **
1466 **	Parameters:
1467 **		e -- the envelope to check.
1468 **
1469 **	Returns:
1470 **		none.
1471 **
1472 **	Side Effects:
1473 **		Arranges to queue all tempfailed messages in q
1474 **			or deliver error responses.
1475 */
1476 
1477 checkerrors(e)
1478 	register ENVELOPE *e;
1479 {
1480 # ifdef DEBUG
1481 	if (tTd(4, 1))
1482 	{
1483 		printf("\ncheckerrors: FatalErrors %d, errorqueue:\n");
1484 		printaddr(e->e_errorqueue, TRUE);
1485 	}
1486 # endif DEBUG
1487 
1488 	/* mail back the transcript on errors */
1489 	if (FatalErrors)
1490 		savemail();
1491 
1492 	/* queue up anything laying around */
1493 	if (e->e_queueup)
1494 	{
1495 # ifdef QUEUE
1496 		queueup(e, FALSE);
1497 # else QUEUE
1498 		syserr("finis: trying to queue %s", e->e_df);
1499 # endif QUEUE
1500 	}
1501 }
1502