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