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