1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 
6 SCCSID(@(#)deliver.c	3.100		08/22/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", CurEnv->e_id,
878 				  CurEnv->e_to, statmsg);
879 # endif LOG
880 # ifdef QUEUE
881 	if (stat != EX_TEMPFAIL)
882 # endif QUEUE
883 		setstat(stat);
884 }
885 /*
886 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
887 **
888 **	This can be made an arbitrary message separator by changing $l
889 **
890 **	One of the ugliest hacks seen by human eyes is
891 **	contained herein: UUCP wants those stupid
892 **	"remote from <host>" lines.  Why oh why does a
893 **	well-meaning programmer such as myself have to
894 **	deal with this kind of antique garbage????
895 **
896 **	Parameters:
897 **		fp -- the file to output to.
898 **		m -- the mailer describing this entry.
899 **
900 **	Returns:
901 **		none
902 **
903 **	Side Effects:
904 **		outputs some text to fp.
905 */
906 
907 putfromline(fp, m)
908 	register FILE *fp;
909 	register MAILER *m;
910 {
911 	char buf[MAXLINE];
912 
913 	if (bitset(M_NHDR, m->m_flags))
914 		return;
915 
916 # ifdef UGLYUUCP
917 	if (bitset(M_UGLYUUCP, m->m_flags))
918 	{
919 		extern char *macvalue();
920 		char *sys = macvalue('g');
921 		char *bang = index(sys, '!');
922 
923 		if (bang == NULL)
924 			syserr("No ! in UUCP! (%s)", sys);
925 		else
926 			*bang = '\0';
927 		expand("From $f  $d remote from $g\n", buf,
928 				&buf[sizeof buf - 1], CurEnv);
929 		*bang = '!';
930 	}
931 	else
932 # endif UGLYUUCP
933 		expand("$l\n", buf, &buf[sizeof buf - 1], CurEnv);
934 	putline(buf, fp, bitset(M_FULLSMTP, m->m_flags));
935 }
936 /*
937 **  PUTHEADER -- put the header part of a message from the in-core copy
938 **
939 **	Parameters:
940 **		fp -- file to put it on.
941 **		m -- mailer to use.
942 **		e -- envelope to use.
943 **
944 **	Returns:
945 **		none.
946 **
947 **	Side Effects:
948 **		none.
949 */
950 
951 putheader(fp, m, e)
952 	register FILE *fp;
953 	register struct mailer *m;
954 	register ENVELOPE *e;
955 {
956 	char buf[BUFSIZ];
957 	register HDR *h;
958 	extern char *arpadate();
959 	extern char *capitalize();
960 	extern char *hvalue();
961 	extern bool samefrom();
962 	char *of_line;
963 	char obuf[MAXLINE];
964 	register char *obp;
965 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
966 
967 	of_line = hvalue("original-from");
968 	for (h = e->e_header; h != NULL; h = h->h_link)
969 	{
970 		register char *p;
971 		char *origfrom = e->e_origfrom;
972 		bool nooutput;
973 
974 		nooutput = FALSE;
975 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
976 			nooutput = TRUE;
977 
978 		/* use From: line from message if generated is the same */
979 		p = h->h_value;
980 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
981 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
982 		{
983 			p = origfrom;
984 			origfrom = NULL;
985 		}
986 		else if (bitset(H_DEFAULT, h->h_flags))
987 		{
988 			/* macro expand value if generated internally */
989 			expand(h->h_value, buf, &buf[sizeof buf], e);
990 			p = buf;
991 		}
992 		else if (bitset(H_ADDR, h->h_flags))
993 		{
994 			if (p == NULL || *p == '\0' || nooutput)
995 				continue;
996 			commaize(p, capitalize(h->h_field), fp, e->e_oldstyle, m);
997 			nooutput = TRUE;
998 		}
999 		if (p == NULL || *p == '\0')
1000 			continue;
1001 
1002 		/* hack, hack -- output Original-From field if different */
1003 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
1004 		{
1005 			/* output new Original-From line if needed */
1006 			if (of_line == NULL && !samefrom(p, origfrom))
1007 			{
1008 				(void) sprintf(obuf, "Original-From: %s\n", origfrom);
1009 				putline(obuf, fp, fullsmtp);
1010 			}
1011 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
1012 			{
1013 				/* delete Original-From: line if redundant */
1014 				p = of_line;
1015 				of_line = NULL;
1016 			}
1017 		}
1018 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
1019 			nooutput = TRUE;
1020 
1021 		/* finally, output the header line */
1022 		if (!nooutput)
1023 		{
1024 			(void) sprintf(obuf, "%s: %s\n", capitalize(h->h_field), p);
1025 			putline(obuf, fp, fullsmtp);
1026 			h->h_flags |= H_USED;
1027 		}
1028 	}
1029 }
1030 /*
1031 **  COMMAIZE -- output a header field, making a comma-translated list.
1032 **
1033 **	Parameters:
1034 **		p -- the field to output.
1035 **		tag -- the tag to associate with it.
1036 **		fp -- file to put it to.
1037 **		oldstyle -- TRUE if this is an old style header.
1038 **		m -- a pointer to the mailer descriptor.
1039 **
1040 **	Returns:
1041 **		none.
1042 **
1043 **	Side Effects:
1044 **		outputs "p" to file "fp".
1045 */
1046 
1047 commaize(p, tag, fp, oldstyle, m)
1048 	register char *p;
1049 	char *tag;
1050 	FILE *fp;
1051 	bool oldstyle;
1052 	MAILER *m;
1053 {
1054 	register int opos;
1055 	bool firstone = TRUE;
1056 	char obuf[MAXLINE];
1057 	register char *obp;
1058 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
1059 
1060 	/*
1061 	**  Output the address list translated by the
1062 	**  mailer and with commas.
1063 	*/
1064 
1065 # ifdef DEBUG
1066 	if (tTd(14, 2))
1067 		printf("commaize(%s: %s)\n", tag, p);
1068 # endif DEBUG
1069 
1070 	obp = obuf;
1071 	(void) sprintf(obp, "%s: ", tag);
1072 	opos = strlen(tag) + 2;
1073 	obp += opos;
1074 
1075 	/*
1076 	**  Run through the list of values.
1077 	*/
1078 
1079 	while (*p != '\0')
1080 	{
1081 		register char *name;
1082 		extern char *remotename();
1083 		char savechar;
1084 
1085 		/*
1086 		**  Find the end of the name.  New style names
1087 		**  end with a comma, old style names end with
1088 		**  a space character.  However, spaces do not
1089 		**  necessarily delimit an old-style name -- at
1090 		**  signs mean keep going.
1091 		*/
1092 
1093 		/* clean up the leading trash in source */
1094 		while (*p != '\0' && (isspace(*p) || *p == ','))
1095 			p++;
1096 		name = p;
1097 
1098 		/* find end of name */
1099 		while (*p != '\0' && *p != ',')
1100 		{
1101 			extern bool isatword();
1102 			char *oldp;
1103 
1104 			if (!oldstyle || !isspace(*p))
1105 			{
1106 				p++;
1107 				continue;
1108 			}
1109 
1110 			/* look to see if we have an at sign */
1111 			oldp = p;
1112 			while (*p != '\0' && isspace(*p))
1113 				p++;
1114 
1115 			if (*p != '@' && !isatword(p))
1116 			{
1117 				p = oldp;
1118 				break;
1119 			}
1120 			p += *p == '@' ? 1 : 2;
1121 			while (*p != '\0' && isspace(*p))
1122 				p++;
1123 		}
1124 		/* at the end of one complete name */
1125 
1126 		/* strip off trailing white space */
1127 		while (p >= name && (isspace(*p) || *p == ',' || *p == '\0'))
1128 			p--;
1129 		if (++p == name)
1130 			continue;
1131 		savechar = *p;
1132 		*p = '\0';
1133 
1134 		/* translate the name to be relative */
1135 		name = remotename(name, m, FALSE);
1136 		if (*name == '\0')
1137 		{
1138 			*p = savechar;
1139 			continue;
1140 		}
1141 
1142 		/* output the name with nice formatting */
1143 		opos += strlen(name);
1144 		if (!firstone)
1145 			opos += 2;
1146 		if (opos > 78 && !firstone)
1147 		{
1148 			(void) sprintf(obp, ",\n");
1149 			putline(obuf, fp, fullsmtp);
1150 			obp = obuf;
1151 			(void) sprintf(obp, "        ");
1152 			obp += strlen(obp);
1153 			opos = 8 + strlen(name);
1154 		}
1155 		else if (!firstone)
1156 		{
1157 			(void) sprintf(obp, ", ");
1158 			obp += 2;
1159 		}
1160 		(void) sprintf(obp, "%s", name);
1161 		obp += strlen(obp);
1162 		firstone = FALSE;
1163 		*p = savechar;
1164 	}
1165 	(void) strcpy(obp, "\n");
1166 	putline(obuf, fp, fullsmtp);
1167 }
1168 /*
1169 **  PUTBODY -- put the body of a message.
1170 **
1171 **	Parameters:
1172 **		fp -- file to output onto.
1173 **		m -- a mailer descriptor.
1174 **		xdot -- if set, use SMTP hidden dot algorithm.
1175 **
1176 **	Returns:
1177 **		none.
1178 **
1179 **	Side Effects:
1180 **		The message is written onto fp.
1181 */
1182 
1183 putbody(fp, m, xdot)
1184 	FILE *fp;
1185 	struct mailer *m;
1186 	bool xdot;
1187 {
1188 	char buf[MAXLINE + 1];
1189 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
1190 
1191 	/*
1192 	**  Output the body of the message
1193 	*/
1194 
1195 #ifdef lint
1196 	/* m will be needed later for complete smtp emulation */
1197 	if (m == NULL)
1198 		return;
1199 #endif lint
1200 
1201 	if (TempFile != NULL)
1202 	{
1203 		rewind(TempFile);
1204 		buf[0] = '.';
1205 		while (!ferror(fp) && fgets(&buf[1], sizeof buf - 1, TempFile) != NULL)
1206 			putline((xdot && buf[1] == '.') ? buf : &buf[1], fp, fullsmtp);
1207 
1208 		if (ferror(TempFile))
1209 		{
1210 			syserr("putbody: read error");
1211 			ExitStat = EX_IOERR;
1212 		}
1213 	}
1214 
1215 	(void) fflush(fp);
1216 	if (ferror(fp) && errno != EPIPE)
1217 	{
1218 		syserr("putbody: write error");
1219 		ExitStat = EX_IOERR;
1220 	}
1221 	errno = 0;
1222 }
1223 /*
1224 **  ISATWORD -- tell if the word we are pointing to is "at".
1225 **
1226 **	Parameters:
1227 **		p -- word to check.
1228 **
1229 **	Returns:
1230 **		TRUE -- if p is the word at.
1231 **		FALSE -- otherwise.
1232 **
1233 **	Side Effects:
1234 **		none.
1235 */
1236 
1237 bool
1238 isatword(p)
1239 	register char *p;
1240 {
1241 	extern char lower();
1242 
1243 	if (lower(p[0]) == 'a' && lower(p[1]) == 't' &&
1244 	    p[2] != '\0' && isspace(p[2]))
1245 		return (TRUE);
1246 	return (FALSE);
1247 }
1248 /*
1249 **  SAMEFROM -- tell if two text addresses represent the same from address.
1250 **
1251 **	Parameters:
1252 **		ifrom -- internally generated form of from address.
1253 **		efrom -- external form of from address.
1254 **
1255 **	Returns:
1256 **		TRUE -- if they convey the same info.
1257 **		FALSE -- if any information has been lost.
1258 **
1259 **	Side Effects:
1260 **		none.
1261 */
1262 
1263 bool
1264 samefrom(ifrom, efrom)
1265 	char *ifrom;
1266 	char *efrom;
1267 {
1268 	register char *p;
1269 	char buf[MAXNAME + 4];
1270 
1271 # ifdef DEBUG
1272 	if (tTd(3, 8))
1273 		printf("samefrom(%s,%s)-->", ifrom, efrom);
1274 # endif DEBUG
1275 	if (strcmp(ifrom, efrom) == 0)
1276 		goto success;
1277 	p = index(ifrom, '@');
1278 	if (p == NULL)
1279 		goto failure;
1280 	*p = '\0';
1281 	(void) strcpy(buf, ifrom);
1282 	(void) strcat(buf, " at ");
1283 	*p++ = '@';
1284 	(void) strcat(buf, p);
1285 	if (strcmp(buf, efrom) == 0)
1286 		goto success;
1287 
1288   failure:
1289 # ifdef DEBUG
1290 	if (tTd(3, 8))
1291 		printf("FALSE\n");
1292 # endif DEBUG
1293 	return (FALSE);
1294 
1295   success:
1296 # ifdef DEBUG
1297 	if (tTd(3, 8))
1298 		printf("TRUE\n");
1299 # endif DEBUG
1300 	return (TRUE);
1301 }
1302 /*
1303 **  MAILFILE -- Send a message to a file.
1304 **
1305 **	If the file has the setuid/setgid bits set, but NO execute
1306 **	bits, sendmail will try to become the owner of that file
1307 **	rather than the real user.  Obviously, this only works if
1308 **	sendmail runs as root.
1309 **
1310 **	Parameters:
1311 **		filename -- the name of the file to send to.
1312 **		ctladdr -- the controlling address header -- includes
1313 **			the userid/groupid to be when sending.
1314 **
1315 **	Returns:
1316 **		The exit code associated with the operation.
1317 **
1318 **	Side Effects:
1319 **		none.
1320 */
1321 
1322 mailfile(filename, ctladdr)
1323 	char *filename;
1324 	ADDRESS *ctladdr;
1325 {
1326 	register FILE *f;
1327 	register int pid;
1328 
1329 	/*
1330 	**  Fork so we can change permissions here.
1331 	**	Note that we MUST use fork, not vfork, because of
1332 	**	the complications of calling subroutines, etc.
1333 	*/
1334 
1335 	DOFORK(fork);
1336 
1337 	if (pid < 0)
1338 		return (EX_OSERR);
1339 	else if (pid == 0)
1340 	{
1341 		/* child -- actually write to file */
1342 		struct stat stb;
1343 
1344 		(void) signal(SIGINT, SIG_DFL);
1345 		(void) signal(SIGHUP, SIG_DFL);
1346 		(void) signal(SIGTERM, SIG_DFL);
1347 		umask(OldUmask);
1348 		if (stat(filename, &stb) < 0)
1349 			stb.st_mode = 0666;
1350 		if (bitset(0111, stb.st_mode))
1351 			exit(EX_CANTCREAT);
1352 		if (ctladdr == NULL)
1353 			ctladdr = &CurEnv->e_from;
1354 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1355 		{
1356 			if (ctladdr->q_uid == 0)
1357 				(void) setgid(DefGid);
1358 			else
1359 				(void) setgid(ctladdr->q_gid);
1360 		}
1361 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1362 		{
1363 			if (ctladdr->q_uid == 0)
1364 				(void) setuid(DefUid);
1365 			else
1366 				(void) setuid(ctladdr->q_uid);
1367 		}
1368 		f = dfopen(filename, "a");
1369 		if (f == NULL)
1370 			exit(EX_CANTCREAT);
1371 
1372 		putfromline(f, Mailer[1]);
1373 		(*CurEnv->e_puthdr)(f, Mailer[1], CurEnv);
1374 		fputs("\n", f);
1375 		(*CurEnv->e_putbody)(f, Mailer[1], FALSE);
1376 		fputs("\n", f);
1377 		(void) fclose(f);
1378 		(void) fflush(stdout);
1379 
1380 		/* reset ISUID & ISGID bits for paranoid systems */
1381 		(void) chmod(filename, (int) stb.st_mode);
1382 		exit(EX_OK);
1383 		/*NOTREACHED*/
1384 	}
1385 	else
1386 	{
1387 		/* parent -- wait for exit status */
1388 		register int i;
1389 		auto int stat;
1390 
1391 		while ((i = wait(&stat)) != pid)
1392 		{
1393 			if (i < 0)
1394 			{
1395 				stat = EX_OSERR << 8;
1396 				break;
1397 			}
1398 		}
1399 		if ((stat & 0377) != 0)
1400 			stat = EX_UNAVAILABLE << 8;
1401 		return ((stat >> 8) & 0377);
1402 	}
1403 }
1404 /*
1405 **  SENDALL -- actually send all the messages.
1406 **
1407 **	Parameters:
1408 **		e -- the envelope to send.
1409 **		verifyonly -- if set, only give verification messages.
1410 **
1411 **	Returns:
1412 **		none.
1413 **
1414 **	Side Effects:
1415 **		Scans the send lists and sends everything it finds.
1416 **		Delivers any appropriate error messages.
1417 */
1418 
1419 sendall(e, verifyonly)
1420 	ENVELOPE *e;
1421 	bool verifyonly;
1422 {
1423 	register ADDRESS *q;
1424 	bool oldverbose;
1425 
1426 # ifdef DEBUG
1427 	if (tTd(13, 2))
1428 	{
1429 		printf("\nSend Queue:\n");
1430 		printaddr(e->e_sendqueue, TRUE);
1431 	}
1432 # endif DEBUG
1433 
1434 	/*
1435 	**  Run through the list and send everything.
1436 	*/
1437 
1438 	oldverbose = Verbose;
1439 	if (verifyonly)
1440 		Verbose = TRUE;
1441 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1442 	{
1443 		if (verifyonly)
1444 		{
1445 			CurEnv->e_to = q->q_paddr;
1446 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1447 				message(Arpa_Info, "deliverable");
1448 		}
1449 		else
1450 			(void) deliver(q);
1451 	}
1452 	Verbose = oldverbose;
1453 
1454 	/*
1455 	**  Now run through and check for errors.
1456 	*/
1457 
1458 	if (verifyonly)
1459 		return;
1460 
1461 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1462 	{
1463 		register ADDRESS *qq;
1464 
1465 		if (bitset(QQUEUEUP, q->q_flags))
1466 			e->e_queueup = TRUE;
1467 		if (!bitset(QBADADDR, q->q_flags))
1468 			continue;
1469 
1470 		/* we have an address that failed -- find the parent */
1471 		for (qq = q; qq != NULL; qq = qq->q_alias)
1472 		{
1473 			char obuf[MAXNAME + 6];
1474 			extern char *aliaslookup();
1475 
1476 			/* we can only have owners for local addresses */
1477 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1478 				continue;
1479 
1480 			/* see if the owner list exists */
1481 			(void) strcpy(obuf, "owner-");
1482 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1483 				(void) strcat(obuf, "owner");
1484 			else
1485 				(void) strcat(obuf, qq->q_user);
1486 			if (aliaslookup(obuf) == NULL)
1487 				continue;
1488 
1489 			/* owner list exists -- add it to the error queue */
1490 			qq->q_flags &= ~QPRIMARY;
1491 			sendto(obuf, 1, qq, &e->e_errorqueue);
1492 			MailBack = TRUE;
1493 			break;
1494 		}
1495 
1496 		/* if we did not find an owner, send to the sender */
1497 		if (qq == NULL)
1498 			sendto(e->e_from.q_paddr, 1, qq, &e->e_errorqueue);
1499 	}
1500 }
1501 /*
1502 **  CHECKERRORS -- check a queue of addresses and process errors.
1503 **
1504 **	Parameters:
1505 **		e -- the envelope to check.
1506 **
1507 **	Returns:
1508 **		none.
1509 **
1510 **	Side Effects:
1511 **		Arranges to queue all tempfailed messages in q
1512 **			or deliver error responses.
1513 */
1514 
1515 checkerrors(e)
1516 	register ENVELOPE *e;
1517 {
1518 	register ADDRESS *q;
1519 
1520 # ifdef DEBUG
1521 	if (tTd(4, 1))
1522 	{
1523 		printf("\ncheckerrors: FatalErrors %d, errorqueue:\n");
1524 		printaddr(e->e_errorqueue, TRUE);
1525 	}
1526 # endif DEBUG
1527 
1528 	/* mail back the transcript on errors */
1529 	if (FatalErrors)
1530 		savemail();
1531 
1532 	/* queue up anything laying around */
1533 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1534 	{
1535 		if (bitset(QQUEUEUP, q->q_flags))
1536 		{
1537 # ifdef QUEUE
1538 			queueup(e, FALSE);
1539 # else QUEUE
1540 			syserr("checkerrors: trying to queue %s", e->e_df);
1541 # endif QUEUE
1542 			break;
1543 		}
1544 	}
1545 }
1546