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