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