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