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