xref: /csrg-svn/usr.sbin/sendmail/src/queue.c (revision 10173)
1 # include "sendmail.h"
2 # include <sys/stat.h>
3 # include <dir.h>
4 # include <signal.h>
5 # include <errno.h>
6 
7 # ifndef QUEUE
8 SCCSID(@(#)queue.c	3.67		01/06/83	(no queueing));
9 # else QUEUE
10 
11 SCCSID(@(#)queue.c	3.67		01/06/83);
12 
13 /*
14 **  Work queue.
15 */
16 
17 struct work
18 {
19 	char		*w_name;	/* name of control file */
20 	long		w_pri;		/* priority of message, see below */
21 	struct work	*w_next;	/* next in queue */
22 };
23 
24 typedef struct work	WORK;
25 
26 WORK	*WorkQ;			/* queue of things to be done */
27 /*
28 **  QUEUEUP -- queue a message up for future transmission.
29 **
30 **	Parameters:
31 **		e -- the envelope to queue up.
32 **		queueall -- if TRUE, queue all addresses, rather than
33 **			just those with the QQUEUEUP flag set.
34 **		announce -- if TRUE, tell when you are queueing up.
35 **
36 **	Returns:
37 **		none.
38 **
39 **	Side Effects:
40 **		The current request are saved in a control file.
41 */
42 
43 queueup(e, queueall, announce)
44 	register ENVELOPE *e;
45 	bool queueall;
46 	bool announce;
47 {
48 	char *tf;
49 	char *qf;
50 	char buf[MAXLINE];
51 	register FILE *tfp;
52 	register HDR *h;
53 	register ADDRESS *q;
54 	MAILER nullmailer;
55 
56 	/*
57 	**  Create control file.
58 	*/
59 
60 	tf = newstr(queuename(e, 't'));
61 	tfp = fopen(tf, "w");
62 	if (tfp == NULL)
63 	{
64 		syserr("queueup: cannot create temp file %s", tf);
65 		return;
66 	}
67 	(void) chmod(tf, FileMode);
68 
69 # ifdef DEBUG
70 	if (tTd(40, 1))
71 		printf("queueing in %s\n", tf);
72 # endif DEBUG
73 
74 	/*
75 	**  If there is no data file yet, create one.
76 	*/
77 
78 	if (e->e_df == NULL)
79 	{
80 		register FILE *dfp;
81 		extern putbody();
82 
83 		e->e_df = newstr(queuename(e, 'd'));
84 		dfp = fopen(e->e_df, "w");
85 		if (dfp == NULL)
86 		{
87 			syserr("queueup: cannot create %s", e->e_df);
88 			(void) fclose(tfp);
89 			return;
90 		}
91 		(void) chmod(e->e_df, FileMode);
92 		(*e->e_putbody)(dfp, ProgMailer, e);
93 		(void) fclose(dfp);
94 		e->e_putbody = putbody;
95 	}
96 
97 	/*
98 	**  Output future work requests.
99 	**	Priority should be first, since it is read by orderq.
100 	*/
101 
102 	/* output message priority */
103 	fprintf(tfp, "P%ld\n", e->e_msgpriority);
104 
105 	/* output creation time */
106 	fprintf(tfp, "T%ld\n", e->e_ctime);
107 
108 	/* output name of data file */
109 	fprintf(tfp, "D%s\n", e->e_df);
110 
111 	/* message from envelope, if it exists */
112 	if (e->e_message != NULL)
113 		fprintf(tfp, "M%s\n", e->e_message);
114 
115 	/* output name of sender */
116 	fprintf(tfp, "S%s\n", e->e_from.q_paddr);
117 
118 	/* output list of recipient addresses */
119 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
120 	{
121 		if (queueall ? !bitset(QDONTSEND, q->q_flags) :
122 			       bitset(QQUEUEUP, q->q_flags))
123 		{
124 			fprintf(tfp, "R%s\n", q->q_paddr);
125 			if (announce)
126 			{
127 				e->e_to = q->q_paddr;
128 				message(Arpa_Info, "queued");
129 				if (LogLevel > 4)
130 					logdelivery("queued");
131 				e->e_to = NULL;
132 			}
133 #ifdef DEBUG
134 			if (tTd(40, 1))
135 			{
136 				printf("queueing ");
137 				printaddr(q, FALSE);
138 			}
139 #endif DEBUG
140 		}
141 	}
142 
143 	/*
144 	**  Output headers for this message.
145 	**	Expand macros completely here.  Queue run will deal with
146 	**	everything as absolute headers.
147 	**		All headers that must be relative to the recipient
148 	**		can be cracked later.
149 	**	We set up a "null mailer" -- i.e., a mailer that will have
150 	**	no effect on the addresses as they are output.
151 	*/
152 
153 	bzero(&nullmailer, sizeof nullmailer);
154 	nullmailer.m_r_rwset = nullmailer.m_s_rwset = -1;
155 
156 	define('g', "$f", e);
157 	for (h = e->e_header; h != NULL; h = h->h_link)
158 	{
159 		if (h->h_value == NULL || h->h_value[0] == '\0')
160 			continue;
161 		fprintf(tfp, "H");
162 		if (h->h_mflags != 0 && bitset(H_CHECK|H_ACHECK, h->h_flags))
163 			mfdecode(h->h_mflags, tfp);
164 		if (bitset(H_DEFAULT, h->h_flags))
165 		{
166 			(void) expand(h->h_value, buf, &buf[sizeof buf], e);
167 			fprintf(tfp, "%s: %s\n", h->h_field, buf);
168 		}
169 		else if (bitset(H_FROM|H_RCPT, h->h_flags))
170 		{
171 			commaize(h, h->h_value, tfp, bitset(EF_OLDSTYLE, e->e_flags),
172 				 &nullmailer);
173 		}
174 		else
175 			fprintf(tfp, "%s: %s\n", h->h_field, h->h_value);
176 	}
177 
178 	/*
179 	**  Clean up.
180 	*/
181 
182 	(void) fclose(tfp);
183 	qf = queuename(e, 'q');
184 	holdsigs();
185 	(void) unlink(qf);
186 	if (link(tf, qf) < 0)
187 		syserr("cannot link(%s, %s), df=%s", tf, qf, e->e_df);
188 	else
189 		(void) unlink(tf);
190 	rlsesigs();
191 
192 # ifdef LOG
193 	/* save log info */
194 	if (LogLevel > 15)
195 		syslog(LOG_DEBUG, "%s: queueup, qf=%s, df=%s\n", e->e_id, qf, e->e_df);
196 # endif LOG
197 }
198 /*
199 **  RUNQUEUE -- run the jobs in the queue.
200 **
201 **	Gets the stuff out of the queue in some presumably logical
202 **	order and processes them.
203 **
204 **	Parameters:
205 **		none.
206 **
207 **	Returns:
208 **		none.
209 **
210 **	Side Effects:
211 **		runs things in the mail queue.
212 */
213 
214 runqueue(forkflag)
215 	bool forkflag;
216 {
217 	/*
218 	**  See if we want to go off and do other useful work.
219 	*/
220 
221 	if (forkflag)
222 	{
223 		int pid;
224 
225 		pid = dofork();
226 		if (pid != 0)
227 		{
228 			/* parent -- pick up intermediate zombie */
229 			(void) waitfor(pid);
230 			if (QueueIntvl != 0)
231 				(void) setevent(QueueIntvl, runqueue, TRUE);
232 			return;
233 		}
234 		/* child -- double fork */
235 		if (fork() != 0)
236 			exit(EX_OK);
237 	}
238 # ifdef LOG
239 	if (LogLevel > 11)
240 		syslog(LOG_DEBUG, "runqueue %s, pid=%d", QueueDir, getpid());
241 # endif LOG
242 
243 	/*
244 	**  Start making passes through the queue.
245 	**	First, read and sort the entire queue.
246 	**	Then, process the work in that order.
247 	**		But if you take too long, start over.
248 	*/
249 
250 	/* order the existing work requests */
251 	(void) orderq();
252 
253 	/* process them once at a time */
254 	while (WorkQ != NULL)
255 	{
256 		WORK *w = WorkQ;
257 
258 		WorkQ = WorkQ->w_next;
259 		dowork(w);
260 		free(w->w_name);
261 		free((char *) w);
262 	}
263 	finis();
264 }
265 /*
266 **  ORDERQ -- order the work queue.
267 **
268 **	Parameters:
269 **		none.
270 **
271 **	Returns:
272 **		The number of request in the queue (not necessarily
273 **		the number of requests in WorkQ however).
274 **
275 **	Side Effects:
276 **		Sets WorkQ to the queue of available work, in order.
277 */
278 
279 # define WLSIZE		120	/* max size of worklist per sort */
280 
281 orderq()
282 {
283 	register struct direct *d;
284 	register WORK *w;
285 	register WORK **wp;		/* parent of w */
286 	DIR *f;
287 	register int i;
288 	WORK wlist[WLSIZE+1];
289 	int wn = -1;
290 	extern workcmpf();
291 
292 	/* clear out old WorkQ */
293 	for (w = WorkQ; w != NULL; )
294 	{
295 		register WORK *nw = w->w_next;
296 
297 		WorkQ = nw;
298 		free(w->w_name);
299 		free((char *) w);
300 		w = nw;
301 	}
302 
303 	/* open the queue directory */
304 	f = opendir(".");
305 	if (f == NULL)
306 	{
307 		syserr("orderq: cannot open \"%s\" as \".\"", QueueDir);
308 		return (0);
309 	}
310 
311 	/*
312 	**  Read the work directory.
313 	*/
314 
315 	while ((d = readdir(f)) != NULL)
316 	{
317 		FILE *cf;
318 		char lbuf[MAXNAME];
319 
320 		/* is this an interesting entry? */
321 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
322 			continue;
323 
324 		/* yes -- open control file (if not too many files) */
325 		if (++wn >= WLSIZE)
326 			continue;
327 		cf = fopen(d->d_name, "r");
328 		if (cf == NULL)
329 		{
330 			/* this may be some random person sending hir msgs */
331 			/* syserr("orderq: cannot open %s", cbuf); */
332 #ifdef DEBUG
333 			if (tTd(41, 2))
334 				printf("orderq: cannot open %s (%d)\n",
335 					d->d_name, errno);
336 #endif DEBUG
337 			errno = 0;
338 			wn--;
339 			continue;
340 		}
341 		wlist[wn].w_name = newstr(d->d_name);
342 
343 		/* extract useful information */
344 		while (fgets(lbuf, sizeof lbuf, cf) != NULL)
345 		{
346 			if (lbuf[0] == 'P')
347 			{
348 				(void) sscanf(&lbuf[1], "%ld", &wlist[wn].w_pri);
349 				break;
350 			}
351 		}
352 		(void) fclose(cf);
353 	}
354 	(void) closedir(f);
355 	wn++;
356 
357 	/*
358 	**  Sort the work directory.
359 	*/
360 
361 	qsort(wlist, min(wn, WLSIZE), sizeof *wlist, workcmpf);
362 
363 	/*
364 	**  Convert the work list into canonical form.
365 	**	Should be turning it into a list of envelopes here perhaps.
366 	*/
367 
368 	wp = &WorkQ;
369 	for (i = min(wn, WLSIZE); --i >= 0; )
370 	{
371 		w = (WORK *) xalloc(sizeof *w);
372 		w->w_name = wlist[i].w_name;
373 		w->w_pri = wlist[i].w_pri;
374 		w->w_next = NULL;
375 		*wp = w;
376 		wp = &w->w_next;
377 	}
378 
379 # ifdef DEBUG
380 	if (tTd(40, 1))
381 	{
382 		for (w = WorkQ; w != NULL; w = w->w_next)
383 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
384 	}
385 # endif DEBUG
386 
387 	return (wn);
388 }
389 /*
390 **  WORKCMPF -- compare function for ordering work.
391 **
392 **	Parameters:
393 **		a -- the first argument.
394 **		b -- the second argument.
395 **
396 **	Returns:
397 **		1 if a < b
398 **		0 if a == b
399 **		-1 if a > b
400 **
401 **	Side Effects:
402 **		none.
403 */
404 
405 workcmpf(a, b)
406 	register WORK *a;
407 	register WORK *b;
408 {
409 	if (a->w_pri == b->w_pri)
410 		return (0);
411 	else if (a->w_pri > b->w_pri)
412 		return (-1);
413 	else
414 		return (1);
415 }
416 /*
417 **  DOWORK -- do a work request.
418 **
419 **	Parameters:
420 **		w -- the work request to be satisfied.
421 **
422 **	Returns:
423 **		none.
424 **
425 **	Side Effects:
426 **		The work request is satisfied if possible.
427 */
428 
429 dowork(w)
430 	register WORK *w;
431 {
432 	register int i;
433 
434 # ifdef DEBUG
435 	if (tTd(40, 1))
436 		printf("dowork: %s pri %ld\n", w->w_name, w->w_pri);
437 # endif DEBUG
438 
439 	/*
440 	**  Fork for work.
441 	*/
442 
443 	i = fork();
444 	if (i < 0)
445 	{
446 		syserr("dowork: cannot fork");
447 		return;
448 	}
449 
450 	if (i == 0)
451 	{
452 		/*
453 		**  CHILD
454 		**	Lock the control file to avoid duplicate deliveries.
455 		**		Then run the file as though we had just read it.
456 		**	We save an idea of the temporary name so we
457 		**		can recover on interrupt.
458 		*/
459 
460 		/* set basic modes, etc. */
461 		(void) alarm(0);
462 		CurEnv->e_flags &= ~EF_FATALERRS;
463 		QueueRun = TRUE;
464 		ErrorMode = EM_MAIL;
465 		CurEnv->e_id = &w->w_name[2];
466 # ifdef LOG
467 		if (LogLevel > 11)
468 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", CurEnv->e_id,
469 			       getpid());
470 # endif LOG
471 
472 		/* don't use the headers from sendmail.cf... */
473 		CurEnv->e_header = NULL;
474 		(void) chompheader("from: $q", TRUE);
475 
476 		/* create the link to the control file during processing */
477 		if (link(w->w_name, queuename(CurEnv, 'l')) < 0)
478 		{
479 			/* being processed by another queuer */
480 # ifdef LOG
481 			if (LogLevel > 4)
482 				syslog(LOG_DEBUG, "%s: locked", CurEnv->e_id);
483 # endif LOG
484 			exit(EX_OK);
485 		}
486 
487 		/* do basic system initialization */
488 		initsys();
489 
490 		/* read the queue control file */
491 		readqf(CurEnv, TRUE);
492 		CurEnv->e_flags |= EF_INQUEUE;
493 		eatheader(CurEnv);
494 
495 		/* do the delivery */
496 		if (!bitset(EF_FATALERRS, CurEnv->e_flags))
497 			sendall(CurEnv, SM_DELIVER);
498 
499 		/* finish up and exit */
500 		finis();
501 	}
502 
503 	/*
504 	**  Parent -- pick up results.
505 	*/
506 
507 	errno = 0;
508 	(void) waitfor(i);
509 }
510 /*
511 **  READQF -- read queue file and set up environment.
512 **
513 **	Parameters:
514 **		e -- the envelope of the job to run.
515 **		full -- if set, read in all information.  Otherwise just
516 **			read in info needed for a queue print.
517 **
518 **	Returns:
519 **		none.
520 **
521 **	Side Effects:
522 **		cf is read and created as the current job, as though
523 **		we had been invoked by argument.
524 */
525 
526 readqf(e, full)
527 	register ENVELOPE *e;
528 	bool full;
529 {
530 	register FILE *f;
531 	char buf[MAXFIELD];
532 	extern char *fgetfolded();
533 	register char *p;
534 
535 	/*
536 	**  Open the file created by queueup.
537 	*/
538 
539 	p = queuename(e, 'q');
540 	f = fopen(p, "r");
541 	if (f == NULL)
542 	{
543 		syserr("readqf: no control file %s", p);
544 		return;
545 	}
546 	FileName = p;
547 	LineNumber = 0;
548 
549 	/*
550 	**  Read and process the file.
551 	*/
552 
553 	if (Verbose && full)
554 		printf("\nRunning %s\n", e->e_id);
555 	while (fgetfolded(buf, sizeof buf, f) != NULL)
556 	{
557 		switch (buf[0])
558 		{
559 		  case 'R':		/* specify recipient */
560 			sendtolist(&buf[1], (ADDRESS *) NULL, &e->e_sendqueue);
561 			break;
562 
563 		  case 'H':		/* header */
564 			if (full)
565 				(void) chompheader(&buf[1], FALSE);
566 			break;
567 
568 		  case 'M':		/* message */
569 			e->e_message = newstr(&buf[1]);
570 			break;
571 
572 		  case 'S':		/* sender */
573 			setsender(newstr(&buf[1]));
574 			break;
575 
576 		  case 'D':		/* data file name */
577 			if (!full)
578 				break;
579 			e->e_df = newstr(&buf[1]);
580 			e->e_dfp = fopen(e->e_df, "r");
581 			if (e->e_dfp == NULL)
582 				syserr("readqf: cannot open %s", e->e_df);
583 			break;
584 
585 		  case 'T':		/* init time */
586 			(void) sscanf(&buf[1], "%ld", &e->e_ctime);
587 			break;
588 
589 		  case 'P':		/* message priority */
590 			(void) sscanf(&buf[1], "%ld", &e->e_msgpriority);
591 
592 			/* make sure that big things get sent eventually */
593 			e->e_msgpriority -= WKTIMEFACT;
594 			break;
595 
596 		  default:
597 			syserr("readqf(%s): bad line \"%s\"", e->e_id, buf);
598 			break;
599 		}
600 	}
601 
602 	FileName = NULL;
603 }
604 /*
605 **  PRINTQUEUE -- print out a representation of the mail queue
606 **
607 **	Parameters:
608 **		none.
609 **
610 **	Returns:
611 **		none.
612 **
613 **	Side Effects:
614 **		Prints a listing of the mail queue on the standard output.
615 */
616 
617 printqueue()
618 {
619 	register WORK *w;
620 	FILE *f;
621 	int nrequests;
622 	char buf[MAXLINE];
623 
624 	/*
625 	**  Read and order the queue.
626 	*/
627 
628 	nrequests = orderq();
629 
630 	/*
631 	**  Print the work list that we have read.
632 	*/
633 
634 	/* first see if there is anything */
635 	if (nrequests <= 0)
636 	{
637 		printf("Mail queue is empty\n");
638 		return;
639 	}
640 
641 	printf("\t\tMail Queue (%d request%s", nrequests, nrequests == 1 ? "" : "s");
642 	if (nrequests > WLSIZE)
643 		printf(", only %d printed", WLSIZE);
644 	printf(")\n--QID-- --Size-- -----Q-Time----- ------------Sender/Recipient------------\n");
645 	for (w = WorkQ; w != NULL; w = w->w_next)
646 	{
647 		struct stat st;
648 		auto time_t submittime = 0;
649 		long dfsize = -1;
650 		char lf[20];
651 		char message[MAXLINE];
652 
653 		printf("%7s", w->w_name + 2);
654 		strcpy(lf, w->w_name);
655 		lf[0] = 'l';
656 		if (stat(lf, &st) >= 0)
657 			printf("*");
658 		else
659 			printf(" ");
660 		errno = 0;
661 		f = fopen(w->w_name, "r");
662 		if (f == NULL)
663 		{
664 			printf(" (finished)\n");
665 			errno = 0;
666 			continue;
667 		}
668 		message[0] = '\0';
669 		while (fgets(buf, sizeof buf, f) != NULL)
670 		{
671 			fixcrlf(buf, TRUE);
672 			switch (buf[0])
673 			{
674 			  case 'M':	/* error message */
675 				strcpy(message, &buf[1]);
676 				break;
677 
678 			  case 'S':	/* sender name */
679 				if (message[0] != '\0')
680 				{
681 					(void) strcat(buf, " (");
682 					(void) strcat(buf, message);
683 					(void) strcat(buf, ")");
684 				}
685 				printf("%8d %.16s %.40s", dfsize,
686 					ctime(&submittime), &buf[1]);
687 				break;
688 
689 			  case 'R':	/* recipient name */
690 				printf("\n\t\t\t\t  %.40s", &buf[1]);
691 				break;
692 
693 			  case 'T':	/* creation time */
694 				sscanf(&buf[1], "%ld", &submittime);
695 				break;
696 
697 			  case 'D':	/* data file name */
698 				if (stat(&buf[1], &st) >= 0)
699 					dfsize = st.st_size;
700 				break;
701 			}
702 		}
703 		if (submittime == (time_t) 0)
704 			printf(" (no control file)");
705 		printf("\n");
706 		fclose(f);
707 	}
708 }
709 
710 # endif QUEUE
711