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