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