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.39		08/25/82	(no queueing));
9 # else QUEUE
10 
11 SCCSID(@(#)queue.c	3.39		08/25/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 creation time */
94 	fprintf(tfp, "T%ld\n", e->e_ctime);
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 > 15)
163 		syslog(LOG_DEBUG, "%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 # ifdef LOG
209 	if (LogLevel > 11)
210 		syslog(LOG_DEBUG, "runqueue, pid=%d", getpid());
211 # endif LOG
212 
213 	/*
214 	**  Start making passes through the queue.
215 	**	First, read and sort the entire queue.
216 	**	Then, process the work in that order.
217 	**		But if you take too long, start over.
218 	**	There is a race condition at the end -- we could get
219 	**		a reorder signal after finishing the queue.
220 	**		In this case we will hang for one more queue
221 	**		interval -- clearly a botch, but rare and
222 	**		relatively innocuous.
223 	*/
224 
225 	for (;;)
226 	{
227 		/* order the existing work requests */
228 		orderq();
229 
230 		/* arrange to reorder later */
231 		ReorderQueue = FALSE;
232 		if (QueueIntvl != 0)
233 			setevent(QueueIntvl, reordersig, FALSE);
234 
235 		/* process them once at a time */
236 		while (WorkQ != NULL)
237 		{
238 			WORK *w = WorkQ;
239 
240 			WorkQ = WorkQ->w_next;
241 			dowork(w);
242 			free(w->w_name);
243 			free((char *) w);
244 			if (ReorderQueue)
245 				break;
246 		}
247 
248 		/* if we are just doing one pass, then we are done */
249 		if (QueueIntvl == 0)
250 			finis();
251 
252 		/* wait for work -- note (harmless) race condition here */
253 		while (!ReorderQueue)
254 		{
255 			if (forkflag)
256 				finis();
257 			pause();
258 		}
259 	}
260 }
261 /*
262 **  REORDERSIG -- catch the reorder signal and tell sendmail to reorder queue.
263 **
264 **	Parameters:
265 **		parent -- if set, called from parent (i.e., not
266 **			really doing the work).
267 **
268 **	Returns:
269 **		none.
270 **
271 **	Side Effects:
272 **		sets the "reorder work queue" flag.
273 */
274 
275 reordersig(parent)
276 	bool parent;
277 {
278 	if (!parent)
279 	{
280 		/* we are in a child doing queueing */
281 		ReorderQueue = TRUE;
282 
283 		/* arrange to get this signal again */
284 		setevent(QueueIntvl, reordersig, FALSE);
285 	}
286 	else
287 	{
288 		/*
289 		**  In parent.  If the child still exists, we want
290 		**  to do nothing.  If the child is gone, we will
291 		**  start up a new one.
292 		**  If the child exists, it is responsible for
293 		**  doing a queue reorder.
294 		**  This code really sucks.
295 		*/
296 
297 		if (kill(QueuePid, SIGALRM) < 0)
298 		{
299 			/* no child -- get zombie & start new one */
300 			static int st;
301 
302 			(void) wait(&st);
303 			runqueue(TRUE);
304 		}
305 		else
306 			setevent(QueueIntvl, reordersig, TRUE);
307 	}
308 }
309 /*
310 **  ORDERQ -- order the work queue.
311 **
312 **	Parameters:
313 **		none.
314 **
315 **	Returns:
316 **		none.
317 **
318 **	Side Effects:
319 **		Sets WorkQ to the queue of available work, in order.
320 */
321 
322 # define WLSIZE		120	/* max size of worklist per sort */
323 
324 orderq()
325 {
326 	register struct direct *d;
327 	register WORK *w;
328 	register WORK **wp;		/* parent of w */
329 	DIR *f;
330 	register int i;
331 	WORK wlist[WLSIZE];
332 	int wn = 0;
333 	extern workcmpf();
334 	extern char *QueueDir;
335 
336 	/* clear out old WorkQ */
337 	for (w = WorkQ; w != NULL; )
338 	{
339 		register WORK *nw = w->w_next;
340 
341 		WorkQ = nw;
342 		free(w->w_name);
343 		free((char *) w);
344 		w = nw;
345 	}
346 
347 	/* open the queue directory */
348 	f = opendir(QueueDir);
349 	if (f == NULL)
350 	{
351 		syserr("orderq: cannot open %s", QueueDir);
352 		return;
353 	}
354 
355 	/*
356 	**  Read the work directory.
357 	*/
358 
359 	while (wn < WLSIZE && (d = readdir(f)) != NULL)
360 	{
361 		char cbuf[MAXNAME];
362 		char lbuf[MAXNAME];
363 		FILE *cf;
364 		register char *p;
365 
366 		/* is this an interesting entry? */
367 		if (d->d_name[0] != 'q' || d->d_name[1] != 'f')
368 			continue;
369 
370 		/* yes -- find the control file location */
371 		(void) strcpy(cbuf, QueueDir);
372 		(void) strcat(cbuf, "/");
373 		p = &cbuf[strlen(cbuf)];
374 		(void) strcpy(p, d->d_name);
375 
376 		/* open control file */
377 		cf = fopen(cbuf, "r");
378 		if (cf == NULL)
379 		{
380 			/* this may be some random person sending hir msgs */
381 			/* syserr("orderq: cannot open %s", cbuf); */
382 			errno = 0;
383 			continue;
384 		}
385 		wlist[wn].w_name = newstr(cbuf);
386 
387 		/* extract useful information */
388 		while (fgets(lbuf, sizeof lbuf, cf) != NULL)
389 		{
390 			fixcrlf(lbuf, TRUE);
391 
392 			switch (lbuf[0])
393 			{
394 			  case 'P':		/* message priority */
395 				(void) sscanf(&lbuf[1], "%ld", &wlist[wn].w_pri);
396 				break;
397 			}
398 		}
399 		wn++;
400 		(void) fclose(cf);
401 	}
402 	(void) closedir(f);
403 
404 	/*
405 	**  Sort the work directory.
406 	*/
407 
408 	qsort(wlist, wn, sizeof *wlist, workcmpf);
409 
410 	/*
411 	**  Convert the work list into canonical form.
412 	*/
413 
414 	wp = &WorkQ;
415 	for (i = 0; i < wn; i++)
416 	{
417 		w = (WORK *) xalloc(sizeof *w);
418 		w->w_name = wlist[i].w_name;
419 		w->w_pri = wlist[i].w_pri;
420 		w->w_next = NULL;
421 		*wp = w;
422 		wp = &w->w_next;
423 	}
424 
425 # ifdef DEBUG
426 	if (tTd(40, 1))
427 	{
428 		for (w = WorkQ; w != NULL; w = w->w_next)
429 			printf("%32s: pri=%ld\n", w->w_name, w->w_pri);
430 	}
431 # endif DEBUG
432 }
433 /*
434 **  WORKCMPF -- compare function for ordering work.
435 **
436 **	Parameters:
437 **		a -- the first argument.
438 **		b -- the second argument.
439 **
440 **	Returns:
441 **		-1 if a < b
442 **		0 if a == b
443 **		1 if a > b
444 **
445 **	Side Effects:
446 **		none.
447 */
448 
449 # define PRIFACT	1800		/* bytes each priority point is worth */
450 
451 workcmpf(a, b)
452 	register WORK *a;
453 	register WORK *b;
454 {
455 	if (a->w_pri == b->w_pri)
456 		return (0);
457 	else if (a->w_pri > b->w_pri)
458 		return (1);
459 	else
460 		return (-1);
461 }
462 /*
463 **  DOWORK -- do a work request.
464 **
465 **	Parameters:
466 **		w -- the work request to be satisfied.
467 **
468 **	Returns:
469 **		none.
470 **
471 **	Side Effects:
472 **		The work request is satisfied if possible.
473 */
474 
475 dowork(w)
476 	register WORK *w;
477 {
478 	register int i;
479 	auto int xstat;
480 
481 # ifdef DEBUG
482 	if (tTd(40, 1))
483 		printf("dowork: %s pri %ld\n", w->w_name, w->w_pri);
484 # endif DEBUG
485 
486 	/*
487 	**  Fork for work.
488 	*/
489 
490 	i = fork();
491 	if (i < 0)
492 	{
493 		syserr("dowork: cannot fork");
494 		return;
495 	}
496 
497 	if (i == 0)
498 	{
499 		char buf[MAXNAME];
500 
501 		/*
502 		**  CHILD
503 		**	Change the name of the control file to avoid
504 		**		duplicate deliveries.   Then run the file
505 		**		as though we had just read it.
506 		**	We save an idea of the temporary name so we
507 		**		can recover on interrupt.
508 		*/
509 
510 		/* set basic modes, etc. */
511 		(void) alarm(0);
512 		FatalErrors = FALSE;
513 		QueueRun = TRUE;
514 		MailBack = TRUE;
515 		CurEnv->e_qf = w->w_name;
516 		CurEnv->e_id = &w->w_name[strlen(QueueDir) + 3];
517 # ifdef LOG
518 		if (LogLevel > 11)
519 			syslog(LOG_DEBUG, "%s: dowork, pid=%d", CurEnv->e_id,
520 			       getpid());
521 # endif LOG
522 
523 		/* don't use the headers from sendmail.cf... */
524 		CurEnv->e_header = NULL;
525 		chompheader("from: $q", TRUE);
526 
527 		/* create the link to the control file during processing */
528 		if (link(w->w_name, queuename(CurEnv, 'l')) < 0)
529 		{
530 			/* being processed by another queuer */
531 # ifdef LOG
532 			if (LogLevel > 4)
533 				syslog(LOG_DEBUG, "%s: locked", CurEnv->e_id);
534 # endif LOG
535 			exit(EX_OK);
536 		}
537 
538 		/* create ourselves a transcript file */
539 		openxscrpt();
540 
541 		/* do basic system initialization */
542 		initsys();
543 
544 		/* read the queue control file */
545 		readqf(CurEnv->e_qf);
546 		eatheader();
547 
548 		/* do the delivery */
549 		if (!FatalErrors)
550 			sendall(CurEnv, FALSE);
551 
552 		/* if still not sent, perhaps we should time out.... */
553 # ifdef DEBUG
554 		if (tTd(40, 3))
555 			printf("curtime=%ld, TimeOut=%ld\n", curtime(),
556 					     CurEnv->e_ctime + TimeOut);
557 # endif DEBUG
558 		if (CurEnv->e_queueup && curtime() > CurEnv->e_ctime + TimeOut)
559 			timeout(w);
560 
561 		/* finish up and exit */
562 		finis();
563 	}
564 
565 	/*
566 	**  Parent -- pick up results.
567 	*/
568 
569 	errno = 0;
570 	while ((i = wait(&xstat)) > 0 && errno != EINTR)
571 	{
572 		if (errno == EINTR)
573 		{
574 			errno = 0;
575 		}
576 	}
577 }
578 /*
579 **  READQF -- read queue file and set up environment.
580 **
581 **	Parameters:
582 **		cf -- name of queue control file.
583 **
584 **	Returns:
585 **		none.
586 **
587 **	Side Effects:
588 **		cf is read and created as the current job, as though
589 **		we had been invoked by argument.
590 */
591 
592 readqf(cf)
593 	char *cf;
594 {
595 	register FILE *f;
596 	char buf[MAXFIELD];
597 	register char *p;
598 	register int i;
599 
600 	/*
601 	**  Open the file created by queueup.
602 	*/
603 
604 	f = fopen(cf, "r");
605 	if (f == NULL)
606 	{
607 		syserr("readqf: no cf file %s", cf);
608 		return;
609 	}
610 
611 	/*
612 	**  Read and process the file.
613 	*/
614 
615 	if (Verbose)
616 		printf("\nRunning %s\n", cf);
617 	while (fgetfolded(buf, sizeof buf, f) != NULL)
618 	{
619 		switch (buf[0])
620 		{
621 		  case 'R':		/* specify recipient */
622 			sendto(&buf[1], 1, (ADDRESS *) NULL, &CurEnv->e_sendqueue);
623 			break;
624 
625 		  case 'H':		/* header */
626 			(void) chompheader(&buf[1], FALSE);
627 			break;
628 
629 		  case 'S':		/* sender */
630 			setsender(newstr(&buf[1]));
631 			break;
632 
633 		  case 'D':		/* data file name */
634 			CurEnv->e_df = newstr(&buf[1]);
635 			TempFile = fopen(CurEnv->e_df, "r");
636 			if (TempFile == NULL)
637 				syserr("readqf: cannot open %s", CurEnv->e_df);
638 			break;
639 
640 		  case 'T':		/* init time */
641 			(void) sscanf(&buf[1], "%ld", &CurEnv->e_ctime);
642 			break;
643 
644 		  case 'P':		/* message priority */
645 			(void) sscanf(&buf[1], "%ld", &CurEnv->e_msgpriority);
646 
647 			/* make sure that big things get sent eventually */
648 			CurEnv->e_msgpriority -= WKTIMEFACT;
649 			break;
650 
651 		  case 'C':		/* message class */
652 			(void) sscanf(&buf[1], "%hd", &CurEnv->e_class);
653 			break;
654 
655 		  case 'M':		/* define macro */
656 			define(buf[1], newstr(&buf[2]));
657 			break;
658 
659 		  default:
660 			syserr("readqf(%s): bad line \"%s\"", cf, buf);
661 			break;
662 		}
663 	}
664 }
665 /*
666 **  TIMEOUT -- process timeout on queue file.
667 **
668 **	Parameters:
669 **		w -- pointer to work request that timed out.
670 **
671 **	Returns:
672 **		none.
673 **
674 **	Side Effects:
675 **		Returns a message to the sender saying that this
676 **		message has timed out.
677 */
678 
679 timeout(w)
680 	register WORK *w;
681 {
682 	char buf[MAXLINE];
683 	extern char *pintvl();
684 
685 # ifdef DEBUG
686 	if (tTd(40, 3))
687 		printf("timeout(%s)\n", w->w_name);
688 # endif DEBUG
689 	message(Arpa_Info, "Message has timed out");
690 
691 	/* return message to sender */
692 	(void) sprintf(buf, "Cannot send mail for %s", pintvl(TimeOut, FALSE));
693 	(void) returntosender(buf, &CurEnv->e_from, TRUE);
694 
695 	/* arrange to remove files from queue */
696 	CurEnv->e_dontqueue = TRUE;
697 }
698 
699 # endif QUEUE
700