xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 67987)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  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	8.58 (Berkeley) 11/23/94 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	8.58 (Berkeley) 11/23/94 (without queueing)";
16 #endif
17 #endif /* not lint */
18 
19 # include <errno.h>
20 # include <pwd.h>
21 # include <dirent.h>
22 
23 # ifdef QUEUE
24 
25 /*
26 **  Work queue.
27 */
28 
29 struct work
30 {
31 	char		*w_name;	/* name of control file */
32 	char		*w_host;	/* name of recipient host */
33 	bool		w_lock;		/* is message locked? */
34 	long		w_pri;		/* priority of message, see below */
35 	time_t		w_ctime;	/* creation time of message */
36 	struct work	*w_next;	/* next in queue */
37 };
38 
39 typedef struct work	WORK;
40 
41 WORK	*WorkQ;			/* queue of things to be done */
42 
43 #define QF_VERSION	1	/* version number of this queue format */
44 /*
45 **  QUEUEUP -- queue a message up for future transmission.
46 **
47 **	Parameters:
48 **		e -- the envelope to queue up.
49 **		queueall -- if TRUE, queue all addresses, rather than
50 **			just those with the QQUEUEUP flag set.
51 **		announce -- if TRUE, tell when you are queueing up.
52 **
53 **	Returns:
54 **		none.
55 **
56 **	Side Effects:
57 **		The current request are saved in a control file.
58 **		The queue file is left locked.
59 */
60 
61 queueup(e, queueall, announce)
62 	register ENVELOPE *e;
63 	bool queueall;
64 	bool announce;
65 {
66 	char *qf;
67 	register FILE *tfp;
68 	register HDR *h;
69 	register ADDRESS *q;
70 	int fd;
71 	int i;
72 	bool newid;
73 	register char *p;
74 	MAILER nullmailer;
75 	MCI mcibuf;
76 	char buf[MAXLINE], tf[MAXLINE];
77 
78 	/*
79 	**  Create control file.
80 	*/
81 
82 	newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags);
83 
84 	/* if newid, queuename will create a locked qf file in e->lockfp */
85 	strcpy(tf, queuename(e, 't'));
86 	tfp = e->e_lockfp;
87 	if (tfp == NULL)
88 		newid = FALSE;
89 
90 	/* if newid, just write the qf file directly (instead of tf file) */
91 	if (!newid)
92 	{
93 		/* get a locked tf file */
94 		for (i = 0; i < 128; i++)
95 		{
96 			fd = open(tf, O_CREAT|O_WRONLY|O_EXCL, FileMode);
97 			if (fd < 0)
98 			{
99 				if (errno != EEXIST)
100 					break;
101 #ifdef LOG
102 				if (LogLevel > 0 && (i % 32) == 0)
103 					syslog(LOG_ALERT, "queueup: cannot create %s, uid=%d: %s",
104 						tf, geteuid(), errstring(errno));
105 #endif
106 			}
107 			else
108 			{
109 				if (lockfile(fd, tf, NULL, LOCK_EX|LOCK_NB))
110 					break;
111 #ifdef LOG
112 				else if (LogLevel > 0 && (i % 32) == 0)
113 					syslog(LOG_ALERT, "queueup: cannot lock %s: %s",
114 						tf, errstring(errno));
115 #endif
116 				close(fd);
117 			}
118 
119 			if ((i % 32) == 31)
120 			{
121 				/* save the old temp file away */
122 				(void) rename(tf, queuename(e, 'T'));
123 			}
124 			else
125 				sleep(i % 32);
126 		}
127 		if (fd < 0 || (tfp = fdopen(fd, "w")) == NULL)
128 		{
129 			printopenfds(TRUE);
130 			syserr("!queueup: cannot create queue temp file %s, uid=%d",
131 				tf, geteuid());
132 		}
133 	}
134 
135 	if (tTd(40, 1))
136 		printf("\n>>>>> queueing %s%s queueall=%d >>>>>\n", e->e_id,
137 			newid ? " (new id)" : "", queueall);
138 	if (tTd(40, 32))
139 	{
140 		printf("  sendq=");
141 		printaddr(e->e_sendqueue, TRUE);
142 	}
143 	if (tTd(40, 9))
144 	{
145 		printf("  tfp=");
146 		dumpfd(fileno(tfp), TRUE, FALSE);
147 		printf("  lockfp=");
148 		if (e->e_lockfp == NULL)
149 			printf("NULL\n");
150 		else
151 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
152 	}
153 
154 	/*
155 	**  If there is no data file yet, create one.
156 	*/
157 
158 	if (e->e_df == NULL)
159 	{
160 		register FILE *dfp;
161 		struct stat stbuf;
162 		extern putbody();
163 
164 		e->e_df = queuename(e, 'd');
165 		e->e_df = newstr(e->e_df);
166 		fd = open(e->e_df, O_WRONLY|O_CREAT|O_TRUNC, FileMode);
167 		if (fd < 0 || (dfp = fdopen(fd, "w")) == NULL)
168 			syserr("!queueup: cannot create data temp file %s, uid=%d",
169 				e->e_df, geteuid());
170 		if (fstat(fd, &stbuf) < 0)
171 			e->e_dfino = -1;
172 		else
173 		{
174 			e->e_dfdev = stbuf.st_dev;
175 			e->e_dfino = stbuf.st_ino;
176 		}
177 		bzero(&mcibuf, sizeof mcibuf);
178 		mcibuf.mci_out = dfp;
179 		mcibuf.mci_mailer = FileMailer;
180 		(*e->e_putbody)(&mcibuf, e, NULL, 0);
181 		(void) xfclose(dfp, "queueup dfp", e->e_id);
182 		e->e_putbody = putbody;
183 	}
184 
185 	/*
186 	**  Output future work requests.
187 	**	Priority and creation time should be first, since
188 	**	they are required by orderq.
189 	*/
190 
191 	/* output queue version number (must be first!) */
192 	fprintf(tfp, "V%d\n", QF_VERSION);
193 
194 	/* output message priority */
195 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
196 
197 	/* output creation time */
198 	fprintf(tfp, "T%ld\n", e->e_ctime);
199 
200 	/* output last delivery time */
201 	fprintf(tfp, "K%ld\n", e->e_dtime);
202 
203 	/* output number of delivery attempts */
204 	fprintf(tfp, "N%d\n", e->e_ntries);
205 
206 	/* output inode number of data file */
207 	/* XXX should probably include device major/minor too */
208 	if (e->e_dfino != -1)
209 		fprintf(tfp, "I%d/%d/%ld\n",
210 			major(e->e_dfdev), minor(e->e_dfdev), e->e_dfino);
211 
212 	/* output type and name of data file */
213 	if (e->e_bodytype != NULL)
214 		fprintf(tfp, "B%s\n", e->e_bodytype);
215 	fprintf(tfp, "D%s\n", e->e_df);
216 
217 	/* message from envelope, if it exists */
218 	if (e->e_message != NULL)
219 		fprintf(tfp, "M%s\n", e->e_message);
220 
221 	/* send various flag bits through */
222 	p = buf;
223 	if (bitset(EF_WARNING, e->e_flags))
224 		*p++ = 'w';
225 	if (bitset(EF_RESPONSE, e->e_flags))
226 		*p++ = 'r';
227 	if (bitset(EF_HAS8BIT, e->e_flags))
228 		*p++ = '8';
229 	*p++ = '\0';
230 	if (buf[0] != '\0')
231 		fprintf(tfp, "F%s\n", buf);
232 
233 	/* $r and $s and $_ macro values */
234 	if ((p = macvalue('r', e)) != NULL)
235 		fprintf(tfp, "$r%s\n", p);
236 	if ((p = macvalue('s', e)) != NULL)
237 		fprintf(tfp, "$s%s\n", p);
238 	if ((p = macvalue('_', e)) != NULL)
239 		fprintf(tfp, "$_%s\n", p);
240 
241 	/* output name of sender */
242 	if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
243 		p = e->e_sender;
244 	else
245 		p = e->e_from.q_paddr;
246 	fprintf(tfp, "S%s\n", p);
247 
248 	/* output ESMTP-supplied "original" information */
249 	if (e->e_envid != NULL)
250 		fprintf(tfp, "Z%s\n", e->e_envid);
251 	if (e->e_omts != NULL)
252 		fprintf(tfp, "O%s\n", e->e_omts);
253 
254 	/* output list of error recipients */
255 	printctladdr(NULL, NULL);
256 	for (q = e->e_errorqueue; q != NULL; q = q->q_next)
257 	{
258 		if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
259 		{
260 			printctladdr(q, tfp);
261 			fprintf(tfp, "E%s\n", q->q_paddr);
262 		}
263 	}
264 
265 	/* output list of recipient addresses */
266 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
267 	{
268 		if (bitset(QQUEUEUP, q->q_flags) ||
269 		    (queueall && !bitset(QDONTSEND|QBADADDR|QSENT, q->q_flags)))
270 		{
271 			printctladdr(q, tfp);
272 			if (q->q_orcpt != NULL)
273 				fprintf(tfp, "Q%s\n", q->q_orcpt);
274 			putc('R', tfp);
275 			if (bitset(QPRIMARY, q->q_flags))
276 				putc('P', tfp);
277 			if (bitset(QPINGONSUCCESS, q->q_flags))
278 				putc('S', tfp);
279 			if (bitset(QPINGONFAILURE, q->q_flags))
280 				putc('F', tfp);
281 			if (bitset(QPINGONDELAY, q->q_flags))
282 				putc('D', tfp);
283 			if (bitset(QHAS_RET_PARAM, q->q_flags))
284 			{
285 				if (bitset(QRET_HDRS, q->q_flags))
286 					putc('N', tfp);
287 				else
288 					putc('B', tfp);
289 			}
290 			putc(':', tfp);
291 			fprintf(tfp, "%s\n", q->q_paddr);
292 			if (announce)
293 			{
294 				e->e_to = q->q_paddr;
295 				message("queued");
296 				if (LogLevel > 8)
297 					logdelivery(NULL, NULL, "queued", NULL, e);
298 				e->e_to = NULL;
299 			}
300 			if (tTd(40, 1))
301 			{
302 				printf("queueing ");
303 				printaddr(q, FALSE);
304 			}
305 		}
306 	}
307 
308 	/*
309 	**  Output headers for this message.
310 	**	Expand macros completely here.  Queue run will deal with
311 	**	everything as absolute headers.
312 	**		All headers that must be relative to the recipient
313 	**		can be cracked later.
314 	**	We set up a "null mailer" -- i.e., a mailer that will have
315 	**	no effect on the addresses as they are output.
316 	*/
317 
318 	bzero((char *) &nullmailer, sizeof nullmailer);
319 	nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
320 			nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1;
321 	nullmailer.m_eol = "\n";
322 	bzero(&mcibuf, sizeof mcibuf);
323 	mcibuf.mci_mailer = &nullmailer;
324 	mcibuf.mci_out = tfp;
325 
326 	define('g', "\201f", e);
327 	for (h = e->e_header; h != NULL; h = h->h_link)
328 	{
329 		extern bool bitzerop();
330 
331 		/* don't output null headers */
332 		if (h->h_value == NULL || h->h_value[0] == '\0')
333 			continue;
334 
335 		/* don't output resent headers on non-resent messages */
336 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
337 			continue;
338 
339 		/* expand macros; if null, don't output header at all */
340 		if (bitset(H_DEFAULT, h->h_flags))
341 		{
342 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
343 			if (buf[0] == '\0')
344 				continue;
345 		}
346 
347 		/* output this header */
348 		fprintf(tfp, "H");
349 
350 		/* if conditional, output the set of conditions */
351 		if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags))
352 		{
353 			int j;
354 
355 			(void) putc('?', tfp);
356 			for (j = '\0'; j <= '\177'; j++)
357 				if (bitnset(j, h->h_mflags))
358 					(void) putc(j, tfp);
359 			(void) putc('?', tfp);
360 		}
361 
362 		/* output the header: expand macros, convert addresses */
363 		if (bitset(H_DEFAULT, h->h_flags))
364 		{
365 			fprintf(tfp, "%s: %s\n", h->h_field, buf);
366 		}
367 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
368 		{
369 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
370 			FILE *savetrace = TrafficLogFile;
371 
372 			TrafficLogFile = NULL;
373 
374 			if (bitset(H_FROM, h->h_flags))
375 				oldstyle = FALSE;
376 
377 			commaize(h, h->h_value, oldstyle, &mcibuf, e);
378 
379 			TrafficLogFile = savetrace;
380 		}
381 		else
382 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
383 	}
384 
385 	/*
386 	**  Clean up.
387 	*/
388 
389 	if (fflush(tfp) < 0 || fsync(fileno(tfp)) < 0 || ferror(tfp))
390 	{
391 		if (newid)
392 			syserr("!552 Error writing control file %s", tf);
393 		else
394 			syserr("!452 Error writing control file %s", tf);
395 	}
396 
397 	if (!newid)
398 	{
399 		/* rename (locked) tf to be (locked) qf */
400 		qf = queuename(e, 'q');
401 		if (rename(tf, qf) < 0)
402 			syserr("cannot rename(%s, %s), df=%s, uid=%d",
403 				tf, qf, e->e_df, geteuid());
404 
405 		/* close and unlock old (locked) qf */
406 		if (e->e_lockfp != NULL)
407 			(void) xfclose(e->e_lockfp, "queueup lockfp", e->e_id);
408 		e->e_lockfp = tfp;
409 	}
410 	else
411 		qf = tf;
412 	errno = 0;
413 	e->e_flags |= EF_INQUEUE;
414 
415 # ifdef LOG
416 	/* save log info */
417 	if (LogLevel > 79)
418 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
419 # endif /* LOG */
420 
421 	if (tTd(40, 1))
422 		printf("<<<<< done queueing %s <<<<<\n\n", e->e_id);
423 	return;
424 }
425 
426 printctladdr(a, tfp)
427 	register ADDRESS *a;
428 	FILE *tfp;
429 {
430 	char *uname;
431 	register struct passwd *pw;
432 	register ADDRESS *q;
433 	uid_t uid;
434 	static ADDRESS *lastctladdr;
435 	static uid_t lastuid;
436 
437 	/* initialization */
438 	if (a == NULL || a->q_alias == NULL || tfp == NULL)
439 	{
440 		if (lastctladdr != NULL && tfp != NULL)
441 			fprintf(tfp, "C\n");
442 		lastctladdr = NULL;
443 		lastuid = 0;
444 		return;
445 	}
446 
447 	/* find the active uid */
448 	q = getctladdr(a);
449 	if (q == NULL)
450 		uid = 0;
451 	else
452 		uid = q->q_uid;
453 	a = a->q_alias;
454 
455 	/* check to see if this is the same as last time */
456 	if (lastctladdr != NULL && uid == lastuid &&
457 	    strcmp(lastctladdr->q_paddr, a->q_paddr) == 0)
458 		return;
459 	lastuid = uid;
460 	lastctladdr = a;
461 
462 	if (uid == 0 || (pw = getpwuid(uid)) == NULL)
463 		uname = "";
464 	else
465 		uname = pw->pw_name;
466 
467 	fprintf(tfp, "C%s:%s\n", uname, a->q_paddr);
468 }
469 /*
470 **  RUNQUEUE -- run the jobs in the queue.
471 **
472 **	Gets the stuff out of the queue in some presumably logical
473 **	order and processes them.
474 **
475 **	Parameters:
476 **		forkflag -- TRUE if the queue scanning should be done in
477 **			a child process.  We double-fork so it is not our
478 **			child and we don't have to clean up after it.
479 **
480 **	Returns:
481 **		none.
482 **
483 **	Side Effects:
484 **		runs things in the mail queue.
485 */
486 
487 ENVELOPE	QueueEnvelope;		/* the queue run envelope */
488 
489 runqueue(forkflag)
490 	bool forkflag;
491 {
492 	register ENVELOPE *e;
493 	int njobs;
494 	int sequenceno = 0;
495 	extern ENVELOPE BlankEnvelope;
496 
497 	/*
498 	**  If no work will ever be selected, don't even bother reading
499 	**  the queue.
500 	*/
501 
502 	CurrentLA = getla();	/* get load average */
503 
504 	if (shouldqueue(0L, curtime()))
505 	{
506 		if (Verbose)
507 			printf("Skipping queue run -- load average too high\n");
508 		if (forkflag && QueueIntvl != 0)
509 			(void) setevent(QueueIntvl, runqueue, TRUE);
510 		return;
511 	}
512 
513 	/*
514 	**  See if we want to go off and do other useful work.
515 	*/
516 
517 	if (forkflag)
518 	{
519 		int pid;
520 #ifdef SIGCHLD
521 		extern void reapchild();
522 
523 		(void) setsignal(SIGCHLD, reapchild);
524 #endif
525 
526 		pid = dofork();
527 		if (pid != 0)
528 		{
529 			/* parent -- pick up intermediate zombie */
530 #ifndef SIGCHLD
531 			(void) waitfor(pid);
532 #endif /* SIGCHLD */
533 			if (QueueIntvl != 0)
534 				(void) setevent(QueueIntvl, runqueue, TRUE);
535 			return;
536 		}
537 		/* child -- double fork */
538 #ifndef SIGCHLD
539 		if (fork() != 0)
540 			exit(EX_OK);
541 #else /* SIGCHLD */
542 		(void) setsignal(SIGCHLD, SIG_DFL);
543 #endif /* SIGCHLD */
544 	}
545 
546 	setproctitle("running queue: %s", QueueDir);
547 
548 # ifdef LOG
549 	if (LogLevel > 69)
550 		syslog(LOG_DEBUG, "runqueue %s, pid=%d, forkflag=%d",
551 			QueueDir, getpid(), forkflag);
552 # endif /* LOG */
553 
554 	/*
555 	**  Release any resources used by the daemon code.
556 	*/
557 
558 # ifdef DAEMON
559 	clrdaemon();
560 # endif /* DAEMON */
561 
562 	/* force it to run expensive jobs */
563 	NoConnect = FALSE;
564 
565 	/*
566 	**  Create ourselves an envelope
567 	*/
568 
569 	CurEnv = &QueueEnvelope;
570 	e = newenvelope(&QueueEnvelope, CurEnv);
571 	e->e_flags = BlankEnvelope.e_flags;
572 
573 	/*
574 	**  Make sure the alias database is open.
575 	*/
576 
577 	initmaps(FALSE, e);
578 
579 	/*
580 	**  Start making passes through the queue.
581 	**	First, read and sort the entire queue.
582 	**	Then, process the work in that order.
583 	**		But if you take too long, start over.
584 	*/
585 
586 	/* order the existing work requests */
587 	njobs = orderq(FALSE);
588 
589 	/* process them once at a time */
590 	while (WorkQ != NULL)
591 	{
592 		WORK *w = WorkQ;
593 
594 		WorkQ = WorkQ->w_next;
595 
596 		/*
597 		**  Ignore jobs that are too expensive for the moment.
598 		*/
599 
600 		sequenceno++;
601 		if (shouldqueue(w->w_pri, w->w_ctime))
602 		{
603 			if (Verbose)
604 				printf("\nSkipping %s (sequence %d of %d)\n",
605 					w->w_name + 2, sequenceno, njobs);
606 		}
607 		else
608 		{
609 			pid_t pid;
610 			extern pid_t dowork();
611 
612 			if (Verbose)
613 				printf("\nRunning %s (sequence %d of %d)\n",
614 					w->w_name + 2, sequenceno, njobs);
615 			pid = dowork(w->w_name + 2, ForkQueueRuns, FALSE, e);
616 			errno = 0;
617 			if (pid != 0)
618 				(void) waitfor(pid);
619 		}
620 		free(w->w_name);
621 		if (w->w_host)
622 			free(w->w_host);
623 		free((char *) w);
624 	}
625 
626 	/* exit without the usual cleanup */
627 	e->e_id = NULL;
628 	finis();
629 }
630 /*
631 **  ORDERQ -- order the work queue.
632 **
633 **	Parameters:
634 **		doall -- if set, include everything in the queue (even
635 **			the jobs that cannot be run because the load
636 **			average is too high).  Otherwise, exclude those
637 **			jobs.
638 **
639 **	Returns:
640 **		The number of request in the queue (not necessarily
641 **		the number of requests in WorkQ however).
642 **
643 **	Side Effects:
644 **		Sets WorkQ to the queue of available work, in order.
645 */
646 
647 # define NEED_P		001
648 # define NEED_T		002
649 # define NEED_R		004
650 # define NEED_S		010
651 
652 orderq(doall)
653 	bool doall;
654 {
655 	register struct dirent *d;
656 	register WORK *w;
657 	DIR *f;
658 	register int i;
659 	WORK wlist[QUEUESIZE+1];
660 	int wn = -1;
661 	int wc;
662 
663 	if (tTd(41, 1))
664 	{
665 		printf("orderq:\n");
666 		if (QueueLimitId != NULL)
667 			printf("\tQueueLimitId = %s\n", QueueLimitId);
668 		if (QueueLimitSender != NULL)
669 			printf("\tQueueLimitSender = %s\n", QueueLimitSender);
670 		if (QueueLimitRecipient != NULL)
671 			printf("\tQueueLimitRecipient = %s\n", QueueLimitRecipient);
672 	}
673 
674 	/* clear out old WorkQ */
675 	for (w = WorkQ; w != NULL; )
676 	{
677 		register WORK *nw = w->w_next;
678 
679 		WorkQ = nw;
680 		free(w->w_name);
681 		if (w->w_host)
682 			free(w->w_host);
683 		free((char *) w);
684 		w = nw;
685 	}
686 
687 	/* open the queue directory */
688 	f = opendir(".");
689 	if (f == NULL)
690 	{
691 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
692 		return (0);
693 	}
694 
695 	/*
696 	**  Read the work directory.
697 	*/
698 
699 	while ((d = readdir(f)) != NULL)
700 	{
701 		FILE *cf;
702 		register char *p;
703 		char lbuf[MAXNAME];
704 		extern bool strcontainedin();
705 
706 		/* is this an interesting entry? */
707 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
708 			continue;
709 
710 		if (QueueLimitId != NULL &&
711 		    !strcontainedin(QueueLimitId, d->d_name))
712 			continue;
713 
714 		/*
715 		**  Check queue name for plausibility.  This handles
716 		**  both old and new type ids.
717 		*/
718 
719 		p = d->d_name + 2;
720 		if (isupper(p[0]) && isupper(p[2]))
721 			p += 3;
722 		else if (isupper(p[1]))
723 			p += 2;
724 		else
725 			p = d->d_name;
726 		for (i = 0; isdigit(*p); p++)
727 			i++;
728 		if (i < 5 || *p != '\0')
729 		{
730 			if (Verbose)
731 				printf("orderq: bogus qf name %s\n", d->d_name);
732 #ifdef LOG
733 			if (LogLevel > 3)
734 				syslog(LOG_CRIT, "orderq: bogus qf name %s",
735 					d->d_name);
736 #endif
737 			if (strlen(d->d_name) >= MAXNAME)
738 				d->d_name[MAXNAME - 1] = '\0';
739 			strcpy(lbuf, d->d_name);
740 			lbuf[0] = 'Q';
741 			(void) rename(d->d_name, lbuf);
742 			continue;
743 		}
744 
745 		/* yes -- open control file (if not too many files) */
746 		if (++wn >= QUEUESIZE)
747 			continue;
748 
749 		cf = fopen(d->d_name, "r");
750 		if (cf == NULL)
751 		{
752 			/* this may be some random person sending hir msgs */
753 			/* syserr("orderq: cannot open %s", cbuf); */
754 			if (tTd(41, 2))
755 				printf("orderq: cannot open %s (%d)\n",
756 					d->d_name, errno);
757 			errno = 0;
758 			wn--;
759 			continue;
760 		}
761 		w = &wlist[wn];
762 		w->w_name = newstr(d->d_name);
763 		w->w_host = NULL;
764 		w->w_lock = !lockfile(fileno(cf), w->w_name, NULL, LOCK_SH|LOCK_NB);
765 
766 		/* make sure jobs in creation don't clog queue */
767 		w->w_pri = 0x7fffffff;
768 		w->w_ctime = 0;
769 
770 		/* extract useful information */
771 		i = NEED_P | NEED_T;
772 		if (QueueLimitSender != NULL)
773 			i |= NEED_S;
774 		if (SortQueueByHost || QueueLimitRecipient != NULL)
775 			i |= NEED_R;
776 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
777 		{
778 			extern long atol();
779 			extern bool strcontainedin();
780 
781 			switch (lbuf[0])
782 			{
783 			  case 'P':
784 				w->w_pri = atol(&lbuf[1]);
785 				i &= ~NEED_P;
786 				break;
787 
788 			  case 'T':
789 				w->w_ctime = atol(&lbuf[1]);
790 				i &= ~NEED_T;
791 				break;
792 
793 			  case 'R':
794 				if (w->w_host == NULL &&
795 				    (p = strrchr(&lbuf[1], '@')) != NULL)
796 					w->w_host = newstr(&p[1]);
797 				if (QueueLimitRecipient == NULL ||
798 				    strcontainedin(QueueLimitRecipient, &lbuf[1]))
799 					i &= ~NEED_R;
800 				break;
801 
802 			  case 'S':
803 				if (QueueLimitSender != NULL &&
804 				    strcontainedin(QueueLimitSender, &lbuf[1]))
805 					i &= ~NEED_S;
806 				break;
807 			}
808 		}
809 		(void) fclose(cf);
810 
811 		if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
812 		    bitset(NEED_R|NEED_S, i))
813 		{
814 			/* don't even bother sorting this job in */
815 			free(w->w_name);
816 			if (w->w_host)
817 				free(w->w_host);
818 			wn--;
819 		}
820 	}
821 	(void) closedir(f);
822 	wn++;
823 
824 	wc = min(wn, QUEUESIZE);
825 
826 	if (!SortQueueByHost)
827 	{
828 		extern workcmpf0();
829 
830 		/*
831 		**  Simple sort based on queue priority only.
832 		*/
833 
834 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf0);
835 	}
836 	else
837 	{
838 		extern workcmpf1();
839 		extern workcmpf2();
840 
841 		/*
842 		**  Sort the work directory for the first time,
843 		**  based on host name, lock status, and priority.
844 		*/
845 
846 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf1);
847 
848 		/*
849 		**  If one message to host is locked, "lock" all messages
850 		**  to that host.
851 		*/
852 
853 		i = 0;
854 		while (i < wc)
855 		{
856 			if (!wlist[i].w_lock)
857 			{
858 				i++;
859 				continue;
860 			}
861 			w = &wlist[i];
862 			while (++i < wc)
863 			{
864 				if (wlist[i].w_host == NULL &&
865 				    w->w_host == NULL)
866 					wlist[i].w_lock = TRUE;
867 				else if (wlist[i].w_host != NULL &&
868 					 w->w_host != NULL &&
869 					 strcmp(wlist[i].w_host, w->w_host) == 0)
870 					wlist[i].w_lock = TRUE;
871 				else
872 					break;
873 			}
874 		}
875 
876 		/*
877 		**  Sort the work directory for the second time,
878 		**  based on lock status, host name, and priority.
879 		*/
880 
881 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf2);
882 	}
883 
884 	/*
885 	**  Convert the work list into canonical form.
886 	**	Should be turning it into a list of envelopes here perhaps.
887 	*/
888 
889 	WorkQ = NULL;
890 	for (i = wc; --i >= 0; )
891 	{
892 		w = (WORK *) xalloc(sizeof *w);
893 		w->w_name = wlist[i].w_name;
894 		w->w_host = wlist[i].w_host;
895 		w->w_lock = wlist[i].w_lock;
896 		w->w_pri = wlist[i].w_pri;
897 		w->w_ctime = wlist[i].w_ctime;
898 		w->w_next = WorkQ;
899 		WorkQ = w;
900 	}
901 
902 	if (tTd(40, 1))
903 	{
904 		for (w = WorkQ; w != NULL; w = w->w_next)
905 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
906 	}
907 
908 	return (wn);
909 }
910 /*
911 **  WORKCMPF0 -- simple priority-only compare function.
912 **
913 **	Parameters:
914 **		a -- the first argument.
915 **		b -- the second argument.
916 **
917 **	Returns:
918 **		-1 if a < b
919 **		 0 if a == b
920 **		+1 if a > b
921 **
922 **	Side Effects:
923 **		none.
924 */
925 
926 workcmpf0(a, b)
927 	register WORK *a;
928 	register WORK *b;
929 {
930 	long pa = a->w_pri;
931 	long pb = b->w_pri;
932 
933 	if (pa == pb)
934 		return 0;
935 	else if (pa > pb)
936 		return 1;
937 	else
938 		return -1;
939 }
940 /*
941 **  WORKCMPF1 -- first compare function for ordering work based on host name.
942 **
943 **	Sorts on host name, lock status, and priority in that order.
944 **
945 **	Parameters:
946 **		a -- the first argument.
947 **		b -- the second argument.
948 **
949 **	Returns:
950 **		<0 if a < b
951 **		 0 if a == b
952 **		>0 if a > b
953 **
954 **	Side Effects:
955 **		none.
956 */
957 
958 workcmpf1(a, b)
959 	register WORK *a;
960 	register WORK *b;
961 {
962 	int i;
963 
964 	/* host name */
965 	if (a->w_host != NULL && b->w_host == NULL)
966 		return 1;
967 	else if (a->w_host == NULL && b->w_host != NULL)
968 		return -1;
969 	if (a->w_host != NULL && b->w_host != NULL &&
970 	    (i = strcmp(a->w_host, b->w_host)))
971 		return i;
972 
973 	/* lock status */
974 	if (a->w_lock != b->w_lock)
975 		return b->w_lock - a->w_lock;
976 
977 	/* job priority */
978 	return a->w_pri - b->w_pri;
979 }
980 /*
981 **  WORKCMPF2 -- second compare function for ordering work based on host name.
982 **
983 **	Sorts on lock status, host name, and priority in that order.
984 **
985 **	Parameters:
986 **		a -- the first argument.
987 **		b -- the second argument.
988 **
989 **	Returns:
990 **		<0 if a < b
991 **		 0 if a == b
992 **		>0 if a > b
993 **
994 **	Side Effects:
995 **		none.
996 */
997 
998 workcmpf2(a, b)
999 	register WORK *a;
1000 	register WORK *b;
1001 {
1002 	int i;
1003 
1004 	/* lock status */
1005 	if (a->w_lock != b->w_lock)
1006 		return a->w_lock - b->w_lock;
1007 
1008 	/* host name */
1009 	if (a->w_host != NULL && b->w_host == NULL)
1010 		return 1;
1011 	else if (a->w_host == NULL && b->w_host != NULL)
1012 		return -1;
1013 	if (a->w_host != NULL && b->w_host != NULL &&
1014 	    (i = strcmp(a->w_host, b->w_host)))
1015 		return i;
1016 
1017 	/* job priority */
1018 	return a->w_pri - b->w_pri;
1019 }
1020 /*
1021 **  DOWORK -- do a work request.
1022 **
1023 **	Parameters:
1024 **		id -- the ID of the job to run.
1025 **		forkflag -- if set, run this in background.
1026 **		requeueflag -- if set, reinstantiate the queue quickly.
1027 **			This is used when expanding aliases in the queue.
1028 **			If forkflag is also set, it doesn't wait for the
1029 **			child.
1030 **		e - the envelope in which to run it.
1031 **
1032 **	Returns:
1033 **		process id of process that is running the queue job.
1034 **
1035 **	Side Effects:
1036 **		The work request is satisfied if possible.
1037 */
1038 
1039 pid_t
1040 dowork(id, forkflag, requeueflag, e)
1041 	char *id;
1042 	bool forkflag;
1043 	bool requeueflag;
1044 	register ENVELOPE *e;
1045 {
1046 	register pid_t pid;
1047 	extern bool readqf();
1048 
1049 	if (tTd(40, 1))
1050 		printf("dowork(%s)\n", id);
1051 
1052 	/*
1053 	**  Fork for work.
1054 	*/
1055 
1056 	if (forkflag)
1057 	{
1058 		pid = fork();
1059 		if (pid < 0)
1060 		{
1061 			syserr("dowork: cannot fork");
1062 			return 0;
1063 		}
1064 		else if (pid > 0)
1065 		{
1066 			/* parent -- clean out connection cache */
1067 			mci_flush(FALSE, NULL);
1068 		}
1069 	}
1070 	else
1071 	{
1072 		pid = 0;
1073 	}
1074 
1075 	if (pid == 0)
1076 	{
1077 		/*
1078 		**  CHILD
1079 		**	Lock the control file to avoid duplicate deliveries.
1080 		**		Then run the file as though we had just read it.
1081 		**	We save an idea of the temporary name so we
1082 		**		can recover on interrupt.
1083 		*/
1084 
1085 		/* set basic modes, etc. */
1086 		(void) alarm(0);
1087 		clearenvelope(e, FALSE);
1088 		e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
1089 		e->e_errormode = EM_MAIL;
1090 		e->e_id = id;
1091 		GrabTo = UseErrorsTo = FALSE;
1092 		ExitStat = EX_OK;
1093 		if (forkflag)
1094 		{
1095 			disconnect(1, e);
1096 			OpMode = MD_DELIVER;
1097 		}
1098 # ifdef LOG
1099 		if (LogLevel > 76)
1100 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
1101 			       getpid());
1102 # endif /* LOG */
1103 
1104 		/* don't use the headers from sendmail.cf... */
1105 		e->e_header = NULL;
1106 
1107 		/* read the queue control file -- return if locked */
1108 		if (!readqf(e))
1109 		{
1110 			if (tTd(40, 4))
1111 				printf("readqf(%s) failed\n", e->e_id);
1112 			if (forkflag)
1113 				exit(EX_OK);
1114 			else
1115 				return 0;
1116 		}
1117 
1118 		e->e_flags |= EF_INQUEUE;
1119 
1120 		/* if this has been tried recently, let it be */
1121 		if (e->e_ntries > 0 && (curtime() - e->e_dtime) < MinQueueAge)
1122 		{
1123 			char *howlong = pintvl(curtime() - e->e_dtime, TRUE);
1124 
1125 			e->e_flags |= EF_KEEPQUEUE;
1126 			if (Verbose || tTd(40, 8))
1127 				printf("%s: too young (%s)\n",
1128 					e->e_id, howlong);
1129 #ifdef LOG
1130 			if (LogLevel > 19)
1131 				syslog(LOG_DEBUG, "%s: too young (%s)",
1132 					e->e_id, howlong);
1133 #endif
1134 		}
1135 		else
1136 		{
1137 			eatheader(e, requeueflag);
1138 
1139 			if (requeueflag)
1140 				queueup(e, TRUE, FALSE);
1141 
1142 			/* do the delivery */
1143 			sendall(e, SM_DELIVER);
1144 		}
1145 
1146 		/* finish up and exit */
1147 		if (forkflag)
1148 			finis();
1149 		else
1150 			dropenvelope(e);
1151 	}
1152 	e->e_id = NULL;
1153 	return pid;
1154 }
1155 /*
1156 **  READQF -- read queue file and set up environment.
1157 **
1158 **	Parameters:
1159 **		e -- the envelope of the job to run.
1160 **
1161 **	Returns:
1162 **		TRUE if it successfully read the queue file.
1163 **		FALSE otherwise.
1164 **
1165 **	Side Effects:
1166 **		The queue file is returned locked.
1167 */
1168 
1169 bool
1170 readqf(e)
1171 	register ENVELOPE *e;
1172 {
1173 	register FILE *qfp;
1174 	ADDRESS *ctladdr;
1175 	struct stat st;
1176 	char *bp;
1177 	int qfver = 0;
1178 	register char *p;
1179 	char *orcpt = NULL;
1180 	char qf[20];
1181 	char buf[MAXLINE];
1182 	extern long atol();
1183 	extern ADDRESS *setctluser();
1184 
1185 	/*
1186 	**  Read and process the file.
1187 	*/
1188 
1189 	strcpy(qf, queuename(e, 'q'));
1190 	qfp = fopen(qf, "r+");
1191 	if (qfp == NULL)
1192 	{
1193 		if (tTd(40, 8))
1194 			printf("readqf(%s): fopen failure (%s)\n",
1195 				qf, errstring(errno));
1196 		if (errno != ENOENT)
1197 			syserr("readqf: no control file %s", qf);
1198 		return FALSE;
1199 	}
1200 
1201 	if (!lockfile(fileno(qfp), qf, NULL, LOCK_EX|LOCK_NB))
1202 	{
1203 		/* being processed by another queuer */
1204 		if (Verbose || tTd(40, 8))
1205 			printf("%s: locked\n", e->e_id);
1206 # ifdef LOG
1207 		if (LogLevel > 19)
1208 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
1209 # endif /* LOG */
1210 		(void) fclose(qfp);
1211 		return FALSE;
1212 	}
1213 
1214 	/*
1215 	**  Check the queue file for plausibility to avoid attacks.
1216 	*/
1217 
1218 	if (fstat(fileno(qfp), &st) < 0)
1219 	{
1220 		/* must have been being processed by someone else */
1221 		if (tTd(40, 8))
1222 			printf("readqf(%s): fstat failure (%s)\n",
1223 				qf, errstring(errno));
1224 		fclose(qfp);
1225 		return FALSE;
1226 	}
1227 
1228 	if (st.st_uid != geteuid())
1229 	{
1230 # ifdef LOG
1231 		if (LogLevel > 0)
1232 		{
1233 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
1234 				e->e_id, st.st_uid, st.st_mode);
1235 		}
1236 # endif /* LOG */
1237 		if (tTd(40, 8))
1238 			printf("readqf(%s): bogus file\n", qf);
1239 		rename(qf, queuename(e, 'Q'));
1240 		fclose(qfp);
1241 		return FALSE;
1242 	}
1243 
1244 	if (st.st_size == 0)
1245 	{
1246 		/* must be a bogus file -- just remove it */
1247 		(void) unlink(qf);
1248 		fclose(qfp);
1249 		return FALSE;
1250 	}
1251 
1252 	if (st.st_nlink == 0)
1253 	{
1254 		/*
1255 		**  Race condition -- we got a file just as it was being
1256 		**  unlinked.  Just assume it is zero length.
1257 		*/
1258 
1259 		fclose(qfp);
1260 		return FALSE;
1261 	}
1262 
1263 	/* good file -- save this lock */
1264 	e->e_lockfp = qfp;
1265 
1266 	/* do basic system initialization */
1267 	initsys(e);
1268 	define('i', e->e_id, e);
1269 
1270 	LineNumber = 0;
1271 	e->e_flags |= EF_GLOBALERRS;
1272 	OpMode = MD_DELIVER;
1273 	ctladdr = NULL;
1274 	e->e_dfino = -1;
1275 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
1276 	{
1277 		register char *p;
1278 		struct stat st;
1279 		u_long qflags;
1280 		ADDRESS *q;
1281 
1282 		if (tTd(40, 4))
1283 			printf("+++++ %s\n", bp);
1284 		switch (bp[0])
1285 		{
1286 		  case 'V':		/* queue file version number */
1287 			qfver = atoi(&bp[1]);
1288 			if (qfver > QF_VERSION)
1289 			{
1290 				syserr("Version number in qf (%d) greater than max (%d)",
1291 					qfver, QF_VERSION);
1292 			}
1293 			break;
1294 
1295 		  case 'C':		/* specify controlling user */
1296 			ctladdr = setctluser(&bp[1]);
1297 			break;
1298 
1299 		  case 'Q':		/* original recipient */
1300 			orcpt = newstr(&bp[1]);
1301 			break;
1302 
1303 		  case 'R':		/* specify recipient */
1304 			p = bp;
1305 			qflags = 0;
1306 			if (qfver >= 1)
1307 			{
1308 				/* get flag bits */
1309 				while (*++p != '\0' && *p != ':')
1310 				{
1311 					switch (*p)
1312 					{
1313 					  case 'S':
1314 						qflags |= QPINGONSUCCESS;
1315 						break;
1316 
1317 					  case 'F':
1318 						qflags |= QPINGONFAILURE;
1319 						break;
1320 
1321 					  case 'D':
1322 						qflags |= QPINGONDELAY;
1323 						break;
1324 
1325 					  case 'B':
1326 						qflags |= QHAS_RET_PARAM;
1327 						break;
1328 
1329 					  case 'N':
1330 						qflags |= QHAS_RET_PARAM|QRET_HDRS;
1331 						break;
1332 
1333 					  case 'P':
1334 						qflags |= QPRIMARY;
1335 						break;
1336 					}
1337 				}
1338 			}
1339 			else
1340 				qflags |= QPRIMARY;
1341 			q = parseaddr(++p, NULLADDR, RF_COPYALL, '\0', NULL, e);
1342 			if (q != NULL)
1343 			{
1344 				q->q_alias = ctladdr;
1345 				q->q_flags |= qflags;
1346 				q->q_orcpt = orcpt;
1347 				(void) recipient(q, &e->e_sendqueue, 0, e);
1348 			}
1349 			orcpt = NULL;
1350 			break;
1351 
1352 		  case 'E':		/* specify error recipient */
1353 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, 0, e);
1354 			break;
1355 
1356 		  case 'H':		/* header */
1357 			(void) chompheader(&bp[1], FALSE, e);
1358 			break;
1359 
1360 		  case 'M':		/* message */
1361 			/* ignore this; we want a new message next time */
1362 			break;
1363 
1364 		  case 'S':		/* sender */
1365 			setsender(newstr(&bp[1]), e, NULL, TRUE);
1366 			break;
1367 
1368 		  case 'B':		/* body type */
1369 			e->e_bodytype = newstr(&bp[1]);
1370 			break;
1371 
1372 		  case 'D':		/* data file name */
1373 			e->e_df = newstr(&bp[1]);
1374 			e->e_dfp = fopen(e->e_df, "r");
1375 			if (e->e_dfp == NULL)
1376 			{
1377 				syserr("readqf: cannot open %s", e->e_df);
1378 				e->e_msgsize = -1;
1379 			}
1380 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
1381 			{
1382 				e->e_msgsize = st.st_size;
1383 				e->e_dfdev = st.st_dev;
1384 				e->e_dfino = st.st_ino;
1385 			}
1386 			break;
1387 
1388 		  case 'T':		/* init time */
1389 			e->e_ctime = atol(&bp[1]);
1390 			break;
1391 
1392 		  case 'I':		/* data file's inode number */
1393 			if (e->e_dfino == -1)
1394 				e->e_dfino = atol(&buf[1]);
1395 			break;
1396 
1397 		  case 'K':		/* time of last deliver attempt */
1398 			e->e_dtime = atol(&buf[1]);
1399 			break;
1400 
1401 		  case 'N':		/* number of delivery attempts */
1402 			e->e_ntries = atoi(&buf[1]);
1403 			break;
1404 
1405 		  case 'P':		/* message priority */
1406 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
1407 			break;
1408 
1409 		  case 'F':		/* flag bits */
1410 			for (p = &bp[1]; *p != '\0'; p++)
1411 			{
1412 				switch (*p)
1413 				{
1414 				  case 'w':	/* warning sent */
1415 					e->e_flags |= EF_WARNING;
1416 					break;
1417 
1418 				  case 'r':	/* response */
1419 					e->e_flags |= EF_RESPONSE;
1420 					break;
1421 
1422 				  case '8':	/* has 8 bit data */
1423 					e->e_flags |= EF_HAS8BIT;
1424 					break;
1425 				}
1426 			}
1427 			break;
1428 
1429 		  case 'O':		/* original MTS from ESMTP */
1430 			e->e_omts = newstr(&bp[1]);
1431 			break;
1432 
1433 		  case 'Z':		/* original envelope id from ESMTP */
1434 			e->e_envid = newstr(&bp[1]);
1435 			break;
1436 
1437 		  case '$':		/* define macro */
1438 			define(bp[1], newstr(&bp[2]), e);
1439 			break;
1440 
1441 		  case '\0':		/* blank line; ignore */
1442 			break;
1443 
1444 		  default:
1445 			syserr("readqf: %s: line %d: bad line \"%s\"",
1446 				qf, LineNumber, bp);
1447 			fclose(qfp);
1448 			rename(qf, queuename(e, 'Q'));
1449 			return FALSE;
1450 		}
1451 
1452 		if (bp != buf)
1453 			free(bp);
1454 	}
1455 
1456 	/*
1457 	**  If we haven't read any lines, this queue file is empty.
1458 	**  Arrange to remove it without referencing any null pointers.
1459 	*/
1460 
1461 	if (LineNumber == 0)
1462 	{
1463 		errno = 0;
1464 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
1465 	}
1466 	return TRUE;
1467 }
1468 /*
1469 **  PRINTQUEUE -- print out a representation of the mail queue
1470 **
1471 **	Parameters:
1472 **		none.
1473 **
1474 **	Returns:
1475 **		none.
1476 **
1477 **	Side Effects:
1478 **		Prints a listing of the mail queue on the standard output.
1479 */
1480 
1481 printqueue()
1482 {
1483 	register WORK *w;
1484 	FILE *f;
1485 	int nrequests;
1486 	char buf[MAXLINE];
1487 
1488 	/*
1489 	**  Check for permission to print the queue
1490 	*/
1491 
1492 	if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
1493 	{
1494 		struct stat st;
1495 # ifdef NGROUPS
1496 		int n;
1497 		GIDSET_T gidset[NGROUPS];
1498 # endif
1499 
1500 		if (stat(QueueDir, &st) < 0)
1501 		{
1502 			syserr("Cannot stat %s", QueueDir);
1503 			return;
1504 		}
1505 # ifdef NGROUPS
1506 		n = getgroups(NGROUPS, gidset);
1507 		while (--n >= 0)
1508 		{
1509 			if (gidset[n] == st.st_gid)
1510 				break;
1511 		}
1512 		if (n < 0)
1513 # else
1514 		if (RealGid != st.st_gid)
1515 # endif
1516 		{
1517 			usrerr("510 You are not permitted to see the queue");
1518 			setstat(EX_NOPERM);
1519 			return;
1520 		}
1521 	}
1522 
1523 	/*
1524 	**  Read and order the queue.
1525 	*/
1526 
1527 	nrequests = orderq(TRUE);
1528 
1529 	/*
1530 	**  Print the work list that we have read.
1531 	*/
1532 
1533 	/* first see if there is anything */
1534 	if (nrequests <= 0)
1535 	{
1536 		printf("Mail queue is empty\n");
1537 		return;
1538 	}
1539 
1540 	CurrentLA = getla();	/* get load average */
1541 
1542 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1543 	if (nrequests > QUEUESIZE)
1544 		printf(", only %d printed", QUEUESIZE);
1545 	if (Verbose)
1546 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1547 	else
1548 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1549 	for (w = WorkQ; w != NULL; w = w->w_next)
1550 	{
1551 		struct stat st;
1552 		auto time_t submittime = 0;
1553 		long dfsize = -1;
1554 		int flags = 0;
1555 		int qfver;
1556 		char message[MAXLINE];
1557 		char bodytype[MAXNAME];
1558 
1559 		printf("%8s", w->w_name + 2);
1560 		f = fopen(w->w_name, "r");
1561 		if (f == NULL)
1562 		{
1563 			printf(" (job completed)\n");
1564 			errno = 0;
1565 			continue;
1566 		}
1567 		if (w->w_lock)
1568 			printf("*");
1569 		else if (shouldqueue(w->w_pri, w->w_ctime))
1570 			printf("X");
1571 		else
1572 			printf(" ");
1573 		errno = 0;
1574 
1575 		message[0] = bodytype[0] = '\0';
1576 		qfver = 0;
1577 		while (fgets(buf, sizeof buf, f) != NULL)
1578 		{
1579 			register int i;
1580 			register char *p;
1581 
1582 			fixcrlf(buf, TRUE);
1583 			switch (buf[0])
1584 			{
1585 			  case 'V':	/* queue file version */
1586 				qfver = atoi(&buf[1]);
1587 				break;
1588 
1589 			  case 'M':	/* error message */
1590 				if ((i = strlen(&buf[1])) >= sizeof message)
1591 					i = sizeof message - 1;
1592 				bcopy(&buf[1], message, i);
1593 				message[i] = '\0';
1594 				break;
1595 
1596 			  case 'B':	/* body type */
1597 				if ((i = strlen(&buf[1])) >= sizeof bodytype)
1598 					i = sizeof bodytype - 1;
1599 				bcopy(&buf[1], bodytype, i);
1600 				bodytype[i] = '\0';
1601 				break;
1602 
1603 			  case 'S':	/* sender name */
1604 				if (Verbose)
1605 					printf("%8ld %10ld%c%.12s %.38s",
1606 					    dfsize,
1607 					    w->w_pri,
1608 					    bitset(EF_WARNING, flags) ? '+' : ' ',
1609 					    ctime(&submittime) + 4,
1610 					    &buf[1]);
1611 				else
1612 					printf("%8ld %.16s %.45s", dfsize,
1613 					    ctime(&submittime), &buf[1]);
1614 				if (message[0] != '\0' || bodytype[0] != '\0')
1615 				{
1616 					printf("\n    %10.10s", bodytype);
1617 					if (message[0] != '\0')
1618 						printf("   (%.60s)", message);
1619 				}
1620 				break;
1621 
1622 			  case 'C':	/* controlling user */
1623 				if (Verbose)
1624 					printf("\n\t\t\t\t      (---%.34s---)",
1625 						&buf[1]);
1626 				break;
1627 
1628 			  case 'R':	/* recipient name */
1629 				p = &buf[1];
1630 				if (qfver >= 1)
1631 				{
1632 					p = strchr(p, ':');
1633 					if (p == NULL)
1634 						break;
1635 					p++;
1636 				}
1637 				if (Verbose)
1638 					printf("\n\t\t\t\t\t  %.38s", p);
1639 				else
1640 					printf("\n\t\t\t\t   %.45s", p);
1641 				break;
1642 
1643 			  case 'T':	/* creation time */
1644 				submittime = atol(&buf[1]);
1645 				break;
1646 
1647 			  case 'D':	/* data file name */
1648 				if (stat(&buf[1], &st) >= 0)
1649 					dfsize = st.st_size;
1650 				break;
1651 
1652 			  case 'F':	/* flag bits */
1653 				for (p = &buf[1]; *p != '\0'; p++)
1654 				{
1655 					switch (*p)
1656 					{
1657 					  case 'w':
1658 						flags |= EF_WARNING;
1659 						break;
1660 					}
1661 				}
1662 			}
1663 		}
1664 		if (submittime == (time_t) 0)
1665 			printf(" (no control file)");
1666 		printf("\n");
1667 		(void) fclose(f);
1668 	}
1669 }
1670 
1671 # endif /* QUEUE */
1672 /*
1673 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1674 **
1675 **	Assigns an id code if one does not already exist.
1676 **	This code is very careful to avoid trashing existing files
1677 **	under any circumstances.
1678 **
1679 **	Parameters:
1680 **		e -- envelope to build it in/from.
1681 **		type -- the file type, used as the first character
1682 **			of the file name.
1683 **
1684 **	Returns:
1685 **		a pointer to the new file name (in a static buffer).
1686 **
1687 **	Side Effects:
1688 **		If no id code is already assigned, queuename will
1689 **		assign an id code, create a qf file, and leave a
1690 **		locked, open-for-write file pointer in the envelope.
1691 */
1692 
1693 char *
1694 queuename(e, type)
1695 	register ENVELOPE *e;
1696 	int type;
1697 {
1698 	static int pid = -1;
1699 	static char c0;
1700 	static char c1;
1701 	static char c2;
1702 	time_t now;
1703 	struct tm *tm;
1704 	static char buf[MAXNAME];
1705 
1706 	if (e->e_id == NULL)
1707 	{
1708 		char qf[20];
1709 
1710 		/* find a unique id */
1711 		if (pid != getpid())
1712 		{
1713 			/* new process -- start back at "AA" */
1714 			pid = getpid();
1715 			now = curtime();
1716 			tm = localtime(&now);
1717 			c0 = 'A' + tm->tm_hour;
1718 			c1 = 'A';
1719 			c2 = 'A' - 1;
1720 		}
1721 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
1722 
1723 		while (c1 < '~' || c2 < 'Z')
1724 		{
1725 			int i;
1726 
1727 			if (c2 >= 'Z')
1728 			{
1729 				c1++;
1730 				c2 = 'A' - 1;
1731 			}
1732 			qf[3] = c1;
1733 			qf[4] = ++c2;
1734 			if (tTd(7, 20))
1735 				printf("queuename: trying \"%s\"\n", qf);
1736 
1737 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1738 			if (i < 0)
1739 			{
1740 				if (errno == EEXIST)
1741 					continue;
1742 				syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1743 					qf, QueueDir, geteuid());
1744 				exit(EX_UNAVAILABLE);
1745 			}
1746 			if (lockfile(i, qf, NULL, LOCK_EX|LOCK_NB))
1747 			{
1748 				e->e_lockfp = fdopen(i, "w");
1749 				break;
1750 			}
1751 
1752 			/* a reader got the file; abandon it and try again */
1753 			(void) close(i);
1754 		}
1755 		if (c1 >= '~' && c2 >= 'Z')
1756 		{
1757 			syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1758 				qf, QueueDir, geteuid());
1759 			exit(EX_OSERR);
1760 		}
1761 		e->e_id = newstr(&qf[2]);
1762 		define('i', e->e_id, e);
1763 		if (tTd(7, 1))
1764 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1765 		if (tTd(7, 9))
1766 		{
1767 			printf("  lockfd=");
1768 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
1769 		}
1770 # ifdef LOG
1771 		if (LogLevel > 93)
1772 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1773 # endif /* LOG */
1774 	}
1775 
1776 	if (type == '\0')
1777 		return (NULL);
1778 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1779 	if (tTd(7, 2))
1780 		printf("queuename: %s\n", buf);
1781 	return (buf);
1782 }
1783 /*
1784 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1785 **
1786 **	Parameters:
1787 **		e -- the envelope to unlock.
1788 **
1789 **	Returns:
1790 **		none
1791 **
1792 **	Side Effects:
1793 **		unlocks the queue for `e'.
1794 */
1795 
1796 unlockqueue(e)
1797 	ENVELOPE *e;
1798 {
1799 	if (tTd(51, 4))
1800 		printf("unlockqueue(%s)\n", e->e_id);
1801 
1802 	/* if there is a lock file in the envelope, close it */
1803 	if (e->e_lockfp != NULL)
1804 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
1805 	e->e_lockfp = NULL;
1806 
1807 	/* don't create a queue id if we don't already have one */
1808 	if (e->e_id == NULL)
1809 		return;
1810 
1811 	/* remove the transcript */
1812 # ifdef LOG
1813 	if (LogLevel > 87)
1814 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1815 # endif /* LOG */
1816 	if (!tTd(51, 104))
1817 		xunlink(queuename(e, 'x'));
1818 
1819 }
1820 /*
1821 **  SETCTLUSER -- create a controlling address
1822 **
1823 **	Create a fake "address" given only a local login name; this is
1824 **	used as a "controlling user" for future recipient addresses.
1825 **
1826 **	Parameters:
1827 **		user -- the user name of the controlling user.
1828 **
1829 **	Returns:
1830 **		An address descriptor for the controlling user.
1831 **
1832 **	Side Effects:
1833 **		none.
1834 */
1835 
1836 ADDRESS *
1837 setctluser(user)
1838 	char *user;
1839 {
1840 	register ADDRESS *a;
1841 	struct passwd *pw;
1842 	char *p;
1843 
1844 	/*
1845 	**  See if this clears our concept of controlling user.
1846 	*/
1847 
1848 	if (user == NULL || *user == '\0')
1849 		return NULL;
1850 
1851 	/*
1852 	**  Set up addr fields for controlling user.
1853 	*/
1854 
1855 	a = (ADDRESS *) xalloc(sizeof *a);
1856 	bzero((char *) a, sizeof *a);
1857 
1858 	p = strchr(user, ':');
1859 	if (p != NULL)
1860 		*p++ = '\0';
1861 	if (*user != '\0' && (pw = getpwnam(user)) != NULL)
1862 	{
1863 		if (strcmp(pw->pw_dir, "/") == 0)
1864 			a->q_home = "";
1865 		else
1866 			a->q_home = newstr(pw->pw_dir);
1867 		a->q_uid = pw->pw_uid;
1868 		a->q_gid = pw->pw_gid;
1869 		a->q_user = newstr(user);
1870 		a->q_flags |= QGOODUID;
1871 	}
1872 	else
1873 	{
1874 		a->q_user = newstr(DefUser);
1875 	}
1876 
1877 	a->q_flags |= QPRIMARY;		/* flag as a "ctladdr"  */
1878 	a->q_mailer = LocalMailer;
1879 	if (p == NULL)
1880 		a->q_paddr = a->q_user;
1881 	else
1882 		a->q_paddr = newstr(p);
1883 	return a;
1884 }
1885