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.70		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 	**  >>>>>>>>>>	"remote from <host>" lines.  Why oh why does a
921 	**  >> NOTE >>	well-meaning programmer such as myself have to
922 	**  >>>>>>>>>>	deal with this kind of antique garbage????
923 	**  >>>>>>>>>>  This even depends on the local UUCP host name
924 	**  >>>>>>>>>>  being in the $U macro!!!!
925 	*/
926 
927 	if (!bitset(M_NHDR, m->m_flags))
928 	{
929 # ifdef UGLYUUCP
930 		if (bitset(M_UGLYUUCP, m->m_flags))
931 			(void) expand("From $f  $d remote from $U", buf,
932 					&buf[sizeof buf - 1]);
933 		else
934 # endif UGLYUUCP
935 			(void) expand("$l", buf, &buf[sizeof buf - 1]);
936 		fprintf(fp, "%s\n", buf);
937 	}
938 
939 	/*
940 	**  Output all header lines
941 	*/
942 
943 	putheader(fp, m);
944 
945 	/*
946 	**  Output the body of the message
947 	*/
948 
949 	if (TempFile != NULL)
950 	{
951 		rewind(TempFile);
952 		while (!ferror(fp) && fgets(buf, sizeof buf, TempFile) != NULL)
953 			fprintf(fp, "%s%s", xdot && buf[0] == '.' ? "." : "", buf);
954 
955 		if (ferror(TempFile))
956 		{
957 			syserr("putmessage: read error");
958 			setstat(EX_IOERR);
959 		}
960 	}
961 
962 	(void) fflush(fp);
963 	if (ferror(fp) && errno != EPIPE)
964 	{
965 		syserr("putmessage: write error");
966 		setstat(EX_IOERR);
967 	}
968 	errno = 0;
969 }
970 /*
971 **  PUTHEADER -- put the header part of a message
972 **
973 **	Parameters:
974 **		fp -- file to put it on.
975 **		m -- mailer to use.
976 **
977 **	Returns:
978 **		none.
979 **
980 **	Side Effects:
981 **		none.
982 */
983 
984 putheader(fp, m)
985 	register FILE *fp;
986 	register struct mailer *m;
987 {
988 	char buf[BUFSIZ];
989 	register HDR *h;
990 	extern char *arpadate();
991 	bool anyheader = FALSE;
992 	extern char *capitalize();
993 	extern char *hvalue();
994 	extern bool samefrom();
995 	char *of_line;
996 
997 	of_line = hvalue("original-from");
998 	for (h = Header; h != NULL; h = h->h_link)
999 	{
1000 		register char *p;
1001 		char *origfrom = OrigFrom;
1002 		bool nooutput;
1003 
1004 		nooutput = FALSE;
1005 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
1006 			nooutput = TRUE;
1007 
1008 		/* use From: line from message if generated is the same */
1009 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
1010 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
1011 		{
1012 			p = origfrom;
1013 			origfrom = NULL;
1014 		}
1015 		else if (bitset(H_DEFAULT, h->h_flags))
1016 		{
1017 			(void) expand(h->h_value, buf, &buf[sizeof buf]);
1018 			p = buf;
1019 		}
1020 		else if (bitset(H_ADDR, h->h_flags))
1021 		{
1022 			register int opos;
1023 			bool firstone = TRUE;
1024 
1025 			/*
1026 			**  Output the address list translated by the
1027 			**  mailer and with commas.
1028 			*/
1029 
1030 			p = h->h_value;
1031 			if (p == NULL || *p == '\0' || nooutput)
1032 				continue;
1033 			fprintf(fp, "%s: ", capitalize(h->h_field));
1034 			opos = strlen(h->h_field) + 2;
1035 			while (*p != '\0')
1036 			{
1037 				register char *name = p;
1038 				extern char *remotename();
1039 				char savechar;
1040 
1041 				/* find the end of the name */
1042 				while (*p != '\0' && *p != ',')
1043 				{
1044 					extern bool isatword();
1045 					char *oldp;
1046 
1047 					if (!OldStyle || !isspace(*p))
1048 					{
1049 						p++;
1050 						continue;
1051 					}
1052 					oldp = p;
1053 					while (*p != '\0' && isspace(*p))
1054 						p++;
1055 					if (*p != '@' && !isatword(p))
1056 					{
1057 						p = oldp;
1058 						break;
1059 					}
1060 					p += *p == '@' ? 1 : 2;
1061 					while (*p != '\0' && isspace(*p))
1062 						p++;
1063 				}
1064 				savechar = *p;
1065 				*p = '\0';
1066 
1067 				/* translate the name to be relative */
1068 				name = remotename(name, m);
1069 				if (*name == '\0')
1070 					continue;
1071 
1072 				/* output the name with nice formatting */
1073 				opos += strlen(name);
1074 				if (!firstone)
1075 					opos += 2;
1076 				if (opos > 78 && !firstone)
1077 				{
1078 					fprintf(fp, ",\n        ");
1079 					opos = 8 + strlen(name);
1080 				}
1081 				else if (!firstone)
1082 					fprintf(fp, ", ");
1083 				fprintf(fp, "%s", name);
1084 				firstone = FALSE;
1085 
1086 				/* clean up the source string */
1087 				*p = savechar;
1088 				while (*p != '\0' && (isspace(*p) || *p == ','))
1089 					p++;
1090 			}
1091 			fprintf(fp, "\n");
1092 			nooutput = TRUE;
1093 		}
1094 		else
1095 			p = h->h_value;
1096 		if (p == NULL || *p == '\0')
1097 			continue;
1098 
1099 		/* hack, hack -- output Original-From field if different */
1100 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
1101 		{
1102 			/* output new Original-From line if needed */
1103 			if (of_line == NULL && !samefrom(p, origfrom))
1104 			{
1105 				fprintf(fp, "Original-From: %s\n", origfrom);
1106 				anyheader = TRUE;
1107 			}
1108 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
1109 			{
1110 				/* delete Original-From: line if redundant */
1111 				p = of_line;
1112 				of_line = NULL;
1113 			}
1114 		}
1115 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
1116 			nooutput = TRUE;
1117 
1118 		/* finally, output the header line */
1119 		if (!nooutput)
1120 		{
1121 			fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
1122 			h->h_flags |= H_USED;
1123 			anyheader = TRUE;
1124 		}
1125 	}
1126 	if (anyheader)
1127 		fprintf(fp, "\n");
1128 }
1129 /*
1130 **  ISATWORD -- tell if the word we are pointing to is "at".
1131 **
1132 **	Parameters:
1133 **		p -- word to check.
1134 **
1135 **	Returns:
1136 **		TRUE -- if p is the word at.
1137 **		FALSE -- otherwise.
1138 **
1139 **	Side Effects:
1140 **		none.
1141 */
1142 
1143 bool
1144 isatword(p)
1145 	register char *p;
1146 {
1147 	extern char lower();
1148 
1149 	if (lower(p[0]) == 'a' && lower(p[1]) == 't' &&
1150 	    p[2] != '\0' && isspace(p[2]))
1151 		return (TRUE);
1152 	return (FALSE);
1153 }
1154 /*
1155 **  REMOTENAME -- return the name relative to the current mailer
1156 **
1157 **	Parameters:
1158 **		name -- the name to translate.
1159 **
1160 **	Returns:
1161 **		the text string representing this address relative to
1162 **			the receiving mailer.
1163 **
1164 **	Side Effects:
1165 **		none.
1166 **
1167 **	Warnings:
1168 **		The text string returned is tucked away locally;
1169 **			copy it if you intend to save it.
1170 */
1171 
1172 char *
1173 remotename(name, m)
1174 	char *name;
1175 	struct mailer *m;
1176 {
1177 	static char buf[MAXNAME];
1178 	char lbuf[MAXNAME];
1179 	extern char *macvalue();
1180 	char *oldf = macvalue('f');
1181 	char *oldx = macvalue('x');
1182 	char *oldg = macvalue('g');
1183 	extern char **prescan();
1184 	register char **pvp;
1185 	extern char *getxpart();
1186 
1187 	/*
1188 	**  Do general rewriting of name.
1189 	**	This will also take care of doing global name translation.
1190 	*/
1191 
1192 	define('x', getxpart(name));
1193 	pvp = prescan(name, '\0');
1194 	for (;;)
1195 	{
1196 		rewrite(pvp, 1);
1197 		rewrite(pvp, 3);
1198 		if (**pvp == CANONNET)
1199 		{
1200 			auto ADDRESS a;
1201 			register char *p;
1202 			extern char *hostalias();
1203 
1204 			/* oops... resolved to something */
1205 			if (buildaddr(pvp, &a) == NULL)
1206 				return (name);
1207 			p = hostalias(&a);
1208 			if (p == NULL)
1209 				return (name);
1210 			pvp = prescan(p, '\0');
1211 		}
1212 		else
1213 		{
1214 			cataddr(pvp, lbuf, sizeof lbuf);
1215 			break;
1216 		}
1217 	}
1218 
1219 	/* make the name relative to the receiving mailer */
1220 	define('f', lbuf);
1221 	(void) expand(m->m_from, buf, &buf[sizeof buf - 1]);
1222 
1223 	/* rewrite to get rid of garbage we added in the expand above */
1224 	pvp = prescan(buf, '\0');
1225 	rewrite(pvp, 2);
1226 	cataddr(pvp, lbuf, sizeof lbuf);
1227 
1228 	/* now add any comment info we had before back */
1229 	define('g', lbuf);
1230 	(void) expand("$q", buf, &buf[sizeof buf - 1]);
1231 
1232 	define('f', oldf);
1233 	define('g', oldg);
1234 	define('x', oldx);
1235 
1236 # ifdef DEBUG
1237 	if (Debug > 0)
1238 		printf("remotename(%s) => `%s'\n", name, buf);
1239 # endif DEBUG
1240 	return (buf);
1241 }
1242 /*
1243 **  SAMEFROM -- tell if two text addresses represent the same from address.
1244 **
1245 **	Parameters:
1246 **		ifrom -- internally generated form of from address.
1247 **		efrom -- external form of from address.
1248 **
1249 **	Returns:
1250 **		TRUE -- if they convey the same info.
1251 **		FALSE -- if any information has been lost.
1252 **
1253 **	Side Effects:
1254 **		none.
1255 */
1256 
1257 bool
1258 samefrom(ifrom, efrom)
1259 	char *ifrom;
1260 	char *efrom;
1261 {
1262 	register char *p;
1263 	char buf[MAXNAME + 4];
1264 
1265 # ifdef DEBUG
1266 	if (Debug > 7)
1267 		printf("samefrom(%s,%s)-->", ifrom, efrom);
1268 # endif DEBUG
1269 	if (strcmp(ifrom, efrom) == 0)
1270 		goto success;
1271 	p = index(ifrom, '@');
1272 	if (p == NULL)
1273 		goto failure;
1274 	*p = '\0';
1275 	strcpy(buf, ifrom);
1276 	strcat(buf, " at ");
1277 	*p++ = '@';
1278 	strcat(buf, p);
1279 	if (strcmp(buf, efrom) == 0)
1280 		goto success;
1281 
1282   failure:
1283 # ifdef DEBUG
1284 	if (Debug > 7)
1285 		printf("FALSE\n");
1286 # endif DEBUG
1287 	return (FALSE);
1288 
1289   success:
1290 # ifdef DEBUG
1291 	if (Debug > 7)
1292 		printf("TRUE\n");
1293 # endif DEBUG
1294 	return (TRUE);
1295 }
1296 /*
1297 **  MAILFILE -- Send a message to a file.
1298 **
1299 **	If the file has the setuid/setgid bits set, but NO execute
1300 **	bits, sendmail will try to become the owner of that file
1301 **	rather than the real user.  Obviously, this only works if
1302 **	sendmail runs as root.
1303 **
1304 **	Parameters:
1305 **		filename -- the name of the file to send to.
1306 **		ctladdr -- the controlling address header -- includes
1307 **			the userid/groupid to be when sending.
1308 **
1309 **	Returns:
1310 **		The exit code associated with the operation.
1311 **
1312 **	Side Effects:
1313 **		none.
1314 */
1315 
1316 mailfile(filename, ctladdr)
1317 	char *filename;
1318 	ADDRESS *ctladdr;
1319 {
1320 	register FILE *f;
1321 	register int pid;
1322 
1323 	/*
1324 	**  Fork so we can change permissions here.
1325 	**	Note that we MUST use fork, not vfork, because of
1326 	**	the complications of calling subroutines, etc.
1327 	*/
1328 
1329 	DOFORK(fork);
1330 
1331 	if (pid < 0)
1332 		return (EX_OSERR);
1333 	else if (pid == 0)
1334 	{
1335 		/* child -- actually write to file */
1336 		struct stat stb;
1337 
1338 		(void) signal(SIGINT, SIG_DFL);
1339 		(void) signal(SIGHUP, SIG_DFL);
1340 		(void) signal(SIGTERM, SIG_DFL);
1341 		umask(OldUmask);
1342 		if (stat(filename, &stb) < 0)
1343 			stb.st_mode = 0666;
1344 		if (bitset(0111, stb.st_mode))
1345 			exit(EX_CANTCREAT);
1346 		if (ctladdr == NULL)
1347 			ctladdr = &From;
1348 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1349 		{
1350 			if (ctladdr->q_uid == 0)
1351 				(void) setgid(DefGid);
1352 			else
1353 				(void) setgid(ctladdr->q_gid);
1354 		}
1355 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1356 		{
1357 			if (ctladdr->q_uid == 0)
1358 				(void) setuid(DefUid);
1359 			else
1360 				(void) setuid(ctladdr->q_uid);
1361 		}
1362 		f = fopen(filename, "a");
1363 		if (f == NULL)
1364 			exit(EX_CANTCREAT);
1365 
1366 		putmessage(f, Mailer[1], FALSE);
1367 		fputs("\n", f);
1368 		(void) fclose(f);
1369 		(void) fflush(stdout);
1370 
1371 		/* reset ISUID & ISGID bits */
1372 		(void) chmod(filename, (int) stb.st_mode);
1373 		exit(EX_OK);
1374 		/*NOTREACHED*/
1375 	}
1376 	else
1377 	{
1378 		/* parent -- wait for exit status */
1379 		register int i;
1380 		auto int stat;
1381 
1382 		while ((i = wait(&stat)) != pid)
1383 		{
1384 			if (i < 0)
1385 			{
1386 				stat = EX_OSERR << 8;
1387 				break;
1388 			}
1389 		}
1390 		if ((stat & 0377) != 0)
1391 			stat = EX_UNAVAILABLE << 8;
1392 		return ((stat >> 8) & 0377);
1393 	}
1394 }
1395 /*
1396 **  SENDALL -- actually send all the messages.
1397 **
1398 **	Parameters:
1399 **		verifyonly -- if set, only give verification messages.
1400 **
1401 **	Returns:
1402 **		none.
1403 **
1404 **	Side Effects:
1405 **		Scans the send lists and sends everything it finds.
1406 */
1407 
1408 sendall(verifyonly)
1409 	bool verifyonly;
1410 {
1411 	register ADDRESS *q;
1412 	typedef int (*fnptr)();
1413 
1414 # ifdef DEBUG
1415 	if (Debug > 1)
1416 	{
1417 		printf("\nSendQueue:\n");
1418 		printaddr(SendQueue, TRUE);
1419 	}
1420 # endif DEBUG
1421 
1422 	for (q = SendQueue; q != NULL; q = q->q_next)
1423 	{
1424 		if (verifyonly)
1425 		{
1426 			To = q->q_paddr;
1427 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1428 			{
1429 				if (bitset(M_LOCAL, q->q_mailer->m_flags))
1430 					message(Arpa_Info, "deliverable");
1431 				else
1432 					message(Arpa_Info, "queueable");
1433 			}
1434 		}
1435 		else
1436 			(void) deliver(q, (fnptr) NULL);
1437 	}
1438 }
1439