1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 
6 SCCSID(@(#)deliver.c	3.134		11/28/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 **		e -- the envelope to deliver.
20 **		firstto -- head of the address list to deliver to.
21 **
22 **	Returns:
23 **		zero -- successfully delivered.
24 **		else -- some failure, see ExitStat for more info.
25 **
26 **	Side Effects:
27 **		The standard input is passed off to someone.
28 */
29 
30 deliver(e, firstto)
31 	register ENVELOPE *e;
32 	ADDRESS *firstto;
33 {
34 	char *host;			/* host being sent to */
35 	char *user;			/* user being sent to */
36 	char **pvp;
37 	register char **mvp;
38 	register char *p;
39 	register MAILER *m;	/* mailer for this recipient */
40 	extern bool checkcompat();
41 	char *pv[MAXPV+1];
42 	char tobuf[MAXLINE-50];		/* text line of to people */
43 	char buf[MAXNAME];
44 	ADDRESS *ctladdr;
45 	extern ADDRESS *getctladdr();
46 	char tfrombuf[MAXNAME];		/* translated from person */
47 	extern char **prescan();
48 	register ADDRESS *to = firstto;
49 	bool clever = FALSE;		/* running user smtp to this mailer */
50 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
51 	register int rcode;		/* response code */
52 
53 	errno = 0;
54 	if (bitset(QDONTSEND, to->q_flags))
55 		return (0);
56 
57 	m = to->q_mailer;
58 	host = to->q_host;
59 
60 # ifdef DEBUG
61 	if (tTd(10, 1))
62 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
63 			m->m_mno, host, to->q_user);
64 # endif DEBUG
65 
66 	/*
67 	**  If this mailer is expensive, and if we don't want to make
68 	**  connections now, just mark these addresses and return.
69 	**	This is useful if we want to batch connections to
70 	**	reduce load.  This will cause the messages to be
71 	**	queued up, and a daemon will come along to send the
72 	**	messages later.
73 	**		This should be on a per-mailer basis.
74 	*/
75 
76 	if (NoConnect && !QueueRun && bitset(M_EXPENSIVE, m->m_flags) &&
77 	    !Verbose)
78 	{
79 		for (; to != NULL; to = to->q_next)
80 		{
81 			if (bitset(QDONTSEND, to->q_flags) || to->q_mailer != m)
82 				continue;
83 			to->q_flags |= QQUEUEUP|QDONTSEND;
84 			e->e_to = to->q_paddr;
85 			message(Arpa_Info, "queued");
86 			if (LogLevel > 4)
87 				logdelivery("queued");
88 		}
89 		e->e_to = NULL;
90 		return (0);
91 	}
92 
93 	/*
94 	**  Do initial argv setup.
95 	**	Insert the mailer name.  Notice that $x expansion is
96 	**	NOT done on the mailer name.  Then, if the mailer has
97 	**	a picky -f flag, we insert it as appropriate.  This
98 	**	code does not check for 'pv' overflow; this places a
99 	**	manifest lower limit of 4 for MAXPV.
100 	**		The from address rewrite is expected to make
101 	**		the address relative to the other end.
102 	*/
103 
104 	/* rewrite from address, using rewriting rules */
105 	expand("$f", buf, &buf[sizeof buf - 1], e);
106 	mvp = prescan(buf, '\0');
107 	rewrite(mvp, 3);
108 	rewrite(mvp, 1);
109 	rewrite(mvp, m->m_s_rwset);
110 	cataddr(mvp, tfrombuf, sizeof tfrombuf);
111 
112 	define('g', tfrombuf, e);		/* translated sender address */
113 	define('h', host, e);			/* to host */
114 	Errors = 0;
115 	pvp = pv;
116 	*pvp++ = m->m_argv[0];
117 
118 	/* insert -f or -r flag as appropriate */
119 	if (bitset(M_FOPT|M_ROPT, m->m_flags) && FromFlag)
120 	{
121 		if (bitset(M_FOPT, m->m_flags))
122 			*pvp++ = "-f";
123 		else
124 			*pvp++ = "-r";
125 		expand("$g", buf, &buf[sizeof buf - 1], e);
126 		*pvp++ = newstr(buf);
127 	}
128 
129 	/*
130 	**  Append the other fixed parts of the argv.  These run
131 	**  up to the first entry containing "$u".  There can only
132 	**  be one of these, and there are only a few more slots
133 	**  in the pv after it.
134 	*/
135 
136 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
137 	{
138 		while ((p = index(p, '$')) != NULL)
139 			if (*++p == 'u')
140 				break;
141 		if (p != NULL)
142 			break;
143 
144 		/* this entry is safe -- go ahead and process it */
145 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
146 		*pvp++ = newstr(buf);
147 		if (pvp >= &pv[MAXPV - 3])
148 		{
149 			syserr("Too many parameters to %s before $u", pv[0]);
150 			return (-1);
151 		}
152 	}
153 
154 	/*
155 	**  If we have no substitution for the user name in the argument
156 	**  list, we know that we must supply the names otherwise -- and
157 	**  SMTP is the answer!!
158 	*/
159 
160 	if (*mvp == NULL)
161 	{
162 		/* running SMTP */
163 # ifdef SMTP
164 		clever = TRUE;
165 		*pvp = NULL;
166 # else SMTP
167 		/* oops!  we don't implement SMTP */
168 		syserr("SMTP style mailer");
169 		return (EX_SOFTWARE);
170 # endif SMTP
171 	}
172 
173 	/*
174 	**  At this point *mvp points to the argument with $u.  We
175 	**  run through our address list and append all the addresses
176 	**  we can.  If we run out of space, do not fret!  We can
177 	**  always send another copy later.
178 	*/
179 
180 	tobuf[0] = '\0';
181 	e->e_to = tobuf;
182 	ctladdr = NULL;
183 	for (; to != NULL; to = to->q_next)
184 	{
185 		/* avoid sending multiple recipients to dumb mailers */
186 		if (tobuf[0] != '\0' && !bitset(M_MUSER, m->m_flags))
187 			break;
188 
189 		/* if already sent or not for this host, don't send */
190 		if (bitset(QDONTSEND, to->q_flags) ||
191 		    strcmp(to->q_host, host) != 0 ||
192 		    to->q_mailer != firstto->q_mailer)
193 			continue;
194 
195 		/* avoid overflowing tobuf */
196 		if (sizeof tobuf - (strlen(to->q_paddr) + strlen(tobuf) + 2) < 0)
197 			break;
198 
199 # ifdef DEBUG
200 		if (tTd(10, 1))
201 		{
202 			printf("\nsend to ");
203 			printaddr(to, FALSE);
204 		}
205 # endif DEBUG
206 
207 		/* compute effective uid/gid when sending */
208 		if (to->q_mailer == ProgMailer)
209 			ctladdr = getctladdr(to);
210 
211 		user = to->q_user;
212 		e->e_to = to->q_paddr;
213 		to->q_flags |= QDONTSEND;
214 
215 		/*
216 		**  Check to see that these people are allowed to
217 		**  talk to each other.
218 		*/
219 
220 		if (!checkcompat(to))
221 		{
222 			giveresponse(EX_UNAVAILABLE, m);
223 			continue;
224 		}
225 
226 		/*
227 		**  Strip quote bits from names if the mailer is dumb
228 		**	about them.
229 		*/
230 
231 		if (bitset(M_STRIPQ, m->m_flags))
232 		{
233 			stripquotes(user, TRUE);
234 			stripquotes(host, TRUE);
235 		}
236 		else
237 		{
238 			stripquotes(user, FALSE);
239 			stripquotes(host, FALSE);
240 		}
241 
242 		/* hack attack -- delivermail compatibility */
243 		if (m == ProgMailer && *user == '|')
244 			user++;
245 
246 		/*
247 		**  If an error message has already been given, don't
248 		**	bother to send to this address.
249 		**
250 		**	>>>>>>>>>> This clause assumes that the local mailer
251 		**	>> NOTE >> cannot do any further aliasing; that
252 		**	>>>>>>>>>> function is subsumed by sendmail.
253 		*/
254 
255 		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
256 			continue;
257 
258 		/* save statistics.... */
259 		markstats(e, to);
260 
261 		/*
262 		**  See if this user name is "special".
263 		**	If the user name has a slash in it, assume that this
264 		**	is a file -- send it off without further ado.  Note
265 		**	that this type of addresses is not processed along
266 		**	with the others, so we fudge on the To person.
267 		*/
268 
269 		if (m == LocalMailer)
270 		{
271 			if (user[0] == '/')
272 			{
273 				rcode = mailfile(user, getctladdr(to));
274 				giveresponse(rcode, m);
275 				continue;
276 			}
277 		}
278 
279 		/*
280 		**  Address is verified -- add this user to mailer
281 		**  argv, and add it to the print list of recipients.
282 		*/
283 
284 		/* link together the chain of recipients */
285 		to->q_tchain = tochain;
286 		tochain = to;
287 
288 		/* create list of users for error messages */
289 		if (tobuf[0] != '\0')
290 			(void) strcat(tobuf, ",");
291 		(void) strcat(tobuf, to->q_paddr);
292 		define('u', user, e);		/* to user */
293 		define('z', to->q_home, e);	/* user's home */
294 
295 		/*
296 		**  Expand out this user into argument list.
297 		*/
298 
299 		if (!clever)
300 		{
301 			expand(*mvp, buf, &buf[sizeof buf - 1], e);
302 			*pvp++ = newstr(buf);
303 			if (pvp >= &pv[MAXPV - 2])
304 			{
305 				/* allow some space for trailing parms */
306 				break;
307 			}
308 		}
309 	}
310 
311 	/* see if any addresses still exist */
312 	if (tobuf[0] == '\0')
313 	{
314 		define('g', (char *) NULL, e);
315 		return (0);
316 	}
317 
318 	/* print out messages as full list */
319 	e->e_to = tobuf;
320 
321 	/*
322 	**  Fill out any parameters after the $u parameter.
323 	*/
324 
325 	while (!clever && *++mvp != NULL)
326 	{
327 		expand(*mvp, buf, &buf[sizeof buf - 1], e);
328 		*pvp++ = newstr(buf);
329 		if (pvp >= &pv[MAXPV])
330 			syserr("deliver: pv overflow after $u for %s", pv[0]);
331 	}
332 	*pvp++ = NULL;
333 
334 	/*
335 	**  Call the mailer.
336 	**	The argument vector gets built, pipes
337 	**	are created as necessary, and we fork & exec as
338 	**	appropriate.
339 	**	If we are running SMTP, we just need to clean up.
340 	*/
341 
342 	message(Arpa_Info, "Connecting to %s.%s...", host, m->m_name);
343 
344 	if (ctladdr == NULL)
345 		ctladdr = &e->e_from;
346 # ifdef SMTP
347 	if (clever)
348 	{
349 		/* send the initial SMTP protocol */
350 		rcode = smtpinit(m, pv, (ADDRESS *) NULL);
351 
352 		/* send the recipient list */
353 		for (to = tochain; to != NULL; to = to->q_tchain)
354 		{
355 			int i;
356 
357 			if (rcode == EX_OK)
358 				i = smtprcpt(to);
359 			else
360 				i = rcode;
361 			if (i != EX_OK)
362 			{
363 				if (i == EX_TEMPFAIL)
364 					to->q_flags |= QQUEUEUP;
365 				else
366 					to->q_flags |= QBADADDR;
367 				giveresponse(rcode, m);
368 			}
369 		}
370 
371 		/* now send the closing protocol */
372 		if (rcode == EX_OK)
373 			rcode = smtpfinish(m, e);
374 		if (rcode != EX_OK)
375 			giveresponse(rcode, m);
376 		smtpquit(pv[0], rcode == EX_OK);
377 	}
378 	else
379 # endif SMTP
380 		rcode = sendoff(e, m, pv, ctladdr);
381 
382 	/*
383 	**  If we got a temporary failure, arrange to queue the
384 	**  addressees.
385 	*/
386 
387 	if (rcode == EX_TEMPFAIL)
388 	{
389 		for (to = tochain; to != NULL; to = to->q_tchain)
390 			to->q_flags |= QQUEUEUP;
391 	}
392 
393 	errno = 0;
394 	define('g', (char *) NULL, e);
395 	return (rcode);
396 }
397 /*
398 **  DOFORK -- do a fork, retrying a couple of times on failure.
399 **
400 **	This MUST be a macro, since after a vfork we are running
401 **	two processes on the same stack!!!
402 **
403 **	Parameters:
404 **		none.
405 **
406 **	Returns:
407 **		From a macro???  You've got to be kidding!
408 **
409 **	Side Effects:
410 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
411 **			pid of child in parent, zero in child.
412 **			-1 on unrecoverable error.
413 **
414 **	Notes:
415 **		I'm awfully sorry this looks so awful.  That's
416 **		vfork for you.....
417 */
418 
419 # define NFORKTRIES	5
420 # ifdef VMUNIX
421 # define XFORK	vfork
422 # else VMUNIX
423 # define XFORK	fork
424 # endif VMUNIX
425 
426 # define DOFORK(fORKfN) \
427 {\
428 	register int i;\
429 \
430 	for (i = NFORKTRIES; i-- > 0; )\
431 	{\
432 		pid = fORKfN();\
433 		if (pid >= 0)\
434 			break;\
435 		sleep(NFORKTRIES - i);\
436 	}\
437 }
438 /*
439 **  DOFORK -- simple fork interface to DOFORK.
440 **
441 **	Parameters:
442 **		none.
443 **
444 **	Returns:
445 **		pid of child in parent.
446 **		zero in child.
447 **		-1 on error.
448 **
449 **	Side Effects:
450 **		returns twice, once in parent and once in child.
451 */
452 
453 dofork()
454 {
455 	register int pid;
456 
457 	DOFORK(fork);
458 	return (pid);
459 }
460 /*
461 **  SENDOFF -- send off call to mailer & collect response.
462 **
463 **	Parameters:
464 **		e -- the envelope to mail.
465 **		m -- mailer descriptor.
466 **		pvp -- parameter vector to send to it.
467 **		ctladdr -- an address pointer controlling the
468 **			user/groupid etc. of the mailer.
469 **
470 **	Returns:
471 **		exit status of mailer.
472 **
473 **	Side Effects:
474 **		none.
475 */
476 
477 sendoff(e, m, pvp, ctladdr)
478 	register ENVELOPE *e;
479 	MAILER *m;
480 	char **pvp;
481 	ADDRESS *ctladdr;
482 {
483 	auto FILE *mfile;
484 	auto FILE *rfile;
485 	register int i;
486 	int pid;
487 
488 	/*
489 	**  Create connection to mailer.
490 	*/
491 
492 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
493 	if (pid < 0)
494 		return (-1);
495 
496 	/*
497 	**  Format and send message.
498 	**	We ignore broken pipes so that the mailer need not read
499 	**	its input if it is not convenient to do so (e.g., on
500 	**	some error).
501 	*/
502 
503 	(void) signal(SIGPIPE, SIG_IGN);
504 	putfromline(mfile, m);
505 	(*e->e_puthdr)(mfile, m, e);
506 	fprintf(mfile, "\n");
507 	(*e->e_putbody)(mfile, m, FALSE);
508 	(void) fclose(mfile);
509 
510 	i = endmailer(pid, pvp[0]);
511 	giveresponse(i, m);
512 
513 	/* arrange a return receipt if requested */
514 	if (e->e_receiptto != NULL && bitset(M_LOCAL, m->m_flags))
515 	{
516 		e->e_flags |= EF_SENDRECEIPT;
517 		if (ExitStat == EX_OK && Xscript != NULL)
518 			fprintf(Xscript, "%s... successfully delivered\n",
519 				e->e_to);
520 		/* do we want to send back more info? */
521 	}
522 
523 	return (i);
524 }
525 /*
526 **  ENDMAILER -- Wait for mailer to terminate.
527 **
528 **	We should never get fatal errors (e.g., segmentation
529 **	violation), so we report those specially.  For other
530 **	errors, we choose a status message (into statmsg),
531 **	and if it represents an error, we print it.
532 **
533 **	Parameters:
534 **		pid -- pid of mailer.
535 **		name -- name of mailer (for error messages).
536 **
537 **	Returns:
538 **		exit code of mailer.
539 **
540 **	Side Effects:
541 **		none.
542 */
543 
544 endmailer(pid, name)
545 	int pid;
546 	char *name;
547 {
548 	int st;
549 
550 	/* in the IPC case there is nothing to wait for */
551 	if (pid == 0)
552 		return (EX_OK);
553 
554 	/* wait for the mailer process to die and collect status */
555 	st = waitfor(pid);
556 	if (st == -1)
557 	{
558 		syserr("endmailer %s: wait", name);
559 		return (EX_SOFTWARE);
560 	}
561 
562 	/* see if it died a horrid death */
563 	if ((st & 0377) != 0)
564 	{
565 		syserr("endmailer %s: stat %o", name, st);
566 		ExitStat = EX_UNAVAILABLE;
567 		return (EX_UNAVAILABLE);
568 	}
569 
570 	/* normal death -- return status */
571 	st = (st >> 8) & 0377;
572 	return (st);
573 }
574 /*
575 **  OPENMAILER -- open connection to mailer.
576 **
577 **	Parameters:
578 **		m -- mailer descriptor.
579 **		pvp -- parameter vector to pass to mailer.
580 **		ctladdr -- controlling address for user.
581 **		clever -- create a full duplex connection.
582 **		pmfile -- pointer to mfile (to mailer) connection.
583 **		prfile -- pointer to rfile (from mailer) connection.
584 **
585 **	Returns:
586 **		pid of mailer ( > 0 ).
587 **		-1 on error.
588 **		zero on an IPC connection.
589 **
590 **	Side Effects:
591 **		creates a mailer in a subprocess.
592 */
593 
594 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
595 	MAILER *m;
596 	char **pvp;
597 	ADDRESS *ctladdr;
598 	bool clever;
599 	FILE **pmfile;
600 	FILE **prfile;
601 {
602 	int pid;
603 	int mpvect[2];
604 	int rpvect[2];
605 	FILE *mfile;
606 	FILE *rfile;
607 	extern FILE *fdopen();
608 
609 # ifdef DEBUG
610 	if (tTd(11, 1))
611 	{
612 		printf("openmailer:");
613 		printav(pvp);
614 	}
615 # endif DEBUG
616 	errno = 0;
617 
618 	/*
619 	**  Deal with the special case of mail handled through an IPC
620 	**  connection.
621 	**	In this case we don't actually fork.  We must be
622 	**	running SMTP for this to work.  We will return a
623 	**	zero pid to indicate that we are running IPC.
624 	*/
625 
626 	if (strcmp(m->m_mailer, "[IPC]") == 0)
627 	{
628 #ifdef DAEMON
629 		register int i;
630 		register u_short port;
631 
632 		if (!clever)
633 			syserr("non-clever IPC");
634 		if (pvp[2] != NULL)
635 			port = atoi(pvp[2]);
636 		else
637 			port = 0;
638 		i = makeconnection(pvp[1], port, pmfile, prfile);
639 		if (i != EX_OK)
640 		{
641 			ExitStat = i;
642 			return (-1);
643 		}
644 		else
645 			return (0);
646 #else DAEMON
647 		syserr("openmailer: no IPC");
648 		return (-1);
649 #endif DAEMON
650 	}
651 
652 	/* create a pipe to shove the mail through */
653 	if (pipe(mpvect) < 0)
654 	{
655 		syserr("openmailer: 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("openmailer: 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 	if (Xscript != NULL)
676 		(void) fflush(Xscript);			/* for debugging */
677 	(void) fflush(stdout);
678 	DOFORK(XFORK);
679 	/* pid is set by DOFORK */
680 	if (pid < 0)
681 	{
682 		/* failure */
683 		syserr("openmailer: cannot fork");
684 		(void) close(mpvect[0]);
685 		(void) close(mpvect[1]);
686 #ifdef SMTP
687 		if (clever)
688 		{
689 			(void) close(rpvect[0]);
690 			(void) close(rpvect[1]);
691 		}
692 #endif SMTP
693 		return (-1);
694 	}
695 	else if (pid == 0)
696 	{
697 		/* child -- set up input & exec mailer */
698 		/* make diagnostic output be standard output */
699 		(void) signal(SIGINT, SIG_IGN);
700 		(void) signal(SIGHUP, SIG_IGN);
701 		(void) signal(SIGTERM, SIG_DFL);
702 
703 		/* arrange to filter standard & diag output of command */
704 		if (clever)
705 		{
706 			(void) close(rpvect[0]);
707 			(void) close(1);
708 			(void) dup(rpvect[1]);
709 			(void) close(rpvect[1]);
710 		}
711 		else if (OpMode == MD_SMTP || HoldErrs)
712 		{
713 			/* put mailer output in transcript */
714 			(void) close(1);
715 			(void) dup(fileno(Xscript));
716 		}
717 		(void) close(2);
718 		(void) dup(1);
719 
720 		/* arrange to get standard input */
721 		(void) close(mpvect[1]);
722 		(void) close(0);
723 		if (dup(mpvect[0]) < 0)
724 		{
725 			syserr("Cannot dup to zero!");
726 			_exit(EX_OSERR);
727 		}
728 		(void) close(mpvect[0]);
729 		if (!bitset(M_RESTR, m->m_flags))
730 		{
731 			if (ctladdr->q_uid == 0)
732 			{
733 				(void) setgid(DefGid);
734 				(void) setuid(DefUid);
735 			}
736 			else
737 			{
738 				(void) setgid(ctladdr->q_gid);
739 				(void) setuid(ctladdr->q_uid);
740 			}
741 		}
742 
743 		/*
744 		**  We have to be careful with vfork - we can't mung up the
745 		**  memory but we don't want the mailer to inherit any extra
746 		**  open files.  Chances are the mailer won't
747 		**  care about an extra file, but then again you never know.
748 		**  Actually, we would like to close(fileno(pwf)), but it's
749 		**  declared static so we can't.  But if we fclose(pwf), which
750 		**  is what endpwent does, it closes it in the parent too and
751 		**  the next getpwnam will be slower.  If you have a weird
752 		**  mailer that chokes on the extra file you should do the
753 		**  endpwent().			-MRH
754 		**
755 		**  Similar comments apply to log.  However, openlog is
756 		**  clever enough to set the FIOCLEX mode on the file,
757 		**  so it will be closed automatically on the exec.
758 		*/
759 
760 		closeall();
761 
762 		/* try to execute the mailer */
763 		execv(m->m_mailer, pvp);
764 
765 		/* syserr fails because log is closed */
766 		/* syserr("Cannot exec %s", m->m_mailer); */
767 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
768 		(void) fflush(stdout);
769 		_exit(EX_UNAVAILABLE);
770 	}
771 
772 	/*
773 	**  Set up return value.
774 	*/
775 
776 	(void) close(mpvect[0]);
777 	mfile = fdopen(mpvect[1], "w");
778 	if (clever)
779 	{
780 		(void) close(rpvect[1]);
781 		rfile = fdopen(rpvect[0], "r");
782 	}
783 
784 	*pmfile = mfile;
785 	*prfile = rfile;
786 
787 	return (pid);
788 }
789 /*
790 **  GIVERESPONSE -- Interpret an error response from a mailer
791 **
792 **	Parameters:
793 **		stat -- the status code from the mailer (high byte
794 **			only; core dumps must have been taken care of
795 **			already).
796 **		m -- the mailer descriptor for this mailer.
797 **
798 **	Returns:
799 **		none.
800 **
801 **	Side Effects:
802 **		Errors may be incremented.
803 **		ExitStat may be set.
804 */
805 
806 /*ARGSUSED*/
807 giveresponse(stat, m)
808 	int stat;
809 	register MAILER *m;
810 {
811 	register char *statmsg;
812 	extern char *SysExMsg[];
813 	register int i;
814 	extern int N_SysEx;
815 	char buf[30];
816 
817 	/*
818 	**  Compute status message from code.
819 	*/
820 
821 	i = stat - EX__BASE;
822 	if (stat == 0)
823 		statmsg = "250 Sent";
824 	else if (i < 0 || i > N_SysEx)
825 	{
826 		(void) sprintf(buf, "554 unknown mailer error %d", stat);
827 		stat = EX_UNAVAILABLE;
828 		statmsg = buf;
829 	}
830 	else
831 		statmsg = SysExMsg[i];
832 
833 	/*
834 	**  Print the message as appropriate
835 	*/
836 
837 	if (stat == 0)
838 		message(Arpa_Info, &statmsg[4]);
839 	else if (stat == EX_TEMPFAIL)
840 		message(Arpa_Info, "deferred");
841 	else
842 	{
843 		Errors++;
844 		usrerr(statmsg);
845 		CurEnv->e_flags |= EF_FATALERRS;
846 	}
847 
848 	/*
849 	**  Final cleanup.
850 	**	Log a record of the transaction.  Compute the new
851 	**	ExitStat -- if we already had an error, stick with
852 	**	that.
853 	*/
854 
855 	if (LogLevel > ((stat == 0 || stat == EX_TEMPFAIL) ? 3 : 2))
856 		logdelivery(&statmsg[4]);
857 
858 	if (stat != EX_TEMPFAIL)
859 		setstat(stat);
860 }
861 /*
862 **  LOGDELIVERY -- log the delivery in the system log
863 **
864 **	Parameters:
865 **		stat -- the message to print for the status
866 **
867 **	Returns:
868 **		none
869 **
870 **	Side Effects:
871 **		none
872 */
873 
874 logdelivery(stat)
875 	char *stat;
876 {
877 	extern char *pintvl();
878 
879 # ifdef LOG
880 	syslog(LOG_INFO, "%s: to=%s, delay=%s, stat=%s", CurEnv->e_id,
881 	       CurEnv->e_to, pintvl(curtime() - CurEnv->e_ctime, TRUE), stat);
882 # endif LOG
883 }
884 /*
885 **  PUTFROMLINE -- output a UNIX-style from line (or whatever)
886 **
887 **	This can be made an arbitrary message separator by changing $l
888 **
889 **	One of the ugliest hacks seen by human eyes is
890 **	contained herein: UUCP wants those stupid
891 **	"emote from <host>" lines.  Why oh why does a
892 **	well-meaning programmer such as myself have to
893 **	deal with this kind of antique garbage????
894 **
895 **	Parameters:
896 **		fp -- the file to output to.
897 **		m -- the mailer describing this entry.
898 **
899 **	Returns:
900 **		none
901 **
902 **	Side Effects:
903 **		outputs some text to fp.
904 */
905 
906 putfromline(fp, m)
907 	register FILE *fp;
908 	register MAILER *m;
909 {
910 	char buf[MAXLINE];
911 
912 	if (bitset(M_NHDR, m->m_flags))
913 		return;
914 
915 # ifdef UGLYUUCP
916 	if (bitset(M_UGLYUUCP, m->m_flags))
917 	{
918 		extern char *macvalue();
919 		char *sys = macvalue('g', CurEnv);
920 		char *bang = index(sys, '!');
921 
922 		if (bang == NULL)
923 			syserr("No ! in UUCP! (%s)", sys);
924 		else
925 		{
926 			*bang = '\0';
927 			expand("From $f  $d remote from $g\n", buf,
928 					&buf[sizeof buf - 1], CurEnv);
929 			*bang = '!';
930 		}
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 **  PUTBODY -- put the body of a message.
939 **
940 **	Parameters:
941 **		fp -- file to output onto.
942 **		m -- a mailer descriptor.
943 **		xdot -- if set, use SMTP hidden dot algorithm.
944 **
945 **	Returns:
946 **		none.
947 **
948 **	Side Effects:
949 **		The message is written onto fp.
950 */
951 
952 putbody(fp, m, xdot)
953 	FILE *fp;
954 	MAILER *m;
955 	bool xdot;
956 {
957 	char buf[MAXLINE + 1];
958 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
959 
960 	/*
961 	**  Output the body of the message
962 	*/
963 
964 	if (TempFile != NULL)
965 	{
966 		rewind(TempFile);
967 		buf[0] = '.';
968 		while (!ferror(fp) && fgets(&buf[1], sizeof buf - 1, TempFile) != NULL)
969 			putline((xdot && buf[1] == '.') ? buf : &buf[1], fp, fullsmtp);
970 
971 		if (ferror(TempFile))
972 		{
973 			syserr("putbody: read error");
974 			ExitStat = EX_IOERR;
975 		}
976 	}
977 
978 	(void) fflush(fp);
979 	if (ferror(fp) && errno != EPIPE)
980 	{
981 		syserr("putbody: write error");
982 		ExitStat = EX_IOERR;
983 	}
984 	errno = 0;
985 }
986 /*
987 **  MAILFILE -- Send a message to a file.
988 **
989 **	If the file has the setuid/setgid bits set, but NO execute
990 **	bits, sendmail will try to become the owner of that file
991 **	rather than the real user.  Obviously, this only works if
992 **	sendmail runs as root.
993 **
994 **	This could be done as a subordinate mailer, except that it
995 **	is used implicitly to save messages in ~/dead.letter.  We
996 **	view this as being sufficiently important as to include it
997 **	here.  For example, if the system is dying, we shouldn't have
998 **	to create another process plus some pipes to save the message.
999 **
1000 **	Parameters:
1001 **		filename -- the name of the file to send to.
1002 **		ctladdr -- the controlling address header -- includes
1003 **			the userid/groupid to be when sending.
1004 **
1005 **	Returns:
1006 **		The exit code associated with the operation.
1007 **
1008 **	Side Effects:
1009 **		none.
1010 */
1011 
1012 mailfile(filename, ctladdr)
1013 	char *filename;
1014 	ADDRESS *ctladdr;
1015 {
1016 	register FILE *f;
1017 	register int pid;
1018 
1019 	/*
1020 	**  Fork so we can change permissions here.
1021 	**	Note that we MUST use fork, not vfork, because of
1022 	**	the complications of calling subroutines, etc.
1023 	*/
1024 
1025 	DOFORK(fork);
1026 
1027 	if (pid < 0)
1028 		return (EX_OSERR);
1029 	else if (pid == 0)
1030 	{
1031 		/* child -- actually write to file */
1032 		struct stat stb;
1033 
1034 		(void) signal(SIGINT, SIG_DFL);
1035 		(void) signal(SIGHUP, SIG_DFL);
1036 		(void) signal(SIGTERM, SIG_DFL);
1037 		umask(OldUmask);
1038 		if (stat(filename, &stb) < 0)
1039 			stb.st_mode = 0666;
1040 		if (bitset(0111, stb.st_mode))
1041 			exit(EX_CANTCREAT);
1042 		if (ctladdr == NULL)
1043 			ctladdr = &CurEnv->e_from;
1044 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1045 		{
1046 			if (ctladdr->q_uid == 0)
1047 				(void) setgid(DefGid);
1048 			else
1049 				(void) setgid(ctladdr->q_gid);
1050 		}
1051 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1052 		{
1053 			if (ctladdr->q_uid == 0)
1054 				(void) setuid(DefUid);
1055 			else
1056 				(void) setuid(ctladdr->q_uid);
1057 		}
1058 		f = dfopen(filename, "a");
1059 		if (f == NULL)
1060 			exit(EX_CANTCREAT);
1061 
1062 		putfromline(f, ProgMailer);
1063 		(*CurEnv->e_puthdr)(f, ProgMailer, CurEnv);
1064 		fputs("\n", f);
1065 		(*CurEnv->e_putbody)(f, ProgMailer, FALSE);
1066 		fputs("\n", f);
1067 		(void) fclose(f);
1068 		(void) fflush(stdout);
1069 
1070 		/* reset ISUID & ISGID bits for paranoid systems */
1071 		(void) chmod(filename, (int) stb.st_mode);
1072 		exit(EX_OK);
1073 		/*NOTREACHED*/
1074 	}
1075 	else
1076 	{
1077 		/* parent -- wait for exit status */
1078 		int st;
1079 
1080 		st = waitfor(pid);
1081 		if ((st & 0377) != 0)
1082 			return (EX_UNAVAILABLE);
1083 		else
1084 			return ((st >> 8) & 0377);
1085 	}
1086 }
1087 /*
1088 **  SENDALL -- actually send all the messages.
1089 **
1090 **	Parameters:
1091 **		e -- the envelope to send.
1092 **		mode -- the delivery mode to use.
1093 **
1094 **	Returns:
1095 **		none.
1096 **
1097 **	Side Effects:
1098 **		Scans the send lists and sends everything it finds.
1099 **		Delivers any appropriate error messages.
1100 **		If we are running in a non-interactive mode, takes the
1101 **			appropriate action.
1102 */
1103 
1104 sendall(e, mode)
1105 	ENVELOPE *e;
1106 	char mode;
1107 {
1108 	register ADDRESS *q;
1109 	bool oldverbose;
1110 	int pid;
1111 
1112 #ifdef DEBUG
1113 	if (tTd(13, 1))
1114 	{
1115 		printf("\nSENDALL: mode %c, sendqueue:\n", mode);
1116 		printaddr(e->e_sendqueue, TRUE);
1117 	}
1118 #endif DEBUG
1119 
1120 	/*
1121 	**  Do any preprocessing necessary for the mode we are running.
1122 	**	Check to make sure the hop count is reasonable.
1123 	**	Delete sends to the sender in mailing lists.
1124 	*/
1125 
1126 	CurEnv = e;
1127 
1128 	if (e->e_hopcount > MAXHOP)
1129 	{
1130 		syserr("sendall: too many hops (%d max)", MAXHOP);
1131 		return;
1132 	}
1133 
1134 	if (!MeToo)
1135 	{
1136 		e->e_from.q_flags |= QDONTSEND;
1137 		recipient(&e->e_from, &e->e_sendqueue);
1138 	}
1139 
1140 # ifdef QUEUE
1141 	if ((mode == SM_QUEUE || mode == SM_FORK ||
1142 	     (mode != SM_VERIFY && SuperSafe)) &&
1143 	    !bitset(EF_INQUEUE, e->e_flags))
1144 		queueup(e, TRUE, mode == SM_QUEUE);
1145 #endif QUEUE
1146 
1147 	oldverbose = Verbose;
1148 	switch (mode)
1149 	{
1150 	  case SM_VERIFY:
1151 		Verbose = TRUE;
1152 		break;
1153 
1154 	  case SM_QUEUE:
1155 		e->e_flags |= EF_INQUEUE|EF_KEEPQUEUE;
1156 		return;
1157 
1158 	  case SM_FORK:
1159 		if (Xscript != NULL)
1160 			(void) fflush(Xscript);
1161 		pid = fork();
1162 		if (pid < 0)
1163 		{
1164 			mode = SM_DELIVER;
1165 			break;
1166 		}
1167 		else if (pid > 0)
1168 		{
1169 			/* be sure we leave the temp files to our child */
1170 			e->e_id = e->e_df = NULL;
1171 			return;
1172 		}
1173 
1174 		/* double fork to avoid zombies */
1175 		if (fork() > 0)
1176 			exit(EX_OK);
1177 
1178 		/* be sure we are immune from the terminal */
1179 		disconnect();
1180 
1181 		break;
1182 	}
1183 
1184 	/*
1185 	**  Run through the list and send everything.
1186 	*/
1187 
1188 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1189 	{
1190 		if (mode == SM_VERIFY)
1191 		{
1192 			e->e_to = q->q_paddr;
1193 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1194 				message(Arpa_Info, "deliverable");
1195 		}
1196 		else
1197 			(void) deliver(e, q);
1198 	}
1199 	Verbose = oldverbose;
1200 
1201 	/*
1202 	**  Now run through and check for errors.
1203 	*/
1204 
1205 	if (mode == SM_VERIFY)
1206 		return;
1207 
1208 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1209 	{
1210 		register ADDRESS *qq;
1211 
1212 # ifdef DEBUG
1213 		if (tTd(13, 3))
1214 		{
1215 			printf("Checking ");
1216 			printaddr(q, FALSE);
1217 		}
1218 # endif DEBUG
1219 
1220 		/* only send errors if the message failed */
1221 		if (!bitset(QBADADDR, q->q_flags))
1222 			continue;
1223 
1224 		/* we have an address that failed -- find the parent */
1225 		for (qq = q; qq != NULL; qq = qq->q_alias)
1226 		{
1227 			char obuf[MAXNAME + 6];
1228 			extern char *aliaslookup();
1229 
1230 			/* we can only have owners for local addresses */
1231 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1232 				continue;
1233 
1234 			/* see if the owner list exists */
1235 			(void) strcpy(obuf, "owner-");
1236 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1237 				(void) strcat(obuf, "owner");
1238 			else
1239 				(void) strcat(obuf, qq->q_user);
1240 			if (aliaslookup(obuf) == NULL)
1241 				continue;
1242 
1243 # ifdef DEBUG
1244 			if (tTd(13, 4))
1245 				printf("Errors to %s\n", obuf);
1246 # endif DEBUG
1247 
1248 			/* owner list exists -- add it to the error queue */
1249 			sendto(obuf, (ADDRESS *) NULL, &e->e_errorqueue);
1250 			ErrorMode == EM_MAIL;
1251 			break;
1252 		}
1253 
1254 		/* if we did not find an owner, send to the sender */
1255 		if (qq == NULL && bitset(QBADADDR, q->q_flags))
1256 			sendto(e->e_from.q_paddr, qq, &e->e_errorqueue);
1257 	}
1258 
1259 	if (mode == SM_FORK)
1260 		finis();
1261 }
1262