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