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