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