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