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