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