xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 64839)
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.28 (Berkeley) 11/13/93 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	8.28 (Berkeley) 11/13/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 		else if (pid > 0)
828 		{
829 			/* parent -- clean out connection cache */
830 			mci_flush(FALSE, NULL);
831 		}
832 	}
833 	else
834 	{
835 		pid = 0;
836 	}
837 
838 	if (pid == 0)
839 	{
840 		/*
841 		**  CHILD
842 		**	Lock the control file to avoid duplicate deliveries.
843 		**		Then run the file as though we had just read it.
844 		**	We save an idea of the temporary name so we
845 		**		can recover on interrupt.
846 		*/
847 
848 		/* set basic modes, etc. */
849 		(void) alarm(0);
850 		clearenvelope(e, FALSE);
851 		e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
852 		e->e_errormode = EM_MAIL;
853 		e->e_id = id;
854 		GrabTo = UseErrorsTo = FALSE;
855 		if (forkflag)
856 		{
857 			disconnect(1, e);
858 			OpMode = MD_DELIVER;
859 		}
860 # ifdef LOG
861 		if (LogLevel > 76)
862 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
863 			       getpid());
864 # endif /* LOG */
865 
866 		/* don't use the headers from sendmail.cf... */
867 		e->e_header = NULL;
868 
869 		/* read the queue control file -- return if locked */
870 		if (!readqf(e, !requeueflag))
871 		{
872 			if (tTd(40, 4))
873 				printf("readqf(%s) failed\n", e->e_id);
874 			if (forkflag)
875 				exit(EX_OK);
876 			else
877 				return;
878 		}
879 
880 		e->e_flags |= EF_INQUEUE;
881 		eatheader(e, requeueflag);
882 
883 		if (requeueflag)
884 			queueup(e, TRUE, FALSE);
885 
886 		/* do the delivery */
887 		sendall(e, SM_DELIVER);
888 
889 		/* finish up and exit */
890 		if (forkflag)
891 			finis();
892 		else
893 			dropenvelope(e);
894 	}
895 	e->e_id = NULL;
896 	return pid;
897 }
898 /*
899 **  READQF -- read queue file and set up environment.
900 **
901 **	Parameters:
902 **		e -- the envelope of the job to run.
903 **		announcefile -- if set, announce the name of the queue
904 **			file in error messages.
905 **
906 **	Returns:
907 **		TRUE if it successfully read the queue file.
908 **		FALSE otherwise.
909 **
910 **	Side Effects:
911 **		The queue file is returned locked.
912 */
913 
914 bool
915 readqf(e, announcefile)
916 	register ENVELOPE *e;
917 	bool announcefile;
918 {
919 	register FILE *qfp;
920 	ADDRESS *ctladdr;
921 	struct stat st;
922 	char *bp;
923 	char qf[20];
924 	char buf[MAXLINE];
925 	extern long atol();
926 	extern ADDRESS *setctluser();
927 
928 	/*
929 	**  Read and process the file.
930 	*/
931 
932 	strcpy(qf, queuename(e, 'q'));
933 	qfp = fopen(qf, "r+");
934 	if (qfp == NULL)
935 	{
936 		if (tTd(40, 8))
937 			printf("readqf(%s): fopen failure (%s)\n",
938 				qf, errstring(errno));
939 		if (errno != ENOENT)
940 			syserr("readqf: no control file %s", qf);
941 		return FALSE;
942 	}
943 
944 	if (!lockfile(fileno(qfp), qf, NULL, LOCK_EX|LOCK_NB))
945 	{
946 		/* being processed by another queuer */
947 		if (tTd(40, 8))
948 			printf("readqf(%s): locked\n", qf);
949 		if (Verbose)
950 			printf("%s: locked\n", e->e_id);
951 # ifdef LOG
952 		if (LogLevel > 19)
953 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
954 # endif /* LOG */
955 		(void) fclose(qfp);
956 		return FALSE;
957 	}
958 
959 	/*
960 	**  Check the queue file for plausibility to avoid attacks.
961 	*/
962 
963 	if (fstat(fileno(qfp), &st) < 0)
964 	{
965 		/* must have been being processed by someone else */
966 		if (tTd(40, 8))
967 			printf("readqf(%s): fstat failure (%s)\n",
968 				qf, errstring(errno));
969 		fclose(qfp);
970 		return FALSE;
971 	}
972 
973 	if (st.st_uid != geteuid())
974 	{
975 # ifdef LOG
976 		if (LogLevel > 0)
977 		{
978 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
979 				e->e_id, st.st_uid, st.st_mode);
980 		}
981 # endif /* LOG */
982 		if (tTd(40, 8))
983 			printf("readqf(%s): bogus file\n", qf);
984 		rename(qf, queuename(e, 'Q'));
985 		fclose(qfp);
986 		return FALSE;
987 	}
988 
989 	if (st.st_size == 0)
990 	{
991 		/* must be a bogus file -- just remove it */
992 		(void) unlink(qf);
993 		fclose(qfp);
994 		return FALSE;
995 	}
996 
997 	if (st.st_nlink == 0)
998 	{
999 		/*
1000 		**  Race condition -- we got a file just as it was being
1001 		**  unlinked.  Just assume it is zero length.
1002 		*/
1003 
1004 		fclose(qfp);
1005 		return FALSE;
1006 	}
1007 
1008 	/* good file -- save this lock */
1009 	e->e_lockfp = qfp;
1010 
1011 	/* do basic system initialization */
1012 	initsys(e);
1013 
1014 	if (announcefile)
1015 		FileName = qf;
1016 	LineNumber = 0;
1017 	e->e_flags |= EF_GLOBALERRS;
1018 	OpMode = MD_DELIVER;
1019 	if (Verbose)
1020 		printf("\nRunning %s\n", e->e_id);
1021 	ctladdr = NULL;
1022 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
1023 	{
1024 		register char *p;
1025 		struct stat st;
1026 
1027 		if (tTd(40, 4))
1028 			printf("+++++ %s\n", bp);
1029 		switch (bp[0])
1030 		{
1031 		  case 'C':		/* specify controlling user */
1032 			ctladdr = setctluser(&bp[1]);
1033 			break;
1034 
1035 		  case 'R':		/* specify recipient */
1036 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
1037 			break;
1038 
1039 		  case 'E':		/* specify error recipient */
1040 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
1041 			break;
1042 
1043 		  case 'H':		/* header */
1044 			(void) chompheader(&bp[1], FALSE, e);
1045 			break;
1046 
1047 		  case 'M':		/* message */
1048 			/* ignore this; we want a new message next time */
1049 			break;
1050 
1051 		  case 'S':		/* sender */
1052 			setsender(newstr(&bp[1]), e, NULL, TRUE);
1053 			break;
1054 
1055 		  case 'B':		/* body type */
1056 			e->e_bodytype = newstr(&bp[1]);
1057 			break;
1058 
1059 		  case 'D':		/* data file name */
1060 			e->e_df = newstr(&bp[1]);
1061 			e->e_dfp = fopen(e->e_df, "r");
1062 			if (e->e_dfp == NULL)
1063 			{
1064 				syserr("readqf: cannot open %s", e->e_df);
1065 				e->e_msgsize = -1;
1066 			}
1067 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
1068 				e->e_msgsize = st.st_size;
1069 			break;
1070 
1071 		  case 'T':		/* init time */
1072 			e->e_ctime = atol(&bp[1]);
1073 			break;
1074 
1075 		  case 'P':		/* message priority */
1076 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
1077 			break;
1078 
1079 		  case 'F':		/* flag bits */
1080 			for (p = &bp[1]; *p != '\0'; p++)
1081 			{
1082 				switch (*p)
1083 				{
1084 				  case 'w':	/* warning sent */
1085 					e->e_flags |= EF_WARNING;
1086 					break;
1087 
1088 				  case 'r':	/* response */
1089 					e->e_flags |= EF_RESPONSE;
1090 					break;
1091 				}
1092 			}
1093 			break;
1094 
1095 		  case '$':		/* define macro */
1096 			define(bp[1], newstr(&bp[2]), e);
1097 			break;
1098 
1099 		  case '\0':		/* blank line; ignore */
1100 			break;
1101 
1102 		  default:
1103 			syserr("readqf: bad line \"%s\"", e->e_id,
1104 				LineNumber, bp);
1105 			fclose(qfp);
1106 			rename(qf, queuename(e, 'Q'));
1107 			return FALSE;
1108 		}
1109 
1110 		if (bp != buf)
1111 			free(bp);
1112 	}
1113 
1114 	FileName = NULL;
1115 
1116 	/*
1117 	**  If we haven't read any lines, this queue file is empty.
1118 	**  Arrange to remove it without referencing any null pointers.
1119 	*/
1120 
1121 	if (LineNumber == 0)
1122 	{
1123 		errno = 0;
1124 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
1125 	}
1126 	return TRUE;
1127 }
1128 /*
1129 **  PRINTQUEUE -- print out a representation of the mail queue
1130 **
1131 **	Parameters:
1132 **		none.
1133 **
1134 **	Returns:
1135 **		none.
1136 **
1137 **	Side Effects:
1138 **		Prints a listing of the mail queue on the standard output.
1139 */
1140 
1141 printqueue()
1142 {
1143 	register WORK *w;
1144 	FILE *f;
1145 	int nrequests;
1146 	char buf[MAXLINE];
1147 
1148 	/*
1149 	**  Check for permission to print the queue
1150 	*/
1151 
1152 	if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
1153 	{
1154 		struct stat st;
1155 # ifdef NGROUPS
1156 		int n;
1157 		GIDSET_T gidset[NGROUPS];
1158 # endif
1159 
1160 		if (stat(QueueDir, &st) < 0)
1161 		{
1162 			syserr("Cannot stat %s", QueueDir);
1163 			return;
1164 		}
1165 # ifdef NGROUPS
1166 		n = getgroups(NGROUPS, gidset);
1167 		while (--n >= 0)
1168 		{
1169 			if (gidset[n] == st.st_gid)
1170 				break;
1171 		}
1172 		if (n < 0)
1173 # else
1174 		if (RealGid != st.st_gid)
1175 # endif
1176 		{
1177 			usrerr("510 You are not permitted to see the queue");
1178 			setstat(EX_NOPERM);
1179 			return;
1180 		}
1181 	}
1182 
1183 	/*
1184 	**  Read and order the queue.
1185 	*/
1186 
1187 	nrequests = orderq(TRUE);
1188 
1189 	/*
1190 	**  Print the work list that we have read.
1191 	*/
1192 
1193 	/* first see if there is anything */
1194 	if (nrequests <= 0)
1195 	{
1196 		printf("Mail queue is empty\n");
1197 		return;
1198 	}
1199 
1200 	CurrentLA = getla();	/* get load average */
1201 
1202 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1203 	if (nrequests > QUEUESIZE)
1204 		printf(", only %d printed", QUEUESIZE);
1205 	if (Verbose)
1206 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1207 	else
1208 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1209 	for (w = WorkQ; w != NULL; w = w->w_next)
1210 	{
1211 		struct stat st;
1212 		auto time_t submittime = 0;
1213 		long dfsize = -1;
1214 		int flags = 0;
1215 		char message[MAXLINE];
1216 		char bodytype[MAXNAME];
1217 
1218 		printf("%8s", w->w_name + 2);
1219 		f = fopen(w->w_name, "r");
1220 		if (f == NULL)
1221 		{
1222 			printf(" (job completed)\n");
1223 			errno = 0;
1224 			continue;
1225 		}
1226 		if (!lockfile(fileno(f), w->w_name, NULL, LOCK_SH|LOCK_NB))
1227 			printf("*");
1228 		else if (shouldqueue(w->w_pri, w->w_ctime))
1229 			printf("X");
1230 		else
1231 			printf(" ");
1232 		errno = 0;
1233 
1234 		message[0] = bodytype[0] = '\0';
1235 		while (fgets(buf, sizeof buf, f) != NULL)
1236 		{
1237 			register int i;
1238 			register char *p;
1239 
1240 			fixcrlf(buf, TRUE);
1241 			switch (buf[0])
1242 			{
1243 			  case 'M':	/* error message */
1244 				if ((i = strlen(&buf[1])) >= sizeof message)
1245 					i = sizeof message - 1;
1246 				bcopy(&buf[1], message, i);
1247 				message[i] = '\0';
1248 				break;
1249 
1250 			  case 'B':	/* body type */
1251 				if ((i = strlen(&buf[1])) >= sizeof bodytype)
1252 					i = sizeof bodytype - 1;
1253 				bcopy(&buf[1], bodytype, i);
1254 				bodytype[i] = '\0';
1255 				break;
1256 
1257 			  case 'S':	/* sender name */
1258 				if (Verbose)
1259 					printf("%8ld %10ld%c%.12s %.38s",
1260 					    dfsize,
1261 					    w->w_pri,
1262 					    bitset(EF_WARNING, flags) ? '+' : ' ',
1263 					    ctime(&submittime) + 4,
1264 					    &buf[1]);
1265 				else
1266 					printf("%8ld %.16s %.45s", dfsize,
1267 					    ctime(&submittime), &buf[1]);
1268 				if (message[0] != '\0' || bodytype[0] != '\0')
1269 				{
1270 					printf("\n    %10.10s", bodytype);
1271 					if (message[0] != '\0')
1272 						printf("   (%.60s)", message);
1273 				}
1274 				break;
1275 
1276 			  case 'C':	/* controlling user */
1277 				if (Verbose)
1278 					printf("\n\t\t\t\t      (---%.34s---)",
1279 						&buf[1]);
1280 				break;
1281 
1282 			  case 'R':	/* recipient name */
1283 				if (Verbose)
1284 					printf("\n\t\t\t\t\t  %.38s", &buf[1]);
1285 				else
1286 					printf("\n\t\t\t\t   %.45s", &buf[1]);
1287 				break;
1288 
1289 			  case 'T':	/* creation time */
1290 				submittime = atol(&buf[1]);
1291 				break;
1292 
1293 			  case 'D':	/* data file name */
1294 				if (stat(&buf[1], &st) >= 0)
1295 					dfsize = st.st_size;
1296 				break;
1297 
1298 			  case 'F':	/* flag bits */
1299 				for (p = &buf[1]; *p != '\0'; p++)
1300 				{
1301 					switch (*p)
1302 					{
1303 					  case 'w':
1304 						flags |= EF_WARNING;
1305 						break;
1306 					}
1307 				}
1308 			}
1309 		}
1310 		if (submittime == (time_t) 0)
1311 			printf(" (no control file)");
1312 		printf("\n");
1313 		(void) fclose(f);
1314 	}
1315 }
1316 
1317 # endif /* QUEUE */
1318 /*
1319 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1320 **
1321 **	Assigns an id code if one does not already exist.
1322 **	This code is very careful to avoid trashing existing files
1323 **	under any circumstances.
1324 **
1325 **	Parameters:
1326 **		e -- envelope to build it in/from.
1327 **		type -- the file type, used as the first character
1328 **			of the file name.
1329 **
1330 **	Returns:
1331 **		a pointer to the new file name (in a static buffer).
1332 **
1333 **	Side Effects:
1334 **		If no id code is already assigned, queuename will
1335 **		assign an id code, create a qf file, and leave a
1336 **		locked, open-for-write file pointer in the envelope.
1337 */
1338 
1339 char *
1340 queuename(e, type)
1341 	register ENVELOPE *e;
1342 	int type;
1343 {
1344 	static int pid = -1;
1345 	static char c0;
1346 	static char c1;
1347 	static char c2;
1348 	time_t now;
1349 	struct tm *tm;
1350 	static char buf[MAXNAME];
1351 
1352 	if (e->e_id == NULL)
1353 	{
1354 		char qf[20];
1355 
1356 		/* find a unique id */
1357 		if (pid != getpid())
1358 		{
1359 			/* new process -- start back at "AA" */
1360 			pid = getpid();
1361 			now = curtime();
1362 			tm = localtime(&now);
1363 			c0 = 'A' + tm->tm_hour;
1364 			c1 = 'A';
1365 			c2 = 'A' - 1;
1366 		}
1367 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
1368 
1369 		while (c1 < '~' || c2 < 'Z')
1370 		{
1371 			int i;
1372 
1373 			if (c2 >= 'Z')
1374 			{
1375 				c1++;
1376 				c2 = 'A' - 1;
1377 			}
1378 			qf[3] = c1;
1379 			qf[4] = ++c2;
1380 			if (tTd(7, 20))
1381 				printf("queuename: trying \"%s\"\n", qf);
1382 
1383 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1384 			if (i < 0)
1385 			{
1386 				if (errno == EEXIST)
1387 					continue;
1388 				syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1389 					qf, QueueDir, geteuid());
1390 				exit(EX_UNAVAILABLE);
1391 			}
1392 			if (lockfile(i, qf, NULL, LOCK_EX|LOCK_NB))
1393 			{
1394 				e->e_lockfp = fdopen(i, "w");
1395 				break;
1396 			}
1397 
1398 			/* a reader got the file; abandon it and try again */
1399 			(void) close(i);
1400 		}
1401 		if (c1 >= '~' && c2 >= 'Z')
1402 		{
1403 			syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1404 				qf, QueueDir, geteuid());
1405 			exit(EX_OSERR);
1406 		}
1407 		e->e_id = newstr(&qf[2]);
1408 		define('i', e->e_id, e);
1409 		if (tTd(7, 1))
1410 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1411 		if (tTd(7, 9))
1412 		{
1413 			printf("  lockfd=");
1414 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
1415 		}
1416 # ifdef LOG
1417 		if (LogLevel > 93)
1418 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1419 # endif /* LOG */
1420 	}
1421 
1422 	if (type == '\0')
1423 		return (NULL);
1424 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1425 	if (tTd(7, 2))
1426 		printf("queuename: %s\n", buf);
1427 	return (buf);
1428 }
1429 /*
1430 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1431 **
1432 **	Parameters:
1433 **		e -- the envelope to unlock.
1434 **
1435 **	Returns:
1436 **		none
1437 **
1438 **	Side Effects:
1439 **		unlocks the queue for `e'.
1440 */
1441 
1442 unlockqueue(e)
1443 	ENVELOPE *e;
1444 {
1445 	if (tTd(51, 4))
1446 		printf("unlockqueue(%s)\n", e->e_id);
1447 
1448 	/* if there is a lock file in the envelope, close it */
1449 	if (e->e_lockfp != NULL)
1450 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
1451 	e->e_lockfp = NULL;
1452 
1453 	/* don't create a queue id if we don't already have one */
1454 	if (e->e_id == NULL)
1455 		return;
1456 
1457 	/* remove the transcript */
1458 # ifdef LOG
1459 	if (LogLevel > 87)
1460 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1461 # endif /* LOG */
1462 	if (!tTd(51, 104))
1463 		xunlink(queuename(e, 'x'));
1464 
1465 }
1466 /*
1467 **  SETCTLUSER -- create a controlling address
1468 **
1469 **	Create a fake "address" given only a local login name; this is
1470 **	used as a "controlling user" for future recipient addresses.
1471 **
1472 **	Parameters:
1473 **		user -- the user name of the controlling user.
1474 **
1475 **	Returns:
1476 **		An address descriptor for the controlling user.
1477 **
1478 **	Side Effects:
1479 **		none.
1480 */
1481 
1482 ADDRESS *
1483 setctluser(user)
1484 	char *user;
1485 {
1486 	register ADDRESS *a;
1487 	struct passwd *pw;
1488 	char *p;
1489 
1490 	/*
1491 	**  See if this clears our concept of controlling user.
1492 	*/
1493 
1494 	if (user == NULL || *user == '\0')
1495 		return NULL;
1496 
1497 	/*
1498 	**  Set up addr fields for controlling user.
1499 	*/
1500 
1501 	a = (ADDRESS *) xalloc(sizeof *a);
1502 	bzero((char *) a, sizeof *a);
1503 
1504 	p = strchr(user, ':');
1505 	if (p != NULL)
1506 		*p++ = '\0';
1507 	if (*user != '\0' && (pw = getpwnam(user)) != NULL)
1508 	{
1509 		a->q_home = newstr(pw->pw_dir);
1510 		a->q_uid = pw->pw_uid;
1511 		a->q_gid = pw->pw_gid;
1512 		a->q_user = newstr(user);
1513 		a->q_flags |= QGOODUID;
1514 	}
1515 	else
1516 	{
1517 		a->q_user = newstr(DefUser);
1518 	}
1519 
1520 	a->q_flags |= QPRIMARY;		/* flag as a "ctladdr"  */
1521 	a->q_mailer = LocalMailer;
1522 	if (p == NULL)
1523 		a->q_paddr = a->q_user;
1524 	else
1525 		a->q_paddr = newstr(p);
1526 	return a;
1527 }
1528