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