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