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