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