xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 58915)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 # include "sendmail.h"
10 
11 #ifndef lint
12 #ifdef QUEUE
13 static char sccsid[] = "@(#)queue.c	6.42 (Berkeley) 04/01/93 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	6.42 (Berkeley) 04/01/93 (without queueing)";
16 #endif
17 #endif /* not lint */
18 
19 # include <sys/stat.h>
20 # include <sys/dir.h>
21 # include <signal.h>
22 # include <errno.h>
23 # include <pwd.h>
24 # ifndef MAXNAMLEN
25 # include <dirent.h>
26 # endif
27 
28 # ifdef QUEUE
29 
30 /*
31 **  Work queue.
32 */
33 
34 struct work
35 {
36 	char		*w_name;	/* name of control file */
37 	long		w_pri;		/* priority of message, see below */
38 	time_t		w_ctime;	/* creation time of message */
39 	struct work	*w_next;	/* next in queue */
40 };
41 
42 typedef struct work	WORK;
43 
44 WORK	*WorkQ;			/* queue of things to be done */
45 /*
46 **  QUEUEUP -- queue a message up for future transmission.
47 **
48 **	Parameters:
49 **		e -- the envelope to queue up.
50 **		queueall -- if TRUE, queue all addresses, rather than
51 **			just those with the QQUEUEUP flag set.
52 **		announce -- if TRUE, tell when you are queueing up.
53 **
54 **	Returns:
55 **		none.
56 **
57 **	Side Effects:
58 **		The current request are saved in a control file.
59 **		The queue file is left locked.
60 */
61 
62 queueup(e, queueall, announce)
63 	register ENVELOPE *e;
64 	bool queueall;
65 	bool announce;
66 {
67 	char *qf;
68 	register FILE *tfp;
69 	register HDR *h;
70 	register ADDRESS *q;
71 	int fd;
72 	int i;
73 	bool newid;
74 	register char *p;
75 	MAILER nullmailer;
76 	ADDRESS *lastctladdr;
77 	char buf[MAXLINE], tf[MAXLINE];
78 	extern char *macvalue();
79 	extern ADDRESS *getctladdr();
80 
81 	/*
82 	**  Create control file.
83 	*/
84 
85 	newid = (e->e_id == NULL);
86 	strcpy(tf, queuename(e, 't'));
87 	tfp = e->e_lockfp;
88 	if (tfp == NULL)
89 		newid = FALSE;
90 	if (newid)
91 	{
92 		tfp = e->e_lockfp;
93 	}
94 	else
95 	{
96 		/* get a locked tf file */
97 		for (i = 100; --i >= 0; )
98 		{
99 			extern bool lockfile();
100 
101 			fd = open(tf, O_CREAT|O_WRONLY|O_EXCL, FileMode);
102 			if (fd < 0)
103 			{
104 				if (errno == EEXIST)
105 					continue;
106 notemp:
107 				syserr("!queueup: cannot create temp file %s", tf);
108 			}
109 
110 			if (lockfile(fd, tf, LOCK_EX|LOCK_NB))
111 				break;
112 
113 			close(fd);
114 			sleep(i);
115 		}
116 		if (fd < 0)
117 			goto notemp;
118 
119 		tfp = fdopen(fd, "w");
120 	}
121 
122 	if (tTd(40, 1))
123 		printf("queueing %s\n", e->e_id);
124 
125 	/*
126 	**  If there is no data file yet, create one.
127 	*/
128 
129 	if (e->e_df == NULL)
130 	{
131 		register FILE *dfp;
132 		extern putbody();
133 
134 		e->e_df = newstr(queuename(e, 'd'));
135 		fd = open(e->e_df, O_WRONLY|O_CREAT, FileMode);
136 		if (fd < 0)
137 			syserr("!queueup: cannot create %s", e->e_df);
138 		dfp = fdopen(fd, "w");
139 		(*e->e_putbody)(dfp, ProgMailer, e);
140 		(void) xfclose(dfp, "queueup dfp", e->e_id);
141 		e->e_putbody = putbody;
142 	}
143 
144 	/*
145 	**  Output future work requests.
146 	**	Priority and creation time should be first, since
147 	**	they are required by orderq.
148 	*/
149 
150 	/* output message priority */
151 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
152 
153 	/* output creation time */
154 	fprintf(tfp, "T%ld\n", e->e_ctime);
155 
156 	/* output name of data file */
157 	fprintf(tfp, "D%s\n", e->e_df);
158 
159 	/* message from envelope, if it exists */
160 	if (e->e_message != NULL)
161 		fprintf(tfp, "M%s\n", e->e_message);
162 
163 	/* send various flag bits through */
164 	p = buf;
165 	if (bitset(EF_WARNING, e->e_flags))
166 		*p++ = 'w';
167 	if (bitset(EF_RESPONSE, e->e_flags))
168 		*p++ = 'r';
169 	*p++ = '\0';
170 	if (buf[0] != '\0')
171 		fprintf(tfp, "F%s\n", buf);
172 
173 	/* $r and $s macro values */
174 	if ((p = macvalue('r', e)) != NULL)
175 		fprintf(tfp, "$r%s\n", p);
176 	if ((p = macvalue('s', e)) != NULL)
177 		fprintf(tfp, "$s%s\n", p);
178 
179 	/* output name of sender */
180 	fprintf(tfp, "S%s\n", e->e_from.q_paddr);
181 
182 	/* output list of error recipients */
183 	lastctladdr = NULL;
184 	for (q = e->e_errorqueue; q != NULL; q = q->q_next)
185 	{
186 		if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
187 		{
188 			ADDRESS *ctladdr;
189 
190 			ctladdr = getctladdr(q);
191 			if (ctladdr != lastctladdr)
192 			{
193 				printctladdr(ctladdr, tfp);
194 				lastctladdr = ctladdr;
195 			}
196 			fprintf(tfp, "E%s\n", q->q_paddr);
197 		}
198 	}
199 
200 	/* output list of recipient addresses */
201 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
202 	{
203 		if (bitset(QQUEUEUP, q->q_flags) ||
204 		    (queueall && !bitset(QDONTSEND|QBADADDR|QSENT, q->q_flags)))
205 		{
206 			ADDRESS *ctladdr;
207 
208 			ctladdr = getctladdr(q);
209 			if (ctladdr != lastctladdr)
210 			{
211 				printctladdr(ctladdr, tfp);
212 				lastctladdr = ctladdr;
213 			}
214 			fprintf(tfp, "R%s\n", q->q_paddr);
215 			if (announce)
216 			{
217 				e->e_to = q->q_paddr;
218 				message("queued");
219 				if (LogLevel > 8)
220 					logdelivery(NULL, NULL, "queued", e);
221 				e->e_to = NULL;
222 			}
223 			if (tTd(40, 1))
224 			{
225 				printf("queueing ");
226 				printaddr(q, FALSE);
227 			}
228 		}
229 	}
230 
231 	/*
232 	**  Output headers for this message.
233 	**	Expand macros completely here.  Queue run will deal with
234 	**	everything as absolute headers.
235 	**		All headers that must be relative to the recipient
236 	**		can be cracked later.
237 	**	We set up a "null mailer" -- i.e., a mailer that will have
238 	**	no effect on the addresses as they are output.
239 	*/
240 
241 	bzero((char *) &nullmailer, sizeof nullmailer);
242 	nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
243 			nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1;
244 	nullmailer.m_eol = "\n";
245 
246 	define('g', "\201f", e);
247 	for (h = e->e_header; h != NULL; h = h->h_link)
248 	{
249 		extern bool bitzerop();
250 
251 		/* don't output null headers */
252 		if (h->h_value == NULL || h->h_value[0] == '\0')
253 			continue;
254 
255 		/* don't output resent headers on non-resent messages */
256 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
257 			continue;
258 
259 		/* output this header */
260 		fprintf(tfp, "H");
261 
262 		/* if conditional, output the set of conditions */
263 		if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags))
264 		{
265 			int j;
266 
267 			(void) putc('?', tfp);
268 			for (j = '\0'; j <= '\177'; j++)
269 				if (bitnset(j, h->h_mflags))
270 					(void) putc(j, tfp);
271 			(void) putc('?', tfp);
272 		}
273 
274 		/* output the header: expand macros, convert addresses */
275 		if (bitset(H_DEFAULT, h->h_flags))
276 		{
277 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
278 			fprintf(tfp, "%s: %s\n", h->h_field, buf);
279 		}
280 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
281 		{
282 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
283 
284 			if (bitset(H_FROM, h->h_flags))
285 				oldstyle = FALSE;
286 
287 			commaize(h, h->h_value, tfp, oldstyle,
288 				 &nullmailer, e);
289 		}
290 		else
291 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
292 	}
293 
294 	/*
295 	**  Clean up.
296 	*/
297 
298 	fflush(tfp);
299 	if (ferror(tfp))
300 	{
301 		if (newid)
302 			syserr("!552 Error writing control file %s", tf);
303 		else
304 			syserr("!452 Error writing control file %s", tf);
305 	}
306 
307 	if (!newid)
308 	{
309 		qf = queuename(e, 'q');
310 		if (rename(tf, qf) < 0)
311 			syserr("cannot rename(%s, %s), df=%s", tf, qf, e->e_df);
312 		if (e->e_lockfp != NULL)
313 			(void) xfclose(e->e_lockfp, "queueup lockfp", e->e_id);
314 		e->e_lockfp = tfp;
315 	}
316 	else
317 		qf = tf;
318 	errno = 0;
319 
320 # ifdef LOG
321 	/* save log info */
322 	if (LogLevel > 79)
323 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
324 # endif /* LOG */
325 	fflush(tfp);
326 	return;
327 }
328 
329 printctladdr(a, tfp)
330 	ADDRESS *a;
331 	FILE *tfp;
332 {
333 	char *u;
334 	struct passwd *pw;
335 	extern struct passwd *getpwuid();
336 
337 	if (a == NULL)
338 	{
339 		fprintf(tfp, "C\n");
340 		return;
341 	}
342 	if (a->q_uid == 0 || (pw = getpwuid(a->q_uid)) == NULL)
343 		u = DefUser;
344 	else
345 		u = pw->pw_name;
346 	fprintf(tfp, "C%s\n", u);
347 }
348 
349 /*
350 **  RUNQUEUE -- run the jobs in the queue.
351 **
352 **	Gets the stuff out of the queue in some presumably logical
353 **	order and processes them.
354 **
355 **	Parameters:
356 **		forkflag -- TRUE if the queue scanning should be done in
357 **			a child process.  We double-fork so it is not our
358 **			child and we don't have to clean up after it.
359 **
360 **	Returns:
361 **		none.
362 **
363 **	Side Effects:
364 **		runs things in the mail queue.
365 */
366 
367 ENVELOPE	QueueEnvelope;		/* the queue run envelope */
368 
369 runqueue(forkflag)
370 	bool forkflag;
371 {
372 	extern bool shouldqueue();
373 	register ENVELOPE *e;
374 	extern ENVELOPE BlankEnvelope;
375 	extern ENVELOPE *newenvelope();
376 
377 	/*
378 	**  If no work will ever be selected, don't even bother reading
379 	**  the queue.
380 	*/
381 
382 	CurrentLA = getla();	/* get load average */
383 
384 	if (shouldqueue(0L, curtime()))
385 	{
386 		if (Verbose)
387 			printf("Skipping queue run -- load average too high\n");
388 		if (forkflag && QueueIntvl != 0)
389 			(void) setevent(QueueIntvl, runqueue, TRUE);
390 		return;
391 	}
392 
393 	/*
394 	**  See if we want to go off and do other useful work.
395 	*/
396 
397 	if (forkflag)
398 	{
399 		int pid;
400 
401 		pid = dofork();
402 		if (pid != 0)
403 		{
404 			extern void reapchild();
405 
406 			/* parent -- pick up intermediate zombie */
407 #ifndef SIGCHLD
408 			(void) waitfor(pid);
409 #else /* SIGCHLD */
410 			(void) signal(SIGCHLD, reapchild);
411 #endif /* SIGCHLD */
412 			if (QueueIntvl != 0)
413 				(void) setevent(QueueIntvl, runqueue, TRUE);
414 			return;
415 		}
416 		/* child -- double fork */
417 #ifndef SIGCHLD
418 		if (fork() != 0)
419 			exit(EX_OK);
420 #else /* SIGCHLD */
421 		(void) signal(SIGCHLD, SIG_DFL);
422 #endif /* SIGCHLD */
423 	}
424 
425 	setproctitle("running queue: %s", QueueDir);
426 
427 # ifdef LOG
428 	if (LogLevel > 69)
429 		syslog(LOG_DEBUG, "runqueue %s, pid=%d, forkflag=%d",
430 			QueueDir, getpid(), forkflag);
431 # endif /* LOG */
432 
433 	/*
434 	**  Release any resources used by the daemon code.
435 	*/
436 
437 # ifdef DAEMON
438 	clrdaemon();
439 # endif /* DAEMON */
440 
441 	/*
442 	**  Create ourselves an envelope
443 	*/
444 
445 	CurEnv = &QueueEnvelope;
446 	e = newenvelope(&QueueEnvelope, CurEnv);
447 	e->e_flags = BlankEnvelope.e_flags;
448 
449 	/*
450 	**  Make sure the alias database is open.
451 	*/
452 
453 	initaliases(AliasFile, FALSE, e);
454 
455 	/*
456 	**  Start making passes through the queue.
457 	**	First, read and sort the entire queue.
458 	**	Then, process the work in that order.
459 	**		But if you take too long, start over.
460 	*/
461 
462 	/* order the existing work requests */
463 	(void) orderq(FALSE);
464 
465 	/* process them once at a time */
466 	while (WorkQ != NULL)
467 	{
468 		WORK *w = WorkQ;
469 		extern bool shouldqueue();
470 
471 		WorkQ = WorkQ->w_next;
472 
473 		/*
474 		**  Ignore jobs that are too expensive for the moment.
475 		*/
476 
477 		if (shouldqueue(w->w_pri, w->w_ctime))
478 		{
479 			if (Verbose)
480 				printf("\nSkipping %s\n", w->w_name + 2);
481 			continue;
482 		}
483 
484 		dowork(w->w_name + 2, ForkQueueRuns, e);
485 		free(w->w_name);
486 		free((char *) w);
487 	}
488 
489 	/* exit without the usual cleanup */
490 	e->e_id = NULL;
491 	finis();
492 }
493 /*
494 **  ORDERQ -- order the work queue.
495 **
496 **	Parameters:
497 **		doall -- if set, include everything in the queue (even
498 **			the jobs that cannot be run because the load
499 **			average is too high).  Otherwise, exclude those
500 **			jobs.
501 **
502 **	Returns:
503 **		The number of request in the queue (not necessarily
504 **		the number of requests in WorkQ however).
505 **
506 **	Side Effects:
507 **		Sets WorkQ to the queue of available work, in order.
508 */
509 
510 # define NEED_P		001
511 # define NEED_T		002
512 # define NEED_R		004
513 # define NEED_S		010
514 
515 orderq(doall)
516 	bool doall;
517 {
518 	register struct direct *d;
519 	register WORK *w;
520 	DIR *f;
521 	register int i;
522 	WORK wlist[QUEUESIZE+1];
523 	int wn = -1;
524 	extern workcmpf();
525 
526 	if (tTd(41, 1))
527 	{
528 		printf("orderq:\n");
529 		if (QueueLimitId != NULL)
530 			printf("\tQueueLimitId = %s\n", QueueLimitId);
531 		if (QueueLimitSender != NULL)
532 			printf("\tQueueLimitSender = %s\n", QueueLimitSender);
533 		if (QueueLimitRecipient != NULL)
534 			printf("\tQueueLimitRecipient = %s\n", QueueLimitRecipient);
535 	}
536 
537 	/* clear out old WorkQ */
538 	for (w = WorkQ; w != NULL; )
539 	{
540 		register WORK *nw = w->w_next;
541 
542 		WorkQ = nw;
543 		free(w->w_name);
544 		free((char *) w);
545 		w = nw;
546 	}
547 
548 	/* open the queue directory */
549 	f = opendir(".");
550 	if (f == NULL)
551 	{
552 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
553 		return (0);
554 	}
555 
556 	/*
557 	**  Read the work directory.
558 	*/
559 
560 	while ((d = readdir(f)) != NULL)
561 	{
562 		FILE *cf;
563 		char lbuf[MAXNAME];
564 		extern bool shouldqueue();
565 		extern bool strcontainedin();
566 
567 		/* is this an interesting entry? */
568 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
569 			continue;
570 
571 		if (QueueLimitId != NULL &&
572 		    !strcontainedin(QueueLimitId, d->d_name))
573 			continue;
574 
575 		/*
576 		**  Check queue name for plausibility.  This handles
577 		**  both old and new type ids.
578 		*/
579 
580 		i = strlen(d->d_name);
581 		if (i != 9 && i != 10)
582 		{
583 			if (Verbose)
584 				printf("orderq: bogus qf name %s\n", d->d_name);
585 #ifdef LOG
586 			if (LogLevel > 3)
587 				syslog(LOG_NOTICE, "orderq: bogus qf name %s",
588 					d->d_name);
589 #endif
590 			if (strlen(d->d_name) >= MAXNAME)
591 				d->d_name[MAXNAME - 1] = '\0';
592 			strcpy(lbuf, d->d_name);
593 			lbuf[0] = 'Q';
594 			(void) rename(d->d_name, lbuf);
595 			continue;
596 		}
597 
598 		/* yes -- open control file (if not too many files) */
599 		if (++wn >= QUEUESIZE)
600 			continue;
601 
602 		cf = fopen(d->d_name, "r");
603 		if (cf == NULL)
604 		{
605 			/* this may be some random person sending hir msgs */
606 			/* syserr("orderq: cannot open %s", cbuf); */
607 			if (tTd(41, 2))
608 				printf("orderq: cannot open %s (%d)\n",
609 					d->d_name, errno);
610 			errno = 0;
611 			wn--;
612 			continue;
613 		}
614 		w = &wlist[wn];
615 		w->w_name = newstr(d->d_name);
616 
617 		/* make sure jobs in creation don't clog queue */
618 		w->w_pri = 0x7fffffff;
619 		w->w_ctime = 0;
620 
621 		/* extract useful information */
622 		i = NEED_P | NEED_T;
623 		if (QueueLimitSender != NULL)
624 			i |= NEED_S;
625 		if (QueueLimitRecipient != NULL)
626 			i |= NEED_R;
627 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
628 		{
629 			extern long atol();
630 			extern bool strcontainedin();
631 
632 			switch (lbuf[0])
633 			{
634 			  case 'P':
635 				w->w_pri = atol(&lbuf[1]);
636 				i &= ~NEED_P;
637 				break;
638 
639 			  case 'T':
640 				w->w_ctime = atol(&lbuf[1]);
641 				i &= ~NEED_T;
642 				break;
643 
644 			  case 'R':
645 				if (QueueLimitRecipient != NULL &&
646 				    strcontainedin(QueueLimitRecipient, &lbuf[1]))
647 					i &= ~NEED_R;
648 				break;
649 
650 			  case 'S':
651 				if (QueueLimitSender != NULL &&
652 				    strcontainedin(QueueLimitSender, &lbuf[1]))
653 					i &= ~NEED_S;
654 				break;
655 			}
656 		}
657 		(void) fclose(cf);
658 
659 		if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
660 		    bitset(NEED_R|NEED_S, i))
661 		{
662 			/* don't even bother sorting this job in */
663 			wn--;
664 		}
665 	}
666 	(void) closedir(f);
667 	wn++;
668 
669 	/*
670 	**  Sort the work directory.
671 	*/
672 
673 	qsort((char *) wlist, min(wn, QUEUESIZE), sizeof *wlist, workcmpf);
674 
675 	/*
676 	**  Convert the work list into canonical form.
677 	**	Should be turning it into a list of envelopes here perhaps.
678 	*/
679 
680 	WorkQ = NULL;
681 	for (i = min(wn, QUEUESIZE); --i >= 0; )
682 	{
683 		w = (WORK *) xalloc(sizeof *w);
684 		w->w_name = wlist[i].w_name;
685 		w->w_pri = wlist[i].w_pri;
686 		w->w_ctime = wlist[i].w_ctime;
687 		w->w_next = WorkQ;
688 		WorkQ = w;
689 	}
690 
691 	if (tTd(40, 1))
692 	{
693 		for (w = WorkQ; w != NULL; w = w->w_next)
694 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
695 	}
696 
697 	return (wn);
698 }
699 /*
700 **  WORKCMPF -- compare function for ordering work.
701 **
702 **	Parameters:
703 **		a -- the first argument.
704 **		b -- the second argument.
705 **
706 **	Returns:
707 **		-1 if a < b
708 **		 0 if a == b
709 **		+1 if a > b
710 **
711 **	Side Effects:
712 **		none.
713 */
714 
715 workcmpf(a, b)
716 	register WORK *a;
717 	register WORK *b;
718 {
719 	long pa = a->w_pri;
720 	long pb = b->w_pri;
721 
722 	if (pa == pb)
723 		return (0);
724 	else if (pa > pb)
725 		return (1);
726 	else
727 		return (-1);
728 }
729 /*
730 **  DOWORK -- do a work request.
731 **
732 **	Parameters:
733 **		id -- the ID of the job to run.
734 **		forkflag -- if set, run this in background.
735 **		e - the envelope in which to run it.
736 **
737 **	Returns:
738 **		none.
739 **
740 **	Side Effects:
741 **		The work request is satisfied if possible.
742 */
743 
744 dowork(id, forkflag, e)
745 	char *id;
746 	bool forkflag;
747 	register ENVELOPE *e;
748 {
749 	register int i;
750 	extern bool readqf();
751 
752 	if (tTd(40, 1))
753 		printf("dowork(%s)\n", id);
754 
755 	/*
756 	**  Fork for work.
757 	*/
758 
759 	if (forkflag)
760 	{
761 		i = fork();
762 		if (i < 0)
763 		{
764 			syserr("dowork: cannot fork");
765 			return;
766 		}
767 	}
768 	else
769 	{
770 		i = 0;
771 	}
772 
773 	if (i == 0)
774 	{
775 		/*
776 		**  CHILD
777 		**	Lock the control file to avoid duplicate deliveries.
778 		**		Then run the file as though we had just read it.
779 		**	We save an idea of the temporary name so we
780 		**		can recover on interrupt.
781 		*/
782 
783 		/* set basic modes, etc. */
784 		(void) alarm(0);
785 		clearenvelope(e, FALSE);
786 		e->e_flags |= EF_QUEUERUN;
787 		e->e_errormode = EM_MAIL;
788 		e->e_id = id;
789 # ifdef LOG
790 		if (LogLevel > 76)
791 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
792 			       getpid());
793 # endif /* LOG */
794 
795 		/* don't use the headers from sendmail.cf... */
796 		e->e_header = NULL;
797 
798 		/* read the queue control file -- return if locked */
799 		if (!readqf(e))
800 		{
801 			if (tTd(40, 4))
802 				printf("readqf(%s) failed\n", e->e_id);
803 			if (forkflag)
804 				exit(EX_OK);
805 			else
806 				return;
807 		}
808 
809 		e->e_flags |= EF_INQUEUE;
810 		eatheader(e);
811 
812 		/* do the delivery */
813 		sendall(e, SM_DELIVER);
814 
815 		/* finish up and exit */
816 		if (forkflag)
817 			finis();
818 		else
819 			dropenvelope(e);
820 	}
821 	else
822 	{
823 		/*
824 		**  Parent -- pick up results.
825 		*/
826 
827 		errno = 0;
828 		(void) waitfor(i);
829 	}
830 }
831 /*
832 **  READQF -- read queue file and set up environment.
833 **
834 **	Parameters:
835 **		e -- the envelope of the job to run.
836 **
837 **	Returns:
838 **		TRUE if it successfully read the queue file.
839 **		FALSE otherwise.
840 **
841 **	Side Effects:
842 **		The queue file is returned locked.
843 */
844 
845 bool
846 readqf(e)
847 	register ENVELOPE *e;
848 {
849 	register FILE *qfp;
850 	ADDRESS *ctladdr;
851 	struct stat st;
852 	char *bp;
853 	char qf[20];
854 	char buf[MAXLINE];
855 	extern char *fgetfolded();
856 	extern long atol();
857 	extern ADDRESS *setctluser();
858 	extern bool lockfile();
859 
860 	/*
861 	**  Read and process the file.
862 	*/
863 
864 	strcpy(qf, queuename(e, 'q'));
865 	qfp = fopen(qf, "r+");
866 	if (qfp == NULL)
867 	{
868 		if (tTd(40, 8))
869 			printf("readqf(%s): fopen failure (%s)\n",
870 				qf, errstring(errno));
871 		if (errno != ENOENT)
872 			syserr("readqf: no control file %s", qf);
873 		return FALSE;
874 	}
875 
876 	/*
877 	**  Check the queue file for plausibility to avoid attacks.
878 	*/
879 
880 	if (fstat(fileno(qfp), &st) < 0)
881 	{
882 		/* must have been being processed by someone else */
883 		if (tTd(40, 8))
884 			printf("readqf(%s): fstat failure (%s)\n",
885 				qf, errstring(errno));
886 		fclose(qfp);
887 		return FALSE;
888 	}
889 
890 	if (st.st_uid != geteuid() || (st.st_mode & 07777) != FileMode)
891 	{
892 # ifdef LOG
893 		if (LogLevel > 0)
894 		{
895 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
896 				e->e_id, st.st_uid, st.st_mode);
897 		}
898 # endif /* LOG */
899 		if (tTd(40, 8))
900 			printf("readqf(%s): bogus file\n", qf);
901 		fclose(qfp);
902 		return FALSE;
903 	}
904 
905 	if (!lockfile(fileno(qfp), qf, LOCK_EX|LOCK_NB))
906 	{
907 		/* being processed by another queuer */
908 		if (tTd(40, 8))
909 			printf("readqf(%s): locked\n", qf);
910 		if (Verbose)
911 			printf("%s: locked\n", e->e_id);
912 # ifdef LOG
913 		if (LogLevel > 19)
914 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
915 # endif /* LOG */
916 		(void) fclose(qfp);
917 		return FALSE;
918 	}
919 
920 	/* save this lock */
921 	e->e_lockfp = qfp;
922 
923 	/* do basic system initialization */
924 	initsys(e);
925 
926 	FileName = qf;
927 	LineNumber = 0;
928 	if (Verbose)
929 		printf("\nRunning %s\n", e->e_id);
930 	ctladdr = NULL;
931 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
932 	{
933 		register char *p;
934 		struct stat st;
935 
936 		if (tTd(40, 4))
937 			printf("+++++ %s\n", bp);
938 		switch (bp[0])
939 		{
940 		  case 'C':		/* specify controlling user */
941 			ctladdr = setctluser(&bp[1]);
942 			break;
943 
944 		  case 'R':		/* specify recipient */
945 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
946 			break;
947 
948 		  case 'E':		/* specify error recipient */
949 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
950 			break;
951 
952 		  case 'H':		/* header */
953 			(void) chompheader(&bp[1], FALSE, e);
954 			break;
955 
956 		  case 'M':		/* message */
957 			e->e_message = newstr(&bp[1]);
958 			break;
959 
960 		  case 'S':		/* sender */
961 			setsender(newstr(&bp[1]), e, NULL, TRUE);
962 			break;
963 
964 		  case 'D':		/* data file name */
965 			e->e_df = newstr(&bp[1]);
966 			e->e_dfp = fopen(e->e_df, "r");
967 			if (e->e_dfp == NULL)
968 			{
969 				syserr("readqf: cannot open %s", e->e_df);
970 				e->e_msgsize = -1;
971 			}
972 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
973 				e->e_msgsize = st.st_size;
974 			break;
975 
976 		  case 'T':		/* init time */
977 			e->e_ctime = atol(&bp[1]);
978 			break;
979 
980 		  case 'P':		/* message priority */
981 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
982 			break;
983 
984 		  case 'F':		/* flag bits */
985 			for (p = &bp[1]; *p != '\0'; p++)
986 			{
987 				switch (*p)
988 				{
989 				  case 'w':	/* warning sent */
990 					e->e_flags |= EF_WARNING;
991 					break;
992 
993 				  case 'r':	/* response */
994 					e->e_flags |= EF_RESPONSE;
995 					break;
996 				}
997 			}
998 			break;
999 
1000 		  case '$':		/* define macro */
1001 			define(bp[1], newstr(&bp[2]), e);
1002 			break;
1003 
1004 		  case '\0':		/* blank line; ignore */
1005 			break;
1006 
1007 		  default:
1008 			syserr("readqf(%s:%d): bad line \"%s\"", e->e_id,
1009 				LineNumber, bp);
1010 			break;
1011 		}
1012 
1013 		if (bp != buf)
1014 			free(bp);
1015 	}
1016 
1017 	FileName = NULL;
1018 
1019 	/*
1020 	**  If we haven't read any lines, this queue file is empty.
1021 	**  Arrange to remove it without referencing any null pointers.
1022 	*/
1023 
1024 	if (LineNumber == 0)
1025 	{
1026 		errno = 0;
1027 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
1028 	}
1029 	return TRUE;
1030 }
1031 /*
1032 **  PRINTQUEUE -- print out a representation of the mail queue
1033 **
1034 **	Parameters:
1035 **		none.
1036 **
1037 **	Returns:
1038 **		none.
1039 **
1040 **	Side Effects:
1041 **		Prints a listing of the mail queue on the standard output.
1042 */
1043 
1044 printqueue()
1045 {
1046 	register WORK *w;
1047 	FILE *f;
1048 	int nrequests;
1049 	char buf[MAXLINE];
1050 
1051 	/*
1052 	**  Check for permission to print the queue
1053 	*/
1054 
1055 	if (bitset(PRIV_RESTRMAILQ, PrivacyFlags) && getuid() != 0)
1056 	{
1057 		struct stat st;
1058 # ifdef NGROUPS
1059 		int n;
1060 		int gidset[NGROUPS];
1061 # endif
1062 
1063 		if (stat(QueueDir, &st) < 0)
1064 		{
1065 			syserr("Cannot stat %s", QueueDir);
1066 			return;
1067 		}
1068 # ifdef NGROUPS
1069 		n = getgroups(NGROUPS, gidset);
1070 		while (--n >= 0)
1071 		{
1072 			if (gidset[n] == st.st_gid)
1073 				break;
1074 		}
1075 		if (n < 0)
1076 # else
1077 		if (getgid() != st.st_gid)
1078 # endif
1079 		{
1080 			usrerr("510 You are not permitted to see the queue");
1081 			setstat(EX_NOPERM);
1082 			return;
1083 		}
1084 	}
1085 
1086 	/*
1087 	**  Read and order the queue.
1088 	*/
1089 
1090 	nrequests = orderq(TRUE);
1091 
1092 	/*
1093 	**  Print the work list that we have read.
1094 	*/
1095 
1096 	/* first see if there is anything */
1097 	if (nrequests <= 0)
1098 	{
1099 		printf("Mail queue is empty\n");
1100 		return;
1101 	}
1102 
1103 	CurrentLA = getla();	/* get load average */
1104 
1105 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1106 	if (nrequests > QUEUESIZE)
1107 		printf(", only %d printed", QUEUESIZE);
1108 	if (Verbose)
1109 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1110 	else
1111 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1112 	for (w = WorkQ; w != NULL; w = w->w_next)
1113 	{
1114 		struct stat st;
1115 		auto time_t submittime = 0;
1116 		long dfsize = -1;
1117 		int flags = 0;
1118 		char message[MAXLINE];
1119 		extern bool shouldqueue();
1120 		extern bool lockfile();
1121 
1122 		f = fopen(w->w_name, "r");
1123 		if (f == NULL)
1124 		{
1125 			errno = 0;
1126 			continue;
1127 		}
1128 		printf("%8s", w->w_name + 2);
1129 		if (!lockfile(fileno(f), w->w_name, LOCK_SH|LOCK_NB))
1130 			printf("*");
1131 		else if (shouldqueue(w->w_pri, w->w_ctime))
1132 			printf("X");
1133 		else
1134 			printf(" ");
1135 		errno = 0;
1136 
1137 		message[0] = '\0';
1138 		while (fgets(buf, sizeof buf, f) != NULL)
1139 		{
1140 			register int i;
1141 			register char *p;
1142 
1143 			fixcrlf(buf, TRUE);
1144 			switch (buf[0])
1145 			{
1146 			  case 'M':	/* error message */
1147 				if ((i = strlen(&buf[1])) >= sizeof message)
1148 					i = sizeof message - 1;
1149 				bcopy(&buf[1], message, i);
1150 				message[i] = '\0';
1151 				break;
1152 
1153 			  case 'S':	/* sender name */
1154 				if (Verbose)
1155 					printf("%8ld %10ld%c%.12s %.38s",
1156 					    dfsize,
1157 					    w->w_pri,
1158 					    bitset(EF_WARNING, flags) ? '+' : ' ',
1159 					    ctime(&submittime) + 4,
1160 					    &buf[1]);
1161 				else
1162 					printf("%8ld %.16s %.45s", dfsize,
1163 					    ctime(&submittime), &buf[1]);
1164 				if (message[0] != '\0')
1165 					printf("\n\t\t (%.60s)", message);
1166 				break;
1167 
1168 			  case 'C':	/* controlling user */
1169 				if (Verbose)
1170 					printf("\n\t\t\t\t      (---%.34s---)",
1171 						&buf[1]);
1172 				break;
1173 
1174 			  case 'R':	/* recipient name */
1175 				if (Verbose)
1176 					printf("\n\t\t\t\t\t  %.38s", &buf[1]);
1177 				else
1178 					printf("\n\t\t\t\t   %.45s", &buf[1]);
1179 				break;
1180 
1181 			  case 'T':	/* creation time */
1182 				submittime = atol(&buf[1]);
1183 				break;
1184 
1185 			  case 'D':	/* data file name */
1186 				if (stat(&buf[1], &st) >= 0)
1187 					dfsize = st.st_size;
1188 				break;
1189 
1190 			  case 'F':	/* flag bits */
1191 				for (p = &buf[1]; *p != '\0'; p++)
1192 				{
1193 					switch (*p)
1194 					{
1195 					  case 'w':
1196 						flags |= EF_WARNING;
1197 						break;
1198 					}
1199 				}
1200 			}
1201 		}
1202 		if (submittime == (time_t) 0)
1203 			printf(" (no control file)");
1204 		printf("\n");
1205 		(void) fclose(f);
1206 	}
1207 }
1208 
1209 # endif /* QUEUE */
1210 /*
1211 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1212 **
1213 **	Assigns an id code if one does not already exist.
1214 **	This code is very careful to avoid trashing existing files
1215 **	under any circumstances.
1216 **
1217 **	Parameters:
1218 **		e -- envelope to build it in/from.
1219 **		type -- the file type, used as the first character
1220 **			of the file name.
1221 **
1222 **	Returns:
1223 **		a pointer to the new file name (in a static buffer).
1224 **
1225 **	Side Effects:
1226 **		If no id code is already assigned, queuename will
1227 **		assign an id code, create a qf file, and leave a
1228 **		locked, open-for-write file pointer in the envelope.
1229 */
1230 
1231 char *
1232 queuename(e, type)
1233 	register ENVELOPE *e;
1234 	char type;
1235 {
1236 	static int pid = -1;
1237 	static char c0;
1238 	static char c1;
1239 	static char c2;
1240 	time_t now;
1241 	struct tm *tm;
1242 	static char buf[MAXNAME];
1243 	extern bool lockfile();
1244 
1245 	if (e->e_id == NULL)
1246 	{
1247 		char qf[20];
1248 
1249 		/* find a unique id */
1250 		if (pid != getpid())
1251 		{
1252 			/* new process -- start back at "AA" */
1253 			pid = getpid();
1254 			now = curtime();
1255 			tm = localtime(&now);
1256 			c0 = 'A' + tm->tm_hour;
1257 			c1 = 'A';
1258 			c2 = 'A' - 1;
1259 		}
1260 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
1261 
1262 		while (c1 < '~' || c2 < 'Z')
1263 		{
1264 			int i;
1265 
1266 			if (c2 >= 'Z')
1267 			{
1268 				c1++;
1269 				c2 = 'A' - 1;
1270 			}
1271 			qf[3] = c1;
1272 			qf[4] = ++c2;
1273 			if (tTd(7, 20))
1274 				printf("queuename: trying \"%s\"\n", qf);
1275 
1276 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1277 			if (i < 0)
1278 			{
1279 				if (errno == EEXIST)
1280 					continue;
1281 				syserr("queuename: Cannot create \"%s\" in \"%s\"",
1282 					qf, QueueDir);
1283 				exit(EX_UNAVAILABLE);
1284 			}
1285 			if (lockfile(i, qf, LOCK_EX|LOCK_NB))
1286 			{
1287 				e->e_lockfp = fdopen(i, "w");
1288 				break;
1289 			}
1290 
1291 			/* a reader got the file; abandon it and try again */
1292 			(void) close(i);
1293 		}
1294 		if (c1 >= '~' && c2 >= 'Z')
1295 		{
1296 			syserr("queuename: Cannot create \"%s\" in \"%s\"",
1297 				qf, QueueDir);
1298 			exit(EX_OSERR);
1299 		}
1300 		e->e_id = newstr(&qf[2]);
1301 		define('i', e->e_id, e);
1302 		if (tTd(7, 1))
1303 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1304 # ifdef LOG
1305 		if (LogLevel > 93)
1306 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1307 # endif /* LOG */
1308 	}
1309 
1310 	if (type == '\0')
1311 		return (NULL);
1312 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1313 	if (tTd(7, 2))
1314 		printf("queuename: %s\n", buf);
1315 	return (buf);
1316 }
1317 /*
1318 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1319 **
1320 **	Parameters:
1321 **		e -- the envelope to unlock.
1322 **
1323 **	Returns:
1324 **		none
1325 **
1326 **	Side Effects:
1327 **		unlocks the queue for `e'.
1328 */
1329 
1330 unlockqueue(e)
1331 	ENVELOPE *e;
1332 {
1333 	if (tTd(51, 4))
1334 		printf("unlockqueue(%s)\n", e->e_id);
1335 
1336 	/* if there is a lock file in the envelope, close it */
1337 	if (e->e_lockfp != NULL)
1338 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
1339 	e->e_lockfp = NULL;
1340 
1341 	/* don't create a queue id if we don't already have one */
1342 	if (e->e_id == NULL)
1343 		return;
1344 
1345 	/* remove the transcript */
1346 # ifdef LOG
1347 	if (LogLevel > 87)
1348 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1349 # endif /* LOG */
1350 	if (!tTd(51, 104))
1351 		xunlink(queuename(e, 'x'));
1352 
1353 }
1354 /*
1355 **  SETCTLUSER -- create a controlling address
1356 **
1357 **	Create a fake "address" given only a local login name; this is
1358 **	used as a "controlling user" for future recipient addresses.
1359 **
1360 **	Parameters:
1361 **		user -- the user name of the controlling user.
1362 **
1363 **	Returns:
1364 **		An address descriptor for the controlling user.
1365 **
1366 **	Side Effects:
1367 **		none.
1368 */
1369 
1370 ADDRESS *
1371 setctluser(user)
1372 	char *user;
1373 {
1374 	register ADDRESS *a;
1375 	struct passwd *pw;
1376 
1377 	/*
1378 	**  See if this clears our concept of controlling user.
1379 	*/
1380 
1381 	if (user == NULL || *user == '\0')
1382 		user = DefUser;
1383 
1384 	/*
1385 	**  Set up addr fields for controlling user.
1386 	*/
1387 
1388 	a = (ADDRESS *) xalloc(sizeof *a);
1389 	bzero((char *) a, sizeof *a);
1390 	if ((pw = getpwnam(user)) != NULL)
1391 	{
1392 		a->q_home = newstr(pw->pw_dir);
1393 		a->q_uid = pw->pw_uid;
1394 		a->q_gid = pw->pw_gid;
1395 		a->q_user = newstr(user);
1396 	}
1397 	else
1398 	{
1399 		a->q_uid = DefUid;
1400 		a->q_gid = DefGid;
1401 		a->q_user = newstr(DefUser);
1402 	}
1403 
1404 	a->q_flags |= QGOODUID|QPRIMARY;	/* flag as a "ctladdr"  */
1405 	a->q_mailer = LocalMailer;
1406 	return a;
1407 }
1408