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.12	08/04/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])
208 		{
209 			if (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 	/* print out messages as full list */
233 	To = tobuf;
234 
235 	/*
236 	**  Fill out any parameters after the $u parameter.
237 	*/
238 
239 	while (*++mvp != NULL)
240 	{
241 		expand(*mvp, buf, &buf[sizeof buf - 1]);
242 		*pvp++ = newstr(buf);
243 		if (pvp >= &pv[MAXPV])
244 			syserr("deliver: pv overflow after $u for %s", pv[0]);
245 	}
246 	*pvp++ = NULL;
247 
248 	/*
249 	**  Call the mailer.
250 	**	The argument vector gets built, pipes
251 	**	are created as necessary, and we fork & exec as
252 	**	appropriate.
253 	*/
254 
255 	if (editfcn == NULL)
256 		editfcn = putmessage;
257 	i = sendoff(m, pv, editfcn);
258 
259 	return (i);
260 }
261 /*
262 **  SENDOFF -- send off call to mailer & collect response.
263 **
264 **	Parameters:
265 **		m -- mailer descriptor.
266 **		pvp -- parameter vector to send to it.
267 **		editfcn -- function to pipe it through.
268 **
269 **	Returns:
270 **		exit status of mailer.
271 **
272 **	Side Effects:
273 **		none.
274 */
275 
276 #define NFORKTRIES	5
277 
278 sendoff(m, pvp, editfcn)
279 	struct mailer *m;
280 	char **pvp;
281 	int (*editfcn)();
282 {
283 	auto int st;
284 	register int i;
285 	int pid;
286 	int pvect[2];
287 	FILE *mfile;
288 	extern putmessage();
289 	extern pipesig();
290 	extern FILE *fdopen();
291 
292 # ifdef DEBUG
293 	if (Debug)
294 	{
295 		printf("Sendoff:\n");
296 		printav(pvp);
297 	}
298 # endif DEBUG
299 
300 	rewind(stdin);
301 
302 	/* create a pipe to shove the mail through */
303 	if (pipe(pvect) < 0)
304 	{
305 		syserr("pipe");
306 		return (-1);
307 	}
308 	for (i = NFORKTRIES; i-- > 0; )
309 	{
310 # ifdef VFORK
311 		pid = vfork();
312 # else
313 		pid = fork();
314 # endif
315 		if (pid >= 0)
316 			break;
317 		sleep(NFORKTRIES - i);
318 	}
319 	if (pid < 0)
320 	{
321 		syserr("Cannot fork");
322 		close(pvect[0]);
323 		close(pvect[1]);
324 		return (-1);
325 	}
326 	else if (pid == 0)
327 	{
328 		/* child -- set up input & exec mailer */
329 		/* make diagnostic output be standard output */
330 		close(2);
331 		dup(1);
332 		signal(SIGINT, SIG_IGN);
333 		close(0);
334 		if (dup(pvect[0]) < 0)
335 		{
336 			syserr("Cannot dup to zero!");
337 			_exit(EX_OSERR);
338 		}
339 		close(pvect[0]);
340 		close(pvect[1]);
341 		if (!bitset(M_RESTR, m->m_flags))
342 			setuid(getuid());
343 # ifndef VFORK
344 		/*
345 		**  We have to be careful with vfork - we can't mung up the
346 		**  memory but we don't want the mailer to inherit any extra
347 		**  open files.  Chances are the mailer won't
348 		**  care about an extra file, but then again you never know.
349 		**  Actually, we would like to close(fileno(pwf)), but it's
350 		**  declared static so we can't.  But if we fclose(pwf), which
351 		**  is what endpwent does, it closes it in the parent too and
352 		**  the next getpwnam will be slower.  If you have a weird
353 		**  mailer that chokes on the extra file you should do the
354 		**  endpwent().
355 		**
356 		**  Similar comments apply to log.  However, openlog is
357 		**  clever enough to set the FIOCLEX mode on the file,
358 		**  so it will be closed automatically on the exec.
359 		*/
360 
361 		endpwent();
362 # ifdef LOG
363 		closelog();
364 # endif LOG
365 # endif VFORK
366 		execv(m->m_mailer, pvp);
367 		/* syserr fails because log is closed */
368 		/* syserr("Cannot exec %s", m->m_mailer); */
369 		printf("Cannot exec %s\n", m->m_mailer);
370 		fflush(stdout);
371 		_exit(EX_UNAVAILABLE);
372 	}
373 
374 	/* write out message to mailer */
375 	close(pvect[0]);
376 	signal(SIGPIPE, pipesig);
377 	mfile = fdopen(pvect[1], "w");
378 	if (editfcn == NULL)
379 		editfcn = putmessage;
380 	(*editfcn)(mfile, m);
381 	fclose(mfile);
382 
383 	/*
384 	**  Wait for child to die and report status.
385 	**	We should never get fatal errors (e.g., segmentation
386 	**	violation), so we report those specially.  For other
387 	**	errors, we choose a status message (into statmsg),
388 	**	and if it represents an error, we print it.
389 	*/
390 
391 	while ((i = wait(&st)) > 0 && i != pid)
392 		continue;
393 	if (i < 0)
394 	{
395 		syserr("wait");
396 		return (-1);
397 	}
398 	if ((st & 0377) != 0)
399 	{
400 		syserr("%s: stat %o", pvp[0], st);
401 		ExitStat = EX_UNAVAILABLE;
402 		return (-1);
403 	}
404 	i = (st >> 8) & 0377;
405 	giveresponse(i, TRUE, m);
406 	return (i);
407 }
408 /*
409 **  GIVERESPONSE -- Interpret an error response from a mailer
410 **
411 **	Parameters:
412 **		stat -- the status code from the mailer (high byte
413 **			only; core dumps must have been taken care of
414 **			already).
415 **		force -- if set, force an error message output, even
416 **			if the mailer seems to like to print its own
417 **			messages.
418 **		m -- the mailer descriptor for this mailer.
419 **
420 **	Returns:
421 **		stat.
422 **
423 **	Side Effects:
424 **		Errors may be incremented.
425 **		ExitStat may be set.
426 **
427 **	Called By:
428 **		deliver
429 */
430 
431 giveresponse(stat, force, m)
432 	int stat;
433 	int force;
434 	register struct mailer *m;
435 {
436 	register char *statmsg;
437 	extern char *SysExMsg[];
438 	register int i;
439 	extern int N_SysEx;
440 	extern long MsgSize;
441 	char buf[30];
442 	extern char *sprintf();
443 
444 	i = stat - EX__BASE;
445 	if (i < 0 || i > N_SysEx)
446 		statmsg = NULL;
447 	else
448 		statmsg = SysExMsg[i];
449 	if (stat == 0)
450 		statmsg = "ok";
451 	else
452 	{
453 		Errors++;
454 		if (statmsg == NULL && m->m_badstat != 0)
455 		{
456 			stat = m->m_badstat;
457 			i = stat - EX__BASE;
458 # ifdef DEBUG
459 			if (i < 0 || i >= N_SysEx)
460 				syserr("Bad m_badstat %d", stat);
461 			else
462 # endif DEBUG
463 			statmsg = SysExMsg[i];
464 		}
465 		if (statmsg == NULL)
466 			usrerr("unknown mailer response %d", stat);
467 		else if (force || !bitset(M_QUIET, m->m_flags))
468 			usrerr("%s", statmsg);
469 	}
470 
471 	/*
472 	**  Final cleanup.
473 	**	Log a record of the transaction.  Compute the new
474 	**	ExitStat -- if we already had an error, stick with
475 	**	that.
476 	*/
477 
478 	if (statmsg == NULL)
479 	{
480 		sprintf(buf, "error %d", stat);
481 		statmsg = buf;
482 	}
483 
484 # ifdef LOG
485 	syslog(LOG_INFO, "%s->%s: %ld: %s", From.q_paddr, To, MsgSize, statmsg);
486 # endif LOG
487 	setstat(stat);
488 	return (stat);
489 }
490 /*
491 **  PUTMESSAGE -- output a message to the final mailer.
492 **
493 **	This routine takes care of recreating the header from the
494 **	in-core copy, etc.
495 **
496 **	Parameters:
497 **		fp -- file to output onto.
498 **		m -- a mailer descriptor.
499 **
500 **	Returns:
501 **		none.
502 **
503 **	Side Effects:
504 **		The message is written onto fp.
505 */
506 
507 putmessage(fp, m)
508 	FILE *fp;
509 	struct mailer *m;
510 {
511 	char buf[BUFSIZ];
512 	register int i;
513 	HDR *h;
514 	register char *p;
515 	extern char *arpadate();
516 	bool anyheader = FALSE;
517 	extern char *expand();
518 	extern char *capitalize();
519 
520 	/* output "From" line unless supressed */
521 	if (!bitset(M_NHDR, m->m_flags))
522 		fprintf(fp, "%s\n", FromLine);
523 
524 	/* output all header lines */
525 	for (h = Header; h != NULL; h = h->h_link)
526 	{
527 		if (bitset(H_DELETE, h->h_flags))
528 			continue;
529 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
530 			continue;
531 		if (bitset(H_DEFAULT, h->h_flags))
532 		{
533 			expand(h->h_value, buf, &buf[sizeof buf]);
534 			p = buf;
535 		}
536 		else
537 			p = h->h_value;
538 		if (*p == '\0')
539 			continue;
540 		fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
541 		h->h_flags |= H_USED;
542 		anyheader = TRUE;
543 	}
544 
545 	if (anyheader)
546 		fprintf(fp, "\n");
547 
548 	/* output the body of the message */
549 	while (!ferror(fp) && (i = read(0, buf, BUFSIZ)) > 0)
550 		fwrite(buf, 1, i, fp);
551 
552 	if (ferror(fp))
553 	{
554 		syserr("putmessage: write error");
555 		setstat(EX_IOERR);
556 	}
557 }
558 /*
559 **  PIPESIG -- Handle broken pipe signals
560 **
561 **	This just logs an error.
562 **
563 **	Parameters:
564 **		none
565 **
566 **	Returns:
567 **		none
568 **
569 **	Side Effects:
570 **		logs an error message.
571 */
572 
573 pipesig()
574 {
575 	syserr("Broken pipe");
576 	signal(SIGPIPE, SIG_IGN);
577 }
578 /*
579 **  SENDTO -- Designate a send list.
580 **
581 **	The parameter is a comma-separated list of people to send to.
582 **	This routine arranges to send to all of them.
583 **
584 **	Parameters:
585 **		list -- the send list.
586 **		copyf -- the copy flag; passed to parse.
587 **
588 **	Returns:
589 **		none
590 **
591 **	Side Effects:
592 **		none.
593 */
594 
595 sendto(list, copyf)
596 	char *list;
597 	int copyf;
598 {
599 	register char *p;
600 	register char *q;
601 	register char c;
602 	ADDRESS *a;
603 	extern ADDRESS *parse();
604 	bool more;
605 
606 	/* more keeps track of what the previous delimiter was */
607 	more = TRUE;
608 	for (p = list; more; )
609 	{
610 		/* find the end of this address */
611 		q = p;
612 		while ((c = *p++) != '\0' && c != ',' && c != '\n')
613 			continue;
614 		more = c != '\0';
615 		*--p = '\0';
616 		if (more)
617 			p++;
618 
619 		/* parse the address */
620 		if ((a = parse(q, (ADDRESS *) NULL, copyf)) == NULL)
621 			continue;
622 
623 		/* arrange to send to this person */
624 		recipient(a);
625 	}
626 	To = NULL;
627 }
628 /*
629 **  RECIPIENT -- Designate a message recipient
630 **
631 **	Saves the named person for future mailing.
632 **
633 **	Parameters:
634 **		a -- the (preparsed) address header for the recipient.
635 **
636 **	Returns:
637 **		none.
638 **
639 **	Side Effects:
640 **		none.
641 */
642 
643 recipient(a)
644 	register ADDRESS *a;
645 {
646 	register ADDRESS *q;
647 	register struct mailer *m;
648 	extern bool forward();
649 	extern int errno;
650 	extern bool sameaddr();
651 
652 	To = a->q_paddr;
653 	m = Mailer[a->q_mailer];
654 	errno = 0;
655 # ifdef DEBUG
656 	if (Debug)
657 		printf("recipient(%s)\n", To);
658 # endif DEBUG
659 
660 	/*
661 	**  Do sickly crude mapping for program mailing, etc.
662 	*/
663 
664 	if (a->q_mailer == 0 && a->q_user[0] == '|')
665 	{
666 		a->q_mailer = 1;
667 		m = Mailer[1];
668 		a->q_user++;
669 	}
670 
671 	/*
672 	**  Look up this person in the recipient list.  If they
673 	**  are there already, return, otherwise continue.
674 	**  If the list is empty, just add it.
675 	*/
676 
677 	if (m->m_sendq == NULL)
678 	{
679 		m->m_sendq = a;
680 	}
681 	else
682 	{
683 		ADDRESS *pq;
684 
685 		for (q = m->m_sendq; q != NULL; pq = q, q = q->q_next)
686 		{
687 			if (!ForceMail && sameaddr(q, a, FALSE))
688 			{
689 # ifdef DEBUG
690 				if (Debug)
691 					printf("(%s in sendq)\n", a->q_paddr);
692 # endif DEBUG
693 				return;
694 			}
695 		}
696 
697 		/* add address on list */
698 		q = pq;
699 		q->q_next = a;
700 	}
701 	a->q_next = NULL;
702 
703 	/*
704 	**  See if the user wants hir mail forwarded.
705 	**	`Forward' must do the forwarding recursively.
706 	*/
707 
708 	if (m == Mailer[0] && !NoAlias && forward(a))
709 		setbit(QDONTSEND, a->q_flags);
710 
711 	return;
712 }
713 /*
714 **  MAILFILE -- Send a message to a file.
715 **
716 **	Parameters:
717 **		filename -- the name of the file to send to.
718 **
719 **	Returns:
720 **		The exit code associated with the operation.
721 **
722 **	Side Effects:
723 **		none.
724 **
725 **	Called By:
726 **		deliver
727 */
728 
729 mailfile(filename)
730 	char *filename;
731 {
732 	register FILE *f;
733 
734 	f = fopen(filename, "a");
735 	if (f == NULL)
736 		return (EX_CANTCREAT);
737 
738 	putmessage(f, Mailer[1]);
739 	fputs("\n", f);
740 	fclose(f);
741 	return (EX_OK);
742 }
743