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