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