xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 58801)
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.39 (Berkeley) 03/25/93 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	6.39 (Berkeley) 03/25/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 
470 		WorkQ = WorkQ->w_next;
471 		dowork(w, e);
472 		free(w->w_name);
473 		free((char *) w);
474 	}
475 
476 	/* exit without the usual cleanup */
477 	e->e_id = NULL;
478 	finis();
479 }
480 /*
481 **  ORDERQ -- order the work queue.
482 **
483 **	Parameters:
484 **		doall -- if set, include everything in the queue (even
485 **			the jobs that cannot be run because the load
486 **			average is too high).  Otherwise, exclude those
487 **			jobs.
488 **
489 **	Returns:
490 **		The number of request in the queue (not necessarily
491 **		the number of requests in WorkQ however).
492 **
493 **	Side Effects:
494 **		Sets WorkQ to the queue of available work, in order.
495 */
496 
497 # define NEED_P		001
498 # define NEED_T		002
499 # define NEED_R		004
500 # define NEED_S		010
501 
502 orderq(doall)
503 	bool doall;
504 {
505 	register struct direct *d;
506 	register WORK *w;
507 	DIR *f;
508 	register int i;
509 	WORK wlist[QUEUESIZE+1];
510 	int wn = -1;
511 	extern workcmpf();
512 
513 	if (tTd(41, 1))
514 	{
515 		printf("orderq:\n");
516 		if (QueueLimitId != NULL)
517 			printf("\tQueueLimitId = %s\n", QueueLimitId);
518 		if (QueueLimitSender != NULL)
519 			printf("\tQueueLimitSender = %s\n", QueueLimitSender);
520 		if (QueueLimitRecipient != NULL)
521 			printf("\tQueueLimitRecipient = %s\n", QueueLimitRecipient);
522 	}
523 
524 	/* clear out old WorkQ */
525 	for (w = WorkQ; w != NULL; )
526 	{
527 		register WORK *nw = w->w_next;
528 
529 		WorkQ = nw;
530 		free(w->w_name);
531 		free((char *) w);
532 		w = nw;
533 	}
534 
535 	/* open the queue directory */
536 	f = opendir(".");
537 	if (f == NULL)
538 	{
539 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
540 		return (0);
541 	}
542 
543 	/*
544 	**  Read the work directory.
545 	*/
546 
547 	while ((d = readdir(f)) != NULL)
548 	{
549 		FILE *cf;
550 		char lbuf[MAXNAME];
551 		extern bool shouldqueue();
552 		extern bool strcontainedin();
553 
554 		/* is this an interesting entry? */
555 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
556 			continue;
557 
558 		if (QueueLimitId != NULL &&
559 		    !strcontainedin(QueueLimitId, d->d_name))
560 			continue;
561 
562 		/*
563 		**  Check queue name for plausibility.  This handles
564 		**  both old and new type ids.
565 		*/
566 
567 		i = strlen(d->d_name);
568 		if (i != 9 && i != 10)
569 		{
570 			if (Verbose)
571 				printf("orderq: bogus qf name %s\n", d->d_name);
572 #ifdef LOG
573 			if (LogLevel > 3)
574 				syslog(LOG_NOTICE, "orderq: bogus qf name %s",
575 					d->d_name);
576 #endif
577 			if (strlen(d->d_name) >= MAXNAME)
578 				d->d_name[MAXNAME - 1] = '\0';
579 			strcpy(lbuf, d->d_name);
580 			lbuf[0] = 'Q';
581 			(void) rename(d->d_name, lbuf);
582 			continue;
583 		}
584 
585 		/* yes -- open control file (if not too many files) */
586 		if (++wn >= QUEUESIZE)
587 			continue;
588 
589 		cf = fopen(d->d_name, "r");
590 		if (cf == NULL)
591 		{
592 			/* this may be some random person sending hir msgs */
593 			/* syserr("orderq: cannot open %s", cbuf); */
594 			if (tTd(41, 2))
595 				printf("orderq: cannot open %s (%d)\n",
596 					d->d_name, errno);
597 			errno = 0;
598 			wn--;
599 			continue;
600 		}
601 		w = &wlist[wn];
602 		w->w_name = newstr(d->d_name);
603 
604 		/* make sure jobs in creation don't clog queue */
605 		w->w_pri = 0x7fffffff;
606 		w->w_ctime = 0;
607 
608 		/* extract useful information */
609 		i = NEED_P | NEED_T;
610 		if (QueueLimitSender != NULL)
611 			i |= NEED_S;
612 		if (QueueLimitRecipient != NULL)
613 			i |= NEED_R;
614 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
615 		{
616 			extern long atol();
617 			extern bool strcontainedin();
618 
619 			switch (lbuf[0])
620 			{
621 			  case 'P':
622 				w->w_pri = atol(&lbuf[1]);
623 				i &= ~NEED_P;
624 				break;
625 
626 			  case 'T':
627 				w->w_ctime = atol(&lbuf[1]);
628 				i &= ~NEED_T;
629 				break;
630 
631 			  case 'R':
632 				if (QueueLimitRecipient != NULL &&
633 				    strcontainedin(QueueLimitRecipient, &lbuf[1]))
634 					i &= ~NEED_R;
635 				break;
636 
637 			  case 'S':
638 				if (QueueLimitSender != NULL &&
639 				    strcontainedin(QueueLimitSender, &lbuf[1]))
640 					i &= ~NEED_S;
641 				break;
642 			}
643 		}
644 		(void) fclose(cf);
645 
646 		if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
647 		    bitset(NEED_R|NEED_S, i))
648 		{
649 			/* don't even bother sorting this job in */
650 			wn--;
651 		}
652 	}
653 	(void) closedir(f);
654 	wn++;
655 
656 	/*
657 	**  Sort the work directory.
658 	*/
659 
660 	qsort((char *) wlist, min(wn, QUEUESIZE), sizeof *wlist, workcmpf);
661 
662 	/*
663 	**  Convert the work list into canonical form.
664 	**	Should be turning it into a list of envelopes here perhaps.
665 	*/
666 
667 	WorkQ = NULL;
668 	for (i = min(wn, QUEUESIZE); --i >= 0; )
669 	{
670 		w = (WORK *) xalloc(sizeof *w);
671 		w->w_name = wlist[i].w_name;
672 		w->w_pri = wlist[i].w_pri;
673 		w->w_ctime = wlist[i].w_ctime;
674 		w->w_next = WorkQ;
675 		WorkQ = w;
676 	}
677 
678 	if (tTd(40, 1))
679 	{
680 		for (w = WorkQ; w != NULL; w = w->w_next)
681 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
682 	}
683 
684 	return (wn);
685 }
686 /*
687 **  WORKCMPF -- compare function for ordering work.
688 **
689 **	Parameters:
690 **		a -- the first argument.
691 **		b -- the second argument.
692 **
693 **	Returns:
694 **		-1 if a < b
695 **		 0 if a == b
696 **		+1 if a > b
697 **
698 **	Side Effects:
699 **		none.
700 */
701 
702 workcmpf(a, b)
703 	register WORK *a;
704 	register WORK *b;
705 {
706 	long pa = a->w_pri;
707 	long pb = b->w_pri;
708 
709 	if (pa == pb)
710 		return (0);
711 	else if (pa > pb)
712 		return (1);
713 	else
714 		return (-1);
715 }
716 /*
717 **  DOWORK -- do a work request.
718 **
719 **	Parameters:
720 **		w -- the work request to be satisfied.
721 **
722 **	Returns:
723 **		none.
724 **
725 **	Side Effects:
726 **		The work request is satisfied if possible.
727 */
728 
729 dowork(w, e)
730 	register WORK *w;
731 	register ENVELOPE *e;
732 {
733 	register int i;
734 	extern bool shouldqueue();
735 	extern bool readqf();
736 
737 	if (tTd(40, 1))
738 		printf("dowork: %s pri %ld\n", w->w_name, w->w_pri);
739 
740 	/*
741 	**  Ignore jobs that are too expensive for the moment.
742 	*/
743 
744 	if (shouldqueue(w->w_pri, w->w_ctime))
745 	{
746 		if (Verbose)
747 			printf("\nSkipping %s\n", w->w_name + 2);
748 		return;
749 	}
750 
751 	/*
752 	**  Fork for work.
753 	*/
754 
755 	if (ForkQueueRuns)
756 	{
757 		i = fork();
758 		if (i < 0)
759 		{
760 			syserr("dowork: cannot fork");
761 			return;
762 		}
763 	}
764 	else
765 	{
766 		i = 0;
767 	}
768 
769 	if (i == 0)
770 	{
771 		/*
772 		**  CHILD
773 		**	Lock the control file to avoid duplicate deliveries.
774 		**		Then run the file as though we had just read it.
775 		**	We save an idea of the temporary name so we
776 		**		can recover on interrupt.
777 		*/
778 
779 		/* set basic modes, etc. */
780 		(void) alarm(0);
781 		clearenvelope(e, FALSE);
782 		e->e_flags |= EF_QUEUERUN;
783 		e->e_errormode = EM_MAIL;
784 		e->e_id = &w->w_name[2];
785 # ifdef LOG
786 		if (LogLevel > 76)
787 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
788 			       getpid());
789 # endif /* LOG */
790 
791 		/* don't use the headers from sendmail.cf... */
792 		e->e_header = NULL;
793 
794 		/* read the queue control file -- return if locked */
795 		if (!readqf(e))
796 		{
797 			if (ForkQueueRuns)
798 				exit(EX_OK);
799 			else
800 				return;
801 		}
802 
803 		e->e_flags |= EF_INQUEUE;
804 		eatheader(e);
805 
806 		/* do the delivery */
807 		if (!bitset(EF_FATALERRS, e->e_flags))
808 			sendall(e, SM_DELIVER);
809 
810 		/* finish up and exit */
811 		if (ForkQueueRuns)
812 			finis();
813 		else
814 			dropenvelope(e);
815 	}
816 	else
817 	{
818 		/*
819 		**  Parent -- pick up results.
820 		*/
821 
822 		errno = 0;
823 		(void) waitfor(i);
824 	}
825 }
826 /*
827 **  READQF -- read queue file and set up environment.
828 **
829 **	Parameters:
830 **		e -- the envelope of the job to run.
831 **
832 **	Returns:
833 **		TRUE if it successfully read the queue file.
834 **		FALSE otherwise.
835 **
836 **	Side Effects:
837 **		The queue file is returned locked.
838 */
839 
840 bool
841 readqf(e)
842 	register ENVELOPE *e;
843 {
844 	char *qf;
845 	register FILE *qfp;
846 	ADDRESS *ctladdr;
847 	struct stat st;
848 	char *bp;
849 	char buf[MAXLINE];
850 	extern char *fgetfolded();
851 	extern long atol();
852 	extern ADDRESS *setctluser();
853 	extern bool lockfile();
854 
855 	/*
856 	**  Read and process the file.
857 	*/
858 
859 	qf = queuename(e, 'q');
860 	qfp = fopen(qf, "r+");
861 	if (qfp == NULL)
862 	{
863 		if (errno != ENOENT)
864 			syserr("readqf: no control file %s", qf);
865 		return FALSE;
866 	}
867 
868 	/*
869 	**  Check the queue file for plausibility to avoid attacks.
870 	*/
871 
872 	if (fstat(fileno(qfp), &st) < 0)
873 	{
874 		/* must have been being processed by someone else */
875 		fclose(qfp);
876 		return FALSE;
877 	}
878 
879 	if (st.st_uid != geteuid() || (st.st_mode & 07777) != FileMode)
880 	{
881 # ifdef LOG
882 		if (LogLevel > 0)
883 		{
884 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
885 				e->e_id, st.st_uid, st.st_mode);
886 		}
887 # endif /* LOG */
888 		fclose(qfp);
889 		return FALSE;
890 	}
891 
892 	if (!lockfile(fileno(qfp), qf, LOCK_EX|LOCK_NB))
893 	{
894 		/* being processed by another queuer */
895 		if (Verbose)
896 			printf("%s: locked\n", e->e_id);
897 # ifdef LOG
898 		if (LogLevel > 19)
899 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
900 # endif /* LOG */
901 		(void) fclose(qfp);
902 		return FALSE;
903 	}
904 
905 	/* save this lock */
906 	e->e_lockfp = qfp;
907 
908 	/* do basic system initialization */
909 	initsys(e);
910 
911 	FileName = qf;
912 	LineNumber = 0;
913 	if (Verbose)
914 		printf("\nRunning %s\n", e->e_id);
915 	ctladdr = NULL;
916 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
917 	{
918 		register char *p;
919 		struct stat st;
920 
921 		if (tTd(40, 4))
922 			printf("+++++ %s\n", bp);
923 		switch (bp[0])
924 		{
925 		  case 'C':		/* specify controlling user */
926 			ctladdr = setctluser(&bp[1]);
927 			break;
928 
929 		  case 'R':		/* specify recipient */
930 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
931 			break;
932 
933 		  case 'E':		/* specify error recipient */
934 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
935 			break;
936 
937 		  case 'H':		/* header */
938 			(void) chompheader(&bp[1], FALSE, e);
939 			break;
940 
941 		  case 'M':		/* message */
942 			e->e_message = newstr(&bp[1]);
943 			break;
944 
945 		  case 'S':		/* sender */
946 			setsender(newstr(&bp[1]), e, NULL, TRUE);
947 			break;
948 
949 		  case 'D':		/* data file name */
950 			e->e_df = newstr(&bp[1]);
951 			e->e_dfp = fopen(e->e_df, "r");
952 			if (e->e_dfp == NULL)
953 			{
954 				syserr("readqf: cannot open %s", e->e_df);
955 				e->e_msgsize = -1;
956 			}
957 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
958 				e->e_msgsize = st.st_size;
959 			break;
960 
961 		  case 'T':		/* init time */
962 			e->e_ctime = atol(&bp[1]);
963 			break;
964 
965 		  case 'P':		/* message priority */
966 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
967 			break;
968 
969 		  case 'F':		/* flag bits */
970 			for (p = &bp[1]; *p != '\0'; p++)
971 			{
972 				switch (*p)
973 				{
974 				  case 'w':	/* warning sent */
975 					e->e_flags |= EF_WARNING;
976 					break;
977 
978 				  case 'r':	/* response */
979 					e->e_flags |= EF_RESPONSE;
980 					break;
981 				}
982 			}
983 			break;
984 
985 		  case '$':		/* define macro */
986 			define(bp[1], newstr(&bp[2]), e);
987 			break;
988 
989 		  case '\0':		/* blank line; ignore */
990 			break;
991 
992 		  default:
993 			syserr("readqf(%s:%d): bad line \"%s\"", e->e_id,
994 				LineNumber, bp);
995 			break;
996 		}
997 
998 		if (bp != buf)
999 			free(bp);
1000 	}
1001 
1002 	FileName = NULL;
1003 
1004 	/*
1005 	**  If we haven't read any lines, this queue file is empty.
1006 	**  Arrange to remove it without referencing any null pointers.
1007 	*/
1008 
1009 	if (LineNumber == 0)
1010 	{
1011 		errno = 0;
1012 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
1013 	}
1014 	return TRUE;
1015 }
1016 /*
1017 **  PRINTQUEUE -- print out a representation of the mail queue
1018 **
1019 **	Parameters:
1020 **		none.
1021 **
1022 **	Returns:
1023 **		none.
1024 **
1025 **	Side Effects:
1026 **		Prints a listing of the mail queue on the standard output.
1027 */
1028 
1029 printqueue()
1030 {
1031 	register WORK *w;
1032 	FILE *f;
1033 	int nrequests;
1034 	char buf[MAXLINE];
1035 
1036 	/*
1037 	**  Check for permission to print the queue
1038 	*/
1039 
1040 	if (bitset(PRIV_RESTRMAILQ, PrivacyFlags) && getuid() != 0)
1041 	{
1042 		struct stat st;
1043 # ifdef NGROUPS
1044 		int n;
1045 		int gidset[NGROUPS];
1046 # endif
1047 
1048 		if (stat(QueueDir, &st) < 0)
1049 		{
1050 			syserr("Cannot stat %s", QueueDir);
1051 			return;
1052 		}
1053 # ifdef NGROUPS
1054 		n = getgroups(NGROUPS, gidset);
1055 		while (--n >= 0)
1056 		{
1057 			if (gidset[n] == st.st_gid)
1058 				break;
1059 		}
1060 		if (n < 0)
1061 # else
1062 		if (getgid() != st.st_gid)
1063 # endif
1064 		{
1065 			usrerr("510 You are not permitted to see the queue");
1066 			setstat(EX_NOPERM);
1067 			return;
1068 		}
1069 	}
1070 
1071 	/*
1072 	**  Read and order the queue.
1073 	*/
1074 
1075 	nrequests = orderq(TRUE);
1076 
1077 	/*
1078 	**  Print the work list that we have read.
1079 	*/
1080 
1081 	/* first see if there is anything */
1082 	if (nrequests <= 0)
1083 	{
1084 		printf("Mail queue is empty\n");
1085 		return;
1086 	}
1087 
1088 	CurrentLA = getla();	/* get load average */
1089 
1090 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1091 	if (nrequests > QUEUESIZE)
1092 		printf(", only %d printed", QUEUESIZE);
1093 	if (Verbose)
1094 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1095 	else
1096 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1097 	for (w = WorkQ; w != NULL; w = w->w_next)
1098 	{
1099 		struct stat st;
1100 		auto time_t submittime = 0;
1101 		long dfsize = -1;
1102 		int flags = 0;
1103 		char message[MAXLINE];
1104 		extern bool shouldqueue();
1105 		extern bool lockfile();
1106 
1107 		f = fopen(w->w_name, "r");
1108 		if (f == NULL)
1109 		{
1110 			errno = 0;
1111 			continue;
1112 		}
1113 		printf("%8s", w->w_name + 2);
1114 		if (!lockfile(fileno(f), w->w_name, LOCK_SH|LOCK_NB))
1115 			printf("*");
1116 		else if (shouldqueue(w->w_pri, w->w_ctime))
1117 			printf("X");
1118 		else
1119 			printf(" ");
1120 		errno = 0;
1121 
1122 		message[0] = '\0';
1123 		while (fgets(buf, sizeof buf, f) != NULL)
1124 		{
1125 			register int i;
1126 			register char *p;
1127 
1128 			fixcrlf(buf, TRUE);
1129 			switch (buf[0])
1130 			{
1131 			  case 'M':	/* error message */
1132 				if ((i = strlen(&buf[1])) >= sizeof message)
1133 					i = sizeof message - 1;
1134 				bcopy(&buf[1], message, i);
1135 				message[i] = '\0';
1136 				break;
1137 
1138 			  case 'S':	/* sender name */
1139 				if (Verbose)
1140 					printf("%8ld %10ld%c%.12s %.38s",
1141 					    dfsize,
1142 					    w->w_pri,
1143 					    bitset(EF_WARNING, flags) ? '+' : ' ',
1144 					    ctime(&submittime) + 4,
1145 					    &buf[1]);
1146 				else
1147 					printf("%8ld %.16s %.45s", dfsize,
1148 					    ctime(&submittime), &buf[1]);
1149 				if (message[0] != '\0')
1150 					printf("\n\t\t (%.60s)", message);
1151 				break;
1152 
1153 			  case 'C':	/* controlling user */
1154 				if (Verbose)
1155 					printf("\n\t\t\t\t      (---%.34s---)",
1156 						&buf[1]);
1157 				break;
1158 
1159 			  case 'R':	/* recipient name */
1160 				if (Verbose)
1161 					printf("\n\t\t\t\t\t  %.38s", &buf[1]);
1162 				else
1163 					printf("\n\t\t\t\t   %.45s", &buf[1]);
1164 				break;
1165 
1166 			  case 'T':	/* creation time */
1167 				submittime = atol(&buf[1]);
1168 				break;
1169 
1170 			  case 'D':	/* data file name */
1171 				if (stat(&buf[1], &st) >= 0)
1172 					dfsize = st.st_size;
1173 				break;
1174 
1175 			  case 'F':	/* flag bits */
1176 				for (p = &buf[1]; *p != '\0'; p++)
1177 				{
1178 					switch (*p)
1179 					{
1180 					  case 'w':
1181 						flags |= EF_WARNING;
1182 						break;
1183 					}
1184 				}
1185 			}
1186 		}
1187 		if (submittime == (time_t) 0)
1188 			printf(" (no control file)");
1189 		printf("\n");
1190 		(void) fclose(f);
1191 	}
1192 }
1193 
1194 # endif /* QUEUE */
1195 /*
1196 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1197 **
1198 **	Assigns an id code if one does not already exist.
1199 **	This code is very careful to avoid trashing existing files
1200 **	under any circumstances.
1201 **
1202 **	Parameters:
1203 **		e -- envelope to build it in/from.
1204 **		type -- the file type, used as the first character
1205 **			of the file name.
1206 **
1207 **	Returns:
1208 **		a pointer to the new file name (in a static buffer).
1209 **
1210 **	Side Effects:
1211 **		If no id code is already assigned, queuename will
1212 **		assign an id code, create a qf file, and leave a
1213 **		locked, open-for-write file pointer in the envelope.
1214 */
1215 
1216 char *
1217 queuename(e, type)
1218 	register ENVELOPE *e;
1219 	char type;
1220 {
1221 	static int pid = -1;
1222 	static char c0;
1223 	static char c1;
1224 	static char c2;
1225 	time_t now;
1226 	struct tm *tm;
1227 	static char buf[MAXNAME];
1228 	extern bool lockfile();
1229 
1230 	if (e->e_id == NULL)
1231 	{
1232 		char qf[20];
1233 
1234 		/* find a unique id */
1235 		if (pid != getpid())
1236 		{
1237 			/* new process -- start back at "AA" */
1238 			pid = getpid();
1239 			now = curtime();
1240 			tm = localtime(&now);
1241 			c0 = 'A' + tm->tm_hour;
1242 			c1 = 'A';
1243 			c2 = 'A' - 1;
1244 		}
1245 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
1246 
1247 		while (c1 < '~' || c2 < 'Z')
1248 		{
1249 			int i;
1250 
1251 			if (c2 >= 'Z')
1252 			{
1253 				c1++;
1254 				c2 = 'A' - 1;
1255 			}
1256 			qf[3] = c1;
1257 			qf[4] = ++c2;
1258 			if (tTd(7, 20))
1259 				printf("queuename: trying \"%s\"\n", qf);
1260 
1261 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1262 			if (i < 0)
1263 			{
1264 				if (errno == EEXIST)
1265 					continue;
1266 				syserr("queuename: Cannot create \"%s\" in \"%s\"",
1267 					qf, QueueDir);
1268 				exit(EX_UNAVAILABLE);
1269 			}
1270 			if (lockfile(i, qf, LOCK_EX|LOCK_NB))
1271 			{
1272 				e->e_lockfp = fdopen(i, "w");
1273 				break;
1274 			}
1275 
1276 			/* a reader got the file; abandon it and try again */
1277 			(void) close(i);
1278 		}
1279 		if (c1 >= '~' && c2 >= 'Z')
1280 		{
1281 			syserr("queuename: Cannot create \"%s\" in \"%s\"",
1282 				qf, QueueDir);
1283 			exit(EX_OSERR);
1284 		}
1285 		e->e_id = newstr(&qf[2]);
1286 		define('i', e->e_id, e);
1287 		if (tTd(7, 1))
1288 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1289 # ifdef LOG
1290 		if (LogLevel > 93)
1291 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1292 # endif /* LOG */
1293 	}
1294 
1295 	if (type == '\0')
1296 		return (NULL);
1297 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1298 	if (tTd(7, 2))
1299 		printf("queuename: %s\n", buf);
1300 	return (buf);
1301 }
1302 /*
1303 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1304 **
1305 **	Parameters:
1306 **		e -- the envelope to unlock.
1307 **
1308 **	Returns:
1309 **		none
1310 **
1311 **	Side Effects:
1312 **		unlocks the queue for `e'.
1313 */
1314 
1315 unlockqueue(e)
1316 	ENVELOPE *e;
1317 {
1318 	if (tTd(51, 4))
1319 		printf("unlockqueue(%s)\n", e->e_id);
1320 
1321 	/* if there is a lock file in the envelope, close it */
1322 	if (e->e_lockfp != NULL)
1323 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
1324 	e->e_lockfp = NULL;
1325 
1326 	/* don't create a queue id if we don't already have one */
1327 	if (e->e_id == NULL)
1328 		return;
1329 
1330 	/* remove the transcript */
1331 # ifdef LOG
1332 	if (LogLevel > 87)
1333 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1334 # endif /* LOG */
1335 	if (!tTd(51, 104))
1336 		xunlink(queuename(e, 'x'));
1337 
1338 }
1339 /*
1340 **  SETCTLUSER -- create a controlling address
1341 **
1342 **	Create a fake "address" given only a local login name; this is
1343 **	used as a "controlling user" for future recipient addresses.
1344 **
1345 **	Parameters:
1346 **		user -- the user name of the controlling user.
1347 **
1348 **	Returns:
1349 **		An address descriptor for the controlling user.
1350 **
1351 **	Side Effects:
1352 **		none.
1353 */
1354 
1355 ADDRESS *
1356 setctluser(user)
1357 	char *user;
1358 {
1359 	register ADDRESS *a;
1360 	struct passwd *pw;
1361 
1362 	/*
1363 	**  See if this clears our concept of controlling user.
1364 	*/
1365 
1366 	if (user == NULL || *user == '\0')
1367 		user = DefUser;
1368 
1369 	/*
1370 	**  Set up addr fields for controlling user.
1371 	*/
1372 
1373 	a = (ADDRESS *) xalloc(sizeof *a);
1374 	bzero((char *) a, sizeof *a);
1375 	if ((pw = getpwnam(user)) != NULL)
1376 	{
1377 		a->q_home = newstr(pw->pw_dir);
1378 		a->q_uid = pw->pw_uid;
1379 		a->q_gid = pw->pw_gid;
1380 		a->q_user = newstr(user);
1381 	}
1382 	else
1383 	{
1384 		a->q_uid = DefUid;
1385 		a->q_gid = DefGid;
1386 		a->q_user = newstr(DefUser);
1387 	}
1388 
1389 	a->q_flags |= QGOODUID|QPRIMARY;	/* flag as a "ctladdr"  */
1390 	a->q_mailer = LocalMailer;
1391 	return a;
1392 }
1393