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