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