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