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