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