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