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