xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 65200)
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.33 (Berkeley) 12/22/93 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	8.33 (Berkeley) 12/22/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, uid=%d: %s",
99 						tf, geteuid(), errstring(errno));
100 #endif
101 			}
102 			else
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 				close(fd);
112 			}
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 		{
124 			printopenfds(TRUE);
125 			syserr("!queueup: cannot create queue temp file %s, uid=%d",
126 				tf, geteuid());
127 		}
128 	}
129 
130 	if (tTd(40, 1))
131 		printf("\n>>>>> queueing %s%s >>>>>\n", e->e_id,
132 			newid ? " (new id)" : "");
133 	if (tTd(40, 9))
134 	{
135 		printf("  tfp=");
136 		dumpfd(fileno(tfp), TRUE, FALSE);
137 		printf("  lockfp=");
138 		if (e->e_lockfp == NULL)
139 			printf("NULL\n");
140 		else
141 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
142 	}
143 
144 	/*
145 	**  If there is no data file yet, create one.
146 	*/
147 
148 	if (e->e_df == NULL)
149 	{
150 		register FILE *dfp;
151 		extern putbody();
152 
153 		e->e_df = queuename(e, 'd');
154 		e->e_df = newstr(e->e_df);
155 		fd = open(e->e_df, O_WRONLY|O_CREAT, FileMode);
156 		if (fd < 0 || (dfp = fdopen(fd, "w")) == NULL)
157 			syserr("!queueup: cannot create data temp file %s, uid=%d",
158 				e->e_df, geteuid());
159 		(*e->e_putbody)(dfp, FileMailer, e, NULL);
160 		(void) xfclose(dfp, "queueup dfp", e->e_id);
161 		e->e_putbody = putbody;
162 	}
163 
164 	/*
165 	**  Output future work requests.
166 	**	Priority and creation time should be first, since
167 	**	they are required by orderq.
168 	*/
169 
170 	/* output message priority */
171 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
172 
173 	/* output creation time */
174 	fprintf(tfp, "T%ld\n", e->e_ctime);
175 
176 	/* output type and name of data file */
177 	if (e->e_bodytype != NULL)
178 		fprintf(tfp, "B%s\n", e->e_bodytype);
179 	fprintf(tfp, "D%s\n", e->e_df);
180 
181 	/* message from envelope, if it exists */
182 	if (e->e_message != NULL)
183 		fprintf(tfp, "M%s\n", e->e_message);
184 
185 	/* send various flag bits through */
186 	p = buf;
187 	if (bitset(EF_WARNING, e->e_flags))
188 		*p++ = 'w';
189 	if (bitset(EF_RESPONSE, e->e_flags))
190 		*p++ = 'r';
191 	*p++ = '\0';
192 	if (buf[0] != '\0')
193 		fprintf(tfp, "F%s\n", buf);
194 
195 	/* $r and $s and $_ macro values */
196 	if ((p = macvalue('r', e)) != NULL)
197 		fprintf(tfp, "$r%s\n", p);
198 	if ((p = macvalue('s', e)) != NULL)
199 		fprintf(tfp, "$s%s\n", p);
200 	if ((p = macvalue('_', e)) != NULL)
201 		fprintf(tfp, "$_%s\n", p);
202 
203 	/* output name of sender */
204 	fprintf(tfp, "S%s\n", e->e_from.q_paddr);
205 
206 	/* output list of error recipients */
207 	printctladdr(NULL, NULL);
208 	for (q = e->e_errorqueue; q != NULL; q = q->q_next)
209 	{
210 		if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
211 		{
212 			printctladdr(q, tfp);
213 			fprintf(tfp, "E%s\n", q->q_paddr);
214 		}
215 	}
216 
217 	/* output list of recipient addresses */
218 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
219 	{
220 		if (bitset(QQUEUEUP, q->q_flags) ||
221 		    (queueall && !bitset(QDONTSEND|QBADADDR|QSENT, q->q_flags)))
222 		{
223 			printctladdr(q, tfp);
224 			fprintf(tfp, "R%s\n", q->q_paddr);
225 			if (announce)
226 			{
227 				e->e_to = q->q_paddr;
228 				message("queued");
229 				if (LogLevel > 8)
230 					logdelivery(NULL, NULL, "queued", NULL, e);
231 				e->e_to = NULL;
232 			}
233 			if (tTd(40, 1))
234 			{
235 				printf("queueing ");
236 				printaddr(q, FALSE);
237 			}
238 		}
239 	}
240 
241 	/*
242 	**  Output headers for this message.
243 	**	Expand macros completely here.  Queue run will deal with
244 	**	everything as absolute headers.
245 	**		All headers that must be relative to the recipient
246 	**		can be cracked later.
247 	**	We set up a "null mailer" -- i.e., a mailer that will have
248 	**	no effect on the addresses as they are output.
249 	*/
250 
251 	bzero((char *) &nullmailer, sizeof nullmailer);
252 	nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
253 			nullmailer.m_se_rwset = nullmailer.m_sh_rwset = 0;
254 	nullmailer.m_eol = "\n";
255 
256 	define('g', "\201f", e);
257 	for (h = e->e_header; h != NULL; h = h->h_link)
258 	{
259 		extern bool bitzerop();
260 
261 		/* don't output null headers */
262 		if (h->h_value == NULL || h->h_value[0] == '\0')
263 			continue;
264 
265 		/* don't output resent headers on non-resent messages */
266 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
267 			continue;
268 
269 		/* output this header */
270 		fprintf(tfp, "H");
271 
272 		/* if conditional, output the set of conditions */
273 		if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags))
274 		{
275 			int j;
276 
277 			(void) putc('?', tfp);
278 			for (j = '\0'; j <= '\177'; j++)
279 				if (bitnset(j, h->h_mflags))
280 					(void) putc(j, tfp);
281 			(void) putc('?', tfp);
282 		}
283 
284 		/* output the header: expand macros, convert addresses */
285 		if (bitset(H_DEFAULT, h->h_flags))
286 		{
287 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
288 			if (buf[0] != '\0')
289 				fprintf(tfp, "%s: %s\n", h->h_field, buf);
290 		}
291 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
292 		{
293 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
294 			FILE *savetrace = TrafficLogFile;
295 
296 			TrafficLogFile = NULL;
297 
298 			if (bitset(H_FROM, h->h_flags))
299 				oldstyle = FALSE;
300 
301 			commaize(h, h->h_value, tfp, oldstyle,
302 				 &nullmailer, e);
303 
304 			TrafficLogFile = savetrace;
305 		}
306 		else
307 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
308 	}
309 
310 	/*
311 	**  Clean up.
312 	*/
313 
314 	if (fflush(tfp) < 0 || fsync(fileno(tfp)) < 0 || ferror(tfp))
315 	{
316 		if (newid)
317 			syserr("!552 Error writing control file %s", tf);
318 		else
319 			syserr("!452 Error writing control file %s", tf);
320 	}
321 
322 	if (!newid)
323 	{
324 		/* rename (locked) tf to be (locked) qf */
325 		qf = queuename(e, 'q');
326 		if (rename(tf, qf) < 0)
327 			syserr("cannot rename(%s, %s), df=%s, uid=%d",
328 				tf, qf, e->e_df, geteuid());
329 
330 		/* close and unlock old (locked) qf */
331 		if (e->e_lockfp != NULL)
332 			(void) xfclose(e->e_lockfp, "queueup lockfp", e->e_id);
333 		e->e_lockfp = tfp;
334 	}
335 	else
336 		qf = tf;
337 	errno = 0;
338 	e->e_flags |= EF_INQUEUE;
339 
340 # ifdef LOG
341 	/* save log info */
342 	if (LogLevel > 79)
343 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
344 # endif /* LOG */
345 
346 	if (tTd(40, 1))
347 		printf("<<<<< done queueing %s <<<<<\n\n", e->e_id);
348 	return;
349 }
350 
351 printctladdr(a, tfp)
352 	register ADDRESS *a;
353 	FILE *tfp;
354 {
355 	char *uname;
356 	register struct passwd *pw;
357 	register ADDRESS *q;
358 	uid_t uid;
359 	static ADDRESS *lastctladdr;
360 	static uid_t lastuid;
361 
362 	/* initialization */
363 	if (a == NULL || a->q_alias == NULL || tfp == NULL)
364 	{
365 		if (lastctladdr != NULL && tfp != NULL)
366 			fprintf(tfp, "C\n");
367 		lastctladdr = NULL;
368 		lastuid = 0;
369 		return;
370 	}
371 
372 	/* find the active uid */
373 	q = getctladdr(a);
374 	if (q == NULL)
375 		uid = 0;
376 	else
377 		uid = q->q_uid;
378 	a = a->q_alias;
379 
380 	/* check to see if this is the same as last time */
381 	if (lastctladdr != NULL && uid == lastuid &&
382 	    strcmp(lastctladdr->q_paddr, a->q_paddr) == 0)
383 		return;
384 	lastuid = uid;
385 	lastctladdr = a;
386 
387 	if (uid == 0 || (pw = getpwuid(uid)) == NULL)
388 		uname = "";
389 	else
390 		uname = pw->pw_name;
391 
392 	fprintf(tfp, "C%s:%s\n", uname, a->q_paddr);
393 }
394 
395 /*
396 **  RUNQUEUE -- run the jobs in the queue.
397 **
398 **	Gets the stuff out of the queue in some presumably logical
399 **	order and processes them.
400 **
401 **	Parameters:
402 **		forkflag -- TRUE if the queue scanning should be done in
403 **			a child process.  We double-fork so it is not our
404 **			child and we don't have to clean up after it.
405 **
406 **	Returns:
407 **		none.
408 **
409 **	Side Effects:
410 **		runs things in the mail queue.
411 */
412 
413 ENVELOPE	QueueEnvelope;		/* the queue run envelope */
414 
415 runqueue(forkflag)
416 	bool forkflag;
417 {
418 	register ENVELOPE *e;
419 	extern ENVELOPE BlankEnvelope;
420 
421 	/*
422 	**  If no work will ever be selected, don't even bother reading
423 	**  the queue.
424 	*/
425 
426 	CurrentLA = getla();	/* get load average */
427 
428 	if (shouldqueue(0L, curtime()))
429 	{
430 		if (Verbose)
431 			printf("Skipping queue run -- load average too high\n");
432 		if (forkflag && QueueIntvl != 0)
433 			(void) setevent(QueueIntvl, runqueue, TRUE);
434 		return;
435 	}
436 
437 	/*
438 	**  See if we want to go off and do other useful work.
439 	*/
440 
441 	if (forkflag)
442 	{
443 		int pid;
444 
445 		pid = dofork();
446 		if (pid != 0)
447 		{
448 			extern void reapchild();
449 
450 			/* parent -- pick up intermediate zombie */
451 #ifndef SIGCHLD
452 			(void) waitfor(pid);
453 #else /* SIGCHLD */
454 			(void) setsignal(SIGCHLD, reapchild);
455 #endif /* SIGCHLD */
456 			if (QueueIntvl != 0)
457 				(void) setevent(QueueIntvl, runqueue, TRUE);
458 			return;
459 		}
460 		/* child -- double fork */
461 #ifndef SIGCHLD
462 		if (fork() != 0)
463 			exit(EX_OK);
464 #else /* SIGCHLD */
465 		(void) setsignal(SIGCHLD, SIG_DFL);
466 #endif /* SIGCHLD */
467 	}
468 
469 	setproctitle("running queue: %s", QueueDir);
470 
471 # ifdef LOG
472 	if (LogLevel > 69)
473 		syslog(LOG_DEBUG, "runqueue %s, pid=%d, forkflag=%d",
474 			QueueDir, getpid(), forkflag);
475 # endif /* LOG */
476 
477 	/*
478 	**  Release any resources used by the daemon code.
479 	*/
480 
481 # ifdef DAEMON
482 	clrdaemon();
483 # endif /* DAEMON */
484 
485 	/* force it to run expensive jobs */
486 	NoConnect = FALSE;
487 
488 	/*
489 	**  Create ourselves an envelope
490 	*/
491 
492 	CurEnv = &QueueEnvelope;
493 	e = newenvelope(&QueueEnvelope, CurEnv);
494 	e->e_flags = BlankEnvelope.e_flags;
495 
496 	/*
497 	**  Make sure the alias database is open.
498 	*/
499 
500 	initmaps(FALSE, e);
501 
502 	/*
503 	**  Start making passes through the queue.
504 	**	First, read and sort the entire queue.
505 	**	Then, process the work in that order.
506 	**		But if you take too long, start over.
507 	*/
508 
509 	/* order the existing work requests */
510 	(void) orderq(FALSE);
511 
512 	/* process them once at a time */
513 	while (WorkQ != NULL)
514 	{
515 		WORK *w = WorkQ;
516 
517 		WorkQ = WorkQ->w_next;
518 
519 		/*
520 		**  Ignore jobs that are too expensive for the moment.
521 		*/
522 
523 		if (shouldqueue(w->w_pri, w->w_ctime))
524 		{
525 			if (Verbose)
526 				printf("\nSkipping %s\n", w->w_name + 2);
527 		}
528 		else
529 		{
530 			pid_t pid;
531 			extern pid_t dowork();
532 
533 			pid = dowork(w->w_name + 2, ForkQueueRuns, FALSE, e);
534 			errno = 0;
535 			(void) waitfor(pid);
536 		}
537 		free(w->w_name);
538 		free((char *) w);
539 	}
540 
541 	/* exit without the usual cleanup */
542 	e->e_id = NULL;
543 	finis();
544 }
545 /*
546 **  ORDERQ -- order the work queue.
547 **
548 **	Parameters:
549 **		doall -- if set, include everything in the queue (even
550 **			the jobs that cannot be run because the load
551 **			average is too high).  Otherwise, exclude those
552 **			jobs.
553 **
554 **	Returns:
555 **		The number of request in the queue (not necessarily
556 **		the number of requests in WorkQ however).
557 **
558 **	Side Effects:
559 **		Sets WorkQ to the queue of available work, in order.
560 */
561 
562 # define NEED_P		001
563 # define NEED_T		002
564 # define NEED_R		004
565 # define NEED_S		010
566 
567 orderq(doall)
568 	bool doall;
569 {
570 	register struct dirent *d;
571 	register WORK *w;
572 	DIR *f;
573 	register int i;
574 	WORK wlist[QUEUESIZE+1];
575 	int wn = -1;
576 	extern workcmpf();
577 
578 	if (tTd(41, 1))
579 	{
580 		printf("orderq:\n");
581 		if (QueueLimitId != NULL)
582 			printf("\tQueueLimitId = %s\n", QueueLimitId);
583 		if (QueueLimitSender != NULL)
584 			printf("\tQueueLimitSender = %s\n", QueueLimitSender);
585 		if (QueueLimitRecipient != NULL)
586 			printf("\tQueueLimitRecipient = %s\n", QueueLimitRecipient);
587 	}
588 
589 	/* clear out old WorkQ */
590 	for (w = WorkQ; w != NULL; )
591 	{
592 		register WORK *nw = w->w_next;
593 
594 		WorkQ = nw;
595 		free(w->w_name);
596 		free((char *) w);
597 		w = nw;
598 	}
599 
600 	/* open the queue directory */
601 	f = opendir(".");
602 	if (f == NULL)
603 	{
604 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
605 		return (0);
606 	}
607 
608 	/*
609 	**  Read the work directory.
610 	*/
611 
612 	while ((d = readdir(f)) != NULL)
613 	{
614 		FILE *cf;
615 		register char *p;
616 		char lbuf[MAXNAME];
617 		extern bool strcontainedin();
618 
619 		/* is this an interesting entry? */
620 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
621 			continue;
622 
623 		if (QueueLimitId != NULL &&
624 		    !strcontainedin(QueueLimitId, d->d_name))
625 			continue;
626 
627 		/*
628 		**  Check queue name for plausibility.  This handles
629 		**  both old and new type ids.
630 		*/
631 
632 		p = d->d_name + 2;
633 		if (isupper(p[0]) && isupper(p[2]))
634 			p += 3;
635 		else if (isupper(p[1]))
636 			p += 2;
637 		else
638 			p = d->d_name;
639 		for (i = 0; isdigit(*p); p++)
640 			i++;
641 		if (i < 5 || *p != '\0')
642 		{
643 			if (Verbose)
644 				printf("orderq: bogus qf name %s\n", d->d_name);
645 #ifdef LOG
646 			if (LogLevel > 3)
647 				syslog(LOG_CRIT, "orderq: bogus qf name %s",
648 					d->d_name);
649 #endif
650 			if (strlen(d->d_name) >= MAXNAME)
651 				d->d_name[MAXNAME - 1] = '\0';
652 			strcpy(lbuf, d->d_name);
653 			lbuf[0] = 'Q';
654 			(void) rename(d->d_name, lbuf);
655 			continue;
656 		}
657 
658 		/* yes -- open control file (if not too many files) */
659 		if (++wn >= QUEUESIZE)
660 			continue;
661 
662 		cf = fopen(d->d_name, "r");
663 		if (cf == NULL)
664 		{
665 			/* this may be some random person sending hir msgs */
666 			/* syserr("orderq: cannot open %s", cbuf); */
667 			if (tTd(41, 2))
668 				printf("orderq: cannot open %s (%d)\n",
669 					d->d_name, errno);
670 			errno = 0;
671 			wn--;
672 			continue;
673 		}
674 		w = &wlist[wn];
675 		w->w_name = newstr(d->d_name);
676 
677 		/* make sure jobs in creation don't clog queue */
678 		w->w_pri = 0x7fffffff;
679 		w->w_ctime = 0;
680 
681 		/* extract useful information */
682 		i = NEED_P | NEED_T;
683 		if (QueueLimitSender != NULL)
684 			i |= NEED_S;
685 		if (QueueLimitRecipient != NULL)
686 			i |= NEED_R;
687 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
688 		{
689 			extern long atol();
690 			extern bool strcontainedin();
691 
692 			switch (lbuf[0])
693 			{
694 			  case 'P':
695 				w->w_pri = atol(&lbuf[1]);
696 				i &= ~NEED_P;
697 				break;
698 
699 			  case 'T':
700 				w->w_ctime = atol(&lbuf[1]);
701 				i &= ~NEED_T;
702 				break;
703 
704 			  case 'R':
705 				if (QueueLimitRecipient != NULL &&
706 				    strcontainedin(QueueLimitRecipient, &lbuf[1]))
707 					i &= ~NEED_R;
708 				break;
709 
710 			  case 'S':
711 				if (QueueLimitSender != NULL &&
712 				    strcontainedin(QueueLimitSender, &lbuf[1]))
713 					i &= ~NEED_S;
714 				break;
715 			}
716 		}
717 		(void) fclose(cf);
718 
719 		if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
720 		    bitset(NEED_R|NEED_S, i))
721 		{
722 			/* don't even bother sorting this job in */
723 			wn--;
724 		}
725 	}
726 	(void) closedir(f);
727 	wn++;
728 
729 	/*
730 	**  Sort the work directory.
731 	*/
732 
733 	qsort((char *) wlist, min(wn, QUEUESIZE), sizeof *wlist, workcmpf);
734 
735 	/*
736 	**  Convert the work list into canonical form.
737 	**	Should be turning it into a list of envelopes here perhaps.
738 	*/
739 
740 	WorkQ = NULL;
741 	for (i = min(wn, QUEUESIZE); --i >= 0; )
742 	{
743 		w = (WORK *) xalloc(sizeof *w);
744 		w->w_name = wlist[i].w_name;
745 		w->w_pri = wlist[i].w_pri;
746 		w->w_ctime = wlist[i].w_ctime;
747 		w->w_next = WorkQ;
748 		WorkQ = w;
749 	}
750 
751 	if (tTd(40, 1))
752 	{
753 		for (w = WorkQ; w != NULL; w = w->w_next)
754 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
755 	}
756 
757 	return (wn);
758 }
759 /*
760 **  WORKCMPF -- compare function for ordering work.
761 **
762 **	Parameters:
763 **		a -- the first argument.
764 **		b -- the second argument.
765 **
766 **	Returns:
767 **		-1 if a < b
768 **		 0 if a == b
769 **		+1 if a > b
770 **
771 **	Side Effects:
772 **		none.
773 */
774 
775 workcmpf(a, b)
776 	register WORK *a;
777 	register WORK *b;
778 {
779 	long pa = a->w_pri;
780 	long pb = b->w_pri;
781 
782 	if (pa == pb)
783 		return (0);
784 	else if (pa > pb)
785 		return (1);
786 	else
787 		return (-1);
788 }
789 /*
790 **  DOWORK -- do a work request.
791 **
792 **	Parameters:
793 **		id -- the ID of the job to run.
794 **		forkflag -- if set, run this in background.
795 **		requeueflag -- if set, reinstantiate the queue quickly.
796 **			This is used when expanding aliases in the queue.
797 **			If forkflag is also set, it doesn't wait for the
798 **			child.
799 **		e - the envelope in which to run it.
800 **
801 **	Returns:
802 **		process id of process that is running the queue job.
803 **
804 **	Side Effects:
805 **		The work request is satisfied if possible.
806 */
807 
808 pid_t
809 dowork(id, forkflag, requeueflag, e)
810 	char *id;
811 	bool forkflag;
812 	bool requeueflag;
813 	register ENVELOPE *e;
814 {
815 	register pid_t pid;
816 	extern bool readqf();
817 
818 	if (tTd(40, 1))
819 		printf("dowork(%s)\n", id);
820 
821 	/*
822 	**  Fork for work.
823 	*/
824 
825 	if (forkflag)
826 	{
827 		pid = fork();
828 		if (pid < 0)
829 		{
830 			syserr("dowork: cannot fork");
831 			return 0;
832 		}
833 		else if (pid > 0)
834 		{
835 			/* parent -- clean out connection cache */
836 			mci_flush(FALSE, NULL);
837 		}
838 	}
839 	else
840 	{
841 		pid = 0;
842 	}
843 
844 	if (pid == 0)
845 	{
846 		/*
847 		**  CHILD
848 		**	Lock the control file to avoid duplicate deliveries.
849 		**		Then run the file as though we had just read it.
850 		**	We save an idea of the temporary name so we
851 		**		can recover on interrupt.
852 		*/
853 
854 		/* set basic modes, etc. */
855 		(void) alarm(0);
856 		clearenvelope(e, FALSE);
857 		e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
858 		e->e_errormode = EM_MAIL;
859 		e->e_id = id;
860 		GrabTo = UseErrorsTo = FALSE;
861 		if (forkflag)
862 		{
863 			disconnect(1, e);
864 			OpMode = MD_DELIVER;
865 		}
866 # ifdef LOG
867 		if (LogLevel > 76)
868 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
869 			       getpid());
870 # endif /* LOG */
871 
872 		/* don't use the headers from sendmail.cf... */
873 		e->e_header = NULL;
874 
875 		/* read the queue control file -- return if locked */
876 		if (!readqf(e))
877 		{
878 			if (tTd(40, 4))
879 				printf("readqf(%s) failed\n", e->e_id);
880 			if (forkflag)
881 				exit(EX_OK);
882 			else
883 				return;
884 		}
885 
886 		e->e_flags |= EF_INQUEUE;
887 		eatheader(e, requeueflag);
888 
889 		if (requeueflag)
890 			queueup(e, TRUE, FALSE);
891 
892 		/* do the delivery */
893 		sendall(e, SM_DELIVER);
894 
895 		/* finish up and exit */
896 		if (forkflag)
897 			finis();
898 		else
899 			dropenvelope(e);
900 	}
901 	e->e_id = NULL;
902 	return pid;
903 }
904 /*
905 **  READQF -- read queue file and set up environment.
906 **
907 **	Parameters:
908 **		e -- the envelope of the job to run.
909 **
910 **	Returns:
911 **		TRUE if it successfully read the queue file.
912 **		FALSE otherwise.
913 **
914 **	Side Effects:
915 **		The queue file is returned locked.
916 */
917 
918 bool
919 readqf(e)
920 	register ENVELOPE *e;
921 {
922 	register FILE *qfp;
923 	ADDRESS *ctladdr;
924 	struct stat st;
925 	char *bp;
926 	char qf[20];
927 	char buf[MAXLINE];
928 	extern long atol();
929 	extern ADDRESS *setctluser();
930 
931 	/*
932 	**  Read and process the file.
933 	*/
934 
935 	strcpy(qf, queuename(e, 'q'));
936 	qfp = fopen(qf, "r+");
937 	if (qfp == NULL)
938 	{
939 		if (tTd(40, 8))
940 			printf("readqf(%s): fopen failure (%s)\n",
941 				qf, errstring(errno));
942 		if (errno != ENOENT)
943 			syserr("readqf: no control file %s", qf);
944 		return FALSE;
945 	}
946 
947 	if (!lockfile(fileno(qfp), qf, NULL, LOCK_EX|LOCK_NB))
948 	{
949 		/* being processed by another queuer */
950 		if (tTd(40, 8))
951 			printf("readqf(%s): locked\n", qf);
952 		if (Verbose)
953 			printf("%s: locked\n", e->e_id);
954 # ifdef LOG
955 		if (LogLevel > 19)
956 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
957 # endif /* LOG */
958 		(void) fclose(qfp);
959 		return FALSE;
960 	}
961 
962 	/*
963 	**  Check the queue file for plausibility to avoid attacks.
964 	*/
965 
966 	if (fstat(fileno(qfp), &st) < 0)
967 	{
968 		/* must have been being processed by someone else */
969 		if (tTd(40, 8))
970 			printf("readqf(%s): fstat failure (%s)\n",
971 				qf, errstring(errno));
972 		fclose(qfp);
973 		return FALSE;
974 	}
975 
976 	if (st.st_uid != geteuid())
977 	{
978 # ifdef LOG
979 		if (LogLevel > 0)
980 		{
981 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
982 				e->e_id, st.st_uid, st.st_mode);
983 		}
984 # endif /* LOG */
985 		if (tTd(40, 8))
986 			printf("readqf(%s): bogus file\n", qf);
987 		rename(qf, queuename(e, 'Q'));
988 		fclose(qfp);
989 		return FALSE;
990 	}
991 
992 	if (st.st_size == 0)
993 	{
994 		/* must be a bogus file -- just remove it */
995 		(void) unlink(qf);
996 		fclose(qfp);
997 		return FALSE;
998 	}
999 
1000 	if (st.st_nlink == 0)
1001 	{
1002 		/*
1003 		**  Race condition -- we got a file just as it was being
1004 		**  unlinked.  Just assume it is zero length.
1005 		*/
1006 
1007 		fclose(qfp);
1008 		return FALSE;
1009 	}
1010 
1011 	/* good file -- save this lock */
1012 	e->e_lockfp = qfp;
1013 
1014 	/* do basic system initialization */
1015 	initsys(e);
1016 	define('i', e->e_id, e);
1017 
1018 	LineNumber = 0;
1019 	e->e_flags |= EF_GLOBALERRS;
1020 	OpMode = MD_DELIVER;
1021 	if (Verbose)
1022 		printf("\nRunning %s\n", e->e_id);
1023 	ctladdr = NULL;
1024 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
1025 	{
1026 		register char *p;
1027 		struct stat st;
1028 
1029 		if (tTd(40, 4))
1030 			printf("+++++ %s\n", bp);
1031 		switch (bp[0])
1032 		{
1033 		  case 'C':		/* specify controlling user */
1034 			ctladdr = setctluser(&bp[1]);
1035 			break;
1036 
1037 		  case 'R':		/* specify recipient */
1038 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
1039 			break;
1040 
1041 		  case 'E':		/* specify error recipient */
1042 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
1043 			break;
1044 
1045 		  case 'H':		/* header */
1046 			(void) chompheader(&bp[1], FALSE, e);
1047 			break;
1048 
1049 		  case 'M':		/* message */
1050 			/* ignore this; we want a new message next time */
1051 			break;
1052 
1053 		  case 'S':		/* sender */
1054 			setsender(newstr(&bp[1]), e, NULL, TRUE);
1055 			break;
1056 
1057 		  case 'B':		/* body type */
1058 			e->e_bodytype = newstr(&bp[1]);
1059 			break;
1060 
1061 		  case 'D':		/* data file name */
1062 			e->e_df = newstr(&bp[1]);
1063 			e->e_dfp = fopen(e->e_df, "r");
1064 			if (e->e_dfp == NULL)
1065 			{
1066 				syserr("readqf: cannot open %s", e->e_df);
1067 				e->e_msgsize = -1;
1068 			}
1069 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
1070 				e->e_msgsize = st.st_size;
1071 			break;
1072 
1073 		  case 'T':		/* init time */
1074 			e->e_ctime = atol(&bp[1]);
1075 			break;
1076 
1077 		  case 'P':		/* message priority */
1078 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
1079 			break;
1080 
1081 		  case 'F':		/* flag bits */
1082 			for (p = &bp[1]; *p != '\0'; p++)
1083 			{
1084 				switch (*p)
1085 				{
1086 				  case 'w':	/* warning sent */
1087 					e->e_flags |= EF_WARNING;
1088 					break;
1089 
1090 				  case 'r':	/* response */
1091 					e->e_flags |= EF_RESPONSE;
1092 					break;
1093 				}
1094 			}
1095 			break;
1096 
1097 		  case '$':		/* define macro */
1098 			define(bp[1], newstr(&bp[2]), e);
1099 			break;
1100 
1101 		  case '\0':		/* blank line; ignore */
1102 			break;
1103 
1104 		  default:
1105 			syserr("readqf: %s: line %s: bad line \"%s\"",
1106 				qf, LineNumber, bp);
1107 			fclose(qfp);
1108 			rename(qf, queuename(e, 'Q'));
1109 			return FALSE;
1110 		}
1111 
1112 		if (bp != buf)
1113 			free(bp);
1114 	}
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