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