xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 55019)
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.44 (Berkeley) 07/12/92 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	5.44 (Berkeley) 07/12/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 recipient addresses */
198 	lastctladdr = NULL;
199 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
200 	{
201 		if (queueall ? !bitset(QDONTSEND|QSENT, q->q_flags) :
202 			       bitset(QQUEUEUP, 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, "R%s\n", q->q_paddr);
215 			if (announce)
216 			{
217 				e->e_to = q->q_paddr;
218 				message(Arpa_Info, "queued");
219 				if (LogLevel > 4)
220 					logdelivery("queued", e);
221 				e->e_to = NULL;
222 			}
223 			if (tTd(40, 1))
224 			{
225 				printf("queueing ");
226 				printaddr(q, FALSE);
227 			}
228 		}
229 	}
230 
231 	/* output list of error recipients */
232 	for (q = e->e_errorqueue; q != NULL; q = q->q_next)
233 	{
234 		if (!bitset(QDONTSEND, q->q_flags))
235 		{
236 			ADDRESS *ctladdr;
237 
238 			ctladdr = getctladdr(q);
239 			if (ctladdr == NULL && q->q_alias != NULL)
240 				ctladdr = nullctladdr;
241 			if (ctladdr != lastctladdr)
242 			{
243 				printctladdr(ctladdr, tfp);
244 				lastctladdr = ctladdr;
245 			}
246 			fprintf(tfp, "E%s\n", q->q_paddr);
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 runqueue(forkflag, e)
373 	bool forkflag;
374 	register ENVELOPE *e;
375 {
376 	extern bool shouldqueue();
377 
378 	/*
379 	**  If no work will ever be selected, don't even bother reading
380 	**  the queue.
381 	*/
382 
383 	CurrentLA = getla();	/* get load average */
384 
385 	if (shouldqueue(-100000000L))
386 	{
387 		if (Verbose)
388 			printf("Skipping queue run -- load average too high\n");
389 
390 		if (forkflag)
391 			return;
392 		finis();
393 	}
394 
395 	/*
396 	**  See if we want to go off and do other useful work.
397 	*/
398 
399 	if (forkflag)
400 	{
401 		int pid;
402 
403 		pid = dofork();
404 		if (pid != 0)
405 		{
406 			extern void reapchild();
407 
408 			/* parent -- pick up intermediate zombie */
409 #ifndef SIGCHLD
410 			(void) waitfor(pid);
411 #else SIGCHLD
412 			(void) signal(SIGCHLD, reapchild);
413 #endif SIGCHLD
414 			if (QueueIntvl != 0)
415 				(void) setevent(QueueIntvl, runqueue, TRUE);
416 			return;
417 		}
418 		/* child -- double fork */
419 #ifndef SIGCHLD
420 		if (fork() != 0)
421 			exit(EX_OK);
422 #else SIGCHLD
423 		(void) signal(SIGCHLD, SIG_DFL);
424 #endif SIGCHLD
425 	}
426 
427 	setproctitle("running queue: %s", QueueDir);
428 
429 # ifdef LOG
430 	if (LogLevel > 11)
431 		syslog(LOG_DEBUG, "runqueue %s, pid=%d", QueueDir, getpid());
432 # endif LOG
433 
434 	/*
435 	**  Release any resources used by the daemon code.
436 	*/
437 
438 # ifdef DAEMON
439 	clrdaemon();
440 # endif DAEMON
441 
442 	/*
443 	**  Make sure the alias database is open.
444 	*/
445 
446 	initaliases(AliasFile, FALSE, e);
447 
448 	/*
449 	**  Start making passes through the queue.
450 	**	First, read and sort the entire queue.
451 	**	Then, process the work in that order.
452 	**		But if you take too long, start over.
453 	*/
454 
455 	/* order the existing work requests */
456 	(void) orderq(FALSE);
457 
458 	/* process them once at a time */
459 	while (WorkQ != NULL)
460 	{
461 		WORK *w = WorkQ;
462 
463 		WorkQ = WorkQ->w_next;
464 		dowork(w, e);
465 		free(w->w_name);
466 		free((char *) w);
467 	}
468 
469 	/* exit without the usual cleanup */
470 	exit(ExitStat);
471 }
472 /*
473 **  ORDERQ -- order the work queue.
474 **
475 **	Parameters:
476 **		doall -- if set, include everything in the queue (even
477 **			the jobs that cannot be run because the load
478 **			average is too high).  Otherwise, exclude those
479 **			jobs.
480 **
481 **	Returns:
482 **		The number of request in the queue (not necessarily
483 **		the number of requests in WorkQ however).
484 **
485 **	Side Effects:
486 **		Sets WorkQ to the queue of available work, in order.
487 */
488 
489 # define NEED_P		001
490 # define NEED_T		002
491 
492 orderq(doall)
493 	bool doall;
494 {
495 	register struct direct *d;
496 	register WORK *w;
497 	DIR *f;
498 	register int i;
499 	WORK wlist[QUEUESIZE+1];
500 	int wn = -1;
501 	extern workcmpf();
502 
503 	/* clear out old WorkQ */
504 	for (w = WorkQ; w != NULL; )
505 	{
506 		register WORK *nw = w->w_next;
507 
508 		WorkQ = nw;
509 		free(w->w_name);
510 		free((char *) w);
511 		w = nw;
512 	}
513 
514 	/* open the queue directory */
515 	f = opendir(".");
516 	if (f == NULL)
517 	{
518 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
519 		return (0);
520 	}
521 
522 	/*
523 	**  Read the work directory.
524 	*/
525 
526 	while ((d = readdir(f)) != NULL)
527 	{
528 		FILE *cf;
529 		char lbuf[MAXNAME];
530 
531 		/* is this an interesting entry? */
532 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
533 			continue;
534 
535 		/* yes -- open control file (if not too many files) */
536 		if (++wn >= QUEUESIZE)
537 			continue;
538 		cf = fopen(d->d_name, "r");
539 		if (cf == NULL)
540 		{
541 			/* this may be some random person sending hir msgs */
542 			/* syserr("orderq: cannot open %s", cbuf); */
543 			if (tTd(41, 2))
544 				printf("orderq: cannot open %s (%d)\n",
545 					d->d_name, errno);
546 			errno = 0;
547 			wn--;
548 			continue;
549 		}
550 		w = &wlist[wn];
551 		w->w_name = newstr(d->d_name);
552 
553 		/* make sure jobs in creation don't clog queue */
554 		w->w_pri = 0x7fffffff;
555 		w->w_ctime = 0;
556 
557 		/* extract useful information */
558 		i = NEED_P | NEED_T;
559 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
560 		{
561 			extern long atol();
562 
563 			switch (lbuf[0])
564 			{
565 			  case 'P':
566 				w->w_pri = atol(&lbuf[1]);
567 				i &= ~NEED_P;
568 				break;
569 
570 			  case 'T':
571 				w->w_ctime = atol(&lbuf[1]);
572 				i &= ~NEED_T;
573 				break;
574 			}
575 		}
576 		(void) fclose(cf);
577 
578 		if (!doall && shouldqueue(w->w_pri))
579 		{
580 			/* don't even bother sorting this job in */
581 			wn--;
582 		}
583 	}
584 	(void) closedir(f);
585 	wn++;
586 
587 	/*
588 	**  Sort the work directory.
589 	*/
590 
591 	qsort((char *) wlist, min(wn, QUEUESIZE), sizeof *wlist, workcmpf);
592 
593 	/*
594 	**  Convert the work list into canonical form.
595 	**	Should be turning it into a list of envelopes here perhaps.
596 	*/
597 
598 	WorkQ = NULL;
599 	for (i = min(wn, QUEUESIZE); --i >= 0; )
600 	{
601 		w = (WORK *) xalloc(sizeof *w);
602 		w->w_name = wlist[i].w_name;
603 		w->w_pri = wlist[i].w_pri;
604 		w->w_ctime = wlist[i].w_ctime;
605 		w->w_next = WorkQ;
606 		WorkQ = w;
607 	}
608 
609 	if (tTd(40, 1))
610 	{
611 		for (w = WorkQ; w != NULL; w = w->w_next)
612 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
613 	}
614 
615 	return (wn);
616 }
617 /*
618 **  WORKCMPF -- compare function for ordering work.
619 **
620 **	Parameters:
621 **		a -- the first argument.
622 **		b -- the second argument.
623 **
624 **	Returns:
625 **		-1 if a < b
626 **		 0 if a == b
627 **		+1 if a > b
628 **
629 **	Side Effects:
630 **		none.
631 */
632 
633 workcmpf(a, b)
634 	register WORK *a;
635 	register WORK *b;
636 {
637 	long pa = a->w_pri + a->w_ctime;
638 	long pb = b->w_pri + b->w_ctime;
639 
640 	if (pa == pb)
641 		return (0);
642 	else if (pa > pb)
643 		return (1);
644 	else
645 		return (-1);
646 }
647 /*
648 **  DOWORK -- do a work request.
649 **
650 **	Parameters:
651 **		w -- the work request to be satisfied.
652 **
653 **	Returns:
654 **		none.
655 **
656 **	Side Effects:
657 **		The work request is satisfied if possible.
658 */
659 
660 dowork(w, e)
661 	register WORK *w;
662 	register ENVELOPE *e;
663 {
664 	register int i;
665 	extern bool shouldqueue();
666 	extern bool readqf();
667 
668 	if (tTd(40, 1))
669 		printf("dowork: %s pri %ld\n", w->w_name, w->w_pri);
670 
671 	/*
672 	**  Ignore jobs that are too expensive for the moment.
673 	*/
674 
675 	if (shouldqueue(w->w_pri))
676 	{
677 		if (Verbose)
678 			printf("\nSkipping %s\n", w->w_name + 2);
679 		return;
680 	}
681 
682 	/*
683 	**  Fork for work.
684 	*/
685 
686 	if (ForkQueueRuns)
687 	{
688 		i = fork();
689 		if (i < 0)
690 		{
691 			syserr("dowork: cannot fork");
692 			return;
693 		}
694 	}
695 	else
696 	{
697 		i = 0;
698 	}
699 
700 	if (i == 0)
701 	{
702 		/*
703 		**  CHILD
704 		**	Lock the control file to avoid duplicate deliveries.
705 		**		Then run the file as though we had just read it.
706 		**	We save an idea of the temporary name so we
707 		**		can recover on interrupt.
708 		*/
709 
710 		/* set basic modes, etc. */
711 		(void) alarm(0);
712 		clearenvelope(e, FALSE);
713 		QueueRun = TRUE;
714 		ErrorMode = EM_MAIL;
715 		e->e_id = &w->w_name[2];
716 # ifdef LOG
717 		if (LogLevel > 11)
718 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
719 			       getpid());
720 # endif LOG
721 
722 		/* don't use the headers from sendmail.cf... */
723 		e->e_header = NULL;
724 
725 		/* read the queue control file -- return if locked */
726 		if (!readqf(e))
727 		{
728 			if (ForkQueueRuns)
729 				exit(EX_OK);
730 			else
731 				return;
732 		}
733 
734 		e->e_flags |= EF_INQUEUE;
735 		eatheader(e);
736 
737 		/* do the delivery */
738 		if (!bitset(EF_FATALERRS, e->e_flags))
739 			sendall(e, SM_DELIVER);
740 
741 		/* finish up and exit */
742 		if (ForkQueueRuns)
743 			finis();
744 		else
745 			dropenvelope(e);
746 	}
747 	else
748 	{
749 		/*
750 		**  Parent -- pick up results.
751 		*/
752 
753 		errno = 0;
754 		(void) waitfor(i);
755 	}
756 }
757 /*
758 **  READQF -- read queue file and set up environment.
759 **
760 **	Parameters:
761 **		e -- the envelope of the job to run.
762 **
763 **	Returns:
764 **		TRUE if it successfully read the queue file.
765 **		FALSE otherwise.
766 **
767 **	Side Effects:
768 **		The queue file is returned locked.
769 */
770 
771 bool
772 readqf(e)
773 	register ENVELOPE *e;
774 {
775 	char *qf;
776 	register FILE *qfp;
777 	ADDRESS *ctladdr;
778 	char buf[MAXFIELD];
779 	extern char *fgetfolded();
780 	extern long atol();
781 	extern ADDRESS *setctluser();
782 # ifdef LOCKF
783 	struct flock lfd;
784 # endif
785 
786 	/*
787 	**  Read and process the file.
788 	*/
789 
790 	qf = queuename(e, 'q');
791 	qfp = fopen(qf, "r+");
792 	if (qfp == NULL)
793 	{
794 		if (errno != ENOENT)
795 			syserr("readqf: no control file %s", qf);
796 		return FALSE;
797 	}
798 
799 # ifdef LOCKF
800 	lfd.l_type = F_WRLCK;
801 	lfd.l_whence = lfd.l_start = lfd.l_len = 0;
802 	if (fcntl(fileno(qfp), F_SETLK, &lfd) < 0)
803 # else
804 	if (flock(fileno(qfp), LOCK_EX|LOCK_NB) < 0)
805 # endif
806 	{
807 		/* being processed by another queuer */
808 		if (Verbose)
809 			printf("%s: locked\n", e->e_id);
810 # ifdef LOG
811 		if (LogLevel > 9)
812 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
813 # endif LOG
814 		(void) fclose(qfp);
815 		return FALSE;
816 	}
817 
818 	/* save this lock */
819 	e->e_lockfp = qfp;
820 
821 	/* do basic system initialization */
822 	initsys(e);
823 
824 	FileName = qf;
825 	LineNumber = 0;
826 	if (Verbose)
827 		printf("\nRunning %s\n", e->e_id);
828 	ctladdr = NULL;
829 	while (fgetfolded(buf, sizeof buf, qfp) != NULL)
830 	{
831 		if (tTd(40, 4))
832 			printf("+++++ %s\n", buf);
833 		switch (buf[0])
834 		{
835 		  case 'C':		/* specify controlling user */
836 			ctladdr = setctluser(&buf[1]);
837 			break;
838 
839 		  case 'R':		/* specify recipient */
840 			sendtolist(&buf[1], ctladdr, &e->e_sendqueue, e);
841 			break;
842 
843 		  case 'E':		/* specify error recipient */
844 			sendtolist(&buf[1], ctladdr, &e->e_errorqueue, e);
845 			break;
846 
847 		  case 'H':		/* header */
848 			(void) chompheader(&buf[1], FALSE, e);
849 			break;
850 
851 		  case 'M':		/* message */
852 			e->e_message = newstr(&buf[1]);
853 			break;
854 
855 		  case 'S':		/* sender */
856 			setsender(newstr(&buf[1]), e);
857 			break;
858 
859 		  case 'D':		/* data file name */
860 			e->e_df = newstr(&buf[1]);
861 			e->e_dfp = fopen(e->e_df, "r");
862 			if (e->e_dfp == NULL)
863 				syserr("readqf: cannot open %s", e->e_df);
864 			break;
865 
866 		  case 'T':		/* init time */
867 			e->e_ctime = atol(&buf[1]);
868 			break;
869 
870 		  case 'P':		/* message priority */
871 			e->e_msgpriority = atol(&buf[1]) + WkTimeFact;
872 			break;
873 
874 		  case '$':		/* define macro */
875 			define(buf[1], newstr(&buf[2]), e);
876 			break;
877 
878 		  case '\0':		/* blank line; ignore */
879 			break;
880 
881 		  default:
882 			syserr("readqf(%s:%d): bad line \"%s\"", e->e_id,
883 				LineNumber, buf);
884 			break;
885 		}
886 	}
887 
888 	FileName = NULL;
889 
890 	/*
891 	**  If we haven't read any lines, this queue file is empty.
892 	**  Arrange to remove it without referencing any null pointers.
893 	*/
894 
895 	if (LineNumber == 0)
896 	{
897 		errno = 0;
898 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
899 	}
900 	return TRUE;
901 }
902 /*
903 **  PRINTQUEUE -- print out a representation of the mail queue
904 **
905 **	Parameters:
906 **		none.
907 **
908 **	Returns:
909 **		none.
910 **
911 **	Side Effects:
912 **		Prints a listing of the mail queue on the standard output.
913 */
914 
915 printqueue()
916 {
917 	register WORK *w;
918 	FILE *f;
919 	int nrequests;
920 	char buf[MAXLINE];
921 
922 	/*
923 	**  Read and order the queue.
924 	*/
925 
926 	nrequests = orderq(TRUE);
927 
928 	/*
929 	**  Print the work list that we have read.
930 	*/
931 
932 	/* first see if there is anything */
933 	if (nrequests <= 0)
934 	{
935 		printf("Mail queue is empty\n");
936 		return;
937 	}
938 
939 	CurrentLA = getla();	/* get load average */
940 
941 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
942 	if (nrequests > QUEUESIZE)
943 		printf(", only %d printed", QUEUESIZE);
944 	if (Verbose)
945 		printf(")\n--QID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
946 	else
947 		printf(")\n--QID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
948 	for (w = WorkQ; w != NULL; w = w->w_next)
949 	{
950 		struct stat st;
951 		auto time_t submittime = 0;
952 		long dfsize = -1;
953 		char message[MAXLINE];
954 # ifdef LOCKF
955 		struct flock lfd;
956 # endif
957 		extern bool shouldqueue();
958 
959 		f = fopen(w->w_name, "r");
960 		if (f == NULL)
961 		{
962 			errno = 0;
963 			continue;
964 		}
965 		printf("%7s", w->w_name + 2);
966 # ifdef LOCKF
967 		lfd.l_type = F_RDLCK;
968 		lfd.l_whence = lfd.l_start = lfd.l_len = 0;
969 		if (fcntl(fileno(f), F_GETLK, &lfd) < 0 || lfd.l_type != F_UNLCK)
970 # else
971 		if (flock(fileno(f), LOCK_SH|LOCK_NB) < 0)
972 # endif
973 			printf("*");
974 		else if (shouldqueue(w->w_pri))
975 			printf("X");
976 		else
977 			printf(" ");
978 		errno = 0;
979 
980 		message[0] = '\0';
981 		while (fgets(buf, sizeof buf, f) != NULL)
982 		{
983 			register int i;
984 
985 			fixcrlf(buf, TRUE);
986 			switch (buf[0])
987 			{
988 			  case 'M':	/* error message */
989 				if ((i = strlen(&buf[1])) >= sizeof message)
990 					i = sizeof message;
991 				bcopy(&buf[1], message, i);
992 				message[i] = '\0';
993 				break;
994 
995 			  case 'S':	/* sender name */
996 				if (Verbose)
997 					printf("%8ld %10ld %.12s %.38s", dfsize,
998 					    w->w_pri, ctime(&submittime) + 4,
999 					    &buf[1]);
1000 				else
1001 					printf("%8ld %.16s %.45s", dfsize,
1002 					    ctime(&submittime), &buf[1]);
1003 				if (message[0] != '\0')
1004 					printf("\n\t\t (%.60s)", message);
1005 				break;
1006 
1007 			  case 'C':	/* controlling user */
1008 				if (Verbose)
1009 					printf("\n\t\t\t\t     (---%.34s---)", &buf[1]);
1010 				break;
1011 
1012 			  case 'R':	/* recipient name */
1013 				if (Verbose)
1014 					printf("\n\t\t\t\t\t %.38s", &buf[1]);
1015 				else
1016 					printf("\n\t\t\t\t  %.45s", &buf[1]);
1017 				break;
1018 
1019 			  case 'T':	/* creation time */
1020 				submittime = atol(&buf[1]);
1021 				break;
1022 
1023 			  case 'D':	/* data file name */
1024 				if (stat(&buf[1], &st) >= 0)
1025 					dfsize = st.st_size;
1026 				break;
1027 			}
1028 		}
1029 		if (submittime == (time_t) 0)
1030 			printf(" (no control file)");
1031 		printf("\n");
1032 		(void) fclose(f);
1033 	}
1034 }
1035 
1036 # endif QUEUE
1037 /*
1038 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1039 **
1040 **	Assigns an id code if one does not already exist.
1041 **	This code is very careful to avoid trashing existing files
1042 **	under any circumstances.
1043 **
1044 **	Parameters:
1045 **		e -- envelope to build it in/from.
1046 **		type -- the file type, used as the first character
1047 **			of the file name.
1048 **
1049 **	Returns:
1050 **		a pointer to the new file name (in a static buffer).
1051 **
1052 **	Side Effects:
1053 **		If no id code is already assigned, queuename will
1054 **		assign an id code, create a qf file, and leave a
1055 **		locked, open-for-write file pointer in the envelope.
1056 */
1057 
1058 char *
1059 queuename(e, type)
1060 	register ENVELOPE *e;
1061 	char type;
1062 {
1063 	static char buf[MAXNAME];
1064 	static int pid = -1;
1065 	char c1 = 'A';
1066 	char c2 = 'A';
1067 
1068 	if (e->e_id == NULL)
1069 	{
1070 		char qf[20];
1071 
1072 		/* find a unique id */
1073 		if (pid != getpid())
1074 		{
1075 			/* new process -- start back at "AA" */
1076 			pid = getpid();
1077 			c1 = 'A';
1078 			c2 = 'A' - 1;
1079 		}
1080 		(void) sprintf(qf, "qfAA%05d", pid);
1081 
1082 		while (c1 < '~' || c2 < 'Z')
1083 		{
1084 			int i;
1085 # ifdef LOCKF
1086 			struct flock lfd;
1087 # endif
1088 
1089 			if (c2 >= 'Z')
1090 			{
1091 				c1++;
1092 				c2 = 'A' - 1;
1093 			}
1094 			qf[2] = c1;
1095 			qf[3] = ++c2;
1096 			if (tTd(7, 20))
1097 				printf("queuename: trying \"%s\"\n", qf);
1098 
1099 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1100 			if (i < 0)
1101 			{
1102 				if (errno == EEXIST)
1103 					continue;
1104 				syserr("queuename: Cannot create \"%s\" in \"%s\"",
1105 					qf, QueueDir);
1106 				exit(EX_UNAVAILABLE);
1107 			}
1108 # ifdef LOCKF
1109 			lfd.l_type = F_WRLCK;
1110 			lfd.l_whence = lfd.l_start = lfd.l_len = 0;
1111 			if (fcntl(i, F_SETLK, &lfd) >= 0)
1112 # else
1113 			if (flock(i, LOCK_EX|LOCK_NB) >= 0)
1114 # endif
1115 			{
1116 				e->e_lockfp = fdopen(i, "w");
1117 				break;
1118 			}
1119 
1120 			/* a reader got the file; abandon it and try again */
1121 			(void) close(i);
1122 		}
1123 		if (c1 >= '~' && c2 >= 'Z')
1124 		{
1125 			syserr("queuename: Cannot create \"%s\" in \"%s\"",
1126 				qf, QueueDir);
1127 			exit(EX_OSERR);
1128 		}
1129 		e->e_id = newstr(&qf[2]);
1130 		define('i', e->e_id, e);
1131 		if (tTd(7, 1))
1132 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1133 # ifdef LOG
1134 		if (LogLevel > 16)
1135 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1136 # endif LOG
1137 	}
1138 
1139 	if (type == '\0')
1140 		return (NULL);
1141 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1142 	if (tTd(7, 2))
1143 		printf("queuename: %s\n", buf);
1144 	return (buf);
1145 }
1146 /*
1147 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1148 **
1149 **	Parameters:
1150 **		e -- the envelope to unlock.
1151 **
1152 **	Returns:
1153 **		none
1154 **
1155 **	Side Effects:
1156 **		unlocks the queue for `e'.
1157 */
1158 
1159 unlockqueue(e)
1160 	ENVELOPE *e;
1161 {
1162 	/* if there is a lock file in the envelope, close it */
1163 	if (e->e_lockfp != NULL)
1164 		fclose(e->e_lockfp);
1165 	e->e_lockfp = NULL;
1166 
1167 	/* remove the transcript */
1168 # ifdef LOG
1169 	if (LogLevel > 19)
1170 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1171 # endif LOG
1172 	if (!tTd(51, 4))
1173 		xunlink(queuename(e, 'x'));
1174 
1175 }
1176 /*
1177 **  SETCTLUSER -- create a controlling address
1178 **
1179 **	Create a fake "address" given only a local login name; this is
1180 **	used as a "controlling user" for future recipient addresses.
1181 **
1182 **	Parameters:
1183 **		user -- the user name of the controlling user.
1184 **
1185 **	Returns:
1186 **		An address descriptor for the controlling user.
1187 **
1188 **	Side Effects:
1189 **		none.
1190 */
1191 
1192 ADDRESS *
1193 setctluser(user)
1194 	char *user;
1195 {
1196 	register ADDRESS *a;
1197 	struct passwd *pw;
1198 
1199 	/*
1200 	**  See if this clears our concept of controlling user.
1201 	*/
1202 
1203 	if (user == NULL || *user == '\0')
1204 		return NULL;
1205 
1206 	/*
1207 	**  Set up addr fields for controlling user.
1208 	*/
1209 
1210 	a = (ADDRESS *) xalloc(sizeof *a);
1211 	bzero((char *) a, sizeof *a);
1212 	if ((pw = getpwnam(user)) != NULL)
1213 	{
1214 		a->q_home = newstr(pw->pw_dir);
1215 		a->q_uid = pw->pw_uid;
1216 		a->q_gid = pw->pw_gid;
1217 		a->q_ruser = newstr(user);
1218 	}
1219 	else
1220 	{
1221 		a->q_uid = DefUid;
1222 		a->q_gid = DefGid;
1223 		a->q_ruser = newstr(DefUser);
1224 	}
1225 
1226 	a->q_flags |= QGOODUID;		/* flag as a "ctladdr"  */
1227 	return a;
1228 }
1229