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.93		07/02/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 		else
866 			fprintf(Xscript, "%s\n", statmsg);
867 	}
868 
869 	/*
870 	**  Final cleanup.
871 	**	Log a record of the transaction.  Compute the new
872 	**	ExitStat -- if we already had an error, stick with
873 	**	that.
874 	*/
875 
876 	if (statmsg == NULL)
877 	{
878 		(void) sprintf(buf, "error %d", stat);
879 		statmsg = buf;
880 	}
881 
882 # ifdef LOG
883 	syslog(LOG_INFO, "%s->%s: %ld: %s", CurEnv->e_from.q_paddr, CurEnv->e_to, CurEnv->e_msgsize, statmsg);
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 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL &&
985 		    strcmp(m->m_from, "$f") == 0 && of_line == NULL)
986 		{
987 			p = origfrom;
988 			origfrom = NULL;
989 		}
990 		else if (bitset(H_DEFAULT, h->h_flags))
991 		{
992 			expand(h->h_value, buf, &buf[sizeof buf], e);
993 			p = buf;
994 		}
995 		else if (bitset(H_ADDR, h->h_flags))
996 		{
997 			register int opos;
998 			bool firstone = TRUE;
999 
1000 			/*
1001 			**  Output the address list translated by the
1002 			**  mailer and with commas.
1003 			*/
1004 
1005 			p = h->h_value;
1006 			if (p == NULL || *p == '\0' || nooutput)
1007 				continue;
1008 			obp = obuf;
1009 			(void) sprintf(obp, "%s: ", capitalize(h->h_field));
1010 			opos = strlen(h->h_field) + 2;
1011 			obp += opos;
1012 			while (*p != '\0')
1013 			{
1014 				register char *name = p;
1015 				extern char *remotename();
1016 				char savechar;
1017 
1018 				/* find the end of the name */
1019 				while (*p != '\0' && *p != ',')
1020 				{
1021 					extern bool isatword();
1022 					char *oldp;
1023 
1024 					if (!e->e_oldstyle || !isspace(*p))
1025 					{
1026 						p++;
1027 						continue;
1028 					}
1029 					oldp = p;
1030 					while (*p != '\0' && isspace(*p))
1031 						p++;
1032 					if (*p != '@' && !isatword(p))
1033 					{
1034 						p = oldp;
1035 						break;
1036 					}
1037 					p += *p == '@' ? 1 : 2;
1038 					while (*p != '\0' && isspace(*p))
1039 						p++;
1040 				}
1041 				savechar = *p;
1042 				*p = '\0';
1043 
1044 				/* translate the name to be relative */
1045 				name = remotename(name, m, FALSE);
1046 				if (*name == '\0')
1047 					continue;
1048 
1049 				/* output the name with nice formatting */
1050 				opos += strlen(name);
1051 				if (!firstone)
1052 					opos += 2;
1053 				if (opos > 78 && !firstone)
1054 				{
1055 					(void) sprintf(obp, ",\n");
1056 					putline(obuf, fp, fullsmtp);
1057 					obp = obuf;
1058 					(void) sprintf(obp, "        ");
1059 					obp += strlen(obp);
1060 					opos = 8 + strlen(name);
1061 				}
1062 				else if (!firstone)
1063 				{
1064 					(void) sprintf(obp, ", ");
1065 					obp += 2;
1066 				}
1067 				(void) sprintf(obp, "%s", name);
1068 				obp += strlen(obp);
1069 				firstone = FALSE;
1070 
1071 				/* clean up the source string */
1072 				*p = savechar;
1073 				while (*p != '\0' && (isspace(*p) || *p == ','))
1074 					p++;
1075 			}
1076 			(void) strcpy(obp, "\n");
1077 			putline(obuf, fp, fullsmtp);
1078 			nooutput = TRUE;
1079 		}
1080 		else
1081 			p = h->h_value;
1082 		if (p == NULL || *p == '\0')
1083 			continue;
1084 
1085 		/* hack, hack -- output Original-From field if different */
1086 		if (strcmp(h->h_field, "from") == 0 && origfrom != NULL)
1087 		{
1088 			/* output new Original-From line if needed */
1089 			if (of_line == NULL && !samefrom(p, origfrom))
1090 			{
1091 				(void) sprintf(obuf, "Original-From: %s\n", origfrom);
1092 				putline(obuf, fp, fullsmtp);
1093 			}
1094 			if (of_line != NULL && !nooutput && samefrom(p, of_line))
1095 			{
1096 				/* delete Original-From: line if redundant */
1097 				p = of_line;
1098 				of_line = NULL;
1099 			}
1100 		}
1101 		else if (strcmp(h->h_field, "original-from") == 0 && of_line == NULL)
1102 			nooutput = TRUE;
1103 
1104 		/* finally, output the header line */
1105 		if (!nooutput)
1106 		{
1107 			(void) sprintf(obuf, "%s: %s\n", capitalize(h->h_field), p);
1108 			putline(obuf, fp, fullsmtp);
1109 			h->h_flags |= H_USED;
1110 		}
1111 	}
1112 }
1113 /*
1114 **  PUTBODY -- put the body of a message.
1115 **
1116 **	Parameters:
1117 **		fp -- file to output onto.
1118 **		m -- a mailer descriptor.
1119 **		xdot -- if set, use SMTP hidden dot algorithm.
1120 **
1121 **	Returns:
1122 **		none.
1123 **
1124 **	Side Effects:
1125 **		The message is written onto fp.
1126 */
1127 
1128 putbody(fp, m, xdot)
1129 	FILE *fp;
1130 	struct mailer *m;
1131 	bool xdot;
1132 {
1133 	char buf[MAXLINE + 1];
1134 	bool fullsmtp = bitset(M_FULLSMTP, m->m_flags);
1135 
1136 	/*
1137 	**  Output the body of the message
1138 	*/
1139 
1140 #ifdef lint
1141 	/* m will be needed later for complete smtp emulation */
1142 	if (m == NULL)
1143 		return;
1144 #endif lint
1145 
1146 	if (TempFile != NULL)
1147 	{
1148 		rewind(TempFile);
1149 		buf[0] = '.';
1150 		while (!ferror(fp) && fgets(&buf[1], sizeof buf - 1, TempFile) != NULL)
1151 			putline((xdot && buf[1] == '.') ? buf : &buf[1], fp, fullsmtp);
1152 
1153 		if (ferror(TempFile))
1154 		{
1155 			syserr("putbody: read error");
1156 			ExitStat = EX_IOERR;
1157 		}
1158 	}
1159 
1160 	(void) fflush(fp);
1161 	if (ferror(fp) && errno != EPIPE)
1162 	{
1163 		syserr("putbody: write error");
1164 		ExitStat = EX_IOERR;
1165 	}
1166 	errno = 0;
1167 }
1168 /*
1169 **  ISATWORD -- tell if the word we are pointing to is "at".
1170 **
1171 **	Parameters:
1172 **		p -- word to check.
1173 **
1174 **	Returns:
1175 **		TRUE -- if p is the word at.
1176 **		FALSE -- otherwise.
1177 **
1178 **	Side Effects:
1179 **		none.
1180 */
1181 
1182 bool
1183 isatword(p)
1184 	register char *p;
1185 {
1186 	extern char lower();
1187 
1188 	if (lower(p[0]) == 'a' && lower(p[1]) == 't' &&
1189 	    p[2] != '\0' && isspace(p[2]))
1190 		return (TRUE);
1191 	return (FALSE);
1192 }
1193 /*
1194 **  REMOTENAME -- return the name relative to the current mailer
1195 **
1196 **	Parameters:
1197 **		name -- the name to translate.
1198 **		force -- if set, forces rewriting even if the mailer
1199 **			does not request it.  Used for rewriting
1200 **			sender addresses.
1201 **
1202 **	Returns:
1203 **		the text string representing this address relative to
1204 **			the receiving mailer.
1205 **
1206 **	Side Effects:
1207 **		none.
1208 **
1209 **	Warnings:
1210 **		The text string returned is tucked away locally;
1211 **			copy it if you intend to save it.
1212 */
1213 
1214 char *
1215 remotename(name, m, force)
1216 	char *name;
1217 	struct mailer *m;
1218 	bool force;
1219 {
1220 	static char buf[MAXNAME];
1221 	char lbuf[MAXNAME];
1222 	extern char *macvalue();
1223 	char *oldf = macvalue('f');
1224 	char *oldx = macvalue('x');
1225 	char *oldg = macvalue('g');
1226 	extern char **prescan();
1227 	register char **pvp;
1228 	extern char *getxpart();
1229 	extern ADDRESS *buildaddr();
1230 
1231 	/*
1232 	**  See if this mailer wants the name to be rewritten.  There are
1233 	**  many problems here, owing to the standards for doing replies.
1234 	**  In general, these names should only be rewritten if we are
1235 	**  sending to another host that runs sendmail.
1236 	*/
1237 
1238 	if (!bitset(M_RELRCPT, m->m_flags) && !force)
1239 		return (name);
1240 
1241 	/*
1242 	**  Do general rewriting of name.
1243 	**	This will also take care of doing global name translation.
1244 	*/
1245 
1246 	define('x', getxpart(name));
1247 	pvp = prescan(name, '\0');
1248 	if (pvp == NULL)
1249 		return (name);
1250 	rewrite(pvp, 1);
1251 	rewrite(pvp, 3);
1252 	if (**pvp == CANONNET)
1253 	{
1254 		/* oops... resolved to something */
1255 		return (name);
1256 	}
1257 	cataddr(pvp, lbuf, sizeof lbuf);
1258 
1259 	/* make the name relative to the receiving mailer */
1260 	define('f', lbuf);
1261 	expand(m->m_from, buf, &buf[sizeof buf - 1], CurEnv);
1262 
1263 	/* rewrite to get rid of garbage we added in the expand above */
1264 	pvp = prescan(buf, '\0');
1265 	if (pvp == NULL)
1266 		return (name);
1267 	rewrite(pvp, 2);
1268 	cataddr(pvp, lbuf, sizeof lbuf);
1269 
1270 	/* now add any comment info we had before back */
1271 	define('g', lbuf);
1272 	expand("$q", buf, &buf[sizeof buf - 1], CurEnv);
1273 
1274 	define('f', oldf);
1275 	define('g', oldg);
1276 	define('x', oldx);
1277 
1278 # ifdef DEBUG
1279 	if (Debug > 0)
1280 		printf("remotename(%s) => `%s'\n", name, buf);
1281 # endif DEBUG
1282 	return (buf);
1283 }
1284 /*
1285 **  SAMEFROM -- tell if two text addresses represent the same from address.
1286 **
1287 **	Parameters:
1288 **		ifrom -- internally generated form of from address.
1289 **		efrom -- external form of from address.
1290 **
1291 **	Returns:
1292 **		TRUE -- if they convey the same info.
1293 **		FALSE -- if any information has been lost.
1294 **
1295 **	Side Effects:
1296 **		none.
1297 */
1298 
1299 bool
1300 samefrom(ifrom, efrom)
1301 	char *ifrom;
1302 	char *efrom;
1303 {
1304 	register char *p;
1305 	char buf[MAXNAME + 4];
1306 
1307 # ifdef DEBUG
1308 	if (Debug > 7)
1309 		printf("samefrom(%s,%s)-->", ifrom, efrom);
1310 # endif DEBUG
1311 	if (strcmp(ifrom, efrom) == 0)
1312 		goto success;
1313 	p = index(ifrom, '@');
1314 	if (p == NULL)
1315 		goto failure;
1316 	*p = '\0';
1317 	(void) strcpy(buf, ifrom);
1318 	(void) strcat(buf, " at ");
1319 	*p++ = '@';
1320 	(void) strcat(buf, p);
1321 	if (strcmp(buf, efrom) == 0)
1322 		goto success;
1323 
1324   failure:
1325 # ifdef DEBUG
1326 	if (Debug > 7)
1327 		printf("FALSE\n");
1328 # endif DEBUG
1329 	return (FALSE);
1330 
1331   success:
1332 # ifdef DEBUG
1333 	if (Debug > 7)
1334 		printf("TRUE\n");
1335 # endif DEBUG
1336 	return (TRUE);
1337 }
1338 /*
1339 **  MAILFILE -- Send a message to a file.
1340 **
1341 **	If the file has the setuid/setgid bits set, but NO execute
1342 **	bits, sendmail will try to become the owner of that file
1343 **	rather than the real user.  Obviously, this only works if
1344 **	sendmail runs as root.
1345 **
1346 **	Parameters:
1347 **		filename -- the name of the file to send to.
1348 **		ctladdr -- the controlling address header -- includes
1349 **			the userid/groupid to be when sending.
1350 **
1351 **	Returns:
1352 **		The exit code associated with the operation.
1353 **
1354 **	Side Effects:
1355 **		none.
1356 */
1357 
1358 mailfile(filename, ctladdr)
1359 	char *filename;
1360 	ADDRESS *ctladdr;
1361 {
1362 	register FILE *f;
1363 	register int pid;
1364 
1365 	/*
1366 	**  Fork so we can change permissions here.
1367 	**	Note that we MUST use fork, not vfork, because of
1368 	**	the complications of calling subroutines, etc.
1369 	*/
1370 
1371 	DOFORK(fork);
1372 
1373 	if (pid < 0)
1374 		return (EX_OSERR);
1375 	else if (pid == 0)
1376 	{
1377 		/* child -- actually write to file */
1378 		struct stat stb;
1379 
1380 		(void) signal(SIGINT, SIG_DFL);
1381 		(void) signal(SIGHUP, SIG_DFL);
1382 		(void) signal(SIGTERM, SIG_DFL);
1383 		umask(OldUmask);
1384 		if (stat(filename, &stb) < 0)
1385 			stb.st_mode = 0666;
1386 		if (bitset(0111, stb.st_mode))
1387 			exit(EX_CANTCREAT);
1388 		if (ctladdr == NULL)
1389 			ctladdr = &CurEnv->e_from;
1390 		if (!bitset(S_ISGID, stb.st_mode) || setgid(stb.st_gid) < 0)
1391 		{
1392 			if (ctladdr->q_uid == 0)
1393 				(void) setgid(DefGid);
1394 			else
1395 				(void) setgid(ctladdr->q_gid);
1396 		}
1397 		if (!bitset(S_ISUID, stb.st_mode) || setuid(stb.st_uid) < 0)
1398 		{
1399 			if (ctladdr->q_uid == 0)
1400 				(void) setuid(DefUid);
1401 			else
1402 				(void) setuid(ctladdr->q_uid);
1403 		}
1404 		f = dfopen(filename, "a");
1405 		if (f == NULL)
1406 			exit(EX_CANTCREAT);
1407 
1408 		putfromline(f, Mailer[1]);
1409 		(*CurEnv->e_puthdr)(f, Mailer[1], CurEnv);
1410 		fputs("\n", f);
1411 		(*CurEnv->e_putbody)(f, Mailer[1], FALSE);
1412 		fputs("\n", f);
1413 		(void) fclose(f);
1414 		(void) fflush(stdout);
1415 
1416 		/* reset ISUID & ISGID bits for paranoid systems */
1417 		(void) chmod(filename, (int) stb.st_mode);
1418 		exit(EX_OK);
1419 		/*NOTREACHED*/
1420 	}
1421 	else
1422 	{
1423 		/* parent -- wait for exit status */
1424 		register int i;
1425 		auto int stat;
1426 
1427 		while ((i = wait(&stat)) != pid)
1428 		{
1429 			if (i < 0)
1430 			{
1431 				stat = EX_OSERR << 8;
1432 				break;
1433 			}
1434 		}
1435 		if ((stat & 0377) != 0)
1436 			stat = EX_UNAVAILABLE << 8;
1437 		return ((stat >> 8) & 0377);
1438 	}
1439 }
1440 /*
1441 **  SENDALL -- actually send all the messages.
1442 **
1443 **	Parameters:
1444 **		e -- the envelope to send.
1445 **		verifyonly -- if set, only give verification messages.
1446 **
1447 **	Returns:
1448 **		none.
1449 **
1450 **	Side Effects:
1451 **		Scans the send lists and sends everything it finds.
1452 **		Delivers any appropriate error messages.
1453 */
1454 
1455 sendall(e, verifyonly)
1456 	ENVELOPE *e;
1457 	bool verifyonly;
1458 {
1459 	register ADDRESS *q;
1460 
1461 # ifdef DEBUG
1462 	if (Debug > 1)
1463 	{
1464 		printf("\nSend Queue:\n");
1465 		printaddr(e->e_sendqueue, TRUE);
1466 	}
1467 # endif DEBUG
1468 
1469 	/*
1470 	**  Run through the list and send everything.
1471 	*/
1472 
1473 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1474 	{
1475 		if (verifyonly)
1476 		{
1477 			CurEnv->e_to = q->q_paddr;
1478 			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
1479 				message(Arpa_Info, "deliverable");
1480 		}
1481 		else
1482 			(void) deliver(q);
1483 	}
1484 
1485 	/*
1486 	**  Now run through and check for errors.
1487 	*/
1488 
1489 	if (verifyonly)
1490 		return;
1491 
1492 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
1493 	{
1494 		register ADDRESS *qq;
1495 
1496 		if (bitset(QQUEUEUP, q->q_flags))
1497 			e->e_queueup = TRUE;
1498 		if (!bitset(QBADADDR, q->q_flags))
1499 			continue;
1500 
1501 		/* we have an address that failed -- find the parent */
1502 		for (qq = q; qq != NULL; qq = qq->q_alias)
1503 		{
1504 			char obuf[MAXNAME + 6];
1505 			extern char *aliaslookup();
1506 
1507 			/* we can only have owners for local addresses */
1508 			if (!bitset(M_LOCAL, qq->q_mailer->m_flags))
1509 				continue;
1510 
1511 			/* see if the owner list exists */
1512 			(void) strcpy(obuf, "owner-");
1513 			if (strncmp(qq->q_user, "owner-", 6) == 0)
1514 				(void) strcat(obuf, "owner");
1515 			else
1516 				(void) strcat(obuf, qq->q_user);
1517 			if (aliaslookup(obuf) == NULL)
1518 				continue;
1519 
1520 			/* owner list exists -- add it to the error queue */
1521 			qq->q_flags &= ~QPRIMARY;
1522 			sendto(obuf, 1, qq, &e->e_errorqueue);
1523 			MailBack = TRUE;
1524 			break;
1525 		}
1526 
1527 		/* if we did not find an owner, send to the sender */
1528 		if (qq == NULL)
1529 			sendto(e->e_from.q_paddr, 1, qq, &e->e_errorqueue);
1530 	}
1531 }
1532 /*
1533 **  CHECKERRORS -- check a queue of addresses and process errors.
1534 **
1535 **	Parameters:
1536 **		e -- the envelope to check.
1537 **
1538 **	Returns:
1539 **		none.
1540 **
1541 **	Side Effects:
1542 **		Arranges to queue all tempfailed messages in q
1543 **			or deliver error responses.
1544 */
1545 
1546 checkerrors(e)
1547 	register ENVELOPE *e;
1548 {
1549 # ifdef DEBUG
1550 	if (Debug > 0)
1551 	{
1552 		printf("\ncheckerrors: errorqueue:\n");
1553 		printaddr(e->e_errorqueue, TRUE);
1554 	}
1555 # endif DEBUG
1556 
1557 	/* mail back the transcript on errors */
1558 	if (FatalErrors)
1559 		savemail();
1560 
1561 	/* queue up anything laying around */
1562 	if (e->e_queueup)
1563 	{
1564 # ifdef QUEUE
1565 		queueup(e, FALSE);
1566 # else QUEUE
1567 		syserr("finis: trying to queue %s", e->e_df);
1568 # endif QUEUE
1569 	}
1570 }
1571