1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # include <sys/stat.h>
5 # ifdef LOG
6 # include <syslog.h>
7 # endif LOG
8 
9 static char SccsId[] = "@(#)deliver.c	3.57	11/27/81";
10 
11 /*
12 **  DELIVER -- Deliver a message to a list of addresses.
13 **
14 **	This routine delivers to everyone on the same host as the
15 **	user on the head of the list.  It is clever about mailers
16 **	that don't handle multiple users.  It is NOT guaranteed
17 **	that it will deliver to all these addresses however -- so
18 **	deliver should be called once for each address on the
19 **	list.
20 **
21 **	Parameters:
22 **		firstto -- head of the address list to deliver to.
23 **		editfcn -- if non-NULL, we want to call this function
24 **			to output the letter (instead of just out-
25 **			putting it raw).
26 **
27 **	Returns:
28 **		zero -- successfully delivered.
29 **		else -- some failure, see ExitStat for more info.
30 **
31 **	Side Effects:
32 **		The standard input is passed off to someone.
33 */
34 
35 deliver(firstto, editfcn)
36 	ADDRESS *firstto;
37 	int (*editfcn)();
38 {
39 	char *host;			/* host being sent to */
40 	char *user;			/* user being sent to */
41 	char **pvp;
42 	register char **mvp;
43 	register char *p;
44 	register struct mailer *m;	/* mailer for this recipient */
45 	register int i;
46 	extern putmessage();
47 	extern bool checkcompat();
48 	char *pv[MAXPV+1];
49 	char tobuf[MAXLINE];		/* text line of to people */
50 	char buf[MAXNAME];
51 	ADDRESS *ctladdr;
52 	extern ADDRESS *getctladdr();
53 	char tfrombuf[MAXNAME];		/* translated from person */
54 	extern char **prescan();
55 	register ADDRESS *to = firstto;
56 	bool clever = FALSE;		/* running user smtp to this mailer */
57 	bool tempfail = FALSE;
58 	ADDRESS *tochain = NULL;	/* chain of users in this mailer call */
59 
60 	errno = 0;
61 	if (!ForceMail && bitset(QDONTSEND, to->q_flags))
62 		return (0);
63 
64 # ifdef DEBUG
65 	if (Debug)
66 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
67 			to->q_mailer->m_mno, to->q_host, to->q_user);
68 # endif DEBUG
69 
70 	/*
71 	**  Do initial argv setup.
72 	**	Insert the mailer name.  Notice that $x expansion is
73 	**	NOT done on the mailer name.  Then, if the mailer has
74 	**	a picky -f flag, we insert it as appropriate.  This
75 	**	code does not check for 'pv' overflow; this places a
76 	**	manifest lower limit of 4 for MAXPV.
77 	*/
78 
79 	m = to->q_mailer;
80 	host = to->q_host;
81 
82 	/* rewrite from address, using rewriting rules */
83 	(void) expand(m->m_from, buf, &buf[sizeof buf - 1]);
84 	mvp = prescan(buf, '\0');
85 	if (mvp == NULL)
86 	{
87 		syserr("bad mailer from translate \"%s\"", buf);
88 		return (EX_SOFTWARE);
89 	}
90 	rewrite(mvp, 2);
91 	cataddr(mvp, tfrombuf, sizeof tfrombuf);
92 
93 	define('g', tfrombuf);		/* translated sender address */
94 	define('h', host);		/* to host */
95 	Errors = 0;
96 	pvp = pv;
97 	*pvp++ = m->m_argv[0];
98 
99 	/* insert -f or -r flag as appropriate */
100 	if (bitset(M_FOPT|M_ROPT, m->m_flags) && FromFlag)
101 	{
102 		if (bitset(M_FOPT, m->m_flags))
103 			*pvp++ = "-f";
104 		else
105 			*pvp++ = "-r";
106 		(void) expand("$g", buf, &buf[sizeof buf - 1]);
107 		*pvp++ = newstr(buf);
108 	}
109 
110 	/*
111 	**  Append the other fixed parts of the argv.  These run
112 	**  up to the first entry containing "$u".  There can only
113 	**  be one of these, and there are only a few more slots
114 	**  in the pv after it.
115 	*/
116 
117 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
118 	{
119 		while ((p = index(p, '$')) != NULL)
120 			if (*++p == 'u')
121 				break;
122 		if (p != NULL)
123 			break;
124 
125 		/* this entry is safe -- go ahead and process it */
126 		(void) expand(*mvp, buf, &buf[sizeof buf - 1]);
127 		*pvp++ = newstr(buf);
128 		if (pvp >= &pv[MAXPV - 3])
129 		{
130 			syserr("Too many parameters to %s before $u", pv[0]);
131 			return (-1);
132 		}
133 	}
134 
135 	if (*mvp == NULL)
136 	{
137 		/* running SMTP */
138 		clever = TRUE;
139 		*pvp = NULL;
140 		i = smtpinit(m, pv, (ADDRESS *) NULL);
141 		giveresponse(i, TRUE, m);
142 		if (i == EX_TEMPFAIL)
143 		{
144 			QueueUp = TRUE;
145 			tempfail = TRUE;
146 		}
147 	}
148 
149 	/*
150 	**  At this point *mvp points to the argument with $u.  We
151 	**  run through our address list and append all the addresses
152 	**  we can.  If we run out of space, do not fret!  We can
153 	**  always send another copy later.
154 	*/
155 
156 	tobuf[0] = '\0';
157 	To = tobuf;
158 	ctladdr = NULL;
159 	for (; to != NULL; to = to->q_next)
160 	{
161 		/* avoid sending multiple recipients to dumb mailers */
162 		if (tobuf[0] != '\0' && !bitset(M_MUSER, m->m_flags))
163 			break;
164 
165 		/* if already sent or not for this host, don't send */
166 		if ((!ForceMail && bitset(QDONTSEND, to->q_flags)) ||
167 		    strcmp(to->q_host, host) != 0 || to->q_mailer != firstto->q_mailer)
168 			continue;
169 
170 # ifdef DEBUG
171 		if (Debug)
172 		{
173 			printf("\nsend to ");
174 			printaddr(to, FALSE);
175 		}
176 # endif DEBUG
177 
178 		/* link together the chain of recipients */
179 		if (!bitset(QDONTSEND, to->q_flags))
180 		{
181 			to->q_tchain = tochain;
182 			tochain = to;
183 		}
184 
185 		/* compute effective uid/gid when sending */
186 		if (to->q_mailer == ProgMailer)
187 			ctladdr = getctladdr(to);
188 
189 		user = to->q_user;
190 		To = to->q_paddr;
191 		to->q_flags |= QDONTSEND;
192 		if (tempfail)
193 		{
194 			to->q_flags |= QQUEUEUP;
195 			continue;
196 		}
197 
198 		/*
199 		**  Check to see that these people are allowed to
200 		**  talk to each other.
201 		*/
202 
203 		if (!checkcompat(to))
204 		{
205 			giveresponse(EX_UNAVAILABLE, TRUE, m);
206 			continue;
207 		}
208 
209 		/*
210 		**  Strip quote bits from names if the mailer is dumb
211 		**	about them.
212 		*/
213 
214 		if (bitset(M_STRIPQ, m->m_flags))
215 		{
216 			stripquotes(user, TRUE);
217 			stripquotes(host, TRUE);
218 		}
219 		else
220 		{
221 			stripquotes(user, FALSE);
222 			stripquotes(host, FALSE);
223 		}
224 
225 		/*
226 		**  If an error message has already been given, don't
227 		**	bother to send to this address.
228 		**
229 		**	>>>>>>>>>> This clause assumes that the local mailer
230 		**	>> NOTE >> cannot do any further aliasing; that
231 		**	>>>>>>>>>> function is subsumed by sendmail.
232 		*/
233 
234 		if (bitset(QBADADDR, to->q_flags))
235 			continue;
236 
237 		/* save statistics.... */
238 		Stat.stat_nt[to->q_mailer->m_mno]++;
239 		Stat.stat_bt[to->q_mailer->m_mno] += kbytes(MsgSize);
240 
241 		/*
242 		**  See if this user name is "special".
243 		**	If the user name has a slash in it, assume that this
244 		**	is a file -- send it off without further ado.
245 		**	Note that this means that editfcn's will not
246 		**	be applied to the message.  Also note that
247 		**	this type of addresses is not processed along
248 		**	with the others, so we fudge on the To person.
249 		*/
250 
251 		if (m == LocalMailer)
252 		{
253 			if (index(user, '/') != NULL)
254 			{
255 				i = mailfile(user, getctladdr(to));
256 				giveresponse(i, TRUE, m);
257 				continue;
258 			}
259 		}
260 
261 		/*
262 		**  Address is verified -- add this user to mailer
263 		**  argv, and add it to the print list of recipients.
264 		*/
265 
266 		/* create list of users for error messages */
267 		if (tobuf[0] != '\0')
268 			(void) strcat(tobuf, ",");
269 		(void) strcat(tobuf, to->q_paddr);
270 		define('u', user);		/* to user */
271 		define('z', to->q_home);	/* user's home */
272 
273 		/*
274 		**  Expand out this user into argument list or
275 		**  send it to our SMTP server.
276 		*/
277 
278 		if (clever)
279 		{
280 			i = smtprcpt(to);
281 			if (i == EX_TEMPFAIL)
282 			{
283 				QueueUp = TRUE;
284 				to->q_flags |= QQUEUEUP;
285 			}
286 			else if (i != EX_OK)
287 			{
288 				to->q_flags |= QBADADDR;
289 				giveresponse(i, TRUE, m);
290 			}
291 		}
292 		else
293 		{
294 			(void) expand(*mvp, buf, &buf[sizeof buf - 1]);
295 			*pvp++ = newstr(buf);
296 			if (pvp >= &pv[MAXPV - 2])
297 			{
298 				/* allow some space for trailing parms */
299 				break;
300 			}
301 		}
302 	}
303 
304 	/* see if any addresses still exist */
305 	if (tobuf[0] == '\0')
306 	{
307 		if (clever)
308 			smtpquit(pv[0]);
309 		return (0);
310 	}
311 
312 	/* print out messages as full list */
313 	To = tobuf;
314 
315 	/*
316 	**  Fill out any parameters after the $u parameter.
317 	*/
318 
319 	while (!clever && *++mvp != NULL)
320 	{
321 		(void) expand(*mvp, buf, &buf[sizeof buf - 1]);
322 		*pvp++ = newstr(buf);
323 		if (pvp >= &pv[MAXPV])
324 			syserr("deliver: pv overflow after $u for %s", pv[0]);
325 	}
326 	*pvp++ = NULL;
327 
328 	/*
329 	**  Call the mailer.
330 	**	The argument vector gets built, pipes
331 	**	are created as necessary, and we fork & exec as
332 	**	appropriate.
333 	**	If we are running SMTP, we just need to clean up.
334 	*/
335 
336 	if (editfcn == NULL)
337 		editfcn = putmessage;
338 	if (ctladdr == NULL)
339 		ctladdr = &From;
340 	if (clever)
341 	{
342 		i = smtpfinish(m, editfcn);
343 		smtpquit(pv[0]);
344 	}
345 	else
346 		i = sendoff(m, pv, editfcn, ctladdr);
347 
348 	/*
349 	**  If we got a temporary failure, arrange to queue the
350 	**  addressees.
351 	*/
352 
353 	if (i == EX_TEMPFAIL)
354 	{
355 		QueueUp = TRUE;
356 		for (to = tochain; to != NULL; to = to->q_tchain)
357 			to->q_flags |= QQUEUEUP;
358 	}
359 
360 	errno = 0;
361 	return (i);
362 }
363 /*
364 **  DOFORK -- do a fork, retrying a couple of times on failure.
365 **
366 **	This MUST be a macro, since after a vfork we are running
367 **	two processes on the same stack!!!
368 **
369 **	Parameters:
370 **		none.
371 **
372 **	Returns:
373 **		From a macro???  You've got to be kidding!
374 **
375 **	Side Effects:
376 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
377 **			pid of child in parent, zero in child.
378 **			-1 on unrecoverable error.
379 **
380 **	Notes:
381 **		I'm awfully sorry this looks so awful.  That's
382 **		vfork for you.....
383 */
384 
385 # define NFORKTRIES	5
386 # ifdef VFORK
387 # define XFORK	vfork
388 # else VFORK
389 # define XFORK	fork
390 # endif VFORK
391 
392 # define DOFORK(fORKfN) \
393 {\
394 	register int i;\
395 \
396 	for (i = NFORKTRIES; i-- > 0; )\
397 	{\
398 		pid = fORKfN();\
399 		if (pid >= 0)\
400 			break;\
401 		sleep((unsigned) NFORKTRIES - i);\
402 	}\
403 }
404 /*
405 **  DOFORK -- simple fork interface to DOFORK.
406 **
407 **	Parameters:
408 **		none.
409 **
410 **	Returns:
411 **		pid of child in parent.
412 **		zero in child.
413 **		-1 on error.
414 **
415 **	Side Effects:
416 **		returns twice, once in parent and once in child.
417 */
418 
419 dofork()
420 {
421 	register int pid;
422 
423 	DOFORK(fork);
424 	return (pid);
425 }
426 /*
427 **  SENDOFF -- send off call to mailer & collect response.
428 **
429 **	Parameters:
430 **		m -- mailer descriptor.
431 **		pvp -- parameter vector to send to it.
432 **		editfcn -- function to pipe it through.
433 **		ctladdr -- an address pointer controlling the
434 **			user/groupid etc. of the mailer.
435 **
436 **	Returns:
437 **		exit status of mailer.
438 **
439 **	Side Effects:
440 **		none.
441 */
442 
443 sendoff(m, pvp, editfcn, ctladdr)
444 	struct mailer *m;
445 	char **pvp;
446 	int (*editfcn)();
447 	ADDRESS *ctladdr;
448 {
449 	auto FILE *mfile;
450 	auto FILE *rfile;
451 	register int i;
452 	extern putmessage();
453 	int pid;
454 
455 	/*
456 	**  Create connection to mailer.
457 	*/
458 
459 	pid = openmailer(m, pvp, ctladdr, FALSE, &mfile, &rfile);
460 	if (pid < 0)
461 		return (-1);
462 
463 	/*
464 	**  Format and send message.
465 	*/
466 
467 	(void) signal(SIGPIPE, SIG_IGN);
468 	if (editfcn == NULL)
469 		editfcn = putmessage;
470 
471 	(*editfcn)(mfile, m, FALSE);
472 	(void) fclose(mfile);
473 
474 	i = endmailer(pid, pvp[0]);
475 	giveresponse(i, TRUE, m);
476 	return (i);
477 }
478 /*
479 **  ENDMAILER -- Wait for mailer to terminate.
480 **
481 **	We should never get fatal errors (e.g., segmentation
482 **	violation), so we report those specially.  For other
483 **	errors, we choose a status message (into statmsg),
484 **	and if it represents an error, we print it.
485 **
486 **	Parameters:
487 **		pid -- pid of mailer.
488 **		name -- name of mailer (for error messages).
489 **
490 **	Returns:
491 **		exit code of mailer.
492 **
493 **	Side Effects:
494 **		none.
495 */
496 
497 endmailer(pid, name)
498 	int pid;
499 	char *name;
500 {
501 	register int i;
502 	auto int st;
503 
504 	while ((i = wait(&st)) > 0 && i != pid)
505 		continue;
506 	if (i < 0)
507 	{
508 		syserr("wait");
509 		return (-1);
510 	}
511 	if ((st & 0377) != 0)
512 	{
513 		syserr("%s: stat %o", name, st);
514 		ExitStat = EX_UNAVAILABLE;
515 		return (-1);
516 	}
517 	i = (st >> 8) & 0377;
518 	return (i);
519 }
520 /*
521 **  OPENMAILER -- open connection to mailer.
522 **
523 **	Parameters:
524 **		m -- mailer descriptor.
525 **		pvp -- parameter vector to pass to mailer.
526 **		ctladdr -- controlling address for user.
527 **		clever -- create a full duplex connection.
528 **		pmfile -- pointer to mfile (to mailer) connection.
529 **		prfile -- pointer to rfile (from mailer) connection.
530 **
531 **	Returns:
532 **		pid of mailer.
533 **		-1 on error.
534 **
535 **	Side Effects:
536 **		creates a mailer in a subprocess.
537 */
538 
539 openmailer(m, pvp, ctladdr, clever, pmfile, prfile)
540 	struct mailer *m;
541 	char **pvp;
542 	ADDRESS *ctladdr;
543 	bool clever;
544 	FILE **pmfile;
545 	FILE **prfile;
546 {
547 	int pid;
548 	int mpvect[2];
549 	int rpvect[2];
550 	FILE *mfile;
551 	FILE *rfile;
552 	extern FILE *fdopen();
553 
554 # ifdef DEBUG
555 	if (Debug)
556 	{
557 		printf("openmailer:\n");
558 		printav(pvp);
559 	}
560 # endif DEBUG
561 	errno = 0;
562 
563 	/* create a pipe to shove the mail through */
564 	if (pipe(mpvect) < 0)
565 	{
566 		syserr("pipe (to mailer)");
567 		return (-1);
568 	}
569 
570 	/* if this mailer speaks smtp, create a return pipe */
571 	if (clever && pipe(rpvect) < 0)
572 	{
573 		syserr("pipe (from mailer)");
574 		(void) close(mpvect[0]);
575 		(void) close(mpvect[1]);
576 		return (-1);
577 	}
578 
579 	DOFORK(XFORK);
580 	/* pid is set by DOFORK */
581 	if (pid < 0)
582 	{
583 		syserr("Cannot fork");
584 		(void) close(mpvect[0]);
585 		(void) close(mpvect[1]);
586 		if (clever)
587 		{
588 			(void) close(rpvect[0]);
589 			(void) close(rpvect[1]);
590 		}
591 		return (-1);
592 	}
593 	else if (pid == 0)
594 	{
595 		/* child -- set up input & exec mailer */
596 		/* make diagnostic output be standard output */
597 		(void) signal(SIGINT, SIG_IGN);
598 		(void) signal(SIGHUP, SIG_IGN);
599 		(void) signal(SIGTERM, SIG_DFL);
600 
601 		/* arrange to filter standard & diag output of command */
602 		if (clever)
603 		{
604 			(void) close(rpvect[0]);
605 			(void) close(1);
606 			(void) dup(rpvect[1]);
607 			(void) close(rpvect[1]);
608 		}
609 		else if (OutChannel != stdout)
610 		{
611 			(void) close(1);
612 			(void) dup(fileno(OutChannel));
613 		}
614 		(void) close(2);
615 		(void) dup(1);
616 
617 		/* arrange to get standard input */
618 		(void) close(mpvect[1]);
619 		(void) close(0);
620 		if (dup(mpvect[0]) < 0)
621 		{
622 			syserr("Cannot dup to zero!");
623 			_exit(EX_OSERR);
624 		}
625 		(void) close(mpvect[0]);
626 		if (!bitset(M_RESTR, m->m_flags))
627 		{
628 			if (ctladdr->q_uid == 0)
629 			{
630 				extern int DefUid, DefGid;
631 
632 				(void) setgid(DefGid);
633 				(void) setuid(DefUid);
634 			}
635 			else
636 			{
637 				(void) setgid(ctladdr->q_gid);
638 				(void) setuid(ctladdr->q_uid);
639 			}
640 		}
641 # ifndef VFORK
642 		/*
643 		**  We have to be careful with vfork - we can't mung up the
644 		**  memory but we don't want the mailer to inherit any extra
645 		**  open files.  Chances are the mailer won't
646 		**  care about an extra file, but then again you never know.
647 		**  Actually, we would like to close(fileno(pwf)), but it's
648 		**  declared static so we can't.  But if we fclose(pwf), which
649 		**  is what endpwent does, it closes it in the parent too and
650 		**  the next getpwnam will be slower.  If you have a weird
651 		**  mailer that chokes on the extra file you should do the
652 		**  endpwent().
653 		**
654 		**  Similar comments apply to log.  However, openlog is
655 		**  clever enough to set the FIOCLEX mode on the file,
656 		**  so it will be closed automatically on the exec.
657 		*/
658 
659 		endpwent();
660 # ifdef LOG
661 		closelog();
662 # endif LOG
663 # endif VFORK
664 		execv(m->m_mailer, pvp);
665 		/* syserr fails because log is closed */
666 		/* syserr("Cannot exec %s", m->m_mailer); */
667 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
668 		(void) fflush(stdout);
669 		_exit(EX_UNAVAILABLE);
670 	}
671 
672 	/*
673 	**  Set up return value.
674 	*/
675 
676 	(void) close(mpvect[0]);
677 	mfile = fdopen(mpvect[1], "w");
678 	if (clever)
679 	{
680 		(void) close(rpvect[1]);
681 		rfile = fdopen(rpvect[0], "r");
682 	}
683 
684 	*pmfile = mfile;
685 	*prfile = rfile;
686 
687 	return (pid);
688 }
689 /*
690 **  GIVERESPONSE -- Interpret an error response from a mailer
691 **
692 **	Parameters:
693 **		stat -- the status code from the mailer (high byte
694 **			only; core dumps must have been taken care of
695 **			already).
696 **		force -- if set, force an error message output, even
697 **			if the mailer seems to like to print its own
698 **			messages.
699 **		m -- the mailer descriptor for this mailer.
700 **
701 **	Returns:
702 **		none.
703 **
704 **	Side Effects:
705 **		Errors may be incremented.
706 **		ExitStat may be set.
707 */
708 
709 giveresponse(stat, force, m)
710 	int stat;
711 	int force;
712 	register struct mailer *m;
713 {
714 	register char *statmsg;
715 	extern char *SysExMsg[];
716 	register int i;
717 	extern int N_SysEx;
718 	char buf[30];
719 
720 	/*
721 	**  Compute status message from code.
722 	*/
723 
724 	i = stat - EX__BASE;
725 	if (i < 0 || i > N_SysEx)
726 		statmsg = NULL;
727 	else
728 		statmsg = SysExMsg[i];
729 	if (stat == 0)
730 	{
731 		if (bitset(M_LOCAL, m->m_flags))
732 			statmsg = "delivered";
733 		else
734 			statmsg = "queued";
735 		if (Verbose)
736 			message(Arpa_Info, statmsg);
737 	}
738 	else if (stat == EX_TEMPFAIL)
739 	{
740 		if (Verbose)
741 			message(Arpa_Info, "transmission deferred");
742 	}
743 	else
744 	{
745 		Errors++;
746 		if (statmsg == NULL && m->m_badstat != 0)
747 		{
748 			stat = m->m_badstat;
749 			i = stat - EX__BASE;
750 # ifdef DEBUG
751 			if (i < 0 || i >= N_SysEx)
752 				syserr("Bad m_badstat %d", stat);
753 			else
754 # endif DEBUG
755 			statmsg = SysExMsg[i];
756 		}
757 		if (statmsg == NULL)
758 			usrerr("unknown mailer response %d", stat);
759 		else if (force || !bitset(M_QUIET, m->m_flags) || Verbose)
760 			usrerr("%s", statmsg);
761 	}
762 
763 	/*
764 	**  Final cleanup.
765 	**	Log a record of the transaction.  Compute the new
766 	**	ExitStat -- if we already had an error, stick with
767 	**	that.
768 	*/
769 
770 	if (statmsg == NULL)
771 	{
772 		(void) sprintf(buf, "error %d", stat);
773 		statmsg = buf;
774 	}
775 
776 # ifdef LOG
777 	syslog(LOG_INFO, "%s->%s: %ld: %s", From.q_paddr, To, MsgSize, statmsg);
778 # endif LOG
779 	if (stat != EX_TEMPFAIL)
780 		setstat(stat);
781 }
782 /*
783 **  PUTMESSAGE -- output a message to the final mailer.
784 **
785 **	This routine takes care of recreating the header from the
786 **	in-core copy, etc.
787 **
788 **	Parameters:
789 **		fp -- file to output onto.
790 **		m -- a mailer descriptor.
791 **		xdot -- if set, hide lines beginning with dot.
792 **
793 **	Returns:
794 **		none.
795 **
796 **	Side Effects:
797 **		The message is written onto fp.
798 */
799 
800 putmessage(fp, m, xdot)
801 	FILE *fp;
802 	struct mailer *m;
803 	bool xdot;
804 {
805 	char buf[BUFSIZ];
806 	register HDR *h;
807 	extern char *arpadate();
808 	bool anyheader = FALSE;
809 	extern char *capitalize();
810 	extern char *hvalue();
811 	extern bool samefrom();
812 	char *of_line;
813 
814 	/*
815 	**  Output "From" line unless supressed
816 	**
817 	**  >>>>>>>>>>	One of the ugliest hacks seen by human eyes is
818 	**  >>>>>>>>>>	contained herein: UUCP wants those stupid
819 	**  >> NOTE >>	"remote from <host>" lines.  Why oh why does a
820 	**  >>>>>>>>>>	well-meaning programmer such as myself have to
821 	**  >>>>>>>>>>	deal with this kind of antique garbage????
822 	*/
823 
824 	if (!bitset(M_NHDR, m->m_flags))
825 	{
826 		if (strcmp(m->m_name, "uucp") == 0)
827 			(void) expand("From $f  $d remote from $h", buf,
828 					&buf[sizeof buf - 1]);
829 		else
830 			(void) expand("$l", buf, &buf[sizeof buf - 1]);
831 		fprintf(fp, "%s\n", buf);
832 	}
833 
834 	/*
835 	**  Output all header lines
836 	*/
837 
838 	of_line = hvalue("original-from");
839 	for (h = Header; h != NULL; h = h->h_link)
840 	{
841 		register char *p;
842 		char *origfrom = OrigFrom;
843 		bool nooutput;
844 
845 		nooutput = FALSE;
846 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
847 		{
848 			p = ")><(";		/* can't happen (I hope) */
849 			nooutput = TRUE;
850 		}
851 
852 		/* use From: line from message if generated is the same */
853 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
854 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
855 		{
856 			p = origfrom;
857 			origfrom = NULL;
858 		}
859 		else if (bitset(H_DEFAULT, h->h_flags))
860 		{
861 			(void) expand(h->h_value, buf, &buf[sizeof buf]);
862 			p = buf;
863 		}
864 		else
865 			p = h->h_value;
866 		if (p == NULL || *p == '\0')
867 			continue;
868 
869 		/* hack, hack -- output Original-From field if different */
870 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
871 		{
872 			/* output new Original-From line if needed */
873 			if (of_line == NULL && !samefrom(p, origfrom))
874 			{
875 				fprintf(fp, "Original-From: %s\n", origfrom);
876 				anyheader = TRUE;
877 			}
878 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
879 			{
880 				/* delete Original-From: line if redundant */
881 				p = of_line;
882 				of_line = NULL;
883 			}
884 		}
885 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
886 			nooutput = TRUE;
887 
888 		/* finally, output the header line */
889 		if (!nooutput)
890 		{
891 			fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
892 			h->h_flags |= H_USED;
893 			anyheader = TRUE;
894 		}
895 	}
896 	if (anyheader)
897 		fprintf(fp, "\n");
898 
899 	/*
900 	**  Output the body of the message
901 	*/
902 
903 	if (TempFile != NULL)
904 	{
905 		rewind(TempFile);
906 		while (!ferror(fp) && fgets(buf, sizeof buf, TempFile) != NULL)
907 			fprintf(fp, "%s%s", xdot && buf[0] == '.' ? "." : "", buf);
908 
909 		if (ferror(TempFile))
910 		{
911 			syserr("putmessage: read error");
912 			setstat(EX_IOERR);
913 		}
914 	}
915 
916 	(void) fflush(fp);
917 	if (ferror(fp) && errno != EPIPE)
918 	{
919 		syserr("putmessage: write error");
920 		setstat(EX_IOERR);
921 	}
922 	errno = 0;
923 }
924 /*
925 **  SAMEFROM -- tell if two text addresses represent the same from address.
926 **
927 **	Parameters:
928 **		ifrom -- internally generated form of from address.
929 **		efrom -- external form of from address.
930 **
931 **	Returns:
932 **		TRUE -- if they convey the same info.
933 **		FALSE -- if any information has been lost.
934 **
935 **	Side Effects:
936 **		none.
937 */
938 
939 bool
940 samefrom(ifrom, efrom)
941 	char *ifrom;
942 	char *efrom;
943 {
944 	register char *p;
945 	char buf[MAXNAME + 4];
946 
947 # ifdef DEBUG
948 	if (Debug > 7)
949 		printf("samefrom(%s,%s)-->", ifrom, efrom);
950 # endif DEBUG
951 	if (strcmp(ifrom, efrom) == 0)
952 		goto success;
953 	p = index(ifrom, '@');
954 	if (p == NULL)
955 		goto failure;
956 	*p = '\0';
957 	strcpy(buf, ifrom);
958 	strcat(buf, " at ");
959 	*p++ = '@';
960 	strcat(buf, p);
961 	if (strcmp(buf, efrom) == 0)
962 		goto success;
963 
964   failure:
965 # ifdef DEBUG
966 	if (Debug > 7)
967 		printf("FALSE\n");
968 # endif DEBUG
969 	return (FALSE);
970 
971   success:
972 # ifdef DEBUG
973 	if (Debug > 7)
974 		printf("TRUE\n");
975 # endif DEBUG
976 	return (TRUE);
977 }
978 /*
979 **  MAILFILE -- Send a message to a file.
980 **
981 **	If the file has the setuid/setgid bits set, but NO execute
982 **	bits, sendmail will try to become the owner of that file
983 **	rather than the real user.  Obviously, this only works if
984 **	sendmail runs as root.
985 **
986 **	Parameters:
987 **		filename -- the name of the file to send to.
988 **		ctladdr -- the controlling address header -- includes
989 **			the userid/groupid to be when sending.
990 **
991 **	Returns:
992 **		The exit code associated with the operation.
993 **
994 **	Side Effects:
995 **		none.
996 */
997 
998 mailfile(filename, ctladdr)
999 	char *filename;
1000 	ADDRESS *ctladdr;
1001 {
1002 	register FILE *f;
1003 	register int pid;
1004 
1005 	/*
1006 	**  Fork so we can change permissions here.
1007 	**	Note that we MUST use fork, not vfork, because of
1008 	**	the complications of calling subroutines, etc.
1009 	*/
1010 
1011 	DOFORK(fork);
1012 
1013 	if (pid < 0)
1014 		return (EX_OSERR);
1015 	else if (pid == 0)
1016 	{
1017 		/* child -- actually write to file */
1018 		struct stat stb;
1019 		extern int DefUid, DefGid;
1020 
1021 		(void) signal(SIGINT, SIG_DFL);
1022 		(void) signal(SIGHUP, SIG_DFL);
1023 		(void) signal(SIGTERM, SIG_DFL);
1024 		umask(OldUmask);
1025 		if (stat(filename, &stb) < 0)
1026 			stb.st_mode = 0666;
1027 		if (bitset(0111, stb.st_mode))
1028 			exit(EX_CANTCREAT);
1029 		if (ctladdr == NULL)
1030 			ctladdr = &From;
1031 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1032 		{
1033 			if (ctladdr->q_uid == 0)
1034 				(void) setgid(DefGid);
1035 			else
1036 				(void) setgid(ctladdr->q_gid);
1037 		}
1038 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1039 		{
1040 			if (ctladdr->q_uid == 0)
1041 				(void) setuid(DefUid);
1042 			else
1043 				(void) setuid(ctladdr->q_uid);
1044 		}
1045 		f = fopen(filename, "a");
1046 		if (f == NULL)
1047 			exit(EX_CANTCREAT);
1048 
1049 		putmessage(f, Mailer[1], FALSE);
1050 		fputs("\n", f);
1051 		(void) fclose(f);
1052 		(void) fflush(stdout);
1053 
1054 		/* reset ISUID & ISGID bits */
1055 		(void) chmod(filename, (int) stb.st_mode);
1056 		exit(EX_OK);
1057 		/*NOTREACHED*/
1058 	}
1059 	else
1060 	{
1061 		/* parent -- wait for exit status */
1062 		register int i;
1063 		auto int stat;
1064 
1065 		while ((i = wait(&stat)) != pid)
1066 		{
1067 			if (i < 0)
1068 			{
1069 				stat = EX_OSERR << 8;
1070 				break;
1071 			}
1072 		}
1073 		if ((stat & 0377) != 0)
1074 			stat = EX_UNAVAILABLE << 8;
1075 		return ((stat >> 8) & 0377);
1076 	}
1077 }
1078 /*
1079 **  SENDALL -- actually send all the messages.
1080 **
1081 **	Parameters:
1082 **		verifyonly -- if set, only give verification messages.
1083 **
1084 **	Returns:
1085 **		none.
1086 **
1087 **	Side Effects:
1088 **		Scans the send lists and sends everything it finds.
1089 */
1090 
1091 sendall(verifyonly)
1092 	bool verifyonly;
1093 {
1094 	register ADDRESS *q;
1095 	typedef int (*fnptr)();
1096 
1097 # ifdef DEBUG
1098 	if (Debug > 1)
1099 	{
1100 		printf("\nSendQueue:\n");
1101 		printaddr(SendQueue, TRUE);
1102 	}
1103 # endif DEBUG
1104 
1105 	for (q = SendQueue; q != NULL; q = q->q_next)
1106 	{
1107 		if (verifyonly)
1108 		{
1109 			To = q->q_paddr;
1110 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1111 			{
1112 				if (bitset(M_LOCAL, q->q_mailer->m_flags))
1113 					message(Arpa_Info, "deliverable");
1114 				else
1115 					message(Arpa_Info, "queueable");
1116 			}
1117 		}
1118 		else
1119 			(void) deliver(q, (fnptr) NULL);
1120 	}
1121 }
1122