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