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