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