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