1 # include <signal.h>
2 # include <errno.h>
3 # include "sendmail.h"
4 # ifdef LOG
5 # include <syslog.h>
6 # endif LOG
7 
8 static char SccsId[] = "@(#)deliver.c	3.31	08/29/81";
9 
10 /*
11 **  DELIVER -- Deliver a message to a particular address.
12 **
13 **	Parameters:
14 **		to -- the address to deliver the message to.
15 **		editfcn -- if non-NULL, we want to call this function
16 **			to output the letter (instead of just out-
17 **			putting it raw).
18 **
19 **	Returns:
20 **		zero -- successfully delivered.
21 **		else -- some failure, see ExitStat for more info.
22 **
23 **	Side Effects:
24 **		The standard input is passed off to someone.
25 */
26 
27 deliver(to, editfcn)
28 	ADDRESS *to;
29 	int (*editfcn)();
30 {
31 	char *host;
32 	char *user;
33 	char **pvp;
34 	register char **mvp;
35 	register char *p;
36 	register struct mailer *m;
37 	register int i;
38 	extern putmessage();
39 	extern bool checkcompat();
40 	char *pv[MAXPV+1];
41 	char tobuf[MAXLINE];
42 	char buf[MAXNAME];
43 	bool firstone;
44 
45 	if (bitset(QDONTSEND, to->q_flags))
46 		return (0);
47 
48 # ifdef DEBUG
49 	if (Debug)
50 		printf("\n--deliver, mailer=%d, host=`%s', first user=`%s'\n",
51 			to->q_mailer, to->q_host, to->q_user);
52 # endif DEBUG
53 
54 	/*
55 	**  Do initial argv setup.
56 	**	Insert the mailer name.  Notice that $x expansion is
57 	**	NOT done on the mailer name.  Then, if the mailer has
58 	**	a picky -f flag, we insert it as appropriate.  This
59 	**	code does not check for 'pv' overflow; this places a
60 	**	manifest lower limit of 4 for MAXPV.
61 	*/
62 
63 	m = Mailer[to->q_mailer];
64 	host = to->q_host;
65 	define('g', m->m_from);		/* translated from address */
66 	define('h', host);		/* to host */
67 	Errors = 0;
68 	errno = 0;
69 	pvp = pv;
70 	*pvp++ = m->m_argv[0];
71 
72 	/* insert -f or -r flag as appropriate */
73 	if (bitset(M_FOPT|M_ROPT, m->m_flags) && FromFlag)
74 	{
75 		if (bitset(M_FOPT, m->m_flags))
76 			*pvp++ = "-f";
77 		else
78 			*pvp++ = "-r";
79 		(void) expand("$g", buf, &buf[sizeof buf - 1]);
80 		*pvp++ = newstr(buf);
81 	}
82 
83 	/*
84 	**  Append the other fixed parts of the argv.  These run
85 	**  up to the first entry containing "$u".  There can only
86 	**  be one of these, and there are only a few more slots
87 	**  in the pv after it.
88 	*/
89 
90 	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
91 	{
92 		while ((p = index(p, '$')) != NULL)
93 			if (*++p == 'u')
94 				break;
95 		if (p != NULL)
96 			break;
97 
98 		/* this entry is safe -- go ahead and process it */
99 		(void) expand(*mvp, buf, &buf[sizeof buf - 1]);
100 		*pvp++ = newstr(buf);
101 		if (pvp >= &pv[MAXPV - 3])
102 		{
103 			syserr("Too many parameters to %s before $u", pv[0]);
104 			return (-1);
105 		}
106 	}
107 	if (*mvp == NULL)
108 		syserr("No $u in mailer argv for %s", pv[0]);
109 
110 	/*
111 	**  At this point *mvp points to the argument with $u.  We
112 	**  run through our address list and append all the addresses
113 	**  we can.  If we run out of space, do not fret!  We can
114 	**  always send another copy later.
115 	*/
116 
117 	tobuf[0] = '\0';
118 	firstone = TRUE;
119 	To = tobuf;
120 	for (; to != NULL; to = to->q_next)
121 	{
122 		/* avoid sending multiple recipients to dumb mailers */
123 		if (!firstone && !bitset(M_MUSER, m->m_flags))
124 			break;
125 
126 		/* if already sent or not for this host, don't send */
127 		if (bitset(QDONTSEND, to->q_flags) || strcmp(to->q_host, host) != 0)
128 			continue;
129 		user = to->q_user;
130 		To = to->q_paddr;
131 		to->q_flags |= QDONTSEND;
132 		firstone = FALSE;
133 
134 # ifdef DEBUG
135 		if (Debug)
136 			printf("   send to `%s'\n", user);
137 # endif DEBUG
138 
139 		/*
140 		**  Check to see that these people are allowed to
141 		**  talk to each other.
142 		*/
143 
144 		if (!checkcompat(to))
145 		{
146 			giveresponse(EX_UNAVAILABLE, TRUE, m);
147 			continue;
148 		}
149 
150 		/*
151 		**  Strip quote bits from names if the mailer is dumb
152 		**	about them.
153 		*/
154 
155 		if (bitset(M_STRIPQ, m->m_flags))
156 		{
157 			stripquotes(user, TRUE);
158 			stripquotes(host, TRUE);
159 		}
160 		else
161 		{
162 			stripquotes(user, FALSE);
163 			stripquotes(host, FALSE);
164 		}
165 
166 		/*
167 		**  If an error message has already been given, don't
168 		**	bother to send to this address.
169 		**
170 		**	>>>>>>>>>> This clause assumes that the local mailer
171 		**	>> NOTE >> cannot do any further aliasing; that
172 		**	>>>>>>>>>> function is subsumed by sendmail.
173 		*/
174 
175 		if (bitset(QBADADDR, to->q_flags))
176 			continue;
177 
178 		/*
179 		**  See if this user name is "special".
180 		**	If the user name has a slash in it, assume that this
181 		**	is a file -- send it off without further ado.
182 		**	Note that this means that editfcn's will not
183 		**	be applied to the message.  Also note that
184 		**	this type of addresses is not processed along
185 		**	with the others, so we fudge on the To person.
186 		*/
187 
188 		if (m == Mailer[MN_LOCAL])
189 		{
190 			if (index(user, '/') != NULL)
191 			{
192 				i = mailfile(user);
193 				giveresponse(i, TRUE, m);
194 				continue;
195 			}
196 		}
197 
198 		/* create list of users for error messages */
199 		if (tobuf[0] != '\0')
200 			(void) strcat(tobuf, ",");
201 		(void) strcat(tobuf, to->q_paddr);
202 		define('u', user);		/* to user */
203 		define('z', to->q_home);	/* user's home */
204 
205 		/* expand out this user */
206 		(void) expand(user, buf, &buf[sizeof buf - 1]);
207 		*pvp++ = newstr(buf);
208 		if (pvp >= &pv[MAXPV - 2])
209 		{
210 			/* allow some space for trailing parms */
211 			break;
212 		}
213 	}
214 
215 	/* see if any addresses still exist */
216 	if (tobuf[0] == '\0')
217 		return (0);
218 
219 	/* print out messages as full list */
220 	To = tobuf;
221 
222 	/*
223 	**  Fill out any parameters after the $u parameter.
224 	*/
225 
226 	while (*++mvp != NULL)
227 	{
228 		(void) expand(*mvp, buf, &buf[sizeof buf - 1]);
229 		*pvp++ = newstr(buf);
230 		if (pvp >= &pv[MAXPV])
231 			syserr("deliver: pv overflow after $u for %s", pv[0]);
232 	}
233 	*pvp++ = NULL;
234 
235 	/*
236 	**  Call the mailer.
237 	**	The argument vector gets built, pipes
238 	**	are created as necessary, and we fork & exec as
239 	**	appropriate.
240 	**
241 	**	Notice the tacky hack to handle private mailers.
242 	*/
243 
244 	if (editfcn == NULL)
245 		editfcn = putmessage;
246 	i = sendoff(m, pv, editfcn);
247 
248 	return (i);
249 }
250 /*
251 **  DOFORK -- do a fork, retrying a couple of times on failure.
252 **
253 **	This MUST be a macro, since after a vfork we are running
254 **	two processes on the same stack!!!
255 **
256 **	Parameters:
257 **		none.
258 **
259 **	Returns:
260 **		From a macro???  You've got to be kidding!
261 **
262 **	Side Effects:
263 **		Modifies the ==> LOCAL <== variable 'pid', leaving:
264 **			pid of child in parent, zero in child.
265 **			-1 on unrecoverable error.
266 **
267 **	Notes:
268 **		I'm awfully sorry this looks so awful.  That's
269 **		vfork for you.....
270 */
271 
272 # define NFORKTRIES	5
273 # ifdef VFORK
274 # define XFORK	vfork
275 # else VFORK
276 # define XFORK	fork
277 # endif VFORK
278 
279 # define DOFORK(fORKfN) \
280 {\
281 	register int i;\
282 \
283 	for (i = NFORKTRIES; i-- > 0; )\
284 	{\
285 		pid = fORKfN();\
286 		if (pid >= 0)\
287 			break;\
288 		sleep((unsigned) NFORKTRIES - i);\
289 	}\
290 }
291 /*
292 **  SENDOFF -- send off call to mailer & collect response.
293 **
294 **	Parameters:
295 **		m -- mailer descriptor.
296 **		pvp -- parameter vector to send to it.
297 **		editfcn -- function to pipe it through.
298 **
299 **	Returns:
300 **		exit status of mailer.
301 **
302 **	Side Effects:
303 **		none.
304 */
305 
306 sendoff(m, pvp, editfcn)
307 	struct mailer *m;
308 	char **pvp;
309 	int (*editfcn)();
310 {
311 	auto int st;
312 	register int i;
313 	int pid;
314 	int pvect[2];
315 	FILE *mfile;
316 	extern putmessage();
317 	extern FILE *fdopen();
318 
319 # ifdef DEBUG
320 	if (Debug)
321 	{
322 		printf("Sendoff:\n");
323 		printav(pvp);
324 	}
325 # endif DEBUG
326 
327 	/* create a pipe to shove the mail through */
328 	if (pipe(pvect) < 0)
329 	{
330 		syserr("pipe");
331 		return (-1);
332 	}
333 	DOFORK(XFORK);
334 	if (pid < 0)
335 	{
336 		syserr("Cannot fork");
337 		(void) close(pvect[0]);
338 		(void) close(pvect[1]);
339 		return (-1);
340 	}
341 	else if (pid == 0)
342 	{
343 		/* child -- set up input & exec mailer */
344 		/* make diagnostic output be standard output */
345 		(void) signal(SIGINT, SIG_DFL);
346 		(void) signal(SIGHUP, SIG_DFL);
347 		(void) signal(SIGTERM, SIG_DFL);
348 		(void) close(2);
349 		(void) dup(1);
350 		(void) close(0);
351 		if (dup(pvect[0]) < 0)
352 		{
353 			syserr("Cannot dup to zero!");
354 			_exit(EX_OSERR);
355 		}
356 		(void) close(pvect[0]);
357 		(void) close(pvect[1]);
358 		if (!bitset(M_RESTR, m->m_flags))
359 		{
360 			(void) setuid(getuid());
361 			(void) setgid(getgid());
362 		}
363 # ifndef VFORK
364 		/*
365 		**  We have to be careful with vfork - we can't mung up the
366 		**  memory but we don't want the mailer to inherit any extra
367 		**  open files.  Chances are the mailer won't
368 		**  care about an extra file, but then again you never know.
369 		**  Actually, we would like to close(fileno(pwf)), but it's
370 		**  declared static so we can't.  But if we fclose(pwf), which
371 		**  is what endpwent does, it closes it in the parent too and
372 		**  the next getpwnam will be slower.  If you have a weird
373 		**  mailer that chokes on the extra file you should do the
374 		**  endpwent().
375 		**
376 		**  Similar comments apply to log.  However, openlog is
377 		**  clever enough to set the FIOCLEX mode on the file,
378 		**  so it will be closed automatically on the exec.
379 		*/
380 
381 		endpwent();
382 # ifdef LOG
383 		closelog();
384 # endif LOG
385 # endif VFORK
386 		execv(m->m_mailer, pvp);
387 		/* syserr fails because log is closed */
388 		/* syserr("Cannot exec %s", m->m_mailer); */
389 		printf("Cannot exec '%s' errno=%d\n", m->m_mailer, errno);
390 		(void) fflush(stdout);
391 		_exit(EX_UNAVAILABLE);
392 	}
393 
394 	/* write out message to mailer */
395 	(void) close(pvect[0]);
396 	(void) signal(SIGPIPE, SIG_IGN);
397 	mfile = fdopen(pvect[1], "w");
398 	if (editfcn == NULL)
399 		editfcn = putmessage;
400 	(*editfcn)(mfile, m);
401 	(void) fclose(mfile);
402 
403 	/*
404 	**  Wait for child to die and report status.
405 	**	We should never get fatal errors (e.g., segmentation
406 	**	violation), so we report those specially.  For other
407 	**	errors, we choose a status message (into statmsg),
408 	**	and if it represents an error, we print it.
409 	*/
410 
411 	while ((i = wait(&st)) > 0 && i != pid)
412 		continue;
413 	if (i < 0)
414 	{
415 		syserr("wait");
416 		return (-1);
417 	}
418 	if ((st & 0377) != 0)
419 	{
420 		syserr("%s: stat %o", pvp[0], st);
421 		ExitStat = EX_UNAVAILABLE;
422 		return (-1);
423 	}
424 	i = (st >> 8) & 0377;
425 	giveresponse(i, TRUE, m);
426 	return (i);
427 }
428 /*
429 **  GIVERESPONSE -- Interpret an error response from a mailer
430 **
431 **	Parameters:
432 **		stat -- the status code from the mailer (high byte
433 **			only; core dumps must have been taken care of
434 **			already).
435 **		force -- if set, force an error message output, even
436 **			if the mailer seems to like to print its own
437 **			messages.
438 **		m -- the mailer descriptor for this mailer.
439 **
440 **	Returns:
441 **		none.
442 **
443 **	Side Effects:
444 **		Errors may be incremented.
445 **		ExitStat may be set.
446 **
447 **	Called By:
448 **		deliver
449 */
450 
451 giveresponse(stat, force, m)
452 	int stat;
453 	int force;
454 	register struct mailer *m;
455 {
456 	register char *statmsg;
457 	extern char *SysExMsg[];
458 	register int i;
459 	extern int N_SysEx;
460 	extern long MsgSize;
461 	char buf[30];
462 
463 	i = stat - EX__BASE;
464 	if (i < 0 || i > N_SysEx)
465 		statmsg = NULL;
466 	else
467 		statmsg = SysExMsg[i];
468 	if (stat == 0)
469 	{
470 		if (bitset(M_LOCAL, m->m_flags))
471 			statmsg = "delivered";
472 		else
473 			statmsg = "queued";
474 		if (Verbose)
475 			message(Arpa_Info, statmsg);
476 	}
477 	else
478 	{
479 		Errors++;
480 		if (statmsg == NULL && m->m_badstat != 0)
481 		{
482 			stat = m->m_badstat;
483 			i = stat - EX__BASE;
484 # ifdef DEBUG
485 			if (i < 0 || i >= N_SysEx)
486 				syserr("Bad m_badstat %d", stat);
487 			else
488 # endif DEBUG
489 			statmsg = SysExMsg[i];
490 		}
491 		if (statmsg == NULL)
492 			usrerr("unknown mailer response %d", stat);
493 		else if (force || !bitset(M_QUIET, m->m_flags) || Verbose)
494 			usrerr("%s", statmsg);
495 	}
496 
497 	/*
498 	**  Final cleanup.
499 	**	Log a record of the transaction.  Compute the new
500 	**	ExitStat -- if we already had an error, stick with
501 	**	that.
502 	*/
503 
504 	if (statmsg == NULL)
505 	{
506 		(void) sprintf(buf, "error %d", stat);
507 		statmsg = buf;
508 	}
509 
510 # ifdef LOG
511 	syslog(LOG_INFO, "%s->%s: %ld: %s", From.q_paddr, To, MsgSize, statmsg);
512 # endif LOG
513 	setstat(stat);
514 }
515 /*
516 **  PUTMESSAGE -- output a message to the final mailer.
517 **
518 **	This routine takes care of recreating the header from the
519 **	in-core copy, etc.
520 **
521 **	Parameters:
522 **		fp -- file to output onto.
523 **		m -- a mailer descriptor.
524 **
525 **	Returns:
526 **		none.
527 **
528 **	Side Effects:
529 **		The message is written onto fp.
530 */
531 
532 putmessage(fp, m)
533 	FILE *fp;
534 	struct mailer *m;
535 {
536 	char buf[BUFSIZ];
537 	register int i;
538 	HDR *h;
539 	register char *p;
540 	extern char *arpadate();
541 	bool anyheader = FALSE;
542 	extern char *capitalize();
543 
544 	/* output "From" line unless supressed */
545 	if (!bitset(M_NHDR, m->m_flags))
546 	{
547 		(void) expand("$l", buf, &buf[sizeof buf - 1]);
548 		fprintf(fp, "%s\n", buf);
549 	}
550 
551 	/* output all header lines */
552 	for (h = Header; h != NULL; h = h->h_link)
553 	{
554 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
555 		{
556 			p = ")><(";		/* can't happen (I hope) */
557 			goto checkfrom;
558 		}
559 		if (bitset(H_DEFAULT, h->h_flags))
560 		{
561 			(void) expand(h->h_value, buf, &buf[sizeof buf]);
562 			p = buf;
563 		}
564 		else
565 			p = h->h_value;
566 		if (*p == '\0')
567 			continue;
568 		fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
569 		h->h_flags |= H_USED;
570 		anyheader = TRUE;
571 
572 		/* hack, hack -- output Original-From field if different */
573 	checkfrom:
574 		if (strcmp(h->h_field, "from") == 0)
575 		{
576 			extern char *hvalue();
577 			char *ofrom = hvalue("original-from");
578 
579 			if (ofrom != NULL && strcmp(p, ofrom) != 0)
580 				fprintf(fp, "Original-From: %s\n", ofrom);
581 		}
582 	}
583 
584 	if (anyheader)
585 		fprintf(fp, "\n");
586 
587 	/* output the body of the message */
588 	rewind(TempFile);
589 	while (!ferror(fp) && (i = fread(buf, 1, BUFSIZ, TempFile)) > 0)
590 		(void) fwrite(buf, 1, i, fp);
591 
592 	if (ferror(fp) && errno != EPIPE)
593 	{
594 		syserr("putmessage: write error");
595 		setstat(EX_IOERR);
596 	}
597 	errno = 0;
598 }
599 /*
600 **  MAILFILE -- Send a message to a file.
601 **
602 **	Parameters:
603 **		filename -- the name of the file to send to.
604 **
605 **	Returns:
606 **		The exit code associated with the operation.
607 **
608 **	Side Effects:
609 **		none.
610 */
611 
612 mailfile(filename)
613 	char *filename;
614 {
615 	register FILE *f;
616 	register int pid;
617 	register int i;
618 
619 	/*
620 	**  Fork so we can change permissions here.
621 	**	Note that we MUST use fork, not vfork, because of
622 	**	the complications of calling subroutines, etc.
623 	*/
624 
625 	DOFORK(fork);
626 
627 	if (pid < 0)
628 		return (EX_OSERR);
629 	else if (pid == 0)
630 	{
631 		/* child -- actually write to file */
632 		(void) setuid(getuid());
633 		(void) setgid(getgid());
634 		(void) signal(SIGINT, SIG_DFL);
635 		(void) signal(SIGHUP, SIG_DFL);
636 		(void) signal(SIGTERM, SIG_DFL);
637 		f = fopen(filename, "a");
638 		if (f == NULL)
639 			exit(EX_CANTCREAT);
640 
641 		putmessage(f, Mailer[1]);
642 		fputs("\n", f);
643 		(void) fclose(f);
644 		(void) fflush(stdout);
645 		exit(EX_OK);
646 	}
647 	else
648 	{
649 		/* parent -- wait for exit status */
650 		register int i;
651 		auto int stat;
652 
653 		while ((i = wait(&stat)) != pid)
654 		{
655 			if (i < 0)
656 			{
657 				stat = EX_OSERR << 8;
658 				break;
659 			}
660 		}
661 		if ((stat & 0377) != 0)
662 			stat = EX_UNAVAILABLE << 8;
663 		return ((stat >> 8) & 0377);
664 	}
665 }
666