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