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