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