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.71		03/05/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 		i = smtpinit(m, pv, (ADDRESS *) NULL);
172 		giveresponse(i, TRUE, m);
173 # ifdef QUEUE
174 		if (i == EX_TEMPFAIL)
175 		{
176 			QueueUp = TRUE;
177 			tempfail = TRUE;
178 		}
179 # endif QUEUE
180 # else SMTP
181 		/* oops!  we don't implement SMTP */
182 		syserr("SMTP style mailer");
183 		return (EX_SOFTWARE);
184 # endif SMTP
185 	}
186 
187 	/*
188 	**  At this point *mvp points to the argument with $u.  We
189 	**  run through our address list and append all the addresses
190 	**  we can.  If we run out of space, do not fret!  We can
191 	**  always send another copy later.
192 	*/
193 
194 	tobuf[0] = '\0';
195 	To = tobuf;
196 	ctladdr = NULL;
197 	for (; to != NULL; to = to->q_next)
198 	{
199 		/* avoid sending multiple recipients to dumb mailers */
200 		if (tobuf[0] != '\0' && !bitset(M_MUSER, m->m_flags))
201 			break;
202 
203 		/* if already sent or not for this host, don't send */
204 		if ((!ForceMail && bitset(QDONTSEND, to->q_flags)) ||
205 		    strcmp(to->q_host, host) != 0 || to->q_mailer != firstto->q_mailer)
206 			continue;
207 
208 # ifdef DEBUG
209 		if (Debug)
210 		{
211 			printf("\nsend to ");
212 			printaddr(to, FALSE);
213 		}
214 # endif DEBUG
215 
216 		/* link together the chain of recipients */
217 		if (!bitset(QDONTSEND, to->q_flags))
218 		{
219 			to->q_tchain = tochain;
220 			tochain = to;
221 		}
222 
223 		/* compute effective uid/gid when sending */
224 		if (to->q_mailer == ProgMailer)
225 			ctladdr = getctladdr(to);
226 
227 		user = to->q_user;
228 		To = to->q_paddr;
229 		to->q_flags |= QDONTSEND;
230 		if (tempfail)
231 		{
232 			to->q_flags |= QQUEUEUP;
233 			continue;
234 		}
235 
236 		/*
237 		**  Check to see that these people are allowed to
238 		**  talk to each other.
239 		*/
240 
241 		if (!checkcompat(to))
242 		{
243 			giveresponse(EX_UNAVAILABLE, TRUE, m);
244 			continue;
245 		}
246 
247 		/*
248 		**  Strip quote bits from names if the mailer is dumb
249 		**	about them.
250 		*/
251 
252 		if (bitset(M_STRIPQ, m->m_flags))
253 		{
254 			stripquotes(user, TRUE);
255 			stripquotes(host, TRUE);
256 		}
257 		else
258 		{
259 			stripquotes(user, FALSE);
260 			stripquotes(host, FALSE);
261 		}
262 
263 		/*
264 		**  If an error message has already been given, don't
265 		**	bother to send to this address.
266 		**
267 		**	>>>>>>>>>> This clause assumes that the local mailer
268 		**	>> NOTE >> cannot do any further aliasing; that
269 		**	>>>>>>>>>> function is subsumed by sendmail.
270 		*/
271 
272 		if (bitset(QBADADDR, to->q_flags))
273 			continue;
274 
275 		/* save statistics.... */
276 		Stat.stat_nt[to->q_mailer->m_mno]++;
277 		Stat.stat_bt[to->q_mailer->m_mno] += kbytes(MsgSize);
278 
279 		/*
280 		**  See if this user name is "special".
281 		**	If the user name has a slash in it, assume that this
282 		**	is a file -- send it off without further ado.
283 		**	Note that this means that editfcn's will not
284 		**	be applied to the message.  Also note that
285 		**	this type of addresses is not processed along
286 		**	with the others, so we fudge on the To person.
287 		*/
288 
289 		if (m == LocalMailer)
290 		{
291 			if (user[0] == '/')
292 			{
293 				i = mailfile(user, getctladdr(to));
294 				giveresponse(i, TRUE, m);
295 				continue;
296 			}
297 		}
298 
299 		/*
300 		**  Address is verified -- add this user to mailer
301 		**  argv, and add it to the print list of recipients.
302 		*/
303 
304 		/* create list of users for error messages */
305 		if (tobuf[0] != '\0')
306 			(void) strcat(tobuf, ",");
307 		(void) strcat(tobuf, to->q_paddr);
308 		define('u', user);		/* to user */
309 		define('z', to->q_home);	/* user's home */
310 
311 		/*
312 		**  Expand out this user into argument list or
313 		**  send it to our SMTP server.
314 		*/
315 
316 		if (clever)
317 		{
318 # ifdef SMTP
319 			i = smtprcpt(to);
320 			if (i != EX_OK)
321 			{
322 # ifdef QUEUE
323 				if (i == EX_TEMPFAIL)
324 				{
325 					QueueUp = TRUE;
326 					to->q_flags |= QQUEUEUP;
327 				}
328 				else
329 # endif QUEUE
330 				{
331 					to->q_flags |= QBADADDR;
332 					giveresponse(i, TRUE, m);
333 				}
334 			}
335 # else SMTP
336 			syserr("trying to be clever");
337 # endif SMTP
338 		}
339 		else
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 			return (-1);
653 		else
654 			return (0);
655 	}
656 # endif DAEMON
657 
658 	/* create a pipe to shove the mail through */
659 	if (pipe(mpvect) < 0)
660 	{
661 		syserr("pipe (to mailer)");
662 		return (-1);
663 	}
664 
665 # ifdef SMTP
666 	/* if this mailer speaks smtp, create a return pipe */
667 	if (clever && pipe(rpvect) < 0)
668 	{
669 		syserr("pipe (from mailer)");
670 		(void) close(mpvect[0]);
671 		(void) close(mpvect[1]);
672 		return (-1);
673 	}
674 # endif SMTP
675 
676 	/*
677 	**  Actually fork the mailer process.
678 	**	DOFORK is clever about retrying.
679 	*/
680 
681 	DOFORK(XFORK);
682 	/* pid is set by DOFORK */
683 	if (pid < 0)
684 	{
685 		/* failure */
686 		syserr("Cannot fork");
687 		(void) close(mpvect[0]);
688 		(void) close(mpvect[1]);
689 		if (clever)
690 		{
691 			(void) close(rpvect[0]);
692 			(void) close(rpvect[1]);
693 		}
694 		return (-1);
695 	}
696 	else if (pid == 0)
697 	{
698 		/* child -- set up input & exec mailer */
699 		/* make diagnostic output be standard output */
700 		(void) signal(SIGINT, SIG_IGN);
701 		(void) signal(SIGHUP, SIG_IGN);
702 		(void) signal(SIGTERM, SIG_DFL);
703 
704 		/* arrange to filter standard & diag output of command */
705 		if (clever)
706 		{
707 			(void) close(rpvect[0]);
708 			(void) close(1);
709 			(void) dup(rpvect[1]);
710 			(void) close(rpvect[1]);
711 		}
712 		else if (OutChannel != stdout)
713 		{
714 			(void) close(1);
715 			(void) dup(fileno(OutChannel));
716 		}
717 		(void) close(2);
718 		(void) dup(1);
719 
720 		/* arrange to get standard input */
721 		(void) close(mpvect[1]);
722 		(void) close(0);
723 		if (dup(mpvect[0]) < 0)
724 		{
725 			syserr("Cannot dup to zero!");
726 			_exit(EX_OSERR);
727 		}
728 		(void) close(mpvect[0]);
729 		if (!bitset(M_RESTR, m->m_flags))
730 		{
731 			if (ctladdr->q_uid == 0)
732 			{
733 				(void) setgid(DefGid);
734 				(void) setuid(DefUid);
735 			}
736 			else
737 			{
738 				(void) setgid(ctladdr->q_gid);
739 				(void) setuid(ctladdr->q_uid);
740 			}
741 		}
742 # ifndef VFORK
743 		/*
744 		**  We have to be careful with vfork - we can't mung up the
745 		**  memory but we don't want the mailer to inherit any extra
746 		**  open files.  Chances are the mailer won't
747 		**  care about an extra file, but then again you never know.
748 		**  Actually, we would like to close(fileno(pwf)), but it's
749 		**  declared static so we can't.  But if we fclose(pwf), which
750 		**  is what endpwent does, it closes it in the parent too and
751 		**  the next getpwnam will be slower.  If you have a weird
752 		**  mailer that chokes on the extra file you should do the
753 		**  endpwent().
754 		**
755 		**  Similar comments apply to log.  However, openlog is
756 		**  clever enough to set the FIOCLEX mode on the file,
757 		**  so it will be closed automatically on the exec.
758 		*/
759 
760 		endpwent();
761 # ifdef LOG
762 		closelog();
763 # endif LOG
764 # endif VFORK
765 
766 		/* try to execute the mailer */
767 		execv(m->m_mailer, pvp);
768 
769 		/* syserr fails because log is closed */
770 		/* syserr("Cannot exec %s", m->m_mailer); */
771 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
772 		(void) fflush(stdout);
773 		_exit(EX_UNAVAILABLE);
774 	}
775 
776 	/*
777 	**  Set up return value.
778 	*/
779 
780 	(void) close(mpvect[0]);
781 	mfile = fdopen(mpvect[1], "w");
782 	if (clever)
783 	{
784 		(void) close(rpvect[1]);
785 		rfile = fdopen(rpvect[0], "r");
786 	}
787 
788 	*pmfile = mfile;
789 	*prfile = rfile;
790 
791 	return (pid);
792 }
793 /*
794 **  GIVERESPONSE -- Interpret an error response from a mailer
795 **
796 **	Parameters:
797 **		stat -- the status code from the mailer (high byte
798 **			only; core dumps must have been taken care of
799 **			already).
800 **		force -- if set, force an error message output, even
801 **			if the mailer seems to like to print its own
802 **			messages.
803 **		m -- the mailer descriptor for this mailer.
804 **
805 **	Returns:
806 **		none.
807 **
808 **	Side Effects:
809 **		Errors may be incremented.
810 **		ExitStat may be set.
811 */
812 
813 giveresponse(stat, force, m)
814 	int stat;
815 	int force;
816 	register struct mailer *m;
817 {
818 	register char *statmsg;
819 	extern char *SysExMsg[];
820 	register int i;
821 	extern int N_SysEx;
822 	char buf[30];
823 
824 	/*
825 	**  Compute status message from code.
826 	*/
827 
828 	i = stat - EX__BASE;
829 	if (i < 0 || i > N_SysEx)
830 		statmsg = NULL;
831 	else
832 		statmsg = SysExMsg[i];
833 	if (stat == 0)
834 	{
835 		if (bitset(M_LOCAL, m->m_flags))
836 			statmsg = "delivered";
837 		else
838 			statmsg = "queued";
839 		if (Verbose)
840 			message(Arpa_Info, statmsg);
841 	}
842 # ifdef QUEUE
843 	else if (stat == EX_TEMPFAIL)
844 	{
845 		if (Verbose)
846 			message(Arpa_Info, "transmission deferred");
847 	}
848 # endif QUEUE
849 	else
850 	{
851 		Errors++;
852 		if (statmsg == NULL && m->m_badstat != 0)
853 		{
854 			stat = m->m_badstat;
855 			i = stat - EX__BASE;
856 # ifdef DEBUG
857 			if (i < 0 || i >= N_SysEx)
858 				syserr("Bad m_badstat %d", stat);
859 			else
860 # endif DEBUG
861 			statmsg = SysExMsg[i];
862 		}
863 		if (statmsg == NULL)
864 			usrerr("unknown mailer response %d", stat);
865 		else if (force || !bitset(M_QUIET, m->m_flags) || Verbose)
866 			usrerr("%s", statmsg);
867 	}
868 
869 	/*
870 	**  Final cleanup.
871 	**	Log a record of the transaction.  Compute the new
872 	**	ExitStat -- if we already had an error, stick with
873 	**	that.
874 	*/
875 
876 	if (statmsg == NULL)
877 	{
878 		(void) sprintf(buf, "error %d", stat);
879 		statmsg = buf;
880 	}
881 
882 # ifdef LOG
883 	syslog(LOG_INFO, "%s->%s: %ld: %s", From.q_paddr, To, MsgSize, statmsg);
884 # endif LOG
885 # ifdef QUEUE
886 	if (stat != EX_TEMPFAIL)
887 # endif QUEUE
888 		setstat(stat);
889 }
890 /*
891 **  PUTMESSAGE -- output a message to the final mailer.
892 **
893 **	This routine takes care of recreating the header from the
894 **	in-core copy, etc.
895 **
896 **	Parameters:
897 **		fp -- file to output onto.
898 **		m -- a mailer descriptor.
899 **		xdot -- if set, hide lines beginning with dot.
900 **
901 **	Returns:
902 **		none.
903 **
904 **	Side Effects:
905 **		The message is written onto fp.
906 */
907 
908 putmessage(fp, m, xdot)
909 	FILE *fp;
910 	struct mailer *m;
911 	bool xdot;
912 {
913 	char buf[BUFSIZ];
914 
915 	/*
916 	**  Output "From" line unless supressed
917 	**
918 	**  >>>>>>>>>>	One of the ugliest hacks seen by human eyes is
919 	**  >>>>>>>>>>	contained herein: UUCP wants those stupid
920 	**  >> NOTE >>	"remote from <host>" lines.  Why oh why does a
921 	**  >>>>>>>>>>	well-meaning programmer such as myself have to
922 	**  >>>>>>>>>>	deal with this kind of antique garbage????
923 	*/
924 
925 	if (!bitset(M_NHDR, m->m_flags))
926 	{
927 # ifdef UGLYUUCP
928 		if (bitset(M_UGLYUUCP, m->m_flags))
929 		{
930 			extern char *macvalue();
931 			char *sys = macvalue('g');
932 			char *bang = index(sys, '!');
933 
934 			if (bang == NULL)
935 				syserr("No ! in UUCP! (%s)", sys);
936 			else
937 				*bang = '\0';
938 			(void) expand("From $f  $d remote from $g", buf,
939 					&buf[sizeof buf - 1]);
940 			*bang = '!';
941 		}
942 		else
943 # endif UGLYUUCP
944 			(void) expand("$l", buf, &buf[sizeof buf - 1]);
945 		fprintf(fp, "%s\n", buf);
946 	}
947 
948 	/*
949 	**  Output all header lines
950 	*/
951 
952 	putheader(fp, m);
953 
954 	/*
955 	**  Output the body of the message
956 	*/
957 
958 	if (TempFile != NULL)
959 	{
960 		rewind(TempFile);
961 		while (!ferror(fp) && fgets(buf, sizeof buf, TempFile) != NULL)
962 			fprintf(fp, "%s%s", xdot && buf[0] == '.' ? "." : "", buf);
963 
964 		if (ferror(TempFile))
965 		{
966 			syserr("putmessage: read error");
967 			setstat(EX_IOERR);
968 		}
969 	}
970 
971 	(void) fflush(fp);
972 	if (ferror(fp) && errno != EPIPE)
973 	{
974 		syserr("putmessage: write error");
975 		setstat(EX_IOERR);
976 	}
977 	errno = 0;
978 }
979 /*
980 **  PUTHEADER -- put the header part of a message
981 **
982 **	Parameters:
983 **		fp -- file to put it on.
984 **		m -- mailer to use.
985 **
986 **	Returns:
987 **		none.
988 **
989 **	Side Effects:
990 **		none.
991 */
992 
993 putheader(fp, m)
994 	register FILE *fp;
995 	register struct mailer *m;
996 {
997 	char buf[BUFSIZ];
998 	register HDR *h;
999 	extern char *arpadate();
1000 	bool anyheader = FALSE;
1001 	extern char *capitalize();
1002 	extern char *hvalue();
1003 	extern bool samefrom();
1004 	char *of_line;
1005 
1006 	of_line = hvalue("original-from");
1007 	for (h = Header; h != NULL; h = h->h_link)
1008 	{
1009 		register char *p;
1010 		char *origfrom = OrigFrom;
1011 		bool nooutput;
1012 
1013 		nooutput = FALSE;
1014 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
1015 			nooutput = TRUE;
1016 
1017 		/* use From: line from message if generated is the same */
1018 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
1019 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
1020 		{
1021 			p = origfrom;
1022 			origfrom = NULL;
1023 		}
1024 		else if (bitset(H_DEFAULT, h->h_flags))
1025 		{
1026 			(void) expand(h->h_value, buf, &buf[sizeof buf]);
1027 			p = buf;
1028 		}
1029 		else if (bitset(H_ADDR, h->h_flags))
1030 		{
1031 			register int opos;
1032 			bool firstone = TRUE;
1033 
1034 			/*
1035 			**  Output the address list translated by the
1036 			**  mailer and with commas.
1037 			*/
1038 
1039 			p = h->h_value;
1040 			if (p == NULL || *p == '\0' || nooutput)
1041 				continue;
1042 			fprintf(fp, "%s: ", capitalize(h->h_field));
1043 			opos = strlen(h->h_field) + 2;
1044 			while (*p != '\0')
1045 			{
1046 				register char *name = p;
1047 				extern char *remotename();
1048 				char savechar;
1049 
1050 				/* find the end of the name */
1051 				while (*p != '\0' && *p != ',')
1052 				{
1053 					extern bool isatword();
1054 					char *oldp;
1055 
1056 					if (!OldStyle || !isspace(*p))
1057 					{
1058 						p++;
1059 						continue;
1060 					}
1061 					oldp = p;
1062 					while (*p != '\0' && isspace(*p))
1063 						p++;
1064 					if (*p != '@' && !isatword(p))
1065 					{
1066 						p = oldp;
1067 						break;
1068 					}
1069 					p += *p == '@' ? 1 : 2;
1070 					while (*p != '\0' && isspace(*p))
1071 						p++;
1072 				}
1073 				savechar = *p;
1074 				*p = '\0';
1075 
1076 				/* translate the name to be relative */
1077 				name = remotename(name, m);
1078 				if (*name == '\0')
1079 					continue;
1080 
1081 				/* output the name with nice formatting */
1082 				opos += strlen(name);
1083 				if (!firstone)
1084 					opos += 2;
1085 				if (opos > 78 && !firstone)
1086 				{
1087 					fprintf(fp, ",\n        ");
1088 					opos = 8 + strlen(name);
1089 				}
1090 				else if (!firstone)
1091 					fprintf(fp, ", ");
1092 				fprintf(fp, "%s", name);
1093 				firstone = FALSE;
1094 
1095 				/* clean up the source string */
1096 				*p = savechar;
1097 				while (*p != '\0' && (isspace(*p) || *p == ','))
1098 					p++;
1099 			}
1100 			fprintf(fp, "\n");
1101 			nooutput = TRUE;
1102 		}
1103 		else
1104 			p = h->h_value;
1105 		if (p == NULL || *p == '\0')
1106 			continue;
1107 
1108 		/* hack, hack -- output Original-From field if different */
1109 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
1110 		{
1111 			/* output new Original-From line if needed */
1112 			if (of_line == NULL && !samefrom(p, origfrom))
1113 			{
1114 				fprintf(fp, "Original-From: %s\n", origfrom);
1115 				anyheader = TRUE;
1116 			}
1117 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
1118 			{
1119 				/* delete Original-From: line if redundant */
1120 				p = of_line;
1121 				of_line = NULL;
1122 			}
1123 		}
1124 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
1125 			nooutput = TRUE;
1126 
1127 		/* finally, output the header line */
1128 		if (!nooutput)
1129 		{
1130 			fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
1131 			h->h_flags |= H_USED;
1132 			anyheader = TRUE;
1133 		}
1134 	}
1135 	if (anyheader)
1136 		fprintf(fp, "\n");
1137 }
1138 /*
1139 **  ISATWORD -- tell if the word we are pointing to is "at".
1140 **
1141 **	Parameters:
1142 **		p -- word to check.
1143 **
1144 **	Returns:
1145 **		TRUE -- if p is the word at.
1146 **		FALSE -- otherwise.
1147 **
1148 **	Side Effects:
1149 **		none.
1150 */
1151 
1152 bool
1153 isatword(p)
1154 	register char *p;
1155 {
1156 	extern char lower();
1157 
1158 	if (lower(p[0]) == 'a' && lower(p[1]) == 't' &&
1159 	    p[2] != '\0' && isspace(p[2]))
1160 		return (TRUE);
1161 	return (FALSE);
1162 }
1163 /*
1164 **  REMOTENAME -- return the name relative to the current mailer
1165 **
1166 **	Parameters:
1167 **		name -- the name to translate.
1168 **
1169 **	Returns:
1170 **		the text string representing this address relative to
1171 **			the receiving mailer.
1172 **
1173 **	Side Effects:
1174 **		none.
1175 **
1176 **	Warnings:
1177 **		The text string returned is tucked away locally;
1178 **			copy it if you intend to save it.
1179 */
1180 
1181 char *
1182 remotename(name, m)
1183 	char *name;
1184 	struct mailer *m;
1185 {
1186 	static char buf[MAXNAME];
1187 	char lbuf[MAXNAME];
1188 	extern char *macvalue();
1189 	char *oldf = macvalue('f');
1190 	char *oldx = macvalue('x');
1191 	char *oldg = macvalue('g');
1192 	extern char **prescan();
1193 	register char **pvp;
1194 	extern char *getxpart();
1195 
1196 	/*
1197 	**  Do general rewriting of name.
1198 	**	This will also take care of doing global name translation.
1199 	*/
1200 
1201 	define('x', getxpart(name));
1202 	pvp = prescan(name, '\0');
1203 	for (;;)
1204 	{
1205 		rewrite(pvp, 1);
1206 		rewrite(pvp, 3);
1207 		if (**pvp == CANONNET)
1208 		{
1209 			auto ADDRESS a;
1210 			register char *p;
1211 			extern char *hostalias();
1212 
1213 			/* oops... resolved to something */
1214 			if (buildaddr(pvp, &a) == NULL)
1215 				return (name);
1216 			p = hostalias(&a);
1217 			if (p == NULL)
1218 				return (name);
1219 			pvp = prescan(p, '\0');
1220 		}
1221 		else
1222 		{
1223 			cataddr(pvp, lbuf, sizeof lbuf);
1224 			break;
1225 		}
1226 	}
1227 
1228 	/* make the name relative to the receiving mailer */
1229 	define('f', lbuf);
1230 	(void) expand(m->m_from, buf, &buf[sizeof buf - 1]);
1231 
1232 	/* rewrite to get rid of garbage we added in the expand above */
1233 	pvp = prescan(buf, '\0');
1234 	rewrite(pvp, 2);
1235 	cataddr(pvp, lbuf, sizeof lbuf);
1236 
1237 	/* now add any comment info we had before back */
1238 	define('g', lbuf);
1239 	(void) expand("$q", buf, &buf[sizeof buf - 1]);
1240 
1241 	define('f', oldf);
1242 	define('g', oldg);
1243 	define('x', oldx);
1244 
1245 # ifdef DEBUG
1246 	if (Debug > 0)
1247 		printf("remotename(%s) => `%s'\n", name, buf);
1248 # endif DEBUG
1249 	return (buf);
1250 }
1251 /*
1252 **  SAMEFROM -- tell if two text addresses represent the same from address.
1253 **
1254 **	Parameters:
1255 **		ifrom -- internally generated form of from address.
1256 **		efrom -- external form of from address.
1257 **
1258 **	Returns:
1259 **		TRUE -- if they convey the same info.
1260 **		FALSE -- if any information has been lost.
1261 **
1262 **	Side Effects:
1263 **		none.
1264 */
1265 
1266 bool
1267 samefrom(ifrom, efrom)
1268 	char *ifrom;
1269 	char *efrom;
1270 {
1271 	register char *p;
1272 	char buf[MAXNAME + 4];
1273 
1274 # ifdef DEBUG
1275 	if (Debug > 7)
1276 		printf("samefrom(%s,%s)-->", ifrom, efrom);
1277 # endif DEBUG
1278 	if (strcmp(ifrom, efrom) == 0)
1279 		goto success;
1280 	p = index(ifrom, '@');
1281 	if (p == NULL)
1282 		goto failure;
1283 	*p = '\0';
1284 	strcpy(buf, ifrom);
1285 	strcat(buf, " at ");
1286 	*p++ = '@';
1287 	strcat(buf, p);
1288 	if (strcmp(buf, efrom) == 0)
1289 		goto success;
1290 
1291   failure:
1292 # ifdef DEBUG
1293 	if (Debug > 7)
1294 		printf("FALSE\n");
1295 # endif DEBUG
1296 	return (FALSE);
1297 
1298   success:
1299 # ifdef DEBUG
1300 	if (Debug > 7)
1301 		printf("TRUE\n");
1302 # endif DEBUG
1303 	return (TRUE);
1304 }
1305 /*
1306 **  MAILFILE -- Send a message to a file.
1307 **
1308 **	If the file has the setuid/setgid bits set, but NO execute
1309 **	bits, sendmail will try to become the owner of that file
1310 **	rather than the real user.  Obviously, this only works if
1311 **	sendmail runs as root.
1312 **
1313 **	Parameters:
1314 **		filename -- the name of the file to send to.
1315 **		ctladdr -- the controlling address header -- includes
1316 **			the userid/groupid to be when sending.
1317 **
1318 **	Returns:
1319 **		The exit code associated with the operation.
1320 **
1321 **	Side Effects:
1322 **		none.
1323 */
1324 
1325 mailfile(filename, ctladdr)
1326 	char *filename;
1327 	ADDRESS *ctladdr;
1328 {
1329 	register FILE *f;
1330 	register int pid;
1331 
1332 	/*
1333 	**  Fork so we can change permissions here.
1334 	**	Note that we MUST use fork, not vfork, because of
1335 	**	the complications of calling subroutines, etc.
1336 	*/
1337 
1338 	DOFORK(fork);
1339 
1340 	if (pid < 0)
1341 		return (EX_OSERR);
1342 	else if (pid == 0)
1343 	{
1344 		/* child -- actually write to file */
1345 		struct stat stb;
1346 
1347 		(void) signal(SIGINT, SIG_DFL);
1348 		(void) signal(SIGHUP, SIG_DFL);
1349 		(void) signal(SIGTERM, SIG_DFL);
1350 		umask(OldUmask);
1351 		if (stat(filename, &stb) < 0)
1352 			stb.st_mode = 0666;
1353 		if (bitset(0111, stb.st_mode))
1354 			exit(EX_CANTCREAT);
1355 		if (ctladdr == NULL)
1356 			ctladdr = &From;
1357 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1358 		{
1359 			if (ctladdr->q_uid == 0)
1360 				(void) setgid(DefGid);
1361 			else
1362 				(void) setgid(ctladdr->q_gid);
1363 		}
1364 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1365 		{
1366 			if (ctladdr->q_uid == 0)
1367 				(void) setuid(DefUid);
1368 			else
1369 				(void) setuid(ctladdr->q_uid);
1370 		}
1371 		f = fopen(filename, "a");
1372 		if (f == NULL)
1373 			exit(EX_CANTCREAT);
1374 
1375 		putmessage(f, Mailer[1], FALSE);
1376 		fputs("\n", f);
1377 		(void) fclose(f);
1378 		(void) fflush(stdout);
1379 
1380 		/* reset ISUID & ISGID bits */
1381 		(void) chmod(filename, (int) stb.st_mode);
1382 		exit(EX_OK);
1383 		/*NOTREACHED*/
1384 	}
1385 	else
1386 	{
1387 		/* parent -- wait for exit status */
1388 		register int i;
1389 		auto int stat;
1390 
1391 		while ((i = wait(&stat)) != pid)
1392 		{
1393 			if (i < 0)
1394 			{
1395 				stat = EX_OSERR << 8;
1396 				break;
1397 			}
1398 		}
1399 		if ((stat & 0377) != 0)
1400 			stat = EX_UNAVAILABLE << 8;
1401 		return ((stat >> 8) & 0377);
1402 	}
1403 }
1404 /*
1405 **  SENDALL -- actually send all the messages.
1406 **
1407 **	Parameters:
1408 **		verifyonly -- if set, only give verification messages.
1409 **
1410 **	Returns:
1411 **		none.
1412 **
1413 **	Side Effects:
1414 **		Scans the send lists and sends everything it finds.
1415 */
1416 
1417 sendall(verifyonly)
1418 	bool verifyonly;
1419 {
1420 	register ADDRESS *q;
1421 	typedef int (*fnptr)();
1422 
1423 # ifdef DEBUG
1424 	if (Debug > 1)
1425 	{
1426 		printf("\nSendQueue:\n");
1427 		printaddr(SendQueue, TRUE);
1428 	}
1429 # endif DEBUG
1430 
1431 	for (q = SendQueue; q != NULL; q = q->q_next)
1432 	{
1433 		if (verifyonly)
1434 		{
1435 			To = q->q_paddr;
1436 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1437 			{
1438 				if (bitset(M_LOCAL, q->q_mailer->m_flags))
1439 					message(Arpa_Info, "deliverable");
1440 				else
1441 					message(Arpa_Info, "queueable");
1442 			}
1443 		}
1444 		else
1445 			(void) deliver(q, (fnptr) NULL);
1446 	}
1447 }
1448