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