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