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