xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 58082)
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.14 (Berkeley) 02/20/93 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	6.14 (Berkeley) 02/20/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 		if (errno == EWOULDBLOCK)
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 		}
875 		else
876 		{
877 			syserr("%s: flock failure", e->e_id);
878 		}
879 		(void) fclose(qfp);
880 		return FALSE;
881 	}
882 
883 	/* save this lock */
884 	e->e_lockfp = qfp;
885 
886 	/* do basic system initialization */
887 	initsys(e);
888 
889 	FileName = qf;
890 	LineNumber = 0;
891 	if (Verbose)
892 		printf("\nRunning %s\n", e->e_id);
893 	ctladdr = NULL;
894 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
895 	{
896 		struct stat st;
897 
898 		if (tTd(40, 4))
899 			printf("+++++ %s\n", bp);
900 		switch (bp[0])
901 		{
902 		  case 'C':		/* specify controlling user */
903 			ctladdr = setctluser(&bp[1]);
904 			break;
905 
906 		  case 'R':		/* specify recipient */
907 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
908 			break;
909 
910 		  case 'E':		/* specify error recipient */
911 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
912 			break;
913 
914 		  case 'H':		/* header */
915 			(void) chompheader(&bp[1], FALSE, e);
916 			break;
917 
918 		  case 'M':		/* message */
919 			e->e_message = newstr(&bp[1]);
920 			break;
921 
922 		  case 'S':		/* sender */
923 			setsender(newstr(&bp[1]), e);
924 			break;
925 
926 		  case 'D':		/* data file name */
927 			e->e_df = newstr(&bp[1]);
928 			e->e_dfp = fopen(e->e_df, "r");
929 			if (e->e_dfp == NULL)
930 			{
931 				syserr("readqf: cannot open %s", e->e_df);
932 				e->e_msgsize = -1;
933 			}
934 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
935 				e->e_msgsize = st.st_size;
936 			break;
937 
938 		  case 'T':		/* init time */
939 			e->e_ctime = atol(&bp[1]);
940 			break;
941 
942 		  case 'P':		/* message priority */
943 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
944 			break;
945 
946 		  case '$':		/* define macro */
947 			define(bp[1], newstr(&bp[2]), e);
948 			break;
949 
950 		  case '\0':		/* blank line; ignore */
951 			break;
952 
953 		  default:
954 			syserr("readqf(%s:%d): bad line \"%s\"", e->e_id,
955 				LineNumber, bp);
956 			break;
957 		}
958 
959 		if (bp != buf)
960 			free(bp);
961 	}
962 
963 	FileName = NULL;
964 
965 	/*
966 	**  If we haven't read any lines, this queue file is empty.
967 	**  Arrange to remove it without referencing any null pointers.
968 	*/
969 
970 	if (LineNumber == 0)
971 	{
972 		errno = 0;
973 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
974 	}
975 	return TRUE;
976 }
977 /*
978 **  PRINTQUEUE -- print out a representation of the mail queue
979 **
980 **	Parameters:
981 **		none.
982 **
983 **	Returns:
984 **		none.
985 **
986 **	Side Effects:
987 **		Prints a listing of the mail queue on the standard output.
988 */
989 
990 printqueue()
991 {
992 	register WORK *w;
993 	FILE *f;
994 	int nrequests;
995 	char buf[MAXLINE];
996 
997 	/*
998 	**  Read and order the queue.
999 	*/
1000 
1001 	nrequests = orderq(TRUE);
1002 
1003 	/*
1004 	**  Print the work list that we have read.
1005 	*/
1006 
1007 	/* first see if there is anything */
1008 	if (nrequests <= 0)
1009 	{
1010 		printf("Mail queue is empty\n");
1011 		return;
1012 	}
1013 
1014 	CurrentLA = getla();	/* get load average */
1015 
1016 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1017 	if (nrequests > QUEUESIZE)
1018 		printf(", only %d printed", QUEUESIZE);
1019 	if (Verbose)
1020 		printf(")\n--QID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1021 	else
1022 		printf(")\n--QID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1023 	for (w = WorkQ; w != NULL; w = w->w_next)
1024 	{
1025 		struct stat st;
1026 		auto time_t submittime = 0;
1027 		long dfsize = -1;
1028 		char message[MAXLINE];
1029 # ifdef LOCKF
1030 		struct flock lfd;
1031 # endif
1032 		extern bool shouldqueue();
1033 
1034 		f = fopen(w->w_name, "r");
1035 		if (f == NULL)
1036 		{
1037 			errno = 0;
1038 			continue;
1039 		}
1040 		printf("%7s", w->w_name + 2);
1041 # ifdef LOCKF
1042 		lfd.l_type = F_RDLCK;
1043 		lfd.l_whence = lfd.l_start = lfd.l_len = 0;
1044 		if (fcntl(fileno(f), F_GETLK, &lfd) < 0 || lfd.l_type != F_UNLCK)
1045 # else
1046 		if (flock(fileno(f), LOCK_SH|LOCK_NB) < 0)
1047 # endif
1048 			printf("*");
1049 		else if (shouldqueue(w->w_pri, w->w_ctime))
1050 			printf("X");
1051 		else
1052 			printf(" ");
1053 		errno = 0;
1054 
1055 		message[0] = '\0';
1056 		while (fgets(buf, sizeof buf, f) != NULL)
1057 		{
1058 			register int i;
1059 
1060 			fixcrlf(buf, TRUE);
1061 			switch (buf[0])
1062 			{
1063 			  case 'M':	/* error message */
1064 				if ((i = strlen(&buf[1])) >= sizeof message)
1065 					i = sizeof message;
1066 				bcopy(&buf[1], message, i);
1067 				message[i] = '\0';
1068 				break;
1069 
1070 			  case 'S':	/* sender name */
1071 				if (Verbose)
1072 					printf("%8ld %10ld %.12s %.38s", dfsize,
1073 					    w->w_pri, ctime(&submittime) + 4,
1074 					    &buf[1]);
1075 				else
1076 					printf("%8ld %.16s %.45s", dfsize,
1077 					    ctime(&submittime), &buf[1]);
1078 				if (message[0] != '\0')
1079 					printf("\n\t\t (%.60s)", message);
1080 				break;
1081 
1082 			  case 'C':	/* controlling user */
1083 				if (Verbose)
1084 					printf("\n\t\t\t\t     (---%.34s---)", &buf[1]);
1085 				break;
1086 
1087 			  case 'R':	/* recipient name */
1088 				if (Verbose)
1089 					printf("\n\t\t\t\t\t %.38s", &buf[1]);
1090 				else
1091 					printf("\n\t\t\t\t  %.45s", &buf[1]);
1092 				break;
1093 
1094 			  case 'T':	/* creation time */
1095 				submittime = atol(&buf[1]);
1096 				break;
1097 
1098 			  case 'D':	/* data file name */
1099 				if (stat(&buf[1], &st) >= 0)
1100 					dfsize = st.st_size;
1101 				break;
1102 			}
1103 		}
1104 		if (submittime == (time_t) 0)
1105 			printf(" (no control file)");
1106 		printf("\n");
1107 		(void) fclose(f);
1108 	}
1109 }
1110 
1111 # endif /* QUEUE */
1112 /*
1113 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1114 **
1115 **	Assigns an id code if one does not already exist.
1116 **	This code is very careful to avoid trashing existing files
1117 **	under any circumstances.
1118 **
1119 **	Parameters:
1120 **		e -- envelope to build it in/from.
1121 **		type -- the file type, used as the first character
1122 **			of the file name.
1123 **
1124 **	Returns:
1125 **		a pointer to the new file name (in a static buffer).
1126 **
1127 **	Side Effects:
1128 **		If no id code is already assigned, queuename will
1129 **		assign an id code, create a qf file, and leave a
1130 **		locked, open-for-write file pointer in the envelope.
1131 */
1132 
1133 char *
1134 queuename(e, type)
1135 	register ENVELOPE *e;
1136 	char type;
1137 {
1138 	static char buf[MAXNAME];
1139 	static int pid = -1;
1140 	char c1 = 'A';
1141 	char c2 = 'A';
1142 
1143 	if (e->e_id == NULL)
1144 	{
1145 		char qf[20];
1146 
1147 		/* find a unique id */
1148 		if (pid != getpid())
1149 		{
1150 			/* new process -- start back at "AA" */
1151 			pid = getpid();
1152 			c1 = 'A';
1153 			c2 = 'A' - 1;
1154 		}
1155 		(void) sprintf(qf, "qfAA%05d", pid);
1156 
1157 		while (c1 < '~' || c2 < 'Z')
1158 		{
1159 			int i;
1160 # ifdef LOCKF
1161 			struct flock lfd;
1162 # endif
1163 
1164 			if (c2 >= 'Z')
1165 			{
1166 				c1++;
1167 				c2 = 'A' - 1;
1168 			}
1169 			qf[2] = c1;
1170 			qf[3] = ++c2;
1171 			if (tTd(7, 20))
1172 				printf("queuename: trying \"%s\"\n", qf);
1173 
1174 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1175 			if (i < 0)
1176 			{
1177 				if (errno == EEXIST)
1178 					continue;
1179 				syserr("queuename: Cannot create \"%s\" in \"%s\"",
1180 					qf, QueueDir);
1181 				exit(EX_UNAVAILABLE);
1182 			}
1183 # ifdef LOCKF
1184 			lfd.l_type = F_WRLCK;
1185 			lfd.l_whence = lfd.l_start = lfd.l_len = 0;
1186 			if (fcntl(i, F_SETLK, &lfd) >= 0)
1187 # else
1188 			if (flock(i, LOCK_EX|LOCK_NB) >= 0)
1189 # endif
1190 			{
1191 				e->e_lockfp = fdopen(i, "w");
1192 				break;
1193 			}
1194 
1195 			/* a reader got the file; abandon it and try again */
1196 			(void) close(i);
1197 		}
1198 		if (c1 >= '~' && c2 >= 'Z')
1199 		{
1200 			syserr("queuename: Cannot create \"%s\" in \"%s\"",
1201 				qf, QueueDir);
1202 			exit(EX_OSERR);
1203 		}
1204 		e->e_id = newstr(&qf[2]);
1205 		define('i', e->e_id, e);
1206 		if (tTd(7, 1))
1207 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1208 # ifdef LOG
1209 		if (LogLevel > 93)
1210 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1211 # endif /* LOG */
1212 	}
1213 
1214 	if (type == '\0')
1215 		return (NULL);
1216 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1217 	if (tTd(7, 2))
1218 		printf("queuename: %s\n", buf);
1219 	return (buf);
1220 }
1221 /*
1222 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1223 **
1224 **	Parameters:
1225 **		e -- the envelope to unlock.
1226 **
1227 **	Returns:
1228 **		none
1229 **
1230 **	Side Effects:
1231 **		unlocks the queue for `e'.
1232 */
1233 
1234 unlockqueue(e)
1235 	ENVELOPE *e;
1236 {
1237 	/* if there is a lock file in the envelope, close it */
1238 	if (e->e_lockfp != NULL)
1239 		fclose(e->e_lockfp);
1240 	e->e_lockfp = NULL;
1241 
1242 	/* remove the transcript */
1243 # ifdef LOG
1244 	if (LogLevel > 87)
1245 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1246 # endif /* LOG */
1247 	if (!tTd(51, 4))
1248 		xunlink(queuename(e, 'x'));
1249 
1250 }
1251 /*
1252 **  SETCTLUSER -- create a controlling address
1253 **
1254 **	Create a fake "address" given only a local login name; this is
1255 **	used as a "controlling user" for future recipient addresses.
1256 **
1257 **	Parameters:
1258 **		user -- the user name of the controlling user.
1259 **
1260 **	Returns:
1261 **		An address descriptor for the controlling user.
1262 **
1263 **	Side Effects:
1264 **		none.
1265 */
1266 
1267 ADDRESS *
1268 setctluser(user)
1269 	char *user;
1270 {
1271 	register ADDRESS *a;
1272 	struct passwd *pw;
1273 
1274 	/*
1275 	**  See if this clears our concept of controlling user.
1276 	*/
1277 
1278 	if (user == NULL || *user == '\0')
1279 		return NULL;
1280 
1281 	/*
1282 	**  Set up addr fields for controlling user.
1283 	*/
1284 
1285 	a = (ADDRESS *) xalloc(sizeof *a);
1286 	bzero((char *) a, sizeof *a);
1287 	if ((pw = getpwnam(user)) != NULL)
1288 	{
1289 		a->q_home = newstr(pw->pw_dir);
1290 		a->q_uid = pw->pw_uid;
1291 		a->q_gid = pw->pw_gid;
1292 		a->q_user = newstr(user);
1293 	}
1294 	else
1295 	{
1296 		a->q_uid = DefUid;
1297 		a->q_gid = DefGid;
1298 		a->q_user = newstr(DefUser);
1299 	}
1300 
1301 	a->q_flags |= QGOODUID;		/* flag as a "ctladdr"  */
1302 	a->q_mailer = LocalMailer;
1303 	return a;
1304 }
1305