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