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