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