xref: /original-bsd/usr.sbin/sendmail/src/queue.c (revision cf2e4d33)
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.48 (Berkeley) 08/18/94 (with queueing)";
14 #else
15 static char sccsid[] = "@(#)queue.c	8.48 (Berkeley) 08/18/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 
1075 		/* if this has been tried recently, let it be */
1076 		if (e->e_ntries > 0 && (curtime() - e->e_dtime) > MinQueueAge)
1077 		{
1078 			char *howlong = pintvl(curtime() - e->e_dtime, TRUE);
1079 
1080 			e->e_flags |= EF_KEEPQUEUE;
1081 			if (Verbose || tTd(40, 8))
1082 				printf("%s: too young (%s)\n",
1083 					e->e_id, howlong);
1084 #ifdef LOG
1085 			if (LogLevel > 19)
1086 				syslog(LOG_DEBUG, "%s: too young (%s)",
1087 					e->e_id, howlong);
1088 #endif
1089 		}
1090 		else
1091 		{
1092 			eatheader(e, requeueflag);
1093 
1094 			if (requeueflag)
1095 				queueup(e, TRUE, FALSE);
1096 
1097 			/* do the delivery */
1098 			sendall(e, SM_DELIVER);
1099 		}
1100 
1101 		/* finish up and exit */
1102 		if (forkflag)
1103 			finis();
1104 		else
1105 			dropenvelope(e);
1106 	}
1107 	e->e_id = NULL;
1108 	return pid;
1109 }
1110 /*
1111 **  READQF -- read queue file and set up environment.
1112 **
1113 **	Parameters:
1114 **		e -- the envelope of the job to run.
1115 **
1116 **	Returns:
1117 **		TRUE if it successfully read the queue file.
1118 **		FALSE otherwise.
1119 **
1120 **	Side Effects:
1121 **		The queue file is returned locked.
1122 */
1123 
1124 bool
1125 readqf(e)
1126 	register ENVELOPE *e;
1127 {
1128 	register FILE *qfp;
1129 	ADDRESS *ctladdr;
1130 	struct stat st;
1131 	char *bp;
1132 	char qf[20];
1133 	char buf[MAXLINE];
1134 	extern long atol();
1135 	extern ADDRESS *setctluser();
1136 
1137 	/*
1138 	**  Read and process the file.
1139 	*/
1140 
1141 	strcpy(qf, queuename(e, 'q'));
1142 	qfp = fopen(qf, "r+");
1143 	if (qfp == NULL)
1144 	{
1145 		if (tTd(40, 8))
1146 			printf("readqf(%s): fopen failure (%s)\n",
1147 				qf, errstring(errno));
1148 		if (errno != ENOENT)
1149 			syserr("readqf: no control file %s", qf);
1150 		return FALSE;
1151 	}
1152 
1153 	if (!lockfile(fileno(qfp), qf, NULL, LOCK_EX|LOCK_NB))
1154 	{
1155 		/* being processed by another queuer */
1156 		if (Verbose || tTd(40, 8))
1157 			printf("%s: locked\n", e->e_id);
1158 # ifdef LOG
1159 		if (LogLevel > 19)
1160 			syslog(LOG_DEBUG, "%s: locked", e->e_id);
1161 # endif /* LOG */
1162 		(void) fclose(qfp);
1163 		return FALSE;
1164 	}
1165 
1166 	/*
1167 	**  Check the queue file for plausibility to avoid attacks.
1168 	*/
1169 
1170 	if (fstat(fileno(qfp), &st) < 0)
1171 	{
1172 		/* must have been being processed by someone else */
1173 		if (tTd(40, 8))
1174 			printf("readqf(%s): fstat failure (%s)\n",
1175 				qf, errstring(errno));
1176 		fclose(qfp);
1177 		return FALSE;
1178 	}
1179 
1180 	if (st.st_uid != geteuid())
1181 	{
1182 # ifdef LOG
1183 		if (LogLevel > 0)
1184 		{
1185 			syslog(LOG_ALERT, "%s: bogus queue file, uid=%d, mode=%o",
1186 				e->e_id, st.st_uid, st.st_mode);
1187 		}
1188 # endif /* LOG */
1189 		if (tTd(40, 8))
1190 			printf("readqf(%s): bogus file\n", qf);
1191 		rename(qf, queuename(e, 'Q'));
1192 		fclose(qfp);
1193 		return FALSE;
1194 	}
1195 
1196 	if (st.st_size == 0)
1197 	{
1198 		/* must be a bogus file -- just remove it */
1199 		(void) unlink(qf);
1200 		fclose(qfp);
1201 		return FALSE;
1202 	}
1203 
1204 	if (st.st_nlink == 0)
1205 	{
1206 		/*
1207 		**  Race condition -- we got a file just as it was being
1208 		**  unlinked.  Just assume it is zero length.
1209 		*/
1210 
1211 		fclose(qfp);
1212 		return FALSE;
1213 	}
1214 
1215 	/* good file -- save this lock */
1216 	e->e_lockfp = qfp;
1217 
1218 	/* do basic system initialization */
1219 	initsys(e);
1220 	define('i', e->e_id, e);
1221 
1222 	LineNumber = 0;
1223 	e->e_flags |= EF_GLOBALERRS;
1224 	OpMode = MD_DELIVER;
1225 	if (Verbose)
1226 		printf("\nRunning %s\n", e->e_id);
1227 	ctladdr = NULL;
1228 	e->e_dfino = -1;
1229 	while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
1230 	{
1231 		register char *p;
1232 		struct stat st;
1233 
1234 		if (tTd(40, 4))
1235 			printf("+++++ %s\n", bp);
1236 		switch (bp[0])
1237 		{
1238 		  case 'C':		/* specify controlling user */
1239 			ctladdr = setctluser(&bp[1]);
1240 			break;
1241 
1242 		  case 'R':		/* specify recipient */
1243 			(void) sendtolist(&bp[1], ctladdr, &e->e_sendqueue, e);
1244 			break;
1245 
1246 		  case 'E':		/* specify error recipient */
1247 			(void) sendtolist(&bp[1], ctladdr, &e->e_errorqueue, e);
1248 			break;
1249 
1250 		  case 'H':		/* header */
1251 			(void) chompheader(&bp[1], FALSE, e);
1252 			break;
1253 
1254 		  case 'M':		/* message */
1255 			/* ignore this; we want a new message next time */
1256 			break;
1257 
1258 		  case 'S':		/* sender */
1259 			setsender(newstr(&bp[1]), e, NULL, TRUE);
1260 			break;
1261 
1262 		  case 'B':		/* body type */
1263 			e->e_bodytype = newstr(&bp[1]);
1264 			break;
1265 
1266 		  case 'D':		/* data file name */
1267 			e->e_df = newstr(&bp[1]);
1268 			e->e_dfp = fopen(e->e_df, "r");
1269 			if (e->e_dfp == NULL)
1270 			{
1271 				syserr("readqf: cannot open %s", e->e_df);
1272 				e->e_msgsize = -1;
1273 			}
1274 			else if (fstat(fileno(e->e_dfp), &st) >= 0)
1275 			{
1276 				e->e_msgsize = st.st_size;
1277 				e->e_dfdev = st.st_dev;
1278 				e->e_dfino = st.st_ino;
1279 			}
1280 			break;
1281 
1282 		  case 'T':		/* init time */
1283 			e->e_ctime = atol(&bp[1]);
1284 			break;
1285 
1286 		  case 'I':		/* data file's inode number */
1287 			if (e->e_dfino == -1)
1288 				e->e_dfino = atol(&buf[1]);
1289 			break;
1290 
1291 		  case 'K':		/* time of last deliver attempt */
1292 			e->e_dtime = atol(&buf[1]);
1293 			break;
1294 
1295 		  case 'N':		/* number of delivery attempts */
1296 			e->e_ntries = atoi(&buf[1]);
1297 			break;
1298 
1299 		  case 'P':		/* message priority */
1300 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
1301 			break;
1302 
1303 		  case 'F':		/* flag bits */
1304 			for (p = &bp[1]; *p != '\0'; p++)
1305 			{
1306 				switch (*p)
1307 				{
1308 				  case 'w':	/* warning sent */
1309 					e->e_flags |= EF_WARNING;
1310 					break;
1311 
1312 				  case 'r':	/* response */
1313 					e->e_flags |= EF_RESPONSE;
1314 					break;
1315 
1316 				  case '8':	/* has 8 bit data */
1317 					e->e_flags |= EF_HAS8BIT;
1318 					break;
1319 				}
1320 			}
1321 			break;
1322 
1323 		  case '$':		/* define macro */
1324 			define(bp[1], newstr(&bp[2]), e);
1325 			break;
1326 
1327 		  case '\0':		/* blank line; ignore */
1328 			break;
1329 
1330 		  default:
1331 			syserr("readqf: %s: line %d: bad line \"%s\"",
1332 				qf, LineNumber, bp);
1333 			fclose(qfp);
1334 			rename(qf, queuename(e, 'Q'));
1335 			return FALSE;
1336 		}
1337 
1338 		if (bp != buf)
1339 			free(bp);
1340 	}
1341 
1342 	/*
1343 	**  If we haven't read any lines, this queue file is empty.
1344 	**  Arrange to remove it without referencing any null pointers.
1345 	*/
1346 
1347 	if (LineNumber == 0)
1348 	{
1349 		errno = 0;
1350 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
1351 	}
1352 	return TRUE;
1353 }
1354 /*
1355 **  PRINTQUEUE -- print out a representation of the mail queue
1356 **
1357 **	Parameters:
1358 **		none.
1359 **
1360 **	Returns:
1361 **		none.
1362 **
1363 **	Side Effects:
1364 **		Prints a listing of the mail queue on the standard output.
1365 */
1366 
1367 printqueue()
1368 {
1369 	register WORK *w;
1370 	FILE *f;
1371 	int nrequests;
1372 	char buf[MAXLINE];
1373 
1374 	/*
1375 	**  Check for permission to print the queue
1376 	*/
1377 
1378 	if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
1379 	{
1380 		struct stat st;
1381 # ifdef NGROUPS
1382 		int n;
1383 		GIDSET_T gidset[NGROUPS];
1384 # endif
1385 
1386 		if (stat(QueueDir, &st) < 0)
1387 		{
1388 			syserr("Cannot stat %s", QueueDir);
1389 			return;
1390 		}
1391 # ifdef NGROUPS
1392 		n = getgroups(NGROUPS, gidset);
1393 		while (--n >= 0)
1394 		{
1395 			if (gidset[n] == st.st_gid)
1396 				break;
1397 		}
1398 		if (n < 0)
1399 # else
1400 		if (RealGid != st.st_gid)
1401 # endif
1402 		{
1403 			usrerr("510 You are not permitted to see the queue");
1404 			setstat(EX_NOPERM);
1405 			return;
1406 		}
1407 	}
1408 
1409 	/*
1410 	**  Read and order the queue.
1411 	*/
1412 
1413 	nrequests = orderq(TRUE);
1414 
1415 	/*
1416 	**  Print the work list that we have read.
1417 	*/
1418 
1419 	/* first see if there is anything */
1420 	if (nrequests <= 0)
1421 	{
1422 		printf("Mail queue is empty\n");
1423 		return;
1424 	}
1425 
1426 	CurrentLA = getla();	/* get load average */
1427 
1428 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
1429 	if (nrequests > QUEUESIZE)
1430 		printf(", only %d printed", QUEUESIZE);
1431 	if (Verbose)
1432 		printf(")\n--Q-ID-- --Size-- -Priority- ---Q-Time--- -----------Sender/Recipient-----------\n");
1433 	else
1434 		printf(")\n--Q-ID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
1435 	for (w = WorkQ; w != NULL; w = w->w_next)
1436 	{
1437 		struct stat st;
1438 		auto time_t submittime = 0;
1439 		long dfsize = -1;
1440 		int flags = 0;
1441 		char message[MAXLINE];
1442 		char bodytype[MAXNAME];
1443 
1444 		printf("%8s", w->w_name + 2);
1445 		f = fopen(w->w_name, "r");
1446 		if (f == NULL)
1447 		{
1448 			printf(" (job completed)\n");
1449 			errno = 0;
1450 			continue;
1451 		}
1452 		if (w->w_lock)
1453 			printf("*");
1454 		else if (shouldqueue(w->w_pri, w->w_ctime))
1455 			printf("X");
1456 		else
1457 			printf(" ");
1458 		errno = 0;
1459 
1460 		message[0] = bodytype[0] = '\0';
1461 		while (fgets(buf, sizeof buf, f) != NULL)
1462 		{
1463 			register int i;
1464 			register char *p;
1465 
1466 			fixcrlf(buf, TRUE);
1467 			switch (buf[0])
1468 			{
1469 			  case 'M':	/* error message */
1470 				if ((i = strlen(&buf[1])) >= sizeof message)
1471 					i = sizeof message - 1;
1472 				bcopy(&buf[1], message, i);
1473 				message[i] = '\0';
1474 				break;
1475 
1476 			  case 'B':	/* body type */
1477 				if ((i = strlen(&buf[1])) >= sizeof bodytype)
1478 					i = sizeof bodytype - 1;
1479 				bcopy(&buf[1], bodytype, i);
1480 				bodytype[i] = '\0';
1481 				break;
1482 
1483 			  case 'S':	/* sender name */
1484 				if (Verbose)
1485 					printf("%8ld %10ld%c%.12s %.38s",
1486 					    dfsize,
1487 					    w->w_pri,
1488 					    bitset(EF_WARNING, flags) ? '+' : ' ',
1489 					    ctime(&submittime) + 4,
1490 					    &buf[1]);
1491 				else
1492 					printf("%8ld %.16s %.45s", dfsize,
1493 					    ctime(&submittime), &buf[1]);
1494 				if (message[0] != '\0' || bodytype[0] != '\0')
1495 				{
1496 					printf("\n    %10.10s", bodytype);
1497 					if (message[0] != '\0')
1498 						printf("   (%.60s)", message);
1499 				}
1500 				break;
1501 
1502 			  case 'C':	/* controlling user */
1503 				if (Verbose)
1504 					printf("\n\t\t\t\t      (---%.34s---)",
1505 						&buf[1]);
1506 				break;
1507 
1508 			  case 'R':	/* recipient name */
1509 				if (Verbose)
1510 					printf("\n\t\t\t\t\t  %.38s", &buf[1]);
1511 				else
1512 					printf("\n\t\t\t\t   %.45s", &buf[1]);
1513 				break;
1514 
1515 			  case 'T':	/* creation time */
1516 				submittime = atol(&buf[1]);
1517 				break;
1518 
1519 			  case 'D':	/* data file name */
1520 				if (stat(&buf[1], &st) >= 0)
1521 					dfsize = st.st_size;
1522 				break;
1523 
1524 			  case 'F':	/* flag bits */
1525 				for (p = &buf[1]; *p != '\0'; p++)
1526 				{
1527 					switch (*p)
1528 					{
1529 					  case 'w':
1530 						flags |= EF_WARNING;
1531 						break;
1532 					}
1533 				}
1534 			}
1535 		}
1536 		if (submittime == (time_t) 0)
1537 			printf(" (no control file)");
1538 		printf("\n");
1539 		(void) fclose(f);
1540 	}
1541 }
1542 
1543 # endif /* QUEUE */
1544 /*
1545 **  QUEUENAME -- build a file name in the queue directory for this envelope.
1546 **
1547 **	Assigns an id code if one does not already exist.
1548 **	This code is very careful to avoid trashing existing files
1549 **	under any circumstances.
1550 **
1551 **	Parameters:
1552 **		e -- envelope to build it in/from.
1553 **		type -- the file type, used as the first character
1554 **			of the file name.
1555 **
1556 **	Returns:
1557 **		a pointer to the new file name (in a static buffer).
1558 **
1559 **	Side Effects:
1560 **		If no id code is already assigned, queuename will
1561 **		assign an id code, create a qf file, and leave a
1562 **		locked, open-for-write file pointer in the envelope.
1563 */
1564 
1565 char *
1566 queuename(e, type)
1567 	register ENVELOPE *e;
1568 	int type;
1569 {
1570 	static int pid = -1;
1571 	static char c0;
1572 	static char c1;
1573 	static char c2;
1574 	time_t now;
1575 	struct tm *tm;
1576 	static char buf[MAXNAME];
1577 
1578 	if (e->e_id == NULL)
1579 	{
1580 		char qf[20];
1581 
1582 		/* find a unique id */
1583 		if (pid != getpid())
1584 		{
1585 			/* new process -- start back at "AA" */
1586 			pid = getpid();
1587 			now = curtime();
1588 			tm = localtime(&now);
1589 			c0 = 'A' + tm->tm_hour;
1590 			c1 = 'A';
1591 			c2 = 'A' - 1;
1592 		}
1593 		(void) sprintf(qf, "qf%cAA%05d", c0, pid);
1594 
1595 		while (c1 < '~' || c2 < 'Z')
1596 		{
1597 			int i;
1598 
1599 			if (c2 >= 'Z')
1600 			{
1601 				c1++;
1602 				c2 = 'A' - 1;
1603 			}
1604 			qf[3] = c1;
1605 			qf[4] = ++c2;
1606 			if (tTd(7, 20))
1607 				printf("queuename: trying \"%s\"\n", qf);
1608 
1609 			i = open(qf, O_WRONLY|O_CREAT|O_EXCL, FileMode);
1610 			if (i < 0)
1611 			{
1612 				if (errno == EEXIST)
1613 					continue;
1614 				syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1615 					qf, QueueDir, geteuid());
1616 				exit(EX_UNAVAILABLE);
1617 			}
1618 			if (lockfile(i, qf, NULL, LOCK_EX|LOCK_NB))
1619 			{
1620 				e->e_lockfp = fdopen(i, "w");
1621 				break;
1622 			}
1623 
1624 			/* a reader got the file; abandon it and try again */
1625 			(void) close(i);
1626 		}
1627 		if (c1 >= '~' && c2 >= 'Z')
1628 		{
1629 			syserr("queuename: Cannot create \"%s\" in \"%s\" (euid=%d)",
1630 				qf, QueueDir, geteuid());
1631 			exit(EX_OSERR);
1632 		}
1633 		e->e_id = newstr(&qf[2]);
1634 		define('i', e->e_id, e);
1635 		if (tTd(7, 1))
1636 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
1637 		if (tTd(7, 9))
1638 		{
1639 			printf("  lockfd=");
1640 			dumpfd(fileno(e->e_lockfp), TRUE, FALSE);
1641 		}
1642 # ifdef LOG
1643 		if (LogLevel > 93)
1644 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
1645 # endif /* LOG */
1646 	}
1647 
1648 	if (type == '\0')
1649 		return (NULL);
1650 	(void) sprintf(buf, "%cf%s", type, e->e_id);
1651 	if (tTd(7, 2))
1652 		printf("queuename: %s\n", buf);
1653 	return (buf);
1654 }
1655 /*
1656 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
1657 **
1658 **	Parameters:
1659 **		e -- the envelope to unlock.
1660 **
1661 **	Returns:
1662 **		none
1663 **
1664 **	Side Effects:
1665 **		unlocks the queue for `e'.
1666 */
1667 
1668 unlockqueue(e)
1669 	ENVELOPE *e;
1670 {
1671 	if (tTd(51, 4))
1672 		printf("unlockqueue(%s)\n", e->e_id);
1673 
1674 	/* if there is a lock file in the envelope, close it */
1675 	if (e->e_lockfp != NULL)
1676 		xfclose(e->e_lockfp, "unlockqueue", e->e_id);
1677 	e->e_lockfp = NULL;
1678 
1679 	/* don't create a queue id if we don't already have one */
1680 	if (e->e_id == NULL)
1681 		return;
1682 
1683 	/* remove the transcript */
1684 # ifdef LOG
1685 	if (LogLevel > 87)
1686 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
1687 # endif /* LOG */
1688 	if (!tTd(51, 104))
1689 		xunlink(queuename(e, 'x'));
1690 
1691 }
1692 /*
1693 **  SETCTLUSER -- create a controlling address
1694 **
1695 **	Create a fake "address" given only a local login name; this is
1696 **	used as a "controlling user" for future recipient addresses.
1697 **
1698 **	Parameters:
1699 **		user -- the user name of the controlling user.
1700 **
1701 **	Returns:
1702 **		An address descriptor for the controlling user.
1703 **
1704 **	Side Effects:
1705 **		none.
1706 */
1707 
1708 ADDRESS *
1709 setctluser(user)
1710 	char *user;
1711 {
1712 	register ADDRESS *a;
1713 	struct passwd *pw;
1714 	char *p;
1715 
1716 	/*
1717 	**  See if this clears our concept of controlling user.
1718 	*/
1719 
1720 	if (user == NULL || *user == '\0')
1721 		return NULL;
1722 
1723 	/*
1724 	**  Set up addr fields for controlling user.
1725 	*/
1726 
1727 	a = (ADDRESS *) xalloc(sizeof *a);
1728 	bzero((char *) a, sizeof *a);
1729 
1730 	p = strchr(user, ':');
1731 	if (p != NULL)
1732 		*p++ = '\0';
1733 	if (*user != '\0' && (pw = getpwnam(user)) != NULL)
1734 	{
1735 		if (strcmp(pw->pw_dir, "/") == 0)
1736 			a->q_home = "";
1737 		else
1738 			a->q_home = newstr(pw->pw_dir);
1739 		a->q_uid = pw->pw_uid;
1740 		a->q_gid = pw->pw_gid;
1741 		a->q_user = newstr(user);
1742 		a->q_flags |= QGOODUID;
1743 	}
1744 	else
1745 	{
1746 		a->q_user = newstr(DefUser);
1747 	}
1748 
1749 	a->q_flags |= QPRIMARY;		/* flag as a "ctladdr"  */
1750 	a->q_mailer = LocalMailer;
1751 	if (p == NULL)
1752 		a->q_paddr = a->q_user;
1753 	else
1754 		a->q_paddr = newstr(p);
1755 	return a;
1756 }
1757