xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 67612)
122708Sdist /*
234921Sbostic  * Copyright (c) 1983 Eric P. Allman
362528Sbostic  * Copyright (c) 1988, 1993
462528Sbostic  *	The Regents of the University of California.  All rights reserved.
533731Sbostic  *
642829Sbostic  * %sccs.include.redist.c%
733731Sbostic  */
822708Sdist 
933731Sbostic # include "sendmail.h"
1022708Sdist 
1133731Sbostic #ifndef lint
1233731Sbostic #ifdef QUEUE
13*67612Seric static char sccsid[] = "@(#)queue.c	8.44 (Berkeley) 08/07/94 (with queueing)";
1433731Sbostic #else
15*67612Seric static char sccsid[] = "@(#)queue.c	8.44 (Berkeley) 08/07/94 (without queueing)";
1633731Sbostic #endif
1733731Sbostic #endif /* not lint */
1833731Sbostic 
194632Seric # include <errno.h>
2040973Sbostic # include <pwd.h>
2157736Seric # include <dirent.h>
224632Seric 
2333731Sbostic # ifdef QUEUE
244632Seric 
254632Seric /*
269377Seric **  Work queue.
279377Seric */
289377Seric 
299377Seric struct work
309377Seric {
319377Seric 	char		*w_name;	/* name of control file */
32*67612Seric 	char		*w_host;	/* name of recipient host */
33*67612Seric 	bool		w_lock;		/* is message locked? */
349377Seric 	long		w_pri;		/* priority of message, see below */
3525013Seric 	time_t		w_ctime;	/* creation time of message */
369377Seric 	struct work	*w_next;	/* next in queue */
379377Seric };
389377Seric 
399377Seric typedef struct work	WORK;
409377Seric 
419377Seric WORK	*WorkQ;			/* queue of things to be done */
429377Seric /*
434632Seric **  QUEUEUP -- queue a message up for future transmission.
444632Seric **
454632Seric **	Parameters:
466980Seric **		e -- the envelope to queue up.
476999Seric **		queueall -- if TRUE, queue all addresses, rather than
486999Seric **			just those with the QQUEUEUP flag set.
499377Seric **		announce -- if TRUE, tell when you are queueing up.
504632Seric **
514632Seric **	Returns:
5251920Seric **		none.
534632Seric **
544632Seric **	Side Effects:
559377Seric **		The current request are saved in a control file.
5651920Seric **		The queue file is left locked.
574632Seric */
584632Seric 
599377Seric queueup(e, queueall, announce)
606980Seric 	register ENVELOPE *e;
616999Seric 	bool queueall;
629377Seric 	bool announce;
634632Seric {
647812Seric 	char *qf;
657812Seric 	register FILE *tfp;
664632Seric 	register HDR *h;
675007Seric 	register ADDRESS *q;
6851920Seric 	int fd;
6951920Seric 	int i;
7051920Seric 	bool newid;
7153400Seric 	register char *p;
7210173Seric 	MAILER nullmailer;
7365870Seric 	MCI mcibuf;
7451920Seric 	char buf[MAXLINE], tf[MAXLINE];
754632Seric 
765037Seric 	/*
7717477Seric 	**  Create control file.
785037Seric 	*/
794632Seric 
8064745Seric 	newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags);
8164277Seric 
8264277Seric 	/* if newid, queuename will create a locked qf file in e->lockfp */
8351920Seric 	strcpy(tf, queuename(e, 't'));
8451920Seric 	tfp = e->e_lockfp;
8551920Seric 	if (tfp == NULL)
8651920Seric 		newid = FALSE;
8764277Seric 
8864277Seric 	/* if newid, just write the qf file directly (instead of tf file) */
8964745Seric 	if (!newid)
9051835Seric 	{
9151920Seric 		/* get a locked tf file */
9264070Seric 		for (i = 0; i < 128; i++)
9351835Seric 		{
9451920Seric 			fd = open(tf, O_CREAT|O_WRONLY|O_EXCL, FileMode);
9551920Seric 			if (fd < 0)
9651835Seric 			{
9764070Seric 				if (errno != EEXIST)
9864070Seric 					break;
9964070Seric #ifdef LOG
10064070Seric 				if (LogLevel > 0 && (i % 32) == 0)
10165090Seric 					syslog(LOG_ALERT, "queueup: cannot create %s, uid=%d: %s",
10265090Seric 						tf, geteuid(), errstring(errno));
10364070Seric #endif
10441636Srick 			}
10565090Seric 			else
10665090Seric 			{
10765090Seric 				if (lockfile(fd, tf, NULL, LOCK_EX|LOCK_NB))
10865090Seric 					break;
10964070Seric #ifdef LOG
11065090Seric 				else if (LogLevel > 0 && (i % 32) == 0)
11165090Seric 					syslog(LOG_ALERT, "queueup: cannot lock %s: %s",
11265090Seric 						tf, errstring(errno));
11364070Seric #endif
11465090Seric 				close(fd);
11565090Seric 			}
11658689Seric 
11764070Seric 			if ((i % 32) == 31)
11864070Seric 			{
11964070Seric 				/* save the old temp file away */
12064070Seric 				(void) rename(tf, queuename(e, 'T'));
12164070Seric 			}
12264070Seric 			else
12364070Seric 				sleep(i % 32);
12441636Srick 		}
12564724Seric 		if (fd < 0 || (tfp = fdopen(fd, "w")) == NULL)
12664921Seric 		{
12764921Seric 			printopenfds(TRUE);
12865090Seric 			syserr("!queueup: cannot create queue temp file %s, uid=%d",
12965090Seric 				tf, geteuid());
13064921Seric 		}
13151920Seric 	}
1324632Seric 
1337677Seric 	if (tTd(40, 1))
13464745Seric 		printf("\n>>>>> queueing %s%s >>>>>\n", e->e_id,
13564745Seric 			newid ? " (new id)" : "");
13664745Seric 	if (tTd(40, 9))
13764745Seric 	{
13864745Seric 		printf("  tfp=");
13964745Seric 		dumpfd(fileno(tfp), TRUE, FALSE);
14064745Seric 		printf("  lockfp=");
14164745Seric 		if (e->e_lockfp == NULL)
14264745Seric 			printf("NULL\n");
14364745Seric 		else
14464745Seric 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
14564745Seric 	}
1464632Seric 
1474632Seric 	/*
1486980Seric 	**  If there is no data file yet, create one.
1496980Seric 	*/
1506980Seric 
1516980Seric 	if (e->e_df == NULL)
1526980Seric 	{
1536980Seric 		register FILE *dfp;
1549389Seric 		extern putbody();
1556980Seric 
15664086Seric 		e->e_df = queuename(e, 'd');
15764086Seric 		e->e_df = newstr(e->e_df);
15866891Seric 		fd = open(e->e_df, O_WRONLY|O_CREAT|O_TRUNC, FileMode);
15964724Seric 		if (fd < 0 || (dfp = fdopen(fd, "w")) == NULL)
16065090Seric 			syserr("!queueup: cannot create data temp file %s, uid=%d",
16165090Seric 				e->e_df, geteuid());
16265870Seric 		bzero(&mcibuf, sizeof mcibuf);
16365870Seric 		mcibuf.mci_out = dfp;
16465870Seric 		mcibuf.mci_mailer = FileMailer;
16565870Seric 		(*e->e_putbody)(&mcibuf, e, NULL);
16658680Seric 		(void) xfclose(dfp, "queueup dfp", e->e_id);
1679389Seric 		e->e_putbody = putbody;
1686980Seric 	}
1696980Seric 
1706980Seric 	/*
1714632Seric 	**  Output future work requests.
17225687Seric 	**	Priority and creation time should be first, since
17325687Seric 	**	they are required by orderq.
1744632Seric 	*/
1754632Seric 
1769377Seric 	/* output message priority */
1779377Seric 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
1789377Seric 
1799630Seric 	/* output creation time */
1809630Seric 	fprintf(tfp, "T%ld\n", e->e_ctime);
1819630Seric 
18259093Seric 	/* output type and name of data file */
18359093Seric 	if (e->e_bodytype != NULL)
18459093Seric 		fprintf(tfp, "B%s\n", e->e_bodytype);
1857812Seric 	fprintf(tfp, "D%s\n", e->e_df);
1864632Seric 
18710108Seric 	/* message from envelope, if it exists */
18810108Seric 	if (e->e_message != NULL)
18910108Seric 		fprintf(tfp, "M%s\n", e->e_message);
19010108Seric 
19158737Seric 	/* send various flag bits through */
19258737Seric 	p = buf;
19358737Seric 	if (bitset(EF_WARNING, e->e_flags))
19458737Seric 		*p++ = 'w';
19558737Seric 	if (bitset(EF_RESPONSE, e->e_flags))
19658737Seric 		*p++ = 'r';
19767547Seric 	if (bitset(EF_HAS8BIT, e->e_flags))
19867547Seric 		*p++ = '8';
19958737Seric 	*p++ = '\0';
20058737Seric 	if (buf[0] != '\0')
20158737Seric 		fprintf(tfp, "F%s\n", buf);
20258737Seric 
20358957Seric 	/* $r and $s and $_ macro values */
20453400Seric 	if ((p = macvalue('r', e)) != NULL)
20553400Seric 		fprintf(tfp, "$r%s\n", p);
20653400Seric 	if ((p = macvalue('s', e)) != NULL)
20753400Seric 		fprintf(tfp, "$s%s\n", p);
20858957Seric 	if ((p = macvalue('_', e)) != NULL)
20958957Seric 		fprintf(tfp, "$_%s\n", p);
21053400Seric 
2114632Seric 	/* output name of sender */
2127812Seric 	fprintf(tfp, "S%s\n", e->e_from.q_paddr);
2134632Seric 
21455360Seric 	/* output list of error recipients */
21559670Seric 	printctladdr(NULL, NULL);
21655360Seric 	for (q = e->e_errorqueue; q != NULL; q = q->q_next)
21755360Seric 	{
21858680Seric 		if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
21955360Seric 		{
22059113Seric 			printctladdr(q, tfp);
22155360Seric 			fprintf(tfp, "E%s\n", q->q_paddr);
22255360Seric 		}
22355360Seric 	}
22455360Seric 
2254632Seric 	/* output list of recipient addresses */
2266980Seric 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
2274632Seric 	{
22858250Seric 		if (bitset(QQUEUEUP, q->q_flags) ||
22958680Seric 		    (queueall && !bitset(QDONTSEND|QBADADDR|QSENT, q->q_flags)))
2308245Seric 		{
23159113Seric 			printctladdr(q, tfp);
2327812Seric 			fprintf(tfp, "R%s\n", q->q_paddr);
2339377Seric 			if (announce)
2349377Seric 			{
2359377Seric 				e->e_to = q->q_paddr;
23658151Seric 				message("queued");
23758020Seric 				if (LogLevel > 8)
23864771Seric 					logdelivery(NULL, NULL, "queued", NULL, e);
2399377Seric 				e->e_to = NULL;
2409377Seric 			}
2419387Seric 			if (tTd(40, 1))
2429387Seric 			{
2439387Seric 				printf("queueing ");
2449387Seric 				printaddr(q, FALSE);
2459387Seric 			}
2468245Seric 		}
2474632Seric 	}
2484632Seric 
2499377Seric 	/*
2509377Seric 	**  Output headers for this message.
2519377Seric 	**	Expand macros completely here.  Queue run will deal with
2529377Seric 	**	everything as absolute headers.
2539377Seric 	**		All headers that must be relative to the recipient
2549377Seric 	**		can be cracked later.
25510173Seric 	**	We set up a "null mailer" -- i.e., a mailer that will have
25610173Seric 	**	no effect on the addresses as they are output.
2579377Seric 	*/
2589377Seric 
25910686Seric 	bzero((char *) &nullmailer, sizeof nullmailer);
26058020Seric 	nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
26165584Seric 			nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1;
26210349Seric 	nullmailer.m_eol = "\n";
26365870Seric 	bzero(&mcibuf, sizeof mcibuf);
26465870Seric 	mcibuf.mci_mailer = &nullmailer;
26565870Seric 	mcibuf.mci_out = tfp;
26610173Seric 
26758050Seric 	define('g', "\201f", e);
2686980Seric 	for (h = e->e_header; h != NULL; h = h->h_link)
2694632Seric 	{
27010686Seric 		extern bool bitzerop();
27110686Seric 
27212015Seric 		/* don't output null headers */
2734632Seric 		if (h->h_value == NULL || h->h_value[0] == '\0')
2744632Seric 			continue;
27512015Seric 
27612015Seric 		/* don't output resent headers on non-resent messages */
27712015Seric 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
27812015Seric 			continue;
27912015Seric 
28065267Seric 		/* expand macros; if null, don't output header at all */
28165267Seric 		if (bitset(H_DEFAULT, h->h_flags))
28265267Seric 		{
28365267Seric 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
28465267Seric 			if (buf[0] == '\0')
28565267Seric 				continue;
28665267Seric 		}
28765267Seric 
28812015Seric 		/* output this header */
2897812Seric 		fprintf(tfp, "H");
29012015Seric 
29112015Seric 		/* if conditional, output the set of conditions */
29210686Seric 		if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags))
29310686Seric 		{
29410686Seric 			int j;
29510686Seric 
29623098Seric 			(void) putc('?', tfp);
29710686Seric 			for (j = '\0'; j <= '\177'; j++)
29810686Seric 				if (bitnset(j, h->h_mflags))
29923098Seric 					(void) putc(j, tfp);
30023098Seric 			(void) putc('?', tfp);
30110686Seric 		}
30212015Seric 
30312015Seric 		/* output the header: expand macros, convert addresses */
3047763Seric 		if (bitset(H_DEFAULT, h->h_flags))
3057763Seric 		{
30665267Seric 			fprintf(tfp, "%s: %s\n", h->h_field, buf);
3077763Seric 		}
3088245Seric 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
3099348Seric 		{
31058737Seric 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
31163753Seric 			FILE *savetrace = TrafficLogFile;
31258737Seric 
31363753Seric 			TrafficLogFile = NULL;
31463753Seric 
31558737Seric 			if (bitset(H_FROM, h->h_flags))
31658737Seric 				oldstyle = FALSE;
31758737Seric 
31865870Seric 			commaize(h, h->h_value, oldstyle, &mcibuf, e);
31963753Seric 
32063753Seric 			TrafficLogFile = savetrace;
3219348Seric 		}
3227763Seric 		else
3238245Seric 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
3244632Seric 	}
3254632Seric 
3264632Seric 	/*
3274632Seric 	**  Clean up.
3284632Seric 	*/
3294632Seric 
33064762Seric 	if (fflush(tfp) < 0 || fsync(fileno(tfp)) < 0 || ferror(tfp))
33158732Seric 	{
33258732Seric 		if (newid)
33358732Seric 			syserr("!552 Error writing control file %s", tf);
33458732Seric 		else
33558732Seric 			syserr("!452 Error writing control file %s", tf);
33658732Seric 	}
33758732Seric 
33851920Seric 	if (!newid)
33951920Seric 	{
34064277Seric 		/* rename (locked) tf to be (locked) qf */
34151920Seric 		qf = queuename(e, 'q');
34251920Seric 		if (rename(tf, qf) < 0)
34365090Seric 			syserr("cannot rename(%s, %s), df=%s, uid=%d",
34465090Seric 				tf, qf, e->e_df, geteuid());
34564277Seric 
34664277Seric 		/* close and unlock old (locked) qf */
34751920Seric 		if (e->e_lockfp != NULL)
34858680Seric 			(void) xfclose(e->e_lockfp, "queueup lockfp", e->e_id);
34951920Seric 		e->e_lockfp = tfp;
35051920Seric 	}
35151920Seric 	else
35251920Seric 		qf = tf;
35341636Srick 	errno = 0;
35464745Seric 	e->e_flags |= EF_INQUEUE;
3557391Seric 
3567677Seric # ifdef LOG
3577677Seric 	/* save log info */
35858020Seric 	if (LogLevel > 79)
3597878Seric 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
36056795Seric # endif /* LOG */
36164307Seric 
36264307Seric 	if (tTd(40, 1))
36364307Seric 		printf("<<<<< done queueing %s <<<<<\n\n", e->e_id);
36451920Seric 	return;
3654632Seric }
36654974Seric 
36754974Seric printctladdr(a, tfp)
36859113Seric 	register ADDRESS *a;
36954974Seric 	FILE *tfp;
37054974Seric {
37159113Seric 	char *uname;
37259113Seric 	register struct passwd *pw;
37359113Seric 	register ADDRESS *q;
37459113Seric 	uid_t uid;
37559113Seric 	static ADDRESS *lastctladdr;
37659113Seric 	static uid_t lastuid;
37754974Seric 
37859113Seric 	/* initialization */
37963850Seric 	if (a == NULL || a->q_alias == NULL || tfp == NULL)
38054974Seric 	{
38159670Seric 		if (lastctladdr != NULL && tfp != NULL)
38259113Seric 			fprintf(tfp, "C\n");
38359113Seric 		lastctladdr = NULL;
38459113Seric 		lastuid = 0;
38554974Seric 		return;
38654974Seric 	}
38759113Seric 
38859113Seric 	/* find the active uid */
38959113Seric 	q = getctladdr(a);
39059113Seric 	if (q == NULL)
39159113Seric 		uid = 0;
39254974Seric 	else
39359113Seric 		uid = q->q_uid;
39463850Seric 	a = a->q_alias;
39559113Seric 
39659113Seric 	/* check to see if this is the same as last time */
39759113Seric 	if (lastctladdr != NULL && uid == lastuid &&
39859113Seric 	    strcmp(lastctladdr->q_paddr, a->q_paddr) == 0)
39959113Seric 		return;
40059113Seric 	lastuid = uid;
40159113Seric 	lastctladdr = a;
40259113Seric 
40359113Seric 	if (uid == 0 || (pw = getpwuid(uid)) == NULL)
40459270Seric 		uname = "";
40559113Seric 	else
40659113Seric 		uname = pw->pw_name;
40759113Seric 
40859113Seric 	fprintf(tfp, "C%s:%s\n", uname, a->q_paddr);
40954974Seric }
41054974Seric 
4114632Seric /*
4124632Seric **  RUNQUEUE -- run the jobs in the queue.
4134632Seric **
4144632Seric **	Gets the stuff out of the queue in some presumably logical
4154632Seric **	order and processes them.
4164632Seric **
4174632Seric **	Parameters:
41824941Seric **		forkflag -- TRUE if the queue scanning should be done in
41924941Seric **			a child process.  We double-fork so it is not our
42024941Seric **			child and we don't have to clean up after it.
4214632Seric **
4224632Seric **	Returns:
4234632Seric **		none.
4244632Seric **
4254632Seric **	Side Effects:
4264632Seric **		runs things in the mail queue.
4274632Seric */
4284632Seric 
42955360Seric ENVELOPE	QueueEnvelope;		/* the queue run envelope */
43055360Seric 
43155360Seric runqueue(forkflag)
4324639Seric 	bool forkflag;
4334632Seric {
43455360Seric 	register ENVELOPE *e;
43555360Seric 	extern ENVELOPE BlankEnvelope;
43624953Seric 
4377466Seric 	/*
43824953Seric 	**  If no work will ever be selected, don't even bother reading
43924953Seric 	**  the queue.
44024953Seric 	*/
44124953Seric 
44251920Seric 	CurrentLA = getla();	/* get load average */
44340934Srick 
44458132Seric 	if (shouldqueue(0L, curtime()))
44524953Seric 	{
44624953Seric 		if (Verbose)
44724953Seric 			printf("Skipping queue run -- load average too high\n");
44858107Seric 		if (forkflag && QueueIntvl != 0)
44958107Seric 			(void) setevent(QueueIntvl, runqueue, TRUE);
45055360Seric 		return;
45124953Seric 	}
45224953Seric 
45324953Seric 	/*
4547466Seric 	**  See if we want to go off and do other useful work.
4557466Seric 	*/
4564639Seric 
4574639Seric 	if (forkflag)
4584639Seric 	{
4597943Seric 		int pid;
46065223Seric #ifdef SIGCHLD
46165223Seric 		extern void reapchild();
4627943Seric 
46365223Seric 		(void) setsignal(SIGCHLD, reapchild);
46465223Seric #endif
46565223Seric 
4667943Seric 		pid = dofork();
4677943Seric 		if (pid != 0)
4684639Seric 		{
4697943Seric 			/* parent -- pick up intermediate zombie */
47025184Seric #ifndef SIGCHLD
4719377Seric 			(void) waitfor(pid);
47256795Seric #endif /* SIGCHLD */
4737690Seric 			if (QueueIntvl != 0)
4749348Seric 				(void) setevent(QueueIntvl, runqueue, TRUE);
4754639Seric 			return;
4764639Seric 		}
4777943Seric 		/* child -- double fork */
47825184Seric #ifndef SIGCHLD
4797943Seric 		if (fork() != 0)
4807943Seric 			exit(EX_OK);
48156795Seric #else /* SIGCHLD */
48264035Seric 		(void) setsignal(SIGCHLD, SIG_DFL);
48356795Seric #endif /* SIGCHLD */
4844639Seric 	}
48524941Seric 
48640934Srick 	setproctitle("running queue: %s", QueueDir);
48724941Seric 
4887876Seric # ifdef LOG
48958020Seric 	if (LogLevel > 69)
49055360Seric 		syslog(LOG_DEBUG, "runqueue %s, pid=%d, forkflag=%d",
49155360Seric 			QueueDir, getpid(), forkflag);
49256795Seric # endif /* LOG */
4934639Seric 
4947466Seric 	/*
49510205Seric 	**  Release any resources used by the daemon code.
49610205Seric 	*/
49710205Seric 
49810205Seric # ifdef DAEMON
49910205Seric 	clrdaemon();
50056795Seric # endif /* DAEMON */
50110205Seric 
50264658Seric 	/* force it to run expensive jobs */
50364658Seric 	NoConnect = FALSE;
50464658Seric 
50510205Seric 	/*
50655360Seric 	**  Create ourselves an envelope
50755360Seric 	*/
50855360Seric 
50955360Seric 	CurEnv = &QueueEnvelope;
51058179Seric 	e = newenvelope(&QueueEnvelope, CurEnv);
51155360Seric 	e->e_flags = BlankEnvelope.e_flags;
51255360Seric 
51355360Seric 	/*
51427175Seric 	**  Make sure the alias database is open.
51527175Seric 	*/
51627175Seric 
51760537Seric 	initmaps(FALSE, e);
51827175Seric 
51927175Seric 	/*
5207466Seric 	**  Start making passes through the queue.
5217466Seric 	**	First, read and sort the entire queue.
5227466Seric 	**	Then, process the work in that order.
5237466Seric 	**		But if you take too long, start over.
5247466Seric 	*/
5257466Seric 
5267943Seric 	/* order the existing work requests */
52724954Seric 	(void) orderq(FALSE);
5287690Seric 
5297943Seric 	/* process them once at a time */
5307943Seric 	while (WorkQ != NULL)
5314639Seric 	{
5327943Seric 		WORK *w = WorkQ;
5337881Seric 
5347943Seric 		WorkQ = WorkQ->w_next;
53558884Seric 
53658884Seric 		/*
53758884Seric 		**  Ignore jobs that are too expensive for the moment.
53858884Seric 		*/
53958884Seric 
54058884Seric 		if (shouldqueue(w->w_pri, w->w_ctime))
54158884Seric 		{
54258884Seric 			if (Verbose)
54358884Seric 				printf("\nSkipping %s\n", w->w_name + 2);
54458884Seric 		}
54558930Seric 		else
54658930Seric 		{
54764296Seric 			pid_t pid;
54864296Seric 			extern pid_t dowork();
54964296Seric 
55064296Seric 			pid = dowork(w->w_name + 2, ForkQueueRuns, FALSE, e);
55164296Seric 			errno = 0;
55266316Seric 			if (pid != 0)
55366316Seric 				(void) waitfor(pid);
55458930Seric 		}
5557943Seric 		free(w->w_name);
556*67612Seric 		if (w->w_host)
557*67612Seric 			free(w->w_host);
5587943Seric 		free((char *) w);
5594639Seric 	}
56029866Seric 
56129866Seric 	/* exit without the usual cleanup */
56255467Seric 	e->e_id = NULL;
56355467Seric 	finis();
5644634Seric }
5654634Seric /*
5664632Seric **  ORDERQ -- order the work queue.
5674632Seric **
5684632Seric **	Parameters:
56924941Seric **		doall -- if set, include everything in the queue (even
57024941Seric **			the jobs that cannot be run because the load
57124941Seric **			average is too high).  Otherwise, exclude those
57224941Seric **			jobs.
5734632Seric **
5744632Seric **	Returns:
57510121Seric **		The number of request in the queue (not necessarily
57610121Seric **		the number of requests in WorkQ however).
5774632Seric **
5784632Seric **	Side Effects:
5794632Seric **		Sets WorkQ to the queue of available work, in order.
5804632Seric */
5814632Seric 
58225687Seric # define NEED_P		001
58325687Seric # define NEED_T		002
58458318Seric # define NEED_R		004
58558318Seric # define NEED_S		010
5864632Seric 
58724941Seric orderq(doall)
58824941Seric 	bool doall;
5894632Seric {
59060219Seric 	register struct dirent *d;
5914632Seric 	register WORK *w;
5926625Sglickman 	DIR *f;
5934632Seric 	register int i;
59425687Seric 	WORK wlist[QUEUESIZE+1];
59510070Seric 	int wn = -1;
596*67612Seric 	int wc;
5974632Seric 
59858318Seric 	if (tTd(41, 1))
59958318Seric 	{
60058318Seric 		printf("orderq:\n");
60158318Seric 		if (QueueLimitId != NULL)
60258318Seric 			printf("\tQueueLimitId = %s\n", QueueLimitId);
60358318Seric 		if (QueueLimitSender != NULL)
60458318Seric 			printf("\tQueueLimitSender = %s\n", QueueLimitSender);
60558318Seric 		if (QueueLimitRecipient != NULL)
60658318Seric 			printf("\tQueueLimitRecipient = %s\n", QueueLimitRecipient);
60758318Seric 	}
60858318Seric 
6094632Seric 	/* clear out old WorkQ */
6104632Seric 	for (w = WorkQ; w != NULL; )
6114632Seric 	{
6124632Seric 		register WORK *nw = w->w_next;
6134632Seric 
6144632Seric 		WorkQ = nw;
6154632Seric 		free(w->w_name);
616*67612Seric 		if (w->w_host)
617*67612Seric 			free(w->w_host);
6184632Seric 		free((char *) w);
6194632Seric 		w = nw;
6204632Seric 	}
6214632Seric 
6224632Seric 	/* open the queue directory */
6238148Seric 	f = opendir(".");
6244632Seric 	if (f == NULL)
6254632Seric 	{
6268148Seric 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
62710070Seric 		return (0);
6284632Seric 	}
6294632Seric 
6304632Seric 	/*
6314632Seric 	**  Read the work directory.
6324632Seric 	*/
6334632Seric 
63410070Seric 	while ((d = readdir(f)) != NULL)
6354632Seric 	{
6369377Seric 		FILE *cf;
63764492Seric 		register char *p;
6384632Seric 		char lbuf[MAXNAME];
63958318Seric 		extern bool strcontainedin();
6404632Seric 
6414632Seric 		/* is this an interesting entry? */
6427812Seric 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
6434632Seric 			continue;
6444632Seric 
64558318Seric 		if (QueueLimitId != NULL &&
64658318Seric 		    !strcontainedin(QueueLimitId, d->d_name))
64758318Seric 			continue;
64858318Seric 
64958722Seric 		/*
65058722Seric 		**  Check queue name for plausibility.  This handles
65158722Seric 		**  both old and new type ids.
65258722Seric 		*/
65358722Seric 
65464492Seric 		p = d->d_name + 2;
65564492Seric 		if (isupper(p[0]) && isupper(p[2]))
65664492Seric 			p += 3;
65764492Seric 		else if (isupper(p[1]))
65864492Seric 			p += 2;
65964492Seric 		else
66064492Seric 			p = d->d_name;
66164492Seric 		for (i = 0; isdigit(*p); p++)
66264492Seric 			i++;
66364492Seric 		if (i < 5 || *p != '\0')
66458020Seric 		{
66558020Seric 			if (Verbose)
66658020Seric 				printf("orderq: bogus qf name %s\n", d->d_name);
66758020Seric #ifdef LOG
66858020Seric 			if (LogLevel > 3)
66959615Seric 				syslog(LOG_CRIT, "orderq: bogus qf name %s",
67058020Seric 					d->d_name);
67158020Seric #endif
67258020Seric 			if (strlen(d->d_name) >= MAXNAME)
67358020Seric 				d->d_name[MAXNAME - 1] = '\0';
67458020Seric 			strcpy(lbuf, d->d_name);
67558020Seric 			lbuf[0] = 'Q';
67658020Seric 			(void) rename(d->d_name, lbuf);
67758020Seric 			continue;
67858020Seric 		}
67958020Seric 
68010070Seric 		/* yes -- open control file (if not too many files) */
68125687Seric 		if (++wn >= QUEUESIZE)
68210070Seric 			continue;
68358318Seric 
6848148Seric 		cf = fopen(d->d_name, "r");
6854632Seric 		if (cf == NULL)
6864632Seric 		{
6877055Seric 			/* this may be some random person sending hir msgs */
6887055Seric 			/* syserr("orderq: cannot open %s", cbuf); */
68910090Seric 			if (tTd(41, 2))
69010090Seric 				printf("orderq: cannot open %s (%d)\n",
69110090Seric 					d->d_name, errno);
6927055Seric 			errno = 0;
69310090Seric 			wn--;
6944632Seric 			continue;
6954632Seric 		}
69625687Seric 		w = &wlist[wn];
69725687Seric 		w->w_name = newstr(d->d_name);
698*67612Seric 		w->w_host = NULL;
699*67612Seric 		w->w_lock = !lockfile(fileno(cf), w->w_name, NULL, LOCK_SH|LOCK_NB);
7004632Seric 
70125027Seric 		/* make sure jobs in creation don't clog queue */
70225687Seric 		w->w_pri = 0x7fffffff;
70325687Seric 		w->w_ctime = 0;
70425027Seric 
7054632Seric 		/* extract useful information */
70625687Seric 		i = NEED_P | NEED_T;
70758318Seric 		if (QueueLimitSender != NULL)
70858318Seric 			i |= NEED_S;
709*67612Seric 		if (SortQueueByHost || QueueLimitRecipient != NULL)
71058318Seric 			i |= NEED_R;
71125687Seric 		while (i != 0 && fgets(lbuf, sizeof lbuf, cf) != NULL)
7124632Seric 		{
71324954Seric 			extern long atol();
71458318Seric 			extern bool strcontainedin();
71524954Seric 
71624941Seric 			switch (lbuf[0])
7174632Seric 			{
71824941Seric 			  case 'P':
71925687Seric 				w->w_pri = atol(&lbuf[1]);
72025687Seric 				i &= ~NEED_P;
7214632Seric 				break;
72225013Seric 
72325013Seric 			  case 'T':
72425687Seric 				w->w_ctime = atol(&lbuf[1]);
72525687Seric 				i &= ~NEED_T;
72625013Seric 				break;
72758318Seric 
72858318Seric 			  case 'R':
729*67612Seric 				if (w->w_host == NULL &&
730*67612Seric 				    (p = strrchr(&lbuf[1], '@')) != NULL)
731*67612Seric 					w->w_host = newstr(&p[1]);
732*67612Seric 				if (QueueLimitRecipient == NULL ||
73358318Seric 				    strcontainedin(QueueLimitRecipient, &lbuf[1]))
73458318Seric 					i &= ~NEED_R;
73558318Seric 				break;
73658318Seric 
73758318Seric 			  case 'S':
73858318Seric 				if (QueueLimitSender != NULL &&
73958318Seric 				    strcontainedin(QueueLimitSender, &lbuf[1]))
74058318Seric 					i &= ~NEED_S;
74158318Seric 				break;
7424632Seric 			}
7434632Seric 		}
7444632Seric 		(void) fclose(cf);
74524953Seric 
74658318Seric 		if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
74758318Seric 		    bitset(NEED_R|NEED_S, i))
74824953Seric 		{
74924953Seric 			/* don't even bother sorting this job in */
750*67612Seric 			free(w->w_name);
751*67612Seric 			if (w->w_host)
752*67612Seric 				free(w->w_host);
75324953Seric 			wn--;
75424953Seric 		}
7554632Seric 	}
7566625Sglickman 	(void) closedir(f);
75710090Seric 	wn++;
7584632Seric 
759*67612Seric 	wc = min(wn, QUEUESIZE);
7604632Seric 
761*67612Seric 	if (!SortQueueByHost)
762*67612Seric 	{
763*67612Seric 		extern workcmpf0();
7644632Seric 
765*67612Seric 		/*
766*67612Seric 		**  Simple sort based on queue priority only.
767*67612Seric 		*/
768*67612Seric 
769*67612Seric 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf0);
770*67612Seric 	}
771*67612Seric 	else
772*67612Seric 	{
773*67612Seric 		extern workcmpf1();
774*67612Seric 		extern workcmpf2();
775*67612Seric 
776*67612Seric 		/*
777*67612Seric 		**  Sort the work directory for the first time,
778*67612Seric 		**  based on host name, lock status, and priority.
779*67612Seric 		*/
780*67612Seric 
781*67612Seric 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf1);
782*67612Seric 
783*67612Seric 		/*
784*67612Seric 		**  If one message to host is locked, "lock" all messages
785*67612Seric 		**  to that host.
786*67612Seric 		*/
787*67612Seric 
788*67612Seric 		i = 0;
789*67612Seric 		while (i < wc)
790*67612Seric 		{
791*67612Seric 			if (!wlist[i].w_lock)
792*67612Seric 			{
793*67612Seric 				i++;
794*67612Seric 				continue;
795*67612Seric 			}
796*67612Seric 			w = &wlist[i];
797*67612Seric 			while (++i < wc)
798*67612Seric 			{
799*67612Seric 				if (wlist[i].w_host == NULL &&
800*67612Seric 				    w->w_host == NULL)
801*67612Seric 					wlist[i].w_lock = TRUE;
802*67612Seric 				else if (wlist[i].w_host != NULL &&
803*67612Seric 					 w->w_host != NULL &&
804*67612Seric 					 strcmp(wlist[i].w_host, w->w_host) == 0)
805*67612Seric 					wlist[i].w_lock = TRUE;
806*67612Seric 				else
807*67612Seric 					break;
808*67612Seric 			}
809*67612Seric 		}
810*67612Seric 
811*67612Seric 		/*
812*67612Seric 		**  Sort the work directory for the second time,
813*67612Seric 		**  based on lock status, host name, and priority.
814*67612Seric 		*/
815*67612Seric 
816*67612Seric 		qsort((char *) wlist, wc, sizeof *wlist, workcmpf2);
817*67612Seric 	}
818*67612Seric 
8194632Seric 	/*
8204632Seric 	**  Convert the work list into canonical form.
8219377Seric 	**	Should be turning it into a list of envelopes here perhaps.
8224632Seric 	*/
8234632Seric 
82424981Seric 	WorkQ = NULL;
825*67612Seric 	for (i = wc; --i >= 0; )
8264632Seric 	{
8274632Seric 		w = (WORK *) xalloc(sizeof *w);
8284632Seric 		w->w_name = wlist[i].w_name;
829*67612Seric 		w->w_host = wlist[i].w_host;
830*67612Seric 		w->w_lock = wlist[i].w_lock;
8314632Seric 		w->w_pri = wlist[i].w_pri;
83225013Seric 		w->w_ctime = wlist[i].w_ctime;
83324981Seric 		w->w_next = WorkQ;
83424981Seric 		WorkQ = w;
8354632Seric 	}
8364632Seric 
8377677Seric 	if (tTd(40, 1))
8384632Seric 	{
8394632Seric 		for (w = WorkQ; w != NULL; w = w->w_next)
8405037Seric 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
8414632Seric 	}
84210070Seric 
84310090Seric 	return (wn);
8444632Seric }
8454632Seric /*
846*67612Seric **  WORKCMPF0 -- simple priority-only compare function.
8474632Seric **
8484632Seric **	Parameters:
8494632Seric **		a -- the first argument.
8504632Seric **		b -- the second argument.
8514632Seric **
8524632Seric **	Returns:
85324981Seric **		-1 if a < b
85424981Seric **		 0 if a == b
85524981Seric **		+1 if a > b
8564632Seric **
8574632Seric **	Side Effects:
8584632Seric **		none.
8594632Seric */
8604632Seric 
861*67612Seric workcmpf0(a, b)
8625037Seric 	register WORK *a;
8635037Seric 	register WORK *b;
8644632Seric {
86557438Seric 	long pa = a->w_pri;
86657438Seric 	long pb = b->w_pri;
86724941Seric 
86824941Seric 	if (pa == pb)
869*67612Seric 		return 0;
87024941Seric 	else if (pa > pb)
871*67612Seric 		return 1;
87224981Seric 	else
873*67612Seric 		return -1;
8744632Seric }
8754632Seric /*
876*67612Seric **  WORKCMPF1 -- first compare function for ordering work based on host name.
877*67612Seric **
878*67612Seric **	Sorts on host name, lock status, and priority in that order.
879*67612Seric **
880*67612Seric **	Parameters:
881*67612Seric **		a -- the first argument.
882*67612Seric **		b -- the second argument.
883*67612Seric **
884*67612Seric **	Returns:
885*67612Seric **		<0 if a < b
886*67612Seric **		 0 if a == b
887*67612Seric **		>0 if a > b
888*67612Seric **
889*67612Seric **	Side Effects:
890*67612Seric **		none.
891*67612Seric */
892*67612Seric 
893*67612Seric workcmpf1(a, b)
894*67612Seric 	register WORK *a;
895*67612Seric 	register WORK *b;
896*67612Seric {
897*67612Seric 	int i;
898*67612Seric 
899*67612Seric 	/* host name */
900*67612Seric 	if (a->w_host != NULL && b->w_host == NULL)
901*67612Seric 		return 1;
902*67612Seric 	else if (a->w_host == NULL && b->w_host != NULL)
903*67612Seric 		return -1;
904*67612Seric 	if (a->w_host != NULL && b->w_host != NULL &&
905*67612Seric 	    (i = strcmp(a->w_host, b->w_host)))
906*67612Seric 		return i;
907*67612Seric 
908*67612Seric 	/* lock status */
909*67612Seric 	if (a->w_lock != b->w_lock)
910*67612Seric 		return b->w_lock - a->w_lock;
911*67612Seric 
912*67612Seric 	/* job priority */
913*67612Seric 	return a->w_pri - b->w_pri;
914*67612Seric }
915*67612Seric /*
916*67612Seric **  WORKCMPF2 -- second compare function for ordering work based on host name.
917*67612Seric **
918*67612Seric **	Sorts on lock status, host name, and priority in that order.
919*67612Seric **
920*67612Seric **	Parameters:
921*67612Seric **		a -- the first argument.
922*67612Seric **		b -- the second argument.
923*67612Seric **
924*67612Seric **	Returns:
925*67612Seric **		<0 if a < b
926*67612Seric **		 0 if a == b
927*67612Seric **		>0 if a > b
928*67612Seric **
929*67612Seric **	Side Effects:
930*67612Seric **		none.
931*67612Seric */
932*67612Seric 
933*67612Seric workcmpf2(a, b)
934*67612Seric 	register WORK *a;
935*67612Seric 	register WORK *b;
936*67612Seric {
937*67612Seric 	int i;
938*67612Seric 
939*67612Seric 	/* lock status */
940*67612Seric 	if (a->w_lock != b->w_lock)
941*67612Seric 		return a->w_lock - b->w_lock;
942*67612Seric 
943*67612Seric 	/* host name */
944*67612Seric 	if (a->w_host != NULL && b->w_host == NULL)
945*67612Seric 		return 1;
946*67612Seric 	else if (a->w_host == NULL && b->w_host != NULL)
947*67612Seric 		return -1;
948*67612Seric 	if (a->w_host != NULL && b->w_host != NULL &&
949*67612Seric 	    (i = strcmp(a->w_host, b->w_host)))
950*67612Seric 		return i;
951*67612Seric 
952*67612Seric 	/* job priority */
953*67612Seric 	return a->w_pri - b->w_pri;
954*67612Seric }
955*67612Seric /*
9564632Seric **  DOWORK -- do a work request.
9574632Seric **
9584632Seric **	Parameters:
95958884Seric **		id -- the ID of the job to run.
96058884Seric **		forkflag -- if set, run this in background.
96158924Seric **		requeueflag -- if set, reinstantiate the queue quickly.
96258924Seric **			This is used when expanding aliases in the queue.
96361094Seric **			If forkflag is also set, it doesn't wait for the
96461094Seric **			child.
96558884Seric **		e - the envelope in which to run it.
9664632Seric **
9674632Seric **	Returns:
96864296Seric **		process id of process that is running the queue job.
9694632Seric **
9704632Seric **	Side Effects:
9714632Seric **		The work request is satisfied if possible.
9724632Seric */
9734632Seric 
97464296Seric pid_t
97558924Seric dowork(id, forkflag, requeueflag, e)
97658884Seric 	char *id;
97758884Seric 	bool forkflag;
97858924Seric 	bool requeueflag;
97955012Seric 	register ENVELOPE *e;
9804632Seric {
98164296Seric 	register pid_t pid;
98251920Seric 	extern bool readqf();
9834632Seric 
9847677Seric 	if (tTd(40, 1))
98558884Seric 		printf("dowork(%s)\n", id);
9864632Seric 
9874632Seric 	/*
98824941Seric 	**  Fork for work.
98924941Seric 	*/
99024941Seric 
99158884Seric 	if (forkflag)
99224941Seric 	{
99364296Seric 		pid = fork();
99464296Seric 		if (pid < 0)
99524941Seric 		{
99624941Seric 			syserr("dowork: cannot fork");
99764296Seric 			return 0;
99824941Seric 		}
99964839Seric 		else if (pid > 0)
100064839Seric 		{
100164839Seric 			/* parent -- clean out connection cache */
100264839Seric 			mci_flush(FALSE, NULL);
100364839Seric 		}
100424941Seric 	}
100524941Seric 	else
100624941Seric 	{
100764296Seric 		pid = 0;
100824941Seric 	}
100924941Seric 
101064296Seric 	if (pid == 0)
10114632Seric 	{
10124632Seric 		/*
10134632Seric 		**  CHILD
10148148Seric 		**	Lock the control file to avoid duplicate deliveries.
10158148Seric 		**		Then run the file as though we had just read it.
10167350Seric 		**	We save an idea of the temporary name so we
10177350Seric 		**		can recover on interrupt.
10184632Seric 		*/
10194632Seric 
10207763Seric 		/* set basic modes, etc. */
10217356Seric 		(void) alarm(0);
102255012Seric 		clearenvelope(e, FALSE);
102364554Seric 		e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
102458734Seric 		e->e_errormode = EM_MAIL;
102558884Seric 		e->e_id = id;
102664765Seric 		GrabTo = UseErrorsTo = FALSE;
102766316Seric 		ExitStat = EX_OK;
102863846Seric 		if (forkflag)
102964554Seric 		{
103064296Seric 			disconnect(1, e);
103164554Seric 			OpMode = MD_DELIVER;
103264554Seric 		}
10337876Seric # ifdef LOG
103458020Seric 		if (LogLevel > 76)
103555012Seric 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", e->e_id,
10367881Seric 			       getpid());
103756795Seric # endif /* LOG */
10387763Seric 
10397763Seric 		/* don't use the headers from sendmail.cf... */
104055012Seric 		e->e_header = NULL;
10417763Seric 
104251920Seric 		/* read the queue control file -- return if locked */
104365200Seric 		if (!readqf(e))
10446980Seric 		{
104558884Seric 			if (tTd(40, 4))
104658884Seric 				printf("readqf(%s) failed\n", e->e_id);
104758884Seric 			if (forkflag)
104824941Seric 				exit(EX_OK);
104924941Seric 			else
105066316Seric 				return 0;
10516980Seric 		}
10526980Seric 
105355012Seric 		e->e_flags |= EF_INQUEUE;
105458929Seric 		eatheader(e, requeueflag);
10556980Seric 
105658924Seric 		if (requeueflag)
105758924Seric 			queueup(e, TRUE, FALSE);
105858924Seric 
10596980Seric 		/* do the delivery */
106058915Seric 		sendall(e, SM_DELIVER);
10616980Seric 
10626980Seric 		/* finish up and exit */
106358884Seric 		if (forkflag)
106424941Seric 			finis();
106524941Seric 		else
106655012Seric 			dropenvelope(e);
10674632Seric 	}
106864296Seric 	e->e_id = NULL;
106964296Seric 	return pid;
10704632Seric }
10714632Seric /*
10724632Seric **  READQF -- read queue file and set up environment.
10734632Seric **
10744632Seric **	Parameters:
10759377Seric **		e -- the envelope of the job to run.
10764632Seric **
10774632Seric **	Returns:
107851920Seric **		TRUE if it successfully read the queue file.
107951920Seric **		FALSE otherwise.
10804632Seric **
10814632Seric **	Side Effects:
108251920Seric **		The queue file is returned locked.
10834632Seric */
10844632Seric 
108551920Seric bool
108665200Seric readqf(e)
10879377Seric 	register ENVELOPE *e;
10884632Seric {
108917477Seric 	register FILE *qfp;
109054974Seric 	ADDRESS *ctladdr;
109156400Seric 	struct stat st;
109257135Seric 	char *bp;
109358915Seric 	char qf[20];
109457135Seric 	char buf[MAXLINE];
109524954Seric 	extern long atol();
109654974Seric 	extern ADDRESS *setctluser();
10974632Seric 
10984632Seric 	/*
109917468Seric 	**  Read and process the file.
11004632Seric 	*/
11014632Seric 
110258915Seric 	strcpy(qf, queuename(e, 'q'));
110351937Seric 	qfp = fopen(qf, "r+");
110417477Seric 	if (qfp == NULL)
110517477Seric 	{
110658884Seric 		if (tTd(40, 8))
110758884Seric 			printf("readqf(%s): fopen failure (%s)\n",
110858884Seric 				qf, errstring(errno));
110940934Srick 		if (errno != ENOENT)
111040934Srick 			syserr("readqf: no control file %s", qf);
111151920Seric 		return FALSE;
111217477Seric 	}
111340934Srick 
111464335Seric 	if (!lockfile(fileno(qfp), qf, NULL, LOCK_EX|LOCK_NB))
111564277Seric 	{
111664277Seric 		/* being processed by another queuer */
111764277Seric 		if (tTd(40, 8))
111864277Seric 			printf("readqf(%s): locked\n", qf);
111964277Seric 		if (Verbose)
112064277Seric 			printf("%s: locked\n", e->e_id);
112164277Seric # ifdef LOG
112264277Seric 		if (LogLevel > 19)
112364277Seric 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
112464277Seric # endif /* LOG */
112564277Seric 		(void) fclose(qfp);
112664277Seric 		return FALSE;
112764277Seric 	}
112864277Seric 
112956400Seric 	/*
113056400Seric 	**  Check the queue file for plausibility to avoid attacks.
113156400Seric 	*/
113256400Seric 
113356400Seric 	if (fstat(fileno(qfp), &st) < 0)
113456400Seric 	{
113556400Seric 		/* must have been being processed by someone else */
113658884Seric 		if (tTd(40, 8))
113758884Seric 			printf("readqf(%s): fstat failure (%s)\n",
113858884Seric 				qf, errstring(errno));
113956400Seric 		fclose(qfp);
114056400Seric 		return FALSE;
114156400Seric 	}
114256400Seric 
114364137Seric 	if (st.st_uid != geteuid())
114456400Seric 	{
114556400Seric # ifdef LOG
114656400Seric 		if (LogLevel > 0)
114756400Seric 		{
114856400Seric 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
114956400Seric 				e->e_id, st.st_uid, st.st_mode);
115056400Seric 		}
115156795Seric # endif /* LOG */
115258884Seric 		if (tTd(40, 8))
115358884Seric 			printf("readqf(%s): bogus file\n", qf);
115464277Seric 		rename(qf, queuename(e, 'Q'));
115556400Seric 		fclose(qfp);
115656400Seric 		return FALSE;
115756400Seric 	}
115856400Seric 
115964277Seric 	if (st.st_size == 0)
116040934Srick 	{
116164277Seric 		/* must be a bogus file -- just remove it */
116264277Seric 		(void) unlink(qf);
116364277Seric 		fclose(qfp);
116451920Seric 		return FALSE;
116540934Srick 	}
116640934Srick 
116764277Seric 	if (st.st_nlink == 0)
116859101Seric 	{
116964277Seric 		/*
117064277Seric 		**  Race condition -- we got a file just as it was being
117164277Seric 		**  unlinked.  Just assume it is zero length.
117264277Seric 		*/
117364277Seric 
117459101Seric 		fclose(qfp);
117559101Seric 		return FALSE;
117659101Seric 	}
117759101Seric 
117864277Seric 	/* good file -- save this lock */
117951920Seric 	e->e_lockfp = qfp;
118051920Seric 
118140934Srick 	/* do basic system initialization */
118255012Seric 	initsys(e);
118365164Seric 	define('i', e->e_id, e);
118440934Srick 
11859377Seric 	LineNumber = 0;
118663850Seric 	e->e_flags |= EF_GLOBALERRS;
118763850Seric 	OpMode = MD_DELIVER;
118851920Seric 	if (Verbose)
11899377Seric 		printf("\nRunning %s\n", e->e_id);
119054974Seric 	ctladdr = NULL;
119157135Seric 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
11924632Seric 	{
119358737Seric 		register char *p;
119457529Seric 		struct stat st;
119557529Seric 
119626504Seric 		if (tTd(40, 4))
119757135Seric 			printf("+++++ %s\n", bp);
119857135Seric 		switch (bp[0])
11994632Seric 		{
120040973Sbostic 		  case 'C':		/* specify controlling user */
120157135Seric 			ctladdr = setctluser(&bp[1]);
120240973Sbostic 			break;
120340973Sbostic 
12044632Seric 		  case 'R':		/* specify recipient */
120558082Seric 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
12064632Seric 			break;
12074632Seric 
120825687Seric 		  case 'E':		/* specify error recipient */
120958082Seric 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
121025687Seric 			break;
121125687Seric 
12124632Seric 		  case 'H':		/* header */
121357135Seric 			(void) chompheader(&bp[1], FALSE, e);
12144632Seric 			break;
12154632Seric 
121610108Seric 		  case 'M':		/* message */
121764705Seric 			/* ignore this; we want a new message next time */
121810108Seric 			break;
121910108Seric 
12204632Seric 		  case 'S':		/* sender */
122158704Seric 			setsender(newstr(&bp[1]), e, NULL, TRUE);
12224632Seric 			break;
12234632Seric 
122459093Seric 		  case 'B':		/* body type */
122559093Seric 			e->e_bodytype = newstr(&bp[1]);
122659093Seric 			break;
122759093Seric 
12284632Seric 		  case 'D':		/* data file name */
122957135Seric 			e->e_df = newstr(&bp[1]);
12309544Seric 			e->e_dfp = fopen(e->e_df, "r");
12319544Seric 			if (e->e_dfp == NULL)
123258020Seric 			{
12339377Seric 				syserr("readqf: cannot open %s", e->e_df);
123458020Seric 				e->e_msgsize = -1;
123558020Seric 			}
123658020Seric 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
123757529Seric 				e->e_msgsize = st.st_size;
12384632Seric 			break;
12394632Seric 
12407860Seric 		  case 'T':		/* init time */
124157135Seric 			e->e_ctime = atol(&bp[1]);
12424632Seric 			break;
12434632Seric 
12444634Seric 		  case 'P':		/* message priority */
124557135Seric 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
12464634Seric 			break;
12474634Seric 
124858737Seric 		  case 'F':		/* flag bits */
124958737Seric 			for (p = &bp[1]; *p != '\0'; p++)
125058737Seric 			{
125158737Seric 				switch (*p)
125258737Seric 				{
125358737Seric 				  case 'w':	/* warning sent */
125458737Seric 					e->e_flags |= EF_WARNING;
125558737Seric 					break;
125658737Seric 
125758737Seric 				  case 'r':	/* response */
125858737Seric 					e->e_flags |= EF_RESPONSE;
125958737Seric 					break;
126067547Seric 
126167547Seric 				  case '8':	/* has 8 bit data */
126267547Seric 					e->e_flags |= EF_HAS8BIT;
126367547Seric 					break;
126458737Seric 				}
126558737Seric 			}
126658737Seric 			break;
126758737Seric 
126853400Seric 		  case '$':		/* define macro */
126957135Seric 			define(bp[1], newstr(&bp[2]), e);
127053400Seric 			break;
127153400Seric 
127224941Seric 		  case '\0':		/* blank line; ignore */
127324941Seric 			break;
127424941Seric 
12754632Seric 		  default:
127665960Seric 			syserr("readqf: %s: line %d: bad line \"%s\"",
127765200Seric 				qf, LineNumber, bp);
127863753Seric 			fclose(qfp);
127963753Seric 			rename(qf, queuename(e, 'Q'));
128063753Seric 			return FALSE;
12814632Seric 		}
128257135Seric 
128357135Seric 		if (bp != buf)
128457135Seric 			free(bp);
12854632Seric 	}
12869377Seric 
128724941Seric 	/*
128824941Seric 	**  If we haven't read any lines, this queue file is empty.
128924941Seric 	**  Arrange to remove it without referencing any null pointers.
129024941Seric 	*/
129124941Seric 
129224941Seric 	if (LineNumber == 0)
129324941Seric 	{
129424941Seric 		errno = 0;
129524941Seric 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
129624941Seric 	}
129751920Seric 	return TRUE;
12984632Seric }
12994632Seric /*
13009630Seric **  PRINTQUEUE -- print out a representation of the mail queue
13019630Seric **
13029630Seric **	Parameters:
13039630Seric **		none.
13049630Seric **
13059630Seric **	Returns:
13069630Seric **		none.
13079630Seric **
13089630Seric **	Side Effects:
13099630Seric **		Prints a listing of the mail queue on the standard output.
13109630Seric */
13115182Seric 
13129630Seric printqueue()
13139630Seric {
13149630Seric 	register WORK *w;
13159630Seric 	FILE *f;
131610070Seric 	int nrequests;
13179630Seric 	char buf[MAXLINE];
13189630Seric 
13199630Seric 	/*
132058250Seric 	**  Check for permission to print the queue
132158250Seric 	*/
132258250Seric 
132364333Seric 	if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
132458250Seric 	{
132558250Seric 		struct stat st;
132658523Seric # ifdef NGROUPS
132758523Seric 		int n;
132863937Seric 		GIDSET_T gidset[NGROUPS];
132958523Seric # endif
133058250Seric 
133158517Seric 		if (stat(QueueDir, &st) < 0)
133258250Seric 		{
133358250Seric 			syserr("Cannot stat %s", QueueDir);
133458250Seric 			return;
133558250Seric 		}
133658523Seric # ifdef NGROUPS
133758523Seric 		n = getgroups(NGROUPS, gidset);
133858523Seric 		while (--n >= 0)
133958523Seric 		{
134058523Seric 			if (gidset[n] == st.st_gid)
134158523Seric 				break;
134258523Seric 		}
134358523Seric 		if (n < 0)
134458523Seric # else
134563787Seric 		if (RealGid != st.st_gid)
134658523Seric # endif
134758250Seric 		{
134858250Seric 			usrerr("510 You are not permitted to see the queue");
134958250Seric 			setstat(EX_NOPERM);
135058250Seric 			return;
135158250Seric 		}
135258250Seric 	}
135358250Seric 
135458250Seric 	/*
13559630Seric 	**  Read and order the queue.
13569630Seric 	*/
13579630Seric 
135824941Seric 	nrequests = orderq(TRUE);
13599630Seric 
13609630Seric 	/*
13619630Seric 	**  Print the work list that we have read.
13629630Seric 	*/
13639630Seric 
13649630Seric 	/* first see if there is anything */
136510070Seric 	if (nrequests <= 0)
13669630Seric 	{
136710070Seric 		printf("Mail queue is empty\n");
13689630Seric 		return;
13699630Seric 	}
13709630Seric 
137151920Seric 	CurrentLA = getla();	/* get load average */
137240934Srick 
137310096Seric 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
137425687Seric 	if (nrequests > QUEUESIZE)
137525687Seric 		printf(", only %d printed", QUEUESIZE);
137624979Seric 	if (Verbose)
137758716Seric 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
137824979Seric 	else
137958716Seric 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
13809630Seric 	for (w = WorkQ; w != NULL; w = w->w_next)
13819630Seric 	{
13829630Seric 		struct stat st;
138310070Seric 		auto time_t submittime = 0;
138410070Seric 		long dfsize = -1;
138558737Seric 		int flags = 0;
138610108Seric 		char message[MAXLINE];
138759093Seric 		char bodytype[MAXNAME];
13889630Seric 
138964355Seric 		printf("%8s", w->w_name + 2);
139017468Seric 		f = fopen(w->w_name, "r");
139117468Seric 		if (f == NULL)
139217468Seric 		{
139364355Seric 			printf(" (job completed)\n");
139417468Seric 			errno = 0;
139517468Seric 			continue;
139617468Seric 		}
1397*67612Seric 		if (w->w_lock)
139810070Seric 			printf("*");
139957438Seric 		else if (shouldqueue(w->w_pri, w->w_ctime))
140024941Seric 			printf("X");
140110070Seric 		else
140210070Seric 			printf(" ");
140310070Seric 		errno = 0;
140417468Seric 
140559093Seric 		message[0] = bodytype[0] = '\0';
14069630Seric 		while (fgets(buf, sizeof buf, f) != NULL)
14079630Seric 		{
140853400Seric 			register int i;
140958737Seric 			register char *p;
141053400Seric 
14119630Seric 			fixcrlf(buf, TRUE);
14129630Seric 			switch (buf[0])
14139630Seric 			{
141410108Seric 			  case 'M':	/* error message */
141553400Seric 				if ((i = strlen(&buf[1])) >= sizeof message)
141658737Seric 					i = sizeof message - 1;
141753400Seric 				bcopy(&buf[1], message, i);
141853400Seric 				message[i] = '\0';
141910108Seric 				break;
142010108Seric 
142159093Seric 			  case 'B':	/* body type */
142259093Seric 				if ((i = strlen(&buf[1])) >= sizeof bodytype)
142359093Seric 					i = sizeof bodytype - 1;
142459093Seric 				bcopy(&buf[1], bodytype, i);
142559093Seric 				bodytype[i] = '\0';
142659093Seric 				break;
142759093Seric 
14289630Seric 			  case 'S':	/* sender name */
142924979Seric 				if (Verbose)
143058737Seric 					printf("%8ld %10ld%c%.12s %.38s",
143158737Seric 					    dfsize,
143258737Seric 					    w->w_pri,
143358737Seric 					    bitset(EF_WARNING, flags) ? '+' : ' ',
143458737Seric 					    ctime(&submittime) + 4,
143524979Seric 					    &buf[1]);
143624979Seric 				else
143724979Seric 					printf("%8ld %.16s %.45s", dfsize,
143824979Seric 					    ctime(&submittime), &buf[1]);
143959093Seric 				if (message[0] != '\0' || bodytype[0] != '\0')
144059093Seric 				{
144159093Seric 					printf("\n    %10.10s", bodytype);
144259093Seric 					if (message[0] != '\0')
144359093Seric 						printf("   (%.60s)", message);
144459093Seric 				}
14459630Seric 				break;
144651920Seric 
144740973Sbostic 			  case 'C':	/* controlling user */
144854974Seric 				if (Verbose)
144958716Seric 					printf("\n\t\t\t\t      (---%.34s---)",
145058716Seric 						&buf[1]);
145140973Sbostic 				break;
14529630Seric 
14539630Seric 			  case 'R':	/* recipient name */
145424979Seric 				if (Verbose)
145558716Seric 					printf("\n\t\t\t\t\t  %.38s", &buf[1]);
145624979Seric 				else
145758716Seric 					printf("\n\t\t\t\t   %.45s", &buf[1]);
14589630Seric 				break;
14599630Seric 
14609630Seric 			  case 'T':	/* creation time */
146124941Seric 				submittime = atol(&buf[1]);
14629630Seric 				break;
146310070Seric 
146410070Seric 			  case 'D':	/* data file name */
146510070Seric 				if (stat(&buf[1], &st) >= 0)
146610070Seric 					dfsize = st.st_size;
146710070Seric 				break;
146858737Seric 
146958737Seric 			  case 'F':	/* flag bits */
147058737Seric 				for (p = &buf[1]; *p != '\0'; p++)
147158737Seric 				{
147258737Seric 					switch (*p)
147358737Seric 					{
147458737Seric 					  case 'w':
147558737Seric 						flags |= EF_WARNING;
147658737Seric 						break;
147758737Seric 					}
147858737Seric 				}
14799630Seric 			}
14809630Seric 		}
148110070Seric 		if (submittime == (time_t) 0)
148210070Seric 			printf(" (no control file)");
14839630Seric 		printf("\n");
148423098Seric 		(void) fclose(f);
14859630Seric 	}
14869630Seric }
14879630Seric 
148856795Seric # endif /* QUEUE */
148917468Seric /*
149017468Seric **  QUEUENAME -- build a file name in the queue directory for this envelope.
149117468Seric **
149217468Seric **	Assigns an id code if one does not already exist.
149317468Seric **	This code is very careful to avoid trashing existing files
149417468Seric **	under any circumstances.
149517468Seric **
149617468Seric **	Parameters:
149717468Seric **		e -- envelope to build it in/from.
149817468Seric **		type -- the file type, used as the first character
149917468Seric **			of the file name.
150017468Seric **
150117468Seric **	Returns:
150217468Seric **		a pointer to the new file name (in a static buffer).
150317468Seric **
150417468Seric **	Side Effects:
150551920Seric **		If no id code is already assigned, queuename will
150651920Seric **		assign an id code, create a qf file, and leave a
150751920Seric **		locked, open-for-write file pointer in the envelope.
150817468Seric */
150917468Seric 
151017468Seric char *
151117468Seric queuename(e, type)
151217468Seric 	register ENVELOPE *e;
151359700Seric 	int type;
151417468Seric {
151517468Seric 	static int pid = -1;
151658741Seric 	static char c0;
151758741Seric 	static char c1;
151858741Seric 	static char c2;
151958716Seric 	time_t now;
152058716Seric 	struct tm *tm;
152158689Seric 	static char buf[MAXNAME];
152217468Seric 
152317468Seric 	if (e->e_id == NULL)
152417468Seric 	{
152517468Seric 		char qf[20];
152617468Seric 
152717468Seric 		/* find a unique id */
152817468Seric 		if (pid != getpid())
152917468Seric 		{
153017468Seric 			/* new process -- start back at "AA" */
153117468Seric 			pid = getpid();
153258716Seric 			now = curtime();
153358716Seric 			tm = localtime(&now);
153458716Seric 			c0 = 'A' + tm->tm_hour;
153517468Seric 			c1 = 'A';
153617468Seric 			c2 = 'A' - 1;
153717468Seric 		}
153858716Seric 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
153917468Seric 
154017468Seric 		while (c1 < '~' || c2 < 'Z')
154117468Seric 		{
154217468Seric 			int i;
154317468Seric 
154417468Seric 			if (c2 >= 'Z')
154517468Seric 			{
154617468Seric 				c1++;
154717468Seric 				c2 = 'A' - 1;
154817468Seric 			}
154958716Seric 			qf[3] = c1;
155058716Seric 			qf[4] = ++c2;
155117468Seric 			if (tTd(7, 20))
155240934Srick 				printf("queuename: trying \"%s\"\n", qf);
155317468Seric 
155440934Srick 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
155551920Seric 			if (i < 0)
155651920Seric 			{
155751920Seric 				if (errno == EEXIST)
155851920Seric 					continue;
155964705Seric 				syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
156064705Seric 					qf, QueueDir, geteuid());
156151920Seric 				exit(EX_UNAVAILABLE);
156251920Seric 			}
156364335Seric 			if (lockfile(i, qf, NULL, LOCK_EX|LOCK_NB))
156451920Seric 			{
156551920Seric 				e->e_lockfp = fdopen(i, "w");
156640934Srick 				break;
156717468Seric 			}
156851920Seric 
156951920Seric 			/* a reader got the file; abandon it and try again */
157051920Seric 			(void) close(i);
157117468Seric 		}
157217468Seric 		if (c1 >= '~' && c2 >= 'Z')
157317468Seric 		{
157464705Seric 			syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
157564705Seric 				qf, QueueDir, geteuid());
157617468Seric 			exit(EX_OSERR);
157717468Seric 		}
157817468Seric 		e->e_id = newstr(&qf[2]);
157917468Seric 		define('i', e->e_id, e);
158017468Seric 		if (tTd(7, 1))
158117468Seric 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
158264745Seric 		if (tTd(7, 9))
158364745Seric 		{
158464745Seric 			printf("  lockfd=");
158564745Seric 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
158664745Seric 		}
158717468Seric # ifdef LOG
158858020Seric 		if (LogLevel > 93)
158917468Seric 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
159056795Seric # endif /* LOG */
159117468Seric 	}
159217468Seric 
159317468Seric 	if (type == '\0')
159417468Seric 		return (NULL);
159517468Seric 	(void) sprintf(buf, "%cf%s", type, e->e_id);
159617468Seric 	if (tTd(7, 2))
159717468Seric 		printf("queuename: %s\n", buf);
159817468Seric 	return (buf);
159917468Seric }
160017468Seric /*
160117468Seric **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
160217468Seric **
160317468Seric **	Parameters:
160417468Seric **		e -- the envelope to unlock.
160517468Seric **
160617468Seric **	Returns:
160717468Seric **		none
160817468Seric **
160917468Seric **	Side Effects:
161017468Seric **		unlocks the queue for `e'.
161117468Seric */
161217468Seric 
161317468Seric unlockqueue(e)
161417468Seric 	ENVELOPE *e;
161517468Seric {
161658680Seric 	if (tTd(51, 4))
161758680Seric 		printf("unlockqueue(%s)\n", e->e_id);
161858680Seric 
161951920Seric 	/* if there is a lock file in the envelope, close it */
162051920Seric 	if (e->e_lockfp != NULL)
162158680Seric 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
162251920Seric 	e->e_lockfp = NULL;
162351920Seric 
162458728Seric 	/* don't create a queue id if we don't already have one */
162558728Seric 	if (e->e_id == NULL)
162658728Seric 		return;
162758728Seric 
162817468Seric 	/* remove the transcript */
162917468Seric # ifdef LOG
163058020Seric 	if (LogLevel > 87)
163117468Seric 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
163256795Seric # endif /* LOG */
163358680Seric 	if (!tTd(51, 104))
163417468Seric 		xunlink(queuename(e, 'x'));
163517468Seric 
163617468Seric }
163740973Sbostic /*
163854974Seric **  SETCTLUSER -- create a controlling address
163940973Sbostic **
164054974Seric **	Create a fake "address" given only a local login name; this is
164154974Seric **	used as a "controlling user" for future recipient addresses.
164240973Sbostic **
164340973Sbostic **	Parameters:
164454974Seric **		user -- the user name of the controlling user.
164540973Sbostic **
164640973Sbostic **	Returns:
164754974Seric **		An address descriptor for the controlling user.
164840973Sbostic **
164940973Sbostic **	Side Effects:
165040973Sbostic **		none.
165140973Sbostic */
165240973Sbostic 
165354974Seric ADDRESS *
165454974Seric setctluser(user)
165554974Seric 	char *user;
165640973Sbostic {
165754974Seric 	register ADDRESS *a;
165840973Sbostic 	struct passwd *pw;
165959113Seric 	char *p;
166040973Sbostic 
166140973Sbostic 	/*
166254974Seric 	**  See if this clears our concept of controlling user.
166340973Sbostic 	*/
166440973Sbostic 
166563850Seric 	if (user == NULL || *user == '\0')
166663850Seric 		return NULL;
166740973Sbostic 
166840973Sbostic 	/*
166954974Seric 	**  Set up addr fields for controlling user.
167040973Sbostic 	*/
167140973Sbostic 
167254974Seric 	a = (ADDRESS *) xalloc(sizeof *a);
167354974Seric 	bzero((char *) a, sizeof *a);
167459113Seric 
167559113Seric 	p = strchr(user, ':');
167659113Seric 	if (p != NULL)
167759113Seric 		*p++ = '\0';
167859270Seric 	if (*user != '\0' && (pw = getpwnam(user)) != NULL)
167940973Sbostic 	{
168065822Seric 		if (strcmp(pw->pw_dir, "/") == 0)
168165822Seric 			a->q_home = "";
168265822Seric 		else
168365822Seric 			a->q_home = newstr(pw->pw_dir);
168440973Sbostic 		a->q_uid = pw->pw_uid;
168540973Sbostic 		a->q_gid = pw->pw_gid;
168657642Seric 		a->q_user = newstr(user);
168759270Seric 		a->q_flags |= QGOODUID;
168840973Sbostic 	}
168940973Sbostic 	else
169040973Sbostic 	{
169157642Seric 		a->q_user = newstr(DefUser);
169240973Sbostic 	}
169340973Sbostic 
169459270Seric 	a->q_flags |= QPRIMARY;		/* flag as a "ctladdr"  */
169556328Seric 	a->q_mailer = LocalMailer;
169659113Seric 	if (p == NULL)
169759113Seric 		a->q_paddr = a->q_user;
169859113Seric 	else
169959113Seric 		a->q_paddr = newstr(p);
170054974Seric 	return a;
170140973Sbostic }
1702