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