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