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