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.13	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 		statmsg = "ok";
449 	else
450 	{
451 		Errors++;
452 		if (statmsg == NULL && m->m_badstat != 0)
453 		{
454 			stat = m->m_badstat;
455 			i = stat - EX__BASE;
456 # ifdef DEBUG
457 			if (i < 0 || i >= N_SysEx)
458 				syserr("Bad m_badstat %d", stat);
459 			else
460 # endif DEBUG
461 			statmsg = SysExMsg[i];
462 		}
463 		if (statmsg == NULL)
464 			usrerr("unknown mailer response %d", stat);
465 		else if (force || !bitset(M_QUIET, m->m_flags))
466 			usrerr("%s", statmsg);
467 	}
468 
469 	/*
470 	**  Final cleanup.
471 	**	Log a record of the transaction.  Compute the new
472 	**	ExitStat -- if we already had an error, stick with
473 	**	that.
474 	*/
475 
476 	if (statmsg == NULL)
477 	{
478 		sprintf(buf, "error %d", stat);
479 		statmsg = buf;
480 	}
481 
482 # ifdef LOG
483 	syslog(LOG_INFO, "%s->%s: %ld: %s", From.q_paddr, To, MsgSize, statmsg);
484 # endif LOG
485 	setstat(stat);
486 	return (stat);
487 }
488 /*
489 **  PUTMESSAGE -- output a message to the final mailer.
490 **
491 **	This routine takes care of recreating the header from the
492 **	in-core copy, etc.
493 **
494 **	Parameters:
495 **		fp -- file to output onto.
496 **		m -- a mailer descriptor.
497 **
498 **	Returns:
499 **		none.
500 **
501 **	Side Effects:
502 **		The message is written onto fp.
503 */
504 
505 putmessage(fp, m)
506 	FILE *fp;
507 	struct mailer *m;
508 {
509 	char buf[BUFSIZ];
510 	register int i;
511 	HDR *h;
512 	register char *p;
513 	extern char *arpadate();
514 	bool anyheader = FALSE;
515 	extern char *expand();
516 	extern char *capitalize();
517 
518 	/* output "From" line unless supressed */
519 	if (!bitset(M_NHDR, m->m_flags))
520 		fprintf(fp, "%s\n", FromLine);
521 
522 	/* output all header lines */
523 	for (h = Header; h != NULL; h = h->h_link)
524 	{
525 		if (bitset(H_DELETE, h->h_flags))
526 			continue;
527 		if (bitset(H_CHECK|H_ACHECK, h->h_flags) && !bitset(h->h_mflags, m->m_flags))
528 			continue;
529 		if (bitset(H_DEFAULT, h->h_flags))
530 		{
531 			expand(h->h_value, buf, &buf[sizeof buf]);
532 			p = buf;
533 		}
534 		else
535 			p = h->h_value;
536 		if (*p == '\0')
537 			continue;
538 		fprintf(fp, "%s: %s\n", capitalize(h->h_field), p);
539 		h->h_flags |= H_USED;
540 		anyheader = TRUE;
541 	}
542 
543 	if (anyheader)
544 		fprintf(fp, "\n");
545 
546 	/* output the body of the message */
547 	rewind(stdin);
548 	while (!ferror(fp) && (i = fread(buf, 1, BUFSIZ, stdin)) > 0)
549 		fwrite(buf, 1, i, fp);
550 
551 	if (ferror(fp))
552 	{
553 		syserr("putmessage: write error");
554 		setstat(EX_IOERR);
555 	}
556 }
557 /*
558 **  PIPESIG -- Handle broken pipe signals
559 **
560 **	This just logs an error.
561 **
562 **	Parameters:
563 **		none
564 **
565 **	Returns:
566 **		none
567 **
568 **	Side Effects:
569 **		logs an error message.
570 */
571 
572 pipesig()
573 {
574 	syserr("Broken pipe");
575 	signal(SIGPIPE, SIG_IGN);
576 }
577 /*
578 **  SENDTO -- Designate a send list.
579 **
580 **	The parameter is a comma-separated list of people to send to.
581 **	This routine arranges to send to all of them.
582 **
583 **	Parameters:
584 **		list -- the send list.
585 **		copyf -- the copy flag; passed to parse.
586 **
587 **	Returns:
588 **		none
589 **
590 **	Side Effects:
591 **		none.
592 */
593 
594 sendto(list, copyf)
595 	char *list;
596 	int copyf;
597 {
598 	register char *p;
599 	register char *q;
600 	register char c;
601 	ADDRESS *a;
602 	extern ADDRESS *parse();
603 	bool more;
604 
605 	/* more keeps track of what the previous delimiter was */
606 	more = TRUE;
607 	for (p = list; more; )
608 	{
609 		/* find the end of this address */
610 		q = p;
611 		while ((c = *p++) != '\0' && c != ',' && c != '\n')
612 			continue;
613 		more = c != '\0';
614 		*--p = '\0';
615 		if (more)
616 			p++;
617 
618 		/* parse the address */
619 		if ((a = parse(q, (ADDRESS *) NULL, copyf)) == NULL)
620 			continue;
621 
622 		/* arrange to send to this person */
623 		recipient(a);
624 	}
625 	To = NULL;
626 }
627 /*
628 **  RECIPIENT -- Designate a message recipient
629 **
630 **	Saves the named person for future mailing.
631 **
632 **	Parameters:
633 **		a -- the (preparsed) address header for the recipient.
634 **
635 **	Returns:
636 **		none.
637 **
638 **	Side Effects:
639 **		none.
640 */
641 
642 recipient(a)
643 	register ADDRESS *a;
644 {
645 	register ADDRESS *q;
646 	register struct mailer *m;
647 	extern bool forward();
648 	extern int errno;
649 	extern bool sameaddr();
650 
651 	To = a->q_paddr;
652 	m = Mailer[a->q_mailer];
653 	errno = 0;
654 # ifdef DEBUG
655 	if (Debug)
656 		printf("recipient(%s)\n", To);
657 # endif DEBUG
658 
659 	/*
660 	**  Do sickly crude mapping for program mailing, etc.
661 	*/
662 
663 	if (a->q_mailer == 0 && a->q_user[0] == '|')
664 	{
665 		a->q_mailer = 1;
666 		m = Mailer[1];
667 		a->q_user++;
668 	}
669 
670 	/*
671 	**  Look up this person in the recipient list.  If they
672 	**  are there already, return, otherwise continue.
673 	**  If the list is empty, just add it.
674 	*/
675 
676 	if (m->m_sendq == NULL)
677 	{
678 		m->m_sendq = a;
679 	}
680 	else
681 	{
682 		ADDRESS *pq;
683 
684 		for (q = m->m_sendq; q != NULL; pq = q, q = q->q_next)
685 		{
686 			if (!ForceMail && sameaddr(q, a, FALSE))
687 			{
688 # ifdef DEBUG
689 				if (Debug)
690 					printf("(%s in sendq)\n", a->q_paddr);
691 # endif DEBUG
692 				return;
693 			}
694 		}
695 
696 		/* add address on list */
697 		q = pq;
698 		q->q_next = a;
699 	}
700 	a->q_next = NULL;
701 
702 	/*
703 	**  See if the user wants hir mail forwarded.
704 	**	`Forward' must do the forwarding recursively.
705 	*/
706 
707 	if (m == Mailer[0] && !NoAlias && forward(a))
708 		setbit(QDONTSEND, a->q_flags);
709 
710 	return;
711 }
712 /*
713 **  MAILFILE -- Send a message to a file.
714 **
715 **	Parameters:
716 **		filename -- the name of the file to send to.
717 **
718 **	Returns:
719 **		The exit code associated with the operation.
720 **
721 **	Side Effects:
722 **		none.
723 **
724 **	Called By:
725 **		deliver
726 */
727 
728 mailfile(filename)
729 	char *filename;
730 {
731 	register FILE *f;
732 
733 	f = fopen(filename, "a");
734 	if (f == NULL)
735 		return (EX_CANTCREAT);
736 
737 	putmessage(f, Mailer[1]);
738 	fputs("\n", f);
739 	fclose(f);
740 	return (EX_OK);
741 }
742