xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 24979)
1 /*
2 **  Sendmail
3 **  Copyright (c) 1983  Eric P. Allman
4 **  Berkeley, California
5 **
6 **  Copyright (c) 1983 Regents of the University of California.
7 **  All rights reserved.  The Berkeley software License Agreement
8 **  specifies the terms and conditions for redistribution.
9 */
10 
11 
12 # include "sendmail.h"
13 # include <sys/stat.h>
14 # include <sys/dir.h>
15 # include <signal.h>
16 # include <errno.h>
17 
18 # ifndef QUEUE
19 # ifndef lint
20 static char	SccsId[] = "@(#)queue.c	5.11 (Berkeley) 09/21/85	(no queueing)";
21 # endif not lint
22 # else QUEUE
23 
24 # ifndef lint
25 static char	SccsId[] = "@(#)queue.c	5.11 (Berkeley) 09/21/85";
26 # endif not lint
27 
28 /*
29 **  Work queue.
30 */
31 
32 struct work
33 {
34 	char		*w_name;	/* name of control file */
35 	long		w_pri;		/* priority of message, see below */
36 	long		w_ctime;	/* creation time of message */
37 	struct work	*w_next;	/* next in queue */
38 };
39 
40 typedef struct work	WORK;
41 
42 WORK	*WorkQ;			/* queue of things to be done */
43 /*
44 **  QUEUEUP -- queue a message up for future transmission.
45 **
46 **	Parameters:
47 **		e -- the envelope to queue up.
48 **		queueall -- if TRUE, queue all addresses, rather than
49 **			just those with the QQUEUEUP flag set.
50 **		announce -- if TRUE, tell when you are queueing up.
51 **
52 **	Returns:
53 **		none.
54 **
55 **	Side Effects:
56 **		The current request are saved in a control file.
57 */
58 
59 queueup(e, queueall, announce)
60 	register ENVELOPE *e;
61 	bool queueall;
62 	bool announce;
63 {
64 	char *tf;
65 	char *qf;
66 	char buf[MAXLINE];
67 	register FILE *tfp;
68 	register HDR *h;
69 	register ADDRESS *q;
70 	MAILER nullmailer;
71 
72 	/*
73 	**  Create control file.
74 	*/
75 
76 	tf = newstr(queuename(e, 't'));
77 	tfp = fopen(tf, "w");
78 	if (tfp == NULL)
79 	{
80 		syserr("queueup: cannot create temp file %s", tf);
81 		return;
82 	}
83 	(void) chmod(tf, FileMode);
84 
85 # ifdef DEBUG
86 	if (tTd(40, 1))
87 		printf("queueing %s\n", e->e_id);
88 # endif DEBUG
89 
90 	/*
91 	**  If there is no data file yet, create one.
92 	*/
93 
94 	if (e->e_df == NULL)
95 	{
96 		register FILE *dfp;
97 		extern putbody();
98 
99 		e->e_df = newstr(queuename(e, 'd'));
100 		dfp = fopen(e->e_df, "w");
101 		if (dfp == NULL)
102 		{
103 			syserr("queueup: cannot create %s", e->e_df);
104 			(void) fclose(tfp);
105 			return;
106 		}
107 		(void) chmod(e->e_df, FileMode);
108 		(*e->e_putbody)(dfp, ProgMailer, e);
109 		(void) fclose(dfp);
110 		e->e_putbody = putbody;
111 	}
112 
113 	/*
114 	**  Output future work requests.
115 	**	Priority should be first, since it is read by orderq.
116 	*/
117 
118 	/* output message priority */
119 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
120 
121 	/* output creation time */
122 	fprintf(tfp, "T%ld\n", e->e_ctime);
123 
124 	/* output name of data file */
125 	fprintf(tfp, "D%s\n", e->e_df);
126 
127 	/* message from envelope, if it exists */
128 	if (e->e_message != NULL)
129 		fprintf(tfp, "M%s\n", e->e_message);
130 
131 	/* output name of sender */
132 	fprintf(tfp, "S%s\n", e->e_from.q_paddr);
133 
134 	/* output list of recipient addresses */
135 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
136 	{
137 		if (queueall ? !bitset(QDONTSEND, q->q_flags) :
138 			       bitset(QQUEUEUP, q->q_flags))
139 		{
140 			fprintf(tfp, "R%s\n", q->q_paddr);
141 			if (announce)
142 			{
143 				e->e_to = q->q_paddr;
144 				message(Arpa_Info, "queued");
145 				if (LogLevel > 4)
146 					logdelivery("queued");
147 				e->e_to = NULL;
148 			}
149 #ifdef DEBUG
150 			if (tTd(40, 1))
151 			{
152 				printf("queueing ");
153 				printaddr(q, FALSE);
154 			}
155 #endif DEBUG
156 		}
157 	}
158 
159 	/*
160 	**  Output headers for this message.
161 	**	Expand macros completely here.  Queue run will deal with
162 	**	everything as absolute headers.
163 	**		All headers that must be relative to the recipient
164 	**		can be cracked later.
165 	**	We set up a "null mailer" -- i.e., a mailer that will have
166 	**	no effect on the addresses as they are output.
167 	*/
168 
169 	bzero((char *) &nullmailer, sizeof nullmailer);
170 	nullmailer.m_r_rwset = nullmailer.m_s_rwset = -1;
171 	nullmailer.m_eol = "\n";
172 
173 	define('g', "\001f", e);
174 	for (h = e->e_header; h != NULL; h = h->h_link)
175 	{
176 		extern bool bitzerop();
177 
178 		/* don't output null headers */
179 		if (h->h_value == NULL || h->h_value[0] == '\0')
180 			continue;
181 
182 		/* don't output resent headers on non-resent messages */
183 		if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
184 			continue;
185 
186 		/* output this header */
187 		fprintf(tfp, "H");
188 
189 		/* if conditional, output the set of conditions */
190 		if (!bitzerop(h->h_mflags) && bitset(H_CHECK|H_ACHECK, h->h_flags))
191 		{
192 			int j;
193 
194 			(void) putc('?', tfp);
195 			for (j = '\0'; j <= '\177'; j++)
196 				if (bitnset(j, h->h_mflags))
197 					(void) putc(j, tfp);
198 			(void) putc('?', tfp);
199 		}
200 
201 		/* output the header: expand macros, convert addresses */
202 		if (bitset(H_DEFAULT, h->h_flags))
203 		{
204 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
205 			fprintf(tfp, "%s: %s\n", h->h_field, buf);
206 		}
207 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
208 		{
209 			commaize(h, h->h_value, tfp, bitset(EF_OLDSTYLE, e->e_flags),
210 				 &nullmailer);
211 		}
212 		else
213 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
214 	}
215 
216 	/*
217 	**  Clean up.
218 	*/
219 
220 	(void) fclose(tfp);
221 	qf = queuename(e, 'q');
222 	if (tf != NULL)
223 	{
224 		(void) unlink(qf);
225 		if (rename(tf, qf) < 0)
226 			syserr("cannot unlink(%s, %s), df=%s", tf, qf, e->e_df);
227 		errno = 0;
228 	}
229 
230 # ifdef LOG
231 	/* save log info */
232 	if (LogLevel > 15)
233 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
234 # endif LOG
235 }
236 /*
237 **  RUNQUEUE -- run the jobs in the queue.
238 **
239 **	Gets the stuff out of the queue in some presumably logical
240 **	order and processes them.
241 **
242 **	Parameters:
243 **		forkflag -- TRUE if the queue scanning should be done in
244 **			a child process.  We double-fork so it is not our
245 **			child and we don't have to clean up after it.
246 **
247 **	Returns:
248 **		none.
249 **
250 **	Side Effects:
251 **		runs things in the mail queue.
252 */
253 
254 runqueue(forkflag)
255 	bool forkflag;
256 {
257 	extern bool shouldqueue();
258 
259 	/*
260 	**  If no work will ever be selected, don't even bother reading
261 	**  the queue.
262 	*/
263 
264 	if (shouldqueue(-100000000L))
265 	{
266 		if (Verbose)
267 			printf("Skipping queue run -- load average too high\n");
268 
269 		if (forkflag)
270 			return;
271 		finis();
272 	}
273 
274 	/*
275 	**  See if we want to go off and do other useful work.
276 	*/
277 
278 	if (forkflag)
279 	{
280 		int pid;
281 
282 		pid = dofork();
283 		if (pid != 0)
284 		{
285 			/* parent -- pick up intermediate zombie */
286 			(void) waitfor(pid);
287 			if (QueueIntvl != 0)
288 				(void) setevent(QueueIntvl, runqueue, TRUE);
289 			return;
290 		}
291 		/* child -- double fork */
292 		if (fork() != 0)
293 			exit(EX_OK);
294 	}
295 
296 	setproctitle("running queue");
297 
298 # ifdef LOG
299 	if (LogLevel > 11)
300 		syslog(LOG_DEBUG, "runqueue %s, pid=%d", QueueDir, getpid());
301 # endif LOG
302 
303 	/*
304 	**  Release any resources used by the daemon code.
305 	*/
306 
307 # ifdef DAEMON
308 	clrdaemon();
309 # endif DAEMON
310 
311 	/*
312 	**  Start making passes through the queue.
313 	**	First, read and sort the entire queue.
314 	**	Then, process the work in that order.
315 	**		But if you take too long, start over.
316 	*/
317 
318 	/* order the existing work requests */
319 	(void) orderq(FALSE);
320 
321 	/* process them once at a time */
322 	while (WorkQ != NULL)
323 	{
324 		WORK *w = WorkQ;
325 
326 		WorkQ = WorkQ->w_next;
327 		dowork(w);
328 		free(w->w_name);
329 		free((char *) w);
330 	}
331 	finis();
332 }
333 /*
334 **  ORDERQ -- order the work queue.
335 **
336 **	Parameters:
337 **		doall -- if set, include everything in the queue (even
338 **			the jobs that cannot be run because the load
339 **			average is too high).  Otherwise, exclude those
340 **			jobs.
341 **
342 **	Returns:
343 **		The number of request in the queue (not necessarily
344 **		the number of requests in WorkQ however).
345 **
346 **	Side Effects:
347 **		Sets WorkQ to the queue of available work, in order.
348 */
349 
350 # define WLSIZE		120	/* max size of worklist per sort */
351 
352 orderq(doall)
353 	bool doall;
354 {
355 	register struct direct *d;
356 	register WORK *w;
357 	register WORK **wp;		/* parent of w */
358 	DIR *f;
359 	register int i;
360 	WORK wlist[WLSIZE+1];
361 	int wn = -1;
362 	extern workcmpf();
363 
364 	/* clear out old WorkQ */
365 	for (w = WorkQ; w != NULL; )
366 	{
367 		register WORK *nw = w->w_next;
368 
369 		WorkQ = nw;
370 		free(w->w_name);
371 		free((char *) w);
372 		w = nw;
373 	}
374 
375 	/* open the queue directory */
376 	f = opendir(".");
377 	if (f == NULL)
378 	{
379 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
380 		return (0);
381 	}
382 
383 	/*
384 	**  Read the work directory.
385 	*/
386 
387 	while ((d = readdir(f)) != NULL)
388 	{
389 		FILE *cf;
390 		char lbuf[MAXNAME];
391 
392 		/* is this an interesting entry? */
393 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
394 			continue;
395 
396 		/* yes -- open control file (if not too many files) */
397 		if (++wn >= WLSIZE)
398 			continue;
399 		cf = fopen(d->d_name, "r");
400 		if (cf == NULL)
401 		{
402 			/* this may be some random person sending hir msgs */
403 			/* syserr("orderq: cannot open %s", cbuf); */
404 #ifdef DEBUG
405 			if (tTd(41, 2))
406 				printf("orderq: cannot open %s (%d)\n",
407 					d->d_name, errno);
408 #endif DEBUG
409 			errno = 0;
410 			wn--;
411 			continue;
412 		}
413 		wlist[wn].w_name = newstr(d->d_name);
414 
415 		/* extract useful information */
416 		while (fgets(lbuf, sizeof lbuf, cf) != NULL)
417 		{
418 			extern long atol();
419 
420 			switch (lbuf[0])
421 			{
422 			  case 'P':
423 				wlist[wn].w_pri = atol(&lbuf[1]);
424 				break;
425 
426 			  case 'T':
427 				wlist[wn].w_ctime = atol(&lbuf[1]);
428 				break;
429 			}
430 		}
431 		(void) fclose(cf);
432 
433 		if (!doall && shouldqueue(wlist[wn].w_pri))
434 		{
435 			/* don't even bother sorting this job in */
436 			wn--;
437 		}
438 	}
439 	(void) closedir(f);
440 	wn++;
441 
442 	/*
443 	**  Sort the work directory.
444 	*/
445 
446 	qsort((char *) wlist, min(wn, WLSIZE), sizeof *wlist, workcmpf);
447 
448 	/*
449 	**  Convert the work list into canonical form.
450 	**	Should be turning it into a list of envelopes here perhaps.
451 	*/
452 
453 	wp = &WorkQ;
454 	for (i = min(wn, WLSIZE); --i >= 0; )
455 	{
456 		w = (WORK *) xalloc(sizeof *w);
457 		w->w_name = wlist[i].w_name;
458 		w->w_pri = wlist[i].w_pri;
459 		w->w_ctime = wlist[i].w_ctime;
460 		w->w_next = NULL;
461 		*wp = w;
462 		wp = &w->w_next;
463 	}
464 
465 # ifdef DEBUG
466 	if (tTd(40, 1))
467 	{
468 		for (w = WorkQ; w != NULL; w = w->w_next)
469 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
470 	}
471 # endif DEBUG
472 
473 	return (wn);
474 }
475 /*
476 **  WORKCMPF -- compare function for ordering work.
477 **
478 **	Parameters:
479 **		a -- the first argument.
480 **		b -- the second argument.
481 **
482 **	Returns:
483 **		1 if a < b
484 **		0 if a == b
485 **		-1 if a > b
486 **
487 **	Side Effects:
488 **		none.
489 */
490 
491 workcmpf(a, b)
492 	register WORK *a;
493 	register WORK *b;
494 {
495 	long pa = a->w_pri + a->w_ctime;
496 	long pb = b->w_pri + b->w_ctime;
497 
498 	if (pa == pb)
499 		return (0);
500 	else if (pa > pb)
501 		return (-1);
502 	else
503 		return (1);
504 }
505 /*
506 **  DOWORK -- do a work request.
507 **
508 **	Parameters:
509 **		w -- the work request to be satisfied.
510 **
511 **	Returns:
512 **		none.
513 **
514 **	Side Effects:
515 **		The work request is satisfied if possible.
516 */
517 
518 dowork(w)
519 	register WORK *w;
520 {
521 	register int i;
522 	extern bool shouldqueue();
523 
524 # ifdef DEBUG
525 	if (tTd(40, 1))
526 		printf("dowork: %s pri %ld\n", w->w_name, w->w_pri);
527 # endif DEBUG
528 
529 	/*
530 	**  Ignore jobs that are too expensive for the moment.
531 	*/
532 
533 	if (shouldqueue(w->w_pri))
534 	{
535 		if (Verbose)
536 			printf("\nSkipping %s\n", w->w_name + 2);
537 		return;
538 	}
539 
540 	/*
541 	**  Fork for work.
542 	*/
543 
544 	if (ForkQueueRuns)
545 	{
546 		i = fork();
547 		if (i < 0)
548 		{
549 			syserr("dowork: cannot fork");
550 			return;
551 		}
552 	}
553 	else
554 	{
555 		i = 0;
556 	}
557 
558 	if (i == 0)
559 	{
560 		/*
561 		**  CHILD
562 		**	Lock the control file to avoid duplicate deliveries.
563 		**		Then run the file as though we had just read it.
564 		**	We save an idea of the temporary name so we
565 		**		can recover on interrupt.
566 		*/
567 
568 		/* set basic modes, etc. */
569 		(void) alarm(0);
570 		clearenvelope(CurEnv);
571 		QueueRun = TRUE;
572 		ErrorMode = EM_MAIL;
573 		CurEnv->e_id = &w->w_name[2];
574 # ifdef LOG
575 		if (LogLevel > 11)
576 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", CurEnv->e_id,
577 			       getpid());
578 # endif LOG
579 
580 		/* don't use the headers from sendmail.cf... */
581 		CurEnv->e_header = NULL;
582 
583 		/* lock the control file during processing */
584 		if (link(w->w_name, queuename(CurEnv, 'l')) < 0)
585 		{
586 			/* being processed by another queuer */
587 # ifdef LOG
588 			if (LogLevel > 4)
589 				syslog(LOG_DEBUG, "%s: locked", CurEnv->e_id);
590 # endif LOG
591 			if (ForkQueueRuns)
592 				exit(EX_OK);
593 			else
594 				return;
595 		}
596 
597 		/* do basic system initialization */
598 		initsys();
599 
600 		/* read the queue control file */
601 		readqf(CurEnv, TRUE);
602 		CurEnv->e_flags |= EF_INQUEUE;
603 		eatheader(CurEnv);
604 
605 		/* do the delivery */
606 		if (!bitset(EF_FATALERRS, CurEnv->e_flags))
607 			sendall(CurEnv, SM_DELIVER);
608 
609 		/* finish up and exit */
610 		if (ForkQueueRuns)
611 			finis();
612 		else
613 			dropenvelope(CurEnv);
614 	}
615 	else
616 	{
617 		/*
618 		**  Parent -- pick up results.
619 		*/
620 
621 		errno = 0;
622 		(void) waitfor(i);
623 	}
624 }
625 /*
626 **  READQF -- read queue file and set up environment.
627 **
628 **	Parameters:
629 **		e -- the envelope of the job to run.
630 **		full -- if set, read in all information.  Otherwise just
631 **			read in info needed for a queue print.
632 **
633 **	Returns:
634 **		none.
635 **
636 **	Side Effects:
637 **		cf is read and created as the current job, as though
638 **		we had been invoked by argument.
639 */
640 
641 readqf(e, full)
642 	register ENVELOPE *e;
643 	bool full;
644 {
645 	char *qf;
646 	register FILE *qfp;
647 	char buf[MAXFIELD];
648 	extern char *fgetfolded();
649 	extern long atol();
650 
651 	/*
652 	**  Read and process the file.
653 	*/
654 
655 	qf = queuename(e, 'q');
656 	qfp = fopen(qf, "r");
657 	if (qfp == NULL)
658 	{
659 		syserr("readqf: no control file %s", qf);
660 		return;
661 	}
662 	FileName = qf;
663 	LineNumber = 0;
664 	if (Verbose && full)
665 		printf("\nRunning %s\n", e->e_id);
666 	while (fgetfolded(buf, sizeof buf, qfp) != NULL)
667 	{
668 		switch (buf[0])
669 		{
670 		  case 'R':		/* specify recipient */
671 			sendtolist(&buf[1], (ADDRESS *) NULL, &e->e_sendqueue);
672 			break;
673 
674 		  case 'H':		/* header */
675 			if (full)
676 				(void) chompheader(&buf[1], FALSE);
677 			break;
678 
679 		  case 'M':		/* message */
680 			e->e_message = newstr(&buf[1]);
681 			break;
682 
683 		  case 'S':		/* sender */
684 			setsender(newstr(&buf[1]));
685 			break;
686 
687 		  case 'D':		/* data file name */
688 			if (!full)
689 				break;
690 			e->e_df = newstr(&buf[1]);
691 			e->e_dfp = fopen(e->e_df, "r");
692 			if (e->e_dfp == NULL)
693 				syserr("readqf: cannot open %s", e->e_df);
694 			break;
695 
696 		  case 'T':		/* init time */
697 			e->e_ctime = atol(&buf[1]);
698 			break;
699 
700 		  case 'P':		/* message priority */
701 			e->e_msgpriority = atol(&buf[1]);
702 
703 			/* make sure that big things get sent eventually */
704 			e->e_msgpriority -= WKTIMEFACT;
705 			break;
706 
707 		  case '\0':		/* blank line; ignore */
708 			break;
709 
710 		  default:
711 			syserr("readqf(%s:%d): bad line \"%s\"", e->e_id,
712 				LineNumber, buf);
713 			break;
714 		}
715 	}
716 
717 	(void) fclose(qfp);
718 	FileName = NULL;
719 
720 	/*
721 	**  If we haven't read any lines, this queue file is empty.
722 	**  Arrange to remove it without referencing any null pointers.
723 	*/
724 
725 	if (LineNumber == 0)
726 	{
727 		errno = 0;
728 		e->e_flags |= EF_CLRQUEUE | EF_FATALERRS | EF_RESPONSE;
729 	}
730 }
731 /*
732 **  PRINTQUEUE -- print out a representation of the mail queue
733 **
734 **	Parameters:
735 **		none.
736 **
737 **	Returns:
738 **		none.
739 **
740 **	Side Effects:
741 **		Prints a listing of the mail queue on the standard output.
742 */
743 
744 printqueue()
745 {
746 	register WORK *w;
747 	FILE *f;
748 	int nrequests;
749 	char buf[MAXLINE];
750 
751 	/*
752 	**  Read and order the queue.
753 	*/
754 
755 	nrequests = orderq(TRUE);
756 
757 	/*
758 	**  Print the work list that we have read.
759 	*/
760 
761 	/* first see if there is anything */
762 	if (nrequests <= 0)
763 	{
764 		printf("Mail queue is empty\n");
765 		return;
766 	}
767 
768 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
769 	if (nrequests > WLSIZE)
770 		printf(", only %d printed", WLSIZE);
771 	if (Verbose)
772 		printf(")\n--QID-- --Size-- -Priority- -----Q-Time----- --------Sender/Recipient--------\n");
773 	else
774 		printf(")\n--QID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
775 	for (w = WorkQ; w != NULL; w = w->w_next)
776 	{
777 		struct stat st;
778 		auto time_t submittime = 0;
779 		long dfsize = -1;
780 		char lf[20];
781 		char message[MAXLINE];
782 		extern bool shouldqueue();
783 
784 		f = fopen(w->w_name, "r");
785 		if (f == NULL)
786 		{
787 			errno = 0;
788 			continue;
789 		}
790 		printf("%7s", w->w_name + 2);
791 		(void) strcpy(lf, w->w_name);
792 		lf[0] = 'l';
793 		if (stat(lf, &st) >= 0)
794 			printf("*");
795 		else if (shouldqueue(w->w_pri))
796 			printf("X");
797 		else
798 			printf(" ");
799 		errno = 0;
800 
801 		message[0] = '\0';
802 		while (fgets(buf, sizeof buf, f) != NULL)
803 		{
804 			fixcrlf(buf, TRUE);
805 			switch (buf[0])
806 			{
807 			  case 'M':	/* error message */
808 				(void) strcpy(message, &buf[1]);
809 				break;
810 
811 			  case 'S':	/* sender name */
812 				if (Verbose)
813 					printf("%8ld %10ld %.16s %.37s", dfsize,
814 					    w->w_pri, ctime(&submittime),
815 					    &buf[1]);
816 				else
817 					printf("%8ld %.16s %.45s", dfsize,
818 					    ctime(&submittime), &buf[1]);
819 				if (message[0] != '\0')
820 					printf("\n\t\t (%.62s)", message);
821 				break;
822 
823 			  case 'R':	/* recipient name */
824 				if (Verbose)
825 					printf("\n\t\t\t\t\t     %.37s", &buf[1]);
826 				else
827 					printf("\n\t\t\t\t  %.45s", &buf[1]);
828 				break;
829 
830 			  case 'T':	/* creation time */
831 				submittime = atol(&buf[1]);
832 				break;
833 
834 			  case 'D':	/* data file name */
835 				if (stat(&buf[1], &st) >= 0)
836 					dfsize = st.st_size;
837 				break;
838 			}
839 		}
840 		if (submittime == (time_t) 0)
841 			printf(" (no control file)");
842 		printf("\n");
843 		(void) fclose(f);
844 	}
845 }
846 
847 # endif QUEUE
848 /*
849 **  QUEUENAME -- build a file name in the queue directory for this envelope.
850 **
851 **	Assigns an id code if one does not already exist.
852 **	This code is very careful to avoid trashing existing files
853 **	under any circumstances.
854 **		We first create an nf file that is only used when
855 **		assigning an id.  This file is always empty, so that
856 **		we can never accidently truncate an lf file.
857 **
858 **	Parameters:
859 **		e -- envelope to build it in/from.
860 **		type -- the file type, used as the first character
861 **			of the file name.
862 **
863 **	Returns:
864 **		a pointer to the new file name (in a static buffer).
865 **
866 **	Side Effects:
867 **		Will create the lf and qf files if no id code is
868 **		already assigned.  This will cause the envelope
869 **		to be modified.
870 */
871 
872 char *
873 queuename(e, type)
874 	register ENVELOPE *e;
875 	char type;
876 {
877 	static char buf[MAXNAME];
878 	static int pid = -1;
879 	char c1 = 'A';
880 	char c2 = 'A';
881 
882 	if (e->e_id == NULL)
883 	{
884 		char qf[20];
885 		char nf[20];
886 		char lf[20];
887 
888 		/* find a unique id */
889 		if (pid != getpid())
890 		{
891 			/* new process -- start back at "AA" */
892 			pid = getpid();
893 			c1 = 'A';
894 			c2 = 'A' - 1;
895 		}
896 		(void) sprintf(qf, "qfAA%05d", pid);
897 		(void) strcpy(lf, qf);
898 		lf[0] = 'l';
899 		(void) strcpy(nf, qf);
900 		nf[0] = 'n';
901 
902 		while (c1 < '~' || c2 < 'Z')
903 		{
904 			int i;
905 
906 			if (c2 >= 'Z')
907 			{
908 				c1++;
909 				c2 = 'A' - 1;
910 			}
911 			lf[2] = nf[2] = qf[2] = c1;
912 			lf[3] = nf[3] = qf[3] = ++c2;
913 # ifdef DEBUG
914 			if (tTd(7, 20))
915 				printf("queuename: trying \"%s\"\n", nf);
916 # endif DEBUG
917 
918 # ifdef QUEUE
919 			if (access(lf, 0) >= 0 || access(qf, 0) >= 0)
920 				continue;
921 			errno = 0;
922 			i = creat(nf, FileMode);
923 			if (i < 0)
924 			{
925 				(void) unlink(nf);	/* kernel bug */
926 				continue;
927 			}
928 			(void) close(i);
929 			i = link(nf, lf);
930 			(void) unlink(nf);
931 			if (i < 0)
932 				continue;
933 			if (link(lf, qf) >= 0)
934 				break;
935 			(void) unlink(lf);
936 # else QUEUE
937 			if (close(creat(qf, FileMode)) >= 0)
938 				break;
939 # endif QUEUE
940 		}
941 		if (c1 >= '~' && c2 >= 'Z')
942 		{
943 			syserr("queuename: Cannot create \"%s\" in \"%s\"",
944 				qf, QueueDir);
945 			exit(EX_OSERR);
946 		}
947 		e->e_id = newstr(&qf[2]);
948 		define('i', e->e_id, e);
949 # ifdef DEBUG
950 		if (tTd(7, 1))
951 			printf("queuename: assigned id %s, env=%x\n", e->e_id, e);
952 # ifdef LOG
953 		if (LogLevel > 16)
954 			syslog(LOG_DEBUG, "%s: assigned id", e->e_id);
955 # endif LOG
956 # endif DEBUG
957 	}
958 
959 	if (type == '\0')
960 		return (NULL);
961 	(void) sprintf(buf, "%cf%s", type, e->e_id);
962 # ifdef DEBUG
963 	if (tTd(7, 2))
964 		printf("queuename: %s\n", buf);
965 # endif DEBUG
966 	return (buf);
967 }
968 /*
969 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
970 **
971 **	Parameters:
972 **		e -- the envelope to unlock.
973 **
974 **	Returns:
975 **		none
976 **
977 **	Side Effects:
978 **		unlocks the queue for `e'.
979 */
980 
981 unlockqueue(e)
982 	ENVELOPE *e;
983 {
984 	/* remove the transcript */
985 #ifdef DEBUG
986 # ifdef LOG
987 	if (LogLevel > 19)
988 		syslog(LOG_DEBUG, "%s: unlock", e->e_id);
989 # endif LOG
990 	if (!tTd(51, 4))
991 #endif DEBUG
992 		xunlink(queuename(e, 'x'));
993 
994 # ifdef QUEUE
995 	/* last but not least, remove the lock */
996 	xunlink(queuename(e, 'l'));
997 # endif QUEUE
998 }
999