xref: /illumos-gate/usr/src/cmd/sendmail/src/queue.c (revision d4660949)
1 /*
2  * Copyright (c) 1998-2007 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #pragma ident	"%Z%%M%	%I%	%E% SMI"
15 
16 #include <sendmail.h>
17 #include <sm/sem.h>
18 
19 SM_RCSID("@(#)$Id: queue.c,v 8.977 2008/02/15 23:19:58 ca Exp $")
20 
21 #include <dirent.h>
22 
23 # define RELEASE_QUEUE	(void) 0
24 # define ST_INODE(st)	(st).st_ino
25 
26 #  define sm_file_exists(errno) ((errno) == EEXIST)
27 
28 # if HASFLOCK && defined(O_EXLOCK)
29 #   define SM_OPEN_EXLOCK 1
30 #   define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL|O_EXLOCK)
31 # else /* HASFLOCK && defined(O_EXLOCK) */
32 #  define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL)
33 # endif /* HASFLOCK && defined(O_EXLOCK) */
34 
35 #ifndef SM_OPEN_EXLOCK
36 # define SM_OPEN_EXLOCK 0
37 #endif /* ! SM_OPEN_EXLOCK */
38 
39 /*
40 **  Historical notes:
41 **	QF_VERSION == 4 was sendmail 8.10/8.11 without _FFR_QUEUEDELAY
42 **	QF_VERSION == 5 was sendmail 8.10/8.11 with    _FFR_QUEUEDELAY
43 **	QF_VERSION == 6 was sendmail 8.12      without _FFR_QUEUEDELAY
44 **	QF_VERSION == 7 was sendmail 8.12      with    _FFR_QUEUEDELAY
45 **	QF_VERSION == 8 is  sendmail 8.13
46 */
47 
48 #define QF_VERSION	8	/* version number of this queue format */
49 
50 static char	queue_letter __P((ENVELOPE *, int));
51 static bool	quarantine_queue_item __P((int, int, ENVELOPE *, char *));
52 
53 /* Naming convention: qgrp: index of queue group, qg: QUEUEGROUP */
54 
55 /*
56 **  Work queue.
57 */
58 
59 struct work
60 {
61 	char		*w_name;	/* name of control file */
62 	char		*w_host;	/* name of recipient host */
63 	bool		w_lock;		/* is message locked? */
64 	bool		w_tooyoung;	/* is it too young to run? */
65 	long		w_pri;		/* priority of message, see below */
66 	time_t		w_ctime;	/* creation time */
67 	time_t		w_mtime;	/* modification time */
68 	int		w_qgrp;		/* queue group located in */
69 	int		w_qdir;		/* queue directory located in */
70 	struct work	*w_next;	/* next in queue */
71 };
72 
73 typedef struct work	WORK;
74 
75 static WORK	*WorkQ;		/* queue of things to be done */
76 static int	NumWorkGroups;	/* number of work groups */
77 static time_t	Current_LA_time = 0;
78 
79 /* Get new load average every 30 seconds. */
80 #define GET_NEW_LA_TIME	30
81 
82 #define SM_GET_LA(now)	\
83 	do							\
84 	{							\
85 		now = curtime();				\
86 		if (Current_LA_time < now - GET_NEW_LA_TIME)	\
87 		{						\
88 			sm_getla();				\
89 			Current_LA_time = now;			\
90 		}						\
91 	} while (0)
92 
93 /*
94 **  DoQueueRun indicates that a queue run is needed.
95 **	Notice: DoQueueRun is modified in a signal handler!
96 */
97 
98 static bool	volatile DoQueueRun; /* non-interrupt time queue run needed */
99 
100 /*
101 **  Work group definition structure.
102 **	Each work group contains one or more queue groups. This is done
103 **	to manage the number of queue group runners active at the same time
104 **	to be within the constraints of MaxQueueChildren (if it is set).
105 **	The number of queue groups that can be run on the next work run
106 **	is kept track of. The queue groups are run in a round robin.
107 */
108 
109 struct workgrp
110 {
111 	int		wg_numqgrp;	/* number of queue groups in work grp */
112 	int		wg_runners;	/* total runners */
113 	int		wg_curqgrp;	/* current queue group */
114 	QUEUEGRP	**wg_qgs;	/* array of queue groups */
115 	int		wg_maxact;	/* max # of active runners */
116 	time_t		wg_lowqintvl;	/* lowest queue interval */
117 	int		wg_restart;	/* needs restarting? */
118 	int		wg_restartcnt;	/* count of times restarted */
119 };
120 
121 typedef struct workgrp WORKGRP;
122 
123 static WORKGRP	volatile WorkGrp[MAXWORKGROUPS + 1];	/* work groups */
124 
125 #if SM_HEAP_CHECK
126 static SM_DEBUG_T DebugLeakQ = SM_DEBUG_INITIALIZER("leak_q",
127 	"@(#)$Debug: leak_q - trace memory leaks during queue processing $");
128 #endif /* SM_HEAP_CHECK */
129 
130 /*
131 **  We use EmptyString instead of "" to avoid
132 **  'zero-length format string' warnings from gcc
133 */
134 
135 static const char EmptyString[] = "";
136 
137 static void	grow_wlist __P((int, int));
138 static int	multiqueue_cache __P((char *, int, QUEUEGRP *, int, unsigned int *));
139 static int	gatherq __P((int, int, bool, bool *, bool *));
140 static int	sortq __P((int));
141 static void	printctladdr __P((ADDRESS *, SM_FILE_T *));
142 static bool	readqf __P((ENVELOPE *, bool));
143 static void	restart_work_group __P((int));
144 static void	runner_work __P((ENVELOPE *, int, bool, int, int));
145 static void	schedule_queue_runs __P((bool, int, bool));
146 static char	*strrev __P((char *));
147 static ADDRESS	*setctluser __P((char *, int, ENVELOPE *));
148 #if _FFR_RHS
149 static int	sm_strshufflecmp __P((char *, char *));
150 static void	init_shuffle_alphabet __P(());
151 #endif /* _FFR_RHS */
152 
153 /*
154 **  Note: workcmpf?() don't use a prototype because it will cause a conflict
155 **  with the qsort() call (which expects something like
156 **  int (*compar)(const void *, const void *), not (WORK *, WORK *))
157 */
158 
159 static int	workcmpf0();
160 static int	workcmpf1();
161 static int	workcmpf2();
162 static int	workcmpf3();
163 static int	workcmpf4();
164 static int	randi = 3;	/* index for workcmpf5() */
165 static int	workcmpf5();
166 static int	workcmpf6();
167 #if _FFR_RHS
168 static int	workcmpf7();
169 #endif /* _FFR_RHS */
170 
171 #if RANDOMSHIFT
172 # define get_rand_mod(m)	((get_random() >> RANDOMSHIFT) % (m))
173 #else /* RANDOMSHIFT */
174 # define get_rand_mod(m)	(get_random() % (m))
175 #endif /* RANDOMSHIFT */
176 
177 /*
178 **  File system definition.
179 **	Used to keep track of how much free space is available
180 **	on a file system in which one or more queue directories reside.
181 */
182 
183 typedef struct filesys_shared	FILESYS;
184 
185 struct filesys_shared
186 {
187 	dev_t	fs_dev;		/* unique device id */
188 	long	fs_avail;	/* number of free blocks available */
189 	long	fs_blksize;	/* block size, in bytes */
190 };
191 
192 /* probably kept in shared memory */
193 static FILESYS	FileSys[MAXFILESYS];	/* queue file systems */
194 static const char *FSPath[MAXFILESYS];	/* pathnames for file systems */
195 
196 #if SM_CONF_SHM
197 
198 /*
199 **  Shared memory data
200 **
201 **  Current layout:
202 **	size -- size of shared memory segment
203 **	pid -- pid of owner, should be a unique id to avoid misinterpretations
204 **		by other processes.
205 **	tag -- should be a unique id to avoid misinterpretations by others.
206 **		idea: hash over configuration data that will be stored here.
207 **	NumFileSys -- number of file systems.
208 **	FileSys -- (arrary of) structure for used file systems.
209 **	RSATmpCnt -- counter for number of uses of ephemeral RSA key.
210 **	QShm -- (array of) structure for information about queue directories.
211 */
212 
213 /*
214 **  Queue data in shared memory
215 */
216 
217 typedef struct queue_shared	QUEUE_SHM_T;
218 
219 struct queue_shared
220 {
221 	int	qs_entries;	/* number of entries */
222 	/* XXX more to follow? */
223 };
224 
225 static void	*Pshm;		/* pointer to shared memory */
226 static FILESYS	*PtrFileSys;	/* pointer to queue file system array */
227 int		ShmId = SM_SHM_NO_ID;	/* shared memory id */
228 static QUEUE_SHM_T	*QShm;		/* pointer to shared queue data */
229 static size_t shms;
230 
231 # define SHM_OFF_PID(p)	(((char *) (p)) + sizeof(int))
232 # define SHM_OFF_TAG(p)	(((char *) (p)) + sizeof(pid_t) + sizeof(int))
233 # define SHM_OFF_HEAD	(sizeof(pid_t) + sizeof(int) * 2)
234 
235 /* how to access FileSys */
236 # define FILE_SYS(i)	(PtrFileSys[i])
237 
238 /* first entry is a tag, for now just the size */
239 # define OFF_FILE_SYS(p)	(((char *) (p)) + SHM_OFF_HEAD)
240 
241 /* offset for PNumFileSys */
242 # define OFF_NUM_FILE_SYS(p)	(((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys))
243 
244 /* offset for PRSATmpCnt */
245 # define OFF_RSA_TMP_CNT(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int))
246 int	*PRSATmpCnt;
247 
248 /* offset for queue_shm */
249 # define OFF_QUEUE_SHM(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2)
250 
251 # define QSHM_ENTRIES(i)	QShm[i].qs_entries
252 
253 /* basic size of shared memory segment */
254 # define SM_T_SIZE	(SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2)
255 
256 static unsigned int	hash_q __P((char *, unsigned int));
257 
258 /*
259 **  HASH_Q -- simple hash function
260 **
261 **	Parameters:
262 **		p -- string to hash.
263 **		h -- hash start value (from previous run).
264 **
265 **	Returns:
266 **		hash value.
267 */
268 
269 static unsigned int
270 hash_q(p, h)
271 	char *p;
272 	unsigned int h;
273 {
274 	int c, d;
275 
276 	while (*p != '\0')
277 	{
278 		d = *p++;
279 		c = d;
280 		c ^= c<<6;
281 		h += (c<<11) ^ (c>>1);
282 		h ^= (d<<14) + (d<<7) + (d<<4) + d;
283 	}
284 	return h;
285 }
286 
287 
288 #else /* SM_CONF_SHM */
289 # define FILE_SYS(i)	FileSys[i]
290 #endif /* SM_CONF_SHM */
291 
292 /* access to the various components of file system data */
293 #define FILE_SYS_NAME(i)	FSPath[i]
294 #define FILE_SYS_AVAIL(i)	FILE_SYS(i).fs_avail
295 #define FILE_SYS_BLKSIZE(i)	FILE_SYS(i).fs_blksize
296 #define FILE_SYS_DEV(i)	FILE_SYS(i).fs_dev
297 
298 
299 /*
300 **  Current qf file field assignments:
301 **
302 **	A	AUTH= parameter
303 **	B	body type
304 **	C	controlling user
305 **	D	data file name
306 **	d	data file directory name (added in 8.12)
307 **	E	error recipient
308 **	F	flag bits
309 **	G	free (was: queue delay algorithm if _FFR_QUEUEDELAY)
310 **	H	header
311 **	I	data file's inode number
312 **	K	time of last delivery attempt
313 **	L	Solaris Content-Length: header (obsolete)
314 **	M	message
315 **	N	number of delivery attempts
316 **	P	message priority
317 **	q	quarantine reason
318 **	Q	original recipient (ORCPT=)
319 **	r	final recipient (Final-Recipient: DSN field)
320 **	R	recipient
321 **	S	sender
322 **	T	init time
323 **	V	queue file version
324 **	X	free (was: character set if _FFR_SAVE_CHARSET)
325 **	Y	free (was: current delay if _FFR_QUEUEDELAY)
326 **	Z	original envelope id from ESMTP
327 **	!	deliver by (added in 8.12)
328 **	$	define macro
329 **	.	terminate file
330 */
331 
332 /*
333 **  QUEUEUP -- queue a message up for future transmission.
334 **
335 **	Parameters:
336 **		e -- the envelope to queue up.
337 **		announce -- if true, tell when you are queueing up.
338 **		msync -- if true, then fsync() if SuperSafe interactive mode.
339 **
340 **	Returns:
341 **		none.
342 **
343 **	Side Effects:
344 **		The current request is saved in a control file.
345 **		The queue file is left locked.
346 */
347 
348 void
349 queueup(e, announce, msync)
350 	register ENVELOPE *e;
351 	bool announce;
352 	bool msync;
353 {
354 	register SM_FILE_T *tfp;
355 	register HDR *h;
356 	register ADDRESS *q;
357 	int tfd = -1;
358 	int i;
359 	bool newid;
360 	register char *p;
361 	MAILER nullmailer;
362 	MCI mcibuf;
363 	char qf[MAXPATHLEN];
364 	char tf[MAXPATHLEN];
365 	char df[MAXPATHLEN];
366 	char buf[MAXLINE];
367 
368 	/*
369 	**  Create control file.
370 	*/
371 
372 #define OPEN_TF	do							\
373 		{							\
374 			MODE_T oldumask = 0;				\
375 									\
376 			if (bitset(S_IWGRP, QueueFileMode))		\
377 				oldumask = umask(002);			\
378 			tfd = open(tf, TF_OPEN_FLAGS, QueueFileMode);	\
379 			if (bitset(S_IWGRP, QueueFileMode))		\
380 				(void) umask(oldumask);			\
381 		} while (0)
382 
383 
384 	newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags);
385 	(void) sm_strlcpy(tf, queuename(e, NEWQFL_LETTER), sizeof(tf));
386 	tfp = e->e_lockfp;
387 	if (tfp == NULL && newid)
388 	{
389 		/*
390 		**  open qf file directly: this will give an error if the file
391 		**  already exists and hence prevent problems if a queue-id
392 		**  is reused (e.g., because the clock is set back).
393 		*/
394 
395 		(void) sm_strlcpy(tf, queuename(e, ANYQFL_LETTER), sizeof(tf));
396 		OPEN_TF;
397 		if (tfd < 0 ||
398 #if !SM_OPEN_EXLOCK
399 		    !lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB) ||
400 #endif /* !SM_OPEN_EXLOCK */
401 		    (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
402 					 (void *) &tfd, SM_IO_WRONLY,
403 					 NULL)) == NULL)
404 		{
405 			int save_errno = errno;
406 
407 			printopenfds(true);
408 			errno = save_errno;
409 			syserr("!queueup: cannot create queue file %s, euid=%d, fd=%d, fp=%p",
410 				tf, (int) geteuid(), tfd, tfp);
411 			/* NOTREACHED */
412 		}
413 		e->e_lockfp = tfp;
414 		upd_qs(e, 1, 0, "queueup");
415 	}
416 
417 	/* if newid, write the queue file directly (instead of temp file) */
418 	if (!newid)
419 	{
420 		/* get a locked tf file */
421 		for (i = 0; i < 128; i++)
422 		{
423 			if (tfd < 0)
424 			{
425 				OPEN_TF;
426 				if (tfd < 0)
427 				{
428 					if (errno != EEXIST)
429 						break;
430 					if (LogLevel > 0 && (i % 32) == 0)
431 						sm_syslog(LOG_ALERT, e->e_id,
432 							  "queueup: cannot create %s, euid=%d: %s",
433 							  tf, (int) geteuid(),
434 							  sm_errstring(errno));
435 				}
436 #if SM_OPEN_EXLOCK
437 				else
438 					break;
439 #endif /* SM_OPEN_EXLOCK */
440 			}
441 			if (tfd >= 0)
442 			{
443 #if SM_OPEN_EXLOCK
444 				/* file is locked by open() */
445 				break;
446 #else /* SM_OPEN_EXLOCK */
447 				if (lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB))
448 					break;
449 				else
450 #endif /* SM_OPEN_EXLOCK */
451 				if (LogLevel > 0 && (i % 32) == 0)
452 					sm_syslog(LOG_ALERT, e->e_id,
453 						  "queueup: cannot lock %s: %s",
454 						  tf, sm_errstring(errno));
455 				if ((i % 32) == 31)
456 				{
457 					(void) close(tfd);
458 					tfd = -1;
459 				}
460 			}
461 
462 			if ((i % 32) == 31)
463 			{
464 				/* save the old temp file away */
465 				(void) rename(tf, queuename(e, TEMPQF_LETTER));
466 			}
467 			else
468 				(void) sleep(i % 32);
469 		}
470 		if (tfd < 0 || (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
471 						 (void *) &tfd, SM_IO_WRONLY_B,
472 						 NULL)) == NULL)
473 		{
474 			int save_errno = errno;
475 
476 			printopenfds(true);
477 			errno = save_errno;
478 			syserr("!queueup: cannot create queue temp file %s, uid=%d",
479 				tf, (int) geteuid());
480 		}
481 	}
482 
483 	if (tTd(40, 1))
484 		sm_dprintf("\n>>>>> queueing %s/%s%s >>>>>\n",
485 			   qid_printqueue(e->e_qgrp, e->e_qdir),
486 			   queuename(e, ANYQFL_LETTER),
487 			   newid ? " (new id)" : "");
488 	if (tTd(40, 3))
489 	{
490 		sm_dprintf("  e_flags=");
491 		printenvflags(e);
492 	}
493 	if (tTd(40, 32))
494 	{
495 		sm_dprintf("  sendq=");
496 		printaddr(sm_debug_file(), e->e_sendqueue, true);
497 	}
498 	if (tTd(40, 9))
499 	{
500 		sm_dprintf("  tfp=");
501 		dumpfd(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL), true, false);
502 		sm_dprintf("  lockfp=");
503 		if (e->e_lockfp == NULL)
504 			sm_dprintf("NULL\n");
505 		else
506 			dumpfd(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL),
507 			       true, false);
508 	}
509 
510 	/*
511 	**  If there is no data file yet, create one.
512 	*/
513 
514 	(void) sm_strlcpy(df, queuename(e, DATAFL_LETTER), sizeof(df));
515 	if (bitset(EF_HAS_DF, e->e_flags))
516 	{
517 		if (e->e_dfp != NULL &&
518 		    SuperSafe != SAFE_REALLY &&
519 		    SuperSafe != SAFE_REALLY_POSTMILTER &&
520 		    sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
521 		    errno != EINVAL)
522 		{
523 			syserr("!queueup: cannot commit data file %s, uid=%d",
524 			       queuename(e, DATAFL_LETTER), (int) geteuid());
525 		}
526 		if (e->e_dfp != NULL &&
527 		    SuperSafe == SAFE_INTERACTIVE && msync)
528 		{
529 			if (tTd(40,32))
530 				sm_syslog(LOG_INFO, e->e_id,
531 					  "queueup: fsync(e->e_dfp)");
532 
533 			if (fsync(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD,
534 						NULL)) < 0)
535 			{
536 				if (newid)
537 					syserr("!552 Error writing data file %s",
538 					       df);
539 				else
540 					syserr("!452 Error writing data file %s",
541 					       df);
542 			}
543 		}
544 	}
545 	else
546 	{
547 		int dfd;
548 		MODE_T oldumask = 0;
549 		register SM_FILE_T *dfp = NULL;
550 		struct stat stbuf;
551 
552 		if (e->e_dfp != NULL &&
553 		    sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE))
554 			syserr("committing over bf file");
555 
556 		if (bitset(S_IWGRP, QueueFileMode))
557 			oldumask = umask(002);
558 		dfd = open(df, O_WRONLY|O_CREAT|O_TRUNC|QF_O_EXTRA,
559 			   QueueFileMode);
560 		if (bitset(S_IWGRP, QueueFileMode))
561 			(void) umask(oldumask);
562 		if (dfd < 0 || (dfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
563 						 (void *) &dfd, SM_IO_WRONLY_B,
564 						 NULL)) == NULL)
565 			syserr("!queueup: cannot create data temp file %s, uid=%d",
566 				df, (int) geteuid());
567 		if (fstat(dfd, &stbuf) < 0)
568 			e->e_dfino = -1;
569 		else
570 		{
571 			e->e_dfdev = stbuf.st_dev;
572 			e->e_dfino = ST_INODE(stbuf);
573 		}
574 		e->e_flags |= EF_HAS_DF;
575 		memset(&mcibuf, '\0', sizeof(mcibuf));
576 		mcibuf.mci_out = dfp;
577 		mcibuf.mci_mailer = FileMailer;
578 		(*e->e_putbody)(&mcibuf, e, NULL);
579 
580 		if (SuperSafe == SAFE_REALLY ||
581 		    SuperSafe == SAFE_REALLY_POSTMILTER ||
582 		    (SuperSafe == SAFE_INTERACTIVE && msync))
583 		{
584 			if (tTd(40,32))
585 				sm_syslog(LOG_INFO, e->e_id,
586 					  "queueup: fsync(dfp)");
587 
588 			if (fsync(sm_io_getinfo(dfp, SM_IO_WHAT_FD, NULL)) < 0)
589 			{
590 				if (newid)
591 					syserr("!552 Error writing data file %s",
592 					       df);
593 				else
594 					syserr("!452 Error writing data file %s",
595 					       df);
596 			}
597 		}
598 
599 		if (sm_io_close(dfp, SM_TIME_DEFAULT) < 0)
600 			syserr("!queueup: cannot save data temp file %s, uid=%d",
601 				df, (int) geteuid());
602 		e->e_putbody = putbody;
603 	}
604 
605 	/*
606 	**  Output future work requests.
607 	**	Priority and creation time should be first, since
608 	**	they are required by gatherq.
609 	*/
610 
611 	/* output queue version number (must be first!) */
612 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "V%d\n", QF_VERSION);
613 
614 	/* output creation time */
615 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "T%ld\n", (long) e->e_ctime);
616 
617 	/* output last delivery time */
618 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "K%ld\n", (long) e->e_dtime);
619 
620 	/* output number of delivery attempts */
621 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "N%d\n", e->e_ntries);
622 
623 	/* output message priority */
624 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "P%ld\n", e->e_msgpriority);
625 
626 	/*
627 	**  If data file is in a different directory than the queue file,
628 	**  output a "d" record naming the directory of the data file.
629 	*/
630 
631 	if (e->e_dfqgrp != e->e_qgrp)
632 	{
633 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "d%s\n",
634 			Queue[e->e_dfqgrp]->qg_qpaths[e->e_dfqdir].qp_name);
635 	}
636 
637 	/* output inode number of data file */
638 	/* XXX should probably include device major/minor too */
639 	if (e->e_dfino != -1)
640 	{
641 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "I%ld/%ld/%llu\n",
642 				     (long) major(e->e_dfdev),
643 				     (long) minor(e->e_dfdev),
644 				     (ULONGLONG_T) e->e_dfino);
645 	}
646 
647 	/* output body type */
648 	if (e->e_bodytype != NULL)
649 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "B%s\n",
650 				     denlstring(e->e_bodytype, true, false));
651 
652 	/* quarantine reason */
653 	if (e->e_quarmsg != NULL)
654 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "q%s\n",
655 				     denlstring(e->e_quarmsg, true, false));
656 
657 	/* message from envelope, if it exists */
658 	if (e->e_message != NULL)
659 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n",
660 				     denlstring(e->e_message, true, false));
661 
662 	/* send various flag bits through */
663 	p = buf;
664 	if (bitset(EF_WARNING, e->e_flags))
665 		*p++ = 'w';
666 	if (bitset(EF_RESPONSE, e->e_flags))
667 		*p++ = 'r';
668 	if (bitset(EF_HAS8BIT, e->e_flags))
669 		*p++ = '8';
670 	if (bitset(EF_DELETE_BCC, e->e_flags))
671 		*p++ = 'b';
672 	if (bitset(EF_RET_PARAM, e->e_flags))
673 		*p++ = 'd';
674 	if (bitset(EF_NO_BODY_RETN, e->e_flags))
675 		*p++ = 'n';
676 	if (bitset(EF_SPLIT, e->e_flags))
677 		*p++ = 's';
678 	*p++ = '\0';
679 	if (buf[0] != '\0')
680 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "F%s\n", buf);
681 
682 	/* save $={persistentMacros} macro values */
683 	queueup_macros(macid("{persistentMacros}"), tfp, e);
684 
685 	/* output name of sender */
686 	if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
687 		p = e->e_sender;
688 	else
689 		p = e->e_from.q_paddr;
690 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "S%s\n",
691 			     denlstring(p, true, false));
692 
693 	/* output ESMTP-supplied "original" information */
694 	if (e->e_envid != NULL)
695 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Z%s\n",
696 				     denlstring(e->e_envid, true, false));
697 
698 	/* output AUTH= parameter */
699 	if (e->e_auth_param != NULL)
700 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "A%s\n",
701 				     denlstring(e->e_auth_param, true, false));
702 	if (e->e_dlvr_flag != 0)
703 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "!%c %ld\n",
704 				     (char) e->e_dlvr_flag, e->e_deliver_by);
705 
706 	/* output list of recipient addresses */
707 	printctladdr(NULL, NULL);
708 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
709 	{
710 		if (!QS_IS_UNDELIVERED(q->q_state))
711 			continue;
712 
713 		/* message for this recipient, if it exists */
714 		if (q->q_message != NULL)
715 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n",
716 					     denlstring(q->q_message, true,
717 							false));
718 
719 		printctladdr(q, tfp);
720 		if (q->q_orcpt != NULL)
721 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Q%s\n",
722 					     denlstring(q->q_orcpt, true,
723 							false));
724 		if (q->q_finalrcpt != NULL)
725 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "r%s\n",
726 					     denlstring(q->q_finalrcpt, true,
727 							false));
728 		(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'R');
729 		if (bitset(QPRIMARY, q->q_flags))
730 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'P');
731 		if (bitset(QHASNOTIFY, q->q_flags))
732 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'N');
733 		if (bitset(QPINGONSUCCESS, q->q_flags))
734 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'S');
735 		if (bitset(QPINGONFAILURE, q->q_flags))
736 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'F');
737 		if (bitset(QPINGONDELAY, q->q_flags))
738 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'D');
739 		if (q->q_alias != NULL &&
740 		    bitset(QALIAS, q->q_alias->q_flags))
741 			(void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'A');
742 		(void) sm_io_putc(tfp, SM_TIME_DEFAULT, ':');
743 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s\n",
744 				     denlstring(q->q_paddr, true, false));
745 		if (announce)
746 		{
747 			char *tag = "queued";
748 
749 			if (e->e_quarmsg != NULL)
750 				tag = "quarantined";
751 
752 			e->e_to = q->q_paddr;
753 			message(tag);
754 			if (LogLevel > 8)
755 				logdelivery(q->q_mailer, NULL, q->q_status,
756 					    tag, NULL, (time_t) 0, e);
757 			e->e_to = NULL;
758 		}
759 		if (tTd(40, 1))
760 		{
761 			sm_dprintf("queueing ");
762 			printaddr(sm_debug_file(), q, false);
763 		}
764 	}
765 
766 	/*
767 	**  Output headers for this message.
768 	**	Expand macros completely here.  Queue run will deal with
769 	**	everything as absolute headers.
770 	**		All headers that must be relative to the recipient
771 	**		can be cracked later.
772 	**	We set up a "null mailer" -- i.e., a mailer that will have
773 	**	no effect on the addresses as they are output.
774 	*/
775 
776 	memset((char *) &nullmailer, '\0', sizeof(nullmailer));
777 	nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
778 			nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1;
779 	nullmailer.m_eol = "\n";
780 	memset(&mcibuf, '\0', sizeof(mcibuf));
781 	mcibuf.mci_mailer = &nullmailer;
782 	mcibuf.mci_out = tfp;
783 
784 	macdefine(&e->e_macro, A_PERM, 'g', "\201f");
785 	for (h = e->e_header; h != NULL; h = h->h_link)
786 	{
787 		if (h->h_value == NULL)
788 			continue;
789 
790 		/* don't output resent headers on non-resent messages */
791 		if (bitset(H_RESENT, h->h_flags) &&
792 		    !bitset(EF_RESENT, e->e_flags))
793 			continue;
794 
795 		/* expand macros; if null, don't output header at all */
796 		if (bitset(H_DEFAULT, h->h_flags))
797 		{
798 			(void) expand(h->h_value, buf, sizeof(buf), e);
799 			if (buf[0] == '\0')
800 				continue;
801 			if (buf[0] == ' ' && buf[1] == '\0')
802 				continue;
803 		}
804 
805 		/* output this header */
806 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "H?");
807 
808 		/* output conditional macro if present */
809 		if (h->h_macro != '\0')
810 		{
811 			if (bitset(0200, h->h_macro))
812 				(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT,
813 						     "${%s}",
814 						      macname(bitidx(h->h_macro)));
815 			else
816 				(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT,
817 						     "$%c", h->h_macro);
818 		}
819 		else if (!bitzerop(h->h_mflags) &&
820 			 bitset(H_CHECK|H_ACHECK, h->h_flags))
821 		{
822 			int j;
823 
824 			/* if conditional, output the set of conditions */
825 			for (j = '\0'; j <= '\177'; j++)
826 				if (bitnset(j, h->h_mflags))
827 					(void) sm_io_putc(tfp, SM_TIME_DEFAULT,
828 							  j);
829 		}
830 		(void) sm_io_putc(tfp, SM_TIME_DEFAULT, '?');
831 
832 		/* output the header: expand macros, convert addresses */
833 		if (bitset(H_DEFAULT, h->h_flags) &&
834 		    !bitset(H_BINDLATE, h->h_flags))
835 		{
836 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s:%s\n",
837 					     h->h_field,
838 					     denlstring(buf, false, true));
839 		}
840 		else if (bitset(H_FROM|H_RCPT, h->h_flags) &&
841 			 !bitset(H_BINDLATE, h->h_flags))
842 		{
843 			bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
844 			SM_FILE_T *savetrace = TrafficLogFile;
845 
846 			TrafficLogFile = NULL;
847 
848 			if (bitset(H_FROM, h->h_flags))
849 				oldstyle = false;
850 			commaize(h, h->h_value, oldstyle, &mcibuf, e,
851 				 PXLF_HEADER);
852 
853 			TrafficLogFile = savetrace;
854 		}
855 		else
856 		{
857 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s:%s\n",
858 					     h->h_field,
859 					     denlstring(h->h_value, false,
860 							true));
861 		}
862 	}
863 
864 	/*
865 	**  Clean up.
866 	**
867 	**	Write a terminator record -- this is to prevent
868 	**	scurrilous crackers from appending any data.
869 	*/
870 
871 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ".\n");
872 
873 	if (sm_io_flush(tfp, SM_TIME_DEFAULT) != 0 ||
874 	    ((SuperSafe == SAFE_REALLY ||
875 	      SuperSafe == SAFE_REALLY_POSTMILTER ||
876 	      (SuperSafe == SAFE_INTERACTIVE && msync)) &&
877 	     fsync(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL)) < 0) ||
878 	    sm_io_error(tfp))
879 	{
880 		if (newid)
881 			syserr("!552 Error writing control file %s", tf);
882 		else
883 			syserr("!452 Error writing control file %s", tf);
884 	}
885 
886 	if (!newid)
887 	{
888 		char new = queue_letter(e, ANYQFL_LETTER);
889 
890 		/* rename (locked) tf to be (locked) [qh]f */
891 		(void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER),
892 				  sizeof(qf));
893 		if (rename(tf, qf) < 0)
894 			syserr("cannot rename(%s, %s), uid=%d",
895 				tf, qf, (int) geteuid());
896 		else
897 		{
898 			/*
899 			**  Check if type has changed and only
900 			**  remove the old item if the rename above
901 			**  succeeded.
902 			*/
903 
904 			if (e->e_qfletter != '\0' &&
905 			    e->e_qfletter != new)
906 			{
907 				if (tTd(40, 5))
908 				{
909 					sm_dprintf("type changed from %c to %c\n",
910 						   e->e_qfletter, new);
911 				}
912 
913 				if (unlink(queuename(e, e->e_qfletter)) < 0)
914 				{
915 					/* XXX: something more drastic? */
916 					if (LogLevel > 0)
917 						sm_syslog(LOG_ERR, e->e_id,
918 							  "queueup: unlink(%s) failed: %s",
919 							  queuename(e, e->e_qfletter),
920 							  sm_errstring(errno));
921 				}
922 			}
923 		}
924 		e->e_qfletter = new;
925 
926 		/*
927 		**  fsync() after renaming to make sure metadata is
928 		**  written to disk on filesystems in which renames are
929 		**  not guaranteed.
930 		*/
931 
932 		if (SuperSafe != SAFE_NO)
933 		{
934 			/* for softupdates */
935 			if (tfd >= 0 && fsync(tfd) < 0)
936 			{
937 				syserr("!queueup: cannot fsync queue temp file %s",
938 				       tf);
939 			}
940 			SYNC_DIR(qf, true);
941 		}
942 
943 		/* close and unlock old (locked) queue file */
944 		if (e->e_lockfp != NULL)
945 			(void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
946 		e->e_lockfp = tfp;
947 
948 		/* save log info */
949 		if (LogLevel > 79)
950 			sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", qf);
951 	}
952 	else
953 	{
954 		/* save log info */
955 		if (LogLevel > 79)
956 			sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", tf);
957 
958 		e->e_qfletter = queue_letter(e, ANYQFL_LETTER);
959 	}
960 
961 	errno = 0;
962 	e->e_flags |= EF_INQUEUE;
963 
964 	if (tTd(40, 1))
965 		sm_dprintf("<<<<< done queueing %s <<<<<\n\n", e->e_id);
966 	return;
967 }
968 
969 /*
970 **  PRINTCTLADDR -- print control address to file.
971 **
972 **	Parameters:
973 **		a -- address.
974 **		tfp -- file pointer.
975 **
976 **	Returns:
977 **		none.
978 **
979 **	Side Effects:
980 **		The control address (if changed) is printed to the file.
981 **		The last control address and uid are saved.
982 */
983 
984 static void
985 printctladdr(a, tfp)
986 	register ADDRESS *a;
987 	SM_FILE_T *tfp;
988 {
989 	char *user;
990 	register ADDRESS *q;
991 	uid_t uid;
992 	gid_t gid;
993 	static ADDRESS *lastctladdr = NULL;
994 	static uid_t lastuid;
995 
996 	/* initialization */
997 	if (a == NULL || a->q_alias == NULL || tfp == NULL)
998 	{
999 		if (lastctladdr != NULL && tfp != NULL)
1000 			(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C\n");
1001 		lastctladdr = NULL;
1002 		lastuid = 0;
1003 		return;
1004 	}
1005 
1006 	/* find the active uid */
1007 	q = getctladdr(a);
1008 	if (q == NULL)
1009 	{
1010 		user = NULL;
1011 		uid = 0;
1012 		gid = 0;
1013 	}
1014 	else
1015 	{
1016 		user = q->q_ruser != NULL ? q->q_ruser : q->q_user;
1017 		uid = q->q_uid;
1018 		gid = q->q_gid;
1019 	}
1020 	a = a->q_alias;
1021 
1022 	/* check to see if this is the same as last time */
1023 	if (lastctladdr != NULL && uid == lastuid &&
1024 	    strcmp(lastctladdr->q_paddr, a->q_paddr) == 0)
1025 		return;
1026 	lastuid = uid;
1027 	lastctladdr = a;
1028 
1029 	if (uid == 0 || user == NULL || user[0] == '\0')
1030 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C");
1031 	else
1032 		(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C%s:%ld:%ld",
1033 				     denlstring(user, true, false), (long) uid,
1034 				     (long) gid);
1035 	(void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ":%s\n",
1036 			     denlstring(a->q_paddr, true, false));
1037 }
1038 
1039 /*
1040 **  RUNNERS_SIGTERM -- propagate a SIGTERM to queue runner process
1041 **
1042 **	This propagates the signal to the child processes that are queue
1043 **	runners. This is for a queue runner "cleanup". After all of the
1044 **	child queue runner processes are signaled (it should be SIGTERM
1045 **	being the sig) then the old signal handler (Oldsh) is called
1046 **	to handle any cleanup set for this process (provided it is not
1047 **	SIG_DFL or SIG_IGN). The signal may not be handled immediately
1048 **	if the BlockOldsh flag is set. If the current process doesn't
1049 **	have a parent then handle the signal immediately, regardless of
1050 **	BlockOldsh.
1051 **
1052 **	Parameters:
1053 **		sig -- the signal number being sent
1054 **
1055 **	Returns:
1056 **		none.
1057 **
1058 **	Side Effects:
1059 **		Sets the NoMoreRunners boolean to true to stop more runners
1060 **		from being started in runqueue().
1061 **
1062 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
1063 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1064 **		DOING.
1065 */
1066 
1067 static bool		volatile NoMoreRunners = false;
1068 static sigfunc_t	Oldsh_term = SIG_DFL;
1069 static sigfunc_t	Oldsh_hup = SIG_DFL;
1070 static sigfunc_t	volatile Oldsh = SIG_DFL;
1071 static bool		BlockOldsh = false;
1072 static int		volatile Oldsig = 0;
1073 static SIGFUNC_DECL	runners_sigterm __P((int));
1074 static SIGFUNC_DECL	runners_sighup __P((int));
1075 
1076 static SIGFUNC_DECL
1077 runners_sigterm(sig)
1078 	int sig;
1079 {
1080 	int save_errno = errno;
1081 
1082 	FIX_SYSV_SIGNAL(sig, runners_sigterm);
1083 	errno = save_errno;
1084 	CHECK_CRITICAL(sig);
1085 	NoMoreRunners = true;
1086 	Oldsh = Oldsh_term;
1087 	Oldsig = sig;
1088 	proc_list_signal(PROC_QUEUE, sig);
1089 
1090 	if (!BlockOldsh || getppid() <= 1)
1091 	{
1092 		/* Check that a valid 'old signal handler' is callable */
1093 		if (Oldsh_term != SIG_DFL && Oldsh_term != SIG_IGN &&
1094 		    Oldsh_term != runners_sigterm)
1095 			(*Oldsh_term)(sig);
1096 	}
1097 	errno = save_errno;
1098 	return SIGFUNC_RETURN;
1099 }
1100 /*
1101 **  RUNNERS_SIGHUP -- propagate a SIGHUP to queue runner process
1102 **
1103 **	This propagates the signal to the child processes that are queue
1104 **	runners. This is for a queue runner "cleanup". After all of the
1105 **	child queue runner processes are signaled (it should be SIGHUP
1106 **	being the sig) then the old signal handler (Oldsh) is called to
1107 **	handle any cleanup set for this process (provided it is not SIG_DFL
1108 **	or SIG_IGN). The signal may not be handled immediately if the
1109 **	BlockOldsh flag is set. If the current process doesn't have
1110 **	a parent then handle the signal immediately, regardless of
1111 **	BlockOldsh.
1112 **
1113 **	Parameters:
1114 **		sig -- the signal number being sent
1115 **
1116 **	Returns:
1117 **		none.
1118 **
1119 **	Side Effects:
1120 **		Sets the NoMoreRunners boolean to true to stop more runners
1121 **		from being started in runqueue().
1122 **
1123 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
1124 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1125 **		DOING.
1126 */
1127 
1128 static SIGFUNC_DECL
1129 runners_sighup(sig)
1130 	int sig;
1131 {
1132 	int save_errno = errno;
1133 
1134 	FIX_SYSV_SIGNAL(sig, runners_sighup);
1135 	errno = save_errno;
1136 	CHECK_CRITICAL(sig);
1137 	NoMoreRunners = true;
1138 	Oldsh = Oldsh_hup;
1139 	Oldsig = sig;
1140 	proc_list_signal(PROC_QUEUE, sig);
1141 
1142 	if (!BlockOldsh || getppid() <= 1)
1143 	{
1144 		/* Check that a valid 'old signal handler' is callable */
1145 		if (Oldsh_hup != SIG_DFL && Oldsh_hup != SIG_IGN &&
1146 		    Oldsh_hup != runners_sighup)
1147 			(*Oldsh_hup)(sig);
1148 	}
1149 	errno = save_errno;
1150 	return SIGFUNC_RETURN;
1151 }
1152 /*
1153 **  MARK_WORK_GROUP_RESTART -- mark a work group as needing a restart
1154 **
1155 **  Sets a workgroup for restarting.
1156 **
1157 **	Parameters:
1158 **		wgrp -- the work group id to restart.
1159 **		reason -- why (signal?), -1 to turn off restart
1160 **
1161 **	Returns:
1162 **		none.
1163 **
1164 **	Side effects:
1165 **		May set global RestartWorkGroup to true.
1166 **
1167 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
1168 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1169 **		DOING.
1170 */
1171 
1172 void
1173 mark_work_group_restart(wgrp, reason)
1174 	int wgrp;
1175 	int reason;
1176 {
1177 	if (wgrp < 0 || wgrp > NumWorkGroups)
1178 		return;
1179 
1180 	WorkGrp[wgrp].wg_restart = reason;
1181 	if (reason >= 0)
1182 		RestartWorkGroup = true;
1183 }
1184 /*
1185 **  RESTART_MARKED_WORK_GROUPS -- restart work groups marked as needing restart
1186 **
1187 **  Restart any workgroup marked as needing a restart provided more
1188 **  runners are allowed.
1189 **
1190 **	Parameters:
1191 **		none.
1192 **
1193 **	Returns:
1194 **		none.
1195 **
1196 **	Side effects:
1197 **		Sets global RestartWorkGroup to false.
1198 */
1199 
1200 void
1201 restart_marked_work_groups()
1202 {
1203 	int i;
1204 	int wasblocked;
1205 
1206 	if (NoMoreRunners)
1207 		return;
1208 
1209 	/* Block SIGCHLD so reapchild() doesn't mess with us */
1210 	wasblocked = sm_blocksignal(SIGCHLD);
1211 
1212 	for (i = 0; i < NumWorkGroups; i++)
1213 	{
1214 		if (WorkGrp[i].wg_restart >= 0)
1215 		{
1216 			if (LogLevel > 8)
1217 				sm_syslog(LOG_ERR, NOQID,
1218 					  "restart queue runner=%d due to signal 0x%x",
1219 					  i, WorkGrp[i].wg_restart);
1220 			restart_work_group(i);
1221 		}
1222 	}
1223 	RestartWorkGroup = false;
1224 
1225 	if (wasblocked == 0)
1226 		(void) sm_releasesignal(SIGCHLD);
1227 }
1228 /*
1229 **  RESTART_WORK_GROUP -- restart a specific work group
1230 **
1231 **  Restart a specific workgroup provided more runners are allowed.
1232 **  If the requested work group has been restarted too many times log
1233 **  this and refuse to restart.
1234 **
1235 **	Parameters:
1236 **		wgrp -- the work group id to restart
1237 **
1238 **	Returns:
1239 **		none.
1240 **
1241 **	Side Effects:
1242 **		starts another process doing the work of wgrp
1243 */
1244 
1245 #define MAX_PERSIST_RESTART	10	/* max allowed number of restarts */
1246 
1247 static void
1248 restart_work_group(wgrp)
1249 	int wgrp;
1250 {
1251 	if (NoMoreRunners ||
1252 	    wgrp < 0 || wgrp > NumWorkGroups)
1253 		return;
1254 
1255 	WorkGrp[wgrp].wg_restart = -1;
1256 	if (WorkGrp[wgrp].wg_restartcnt < MAX_PERSIST_RESTART)
1257 	{
1258 		/* avoid overflow; increment here */
1259 		WorkGrp[wgrp].wg_restartcnt++;
1260 		(void) run_work_group(wgrp, RWG_FORK|RWG_PERSISTENT|RWG_RUNALL);
1261 	}
1262 	else
1263 	{
1264 		sm_syslog(LOG_ERR, NOQID,
1265 			  "ERROR: persistent queue runner=%d restarted too many times, queue runner lost",
1266 			  wgrp);
1267 	}
1268 }
1269 /*
1270 **  SCHEDULE_QUEUE_RUNS -- schedule the next queue run for a work group.
1271 **
1272 **	Parameters:
1273 **		runall -- schedule even if individual bit is not set.
1274 **		wgrp -- the work group id to schedule.
1275 **		didit -- the queue run was performed for this work group.
1276 **
1277 **	Returns:
1278 **		nothing
1279 */
1280 
1281 #define INCR_MOD(v, m)	if (++v >= m)	\
1282 				v = 0;	\
1283 			else
1284 
1285 static void
1286 schedule_queue_runs(runall, wgrp, didit)
1287 	bool runall;
1288 	int wgrp;
1289 	bool didit;
1290 {
1291 	int qgrp, cgrp, endgrp;
1292 #if _FFR_QUEUE_SCHED_DBG
1293 	time_t lastsched;
1294 	bool sched;
1295 #endif /* _FFR_QUEUE_SCHED_DBG */
1296 	time_t now;
1297 	time_t minqintvl;
1298 
1299 	/*
1300 	**  This is a bit ugly since we have to duplicate the
1301 	**  code that "walks" through a work queue group.
1302 	*/
1303 
1304 	now = curtime();
1305 	minqintvl = 0;
1306 	cgrp = endgrp = WorkGrp[wgrp].wg_curqgrp;
1307 	do
1308 	{
1309 		time_t qintvl;
1310 
1311 #if _FFR_QUEUE_SCHED_DBG
1312 		lastsched = 0;
1313 		sched = false;
1314 #endif /* _FFR_QUEUE_SCHED_DBG */
1315 		qgrp = WorkGrp[wgrp].wg_qgs[cgrp]->qg_index;
1316 		if (Queue[qgrp]->qg_queueintvl > 0)
1317 			qintvl = Queue[qgrp]->qg_queueintvl;
1318 		else if (QueueIntvl > 0)
1319 			qintvl = QueueIntvl;
1320 		else
1321 			qintvl = (time_t) 0;
1322 #if _FFR_QUEUE_SCHED_DBG
1323 		lastsched = Queue[qgrp]->qg_nextrun;
1324 #endif /* _FFR_QUEUE_SCHED_DBG */
1325 		if ((runall || Queue[qgrp]->qg_nextrun <= now) && qintvl > 0)
1326 		{
1327 #if _FFR_QUEUE_SCHED_DBG
1328 			sched = true;
1329 #endif /* _FFR_QUEUE_SCHED_DBG */
1330 			if (minqintvl == 0 || qintvl < minqintvl)
1331 				minqintvl = qintvl;
1332 
1333 			/*
1334 			**  Only set a new time if a queue run was performed
1335 			**  for this queue group.  If the queue was not run,
1336 			**  we could starve it by setting a new time on each
1337 			**  call.
1338 			*/
1339 
1340 			if (didit)
1341 				Queue[qgrp]->qg_nextrun += qintvl;
1342 		}
1343 #if _FFR_QUEUE_SCHED_DBG
1344 		if (tTd(69, 10))
1345 			sm_syslog(LOG_INFO, NOQID,
1346 				"sqr: wgrp=%d, cgrp=%d, qgrp=%d, intvl=%ld, QI=%ld, runall=%d, lastrun=%ld, nextrun=%ld, sched=%d",
1347 				wgrp, cgrp, qgrp, Queue[qgrp]->qg_queueintvl,
1348 				QueueIntvl, runall, lastsched,
1349 				Queue[qgrp]->qg_nextrun, sched);
1350 #endif /* _FFR_QUEUE_SCHED_DBG */
1351 		INCR_MOD(cgrp, WorkGrp[wgrp].wg_numqgrp);
1352 	} while (endgrp != cgrp);
1353 	if (minqintvl > 0)
1354 		(void) sm_setevent(minqintvl, runqueueevent, 0);
1355 }
1356 
1357 #if _FFR_QUEUE_RUN_PARANOIA
1358 /*
1359 **  CHECKQUEUERUNNER -- check whether a queue group hasn't been run.
1360 **
1361 **	Use this if events may get lost and hence queue runners may not
1362 **	be started and mail will pile up in a queue.
1363 **
1364 **	Parameters:
1365 **		none.
1366 **
1367 **	Returns:
1368 **		true if a queue run is necessary.
1369 **
1370 **	Side Effects:
1371 **		may schedule a queue run.
1372 */
1373 
1374 bool
1375 checkqueuerunner()
1376 {
1377 	int qgrp;
1378 	time_t now, minqintvl;
1379 
1380 	now = curtime();
1381 	minqintvl = 0;
1382 	for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++)
1383 	{
1384 		time_t qintvl;
1385 
1386 		if (Queue[qgrp]->qg_queueintvl > 0)
1387 			qintvl = Queue[qgrp]->qg_queueintvl;
1388 		else if (QueueIntvl > 0)
1389 			qintvl = QueueIntvl;
1390 		else
1391 			qintvl = (time_t) 0;
1392 		if (Queue[qgrp]->qg_nextrun <= now - qintvl)
1393 		{
1394 			if (minqintvl == 0 || qintvl < minqintvl)
1395 				minqintvl = qintvl;
1396 			if (LogLevel > 1)
1397 				sm_syslog(LOG_WARNING, NOQID,
1398 					"checkqueuerunner: queue %d should have been run at %s, queue interval %ld",
1399 					qgrp,
1400 					arpadate(ctime(&Queue[qgrp]->qg_nextrun)),
1401 					qintvl);
1402 		}
1403 	}
1404 	if (minqintvl > 0)
1405 	{
1406 		(void) sm_setevent(minqintvl, runqueueevent, 0);
1407 		return true;
1408 	}
1409 	return false;
1410 }
1411 #endif /* _FFR_QUEUE_RUN_PARANOIA */
1412 
1413 /*
1414 **  RUNQUEUE -- run the jobs in the queue.
1415 **
1416 **	Gets the stuff out of the queue in some presumably logical
1417 **	order and processes them.
1418 **
1419 **	Parameters:
1420 **		forkflag -- true if the queue scanning should be done in
1421 **			a child process.  We double-fork so it is not our
1422 **			child and we don't have to clean up after it.
1423 **			false can be ignored if we have multiple queues.
1424 **		verbose -- if true, print out status information.
1425 **		persistent -- persistent queue runner?
1426 **		runall -- run all groups or only a subset (DoQueueRun)?
1427 **
1428 **	Returns:
1429 **		true if the queue run successfully began.
1430 **
1431 **	Side Effects:
1432 **		runs things in the mail queue using run_work_group().
1433 **		maybe schedules next queue run.
1434 */
1435 
1436 static ENVELOPE	QueueEnvelope;		/* the queue run envelope */
1437 static time_t	LastQueueTime = 0;	/* last time a queue ID assigned */
1438 static pid_t	LastQueuePid = -1;	/* last PID which had a queue ID */
1439 
1440 /* values for qp_supdirs */
1441 #define QP_NOSUB	0x0000	/* No subdirectories */
1442 #define QP_SUBDF	0x0001	/* "df" subdirectory */
1443 #define QP_SUBQF	0x0002	/* "qf" subdirectory */
1444 #define QP_SUBXF	0x0004	/* "xf" subdirectory */
1445 
1446 bool
1447 runqueue(forkflag, verbose, persistent, runall)
1448 	bool forkflag;
1449 	bool verbose;
1450 	bool persistent;
1451 	bool runall;
1452 {
1453 	int i;
1454 	bool ret = true;
1455 	static int curnum = 0;
1456 	sigfunc_t cursh;
1457 #if SM_HEAP_CHECK
1458 	SM_NONVOLATILE int oldgroup = 0;
1459 
1460 	if (sm_debug_active(&DebugLeakQ, 1))
1461 	{
1462 		oldgroup = sm_heap_group();
1463 		sm_heap_newgroup();
1464 		sm_dprintf("runqueue() heap group #%d\n", sm_heap_group());
1465 	}
1466 #endif /* SM_HEAP_CHECK */
1467 
1468 	/* queue run has been started, don't do any more this time */
1469 	DoQueueRun = false;
1470 
1471 	/* more than one queue or more than one directory per queue */
1472 	if (!forkflag && !verbose &&
1473 	    (WorkGrp[0].wg_qgs[0]->qg_numqueues > 1 || NumWorkGroups > 1 ||
1474 	     WorkGrp[0].wg_numqgrp > 1))
1475 		forkflag = true;
1476 
1477 	/*
1478 	**  For controlling queue runners via signals sent to this process.
1479 	**  Oldsh* will get called too by runners_sig* (if it is not SIG_IGN
1480 	**  or SIG_DFL) to preserve cleanup behavior. Now that this process
1481 	**  will have children (and perhaps grandchildren) this handler will
1482 	**  be left in place. This is because this process, once it has
1483 	**  finished spinning off queue runners, may go back to doing something
1484 	**  else (like being a daemon). And we still want on a SIG{TERM,HUP} to
1485 	**  clean up the child queue runners. Only install 'runners_sig*' once
1486 	**  else we'll get stuck looping forever.
1487 	*/
1488 
1489 	cursh = sm_signal(SIGTERM, runners_sigterm);
1490 	if (cursh != runners_sigterm)
1491 		Oldsh_term = cursh;
1492 	cursh = sm_signal(SIGHUP, runners_sighup);
1493 	if (cursh != runners_sighup)
1494 		Oldsh_hup = cursh;
1495 
1496 	for (i = 0; i < NumWorkGroups && !NoMoreRunners; i++)
1497 	{
1498 		int rwgflags = RWG_NONE;
1499 
1500 		/*
1501 		**  If MaxQueueChildren active then test whether the start
1502 		**  of the next queue group's additional queue runners (maximum)
1503 		**  will result in MaxQueueChildren being exceeded.
1504 		**
1505 		**  Note: do not use continue; even though another workgroup
1506 		**	may have fewer queue runners, this would be "unfair",
1507 		**	i.e., this work group might "starve" then.
1508 		*/
1509 
1510 #if _FFR_QUEUE_SCHED_DBG
1511 		if (tTd(69, 10))
1512 			sm_syslog(LOG_INFO, NOQID,
1513 				"rq: curnum=%d, MaxQueueChildren=%d, CurRunners=%d, WorkGrp[curnum].wg_maxact=%d",
1514 				curnum, MaxQueueChildren, CurRunners,
1515 				WorkGrp[curnum].wg_maxact);
1516 #endif /* _FFR_QUEUE_SCHED_DBG */
1517 		if (MaxQueueChildren > 0 &&
1518 		    CurRunners + WorkGrp[curnum].wg_maxact > MaxQueueChildren)
1519 			break;
1520 
1521 		/*
1522 		**  Pick up where we left off (curnum), in case we
1523 		**  used up all the children last time without finishing.
1524 		**  This give a round-robin fairness to queue runs.
1525 		**
1526 		**  Increment CurRunners before calling run_work_group()
1527 		**  to avoid a "race condition" with proc_list_drop() which
1528 		**  decrements CurRunners if the queue runners terminate.
1529 		**  Notice: CurRunners is an upper limit, in some cases
1530 		**  (too few jobs in the queue) this value is larger than
1531 		**  the actual number of queue runners. The discrepancy can
1532 		**  increase if some queue runners "hang" for a long time.
1533 		*/
1534 
1535 		CurRunners += WorkGrp[curnum].wg_maxact;
1536 		if (forkflag)
1537 			rwgflags |= RWG_FORK;
1538 		if (verbose)
1539 			rwgflags |= RWG_VERBOSE;
1540 		if (persistent)
1541 			rwgflags |= RWG_PERSISTENT;
1542 		if (runall)
1543 			rwgflags |= RWG_RUNALL;
1544 		ret = run_work_group(curnum, rwgflags);
1545 
1546 		/*
1547 		**  Failure means a message was printed for ETRN
1548 		**  and subsequent queues are likely to fail as well.
1549 		**  Decrement CurRunners in that case because
1550 		**  none have been started.
1551 		*/
1552 
1553 		if (!ret)
1554 		{
1555 			CurRunners -= WorkGrp[curnum].wg_maxact;
1556 			break;
1557 		}
1558 
1559 		if (!persistent)
1560 			schedule_queue_runs(runall, curnum, true);
1561 		INCR_MOD(curnum, NumWorkGroups);
1562 	}
1563 
1564 	/* schedule left over queue runs */
1565 	if (i < NumWorkGroups && !NoMoreRunners && !persistent)
1566 	{
1567 		int h;
1568 
1569 		for (h = curnum; i < NumWorkGroups; i++)
1570 		{
1571 			schedule_queue_runs(runall, h, false);
1572 			INCR_MOD(h, NumWorkGroups);
1573 		}
1574 	}
1575 
1576 
1577 #if SM_HEAP_CHECK
1578 	if (sm_debug_active(&DebugLeakQ, 1))
1579 		sm_heap_setgroup(oldgroup);
1580 #endif /* SM_HEAP_CHECK */
1581 	return ret;
1582 }
1583 
1584 #if _FFR_SKIP_DOMAINS
1585 /*
1586 **  SKIP_DOMAINS -- Skip 'skip' number of domains in the WorkQ.
1587 **
1588 **  Added by Stephen Frost <sfrost@snowman.net> to support
1589 **  having each runner process every N'th domain instead of
1590 **  every N'th message.
1591 **
1592 **	Parameters:
1593 **		skip -- number of domains in WorkQ to skip.
1594 **
1595 **	Returns:
1596 **		total number of messages skipped.
1597 **
1598 **	Side Effects:
1599 **		may change WorkQ
1600 */
1601 
1602 static int
1603 skip_domains(skip)
1604 	int skip;
1605 {
1606 	int n, seqjump;
1607 
1608 	for (n = 0, seqjump = 0; n < skip && WorkQ != NULL; seqjump++)
1609 	{
1610 		if (WorkQ->w_next != NULL)
1611 		{
1612 			if (WorkQ->w_host != NULL &&
1613 			    WorkQ->w_next->w_host != NULL)
1614 			{
1615 				if (sm_strcasecmp(WorkQ->w_host,
1616 						WorkQ->w_next->w_host) != 0)
1617 					n++;
1618 			}
1619 			else
1620 			{
1621 				if ((WorkQ->w_host != NULL &&
1622 				     WorkQ->w_next->w_host == NULL) ||
1623 				    (WorkQ->w_host == NULL &&
1624 				     WorkQ->w_next->w_host != NULL))
1625 					     n++;
1626 			}
1627 		}
1628 		WorkQ = WorkQ->w_next;
1629 	}
1630 	return seqjump;
1631 }
1632 #endif /* _FFR_SKIP_DOMAINS */
1633 
1634 /*
1635 **  RUNNER_WORK -- have a queue runner do its work
1636 **
1637 **  Have a queue runner do its work a list of entries.
1638 **  When work isn't directly being done then this process can take a signal
1639 **  and terminate immediately (in a clean fashion of course).
1640 **  When work is directly being done, it's not to be interrupted
1641 **  immediately: the work should be allowed to finish at a clean point
1642 **  before termination (in a clean fashion of course).
1643 **
1644 **	Parameters:
1645 **		e -- envelope.
1646 **		sequenceno -- 'th process to run WorkQ.
1647 **		didfork -- did the calling process fork()?
1648 **		skip -- process only each skip'th item.
1649 **		njobs -- number of jobs in WorkQ.
1650 **
1651 **	Returns:
1652 **		none.
1653 **
1654 **	Side Effects:
1655 **		runs things in the mail queue.
1656 */
1657 
1658 static void
1659 runner_work(e, sequenceno, didfork, skip, njobs)
1660 	register ENVELOPE *e;
1661 	int sequenceno;
1662 	bool didfork;
1663 	int skip;
1664 	int njobs;
1665 {
1666 	int n, seqjump;
1667 	WORK *w;
1668 	time_t now;
1669 
1670 	SM_GET_LA(now);
1671 
1672 	/*
1673 	**  Here we temporarily block the second calling of the handlers.
1674 	**  This allows us to handle the signal without terminating in the
1675 	**  middle of direct work. If a signal does come, the test for
1676 	**  NoMoreRunners will find it.
1677 	*/
1678 
1679 	BlockOldsh = true;
1680 	seqjump = skip;
1681 
1682 	/* process them once at a time */
1683 	while (WorkQ != NULL)
1684 	{
1685 #if SM_HEAP_CHECK
1686 		SM_NONVOLATILE int oldgroup = 0;
1687 
1688 		if (sm_debug_active(&DebugLeakQ, 1))
1689 		{
1690 			oldgroup = sm_heap_group();
1691 			sm_heap_newgroup();
1692 			sm_dprintf("run_queue_group() heap group #%d\n",
1693 				sm_heap_group());
1694 		}
1695 #endif /* SM_HEAP_CHECK */
1696 
1697 		/* do no more work */
1698 		if (NoMoreRunners)
1699 		{
1700 			/* Check that a valid signal handler is callable */
1701 			if (Oldsh != SIG_DFL && Oldsh != SIG_IGN &&
1702 			    Oldsh != runners_sighup &&
1703 			    Oldsh != runners_sigterm)
1704 				(*Oldsh)(Oldsig);
1705 			break;
1706 		}
1707 
1708 		w = WorkQ; /* assign current work item */
1709 
1710 		/*
1711 		**  Set the head of the WorkQ to the next work item.
1712 		**  It is set 'skip' ahead (the number of parallel queue
1713 		**  runners working on WorkQ together) since each runner
1714 		**  works on every 'skip'th (N-th) item.
1715 #if _FFR_SKIP_DOMAINS
1716 		**  In the case of the BYHOST Queue Sort Order, the 'item'
1717 		**  is a domain, so we work on every 'skip'th (N-th) domain.
1718 #endif * _FFR_SKIP_DOMAINS *
1719 		*/
1720 
1721 #if _FFR_SKIP_DOMAINS
1722 		if (QueueSortOrder == QSO_BYHOST)
1723 		{
1724 			seqjump = 1;
1725 			if (WorkQ->w_next != NULL)
1726 			{
1727 				if (WorkQ->w_host != NULL &&
1728 				    WorkQ->w_next->w_host != NULL)
1729 				{
1730 					if (sm_strcasecmp(WorkQ->w_host,
1731 							WorkQ->w_next->w_host)
1732 								!= 0)
1733 						seqjump = skip_domains(skip);
1734 					else
1735 						WorkQ = WorkQ->w_next;
1736 				}
1737 				else
1738 				{
1739 					if ((WorkQ->w_host != NULL &&
1740 					     WorkQ->w_next->w_host == NULL) ||
1741 					    (WorkQ->w_host == NULL &&
1742 					     WorkQ->w_next->w_host != NULL))
1743 						seqjump = skip_domains(skip);
1744 					else
1745 						WorkQ = WorkQ->w_next;
1746 				}
1747 			}
1748 			else
1749 				WorkQ = WorkQ->w_next;
1750 		}
1751 		else
1752 #endif /* _FFR_SKIP_DOMAINS */
1753 		{
1754 			for (n = 0; n < skip && WorkQ != NULL; n++)
1755 				WorkQ = WorkQ->w_next;
1756 		}
1757 
1758 		e->e_to = NULL;
1759 
1760 		/*
1761 		**  Ignore jobs that are too expensive for the moment.
1762 		**
1763 		**	Get new load average every GET_NEW_LA_TIME seconds.
1764 		*/
1765 
1766 		SM_GET_LA(now);
1767 		if (shouldqueue(WkRecipFact, Current_LA_time))
1768 		{
1769 			char *msg = "Aborting queue run: load average too high";
1770 
1771 			if (Verbose)
1772 				message("%s", msg);
1773 			if (LogLevel > 8)
1774 				sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg);
1775 			break;
1776 		}
1777 		if (shouldqueue(w->w_pri, w->w_ctime))
1778 		{
1779 			if (Verbose)
1780 				message(EmptyString);
1781 			if (QueueSortOrder == QSO_BYPRIORITY)
1782 			{
1783 				if (Verbose)
1784 					message("Skipping %s/%s (sequence %d of %d) and flushing rest of queue",
1785 						qid_printqueue(w->w_qgrp,
1786 							       w->w_qdir),
1787 						w->w_name + 2, sequenceno,
1788 						njobs);
1789 				if (LogLevel > 8)
1790 					sm_syslog(LOG_INFO, NOQID,
1791 						  "runqueue: Flushing queue from %s/%s (pri %ld, LA %d, %d of %d)",
1792 						  qid_printqueue(w->w_qgrp,
1793 								 w->w_qdir),
1794 						  w->w_name + 2, w->w_pri,
1795 						  CurrentLA, sequenceno,
1796 						  njobs);
1797 				break;
1798 			}
1799 			else if (Verbose)
1800 				message("Skipping %s/%s (sequence %d of %d)",
1801 					qid_printqueue(w->w_qgrp, w->w_qdir),
1802 					w->w_name + 2, sequenceno, njobs);
1803 		}
1804 		else
1805 		{
1806 			if (Verbose)
1807 			{
1808 				message(EmptyString);
1809 				message("Running %s/%s (sequence %d of %d)",
1810 					qid_printqueue(w->w_qgrp, w->w_qdir),
1811 					w->w_name + 2, sequenceno, njobs);
1812 			}
1813 			if (didfork && MaxQueueChildren > 0)
1814 			{
1815 				sm_blocksignal(SIGCHLD);
1816 				(void) sm_signal(SIGCHLD, reapchild);
1817 			}
1818 			if (tTd(63, 100))
1819 				sm_syslog(LOG_DEBUG, NOQID,
1820 					  "runqueue %s dowork(%s)",
1821 					  qid_printqueue(w->w_qgrp, w->w_qdir),
1822 					  w->w_name + 2);
1823 
1824 			(void) dowork(w->w_qgrp, w->w_qdir, w->w_name + 2,
1825 				      ForkQueueRuns, false, e);
1826 			errno = 0;
1827 		}
1828 		sm_free(w->w_name); /* XXX */
1829 		if (w->w_host != NULL)
1830 			sm_free(w->w_host); /* XXX */
1831 		sm_free((char *) w); /* XXX */
1832 		sequenceno += seqjump; /* next sequence number */
1833 #if SM_HEAP_CHECK
1834 		if (sm_debug_active(&DebugLeakQ, 1))
1835 			sm_heap_setgroup(oldgroup);
1836 #endif /* SM_HEAP_CHECK */
1837 	}
1838 
1839 	BlockOldsh = false;
1840 
1841 	/* check the signals didn't happen during the revert */
1842 	if (NoMoreRunners)
1843 	{
1844 		/* Check that a valid signal handler is callable */
1845 		if (Oldsh != SIG_DFL && Oldsh != SIG_IGN &&
1846 		    Oldsh != runners_sighup && Oldsh != runners_sigterm)
1847 			(*Oldsh)(Oldsig);
1848 	}
1849 
1850 	Oldsh = SIG_DFL; /* after the NoMoreRunners check */
1851 }
1852 /*
1853 **  RUN_WORK_GROUP -- run the jobs in a queue group from a work group.
1854 **
1855 **	Gets the stuff out of the queue in some presumably logical
1856 **	order and processes them.
1857 **
1858 **	Parameters:
1859 **		wgrp -- work group to process.
1860 **		flags -- RWG_* flags
1861 **
1862 **	Returns:
1863 **		true if the queue run successfully began.
1864 **
1865 **	Side Effects:
1866 **		runs things in the mail queue.
1867 */
1868 
1869 /* Minimum sleep time for persistent queue runners */
1870 #define MIN_SLEEP_TIME	5
1871 
1872 bool
1873 run_work_group(wgrp, flags)
1874 	int wgrp;
1875 	int flags;
1876 {
1877 	register ENVELOPE *e;
1878 	int njobs, qdir;
1879 	int sequenceno = 1;
1880 	int qgrp, endgrp, h, i;
1881 	time_t now;
1882 	bool full, more;
1883 	SM_RPOOL_T *rpool;
1884 	extern ENVELOPE BlankEnvelope;
1885 	extern SIGFUNC_DECL reapchild __P((int));
1886 
1887 	if (wgrp < 0)
1888 		return false;
1889 
1890 	/*
1891 	**  If no work will ever be selected, don't even bother reading
1892 	**  the queue.
1893 	*/
1894 
1895 	SM_GET_LA(now);
1896 
1897 	if (!bitset(RWG_PERSISTENT, flags) &&
1898 	    shouldqueue(WkRecipFact, Current_LA_time))
1899 	{
1900 		char *msg = "Skipping queue run -- load average too high";
1901 
1902 		if (bitset(RWG_VERBOSE, flags))
1903 			message("458 %s\n", msg);
1904 		if (LogLevel > 8)
1905 			sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg);
1906 		return false;
1907 	}
1908 
1909 	/*
1910 	**  See if we already have too many children.
1911 	*/
1912 
1913 	if (bitset(RWG_FORK, flags) &&
1914 	    WorkGrp[wgrp].wg_lowqintvl > 0 &&
1915 	    !bitset(RWG_PERSISTENT, flags) &&
1916 	    MaxChildren > 0 && CurChildren >= MaxChildren)
1917 	{
1918 		char *msg = "Skipping queue run -- too many children";
1919 
1920 		if (bitset(RWG_VERBOSE, flags))
1921 			message("458 %s (%d)\n", msg, CurChildren);
1922 		if (LogLevel > 8)
1923 			sm_syslog(LOG_INFO, NOQID, "runqueue: %s (%d)",
1924 				  msg, CurChildren);
1925 		return false;
1926 	}
1927 
1928 	/*
1929 	**  See if we want to go off and do other useful work.
1930 	*/
1931 
1932 	if (bitset(RWG_FORK, flags))
1933 	{
1934 		pid_t pid;
1935 
1936 		(void) sm_blocksignal(SIGCHLD);
1937 		(void) sm_signal(SIGCHLD, reapchild);
1938 
1939 		pid = dofork();
1940 		if (pid == -1)
1941 		{
1942 			const char *msg = "Skipping queue run -- fork() failed";
1943 			const char *err = sm_errstring(errno);
1944 
1945 			if (bitset(RWG_VERBOSE, flags))
1946 				message("458 %s: %s\n", msg, err);
1947 			if (LogLevel > 8)
1948 				sm_syslog(LOG_INFO, NOQID, "runqueue: %s: %s",
1949 					  msg, err);
1950 			(void) sm_releasesignal(SIGCHLD);
1951 			return false;
1952 		}
1953 		if (pid != 0)
1954 		{
1955 			/* parent -- pick up intermediate zombie */
1956 			(void) sm_blocksignal(SIGALRM);
1957 
1958 			/* wgrp only used when queue runners are persistent */
1959 			proc_list_add(pid, "Queue runner", PROC_QUEUE,
1960 				      WorkGrp[wgrp].wg_maxact,
1961 				      bitset(RWG_PERSISTENT, flags) ? wgrp : -1,
1962 				      NULL);
1963 			(void) sm_releasesignal(SIGALRM);
1964 			(void) sm_releasesignal(SIGCHLD);
1965 			return true;
1966 		}
1967 
1968 		/* child -- clean up signals */
1969 
1970 		/* Reset global flags */
1971 		RestartRequest = NULL;
1972 		RestartWorkGroup = false;
1973 		ShutdownRequest = NULL;
1974 		PendingSignal = 0;
1975 		CurrentPid = getpid();
1976 		close_sendmail_pid();
1977 
1978 		/*
1979 		**  Initialize exception stack and default exception
1980 		**  handler for child process.
1981 		*/
1982 
1983 		sm_exc_newthread(fatal_error);
1984 		clrcontrol();
1985 		proc_list_clear();
1986 
1987 		/* Add parent process as first child item */
1988 		proc_list_add(CurrentPid, "Queue runner child process",
1989 			      PROC_QUEUE_CHILD, 0, -1, NULL);
1990 		(void) sm_releasesignal(SIGCHLD);
1991 		(void) sm_signal(SIGCHLD, SIG_DFL);
1992 		(void) sm_signal(SIGHUP, SIG_DFL);
1993 		(void) sm_signal(SIGTERM, intsig);
1994 	}
1995 
1996 	/*
1997 	**  Release any resources used by the daemon code.
1998 	*/
1999 
2000 	clrdaemon();
2001 
2002 	/* force it to run expensive jobs */
2003 	NoConnect = false;
2004 
2005 	/* drop privileges */
2006 	if (geteuid() == (uid_t) 0)
2007 		(void) drop_privileges(false);
2008 
2009 	/*
2010 	**  Create ourselves an envelope
2011 	*/
2012 
2013 	CurEnv = &QueueEnvelope;
2014 	rpool = sm_rpool_new_x(NULL);
2015 	e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2016 	e->e_flags = BlankEnvelope.e_flags;
2017 	e->e_parent = NULL;
2018 
2019 	/* make sure we have disconnected from parent */
2020 	if (bitset(RWG_FORK, flags))
2021 	{
2022 		disconnect(1, e);
2023 		QuickAbort = false;
2024 	}
2025 
2026 	/*
2027 	**  If we are running part of the queue, always ignore stored
2028 	**  host status.
2029 	*/
2030 
2031 	if (QueueLimitId != NULL || QueueLimitSender != NULL ||
2032 	    QueueLimitQuarantine != NULL ||
2033 	    QueueLimitRecipient != NULL)
2034 	{
2035 		IgnoreHostStatus = true;
2036 		MinQueueAge = 0;
2037 	}
2038 
2039 	/*
2040 	**  Here is where we choose the queue group from the work group.
2041 	**  The caller of the "domorework" label must setup a new envelope.
2042 	*/
2043 
2044 	endgrp = WorkGrp[wgrp].wg_curqgrp; /* to not spin endlessly */
2045 
2046   domorework:
2047 
2048 	/*
2049 	**  Run a queue group if:
2050 	**  RWG_RUNALL bit is set or the bit for this group is set.
2051 	*/
2052 
2053 	now = curtime();
2054 	for (;;)
2055 	{
2056 		/*
2057 		**  Find the next queue group within the work group that
2058 		**  has been marked as needing a run.
2059 		*/
2060 
2061 		qgrp = WorkGrp[wgrp].wg_qgs[WorkGrp[wgrp].wg_curqgrp]->qg_index;
2062 		WorkGrp[wgrp].wg_curqgrp++; /* advance */
2063 		WorkGrp[wgrp].wg_curqgrp %= WorkGrp[wgrp].wg_numqgrp; /* wrap */
2064 		if (bitset(RWG_RUNALL, flags) ||
2065 		    (Queue[qgrp]->qg_nextrun <= now &&
2066 		     Queue[qgrp]->qg_nextrun != (time_t) -1))
2067 			break;
2068 		if (endgrp == WorkGrp[wgrp].wg_curqgrp)
2069 		{
2070 			e->e_id = NULL;
2071 			if (bitset(RWG_FORK, flags))
2072 				finis(true, true, ExitStat);
2073 			return true; /* we're done */
2074 		}
2075 	}
2076 
2077 	qdir = Queue[qgrp]->qg_curnum; /* round-robin init of queue position */
2078 #if _FFR_QUEUE_SCHED_DBG
2079 	if (tTd(69, 12))
2080 		sm_syslog(LOG_INFO, NOQID,
2081 			"rwg: wgrp=%d, qgrp=%d, qdir=%d, name=%s, curqgrp=%d, numgrps=%d",
2082 			wgrp, qgrp, qdir, qid_printqueue(qgrp, qdir),
2083 			WorkGrp[wgrp].wg_curqgrp, WorkGrp[wgrp].wg_numqgrp);
2084 #endif /* _FFR_QUEUE_SCHED_DBG */
2085 
2086 #if HASNICE
2087 	/* tweak niceness of queue runs */
2088 	if (Queue[qgrp]->qg_nice > 0)
2089 		(void) nice(Queue[qgrp]->qg_nice);
2090 #endif /* HASNICE */
2091 
2092 	/* XXX running queue group... */
2093 	sm_setproctitle(true, CurEnv, "running queue: %s",
2094 			qid_printqueue(qgrp, qdir));
2095 
2096 	if (LogLevel > 69 || tTd(63, 99))
2097 		sm_syslog(LOG_DEBUG, NOQID,
2098 			  "runqueue %s, pid=%d, forkflag=%d",
2099 			  qid_printqueue(qgrp, qdir), (int) CurrentPid,
2100 			  bitset(RWG_FORK, flags));
2101 
2102 	/*
2103 	**  Start making passes through the queue.
2104 	**	First, read and sort the entire queue.
2105 	**	Then, process the work in that order.
2106 	**		But if you take too long, start over.
2107 	*/
2108 
2109 	for (i = 0; i < Queue[qgrp]->qg_numqueues; i++)
2110 	{
2111 		h = gatherq(qgrp, qdir, false, &full, &more);
2112 #if SM_CONF_SHM
2113 		if (ShmId != SM_SHM_NO_ID)
2114 			QSHM_ENTRIES(Queue[qgrp]->qg_qpaths[qdir].qp_idx) = h;
2115 #endif /* SM_CONF_SHM */
2116 		/* If there are no more items in this queue advance */
2117 		if (!more)
2118 		{
2119 			/* A round-robin advance */
2120 			qdir++;
2121 			qdir %= Queue[qgrp]->qg_numqueues;
2122 		}
2123 
2124 		/* Has the WorkList reached the limit? */
2125 		if (full)
2126 			break; /* don't try to gather more */
2127 	}
2128 
2129 	/* order the existing work requests */
2130 	njobs = sortq(Queue[qgrp]->qg_maxlist);
2131 	Queue[qgrp]->qg_curnum = qdir; /* update */
2132 
2133 
2134 	if (!Verbose && bitnset(QD_FORK, Queue[qgrp]->qg_flags))
2135 	{
2136 		int loop, maxrunners;
2137 		pid_t pid;
2138 
2139 		/*
2140 		**  For this WorkQ we want to fork off N children (maxrunners)
2141 		**  at this point. Each child has a copy of WorkQ. Each child
2142 		**  will process every N-th item. The parent will wait for all
2143 		**  of the children to finish before moving on to the next
2144 		**  queue group within the work group. This saves us forking
2145 		**  a new runner-child for each work item.
2146 		**  It's valid for qg_maxqrun == 0 since this may be an
2147 		**  explicit "don't run this queue" setting.
2148 		*/
2149 
2150 		maxrunners = Queue[qgrp]->qg_maxqrun;
2151 
2152 		/*
2153 		**  If no runners are configured for this group but
2154 		**  the queue is "forced" then lets use 1 runner.
2155 		*/
2156 
2157 		if (maxrunners == 0 && bitset(RWG_FORCE, flags))
2158 			maxrunners = 1;
2159 
2160 		/* No need to have more runners then there are jobs */
2161 		if (maxrunners > njobs)
2162 			maxrunners = njobs;
2163 		for (loop = 0; loop < maxrunners; loop++)
2164 		{
2165 			/*
2166 			**  Since the delivery may happen in a child and the
2167 			**  parent does not wait, the parent may close the
2168 			**  maps thereby removing any shared memory used by
2169 			**  the map.  Therefore, close the maps now so the
2170 			**  child will dynamically open them if necessary.
2171 			*/
2172 
2173 			closemaps(false);
2174 
2175 			pid = fork();
2176 			if (pid < 0)
2177 			{
2178 				syserr("run_work_group: cannot fork");
2179 				return false;
2180 			}
2181 			else if (pid > 0)
2182 			{
2183 				/* parent -- clean out connection cache */
2184 				mci_flush(false, NULL);
2185 #if _FFR_SKIP_DOMAINS
2186 				if (QueueSortOrder == QSO_BYHOST)
2187 				{
2188 					sequenceno += skip_domains(1);
2189 				}
2190 				else
2191 #endif /* _FFR_SKIP_DOMAINS */
2192 				{
2193 					/* for the skip */
2194 					WorkQ = WorkQ->w_next;
2195 					sequenceno++;
2196 				}
2197 				proc_list_add(pid, "Queue child runner process",
2198 					      PROC_QUEUE_CHILD, 0, -1, NULL);
2199 
2200 				/* No additional work, no additional runners */
2201 				if (WorkQ == NULL)
2202 					break;
2203 			}
2204 			else
2205 			{
2206 				/* child -- Reset global flags */
2207 				RestartRequest = NULL;
2208 				RestartWorkGroup = false;
2209 				ShutdownRequest = NULL;
2210 				PendingSignal = 0;
2211 				CurrentPid = getpid();
2212 				close_sendmail_pid();
2213 
2214 				/*
2215 				**  Initialize exception stack and default
2216 				**  exception handler for child process.
2217 				**  When fork()'d the child now has a private
2218 				**  copy of WorkQ at its current position.
2219 				*/
2220 
2221 				sm_exc_newthread(fatal_error);
2222 
2223 				/*
2224 				**  SMTP processes (whether -bd or -bs) set
2225 				**  SIGCHLD to reapchild to collect
2226 				**  children status.  However, at delivery
2227 				**  time, that status must be collected
2228 				**  by sm_wait() to be dealt with properly
2229 				**  (check success of delivery based
2230 				**  on status code, etc).  Therefore, if we
2231 				**  are an SMTP process, reset SIGCHLD
2232 				**  back to the default so reapchild
2233 				**  doesn't collect status before
2234 				**  sm_wait().
2235 				*/
2236 
2237 				if (OpMode == MD_SMTP ||
2238 				    OpMode == MD_DAEMON ||
2239 				    MaxQueueChildren > 0)
2240 				{
2241 					proc_list_clear();
2242 					sm_releasesignal(SIGCHLD);
2243 					(void) sm_signal(SIGCHLD, SIG_DFL);
2244 				}
2245 
2246 				/* child -- error messages to the transcript */
2247 				QuickAbort = OnlyOneError = false;
2248 				runner_work(e, sequenceno, true,
2249 					    maxrunners, njobs);
2250 
2251 				/* This child is done */
2252 				finis(true, true, ExitStat);
2253 				/* NOTREACHED */
2254 			}
2255 		}
2256 
2257 		sm_releasesignal(SIGCHLD);
2258 
2259 		/*
2260 		**  Wait until all of the runners have completed before
2261 		**  seeing if there is another queue group in the
2262 		**  work group to process.
2263 		**  XXX Future enhancement: don't wait() for all children
2264 		**  here, just go ahead and make sure that overall the number
2265 		**  of children is not exceeded.
2266 		*/
2267 
2268 		while (CurChildren > 0)
2269 		{
2270 			int status;
2271 			pid_t ret;
2272 
2273 			while ((ret = sm_wait(&status)) <= 0)
2274 				continue;
2275 			proc_list_drop(ret, status, NULL);
2276 		}
2277 	}
2278 	else if (Queue[qgrp]->qg_maxqrun > 0 || bitset(RWG_FORCE, flags))
2279 	{
2280 		/*
2281 		**  When current process will not fork children to do the work,
2282 		**  it will do the work itself. The 'skip' will be 1 since
2283 		**  there are no child runners to divide the work across.
2284 		*/
2285 
2286 		runner_work(e, sequenceno, false, 1, njobs);
2287 	}
2288 
2289 	/* free memory allocated by newenvelope() above */
2290 	sm_rpool_free(rpool);
2291 	QueueEnvelope.e_rpool = NULL;
2292 
2293 	/* Are there still more queues in the work group to process? */
2294 	if (endgrp != WorkGrp[wgrp].wg_curqgrp)
2295 	{
2296 		rpool = sm_rpool_new_x(NULL);
2297 		e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2298 		e->e_flags = BlankEnvelope.e_flags;
2299 		goto domorework;
2300 	}
2301 
2302 	/* No more queues in work group to process. Now check persistent. */
2303 	if (bitset(RWG_PERSISTENT, flags))
2304 	{
2305 		sequenceno = 1;
2306 		sm_setproctitle(true, CurEnv, "running queue: %s",
2307 				qid_printqueue(qgrp, qdir));
2308 
2309 		/*
2310 		**  close bogus maps, i.e., maps which caused a tempfail,
2311 		**	so we get fresh map connections on the next lookup.
2312 		**  closemaps() is also called when children are started.
2313 		*/
2314 
2315 		closemaps(true);
2316 
2317 		/* Close any cached connections. */
2318 		mci_flush(true, NULL);
2319 
2320 		/* Clean out expired related entries. */
2321 		rmexpstab();
2322 
2323 #if NAMED_BIND
2324 		/* Update MX records for FallbackMX. */
2325 		if (FallbackMX != NULL)
2326 			(void) getfallbackmxrr(FallbackMX);
2327 #endif /* NAMED_BIND */
2328 
2329 #if USERDB
2330 		/* close UserDatabase */
2331 		_udbx_close();
2332 #endif /* USERDB */
2333 
2334 #if SM_HEAP_CHECK
2335 		if (sm_debug_active(&SmHeapCheck, 2)
2336 		    && access("memdump", F_OK) == 0
2337 		   )
2338 		{
2339 			SM_FILE_T *out;
2340 
2341 			remove("memdump");
2342 			out = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
2343 					 "memdump.out", SM_IO_APPEND, NULL);
2344 			if (out != NULL)
2345 			{
2346 				(void) sm_io_fprintf(out, SM_TIME_DEFAULT, "----------------------\n");
2347 				sm_heap_report(out,
2348 					sm_debug_level(&SmHeapCheck) - 1);
2349 				(void) sm_io_close(out, SM_TIME_DEFAULT);
2350 			}
2351 		}
2352 #endif /* SM_HEAP_CHECK */
2353 
2354 		/* let me rest for a second to catch my breath */
2355 		if (njobs == 0 && WorkGrp[wgrp].wg_lowqintvl < MIN_SLEEP_TIME)
2356 			sleep(MIN_SLEEP_TIME);
2357 		else if (WorkGrp[wgrp].wg_lowqintvl <= 0)
2358 			sleep(QueueIntvl > 0 ? QueueIntvl : MIN_SLEEP_TIME);
2359 		else
2360 			sleep(WorkGrp[wgrp].wg_lowqintvl);
2361 
2362 		/*
2363 		**  Get the LA outside the WorkQ loop if necessary.
2364 		**  In a persistent queue runner the code is repeated over
2365 		**  and over but gatherq() may ignore entries due to
2366 		**  shouldqueue() (do we really have to do this twice?).
2367 		**  Hence the queue runners would just idle around when once
2368 		**  CurrentLA caused all entries in a queue to be ignored.
2369 		*/
2370 
2371 		if (njobs == 0)
2372 			SM_GET_LA(now);
2373 		rpool = sm_rpool_new_x(NULL);
2374 		e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2375 		e->e_flags = BlankEnvelope.e_flags;
2376 		goto domorework;
2377 	}
2378 
2379 	/* exit without the usual cleanup */
2380 	e->e_id = NULL;
2381 	if (bitset(RWG_FORK, flags))
2382 		finis(true, true, ExitStat);
2383 	/* NOTREACHED */
2384 	return true;
2385 }
2386 
2387 /*
2388 **  DOQUEUERUN -- do a queue run?
2389 */
2390 
2391 bool
2392 doqueuerun()
2393 {
2394 	return DoQueueRun;
2395 }
2396 
2397 /*
2398 **  RUNQUEUEEVENT -- Sets a flag to indicate that a queue run should be done.
2399 **
2400 **	Parameters:
2401 **		none.
2402 **
2403 **	Returns:
2404 **		none.
2405 **
2406 **	Side Effects:
2407 **		The invocation of this function via an alarm may interrupt
2408 **		a set of actions. Thus errno may be set in that context.
2409 **		We need to restore errno at the end of this function to ensure
2410 **		that any work done here that sets errno doesn't return a
2411 **		misleading/false errno value. Errno may	be EINTR upon entry to
2412 **		this function because of non-restartable/continuable system
2413 **		API was active. Iff this is true we will override errno as
2414 **		a timeout (as a more accurate error message).
2415 **
2416 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2417 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2418 **		DOING.
2419 */
2420 
2421 void
2422 runqueueevent(ignore)
2423 	int ignore;
2424 {
2425 	int save_errno = errno;
2426 
2427 	/*
2428 	**  Set the general bit that we want a queue run,
2429 	**  tested in doqueuerun()
2430 	*/
2431 
2432 	DoQueueRun = true;
2433 #if _FFR_QUEUE_SCHED_DBG
2434 	if (tTd(69, 10))
2435 		sm_syslog(LOG_INFO, NOQID, "rqe: done");
2436 #endif /* _FFR_QUEUE_SCHED_DBG */
2437 
2438 	errno = save_errno;
2439 	if (errno == EINTR)
2440 		errno = ETIMEDOUT;
2441 }
2442 /*
2443 **  GATHERQ -- gather messages from the message queue(s) the work queue.
2444 **
2445 **	Parameters:
2446 **		qgrp -- the index of the queue group.
2447 **		qdir -- the index of the queue directory.
2448 **		doall -- if set, include everything in the queue (even
2449 **			the jobs that cannot be run because the load
2450 **			average is too high, or MaxQueueRun is reached).
2451 **			Otherwise, exclude those jobs.
2452 **		full -- (optional) to be set 'true' if WorkList is full
2453 **		more -- (optional) to be set 'true' if there are still more
2454 **			messages in this queue not added to WorkList
2455 **
2456 **	Returns:
2457 **		The number of request in the queue (not necessarily
2458 **		the number of requests in WorkList however).
2459 **
2460 **	Side Effects:
2461 **		prepares available work into WorkList
2462 */
2463 
2464 #define NEED_P		0001	/* 'P': priority */
2465 #define NEED_T		0002	/* 'T': time */
2466 #define NEED_R		0004	/* 'R': recipient */
2467 #define NEED_S		0010	/* 'S': sender */
2468 #define NEED_H		0020	/* host */
2469 #define HAS_QUARANTINE	0040	/* has an unexpected 'q' line */
2470 #define NEED_QUARANTINE	0100	/* 'q': reason */
2471 
2472 static WORK	*WorkList = NULL;	/* list of unsort work */
2473 static int	WorkListSize = 0;	/* current max size of WorkList */
2474 static int	WorkListCount = 0;	/* # of work items in WorkList */
2475 
2476 static int
2477 gatherq(qgrp, qdir, doall, full, more)
2478 	int qgrp;
2479 	int qdir;
2480 	bool doall;
2481 	bool *full;
2482 	bool *more;
2483 {
2484 	register struct dirent *d;
2485 	register WORK *w;
2486 	register char *p;
2487 	DIR *f;
2488 	int i, num_ent;
2489 	int wn;
2490 	QUEUE_CHAR *check;
2491 	char qd[MAXPATHLEN];
2492 	char qf[MAXPATHLEN];
2493 
2494 	wn = WorkListCount - 1;
2495 	num_ent = 0;
2496 	if (qdir == NOQDIR)
2497 		(void) sm_strlcpy(qd, ".", sizeof(qd));
2498 	else
2499 		(void) sm_strlcpyn(qd, sizeof(qd), 2,
2500 			Queue[qgrp]->qg_qpaths[qdir].qp_name,
2501 			(bitset(QP_SUBQF,
2502 				Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
2503 					? "/qf" : ""));
2504 
2505 	if (tTd(41, 1))
2506 	{
2507 		sm_dprintf("gatherq:\n");
2508 
2509 		check = QueueLimitId;
2510 		while (check != NULL)
2511 		{
2512 			sm_dprintf("\tQueueLimitId = %s%s\n",
2513 				check->queue_negate ? "!" : "",
2514 				check->queue_match);
2515 			check = check->queue_next;
2516 		}
2517 
2518 		check = QueueLimitSender;
2519 		while (check != NULL)
2520 		{
2521 			sm_dprintf("\tQueueLimitSender = %s%s\n",
2522 				check->queue_negate ? "!" : "",
2523 				check->queue_match);
2524 			check = check->queue_next;
2525 		}
2526 
2527 		check = QueueLimitRecipient;
2528 		while (check != NULL)
2529 		{
2530 			sm_dprintf("\tQueueLimitRecipient = %s%s\n",
2531 				check->queue_negate ? "!" : "",
2532 				check->queue_match);
2533 			check = check->queue_next;
2534 		}
2535 
2536 		if (QueueMode == QM_QUARANTINE)
2537 		{
2538 			check = QueueLimitQuarantine;
2539 			while (check != NULL)
2540 			{
2541 				sm_dprintf("\tQueueLimitQuarantine = %s%s\n",
2542 					   check->queue_negate ? "!" : "",
2543 					   check->queue_match);
2544 				check = check->queue_next;
2545 			}
2546 		}
2547 	}
2548 
2549 	/* open the queue directory */
2550 	f = opendir(qd);
2551 	if (f == NULL)
2552 	{
2553 		syserr("gatherq: cannot open \"%s\"",
2554 			qid_printqueue(qgrp, qdir));
2555 		if (full != NULL)
2556 			*full = WorkListCount >= MaxQueueRun && MaxQueueRun > 0;
2557 		if (more != NULL)
2558 			*more = false;
2559 		return 0;
2560 	}
2561 
2562 	/*
2563 	**  Read the work directory.
2564 	*/
2565 
2566 	while ((d = readdir(f)) != NULL)
2567 	{
2568 		SM_FILE_T *cf;
2569 		int qfver = 0;
2570 		char lbuf[MAXNAME + 1];
2571 		struct stat sbuf;
2572 
2573 		if (tTd(41, 50))
2574 			sm_dprintf("gatherq: checking %s..", d->d_name);
2575 
2576 		/* is this an interesting entry? */
2577 		if (!(((QueueMode == QM_NORMAL &&
2578 			d->d_name[0] == NORMQF_LETTER) ||
2579 		       (QueueMode == QM_QUARANTINE &&
2580 			d->d_name[0] == QUARQF_LETTER) ||
2581 		       (QueueMode == QM_LOST &&
2582 			d->d_name[0] == LOSEQF_LETTER)) &&
2583 		      d->d_name[1] == 'f'))
2584 		{
2585 			if (tTd(41, 50))
2586 				sm_dprintf("  skipping\n");
2587 			continue;
2588 		}
2589 		if (tTd(41, 50))
2590 			sm_dprintf("\n");
2591 
2592 		if (strlen(d->d_name) >= MAXQFNAME)
2593 		{
2594 			if (Verbose)
2595 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2596 						     "gatherq: %s too long, %d max characters\n",
2597 						     d->d_name, MAXQFNAME);
2598 			if (LogLevel > 0)
2599 				sm_syslog(LOG_ALERT, NOQID,
2600 					  "gatherq: %s too long, %d max characters",
2601 					  d->d_name, MAXQFNAME);
2602 			continue;
2603 		}
2604 
2605 		check = QueueLimitId;
2606 		while (check != NULL)
2607 		{
2608 			if (strcontainedin(false, check->queue_match,
2609 					   d->d_name) != check->queue_negate)
2610 				break;
2611 			else
2612 				check = check->queue_next;
2613 		}
2614 		if (QueueLimitId != NULL && check == NULL)
2615 			continue;
2616 
2617 		/* grow work list if necessary */
2618 		if (++wn >= MaxQueueRun && MaxQueueRun > 0)
2619 		{
2620 			if (wn == MaxQueueRun && LogLevel > 0)
2621 				sm_syslog(LOG_WARNING, NOQID,
2622 					  "WorkList for %s maxed out at %d",
2623 					  qid_printqueue(qgrp, qdir),
2624 					  MaxQueueRun);
2625 			if (doall)
2626 				continue;	/* just count entries */
2627 			break;
2628 		}
2629 		if (wn >= WorkListSize)
2630 		{
2631 			grow_wlist(qgrp, qdir);
2632 			if (wn >= WorkListSize)
2633 				continue;
2634 		}
2635 		SM_ASSERT(wn >= 0);
2636 		w = &WorkList[wn];
2637 
2638 		(void) sm_strlcpyn(qf, sizeof(qf), 3, qd, "/", d->d_name);
2639 		if (stat(qf, &sbuf) < 0)
2640 		{
2641 			if (errno != ENOENT)
2642 				sm_syslog(LOG_INFO, NOQID,
2643 					  "gatherq: can't stat %s/%s",
2644 					  qid_printqueue(qgrp, qdir),
2645 					  d->d_name);
2646 			wn--;
2647 			continue;
2648 		}
2649 		if (!bitset(S_IFREG, sbuf.st_mode))
2650 		{
2651 			/* Yikes!  Skip it or we will hang on open! */
2652 			if (!((d->d_name[0] == DATAFL_LETTER ||
2653 			       d->d_name[0] == NORMQF_LETTER ||
2654 			       d->d_name[0] == QUARQF_LETTER ||
2655 			       d->d_name[0] == LOSEQF_LETTER ||
2656 			       d->d_name[0] == XSCRPT_LETTER) &&
2657 			      d->d_name[1] == 'f' && d->d_name[2] == '\0'))
2658 				syserr("gatherq: %s/%s is not a regular file",
2659 				       qid_printqueue(qgrp, qdir), d->d_name);
2660 			wn--;
2661 			continue;
2662 		}
2663 
2664 		/* avoid work if possible */
2665 		if ((QueueSortOrder == QSO_BYFILENAME ||
2666 		     QueueSortOrder == QSO_BYMODTIME ||
2667 		     QueueSortOrder == QSO_NONE ||
2668 		     QueueSortOrder == QSO_RANDOM) &&
2669 		    QueueLimitQuarantine == NULL &&
2670 		    QueueLimitSender == NULL &&
2671 		    QueueLimitRecipient == NULL)
2672 		{
2673 			w->w_qgrp = qgrp;
2674 			w->w_qdir = qdir;
2675 			w->w_name = newstr(d->d_name);
2676 			w->w_host = NULL;
2677 			w->w_lock = w->w_tooyoung = false;
2678 			w->w_pri = 0;
2679 			w->w_ctime = 0;
2680 			w->w_mtime = sbuf.st_mtime;
2681 			++num_ent;
2682 			continue;
2683 		}
2684 
2685 		/* open control file */
2686 		cf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B,
2687 				NULL);
2688 		if (cf == NULL && OpMode != MD_PRINT)
2689 		{
2690 			/* this may be some random person sending hir msgs */
2691 			if (tTd(41, 2))
2692 				sm_dprintf("gatherq: cannot open %s: %s\n",
2693 					d->d_name, sm_errstring(errno));
2694 			errno = 0;
2695 			wn--;
2696 			continue;
2697 		}
2698 		w->w_qgrp = qgrp;
2699 		w->w_qdir = qdir;
2700 		w->w_name = newstr(d->d_name);
2701 		w->w_host = NULL;
2702 		if (cf != NULL)
2703 		{
2704 			w->w_lock = !lockfile(sm_io_getinfo(cf, SM_IO_WHAT_FD,
2705 							    NULL),
2706 					      w->w_name, NULL,
2707 					      LOCK_SH|LOCK_NB);
2708 		}
2709 		w->w_tooyoung = false;
2710 
2711 		/* make sure jobs in creation don't clog queue */
2712 		w->w_pri = 0x7fffffff;
2713 		w->w_ctime = 0;
2714 		w->w_mtime = sbuf.st_mtime;
2715 
2716 		/* extract useful information */
2717 		i = NEED_P|NEED_T;
2718 		if (QueueSortOrder == QSO_BYHOST
2719 #if _FFR_RHS
2720 		    || QueueSortOrder == QSO_BYSHUFFLE
2721 #endif /* _FFR_RHS */
2722 		   )
2723 		{
2724 			/* need w_host set for host sort order */
2725 			i |= NEED_H;
2726 		}
2727 		if (QueueLimitSender != NULL)
2728 			i |= NEED_S;
2729 		if (QueueLimitRecipient != NULL)
2730 			i |= NEED_R;
2731 		if (QueueLimitQuarantine != NULL)
2732 			i |= NEED_QUARANTINE;
2733 		while (cf != NULL && i != 0 &&
2734 		       sm_io_fgets(cf, SM_TIME_DEFAULT, lbuf,
2735 				   sizeof(lbuf)) != NULL)
2736 		{
2737 			int c;
2738 			time_t age;
2739 
2740 			p = strchr(lbuf, '\n');
2741 			if (p != NULL)
2742 				*p = '\0';
2743 			else
2744 			{
2745 				/* flush rest of overly long line */
2746 				while ((c = sm_io_getc(cf, SM_TIME_DEFAULT))
2747 				       != SM_IO_EOF && c != '\n')
2748 					continue;
2749 			}
2750 
2751 			switch (lbuf[0])
2752 			{
2753 			  case 'V':
2754 				qfver = atoi(&lbuf[1]);
2755 				break;
2756 
2757 			  case 'P':
2758 				w->w_pri = atol(&lbuf[1]);
2759 				i &= ~NEED_P;
2760 				break;
2761 
2762 			  case 'T':
2763 				w->w_ctime = atol(&lbuf[1]);
2764 				i &= ~NEED_T;
2765 				break;
2766 
2767 			  case 'q':
2768 				if (QueueMode != QM_QUARANTINE &&
2769 				    QueueMode != QM_LOST)
2770 				{
2771 					if (tTd(41, 49))
2772 						sm_dprintf("%s not marked as quarantined but has a 'q' line\n",
2773 							   w->w_name);
2774 					i |= HAS_QUARANTINE;
2775 				}
2776 				else if (QueueMode == QM_QUARANTINE)
2777 				{
2778 					if (QueueLimitQuarantine == NULL)
2779 					{
2780 						i &= ~NEED_QUARANTINE;
2781 						break;
2782 					}
2783 					p = &lbuf[1];
2784 					check = QueueLimitQuarantine;
2785 					while (check != NULL)
2786 					{
2787 						if (strcontainedin(false,
2788 								   check->queue_match,
2789 								   p) !=
2790 						    check->queue_negate)
2791 							break;
2792 						else
2793 							check = check->queue_next;
2794 					}
2795 					if (check != NULL)
2796 						i &= ~NEED_QUARANTINE;
2797 				}
2798 				break;
2799 
2800 			  case 'R':
2801 				if (w->w_host == NULL &&
2802 				    (p = strrchr(&lbuf[1], '@')) != NULL)
2803 				{
2804 #if _FFR_RHS
2805 					if (QueueSortOrder == QSO_BYSHUFFLE)
2806 						w->w_host = newstr(&p[1]);
2807 					else
2808 #endif /* _FFR_RHS */
2809 						w->w_host = strrev(&p[1]);
2810 					makelower(w->w_host);
2811 					i &= ~NEED_H;
2812 				}
2813 				if (QueueLimitRecipient == NULL)
2814 				{
2815 					i &= ~NEED_R;
2816 					break;
2817 				}
2818 				if (qfver > 0)
2819 				{
2820 					p = strchr(&lbuf[1], ':');
2821 					if (p == NULL)
2822 						p = &lbuf[1];
2823 					else
2824 						++p; /* skip over ':' */
2825 				}
2826 				else
2827 					p = &lbuf[1];
2828 				check = QueueLimitRecipient;
2829 				while (check != NULL)
2830 				{
2831 					if (strcontainedin(true,
2832 							   check->queue_match,
2833 							   p) !=
2834 					    check->queue_negate)
2835 						break;
2836 					else
2837 						check = check->queue_next;
2838 				}
2839 				if (check != NULL)
2840 					i &= ~NEED_R;
2841 				break;
2842 
2843 			  case 'S':
2844 				check = QueueLimitSender;
2845 				while (check != NULL)
2846 				{
2847 					if (strcontainedin(true,
2848 							   check->queue_match,
2849 							   &lbuf[1]) !=
2850 					    check->queue_negate)
2851 						break;
2852 					else
2853 						check = check->queue_next;
2854 				}
2855 				if (check != NULL)
2856 					i &= ~NEED_S;
2857 				break;
2858 
2859 			  case 'K':
2860 				age = curtime() - (time_t) atol(&lbuf[1]);
2861 				if (age >= 0 && MinQueueAge > 0 &&
2862 				    age < MinQueueAge)
2863 					w->w_tooyoung = true;
2864 				break;
2865 
2866 			  case 'N':
2867 				if (atol(&lbuf[1]) == 0)
2868 					w->w_tooyoung = false;
2869 				break;
2870 			}
2871 		}
2872 		if (cf != NULL)
2873 			(void) sm_io_close(cf, SM_TIME_DEFAULT);
2874 
2875 		if ((!doall && (shouldqueue(w->w_pri, w->w_ctime) ||
2876 		    w->w_tooyoung)) ||
2877 		    bitset(HAS_QUARANTINE, i) ||
2878 		    bitset(NEED_QUARANTINE, i) ||
2879 		    bitset(NEED_R|NEED_S, i))
2880 		{
2881 			/* don't even bother sorting this job in */
2882 			if (tTd(41, 49))
2883 				sm_dprintf("skipping %s (%x)\n", w->w_name, i);
2884 			sm_free(w->w_name); /* XXX */
2885 			if (w->w_host != NULL)
2886 				sm_free(w->w_host); /* XXX */
2887 			wn--;
2888 		}
2889 		else
2890 			++num_ent;
2891 	}
2892 	(void) closedir(f);
2893 	wn++;
2894 
2895 	i = wn - WorkListCount;
2896 	WorkListCount += SM_MIN(num_ent, WorkListSize);
2897 
2898 	if (more != NULL)
2899 		*more = WorkListCount < wn;
2900 
2901 	if (full != NULL)
2902 		*full = (wn >= MaxQueueRun && MaxQueueRun > 0) ||
2903 			(WorkList == NULL && wn > 0);
2904 
2905 	return i;
2906 }
2907 /*
2908 **  SORTQ -- sort the work list
2909 **
2910 **	First the old WorkQ is cleared away. Then the WorkList is sorted
2911 **	for all items so that important (higher sorting value) items are not
2912 **	trunctated off. Then the most important items are moved from
2913 **	WorkList to WorkQ. The lower count of 'max' or MaxListCount items
2914 **	are moved.
2915 **
2916 **	Parameters:
2917 **		max -- maximum number of items to be placed in WorkQ
2918 **
2919 **	Returns:
2920 **		the number of items in WorkQ
2921 **
2922 **	Side Effects:
2923 **		WorkQ gets released and filled with new work. WorkList
2924 **		gets released. Work items get sorted in order.
2925 */
2926 
2927 static int
2928 sortq(max)
2929 	int max;
2930 {
2931 	register int i;			/* local counter */
2932 	register WORK *w;		/* tmp item pointer */
2933 	int wc = WorkListCount;		/* trim size for WorkQ */
2934 
2935 	if (WorkQ != NULL)
2936 	{
2937 		WORK *nw;
2938 
2939 		/* Clear out old WorkQ. */
2940 		for (w = WorkQ; w != NULL; w = nw)
2941 		{
2942 			nw = w->w_next;
2943 			sm_free(w->w_name); /* XXX */
2944 			if (w->w_host != NULL)
2945 				sm_free(w->w_host); /* XXX */
2946 			sm_free((char *) w); /* XXX */
2947 		}
2948 		WorkQ = NULL;
2949 	}
2950 
2951 	if (WorkList == NULL || wc <= 0)
2952 		return 0;
2953 
2954 	/*
2955 	**  The sort now takes place using all of the items in WorkList.
2956 	**  The list gets trimmed to the most important items after the sort.
2957 	**  If the trim were to happen before the sort then one or more
2958 	**  important items might get truncated off -- not what we want.
2959 	*/
2960 
2961 	if (QueueSortOrder == QSO_BYHOST)
2962 	{
2963 		/*
2964 		**  Sort the work directory for the first time,
2965 		**  based on host name, lock status, and priority.
2966 		*/
2967 
2968 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf1);
2969 
2970 		/*
2971 		**  If one message to host is locked, "lock" all messages
2972 		**  to that host.
2973 		*/
2974 
2975 		i = 0;
2976 		while (i < wc)
2977 		{
2978 			if (!WorkList[i].w_lock)
2979 			{
2980 				i++;
2981 				continue;
2982 			}
2983 			w = &WorkList[i];
2984 			while (++i < wc)
2985 			{
2986 				if (WorkList[i].w_host == NULL &&
2987 				    w->w_host == NULL)
2988 					WorkList[i].w_lock = true;
2989 				else if (WorkList[i].w_host != NULL &&
2990 					 w->w_host != NULL &&
2991 					 sm_strcasecmp(WorkList[i].w_host,
2992 						       w->w_host) == 0)
2993 					WorkList[i].w_lock = true;
2994 				else
2995 					break;
2996 			}
2997 		}
2998 
2999 		/*
3000 		**  Sort the work directory for the second time,
3001 		**  based on lock status, host name, and priority.
3002 		*/
3003 
3004 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf2);
3005 	}
3006 	else if (QueueSortOrder == QSO_BYTIME)
3007 	{
3008 		/*
3009 		**  Simple sort based on submission time only.
3010 		*/
3011 
3012 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf3);
3013 	}
3014 	else if (QueueSortOrder == QSO_BYFILENAME)
3015 	{
3016 		/*
3017 		**  Sort based on queue filename.
3018 		*/
3019 
3020 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf4);
3021 	}
3022 	else if (QueueSortOrder == QSO_RANDOM)
3023 	{
3024 		/*
3025 		**  Sort randomly.  To avoid problems with an instable sort,
3026 		**  use a random index into the queue file name to start
3027 		**  comparison.
3028 		*/
3029 
3030 		randi = get_rand_mod(MAXQFNAME);
3031 		if (randi < 2)
3032 			randi = 3;
3033 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf5);
3034 	}
3035 	else if (QueueSortOrder == QSO_BYMODTIME)
3036 	{
3037 		/*
3038 		**  Simple sort based on modification time of queue file.
3039 		**  This puts the oldest items first.
3040 		*/
3041 
3042 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf6);
3043 	}
3044 #if _FFR_RHS
3045 	else if (QueueSortOrder == QSO_BYSHUFFLE)
3046 	{
3047 		/*
3048 		**  Simple sort based on shuffled host name.
3049 		*/
3050 
3051 		init_shuffle_alphabet();
3052 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf7);
3053 	}
3054 #endif /* _FFR_RHS */
3055 	else if (QueueSortOrder == QSO_BYPRIORITY)
3056 	{
3057 		/*
3058 		**  Simple sort based on queue priority only.
3059 		*/
3060 
3061 		qsort((char *) WorkList, wc, sizeof(*WorkList), workcmpf0);
3062 	}
3063 	/* else don't sort at all */
3064 
3065 	/* Check if the per queue group item limit will be exceeded */
3066 	if (wc > max && max > 0)
3067 		wc = max;
3068 
3069 	/*
3070 	**  Convert the work list into canonical form.
3071 	**	Should be turning it into a list of envelopes here perhaps.
3072 	**  Only take the most important items up to the per queue group
3073 	**  maximum.
3074 	*/
3075 
3076 	for (i = wc; --i >= 0; )
3077 	{
3078 		w = (WORK *) xalloc(sizeof(*w));
3079 		w->w_qgrp = WorkList[i].w_qgrp;
3080 		w->w_qdir = WorkList[i].w_qdir;
3081 		w->w_name = WorkList[i].w_name;
3082 		w->w_host = WorkList[i].w_host;
3083 		w->w_lock = WorkList[i].w_lock;
3084 		w->w_tooyoung = WorkList[i].w_tooyoung;
3085 		w->w_pri = WorkList[i].w_pri;
3086 		w->w_ctime = WorkList[i].w_ctime;
3087 		w->w_mtime = WorkList[i].w_mtime;
3088 		w->w_next = WorkQ;
3089 		WorkQ = w;
3090 	}
3091 
3092 	/* free the rest of the list */
3093 	for (i = WorkListCount; --i >= wc; )
3094 	{
3095 		sm_free(WorkList[i].w_name);
3096 		if (WorkList[i].w_host != NULL)
3097 			sm_free(WorkList[i].w_host);
3098 	}
3099 
3100 	if (WorkList != NULL)
3101 		sm_free(WorkList); /* XXX */
3102 	WorkList = NULL;
3103 	WorkListSize = 0;
3104 	WorkListCount = 0;
3105 
3106 	if (tTd(40, 1))
3107 	{
3108 		for (w = WorkQ; w != NULL; w = w->w_next)
3109 		{
3110 			if (w->w_host != NULL)
3111 				sm_dprintf("%22s: pri=%ld %s\n",
3112 					w->w_name, w->w_pri, w->w_host);
3113 			else
3114 				sm_dprintf("%32s: pri=%ld\n",
3115 					w->w_name, w->w_pri);
3116 		}
3117 	}
3118 
3119 	return wc; /* return number of WorkQ items */
3120 }
3121 /*
3122 **  GROW_WLIST -- make the work list larger
3123 **
3124 **	Parameters:
3125 **		qgrp -- the index for the queue group.
3126 **		qdir -- the index for the queue directory.
3127 **
3128 **	Returns:
3129 **		none.
3130 **
3131 **	Side Effects:
3132 **		Adds another QUEUESEGSIZE entries to WorkList if possible.
3133 **		It can fail if there isn't enough memory, so WorkListSize
3134 **		should be checked again upon return.
3135 */
3136 
3137 static void
3138 grow_wlist(qgrp, qdir)
3139 	int qgrp;
3140 	int qdir;
3141 {
3142 	if (tTd(41, 1))
3143 		sm_dprintf("grow_wlist: WorkListSize=%d\n", WorkListSize);
3144 	if (WorkList == NULL)
3145 	{
3146 		WorkList = (WORK *) xalloc((sizeof(*WorkList)) *
3147 					   (QUEUESEGSIZE + 1));
3148 		WorkListSize = QUEUESEGSIZE;
3149 	}
3150 	else
3151 	{
3152 		int newsize = WorkListSize + QUEUESEGSIZE;
3153 		WORK *newlist = (WORK *) sm_realloc((char *) WorkList,
3154 					  (unsigned) sizeof(WORK) * (newsize + 1));
3155 
3156 		if (newlist != NULL)
3157 		{
3158 			WorkListSize = newsize;
3159 			WorkList = newlist;
3160 			if (LogLevel > 1)
3161 			{
3162 				sm_syslog(LOG_INFO, NOQID,
3163 					  "grew WorkList for %s to %d",
3164 					  qid_printqueue(qgrp, qdir),
3165 					  WorkListSize);
3166 			}
3167 		}
3168 		else if (LogLevel > 0)
3169 		{
3170 			sm_syslog(LOG_ALERT, NOQID,
3171 				  "FAILED to grow WorkList for %s to %d",
3172 				  qid_printqueue(qgrp, qdir), newsize);
3173 		}
3174 	}
3175 	if (tTd(41, 1))
3176 		sm_dprintf("grow_wlist: WorkListSize now %d\n", WorkListSize);
3177 }
3178 /*
3179 **  WORKCMPF0 -- simple priority-only compare function.
3180 **
3181 **	Parameters:
3182 **		a -- the first argument.
3183 **		b -- the second argument.
3184 **
3185 **	Returns:
3186 **		-1 if a < b
3187 **		 0 if a == b
3188 **		+1 if a > b
3189 **
3190 */
3191 
3192 static int
3193 workcmpf0(a, b)
3194 	register WORK *a;
3195 	register WORK *b;
3196 {
3197 	long pa = a->w_pri;
3198 	long pb = b->w_pri;
3199 
3200 	if (pa == pb)
3201 		return 0;
3202 	else if (pa > pb)
3203 		return 1;
3204 	else
3205 		return -1;
3206 }
3207 /*
3208 **  WORKCMPF1 -- first compare function for ordering work based on host name.
3209 **
3210 **	Sorts on host name, lock status, and priority in that order.
3211 **
3212 **	Parameters:
3213 **		a -- the first argument.
3214 **		b -- the second argument.
3215 **
3216 **	Returns:
3217 **		<0 if a < b
3218 **		 0 if a == b
3219 **		>0 if a > b
3220 **
3221 */
3222 
3223 static int
3224 workcmpf1(a, b)
3225 	register WORK *a;
3226 	register WORK *b;
3227 {
3228 	int i;
3229 
3230 	/* host name */
3231 	if (a->w_host != NULL && b->w_host == NULL)
3232 		return 1;
3233 	else if (a->w_host == NULL && b->w_host != NULL)
3234 		return -1;
3235 	if (a->w_host != NULL && b->w_host != NULL &&
3236 	    (i = sm_strcasecmp(a->w_host, b->w_host)) != 0)
3237 		return i;
3238 
3239 	/* lock status */
3240 	if (a->w_lock != b->w_lock)
3241 		return b->w_lock - a->w_lock;
3242 
3243 	/* job priority */
3244 	return workcmpf0(a, b);
3245 }
3246 /*
3247 **  WORKCMPF2 -- second compare function for ordering work based on host name.
3248 **
3249 **	Sorts on lock status, host name, and priority in that order.
3250 **
3251 **	Parameters:
3252 **		a -- the first argument.
3253 **		b -- the second argument.
3254 **
3255 **	Returns:
3256 **		<0 if a < b
3257 **		 0 if a == b
3258 **		>0 if a > b
3259 **
3260 */
3261 
3262 static int
3263 workcmpf2(a, b)
3264 	register WORK *a;
3265 	register WORK *b;
3266 {
3267 	int i;
3268 
3269 	/* lock status */
3270 	if (a->w_lock != b->w_lock)
3271 		return a->w_lock - b->w_lock;
3272 
3273 	/* host name */
3274 	if (a->w_host != NULL && b->w_host == NULL)
3275 		return 1;
3276 	else if (a->w_host == NULL && b->w_host != NULL)
3277 		return -1;
3278 	if (a->w_host != NULL && b->w_host != NULL &&
3279 	    (i = sm_strcasecmp(a->w_host, b->w_host)) != 0)
3280 		return i;
3281 
3282 	/* job priority */
3283 	return workcmpf0(a, b);
3284 }
3285 /*
3286 **  WORKCMPF3 -- simple submission-time-only compare function.
3287 **
3288 **	Parameters:
3289 **		a -- the first argument.
3290 **		b -- the second argument.
3291 **
3292 **	Returns:
3293 **		-1 if a < b
3294 **		 0 if a == b
3295 **		+1 if a > b
3296 **
3297 */
3298 
3299 static int
3300 workcmpf3(a, b)
3301 	register WORK *a;
3302 	register WORK *b;
3303 {
3304 	if (a->w_ctime > b->w_ctime)
3305 		return 1;
3306 	else if (a->w_ctime < b->w_ctime)
3307 		return -1;
3308 	else
3309 		return 0;
3310 }
3311 /*
3312 **  WORKCMPF4 -- compare based on file name
3313 **
3314 **	Parameters:
3315 **		a -- the first argument.
3316 **		b -- the second argument.
3317 **
3318 **	Returns:
3319 **		-1 if a < b
3320 **		 0 if a == b
3321 **		+1 if a > b
3322 **
3323 */
3324 
3325 static int
3326 workcmpf4(a, b)
3327 	register WORK *a;
3328 	register WORK *b;
3329 {
3330 	return strcmp(a->w_name, b->w_name);
3331 }
3332 /*
3333 **  WORKCMPF5 -- compare based on assigned random number
3334 **
3335 **	Parameters:
3336 **		a -- the first argument (ignored).
3337 **		b -- the second argument (ignored).
3338 **
3339 **	Returns:
3340 **		randomly 1/-1
3341 */
3342 
3343 /* ARGSUSED0 */
3344 static int
3345 workcmpf5(a, b)
3346 	register WORK *a;
3347 	register WORK *b;
3348 {
3349 	if (strlen(a->w_name) < randi || strlen(b->w_name) < randi)
3350 		return -1;
3351 	return a->w_name[randi] - b->w_name[randi];
3352 }
3353 /*
3354 **  WORKCMPF6 -- simple modification-time-only compare function.
3355 **
3356 **	Parameters:
3357 **		a -- the first argument.
3358 **		b -- the second argument.
3359 **
3360 **	Returns:
3361 **		-1 if a < b
3362 **		 0 if a == b
3363 **		+1 if a > b
3364 **
3365 */
3366 
3367 static int
3368 workcmpf6(a, b)
3369 	register WORK *a;
3370 	register WORK *b;
3371 {
3372 	if (a->w_mtime > b->w_mtime)
3373 		return 1;
3374 	else if (a->w_mtime < b->w_mtime)
3375 		return -1;
3376 	else
3377 		return 0;
3378 }
3379 #if _FFR_RHS
3380 /*
3381 **  WORKCMPF7 -- compare function for ordering work based on shuffled host name.
3382 **
3383 **	Sorts on lock status, host name, and priority in that order.
3384 **
3385 **	Parameters:
3386 **		a -- the first argument.
3387 **		b -- the second argument.
3388 **
3389 **	Returns:
3390 **		<0 if a < b
3391 **		 0 if a == b
3392 **		>0 if a > b
3393 **
3394 */
3395 
3396 static int
3397 workcmpf7(a, b)
3398 	register WORK *a;
3399 	register WORK *b;
3400 {
3401 	int i;
3402 
3403 	/* lock status */
3404 	if (a->w_lock != b->w_lock)
3405 		return a->w_lock - b->w_lock;
3406 
3407 	/* host name */
3408 	if (a->w_host != NULL && b->w_host == NULL)
3409 		return 1;
3410 	else if (a->w_host == NULL && b->w_host != NULL)
3411 		return -1;
3412 	if (a->w_host != NULL && b->w_host != NULL &&
3413 	    (i = sm_strshufflecmp(a->w_host, b->w_host)) != 0)
3414 		return i;
3415 
3416 	/* job priority */
3417 	return workcmpf0(a, b);
3418 }
3419 #endif /* _FFR_RHS */
3420 /*
3421 **  STRREV -- reverse string
3422 **
3423 **	Returns a pointer to a new string that is the reverse of
3424 **	the string pointed to by fwd.  The space for the new
3425 **	string is obtained using xalloc().
3426 **
3427 **	Parameters:
3428 **		fwd -- the string to reverse.
3429 **
3430 **	Returns:
3431 **		the reversed string.
3432 */
3433 
3434 static char *
3435 strrev(fwd)
3436 	char *fwd;
3437 {
3438 	char *rev = NULL;
3439 	int len, cnt;
3440 
3441 	len = strlen(fwd);
3442 	rev = xalloc(len + 1);
3443 	for (cnt = 0; cnt < len; ++cnt)
3444 		rev[cnt] = fwd[len - cnt - 1];
3445 	rev[len] = '\0';
3446 	return rev;
3447 }
3448 
3449 #if _FFR_RHS
3450 
3451 # define NASCII	128
3452 # define NCHAR	256
3453 
3454 static unsigned char ShuffledAlphabet[NCHAR];
3455 
3456 void
3457 init_shuffle_alphabet()
3458 {
3459 	static bool init = false;
3460 	int i;
3461 
3462 	if (init)
3463 		return;
3464 
3465 	/* fill the ShuffledAlphabet */
3466 	for (i = 0; i < NASCII; i++)
3467 		ShuffledAlphabet[i] = i;
3468 
3469 	/* mix it */
3470 	for (i = 1; i < NASCII; i++)
3471 	{
3472 		register int j = get_random() % NASCII;
3473 		register int tmp;
3474 
3475 		tmp = ShuffledAlphabet[j];
3476 		ShuffledAlphabet[j] = ShuffledAlphabet[i];
3477 		ShuffledAlphabet[i] = tmp;
3478 	}
3479 
3480 	/* make it case insensitive */
3481 	for (i = 'A'; i <= 'Z'; i++)
3482 		ShuffledAlphabet[i] = ShuffledAlphabet[i + 'a' - 'A'];
3483 
3484 	/* fill the upper part */
3485 	for (i = 0; i < NASCII; i++)
3486 		ShuffledAlphabet[i + NASCII] = ShuffledAlphabet[i];
3487 	init = true;
3488 }
3489 
3490 static int
3491 sm_strshufflecmp(a, b)
3492 	char *a;
3493 	char *b;
3494 {
3495 	const unsigned char *us1 = (const unsigned char *) a;
3496 	const unsigned char *us2 = (const unsigned char *) b;
3497 
3498 	while (ShuffledAlphabet[*us1] == ShuffledAlphabet[*us2++])
3499 	{
3500 		if (*us1++ == '\0')
3501 			return 0;
3502 	}
3503 	return (ShuffledAlphabet[*us1] - ShuffledAlphabet[*--us2]);
3504 }
3505 #endif /* _FFR_RHS */
3506 
3507 /*
3508 **  DOWORK -- do a work request.
3509 **
3510 **	Parameters:
3511 **		qgrp -- the index of the queue group for the job.
3512 **		qdir -- the index of the queue directory for the job.
3513 **		id -- the ID of the job to run.
3514 **		forkflag -- if set, run this in background.
3515 **		requeueflag -- if set, reinstantiate the queue quickly.
3516 **			This is used when expanding aliases in the queue.
3517 **			If forkflag is also set, it doesn't wait for the
3518 **			child.
3519 **		e - the envelope in which to run it.
3520 **
3521 **	Returns:
3522 **		process id of process that is running the queue job.
3523 **
3524 **	Side Effects:
3525 **		The work request is satisfied if possible.
3526 */
3527 
3528 pid_t
3529 dowork(qgrp, qdir, id, forkflag, requeueflag, e)
3530 	int qgrp;
3531 	int qdir;
3532 	char *id;
3533 	bool forkflag;
3534 	bool requeueflag;
3535 	register ENVELOPE *e;
3536 {
3537 	register pid_t pid;
3538 	SM_RPOOL_T *rpool;
3539 
3540 	if (tTd(40, 1))
3541 		sm_dprintf("dowork(%s/%s)\n", qid_printqueue(qgrp, qdir), id);
3542 
3543 	/*
3544 	**  Fork for work.
3545 	*/
3546 
3547 	if (forkflag)
3548 	{
3549 		/*
3550 		**  Since the delivery may happen in a child and the
3551 		**  parent does not wait, the parent may close the
3552 		**  maps thereby removing any shared memory used by
3553 		**  the map.  Therefore, close the maps now so the
3554 		**  child will dynamically open them if necessary.
3555 		*/
3556 
3557 		closemaps(false);
3558 
3559 		pid = fork();
3560 		if (pid < 0)
3561 		{
3562 			syserr("dowork: cannot fork");
3563 			return 0;
3564 		}
3565 		else if (pid > 0)
3566 		{
3567 			/* parent -- clean out connection cache */
3568 			mci_flush(false, NULL);
3569 		}
3570 		else
3571 		{
3572 			/*
3573 			**  Initialize exception stack and default exception
3574 			**  handler for child process.
3575 			*/
3576 
3577 			/* Reset global flags */
3578 			RestartRequest = NULL;
3579 			RestartWorkGroup = false;
3580 			ShutdownRequest = NULL;
3581 			PendingSignal = 0;
3582 			CurrentPid = getpid();
3583 			sm_exc_newthread(fatal_error);
3584 
3585 			/*
3586 			**  See note above about SMTP processes and SIGCHLD.
3587 			*/
3588 
3589 			if (OpMode == MD_SMTP ||
3590 			    OpMode == MD_DAEMON ||
3591 			    MaxQueueChildren > 0)
3592 			{
3593 				proc_list_clear();
3594 				sm_releasesignal(SIGCHLD);
3595 				(void) sm_signal(SIGCHLD, SIG_DFL);
3596 			}
3597 
3598 			/* child -- error messages to the transcript */
3599 			QuickAbort = OnlyOneError = false;
3600 		}
3601 	}
3602 	else
3603 	{
3604 		pid = 0;
3605 	}
3606 
3607 	if (pid == 0)
3608 	{
3609 		/*
3610 		**  CHILD
3611 		**	Lock the control file to avoid duplicate deliveries.
3612 		**		Then run the file as though we had just read it.
3613 		**	We save an idea of the temporary name so we
3614 		**		can recover on interrupt.
3615 		*/
3616 
3617 		if (forkflag)
3618 		{
3619 			/* Reset global flags */
3620 			RestartRequest = NULL;
3621 			RestartWorkGroup = false;
3622 			ShutdownRequest = NULL;
3623 			PendingSignal = 0;
3624 		}
3625 
3626 		/* set basic modes, etc. */
3627 		sm_clear_events();
3628 		clearstats();
3629 		rpool = sm_rpool_new_x(NULL);
3630 		clearenvelope(e, false, rpool);
3631 		e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
3632 		set_delivery_mode(SM_DELIVER, e);
3633 		e->e_errormode = EM_MAIL;
3634 		e->e_id = id;
3635 		e->e_qgrp = qgrp;
3636 		e->e_qdir = qdir;
3637 		GrabTo = UseErrorsTo = false;
3638 		ExitStat = EX_OK;
3639 		if (forkflag)
3640 		{
3641 			disconnect(1, e);
3642 			set_op_mode(MD_QUEUERUN);
3643 		}
3644 		sm_setproctitle(true, e, "%s from queue", qid_printname(e));
3645 		if (LogLevel > 76)
3646 			sm_syslog(LOG_DEBUG, e->e_id, "dowork, pid=%d",
3647 				  (int) CurrentPid);
3648 
3649 		/* don't use the headers from sendmail.cf... */
3650 		e->e_header = NULL;
3651 
3652 		/* read the queue control file -- return if locked */
3653 		if (!readqf(e, false))
3654 		{
3655 			if (tTd(40, 4) && e->e_id != NULL)
3656 				sm_dprintf("readqf(%s) failed\n",
3657 					qid_printname(e));
3658 			e->e_id = NULL;
3659 			if (forkflag)
3660 				finis(false, true, EX_OK);
3661 			else
3662 			{
3663 				/* adding this frees 8 bytes */
3664 				clearenvelope(e, false, rpool);
3665 
3666 				/* adding this frees 12 bytes */
3667 				sm_rpool_free(rpool);
3668 				e->e_rpool = NULL;
3669 				return 0;
3670 			}
3671 		}
3672 
3673 		e->e_flags |= EF_INQUEUE;
3674 		eatheader(e, requeueflag, true);
3675 
3676 		if (requeueflag)
3677 			queueup(e, false, false);
3678 
3679 		/* do the delivery */
3680 		sendall(e, SM_DELIVER);
3681 
3682 		/* finish up and exit */
3683 		if (forkflag)
3684 			finis(true, true, ExitStat);
3685 		else
3686 		{
3687 			dropenvelope(e, true, false);
3688 			sm_rpool_free(rpool);
3689 			e->e_rpool = NULL;
3690 		}
3691 	}
3692 	e->e_id = NULL;
3693 	return pid;
3694 }
3695 
3696 /*
3697 **  DOWORKLIST -- process a list of envelopes as work requests
3698 **
3699 **	Similar to dowork(), except that after forking, it processes an
3700 **	envelope and its siblings, treating each envelope as a work request.
3701 **
3702 **	Parameters:
3703 **		el -- envelope to be processed including its siblings.
3704 **		forkflag -- if set, run this in background.
3705 **		requeueflag -- if set, reinstantiate the queue quickly.
3706 **			This is used when expanding aliases in the queue.
3707 **			If forkflag is also set, it doesn't wait for the
3708 **			child.
3709 **
3710 **	Returns:
3711 **		process id of process that is running the queue job.
3712 **
3713 **	Side Effects:
3714 **		The work request is satisfied if possible.
3715 */
3716 
3717 pid_t
3718 doworklist(el, forkflag, requeueflag)
3719 	ENVELOPE *el;
3720 	bool forkflag;
3721 	bool requeueflag;
3722 {
3723 	register pid_t pid;
3724 	ENVELOPE *ei;
3725 
3726 	if (tTd(40, 1))
3727 		sm_dprintf("doworklist()\n");
3728 
3729 	/*
3730 	**  Fork for work.
3731 	*/
3732 
3733 	if (forkflag)
3734 	{
3735 		/*
3736 		**  Since the delivery may happen in a child and the
3737 		**  parent does not wait, the parent may close the
3738 		**  maps thereby removing any shared memory used by
3739 		**  the map.  Therefore, close the maps now so the
3740 		**  child will dynamically open them if necessary.
3741 		*/
3742 
3743 		closemaps(false);
3744 
3745 		pid = fork();
3746 		if (pid < 0)
3747 		{
3748 			syserr("doworklist: cannot fork");
3749 			return 0;
3750 		}
3751 		else if (pid > 0)
3752 		{
3753 			/* parent -- clean out connection cache */
3754 			mci_flush(false, NULL);
3755 		}
3756 		else
3757 		{
3758 			/*
3759 			**  Initialize exception stack and default exception
3760 			**  handler for child process.
3761 			*/
3762 
3763 			/* Reset global flags */
3764 			RestartRequest = NULL;
3765 			RestartWorkGroup = false;
3766 			ShutdownRequest = NULL;
3767 			PendingSignal = 0;
3768 			CurrentPid = getpid();
3769 			sm_exc_newthread(fatal_error);
3770 
3771 			/*
3772 			**  See note above about SMTP processes and SIGCHLD.
3773 			*/
3774 
3775 			if (OpMode == MD_SMTP ||
3776 			    OpMode == MD_DAEMON ||
3777 			    MaxQueueChildren > 0)
3778 			{
3779 				proc_list_clear();
3780 				sm_releasesignal(SIGCHLD);
3781 				(void) sm_signal(SIGCHLD, SIG_DFL);
3782 			}
3783 
3784 			/* child -- error messages to the transcript */
3785 			QuickAbort = OnlyOneError = false;
3786 		}
3787 	}
3788 	else
3789 	{
3790 		pid = 0;
3791 	}
3792 
3793 	if (pid != 0)
3794 		return pid;
3795 
3796 	/*
3797 	**  IN CHILD
3798 	**	Lock the control file to avoid duplicate deliveries.
3799 	**		Then run the file as though we had just read it.
3800 	**	We save an idea of the temporary name so we
3801 	**		can recover on interrupt.
3802 	*/
3803 
3804 	if (forkflag)
3805 	{
3806 		/* Reset global flags */
3807 		RestartRequest = NULL;
3808 		RestartWorkGroup = false;
3809 		ShutdownRequest = NULL;
3810 		PendingSignal = 0;
3811 	}
3812 
3813 	/* set basic modes, etc. */
3814 	sm_clear_events();
3815 	clearstats();
3816 	GrabTo = UseErrorsTo = false;
3817 	ExitStat = EX_OK;
3818 	if (forkflag)
3819 	{
3820 		disconnect(1, el);
3821 		set_op_mode(MD_QUEUERUN);
3822 	}
3823 	if (LogLevel > 76)
3824 		sm_syslog(LOG_DEBUG, el->e_id, "doworklist, pid=%d",
3825 			  (int) CurrentPid);
3826 
3827 	for (ei = el; ei != NULL; ei = ei->e_sibling)
3828 	{
3829 		ENVELOPE e;
3830 		SM_RPOOL_T *rpool;
3831 
3832 		if (WILL_BE_QUEUED(ei->e_sendmode))
3833 			continue;
3834 		else if (QueueMode != QM_QUARANTINE &&
3835 			 ei->e_quarmsg != NULL)
3836 			continue;
3837 
3838 		rpool = sm_rpool_new_x(NULL);
3839 		clearenvelope(&e, true, rpool);
3840 		e.e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
3841 		set_delivery_mode(SM_DELIVER, &e);
3842 		e.e_errormode = EM_MAIL;
3843 		e.e_id = ei->e_id;
3844 		e.e_qgrp = ei->e_qgrp;
3845 		e.e_qdir = ei->e_qdir;
3846 		openxscript(&e);
3847 		sm_setproctitle(true, &e, "%s from queue", qid_printname(&e));
3848 
3849 		/* don't use the headers from sendmail.cf... */
3850 		e.e_header = NULL;
3851 		CurEnv = &e;
3852 
3853 		/* read the queue control file -- return if locked */
3854 		if (readqf(&e, false))
3855 		{
3856 			e.e_flags |= EF_INQUEUE;
3857 			eatheader(&e, requeueflag, true);
3858 
3859 			if (requeueflag)
3860 				queueup(&e, false, false);
3861 
3862 			/* do the delivery */
3863 			sendall(&e, SM_DELIVER);
3864 			dropenvelope(&e, true, false);
3865 		}
3866 		else
3867 		{
3868 			if (tTd(40, 4) && e.e_id != NULL)
3869 				sm_dprintf("readqf(%s) failed\n",
3870 					qid_printname(&e));
3871 		}
3872 		sm_rpool_free(rpool);
3873 		ei->e_id = NULL;
3874 	}
3875 
3876 	/* restore CurEnv */
3877 	CurEnv = el;
3878 
3879 	/* finish up and exit */
3880 	if (forkflag)
3881 		finis(true, true, ExitStat);
3882 	return 0;
3883 }
3884 /*
3885 **  READQF -- read queue file and set up environment.
3886 **
3887 **	Parameters:
3888 **		e -- the envelope of the job to run.
3889 **		openonly -- only open the qf (returned as e_lockfp)
3890 **
3891 **	Returns:
3892 **		true if it successfully read the queue file.
3893 **		false otherwise.
3894 **
3895 **	Side Effects:
3896 **		The queue file is returned locked.
3897 */
3898 
3899 static bool
3900 readqf(e, openonly)
3901 	register ENVELOPE *e;
3902 	bool openonly;
3903 {
3904 	register SM_FILE_T *qfp;
3905 	ADDRESS *ctladdr;
3906 	struct stat st, stf;
3907 	char *bp;
3908 	int qfver = 0;
3909 	long hdrsize = 0;
3910 	register char *p;
3911 	char *frcpt = NULL;
3912 	char *orcpt = NULL;
3913 	bool nomore = false;
3914 	bool bogus = false;
3915 	MODE_T qsafe;
3916 	char *err;
3917 	char qf[MAXPATHLEN];
3918 	char buf[MAXLINE];
3919 	int bufsize;
3920 
3921 	/*
3922 	**  Read and process the file.
3923 	*/
3924 
3925 	SM_REQUIRE(e != NULL);
3926 	bp = NULL;
3927 	(void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), sizeof(qf));
3928 	qfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDWR_B, NULL);
3929 	if (qfp == NULL)
3930 	{
3931 		int save_errno = errno;
3932 
3933 		if (tTd(40, 8))
3934 			sm_dprintf("readqf(%s): sm_io_open failure (%s)\n",
3935 				qf, sm_errstring(errno));
3936 		errno = save_errno;
3937 		if (errno != ENOENT
3938 		    )
3939 			syserr("readqf: no control file %s", qf);
3940 		RELEASE_QUEUE;
3941 		return false;
3942 	}
3943 
3944 	if (!lockfile(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), qf, NULL,
3945 		      LOCK_EX|LOCK_NB))
3946 	{
3947 		/* being processed by another queuer */
3948 		if (Verbose)
3949 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3950 					     "%s: locked\n", e->e_id);
3951 		if (tTd(40, 8))
3952 			sm_dprintf("%s: locked\n", e->e_id);
3953 		if (LogLevel > 19)
3954 			sm_syslog(LOG_DEBUG, e->e_id, "locked");
3955 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
3956 		RELEASE_QUEUE;
3957 		return false;
3958 	}
3959 
3960 	RELEASE_QUEUE;
3961 
3962 	/*
3963 	**  Prevent locking race condition.
3964 	**
3965 	**  Process A: readqf(): qfp = fopen(qffile)
3966 	**  Process B: queueup(): rename(tf, qf)
3967 	**  Process B: unlocks(tf)
3968 	**  Process A: lockfile(qf);
3969 	**
3970 	**  Process A (us) has the old qf file (before the rename deleted
3971 	**  the directory entry) and will be delivering based on old data.
3972 	**  This can lead to multiple deliveries of the same recipients.
3973 	**
3974 	**  Catch this by checking if the underlying qf file has changed
3975 	**  *after* acquiring our lock and if so, act as though the file
3976 	**  was still locked (i.e., just return like the lockfile() case
3977 	**  above.
3978 	*/
3979 
3980 	if (stat(qf, &stf) < 0 ||
3981 	    fstat(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), &st) < 0)
3982 	{
3983 		/* must have been being processed by someone else */
3984 		if (tTd(40, 8))
3985 			sm_dprintf("readqf(%s): [f]stat failure (%s)\n",
3986 				qf, sm_errstring(errno));
3987 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
3988 		return false;
3989 	}
3990 
3991 	if (st.st_nlink != stf.st_nlink ||
3992 	    st.st_dev != stf.st_dev ||
3993 	    ST_INODE(st) != ST_INODE(stf) ||
3994 #if HAS_ST_GEN && 0		/* AFS returns garbage in st_gen */
3995 	    st.st_gen != stf.st_gen ||
3996 #endif /* HAS_ST_GEN && 0 */
3997 	    st.st_uid != stf.st_uid ||
3998 	    st.st_gid != stf.st_gid ||
3999 	    st.st_size != stf.st_size)
4000 	{
4001 		/* changed after opened */
4002 		if (Verbose)
4003 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4004 					     "%s: changed\n", e->e_id);
4005 		if (tTd(40, 8))
4006 			sm_dprintf("%s: changed\n", e->e_id);
4007 		if (LogLevel > 19)
4008 			sm_syslog(LOG_DEBUG, e->e_id, "changed");
4009 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4010 		return false;
4011 	}
4012 
4013 	/*
4014 	**  Check the queue file for plausibility to avoid attacks.
4015 	*/
4016 
4017 	qsafe = S_IWOTH|S_IWGRP;
4018 	if (bitset(S_IWGRP, QueueFileMode))
4019 		qsafe &= ~S_IWGRP;
4020 
4021 	bogus = st.st_uid != geteuid() &&
4022 		st.st_uid != TrustedUid &&
4023 		geteuid() != RealUid;
4024 
4025 	/*
4026 	**  If this qf file results from a set-group-ID binary, then
4027 	**  we check whether the directory is group-writable,
4028 	**  the queue file mode contains the group-writable bit, and
4029 	**  the groups are the same.
4030 	**  Notice: this requires that the set-group-ID binary is used to
4031 	**  run the queue!
4032 	*/
4033 
4034 	if (bogus && st.st_gid == getegid() && UseMSP)
4035 	{
4036 		char delim;
4037 		struct stat dst;
4038 
4039 		bp = SM_LAST_DIR_DELIM(qf);
4040 		if (bp == NULL)
4041 			delim = '\0';
4042 		else
4043 		{
4044 			delim = *bp;
4045 			*bp = '\0';
4046 		}
4047 		if (stat(delim == '\0' ? "." : qf, &dst) < 0)
4048 			syserr("readqf: cannot stat directory %s",
4049 				delim == '\0' ? "." : qf);
4050 		else
4051 		{
4052 			bogus = !(bitset(S_IWGRP, QueueFileMode) &&
4053 				  bitset(S_IWGRP, dst.st_mode) &&
4054 				  dst.st_gid == st.st_gid);
4055 		}
4056 		if (delim != '\0')
4057 			*bp = delim;
4058 		bp = NULL;
4059 	}
4060 	if (!bogus)
4061 		bogus = bitset(qsafe, st.st_mode);
4062 	if (bogus)
4063 	{
4064 		if (LogLevel > 0)
4065 		{
4066 			sm_syslog(LOG_ALERT, e->e_id,
4067 				  "bogus queue file, uid=%d, gid=%d, mode=%o",
4068 				  st.st_uid, st.st_gid, st.st_mode);
4069 		}
4070 		if (tTd(40, 8))
4071 			sm_dprintf("readqf(%s): bogus file\n", qf);
4072 		e->e_flags |= EF_INQUEUE;
4073 		if (!openonly)
4074 			loseqfile(e, "bogus file uid/gid in mqueue");
4075 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4076 		return false;
4077 	}
4078 
4079 	if (st.st_size == 0)
4080 	{
4081 		/* must be a bogus file -- if also old, just remove it */
4082 		if (!openonly && st.st_ctime + 10 * 60 < curtime())
4083 		{
4084 			(void) xunlink(queuename(e, DATAFL_LETTER));
4085 			(void) xunlink(queuename(e, ANYQFL_LETTER));
4086 		}
4087 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4088 		return false;
4089 	}
4090 
4091 	if (st.st_nlink == 0)
4092 	{
4093 		/*
4094 		**  Race condition -- we got a file just as it was being
4095 		**  unlinked.  Just assume it is zero length.
4096 		*/
4097 
4098 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4099 		return false;
4100 	}
4101 
4102 #if _FFR_TRUSTED_QF
4103 	/*
4104 	**  If we don't own the file mark it as unsafe.
4105 	**  However, allow TrustedUser to own it as well
4106 	**  in case TrustedUser manipulates the queue.
4107 	*/
4108 
4109 	if (st.st_uid != geteuid() && st.st_uid != TrustedUid)
4110 		e->e_flags |= EF_UNSAFE;
4111 #else /* _FFR_TRUSTED_QF */
4112 	/* If we don't own the file mark it as unsafe */
4113 	if (st.st_uid != geteuid())
4114 		e->e_flags |= EF_UNSAFE;
4115 #endif /* _FFR_TRUSTED_QF */
4116 
4117 	/* good file -- save this lock */
4118 	e->e_lockfp = qfp;
4119 
4120 	/* Just wanted the open file */
4121 	if (openonly)
4122 		return true;
4123 
4124 	/* do basic system initialization */
4125 	initsys(e);
4126 	macdefine(&e->e_macro, A_PERM, 'i', e->e_id);
4127 
4128 	LineNumber = 0;
4129 	e->e_flags |= EF_GLOBALERRS;
4130 	set_op_mode(MD_QUEUERUN);
4131 	ctladdr = NULL;
4132 	e->e_qfletter = queue_letter(e, ANYQFL_LETTER);
4133 	e->e_dfqgrp = e->e_qgrp;
4134 	e->e_dfqdir = e->e_qdir;
4135 #if _FFR_QUEUE_MACRO
4136 	macdefine(&e->e_macro, A_TEMP, macid("{queue}"),
4137 		  qid_printqueue(e->e_qgrp, e->e_qdir));
4138 #endif /* _FFR_QUEUE_MACRO */
4139 	e->e_dfino = -1;
4140 	e->e_msgsize = -1;
4141 	while (bufsize = sizeof(buf),
4142 	       (bp = fgetfolded(buf, &bufsize, qfp)) != NULL)
4143 	{
4144 		unsigned long qflags;
4145 		ADDRESS *q;
4146 		int r;
4147 		time_t now;
4148 		auto char *ep;
4149 
4150 		if (tTd(40, 4))
4151 			sm_dprintf("+++++ %s\n", bp);
4152 		if (nomore)
4153 		{
4154 			/* hack attack */
4155   hackattack:
4156 			syserr("SECURITY ALERT: extra or bogus data in queue file: %s",
4157 			       bp);
4158 			err = "bogus queue line";
4159 			goto fail;
4160 		}
4161 		switch (bp[0])
4162 		{
4163 		  case 'A':		/* AUTH= parameter */
4164 			if (!xtextok(&bp[1]))
4165 				goto hackattack;
4166 			e->e_auth_param = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4167 			break;
4168 
4169 		  case 'B':		/* body type */
4170 			r = check_bodytype(&bp[1]);
4171 			if (!BODYTYPE_VALID(r))
4172 				goto hackattack;
4173 			e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4174 			break;
4175 
4176 		  case 'C':		/* specify controlling user */
4177 			ctladdr = setctluser(&bp[1], qfver, e);
4178 			break;
4179 
4180 		  case 'D':		/* data file name */
4181 			/* obsolete -- ignore */
4182 			break;
4183 
4184 		  case 'd':		/* data file directory name */
4185 			{
4186 				int qgrp, qdir;
4187 
4188 #if _FFR_MSP_PARANOIA
4189 				/* forbid queue groups in MSP? */
4190 				if (UseMSP)
4191 					goto hackattack;
4192 #endif /* _FFR_MSP_PARANOIA */
4193 				for (qgrp = 0;
4194 				     qgrp < NumQueue && Queue[qgrp] != NULL;
4195 				     ++qgrp)
4196 				{
4197 					for (qdir = 0;
4198 					     qdir < Queue[qgrp]->qg_numqueues;
4199 					     ++qdir)
4200 					{
4201 						if (strcmp(&bp[1],
4202 							   Queue[qgrp]->qg_qpaths[qdir].qp_name)
4203 						    == 0)
4204 						{
4205 							e->e_dfqgrp = qgrp;
4206 							e->e_dfqdir = qdir;
4207 							goto done;
4208 						}
4209 					}
4210 				}
4211 				err = "bogus queue file directory";
4212 				goto fail;
4213 			  done:
4214 				break;
4215 			}
4216 
4217 		  case 'E':		/* specify error recipient */
4218 			/* no longer used */
4219 			break;
4220 
4221 		  case 'F':		/* flag bits */
4222 			if (strncmp(bp, "From ", 5) == 0)
4223 			{
4224 				/* we are being spoofed! */
4225 				syserr("SECURITY ALERT: bogus qf line %s", bp);
4226 				err = "bogus queue line";
4227 				goto fail;
4228 			}
4229 			for (p = &bp[1]; *p != '\0'; p++)
4230 			{
4231 				switch (*p)
4232 				{
4233 				  case '8':	/* has 8 bit data */
4234 					e->e_flags |= EF_HAS8BIT;
4235 					break;
4236 
4237 				  case 'b':	/* delete Bcc: header */
4238 					e->e_flags |= EF_DELETE_BCC;
4239 					break;
4240 
4241 				  case 'd':	/* envelope has DSN RET= */
4242 					e->e_flags |= EF_RET_PARAM;
4243 					break;
4244 
4245 				  case 'n':	/* don't return body */
4246 					e->e_flags |= EF_NO_BODY_RETN;
4247 					break;
4248 
4249 				  case 'r':	/* response */
4250 					e->e_flags |= EF_RESPONSE;
4251 					break;
4252 
4253 				  case 's':	/* split */
4254 					e->e_flags |= EF_SPLIT;
4255 					break;
4256 
4257 				  case 'w':	/* warning sent */
4258 					e->e_flags |= EF_WARNING;
4259 					break;
4260 				}
4261 			}
4262 			break;
4263 
4264 		  case 'q':		/* quarantine reason */
4265 			e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4266 			macdefine(&e->e_macro, A_PERM,
4267 				  macid("{quarantine}"), e->e_quarmsg);
4268 			break;
4269 
4270 		  case 'H':		/* header */
4271 
4272 			/*
4273 			**  count size before chompheader() destroys the line.
4274 			**  this isn't accurate due to macro expansion, but
4275 			**  better than before. "-3" to skip H?? at least.
4276 			*/
4277 
4278 			hdrsize += strlen(bp) - 3;
4279 			(void) chompheader(&bp[1], CHHDR_QUEUE, NULL, e);
4280 			break;
4281 
4282 		  case 'I':		/* data file's inode number */
4283 			/* regenerated below */
4284 			break;
4285 
4286 		  case 'K':		/* time of last delivery attempt */
4287 			e->e_dtime = atol(&buf[1]);
4288 			break;
4289 
4290 		  case 'L':		/* Solaris Content-Length: */
4291 		  case 'M':		/* message */
4292 			/* ignore this; we want a new message next time */
4293 			break;
4294 
4295 		  case 'N':		/* number of delivery attempts */
4296 			e->e_ntries = atoi(&buf[1]);
4297 
4298 			/* if this has been tried recently, let it be */
4299 			now = curtime();
4300 			if (e->e_ntries > 0 && e->e_dtime <= now &&
4301 			    now < e->e_dtime + MinQueueAge)
4302 			{
4303 				char *howlong;
4304 
4305 				howlong = pintvl(now - e->e_dtime, true);
4306 				if (Verbose)
4307 					(void) sm_io_fprintf(smioout,
4308 							     SM_TIME_DEFAULT,
4309 							     "%s: too young (%s)\n",
4310 							     e->e_id, howlong);
4311 				if (tTd(40, 8))
4312 					sm_dprintf("%s: too young (%s)\n",
4313 						e->e_id, howlong);
4314 				if (LogLevel > 19)
4315 					sm_syslog(LOG_DEBUG, e->e_id,
4316 						  "too young (%s)",
4317 						  howlong);
4318 				e->e_id = NULL;
4319 				unlockqueue(e);
4320 				if (bp != buf)
4321 					sm_free(bp);
4322 				return false;
4323 			}
4324 			macdefine(&e->e_macro, A_TEMP,
4325 				macid("{ntries}"), &buf[1]);
4326 
4327 #if NAMED_BIND
4328 			/* adjust BIND parameters immediately */
4329 			if (e->e_ntries == 0)
4330 			{
4331 				_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
4332 				_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
4333 			}
4334 			else
4335 			{
4336 				_res.retry = TimeOuts.res_retry[RES_TO_NORMAL];
4337 				_res.retrans = TimeOuts.res_retrans[RES_TO_NORMAL];
4338 			}
4339 #endif /* NAMED_BIND */
4340 			break;
4341 
4342 		  case 'P':		/* message priority */
4343 			e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
4344 			break;
4345 
4346 		  case 'Q':		/* original recipient */
4347 			orcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4348 			break;
4349 
4350 		  case 'r':		/* final recipient */
4351 			frcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4352 			break;
4353 
4354 		  case 'R':		/* specify recipient */
4355 			p = bp;
4356 			qflags = 0;
4357 			if (qfver >= 1)
4358 			{
4359 				/* get flag bits */
4360 				while (*++p != '\0' && *p != ':')
4361 				{
4362 					switch (*p)
4363 					{
4364 					  case 'N':
4365 						qflags |= QHASNOTIFY;
4366 						break;
4367 
4368 					  case 'S':
4369 						qflags |= QPINGONSUCCESS;
4370 						break;
4371 
4372 					  case 'F':
4373 						qflags |= QPINGONFAILURE;
4374 						break;
4375 
4376 					  case 'D':
4377 						qflags |= QPINGONDELAY;
4378 						break;
4379 
4380 					  case 'P':
4381 						qflags |= QPRIMARY;
4382 						break;
4383 
4384 					  case 'A':
4385 						if (ctladdr != NULL)
4386 							ctladdr->q_flags |= QALIAS;
4387 						break;
4388 
4389 					  default: /* ignore or complain? */
4390 						break;
4391 					}
4392 				}
4393 			}
4394 			else
4395 				qflags |= QPRIMARY;
4396 			macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
4397 				"e r");
4398 			if (*p != '\0')
4399 				q = parseaddr(++p, NULLADDR, RF_COPYALL, '\0',
4400 						NULL, e, true);
4401 			else
4402 				q = NULL;
4403 			if (q != NULL)
4404 			{
4405 				/* make sure we keep the current qgrp */
4406 				if (ISVALIDQGRP(e->e_qgrp))
4407 					q->q_qgrp = e->e_qgrp;
4408 				q->q_alias = ctladdr;
4409 				if (qfver >= 1)
4410 					q->q_flags &= ~Q_PINGFLAGS;
4411 				q->q_flags |= qflags;
4412 				q->q_finalrcpt = frcpt;
4413 				q->q_orcpt = orcpt;
4414 				(void) recipient(q, &e->e_sendqueue, 0, e);
4415 			}
4416 			frcpt = NULL;
4417 			orcpt = NULL;
4418 			macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
4419 				NULL);
4420 			break;
4421 
4422 		  case 'S':		/* sender */
4423 			setsender(sm_rpool_strdup_x(e->e_rpool, &bp[1]),
4424 				  e, NULL, '\0', true);
4425 			break;
4426 
4427 		  case 'T':		/* init time */
4428 			e->e_ctime = atol(&bp[1]);
4429 			break;
4430 
4431 		  case 'V':		/* queue file version number */
4432 			qfver = atoi(&bp[1]);
4433 			if (qfver <= QF_VERSION)
4434 				break;
4435 			syserr("Version number in queue file (%d) greater than max (%d)",
4436 				qfver, QF_VERSION);
4437 			err = "unsupported queue file version";
4438 			goto fail;
4439 			/* NOTREACHED */
4440 			break;
4441 
4442 		  case 'Z':		/* original envelope id from ESMTP */
4443 			e->e_envid = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4444 			macdefine(&e->e_macro, A_PERM,
4445 				macid("{dsn_envid}"), e->e_envid);
4446 			break;
4447 
4448 		  case '!':		/* deliver by */
4449 
4450 			/* format: flag (1 char) space long-integer */
4451 			e->e_dlvr_flag = buf[1];
4452 			e->e_deliver_by = strtol(&buf[3], NULL, 10);
4453 
4454 		  case '$':		/* define macro */
4455 			{
4456 				char *p;
4457 
4458 				/* XXX elimate p? */
4459 				r = macid_parse(&bp[1], &ep);
4460 				if (r == 0)
4461 					break;
4462 				p = sm_rpool_strdup_x(e->e_rpool, ep);
4463 				macdefine(&e->e_macro, A_PERM, r, p);
4464 			}
4465 			break;
4466 
4467 		  case '.':		/* terminate file */
4468 			nomore = true;
4469 			break;
4470 
4471 #if _FFR_QUEUEDELAY
4472 		  case 'G':
4473 		  case 'Y':
4474 
4475 			/*
4476 			**  Maintain backward compatibility for
4477 			**  users who defined _FFR_QUEUEDELAY in
4478 			**  previous releases.  Remove this
4479 			**  code in 8.14 or 8.15.
4480 			*/
4481 
4482 			if (qfver == 5 || qfver == 7)
4483 				break;
4484 
4485 			/* If not qfver 5 or 7, then 'G' or 'Y' is invalid */
4486 			/* FALLTHROUGH */
4487 #endif /* _FFR_QUEUEDELAY */
4488 
4489 		  default:
4490 			syserr("readqf: %s: line %d: bad line \"%s\"",
4491 				qf, LineNumber, shortenstring(bp, MAXSHORTSTR));
4492 			err = "unrecognized line";
4493 			goto fail;
4494 		}
4495 
4496 		if (bp != buf)
4497 			SM_FREE(bp);
4498 	}
4499 
4500 	/*
4501 	**  If we haven't read any lines, this queue file is empty.
4502 	**  Arrange to remove it without referencing any null pointers.
4503 	*/
4504 
4505 	if (LineNumber == 0)
4506 	{
4507 		errno = 0;
4508 		e->e_flags |= EF_CLRQUEUE|EF_FATALERRS|EF_RESPONSE;
4509 		return true;
4510 	}
4511 
4512 	/* Check to make sure we have a complete queue file read */
4513 	if (!nomore)
4514 	{
4515 		syserr("readqf: %s: incomplete queue file read", qf);
4516 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4517 		return false;
4518 	}
4519 
4520 #if _FFR_QF_PARANOIA
4521 	/* Check to make sure key fields were read */
4522 	if (e->e_from.q_mailer == NULL)
4523 	{
4524 		syserr("readqf: %s: sender not specified in queue file", qf);
4525 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4526 		return false;
4527 	}
4528 	/* other checks? */
4529 #endif /* _FFR_QF_PARANOIA */
4530 
4531 	/* possibly set ${dsn_ret} macro */
4532 	if (bitset(EF_RET_PARAM, e->e_flags))
4533 	{
4534 		if (bitset(EF_NO_BODY_RETN, e->e_flags))
4535 			macdefine(&e->e_macro, A_PERM,
4536 				macid("{dsn_ret}"), "hdrs");
4537 		else
4538 			macdefine(&e->e_macro, A_PERM,
4539 				macid("{dsn_ret}"), "full");
4540 	}
4541 
4542 	/*
4543 	**  Arrange to read the data file.
4544 	*/
4545 
4546 	p = queuename(e, DATAFL_LETTER);
4547 	e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, p, SM_IO_RDONLY_B,
4548 			      NULL);
4549 	if (e->e_dfp == NULL)
4550 	{
4551 		syserr("readqf: cannot open %s", p);
4552 	}
4553 	else
4554 	{
4555 		e->e_flags |= EF_HAS_DF;
4556 		if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &st)
4557 		    >= 0)
4558 		{
4559 			e->e_msgsize = st.st_size + hdrsize;
4560 			e->e_dfdev = st.st_dev;
4561 			e->e_dfino = ST_INODE(st);
4562 			(void) sm_snprintf(buf, sizeof(buf), "%ld",
4563 					   e->e_msgsize);
4564 			macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"),
4565 				  buf);
4566 		}
4567 	}
4568 
4569 	return true;
4570 
4571   fail:
4572 	/*
4573 	**  There was some error reading the qf file (reason is in err var.)
4574 	**  Cleanup:
4575 	**	close file; clear e_lockfp since it is the same as qfp,
4576 	**	hence it is invalid (as file) after qfp is closed;
4577 	**	the qf file is on disk, so set the flag to avoid calling
4578 	**	queueup() with bogus data.
4579 	*/
4580 
4581 	if (bp != buf)
4582 		SM_FREE(bp);
4583 	if (qfp != NULL)
4584 		(void) sm_io_close(qfp, SM_TIME_DEFAULT);
4585 	e->e_lockfp = NULL;
4586 	e->e_flags |= EF_INQUEUE;
4587 	loseqfile(e, err);
4588 	return false;
4589 }
4590 /*
4591 **  PRTSTR -- print a string, "unprintable" characters are shown as \oct
4592 **
4593 **	Parameters:
4594 **		s -- string to print
4595 **		ml -- maximum length of output
4596 **
4597 **	Returns:
4598 **		number of entries
4599 **
4600 **	Side Effects:
4601 **		Prints a string on stdout.
4602 */
4603 
4604 static void prtstr __P((char *, int));
4605 
4606 static void
4607 prtstr(s, ml)
4608 	char *s;
4609 	int ml;
4610 {
4611 	int c;
4612 
4613 	if (s == NULL)
4614 		return;
4615 	while (ml-- > 0 && ((c = *s++) != '\0'))
4616 	{
4617 		if (c == '\\')
4618 		{
4619 			if (ml-- > 0)
4620 			{
4621 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4622 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4623 			}
4624 		}
4625 		else if (isascii(c) && isprint(c))
4626 			(void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4627 		else
4628 		{
4629 			if ((ml -= 3) > 0)
4630 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4631 						     "\\%03o", c & 0xFF);
4632 		}
4633 	}
4634 }
4635 /*
4636 **  PRINTNQE -- print out number of entries in the mail queue
4637 **
4638 **	Parameters:
4639 **		out -- output file pointer.
4640 **		prefix -- string to output in front of each line.
4641 **
4642 **	Returns:
4643 **		none.
4644 */
4645 
4646 void
4647 printnqe(out, prefix)
4648 	SM_FILE_T *out;
4649 	char *prefix;
4650 {
4651 #if SM_CONF_SHM
4652 	int i, k = 0, nrequests = 0;
4653 	bool unknown = false;
4654 
4655 	if (ShmId == SM_SHM_NO_ID)
4656 	{
4657 		if (prefix == NULL)
4658 			(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4659 					"Data unavailable: shared memory not updated\n");
4660 		else
4661 			(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4662 					"%sNOTCONFIGURED:-1\r\n", prefix);
4663 		return;
4664 	}
4665 	for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
4666 	{
4667 		int j;
4668 
4669 		k++;
4670 		for (j = 0; j < Queue[i]->qg_numqueues; j++)
4671 		{
4672 			int n;
4673 
4674 			if (StopRequest)
4675 				stop_sendmail();
4676 
4677 			n = QSHM_ENTRIES(Queue[i]->qg_qpaths[j].qp_idx);
4678 			if (prefix != NULL)
4679 				(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4680 					"%s%s:%d\r\n",
4681 					prefix, qid_printqueue(i, j), n);
4682 			else if (n < 0)
4683 			{
4684 				(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4685 					"%s: unknown number of entries\n",
4686 					qid_printqueue(i, j));
4687 				unknown = true;
4688 			}
4689 			else if (n == 0)
4690 			{
4691 				(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4692 					"%s is empty\n",
4693 					qid_printqueue(i, j));
4694 			}
4695 			else if (n > 0)
4696 			{
4697 				(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4698 					"%s: entries=%d\n",
4699 					qid_printqueue(i, j), n);
4700 				nrequests += n;
4701 				k++;
4702 			}
4703 		}
4704 	}
4705 	if (prefix == NULL && k > 1)
4706 		(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4707 				     "\t\tTotal requests: %d%s\n",
4708 				     nrequests, unknown ? " (about)" : "");
4709 #else /* SM_CONF_SHM */
4710 	if (prefix == NULL)
4711 		(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4712 			     "Data unavailable without shared memory support\n");
4713 	else
4714 		(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4715 			     "%sNOTAVAILABLE:-1\r\n", prefix);
4716 #endif /* SM_CONF_SHM */
4717 }
4718 /*
4719 **  PRINTQUEUE -- print out a representation of the mail queue
4720 **
4721 **	Parameters:
4722 **		none.
4723 **
4724 **	Returns:
4725 **		none.
4726 **
4727 **	Side Effects:
4728 **		Prints a listing of the mail queue on the standard output.
4729 */
4730 
4731 void
4732 printqueue()
4733 {
4734 	int i, k = 0, nrequests = 0;
4735 
4736 	for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
4737 	{
4738 		int j;
4739 
4740 		k++;
4741 		for (j = 0; j < Queue[i]->qg_numqueues; j++)
4742 		{
4743 			if (StopRequest)
4744 				stop_sendmail();
4745 			nrequests += print_single_queue(i, j);
4746 			k++;
4747 		}
4748 	}
4749 	if (k > 1)
4750 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4751 				     "\t\tTotal requests: %d\n",
4752 				     nrequests);
4753 }
4754 /*
4755 **  PRINT_SINGLE_QUEUE -- print out a representation of a single mail queue
4756 **
4757 **	Parameters:
4758 **		qgrp -- the index of the queue group.
4759 **		qdir -- the queue directory.
4760 **
4761 **	Returns:
4762 **		number of requests in mail queue.
4763 **
4764 **	Side Effects:
4765 **		Prints a listing of the mail queue on the standard output.
4766 */
4767 
4768 int
4769 print_single_queue(qgrp, qdir)
4770 	int qgrp;
4771 	int qdir;
4772 {
4773 	register WORK *w;
4774 	SM_FILE_T *f;
4775 	int nrequests;
4776 	char qd[MAXPATHLEN];
4777 	char qddf[MAXPATHLEN];
4778 	char buf[MAXLINE];
4779 
4780 	if (qdir == NOQDIR)
4781 	{
4782 		(void) sm_strlcpy(qd, ".", sizeof(qd));
4783 		(void) sm_strlcpy(qddf, ".", sizeof(qddf));
4784 	}
4785 	else
4786 	{
4787 		(void) sm_strlcpyn(qd, sizeof(qd), 2,
4788 			Queue[qgrp]->qg_qpaths[qdir].qp_name,
4789 			(bitset(QP_SUBQF,
4790 				Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
4791 					? "/qf" : ""));
4792 		(void) sm_strlcpyn(qddf, sizeof(qddf), 2,
4793 			Queue[qgrp]->qg_qpaths[qdir].qp_name,
4794 			(bitset(QP_SUBDF,
4795 				Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
4796 					? "/df" : ""));
4797 	}
4798 
4799 	/*
4800 	**  Check for permission to print the queue
4801 	*/
4802 
4803 	if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
4804 	{
4805 		struct stat st;
4806 #ifdef NGROUPS_MAX
4807 		int n;
4808 		extern GIDSET_T InitialGidSet[NGROUPS_MAX];
4809 #endif /* NGROUPS_MAX */
4810 
4811 		if (stat(qd, &st) < 0)
4812 		{
4813 			syserr("Cannot stat %s",
4814 				qid_printqueue(qgrp, qdir));
4815 			return 0;
4816 		}
4817 #ifdef NGROUPS_MAX
4818 		n = NGROUPS_MAX;
4819 		while (--n >= 0)
4820 		{
4821 			if (InitialGidSet[n] == st.st_gid)
4822 				break;
4823 		}
4824 		if (n < 0 && RealGid != st.st_gid)
4825 #else /* NGROUPS_MAX */
4826 		if (RealGid != st.st_gid)
4827 #endif /* NGROUPS_MAX */
4828 		{
4829 			usrerr("510 You are not permitted to see the queue");
4830 			setstat(EX_NOPERM);
4831 			return 0;
4832 		}
4833 	}
4834 
4835 	/*
4836 	**  Read and order the queue.
4837 	*/
4838 
4839 	nrequests = gatherq(qgrp, qdir, true, NULL, NULL);
4840 	(void) sortq(Queue[qgrp]->qg_maxlist);
4841 
4842 	/*
4843 	**  Print the work list that we have read.
4844 	*/
4845 
4846 	/* first see if there is anything */
4847 	if (nrequests <= 0)
4848 	{
4849 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s is empty\n",
4850 				     qid_printqueue(qgrp, qdir));
4851 		return 0;
4852 	}
4853 
4854 	sm_getla();	/* get load average */
4855 
4856 	(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t\t%s (%d request%s",
4857 			     qid_printqueue(qgrp, qdir),
4858 			     nrequests, nrequests == 1 ? "" : "s");
4859 	if (MaxQueueRun > 0 && nrequests > MaxQueueRun)
4860 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4861 				     ", only %d printed", MaxQueueRun);
4862 	if (Verbose)
4863 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4864 			")\n-----Q-ID----- --Size-- -Priority- ---Q-Time--- --------Sender/Recipient--------\n");
4865 	else
4866 		(void) sm_io_fprintf(smioout,  SM_TIME_DEFAULT,
4867 			")\n-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------\n");
4868 	for (w = WorkQ; w != NULL; w = w->w_next)
4869 	{
4870 		struct stat st;
4871 		auto time_t submittime = 0;
4872 		long dfsize;
4873 		int flags = 0;
4874 		int qfver;
4875 		char quarmsg[MAXLINE];
4876 		char statmsg[MAXLINE];
4877 		char bodytype[MAXNAME + 1];
4878 		char qf[MAXPATHLEN];
4879 
4880 		if (StopRequest)
4881 			stop_sendmail();
4882 
4883 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%13s",
4884 				     w->w_name + 2);
4885 		(void) sm_strlcpyn(qf, sizeof(qf), 3, qd, "/", w->w_name);
4886 		f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B,
4887 			       NULL);
4888 		if (f == NULL)
4889 		{
4890 			if (errno == EPERM)
4891 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4892 						     " (permission denied)\n");
4893 			else if (errno == ENOENT)
4894 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4895 						     " (job completed)\n");
4896 			else
4897 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4898 						     " (%s)\n",
4899 						     sm_errstring(errno));
4900 			errno = 0;
4901 			continue;
4902 		}
4903 		w->w_name[0] = DATAFL_LETTER;
4904 		(void) sm_strlcpyn(qf, sizeof(qf), 3, qddf, "/", w->w_name);
4905 		if (stat(qf, &st) >= 0)
4906 			dfsize = st.st_size;
4907 		else
4908 		{
4909 			ENVELOPE e;
4910 
4911 			/*
4912 			**  Maybe the df file can't be statted because
4913 			**  it is in a different directory than the qf file.
4914 			**  In order to find out, we must read the qf file.
4915 			*/
4916 
4917 			newenvelope(&e, &BlankEnvelope, sm_rpool_new_x(NULL));
4918 			e.e_id = w->w_name + 2;
4919 			e.e_qgrp = qgrp;
4920 			e.e_qdir = qdir;
4921 			dfsize = -1;
4922 			if (readqf(&e, false))
4923 			{
4924 				char *df = queuename(&e, DATAFL_LETTER);
4925 				if (stat(df, &st) >= 0)
4926 					dfsize = st.st_size;
4927 			}
4928 			if (e.e_lockfp != NULL)
4929 			{
4930 				(void) sm_io_close(e.e_lockfp, SM_TIME_DEFAULT);
4931 				e.e_lockfp = NULL;
4932 			}
4933 			clearenvelope(&e, false, e.e_rpool);
4934 			sm_rpool_free(e.e_rpool);
4935 		}
4936 		if (w->w_lock)
4937 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "*");
4938 		else if (QueueMode == QM_LOST)
4939 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "?");
4940 		else if (w->w_tooyoung)
4941 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "-");
4942 		else if (shouldqueue(w->w_pri, w->w_ctime))
4943 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "X");
4944 		else
4945 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " ");
4946 
4947 		errno = 0;
4948 
4949 		quarmsg[0] = '\0';
4950 		statmsg[0] = bodytype[0] = '\0';
4951 		qfver = 0;
4952 		while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL)
4953 		{
4954 			register int i;
4955 			register char *p;
4956 
4957 			if (StopRequest)
4958 				stop_sendmail();
4959 
4960 			fixcrlf(buf, true);
4961 			switch (buf[0])
4962 			{
4963 			  case 'V':	/* queue file version */
4964 				qfver = atoi(&buf[1]);
4965 				break;
4966 
4967 			  case 'M':	/* error message */
4968 				if ((i = strlen(&buf[1])) >= sizeof(statmsg))
4969 					i = sizeof(statmsg) - 1;
4970 				memmove(statmsg, &buf[1], i);
4971 				statmsg[i] = '\0';
4972 				break;
4973 
4974 			  case 'q':	/* quarantine reason */
4975 				if ((i = strlen(&buf[1])) >= sizeof(quarmsg))
4976 					i = sizeof(quarmsg) - 1;
4977 				memmove(quarmsg, &buf[1], i);
4978 				quarmsg[i] = '\0';
4979 				break;
4980 
4981 			  case 'B':	/* body type */
4982 				if ((i = strlen(&buf[1])) >= sizeof(bodytype))
4983 					i = sizeof(bodytype) - 1;
4984 				memmove(bodytype, &buf[1], i);
4985 				bodytype[i] = '\0';
4986 				break;
4987 
4988 			  case 'S':	/* sender name */
4989 				if (Verbose)
4990 				{
4991 					(void) sm_io_fprintf(smioout,
4992 						SM_TIME_DEFAULT,
4993 						"%8ld %10ld%c%.12s ",
4994 						dfsize,
4995 						w->w_pri,
4996 						bitset(EF_WARNING, flags)
4997 							? '+' : ' ',
4998 						ctime(&submittime) + 4);
4999 					prtstr(&buf[1], 78);
5000 				}
5001 				else
5002 				{
5003 					(void) sm_io_fprintf(smioout,
5004 						SM_TIME_DEFAULT,
5005 						"%8ld %.16s ",
5006 						dfsize,
5007 						ctime(&submittime));
5008 					prtstr(&buf[1], 39);
5009 				}
5010 
5011 				if (quarmsg[0] != '\0')
5012 				{
5013 					(void) sm_io_fprintf(smioout,
5014 							     SM_TIME_DEFAULT,
5015 							     "\n     QUARANTINE: %.*s",
5016 							     Verbose ? 100 : 60,
5017 							     quarmsg);
5018 					quarmsg[0] = '\0';
5019 				}
5020 
5021 				if (statmsg[0] != '\0' || bodytype[0] != '\0')
5022 				{
5023 					(void) sm_io_fprintf(smioout,
5024 						SM_TIME_DEFAULT,
5025 						"\n    %10.10s",
5026 						bodytype);
5027 					if (statmsg[0] != '\0')
5028 						(void) sm_io_fprintf(smioout,
5029 							SM_TIME_DEFAULT,
5030 							"   (%.*s)",
5031 							Verbose ? 100 : 60,
5032 							statmsg);
5033 					statmsg[0] = '\0';
5034 				}
5035 				break;
5036 
5037 			  case 'C':	/* controlling user */
5038 				if (Verbose)
5039 					(void) sm_io_fprintf(smioout,
5040 						SM_TIME_DEFAULT,
5041 						"\n\t\t\t\t\t\t(---%.64s---)",
5042 						&buf[1]);
5043 				break;
5044 
5045 			  case 'R':	/* recipient name */
5046 				p = &buf[1];
5047 				if (qfver >= 1)
5048 				{
5049 					p = strchr(p, ':');
5050 					if (p == NULL)
5051 						break;
5052 					p++;
5053 				}
5054 				if (Verbose)
5055 				{
5056 					(void) sm_io_fprintf(smioout,
5057 							SM_TIME_DEFAULT,
5058 							"\n\t\t\t\t\t\t");
5059 					prtstr(p, 71);
5060 				}
5061 				else
5062 				{
5063 					(void) sm_io_fprintf(smioout,
5064 							SM_TIME_DEFAULT,
5065 							"\n\t\t\t\t\t ");
5066 					prtstr(p, 38);
5067 				}
5068 				if (Verbose && statmsg[0] != '\0')
5069 				{
5070 					(void) sm_io_fprintf(smioout,
5071 							SM_TIME_DEFAULT,
5072 							"\n\t\t (%.100s)",
5073 							statmsg);
5074 					statmsg[0] = '\0';
5075 				}
5076 				break;
5077 
5078 			  case 'T':	/* creation time */
5079 				submittime = atol(&buf[1]);
5080 				break;
5081 
5082 			  case 'F':	/* flag bits */
5083 				for (p = &buf[1]; *p != '\0'; p++)
5084 				{
5085 					switch (*p)
5086 					{
5087 					  case 'w':
5088 						flags |= EF_WARNING;
5089 						break;
5090 					}
5091 				}
5092 			}
5093 		}
5094 		if (submittime == (time_t) 0)
5095 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
5096 					     " (no control file)");
5097 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n");
5098 		(void) sm_io_close(f, SM_TIME_DEFAULT);
5099 	}
5100 	return nrequests;
5101 }
5102 
5103 /*
5104 **  QUEUE_LETTER -- get the proper queue letter for the current QueueMode.
5105 **
5106 **	Parameters:
5107 **		e -- envelope to build it in/from.
5108 **		type -- the file type, used as the first character
5109 **			of the file name.
5110 **
5111 **	Returns:
5112 **		the letter to use
5113 */
5114 
5115 static char
5116 queue_letter(e, type)
5117 	ENVELOPE *e;
5118 	int type;
5119 {
5120 	/* Change type according to QueueMode */
5121 	if (type == ANYQFL_LETTER)
5122 	{
5123 		if (e->e_quarmsg != NULL)
5124 			type = QUARQF_LETTER;
5125 		else
5126 		{
5127 			switch (QueueMode)
5128 			{
5129 			  case QM_NORMAL:
5130 				type = NORMQF_LETTER;
5131 				break;
5132 
5133 			  case QM_QUARANTINE:
5134 				type = QUARQF_LETTER;
5135 				break;
5136 
5137 			  case QM_LOST:
5138 				type = LOSEQF_LETTER;
5139 				break;
5140 
5141 			  default:
5142 				/* should never happen */
5143 				abort();
5144 				/* NOTREACHED */
5145 			}
5146 		}
5147 	}
5148 	return type;
5149 }
5150 
5151 /*
5152 **  QUEUENAME -- build a file name in the queue directory for this envelope.
5153 **
5154 **	Parameters:
5155 **		e -- envelope to build it in/from.
5156 **		type -- the file type, used as the first character
5157 **			of the file name.
5158 **
5159 **	Returns:
5160 **		a pointer to the queue name (in a static buffer).
5161 **
5162 **	Side Effects:
5163 **		If no id code is already assigned, queuename() will
5164 **		assign an id code with assign_queueid().  If no queue
5165 **		directory is assigned, one will be set with setnewqueue().
5166 */
5167 
5168 char *
5169 queuename(e, type)
5170 	register ENVELOPE *e;
5171 	int type;
5172 {
5173 	int qd, qg;
5174 	char *sub = "/";
5175 	char pref[3];
5176 	static char buf[MAXPATHLEN];
5177 
5178 	/* Assign an ID if needed */
5179 	if (e->e_id == NULL)
5180 		assign_queueid(e);
5181 	type = queue_letter(e, type);
5182 
5183 	/* begin of filename */
5184 	pref[0] = (char) type;
5185 	pref[1] = 'f';
5186 	pref[2] = '\0';
5187 
5188 	/* Assign a queue group/directory if needed */
5189 	if (type == XSCRPT_LETTER)
5190 	{
5191 		/*
5192 		**  We don't want to call setnewqueue() if we are fetching
5193 		**  the pathname of the transcript file, because setnewqueue
5194 		**  chooses a queue, and sometimes we need to write to the
5195 		**  transcript file before we have gathered enough information
5196 		**  to choose a queue.
5197 		*/
5198 
5199 		if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR)
5200 		{
5201 			if (e->e_qgrp != NOQGRP && e->e_qdir != NOQDIR)
5202 			{
5203 				e->e_xfqgrp = e->e_qgrp;
5204 				e->e_xfqdir = e->e_qdir;
5205 			}
5206 			else
5207 			{
5208 				e->e_xfqgrp = 0;
5209 				if (Queue[e->e_xfqgrp]->qg_numqueues <= 1)
5210 					e->e_xfqdir = 0;
5211 				else
5212 				{
5213 					e->e_xfqdir = get_rand_mod(
5214 					      Queue[e->e_xfqgrp]->qg_numqueues);
5215 				}
5216 			}
5217 		}
5218 		qd = e->e_xfqdir;
5219 		qg = e->e_xfqgrp;
5220 	}
5221 	else
5222 	{
5223 		if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR)
5224 			(void) setnewqueue(e);
5225 		if (type ==  DATAFL_LETTER)
5226 		{
5227 			qd = e->e_dfqdir;
5228 			qg = e->e_dfqgrp;
5229 		}
5230 		else
5231 		{
5232 			qd = e->e_qdir;
5233 			qg = e->e_qgrp;
5234 		}
5235 	}
5236 
5237 	/* xf files always have a valid qd and qg picked above */
5238 	if ((qd == NOQDIR || qg == NOQGRP) && type != XSCRPT_LETTER)
5239 		(void) sm_strlcpyn(buf, sizeof(buf), 2, pref, e->e_id);
5240 	else
5241 	{
5242 		switch (type)
5243 		{
5244 		  case DATAFL_LETTER:
5245 			if (bitset(QP_SUBDF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5246 				sub = "/df/";
5247 			break;
5248 
5249 		  case QUARQF_LETTER:
5250 		  case TEMPQF_LETTER:
5251 		  case NEWQFL_LETTER:
5252 		  case LOSEQF_LETTER:
5253 		  case NORMQF_LETTER:
5254 			if (bitset(QP_SUBQF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5255 				sub = "/qf/";
5256 			break;
5257 
5258 		  case XSCRPT_LETTER:
5259 			if (bitset(QP_SUBXF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5260 				sub = "/xf/";
5261 			break;
5262 
5263 		  default:
5264 			sm_abort("queuename: bad queue file type %d", type);
5265 		}
5266 
5267 		(void) sm_strlcpyn(buf, sizeof(buf), 4,
5268 				Queue[qg]->qg_qpaths[qd].qp_name,
5269 				sub, pref, e->e_id);
5270 	}
5271 
5272 	if (tTd(7, 2))
5273 		sm_dprintf("queuename: %s\n", buf);
5274 	return buf;
5275 }
5276 
5277 /*
5278 **  INIT_QID_ALG -- Initialize the (static) parameters that are used to
5279 **	generate a queue ID.
5280 **
5281 **	This function is called by the daemon to reset
5282 **	LastQueueTime and LastQueuePid which are used by assign_queueid().
5283 **	Otherwise the algorithm may cause problems because
5284 **	LastQueueTime and LastQueuePid are set indirectly by main()
5285 **	before the daemon process is started, hence LastQueuePid is not
5286 **	the pid of the daemon and therefore a child of the daemon can
5287 **	actually have the same pid as LastQueuePid which means the section
5288 **	in  assign_queueid():
5289 **	* see if we need to get a new base time/pid *
5290 **	is NOT triggered which will cause the same queue id to be generated.
5291 **
5292 **	Parameters:
5293 **		none
5294 **
5295 **	Returns:
5296 **		none.
5297 */
5298 
5299 void
5300 init_qid_alg()
5301 {
5302 	LastQueueTime = 0;
5303 	LastQueuePid = -1;
5304 }
5305 
5306 /*
5307 **  ASSIGN_QUEUEID -- assign a queue ID for this envelope.
5308 **
5309 **	Assigns an id code if one does not already exist.
5310 **	This code assumes that nothing will remain in the queue for
5311 **	longer than 60 years.  It is critical that files with the given
5312 **	name do not already exist in the queue.
5313 **	[No longer initializes e_qdir to NOQDIR.]
5314 **
5315 **	Parameters:
5316 **		e -- envelope to set it in.
5317 **
5318 **	Returns:
5319 **		none.
5320 */
5321 
5322 static const char QueueIdChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
5323 # define QIC_LEN	60
5324 # define QIC_LEN_R	62
5325 
5326 /*
5327 **  Note: the length is "officially" 60 because minutes and seconds are
5328 **	usually only 0-59.  However (Linux):
5329 **       tm_sec The number of seconds after the minute, normally in
5330 **		the range 0 to 59, but can be up to 61 to allow for
5331 **		leap seconds.
5332 **	Hence the real length of the string is 62 to take this into account.
5333 **	Alternatively % QIC_LEN can (should) be used for access everywhere.
5334 */
5335 
5336 # define queuenextid() CurrentPid
5337 
5338 
5339 void
5340 assign_queueid(e)
5341 	register ENVELOPE *e;
5342 {
5343 	pid_t pid = queuenextid();
5344 	static int cX = 0;
5345 	static long random_offset;
5346 	struct tm *tm;
5347 	char idbuf[MAXQFNAME - 2];
5348 	int seq;
5349 
5350 	if (e->e_id != NULL)
5351 		return;
5352 
5353 	/* see if we need to get a new base time/pid */
5354 	if (cX >= QIC_LEN * QIC_LEN || LastQueueTime == 0 ||
5355 	    LastQueuePid != pid)
5356 	{
5357 		time_t then = LastQueueTime;
5358 
5359 		/* if the first time through, pick a random offset */
5360 		if (LastQueueTime == 0)
5361 			random_offset = get_random();
5362 
5363 		while ((LastQueueTime = curtime()) == then &&
5364 		       LastQueuePid == pid)
5365 		{
5366 			(void) sleep(1);
5367 		}
5368 		LastQueuePid = queuenextid();
5369 		cX = 0;
5370 	}
5371 
5372 	/*
5373 	**  Generate a new sequence number between 0 and QIC_LEN*QIC_LEN-1.
5374 	**  This lets us generate up to QIC_LEN*QIC_LEN unique queue ids
5375 	**  per second, per process.  With envelope splitting,
5376 	**  a single message can consume many queue ids.
5377 	*/
5378 
5379 	seq = (int)((cX + random_offset) % (QIC_LEN * QIC_LEN));
5380 	++cX;
5381 	if (tTd(7, 50))
5382 		sm_dprintf("assign_queueid: random_offset = %ld (%d)\n",
5383 			random_offset, seq);
5384 
5385 	tm = gmtime(&LastQueueTime);
5386 	idbuf[0] = QueueIdChars[tm->tm_year % QIC_LEN];
5387 	idbuf[1] = QueueIdChars[tm->tm_mon];
5388 	idbuf[2] = QueueIdChars[tm->tm_mday];
5389 	idbuf[3] = QueueIdChars[tm->tm_hour];
5390 	idbuf[4] = QueueIdChars[tm->tm_min % QIC_LEN_R];
5391 	idbuf[5] = QueueIdChars[tm->tm_sec % QIC_LEN_R];
5392 	idbuf[6] = QueueIdChars[seq / QIC_LEN];
5393 	idbuf[7] = QueueIdChars[seq % QIC_LEN];
5394 	(void) sm_snprintf(&idbuf[8], sizeof(idbuf) - 8, "%06d",
5395 			   (int) LastQueuePid);
5396 	e->e_id = sm_rpool_strdup_x(e->e_rpool, idbuf);
5397 	macdefine(&e->e_macro, A_PERM, 'i', e->e_id);
5398 #if 0
5399 	/* XXX: inherited from MainEnvelope */
5400 	e->e_qgrp = NOQGRP;  /* too early to do anything else */
5401 	e->e_qdir = NOQDIR;
5402 	e->e_xfqgrp = NOQGRP;
5403 #endif /* 0 */
5404 
5405 	/* New ID means it's not on disk yet */
5406 	e->e_qfletter = '\0';
5407 
5408 	if (tTd(7, 1))
5409 		sm_dprintf("assign_queueid: assigned id %s, e=%p\n",
5410 			e->e_id, e);
5411 	if (LogLevel > 93)
5412 		sm_syslog(LOG_DEBUG, e->e_id, "assigned id");
5413 }
5414 /*
5415 **  SYNC_QUEUE_TIME -- Assure exclusive PID in any given second
5416 **
5417 **	Make sure one PID can't be used by two processes in any one second.
5418 **
5419 **		If the system rotates PIDs fast enough, may get the
5420 **		same pid in the same second for two distinct processes.
5421 **		This will interfere with the queue file naming system.
5422 **
5423 **	Parameters:
5424 **		none
5425 **
5426 **	Returns:
5427 **		none
5428 */
5429 
5430 void
5431 sync_queue_time()
5432 {
5433 #if FAST_PID_RECYCLE
5434 	if (OpMode != MD_TEST &&
5435 	    OpMode != MD_VERIFY &&
5436 	    LastQueueTime > 0 &&
5437 	    LastQueuePid == CurrentPid &&
5438 	    curtime() == LastQueueTime)
5439 		(void) sleep(1);
5440 #endif /* FAST_PID_RECYCLE */
5441 }
5442 /*
5443 **  UNLOCKQUEUE -- unlock the queue entry for a specified envelope
5444 **
5445 **	Parameters:
5446 **		e -- the envelope to unlock.
5447 **
5448 **	Returns:
5449 **		none
5450 **
5451 **	Side Effects:
5452 **		unlocks the queue for `e'.
5453 */
5454 
5455 void
5456 unlockqueue(e)
5457 	ENVELOPE *e;
5458 {
5459 	if (tTd(51, 4))
5460 		sm_dprintf("unlockqueue(%s)\n",
5461 			e->e_id == NULL ? "NOQUEUE" : e->e_id);
5462 
5463 
5464 	/* if there is a lock file in the envelope, close it */
5465 	if (e->e_lockfp != NULL)
5466 		(void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
5467 	e->e_lockfp = NULL;
5468 
5469 	/* don't create a queue id if we don't already have one */
5470 	if (e->e_id == NULL)
5471 		return;
5472 
5473 	/* remove the transcript */
5474 	if (LogLevel > 87)
5475 		sm_syslog(LOG_DEBUG, e->e_id, "unlock");
5476 	if (!tTd(51, 104))
5477 		(void) xunlink(queuename(e, XSCRPT_LETTER));
5478 }
5479 /*
5480 **  SETCTLUSER -- create a controlling address
5481 **
5482 **	Create a fake "address" given only a local login name; this is
5483 **	used as a "controlling user" for future recipient addresses.
5484 **
5485 **	Parameters:
5486 **		user -- the user name of the controlling user.
5487 **		qfver -- the version stamp of this queue file.
5488 **		e -- envelope
5489 **
5490 **	Returns:
5491 **		An address descriptor for the controlling user,
5492 **		using storage allocated from e->e_rpool.
5493 **
5494 */
5495 
5496 static ADDRESS *
5497 setctluser(user, qfver, e)
5498 	char *user;
5499 	int qfver;
5500 	ENVELOPE *e;
5501 {
5502 	register ADDRESS *a;
5503 	struct passwd *pw;
5504 	char *p;
5505 
5506 	/*
5507 	**  See if this clears our concept of controlling user.
5508 	*/
5509 
5510 	if (user == NULL || *user == '\0')
5511 		return NULL;
5512 
5513 	/*
5514 	**  Set up addr fields for controlling user.
5515 	*/
5516 
5517 	a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof(*a));
5518 	memset((char *) a, '\0', sizeof(*a));
5519 
5520 	if (*user == ':')
5521 	{
5522 		p = &user[1];
5523 		a->q_user = sm_rpool_strdup_x(e->e_rpool, p);
5524 	}
5525 	else
5526 	{
5527 		p = strtok(user, ":");
5528 		a->q_user = sm_rpool_strdup_x(e->e_rpool, user);
5529 		if (qfver >= 2)
5530 		{
5531 			if ((p = strtok(NULL, ":")) != NULL)
5532 				a->q_uid = atoi(p);
5533 			if ((p = strtok(NULL, ":")) != NULL)
5534 				a->q_gid = atoi(p);
5535 			if ((p = strtok(NULL, ":")) != NULL)
5536 			{
5537 				char *o;
5538 
5539 				a->q_flags |= QGOODUID;
5540 
5541 				/* if there is another ':': restore it */
5542 				if ((o = strtok(NULL, ":")) != NULL && o > p)
5543 					o[-1] = ':';
5544 			}
5545 		}
5546 		else if ((pw = sm_getpwnam(user)) != NULL)
5547 		{
5548 			if (*pw->pw_dir == '\0')
5549 				a->q_home = NULL;
5550 			else if (strcmp(pw->pw_dir, "/") == 0)
5551 				a->q_home = "";
5552 			else
5553 				a->q_home = sm_rpool_strdup_x(e->e_rpool, pw->pw_dir);
5554 			a->q_uid = pw->pw_uid;
5555 			a->q_gid = pw->pw_gid;
5556 			a->q_flags |= QGOODUID;
5557 		}
5558 	}
5559 
5560 	a->q_flags |= QPRIMARY;		/* flag as a "ctladdr" */
5561 	a->q_mailer = LocalMailer;
5562 	if (p == NULL)
5563 		a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user);
5564 	else
5565 		a->q_paddr = sm_rpool_strdup_x(e->e_rpool, p);
5566 	return a;
5567 }
5568 /*
5569 **  LOSEQFILE -- rename queue file with LOSEQF_LETTER & try to let someone know
5570 **
5571 **	Parameters:
5572 **		e -- the envelope (e->e_id will be used).
5573 **		why -- reported to whomever can hear.
5574 **
5575 **	Returns:
5576 **		none.
5577 */
5578 
5579 void
5580 loseqfile(e, why)
5581 	register ENVELOPE *e;
5582 	char *why;
5583 {
5584 	bool loseit = true;
5585 	char *p;
5586 	char buf[MAXPATHLEN];
5587 
5588 	if (e == NULL || e->e_id == NULL)
5589 		return;
5590 	p = queuename(e, ANYQFL_LETTER);
5591 	if (sm_strlcpy(buf, p, sizeof(buf)) >= sizeof(buf))
5592 		return;
5593 	if (!bitset(EF_INQUEUE, e->e_flags))
5594 		queueup(e, false, true);
5595 	else if (QueueMode == QM_LOST)
5596 		loseit = false;
5597 
5598 	/* if already lost, no need to re-lose */
5599 	if (loseit)
5600 	{
5601 		p = queuename(e, LOSEQF_LETTER);
5602 		if (rename(buf, p) < 0)
5603 			syserr("cannot rename(%s, %s), uid=%d",
5604 			       buf, p, (int) geteuid());
5605 		else if (LogLevel > 0)
5606 			sm_syslog(LOG_ALERT, e->e_id,
5607 				  "Losing %s: %s", buf, why);
5608 	}
5609 	if (e->e_dfp != NULL)
5610 	{
5611 		(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
5612 		e->e_dfp = NULL;
5613 	}
5614 	e->e_flags &= ~EF_HAS_DF;
5615 }
5616 /*
5617 **  NAME2QID -- translate a queue group name to a queue group id
5618 **
5619 **	Parameters:
5620 **		queuename -- name of queue group.
5621 **
5622 **	Returns:
5623 **		queue group id if found.
5624 **		NOQGRP otherwise.
5625 */
5626 
5627 int
5628 name2qid(queuename)
5629 	char *queuename;
5630 {
5631 	register STAB *s;
5632 
5633 	s = stab(queuename, ST_QUEUE, ST_FIND);
5634 	if (s == NULL)
5635 		return NOQGRP;
5636 	return s->s_quegrp->qg_index;
5637 }
5638 /*
5639 **  QID_PRINTNAME -- create externally printable version of queue id
5640 **
5641 **	Parameters:
5642 **		e -- the envelope.
5643 **
5644 **	Returns:
5645 **		a printable version
5646 */
5647 
5648 char *
5649 qid_printname(e)
5650 	ENVELOPE *e;
5651 {
5652 	char *id;
5653 	static char idbuf[MAXQFNAME + 34];
5654 
5655 	if (e == NULL)
5656 		return "";
5657 
5658 	if (e->e_id == NULL)
5659 		id = "";
5660 	else
5661 		id = e->e_id;
5662 
5663 	if (e->e_qdir == NOQDIR)
5664 		return id;
5665 
5666 	(void) sm_snprintf(idbuf, sizeof(idbuf), "%.32s/%s",
5667 			   Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_name,
5668 			   id);
5669 	return idbuf;
5670 }
5671 /*
5672 **  QID_PRINTQUEUE -- create full version of queue directory for data files
5673 **
5674 **	Parameters:
5675 **		qgrp -- index in queue group.
5676 **		qdir -- the short version of the queue directory
5677 **
5678 **	Returns:
5679 **		the full pathname to the queue (might point to a static var)
5680 */
5681 
5682 char *
5683 qid_printqueue(qgrp, qdir)
5684 	int qgrp;
5685 	int qdir;
5686 {
5687 	char *subdir;
5688 	static char dir[MAXPATHLEN];
5689 
5690 	if (qdir == NOQDIR)
5691 		return Queue[qgrp]->qg_qdir;
5692 
5693 	if (strcmp(Queue[qgrp]->qg_qpaths[qdir].qp_name, ".") == 0)
5694 		subdir = NULL;
5695 	else
5696 		subdir = Queue[qgrp]->qg_qpaths[qdir].qp_name;
5697 
5698 	(void) sm_strlcpyn(dir, sizeof(dir), 4,
5699 			Queue[qgrp]->qg_qdir,
5700 			subdir == NULL ? "" : "/",
5701 			subdir == NULL ? "" : subdir,
5702 			(bitset(QP_SUBDF,
5703 				Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
5704 					? "/df" : ""));
5705 	return dir;
5706 }
5707 
5708 /*
5709 **  PICKQDIR -- Pick a queue directory from a queue group
5710 **
5711 **	Parameters:
5712 **		qg -- queue group
5713 **		fsize -- file size in bytes
5714 **		e -- envelope, or NULL
5715 **
5716 **	Result:
5717 **		NOQDIR if no queue directory in qg has enough free space to
5718 **		hold a file of size 'fsize', otherwise the index of
5719 **		a randomly selected queue directory which resides on a
5720 **		file system with enough disk space.
5721 **		XXX This could be extended to select a queuedir with
5722 **			a few (the fewest?) number of entries. That data
5723 **			is available if shared memory is used.
5724 **
5725 **	Side Effects:
5726 **		If the request fails and e != NULL then sm_syslog is called.
5727 */
5728 
5729 int
5730 pickqdir(qg, fsize, e)
5731 	QUEUEGRP *qg;
5732 	long fsize;
5733 	ENVELOPE *e;
5734 {
5735 	int qdir;
5736 	int i;
5737 	long avail = 0;
5738 
5739 	/* Pick a random directory, as a starting point. */
5740 	if (qg->qg_numqueues <= 1)
5741 		qdir = 0;
5742 	else
5743 		qdir = get_rand_mod(qg->qg_numqueues);
5744 
5745 	if (MinBlocksFree <= 0 && fsize <= 0)
5746 		return qdir;
5747 
5748 	/*
5749 	**  Now iterate over the queue directories,
5750 	**  looking for a directory with enough space for this message.
5751 	*/
5752 
5753 	i = qdir;
5754 	do
5755 	{
5756 		QPATHS *qp = &qg->qg_qpaths[i];
5757 		long needed = 0;
5758 		long fsavail = 0;
5759 
5760 		if (fsize > 0)
5761 			needed += fsize / FILE_SYS_BLKSIZE(qp->qp_fsysidx)
5762 				  + ((fsize % FILE_SYS_BLKSIZE(qp->qp_fsysidx)
5763 				      > 0) ? 1 : 0);
5764 		if (MinBlocksFree > 0)
5765 			needed += MinBlocksFree;
5766 		fsavail = FILE_SYS_AVAIL(qp->qp_fsysidx);
5767 #if SM_CONF_SHM
5768 		if (fsavail <= 0)
5769 		{
5770 			long blksize;
5771 
5772 			/*
5773 			**  might be not correctly updated,
5774 			**  let's try to get the info directly.
5775 			*/
5776 
5777 			fsavail = freediskspace(FILE_SYS_NAME(qp->qp_fsysidx),
5778 						&blksize);
5779 			if (fsavail < 0)
5780 				fsavail = 0;
5781 		}
5782 #endif /* SM_CONF_SHM */
5783 		if (needed <= fsavail)
5784 			return i;
5785 		if (avail < fsavail)
5786 			avail = fsavail;
5787 
5788 		if (qg->qg_numqueues > 0)
5789 			i = (i + 1) % qg->qg_numqueues;
5790 	} while (i != qdir);
5791 
5792 	if (e != NULL && LogLevel > 0)
5793 		sm_syslog(LOG_ALERT, e->e_id,
5794 			"low on space (%s needs %ld bytes + %ld blocks in %s), max avail: %ld",
5795 			CurHostName == NULL ? "SMTP-DAEMON" : CurHostName,
5796 			fsize, MinBlocksFree,
5797 			qg->qg_qdir, avail);
5798 	return NOQDIR;
5799 }
5800 /*
5801 **  SETNEWQUEUE -- Sets a new queue group and directory
5802 **
5803 **	Assign a queue group and directory to an envelope and store the
5804 **	directory in e->e_qdir.
5805 **
5806 **	Parameters:
5807 **		e -- envelope to assign a queue for.
5808 **
5809 **	Returns:
5810 **		true if successful
5811 **		false otherwise
5812 **
5813 **	Side Effects:
5814 **		On success, e->e_qgrp and e->e_qdir are non-negative.
5815 **		On failure (not enough disk space),
5816 **		e->qgrp = NOQGRP, e->e_qdir = NOQDIR
5817 **		and usrerr() is invoked (which could raise an exception).
5818 */
5819 
5820 bool
5821 setnewqueue(e)
5822 	ENVELOPE *e;
5823 {
5824 	if (tTd(41, 20))
5825 		sm_dprintf("setnewqueue: called\n");
5826 
5827 	/* not set somewhere else */
5828 	if (e->e_qgrp == NOQGRP)
5829 	{
5830 		ADDRESS *q;
5831 
5832 		/*
5833 		**  Use the queue group of the "first" recipient, as set by
5834 		**  the "queuegroup" rule set.  If that is not defined, then
5835 		**  use the queue group of the mailer of the first recipient.
5836 		**  If that is not defined either, then use the default
5837 		**  queue group.
5838 		**  Notice: "first" depends on the sorting of sendqueue
5839 		**  in recipient().
5840 		**  To avoid problems with "bad" recipients look
5841 		**  for a valid address first.
5842 		*/
5843 
5844 		q = e->e_sendqueue;
5845 		while (q != NULL &&
5846 		       (QS_IS_BADADDR(q->q_state) || QS_IS_DEAD(q->q_state)))
5847 		{
5848 			q = q->q_next;
5849 		}
5850 		if (q == NULL)
5851 			e->e_qgrp = 0;
5852 		else if (q->q_qgrp >= 0)
5853 			e->e_qgrp = q->q_qgrp;
5854 		else if (q->q_mailer != NULL &&
5855 			 ISVALIDQGRP(q->q_mailer->m_qgrp))
5856 			e->e_qgrp = q->q_mailer->m_qgrp;
5857 		else
5858 			e->e_qgrp = 0;
5859 		e->e_dfqgrp = e->e_qgrp;
5860 	}
5861 
5862 	if (ISVALIDQDIR(e->e_qdir) && ISVALIDQDIR(e->e_dfqdir))
5863 	{
5864 		if (tTd(41, 20))
5865 			sm_dprintf("setnewqueue: e_qdir already assigned (%s)\n",
5866 				qid_printqueue(e->e_qgrp, e->e_qdir));
5867 		return true;
5868 	}
5869 
5870 	filesys_update();
5871 	e->e_qdir = pickqdir(Queue[e->e_qgrp], e->e_msgsize, e);
5872 	if (e->e_qdir == NOQDIR)
5873 	{
5874 		e->e_qgrp = NOQGRP;
5875 		if (!bitset(EF_FATALERRS, e->e_flags))
5876 			usrerr("452 4.4.5 Insufficient disk space; try again later");
5877 		e->e_flags |= EF_FATALERRS;
5878 		return false;
5879 	}
5880 
5881 	if (tTd(41, 3))
5882 		sm_dprintf("setnewqueue: Assigned queue directory %s\n",
5883 			qid_printqueue(e->e_qgrp, e->e_qdir));
5884 
5885 	if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR)
5886 	{
5887 		e->e_xfqgrp = e->e_qgrp;
5888 		e->e_xfqdir = e->e_qdir;
5889 	}
5890 	e->e_dfqdir = e->e_qdir;
5891 	return true;
5892 }
5893 /*
5894 **  CHKQDIR -- check a queue directory
5895 **
5896 **	Parameters:
5897 **		name -- name of queue directory
5898 **		sff -- flags for safefile()
5899 **
5900 **	Returns:
5901 **		is it a queue directory?
5902 */
5903 
5904 static bool chkqdir __P((char *, long));
5905 
5906 static bool
5907 chkqdir(name, sff)
5908 	char *name;
5909 	long sff;
5910 {
5911 	struct stat statb;
5912 	int i;
5913 
5914 	/* skip over . and .. directories */
5915 	if (name[0] == '.' &&
5916 	    (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
5917 		return false;
5918 #if HASLSTAT
5919 	if (lstat(name, &statb) < 0)
5920 #else /* HASLSTAT */
5921 	if (stat(name, &statb) < 0)
5922 #endif /* HASLSTAT */
5923 	{
5924 		if (tTd(41, 2))
5925 			sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
5926 				   name, sm_errstring(errno));
5927 		return false;
5928 	}
5929 #if HASLSTAT
5930 	if (S_ISLNK(statb.st_mode))
5931 	{
5932 		/*
5933 		**  For a symlink we need to make sure the
5934 		**  target is a directory
5935 		*/
5936 
5937 		if (stat(name, &statb) < 0)
5938 		{
5939 			if (tTd(41, 2))
5940 				sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
5941 					   name, sm_errstring(errno));
5942 			return false;
5943 		}
5944 	}
5945 #endif /* HASLSTAT */
5946 
5947 	if (!S_ISDIR(statb.st_mode))
5948 	{
5949 		if (tTd(41, 2))
5950 			sm_dprintf("chkqdir: \"%s\": Not a directory\n",
5951 				name);
5952 		return false;
5953 	}
5954 
5955 	/* Print a warning if unsafe (but still use it) */
5956 	/* XXX do this only if we want the warning? */
5957 	i = safedirpath(name, RunAsUid, RunAsGid, NULL, sff, 0, 0);
5958 	if (i != 0)
5959 	{
5960 		if (tTd(41, 2))
5961 			sm_dprintf("chkqdir: \"%s\": Not safe: %s\n",
5962 				   name, sm_errstring(i));
5963 #if _FFR_CHK_QUEUE
5964 		if (LogLevel > 8)
5965 			sm_syslog(LOG_WARNING, NOQID,
5966 				  "queue directory \"%s\": Not safe: %s",
5967 				  name, sm_errstring(i));
5968 #endif /* _FFR_CHK_QUEUE */
5969 	}
5970 	return true;
5971 }
5972 /*
5973 **  MULTIQUEUE_CACHE -- cache a list of paths to queues.
5974 **
5975 **	Each potential queue is checked as the cache is built.
5976 **	Thereafter, each is blindly trusted.
5977 **	Note that we can be called again after a timeout to rebuild
5978 **	(although code for that is not ready yet).
5979 **
5980 **	Parameters:
5981 **		basedir -- base of all queue directories.
5982 **		blen -- strlen(basedir).
5983 **		qg -- queue group.
5984 **		qn -- number of queue directories already cached.
5985 **		phash -- pointer to hash value over queue dirs.
5986 #if SM_CONF_SHM
5987 **			only used if shared memory is active.
5988 #endif * SM_CONF_SHM *
5989 **
5990 **	Returns:
5991 **		new number of queue directories.
5992 */
5993 
5994 #define INITIAL_SLOTS	20
5995 #define ADD_SLOTS	10
5996 
5997 static int
5998 multiqueue_cache(basedir, blen, qg, qn, phash)
5999 	char *basedir;
6000 	int blen;
6001 	QUEUEGRP *qg;
6002 	int qn;
6003 	unsigned int *phash;
6004 {
6005 	char *cp;
6006 	int i, len;
6007 	int slotsleft = 0;
6008 	long sff = SFF_ANYFILE;
6009 	char qpath[MAXPATHLEN];
6010 	char subdir[MAXPATHLEN];
6011 	char prefix[MAXPATHLEN];	/* dir relative to basedir */
6012 
6013 	if (tTd(41, 20))
6014 		sm_dprintf("multiqueue_cache: called\n");
6015 
6016 	/* Initialize to current directory */
6017 	prefix[0] = '.';
6018 	prefix[1] = '\0';
6019 	if (qg->qg_numqueues != 0 && qg->qg_qpaths != NULL)
6020 	{
6021 		for (i = 0; i < qg->qg_numqueues; i++)
6022 		{
6023 			if (qg->qg_qpaths[i].qp_name != NULL)
6024 				(void) sm_free(qg->qg_qpaths[i].qp_name); /* XXX */
6025 		}
6026 		(void) sm_free((char *) qg->qg_qpaths); /* XXX */
6027 		qg->qg_qpaths = NULL;
6028 		qg->qg_numqueues = 0;
6029 	}
6030 
6031 	/* If running as root, allow safedirpath() checks to use privs */
6032 	if (RunAsUid == 0)
6033 		sff |= SFF_ROOTOK;
6034 #if _FFR_CHK_QUEUE
6035 	sff |= SFF_SAFEDIRPATH|SFF_NOWWFILES;
6036 	if (!UseMSP)
6037 		sff |= SFF_NOGWFILES;
6038 #endif /* _FFR_CHK_QUEUE */
6039 
6040 	if (!SM_IS_DIR_START(qg->qg_qdir))
6041 	{
6042 		/*
6043 		**  XXX we could add basedir, but then we have to realloc()
6044 		**  the string... Maybe another time.
6045 		*/
6046 
6047 		syserr("QueuePath %s not absolute", qg->qg_qdir);
6048 		ExitStat = EX_CONFIG;
6049 		return qn;
6050 	}
6051 
6052 	/* qpath: directory of current workgroup */
6053 	len = sm_strlcpy(qpath, qg->qg_qdir, sizeof(qpath));
6054 	if (len >= sizeof(qpath))
6055 	{
6056 		syserr("QueuePath %.256s too long (%d max)",
6057 		       qg->qg_qdir, (int) sizeof(qpath));
6058 		ExitStat = EX_CONFIG;
6059 		return qn;
6060 	}
6061 
6062 	/* begin of qpath must be same as basedir */
6063 	if (strncmp(basedir, qpath, blen) != 0 &&
6064 	    (strncmp(basedir, qpath, blen - 1) != 0 || len != blen - 1))
6065 	{
6066 		syserr("QueuePath %s not subpath of QueueDirectory %s",
6067 			qpath, basedir);
6068 		ExitStat = EX_CONFIG;
6069 		return qn;
6070 	}
6071 
6072 	/* Do we have a nested subdirectory? */
6073 	if (blen < len && SM_FIRST_DIR_DELIM(qg->qg_qdir + blen) != NULL)
6074 	{
6075 
6076 		/* Copy subdirectory into prefix for later use */
6077 		if (sm_strlcpy(prefix, qg->qg_qdir + blen, sizeof(prefix)) >=
6078 		    sizeof(prefix))
6079 		{
6080 			syserr("QueuePath %.256s too long (%d max)",
6081 				qg->qg_qdir, (int) sizeof(qpath));
6082 			ExitStat = EX_CONFIG;
6083 			return qn;
6084 		}
6085 		cp = SM_LAST_DIR_DELIM(prefix);
6086 		SM_ASSERT(cp != NULL);
6087 		*cp = '\0';	/* cut off trailing / */
6088 	}
6089 
6090 	/* This is guaranteed by the basedir check above */
6091 	SM_ASSERT(len >= blen - 1);
6092 	cp = &qpath[len - 1];
6093 	if (*cp == '*')
6094 	{
6095 		register DIR *dp;
6096 		register struct dirent *d;
6097 		int off;
6098 		char *delim;
6099 		char relpath[MAXPATHLEN];
6100 
6101 		*cp = '\0';	/* Overwrite wildcard */
6102 		if ((cp = SM_LAST_DIR_DELIM(qpath)) == NULL)
6103 		{
6104 			syserr("QueueDirectory: can not wildcard relative path");
6105 			if (tTd(41, 2))
6106 				sm_dprintf("multiqueue_cache: \"%s*\": Can not wildcard relative path.\n",
6107 					qpath);
6108 			ExitStat = EX_CONFIG;
6109 			return qn;
6110 		}
6111 		if (cp == qpath)
6112 		{
6113 			/*
6114 			**  Special case of top level wildcard, like /foo*
6115 			**	Change to //foo*
6116 			*/
6117 
6118 			(void) sm_strlcpy(qpath + 1, qpath, sizeof(qpath) - 1);
6119 			++cp;
6120 		}
6121 		delim = cp;
6122 		*(cp++) = '\0';		/* Replace / with \0 */
6123 		len = strlen(cp);	/* Last component of queue directory */
6124 
6125 		/*
6126 		**  Path relative to basedir, with trailing /
6127 		**  It will be modified below to specify the subdirectories
6128 		**  so they can be opened without chdir().
6129 		*/
6130 
6131 		off = sm_strlcpyn(relpath, sizeof(relpath), 2, prefix, "/");
6132 		SM_ASSERT(off < sizeof(relpath));
6133 
6134 		if (tTd(41, 2))
6135 			sm_dprintf("multiqueue_cache: prefix=\"%s%s\"\n",
6136 				   relpath, cp);
6137 
6138 		/* It is always basedir: we don't need to store it per group */
6139 		/* XXX: optimize this! -> one more global? */
6140 		qg->qg_qdir = newstr(basedir);
6141 		qg->qg_qdir[blen - 1] = '\0';	/* cut off trailing / */
6142 
6143 		/*
6144 		**  XXX Should probably wrap this whole loop in a timeout
6145 		**  in case some wag decides to NFS mount the queues.
6146 		*/
6147 
6148 		/* Test path to get warning messages. */
6149 		if (qn == 0)
6150 		{
6151 			/*  XXX qg_runasuid and qg_runasgid for specials? */
6152 			i = safedirpath(basedir, RunAsUid, RunAsGid, NULL,
6153 					sff, 0, 0);
6154 			if (i != 0 && tTd(41, 2))
6155 				sm_dprintf("multiqueue_cache: \"%s\": Not safe: %s\n",
6156 					   basedir, sm_errstring(i));
6157 		}
6158 
6159 		if ((dp = opendir(prefix)) == NULL)
6160 		{
6161 			syserr("can not opendir(%s/%s)", qg->qg_qdir, prefix);
6162 			if (tTd(41, 2))
6163 				sm_dprintf("multiqueue_cache: opendir(\"%s/%s\"): %s\n",
6164 					   qg->qg_qdir, prefix,
6165 					   sm_errstring(errno));
6166 			ExitStat = EX_CONFIG;
6167 			return qn;
6168 		}
6169 		while ((d = readdir(dp)) != NULL)
6170 		{
6171 			/* Skip . and .. directories */
6172 			if (strcmp(d->d_name, ".") == 0 ||
6173 			    strcmp(d->d_name, "..") == 0)
6174 				continue;
6175 
6176 			i = strlen(d->d_name);
6177 			if (i < len || strncmp(d->d_name, cp, len) != 0)
6178 			{
6179 				if (tTd(41, 5))
6180 					sm_dprintf("multiqueue_cache: \"%s\", skipped\n",
6181 						d->d_name);
6182 				continue;
6183 			}
6184 
6185 			/* Create relative pathname: prefix + local directory */
6186 			i = sizeof(relpath) - off;
6187 			if (sm_strlcpy(relpath + off, d->d_name, i) >= i)
6188 				continue;	/* way too long */
6189 
6190 			if (!chkqdir(relpath, sff))
6191 				continue;
6192 
6193 			if (qg->qg_qpaths == NULL)
6194 			{
6195 				slotsleft = INITIAL_SLOTS;
6196 				qg->qg_qpaths = (QPATHS *)xalloc((sizeof(*qg->qg_qpaths)) *
6197 								slotsleft);
6198 				qg->qg_numqueues = 0;
6199 			}
6200 			else if (slotsleft < 1)
6201 			{
6202 				qg->qg_qpaths = (QPATHS *)sm_realloc((char *)qg->qg_qpaths,
6203 							  (sizeof(*qg->qg_qpaths)) *
6204 							  (qg->qg_numqueues +
6205 							   ADD_SLOTS));
6206 				if (qg->qg_qpaths == NULL)
6207 				{
6208 					(void) closedir(dp);
6209 					return qn;
6210 				}
6211 				slotsleft += ADD_SLOTS;
6212 			}
6213 
6214 			/* check subdirs */
6215 			qg->qg_qpaths[qg->qg_numqueues].qp_subdirs = QP_NOSUB;
6216 
6217 #define CHKRSUBDIR(name, flag)	\
6218 	(void) sm_strlcpyn(subdir, sizeof(subdir), 3, relpath, "/", name); \
6219 	if (chkqdir(subdir, sff))	\
6220 		qg->qg_qpaths[qg->qg_numqueues].qp_subdirs |= flag;	\
6221 	else
6222 
6223 
6224 			CHKRSUBDIR("qf", QP_SUBQF);
6225 			CHKRSUBDIR("df", QP_SUBDF);
6226 			CHKRSUBDIR("xf", QP_SUBXF);
6227 
6228 			/* assert(strlen(d->d_name) < MAXPATHLEN - 14) */
6229 			/* maybe even - 17 (subdirs) */
6230 
6231 			if (prefix[0] != '.')
6232 				qg->qg_qpaths[qg->qg_numqueues].qp_name =
6233 					newstr(relpath);
6234 			else
6235 				qg->qg_qpaths[qg->qg_numqueues].qp_name =
6236 					newstr(d->d_name);
6237 
6238 			if (tTd(41, 2))
6239 				sm_dprintf("multiqueue_cache: %d: \"%s\" cached (%x).\n",
6240 					qg->qg_numqueues, relpath,
6241 					qg->qg_qpaths[qg->qg_numqueues].qp_subdirs);
6242 #if SM_CONF_SHM
6243 			qg->qg_qpaths[qg->qg_numqueues].qp_idx = qn;
6244 			*phash = hash_q(relpath, *phash);
6245 #endif /* SM_CONF_SHM */
6246 			qg->qg_numqueues++;
6247 			++qn;
6248 			slotsleft--;
6249 		}
6250 		(void) closedir(dp);
6251 
6252 		/* undo damage */
6253 		*delim = '/';
6254 	}
6255 	if (qg->qg_numqueues == 0)
6256 	{
6257 		qg->qg_qpaths = (QPATHS *) xalloc(sizeof(*qg->qg_qpaths));
6258 
6259 		/* test path to get warning messages */
6260 		i = safedirpath(qpath, RunAsUid, RunAsGid, NULL, sff, 0, 0);
6261 		if (i == ENOENT)
6262 		{
6263 			syserr("can not opendir(%s)", qpath);
6264 			if (tTd(41, 2))
6265 				sm_dprintf("multiqueue_cache: opendir(\"%s\"): %s\n",
6266 					   qpath, sm_errstring(i));
6267 			ExitStat = EX_CONFIG;
6268 			return qn;
6269 		}
6270 
6271 		qg->qg_qpaths[0].qp_subdirs = QP_NOSUB;
6272 		qg->qg_numqueues = 1;
6273 
6274 		/* check subdirs */
6275 #define CHKSUBDIR(name, flag)	\
6276 	(void) sm_strlcpyn(subdir, sizeof(subdir), 3, qg->qg_qdir, "/", name); \
6277 	if (chkqdir(subdir, sff))	\
6278 		qg->qg_qpaths[0].qp_subdirs |= flag;	\
6279 	else
6280 
6281 		CHKSUBDIR("qf", QP_SUBQF);
6282 		CHKSUBDIR("df", QP_SUBDF);
6283 		CHKSUBDIR("xf", QP_SUBXF);
6284 
6285 		if (qg->qg_qdir[blen - 1] != '\0' &&
6286 		    qg->qg_qdir[blen] != '\0')
6287 		{
6288 			/*
6289 			**  Copy the last component into qpaths and
6290 			**  cut off qdir
6291 			*/
6292 
6293 			qg->qg_qpaths[0].qp_name = newstr(qg->qg_qdir + blen);
6294 			qg->qg_qdir[blen - 1] = '\0';
6295 		}
6296 		else
6297 			qg->qg_qpaths[0].qp_name = newstr(".");
6298 
6299 #if SM_CONF_SHM
6300 		qg->qg_qpaths[0].qp_idx = qn;
6301 		*phash = hash_q(qg->qg_qpaths[0].qp_name, *phash);
6302 #endif /* SM_CONF_SHM */
6303 		++qn;
6304 	}
6305 	return qn;
6306 }
6307 
6308 /*
6309 **  FILESYS_FIND -- find entry in FileSys table, or add new one
6310 **
6311 **	Given the pathname of a directory, determine the file system
6312 **	in which that directory resides, and return a pointer to the
6313 **	entry in the FileSys table that describes the file system.
6314 **	A new entry is added if necessary (and requested).
6315 **	If the directory does not exist, -1 is returned.
6316 **
6317 **	Parameters:
6318 **		name -- name of directory (must be persistent!)
6319 **		path -- pathname of directory (name plus maybe "/df")
6320 **		add -- add to structure if not found.
6321 **
6322 **	Returns:
6323 **		>=0: found: index in file system table
6324 **		<0: some error, i.e.,
6325 **		FSF_TOO_MANY: too many filesystems (-> syserr())
6326 **		FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
6327 **		FSF_NOT_FOUND: not in list
6328 */
6329 
6330 static short filesys_find __P((const char *, const char *, bool));
6331 
6332 #define FSF_NOT_FOUND	(-1)
6333 #define FSF_STAT_FAIL	(-2)
6334 #define FSF_TOO_MANY	(-3)
6335 
6336 static short
6337 filesys_find(name, path, add)
6338 	const char *name;
6339 	const char *path;
6340 	bool add;
6341 {
6342 	struct stat st;
6343 	short i;
6344 
6345 	if (stat(path, &st) < 0)
6346 	{
6347 		syserr("cannot stat queue directory %s", path);
6348 		return FSF_STAT_FAIL;
6349 	}
6350 	for (i = 0; i < NumFileSys; ++i)
6351 	{
6352 		if (FILE_SYS_DEV(i) == st.st_dev)
6353 		{
6354 			/*
6355 			**  Make sure the file system (FS) name is set:
6356 			**  even though the source code indicates that
6357 			**  FILE_SYS_DEV() is only set below, it could be
6358 			**  set via shared memory, hence we need to perform
6359 			**  this check/assignment here.
6360 			*/
6361 
6362 			if (NULL == FILE_SYS_NAME(i))
6363 				FILE_SYS_NAME(i) = name;
6364 			return i;
6365 		}
6366 	}
6367 	if (i >= MAXFILESYS)
6368 	{
6369 		syserr("too many queue file systems (%d max)", MAXFILESYS);
6370 		return FSF_TOO_MANY;
6371 	}
6372 	if (!add)
6373 		return FSF_NOT_FOUND;
6374 
6375 	++NumFileSys;
6376 	FILE_SYS_NAME(i) = name;
6377 	FILE_SYS_DEV(i) = st.st_dev;
6378 	FILE_SYS_AVAIL(i) = 0;
6379 	FILE_SYS_BLKSIZE(i) = 1024; /* avoid divide by zero */
6380 	return i;
6381 }
6382 
6383 /*
6384 **  FILESYS_SETUP -- set up mapping from queue directories to file systems
6385 **
6386 **	This data structure is used to efficiently check the amount of
6387 **	free space available in a set of queue directories.
6388 **
6389 **	Parameters:
6390 **		add -- initialize structure if necessary.
6391 **
6392 **	Returns:
6393 **		0: success
6394 **		<0: some error, i.e.,
6395 **		FSF_NOT_FOUND: not in list
6396 **		FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
6397 **		FSF_TOO_MANY: too many filesystems (-> syserr())
6398 */
6399 
6400 static int filesys_setup __P((bool));
6401 
6402 static int
6403 filesys_setup(add)
6404 	bool add;
6405 {
6406 	int i, j;
6407 	short fs;
6408 	int ret;
6409 
6410 	ret = 0;
6411 	for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
6412 	{
6413 		for (j = 0; j < Queue[i]->qg_numqueues; ++j)
6414 		{
6415 			QPATHS *qp = &Queue[i]->qg_qpaths[j];
6416 			char qddf[MAXPATHLEN];
6417 
6418 			(void) sm_strlcpyn(qddf, sizeof(qddf), 2, qp->qp_name,
6419 					(bitset(QP_SUBDF, qp->qp_subdirs)
6420 						? "/df" : ""));
6421 			fs = filesys_find(qp->qp_name, qddf, add);
6422 			if (fs >= 0)
6423 				qp->qp_fsysidx = fs;
6424 			else
6425 				qp->qp_fsysidx = 0;
6426 			if (fs < ret)
6427 				ret = fs;
6428 		}
6429 	}
6430 	return ret;
6431 }
6432 
6433 /*
6434 **  FILESYS_UPDATE -- update amount of free space on all file systems
6435 **
6436 **	The FileSys table is used to cache the amount of free space
6437 **	available on all queue directory file systems.
6438 **	This function updates the cached information if it has expired.
6439 **
6440 **	Parameters:
6441 **		none.
6442 **
6443 **	Returns:
6444 **		none.
6445 **
6446 **	Side Effects:
6447 **		Updates FileSys table.
6448 */
6449 
6450 void
6451 filesys_update()
6452 {
6453 	int i;
6454 	long avail, blksize;
6455 	time_t now;
6456 	static time_t nextupdate = 0;
6457 
6458 #if SM_CONF_SHM
6459 	/*
6460 	**  Only the daemon updates the shared memory, i.e.,
6461 	**  if shared memory is available but the pid is not the
6462 	**  one of the daemon, then don't do anything.
6463 	*/
6464 
6465 	if (ShmId != SM_SHM_NO_ID && DaemonPid != CurrentPid)
6466 		return;
6467 #endif /* SM_CONF_SHM */
6468 	now = curtime();
6469 	if (now < nextupdate)
6470 		return;
6471 	nextupdate = now + FILESYS_UPDATE_INTERVAL;
6472 	for (i = 0; i < NumFileSys; ++i)
6473 	{
6474 		FILESYS *fs = &FILE_SYS(i);
6475 
6476 		avail = freediskspace(FILE_SYS_NAME(i), &blksize);
6477 		if (avail < 0 || blksize <= 0)
6478 		{
6479 			if (LogLevel > 5)
6480 				sm_syslog(LOG_ERR, NOQID,
6481 					"filesys_update failed: %s, fs=%s, avail=%ld, blocksize=%ld",
6482 					sm_errstring(errno),
6483 					FILE_SYS_NAME(i), avail, blksize);
6484 			fs->fs_avail = 0;
6485 			fs->fs_blksize = 1024; /* avoid divide by zero */
6486 			nextupdate = now + 2; /* let's do this soon again */
6487 		}
6488 		else
6489 		{
6490 			fs->fs_avail = avail;
6491 			fs->fs_blksize = blksize;
6492 		}
6493 	}
6494 }
6495 
6496 #if _FFR_ANY_FREE_FS
6497 /*
6498 **  FILESYS_FREE -- check whether there is at least one fs with enough space.
6499 **
6500 **	Parameters:
6501 **		fsize -- file size in bytes
6502 **
6503 **	Returns:
6504 **		true iff there is one fs with more than fsize bytes free.
6505 */
6506 
6507 bool
6508 filesys_free(fsize)
6509 	long fsize;
6510 {
6511 	int i;
6512 
6513 	if (fsize <= 0)
6514 		return true;
6515 	for (i = 0; i < NumFileSys; ++i)
6516 	{
6517 		long needed = 0;
6518 
6519 		if (FILE_SYS_AVAIL(i) < 0 || FILE_SYS_BLKSIZE(i) <= 0)
6520 			continue;
6521 		needed += fsize / FILE_SYS_BLKSIZE(i)
6522 			  + ((fsize % FILE_SYS_BLKSIZE(i)
6523 			      > 0) ? 1 : 0)
6524 			  + MinBlocksFree;
6525 		if (needed <= FILE_SYS_AVAIL(i))
6526 			return true;
6527 	}
6528 	return false;
6529 }
6530 #endif /* _FFR_ANY_FREE_FS */
6531 
6532 /*
6533 **  DISK_STATUS -- show amount of free space in queue directories
6534 **
6535 **	Parameters:
6536 **		out -- output file pointer.
6537 **		prefix -- string to output in front of each line.
6538 **
6539 **	Returns:
6540 **		none.
6541 */
6542 
6543 void
6544 disk_status(out, prefix)
6545 	SM_FILE_T *out;
6546 	char *prefix;
6547 {
6548 	int i;
6549 	long avail, blksize;
6550 	long free;
6551 
6552 	for (i = 0; i < NumFileSys; ++i)
6553 	{
6554 		avail = freediskspace(FILE_SYS_NAME(i), &blksize);
6555 		if (avail >= 0 && blksize > 0)
6556 		{
6557 			free = (long)((double) avail *
6558 				((double) blksize / 1024));
6559 		}
6560 		else
6561 			free = -1;
6562 		(void) sm_io_fprintf(out, SM_TIME_DEFAULT,
6563 				"%s%d/%s/%ld\r\n",
6564 				prefix, i,
6565 				FILE_SYS_NAME(i),
6566 					free);
6567 	}
6568 }
6569 
6570 #if SM_CONF_SHM
6571 
6572 /*
6573 **  INIT_SEM -- initialize semaphore system
6574 **
6575 **	Parameters:
6576 **		owner -- is this the owner of semaphores?
6577 **
6578 **	Returns:
6579 **		none.
6580 */
6581 
6582 #if _FFR_USE_SEM_LOCKING
6583 #if SM_CONF_SEM
6584 static int SemId = -1;		/* Semaphore Id */
6585 int SemKey = SM_SEM_KEY;
6586 #endif /* SM_CONF_SEM */
6587 #endif /* _FFR_USE_SEM_LOCKING */
6588 
6589 static void init_sem __P((bool));
6590 
6591 static void
6592 init_sem(owner)
6593 	bool owner;
6594 {
6595 #if _FFR_USE_SEM_LOCKING
6596 #if SM_CONF_SEM
6597 	SemId = sm_sem_start(SemKey, 1, 0, owner);
6598 	if (SemId < 0)
6599 	{
6600 		sm_syslog(LOG_ERR, NOQID,
6601 			"func=init_sem, sem_key=%ld, sm_sem_start=%d, error=%s",
6602 			(long) SemKey, SemId, sm_errstring(-SemId));
6603 		return;
6604 	}
6605 #endif /* SM_CONF_SEM */
6606 #endif /* _FFR_USE_SEM_LOCKING */
6607 	return;
6608 }
6609 
6610 /*
6611 **  STOP_SEM -- stop semaphore system
6612 **
6613 **	Parameters:
6614 **		owner -- is this the owner of semaphores?
6615 **
6616 **	Returns:
6617 **		none.
6618 */
6619 
6620 static void stop_sem __P((bool));
6621 
6622 static void
6623 stop_sem(owner)
6624 	bool owner;
6625 {
6626 #if _FFR_USE_SEM_LOCKING
6627 #if SM_CONF_SEM
6628 	if (owner && SemId >= 0)
6629 		sm_sem_stop(SemId);
6630 #endif /* SM_CONF_SEM */
6631 #endif /* _FFR_USE_SEM_LOCKING */
6632 	return;
6633 }
6634 
6635 /*
6636 **  UPD_QS -- update information about queue when adding/deleting an entry
6637 **
6638 **	Parameters:
6639 **		e -- envelope.
6640 **		count -- add/remove entry (+1/0/-1: add/no change/remove)
6641 **		space -- update the space available as well.
6642 **			(>0/0/<0: add/no change/remove)
6643 **		where -- caller (for logging)
6644 **
6645 **	Returns:
6646 **		none.
6647 **
6648 **	Side Effects:
6649 **		Modifies available space in filesystem.
6650 **		Changes number of entries in queue directory.
6651 */
6652 
6653 void
6654 upd_qs(e, count, space, where)
6655 	ENVELOPE *e;
6656 	int count;
6657 	int space;
6658 	char *where;
6659 {
6660 	short fidx;
6661 	int idx;
6662 # if _FFR_USE_SEM_LOCKING
6663 	int r;
6664 # endif /* _FFR_USE_SEM_LOCKING */
6665 	long s;
6666 
6667 	if (ShmId == SM_SHM_NO_ID || e == NULL)
6668 		return;
6669 	if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR)
6670 		return;
6671 	idx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_idx;
6672 	if (tTd(73,2))
6673 		sm_dprintf("func=upd_qs, count=%d, space=%d, where=%s, idx=%d, entries=%d\n",
6674 			count, space, where, idx, QSHM_ENTRIES(idx));
6675 
6676 	/* XXX in theory this needs to be protected with a mutex */
6677 	if (QSHM_ENTRIES(idx) >= 0 && count != 0)
6678 	{
6679 # if _FFR_USE_SEM_LOCKING
6680 		r = sm_sem_acq(SemId, 0, 1);
6681 # endif /* _FFR_USE_SEM_LOCKING */
6682 		QSHM_ENTRIES(idx) += count;
6683 # if _FFR_USE_SEM_LOCKING
6684 		if (r >= 0)
6685 			r = sm_sem_rel(SemId, 0, 1);
6686 # endif /* _FFR_USE_SEM_LOCKING */
6687 	}
6688 
6689 	fidx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_fsysidx;
6690 	if (fidx < 0)
6691 		return;
6692 
6693 	/* update available space also?  (might be loseqfile) */
6694 	if (space == 0)
6695 		return;
6696 
6697 	/* convert size to blocks; this causes rounding errors */
6698 	s = e->e_msgsize / FILE_SYS_BLKSIZE(fidx);
6699 	if (s == 0)
6700 		return;
6701 
6702 	/* XXX in theory this needs to be protected with a mutex */
6703 	if (space > 0)
6704 		FILE_SYS_AVAIL(fidx) += s;
6705 	else
6706 		FILE_SYS_AVAIL(fidx) -= s;
6707 
6708 }
6709 
6710 static bool write_key_file __P((char *, long));
6711 static long read_key_file __P((char *, long));
6712 
6713 /*
6714 **  WRITE_KEY_FILE -- record some key into a file.
6715 **
6716 **	Parameters:
6717 **		keypath -- file name.
6718 **		key -- key to write.
6719 **
6720 **	Returns:
6721 **		true iff file could be written.
6722 **
6723 **	Side Effects:
6724 **		writes file.
6725 */
6726 
6727 static bool
6728 write_key_file(keypath, key)
6729 	char *keypath;
6730 	long key;
6731 {
6732 	bool ok;
6733 	long sff;
6734 	SM_FILE_T *keyf;
6735 
6736 	ok = false;
6737 	if (keypath == NULL || *keypath == '\0')
6738 		return ok;
6739 	sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT;
6740 	if (TrustedUid != 0 && RealUid == TrustedUid)
6741 		sff |= SFF_OPENASROOT;
6742 	keyf = safefopen(keypath, O_WRONLY|O_TRUNC, FileMode, sff);
6743 	if (keyf == NULL)
6744 	{
6745 		sm_syslog(LOG_ERR, NOQID, "unable to write %s: %s",
6746 			  keypath, sm_errstring(errno));
6747 	}
6748 	else
6749 	{
6750 		if (geteuid() == 0 && RunAsUid != 0)
6751 		{
6752 #  if HASFCHOWN
6753 			int fd;
6754 
6755 			fd = keyf->f_file;
6756 			if (fd >= 0 && fchown(fd, RunAsUid, -1) < 0)
6757 			{
6758 				int err = errno;
6759 
6760 				sm_syslog(LOG_ALERT, NOQID,
6761 					  "ownership change on %s to %d failed: %s",
6762 					  keypath, RunAsUid, sm_errstring(err));
6763 			}
6764 #  endif /* HASFCHOWN */
6765 		}
6766 		ok = sm_io_fprintf(keyf, SM_TIME_DEFAULT, "%ld\n", key) !=
6767 		     SM_IO_EOF;
6768 		ok = (sm_io_close(keyf, SM_TIME_DEFAULT) != SM_IO_EOF) && ok;
6769 	}
6770 	return ok;
6771 }
6772 
6773 /*
6774 **  READ_KEY_FILE -- read a key from a file.
6775 **
6776 **	Parameters:
6777 **		keypath -- file name.
6778 **		key -- default key.
6779 **
6780 **	Returns:
6781 **		key.
6782 */
6783 
6784 static long
6785 read_key_file(keypath, key)
6786 	char *keypath;
6787 	long key;
6788 {
6789 	int r;
6790 	long sff, n;
6791 	SM_FILE_T *keyf;
6792 
6793 	if (keypath == NULL || *keypath == '\0')
6794 		return key;
6795 	sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY;
6796 	if (RealUid == 0 || (TrustedUid != 0 && RealUid == TrustedUid))
6797 		sff |= SFF_OPENASROOT;
6798 	keyf = safefopen(keypath, O_RDONLY, FileMode, sff);
6799 	if (keyf == NULL)
6800 	{
6801 		sm_syslog(LOG_ERR, NOQID, "unable to read %s: %s",
6802 			  keypath, sm_errstring(errno));
6803 	}
6804 	else
6805 	{
6806 		r = sm_io_fscanf(keyf, SM_TIME_DEFAULT, "%ld", &n);
6807 		if (r == 1)
6808 			key = n;
6809 		(void) sm_io_close(keyf, SM_TIME_DEFAULT);
6810 	}
6811 	return key;
6812 }
6813 
6814 /*
6815 **  INIT_SHM -- initialize shared memory structure
6816 **
6817 **	Initialize or attach to shared memory segment.
6818 **	Currently it is not a fatal error if this doesn't work.
6819 **	However, it causes us to have a "fallback" storage location
6820 **	for everything that is supposed to be in the shared memory,
6821 **	which makes the code slightly ugly.
6822 **
6823 **	Parameters:
6824 **		qn -- number of queue directories.
6825 **		owner -- owner of shared memory.
6826 **		hash -- identifies data that is stored in shared memory.
6827 **
6828 **	Returns:
6829 **		none.
6830 */
6831 
6832 static void init_shm __P((int, bool, unsigned int));
6833 
6834 static void
6835 init_shm(qn, owner, hash)
6836 	int qn;
6837 	bool owner;
6838 	unsigned int hash;
6839 {
6840 	int i;
6841 	int count;
6842 	int save_errno;
6843 	bool keyselect;
6844 
6845 	PtrFileSys = &FileSys[0];
6846 	PNumFileSys = &Numfilesys;
6847 /* if this "key" is specified: select one yourself */
6848 #define SEL_SHM_KEY	((key_t) -1)
6849 #define FIRST_SHM_KEY	25
6850 
6851 	/* This allows us to disable shared memory at runtime. */
6852 	if (ShmKey == 0)
6853 		return;
6854 
6855 	count = 0;
6856 	shms = SM_T_SIZE + qn * sizeof(QUEUE_SHM_T);
6857 	keyselect = ShmKey == SEL_SHM_KEY;
6858 	if (keyselect)
6859 	{
6860 		if (owner)
6861 			ShmKey = FIRST_SHM_KEY;
6862 		else
6863 		{
6864 			errno = 0;
6865 			ShmKey = read_key_file(ShmKeyFile, ShmKey);
6866 			keyselect = false;
6867 			if (ShmKey == SEL_SHM_KEY)
6868 			{
6869 				save_errno = (errno != 0) ? errno : EINVAL;
6870 				goto error;
6871 			}
6872 		}
6873 	}
6874 	for (;;)
6875 	{
6876 		/* allow read/write access for group? */
6877 		Pshm = sm_shmstart(ShmKey, shms,
6878 				SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3),
6879 				&ShmId, owner);
6880 		save_errno = errno;
6881 		if (Pshm != NULL || !sm_file_exists(save_errno))
6882 			break;
6883 		if (++count >= 3)
6884 		{
6885 			if (keyselect)
6886 			{
6887 				++ShmKey;
6888 
6889 				/* back where we started? */
6890 				if (ShmKey == SEL_SHM_KEY)
6891 					break;
6892 				continue;
6893 			}
6894 			break;
6895 		}
6896 
6897 		/* only sleep if we are at the first key */
6898 		if (!keyselect || ShmKey == SEL_SHM_KEY)
6899 			sleep(count);
6900 	}
6901 	if (Pshm != NULL)
6902 	{
6903 		int *p;
6904 
6905 		if (keyselect)
6906 			(void) write_key_file(ShmKeyFile, (long) ShmKey);
6907 		if (owner && RunAsUid != 0)
6908 		{
6909 			i = sm_shmsetowner(ShmId, RunAsUid, RunAsGid, 0660);
6910 			if (i != 0)
6911 				sm_syslog(LOG_ERR, NOQID,
6912 					"key=%ld, sm_shmsetowner=%d, RunAsUid=%d, RunAsGid=%d",
6913 					(long) ShmKey, i, RunAsUid, RunAsGid);
6914 		}
6915 		p = (int *) Pshm;
6916 		if (owner)
6917 		{
6918 			*p = (int) shms;
6919 			*((pid_t *) SHM_OFF_PID(Pshm)) = CurrentPid;
6920 			p = (int *) SHM_OFF_TAG(Pshm);
6921 			*p = hash;
6922 		}
6923 		else
6924 		{
6925 			if (*p != (int) shms)
6926 			{
6927 				save_errno = EINVAL;
6928 				cleanup_shm(false);
6929 				goto error;
6930 			}
6931 			p = (int *) SHM_OFF_TAG(Pshm);
6932 			if (*p != (int) hash)
6933 			{
6934 				save_errno = EINVAL;
6935 				cleanup_shm(false);
6936 				goto error;
6937 			}
6938 
6939 			/*
6940 			**  XXX how to check the pid?
6941 			**  Read it from the pid-file? That does
6942 			**  not need to exist.
6943 			**  We could disable shm if we can't confirm
6944 			**  that it is the right one.
6945 			*/
6946 		}
6947 
6948 		PtrFileSys = (FILESYS *) OFF_FILE_SYS(Pshm);
6949 		PNumFileSys = (int *) OFF_NUM_FILE_SYS(Pshm);
6950 		QShm = (QUEUE_SHM_T *) OFF_QUEUE_SHM(Pshm);
6951 		PRSATmpCnt = (int *) OFF_RSA_TMP_CNT(Pshm);
6952 		*PRSATmpCnt = 0;
6953 		if (owner)
6954 		{
6955 			/* initialize values in shared memory */
6956 			NumFileSys = 0;
6957 			for (i = 0; i < qn; i++)
6958 				QShm[i].qs_entries = -1;
6959 		}
6960 		init_sem(owner);
6961 		return;
6962 	}
6963   error:
6964 	if (LogLevel > (owner ? 8 : 11))
6965 	{
6966 		sm_syslog(owner ? LOG_ERR : LOG_NOTICE, NOQID,
6967 			  "can't %s shared memory, key=%ld: %s",
6968 			  owner ? "initialize" : "attach to",
6969 			  (long) ShmKey, sm_errstring(save_errno));
6970 	}
6971 }
6972 #endif /* SM_CONF_SHM */
6973 
6974 
6975 /*
6976 **  SETUP_QUEUES -- set up all queue groups
6977 **
6978 **	Parameters:
6979 **		owner -- owner of shared memory?
6980 **
6981 **	Returns:
6982 **		none.
6983 **
6984 #if SM_CONF_SHM
6985 **	Side Effects:
6986 **		attaches shared memory.
6987 #endif * SM_CONF_SHM *
6988 */
6989 
6990 void
6991 setup_queues(owner)
6992 	bool owner;
6993 {
6994 	int i, qn, len;
6995 	unsigned int hashval;
6996 	time_t now;
6997 	char basedir[MAXPATHLEN];
6998 	struct stat st;
6999 
7000 	/*
7001 	**  Determine basedir for all queue directories.
7002 	**  All queue directories must be (first level) subdirectories
7003 	**  of the basedir.  The basedir is the QueueDir
7004 	**  without wildcards, but with trailing /
7005 	*/
7006 
7007 	hashval = 0;
7008 	errno = 0;
7009 	len = sm_strlcpy(basedir, QueueDir, sizeof(basedir));
7010 
7011 	/* Provide space for trailing '/' */
7012 	if (len >= sizeof(basedir) - 1)
7013 	{
7014 		syserr("QueueDirectory: path too long: %d,  max %d",
7015 			len, (int) sizeof(basedir) - 1);
7016 		ExitStat = EX_CONFIG;
7017 		return;
7018 	}
7019 	SM_ASSERT(len > 0);
7020 	if (basedir[len - 1] == '*')
7021 	{
7022 		char *cp;
7023 
7024 		cp = SM_LAST_DIR_DELIM(basedir);
7025 		if (cp == NULL)
7026 		{
7027 			syserr("QueueDirectory: can not wildcard relative path \"%s\"",
7028 				QueueDir);
7029 			if (tTd(41, 2))
7030 				sm_dprintf("setup_queues: \"%s\": Can not wildcard relative path.\n",
7031 					QueueDir);
7032 			ExitStat = EX_CONFIG;
7033 			return;
7034 		}
7035 
7036 		/* cut off wildcard pattern */
7037 		*++cp = '\0';
7038 		len = cp - basedir;
7039 	}
7040 	else if (!SM_IS_DIR_DELIM(basedir[len - 1]))
7041 	{
7042 		/* append trailing slash since it is a directory */
7043 		basedir[len] = '/';
7044 		basedir[++len] = '\0';
7045 	}
7046 
7047 	/* len counts up to the last directory delimiter */
7048 	SM_ASSERT(basedir[len - 1] == '/');
7049 
7050 	if (chdir(basedir) < 0)
7051 	{
7052 		int save_errno = errno;
7053 
7054 		syserr("can not chdir(%s)", basedir);
7055 		if (save_errno == EACCES)
7056 			(void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
7057 				"Program mode requires special privileges, e.g., root or TrustedUser.\n");
7058 		if (tTd(41, 2))
7059 			sm_dprintf("setup_queues: \"%s\": %s\n",
7060 				   basedir, sm_errstring(errno));
7061 		ExitStat = EX_CONFIG;
7062 		return;
7063 	}
7064 #if SM_CONF_SHM
7065 	hashval = hash_q(basedir, hashval);
7066 #endif /* SM_CONF_SHM */
7067 
7068 	/* initialize for queue runs */
7069 	DoQueueRun = false;
7070 	now = curtime();
7071 	for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
7072 		Queue[i]->qg_nextrun = now;
7073 
7074 
7075 	if (UseMSP && OpMode != MD_TEST)
7076 	{
7077 		long sff = SFF_CREAT;
7078 
7079 		if (stat(".", &st) < 0)
7080 		{
7081 			syserr("can not stat(%s)", basedir);
7082 			if (tTd(41, 2))
7083 				sm_dprintf("setup_queues: \"%s\": %s\n",
7084 					   basedir, sm_errstring(errno));
7085 			ExitStat = EX_CONFIG;
7086 			return;
7087 		}
7088 		if (RunAsUid == 0)
7089 			sff |= SFF_ROOTOK;
7090 
7091 		/*
7092 		**  Check queue directory permissions.
7093 		**	Can we write to a group writable queue directory?
7094 		*/
7095 
7096 		if (bitset(S_IWGRP, QueueFileMode) &&
7097 		    bitset(S_IWGRP, st.st_mode) &&
7098 		    safefile(" ", RunAsUid, RunAsGid, RunAsUserName, sff,
7099 			     QueueFileMode, NULL) != 0)
7100 		{
7101 			syserr("can not write to queue directory %s (RunAsGid=%d, required=%d)",
7102 				basedir, (int) RunAsGid, (int) st.st_gid);
7103 		}
7104 		if (bitset(S_IWOTH|S_IXOTH, st.st_mode))
7105 		{
7106 #if _FFR_MSP_PARANOIA
7107 			syserr("dangerous permissions=%o on queue directory %s",
7108 				(int) st.st_mode, basedir);
7109 #else /* _FFR_MSP_PARANOIA */
7110 			if (LogLevel > 0)
7111 				sm_syslog(LOG_ERR, NOQID,
7112 					  "dangerous permissions=%o on queue directory %s",
7113 					  (int) st.st_mode, basedir);
7114 #endif /* _FFR_MSP_PARANOIA */
7115 		}
7116 #if _FFR_MSP_PARANOIA
7117 		if (NumQueue > 1)
7118 			syserr("can not use multiple queues for MSP");
7119 #endif /* _FFR_MSP_PARANOIA */
7120 	}
7121 
7122 	/* initial number of queue directories */
7123 	qn = 0;
7124 	for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
7125 		qn = multiqueue_cache(basedir, len, Queue[i], qn, &hashval);
7126 
7127 #if SM_CONF_SHM
7128 	init_shm(qn, owner, hashval);
7129 	i = filesys_setup(owner || ShmId == SM_SHM_NO_ID);
7130 	if (i == FSF_NOT_FOUND)
7131 	{
7132 		/*
7133 		**  We didn't get the right filesystem data
7134 		**  This may happen if we don't have the right shared memory.
7135 		**  So let's do this without shared memory.
7136 		*/
7137 
7138 		SM_ASSERT(!owner);
7139 		cleanup_shm(false);	/* release shared memory */
7140 		i = filesys_setup(false);
7141 		if (i < 0)
7142 			syserr("filesys_setup failed twice, result=%d", i);
7143 		else if (LogLevel > 8)
7144 			sm_syslog(LOG_WARNING, NOQID,
7145 				  "shared memory does not contain expected data, ignored");
7146 	}
7147 #else /* SM_CONF_SHM */
7148 	i = filesys_setup(true);
7149 #endif /* SM_CONF_SHM */
7150 	if (i < 0)
7151 		ExitStat = EX_CONFIG;
7152 }
7153 
7154 #if SM_CONF_SHM
7155 /*
7156 **  CLEANUP_SHM -- do some cleanup work for shared memory etc
7157 **
7158 **	Parameters:
7159 **		owner -- owner of shared memory?
7160 **
7161 **	Returns:
7162 **		none.
7163 **
7164 **	Side Effects:
7165 **		detaches shared memory.
7166 */
7167 
7168 void
7169 cleanup_shm(owner)
7170 	bool owner;
7171 {
7172 	if (ShmId != SM_SHM_NO_ID)
7173 	{
7174 		if (sm_shmstop(Pshm, ShmId, owner) < 0 && LogLevel > 8)
7175 			sm_syslog(LOG_INFO, NOQID, "sm_shmstop failed=%s",
7176 				  sm_errstring(errno));
7177 		Pshm = NULL;
7178 		ShmId = SM_SHM_NO_ID;
7179 	}
7180 	stop_sem(owner);
7181 }
7182 #endif /* SM_CONF_SHM */
7183 
7184 /*
7185 **  CLEANUP_QUEUES -- do some cleanup work for queues
7186 **
7187 **	Parameters:
7188 **		none.
7189 **
7190 **	Returns:
7191 **		none.
7192 **
7193 */
7194 
7195 void
7196 cleanup_queues()
7197 {
7198 	sync_queue_time();
7199 }
7200 /*
7201 **  SET_DEF_QUEUEVAL -- set default values for a queue group.
7202 **
7203 **	Parameters:
7204 **		qg -- queue group
7205 **		all -- set all values (true for default group)?
7206 **
7207 **	Returns:
7208 **		none.
7209 **
7210 **	Side Effects:
7211 **		sets default values for the queue group.
7212 */
7213 
7214 void
7215 set_def_queueval(qg, all)
7216 	QUEUEGRP *qg;
7217 	bool all;
7218 {
7219 	if (bitnset(QD_DEFINED, qg->qg_flags))
7220 		return;
7221 	if (all)
7222 		qg->qg_qdir = QueueDir;
7223 #if _FFR_QUEUE_GROUP_SORTORDER
7224 	qg->qg_sortorder = QueueSortOrder;
7225 #endif /* _FFR_QUEUE_GROUP_SORTORDER */
7226 	qg->qg_maxqrun = all ? MaxRunnersPerQueue : -1;
7227 	qg->qg_nice = NiceQueueRun;
7228 }
7229 /*
7230 **  MAKEQUEUE -- define a new queue.
7231 **
7232 **	Parameters:
7233 **		line -- description of queue.  This is in labeled fields.
7234 **			The fields are:
7235 **			   F -- the flags associated with the queue
7236 **			   I -- the interval between running the queue
7237 **			   J -- the maximum # of jobs in work list
7238 **			   [M -- the maximum # of jobs in a queue run]
7239 **			   N -- the niceness at which to run
7240 **			   P -- the path to the queue
7241 **			   S -- the queue sorting order
7242 **			   R -- number of parallel queue runners
7243 **			   r -- max recipients per envelope
7244 **			The first word is the canonical name of the queue.
7245 **		qdef -- this is a 'Q' definition from .cf
7246 **
7247 **	Returns:
7248 **		none.
7249 **
7250 **	Side Effects:
7251 **		enters the queue into the queue table.
7252 */
7253 
7254 void
7255 makequeue(line, qdef)
7256 	char *line;
7257 	bool qdef;
7258 {
7259 	register char *p;
7260 	register QUEUEGRP *qg;
7261 	register STAB *s;
7262 	int i;
7263 	char fcode;
7264 
7265 	/* allocate a queue and set up defaults */
7266 	qg = (QUEUEGRP *) xalloc(sizeof(*qg));
7267 	memset((char *) qg, '\0', sizeof(*qg));
7268 
7269 	if (line[0] == '\0')
7270 	{
7271 		syserr("name required for queue");
7272 		return;
7273 	}
7274 
7275 	/* collect the queue name */
7276 	for (p = line;
7277 	     *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p));
7278 	     p++)
7279 		continue;
7280 	if (*p != '\0')
7281 		*p++ = '\0';
7282 	qg->qg_name = newstr(line);
7283 
7284 	/* set default values, can be overridden below */
7285 	set_def_queueval(qg, false);
7286 
7287 	/* now scan through and assign info from the fields */
7288 	while (*p != '\0')
7289 	{
7290 		auto char *delimptr;
7291 
7292 		while (*p != '\0' &&
7293 		       (*p == ',' || (isascii(*p) && isspace(*p))))
7294 			p++;
7295 
7296 		/* p now points to field code */
7297 		fcode = *p;
7298 		while (*p != '\0' && *p != '=' && *p != ',')
7299 			p++;
7300 		if (*p++ != '=')
7301 		{
7302 			syserr("queue %s: `=' expected", qg->qg_name);
7303 			return;
7304 		}
7305 		while (isascii(*p) && isspace(*p))
7306 			p++;
7307 
7308 		/* p now points to the field body */
7309 		p = munchstring(p, &delimptr, ',');
7310 
7311 		/* install the field into the queue struct */
7312 		switch (fcode)
7313 		{
7314 		  case 'P':		/* pathname */
7315 			if (*p == '\0')
7316 				syserr("queue %s: empty path name",
7317 					qg->qg_name);
7318 			else
7319 				qg->qg_qdir = newstr(p);
7320 			break;
7321 
7322 		  case 'F':		/* flags */
7323 			for (; *p != '\0'; p++)
7324 				if (!(isascii(*p) && isspace(*p)))
7325 					setbitn(*p, qg->qg_flags);
7326 			break;
7327 
7328 			/*
7329 			**  Do we need two intervals here:
7330 			**  One for persistent queue runners,
7331 			**  one for "normal" queue runs?
7332 			*/
7333 
7334 		  case 'I':	/* interval between running the queue */
7335 			qg->qg_queueintvl = convtime(p, 'm');
7336 			break;
7337 
7338 		  case 'N':		/* run niceness */
7339 			qg->qg_nice = atoi(p);
7340 			break;
7341 
7342 		  case 'R':		/* maximum # of runners for the group */
7343 			i = atoi(p);
7344 
7345 			/* can't have more runners than allowed total */
7346 			if (MaxQueueChildren > 0 && i > MaxQueueChildren)
7347 			{
7348 				qg->qg_maxqrun = MaxQueueChildren;
7349 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7350 						     "Q=%s: R=%d exceeds MaxQueueChildren=%d, set to MaxQueueChildren\n",
7351 						     qg->qg_name, i,
7352 						     MaxQueueChildren);
7353 			}
7354 			else
7355 				qg->qg_maxqrun = i;
7356 			break;
7357 
7358 		  case 'J':		/* maximum # of jobs in work list */
7359 			qg->qg_maxlist = atoi(p);
7360 			break;
7361 
7362 		  case 'r':		/* max recipients per envelope */
7363 			qg->qg_maxrcpt = atoi(p);
7364 			break;
7365 
7366 #if _FFR_QUEUE_GROUP_SORTORDER
7367 		  case 'S':		/* queue sorting order */
7368 			switch (*p)
7369 			{
7370 			  case 'h':	/* Host first */
7371 			  case 'H':
7372 				qg->qg_sortorder = QSO_BYHOST;
7373 				break;
7374 
7375 			  case 'p':	/* Priority order */
7376 			  case 'P':
7377 				qg->qg_sortorder = QSO_BYPRIORITY;
7378 				break;
7379 
7380 			  case 't':	/* Submission time */
7381 			  case 'T':
7382 				qg->qg_sortorder = QSO_BYTIME;
7383 				break;
7384 
7385 			  case 'f':	/* File name */
7386 			  case 'F':
7387 				qg->qg_sortorder = QSO_BYFILENAME;
7388 				break;
7389 
7390 			  case 'm':	/* Modification time */
7391 			  case 'M':
7392 				qg->qg_sortorder = QSO_BYMODTIME;
7393 				break;
7394 
7395 			  case 'r':	/* Random */
7396 			  case 'R':
7397 				qg->qg_sortorder = QSO_RANDOM;
7398 				break;
7399 
7400 # if _FFR_RHS
7401 			  case 's':	/* Shuffled host name */
7402 			  case 'S':
7403 				qg->qg_sortorder = QSO_BYSHUFFLE;
7404 				break;
7405 # endif /* _FFR_RHS */
7406 
7407 			  case 'n':	/* none */
7408 			  case 'N':
7409 				qg->qg_sortorder = QSO_NONE;
7410 				break;
7411 
7412 			  default:
7413 				syserr("Invalid queue sort order \"%s\"", p);
7414 			}
7415 			break;
7416 #endif /* _FFR_QUEUE_GROUP_SORTORDER */
7417 
7418 		  default:
7419 			syserr("Q%s: unknown queue equate %c=",
7420 			       qg->qg_name, fcode);
7421 			break;
7422 		}
7423 
7424 		p = delimptr;
7425 	}
7426 
7427 #if !HASNICE
7428 	if (qg->qg_nice != NiceQueueRun)
7429 	{
7430 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7431 				     "Q%s: Warning: N= set on system that doesn't support nice()\n",
7432 				     qg->qg_name);
7433 	}
7434 #endif /* !HASNICE */
7435 
7436 	/* do some rationality checking */
7437 	if (NumQueue >= MAXQUEUEGROUPS)
7438 	{
7439 		syserr("too many queue groups defined (%d max)",
7440 			MAXQUEUEGROUPS);
7441 		return;
7442 	}
7443 
7444 	if (qg->qg_qdir == NULL)
7445 	{
7446 		if (QueueDir == NULL || *QueueDir == '\0')
7447 		{
7448 			syserr("QueueDir must be defined before queue groups");
7449 			return;
7450 		}
7451 		qg->qg_qdir = newstr(QueueDir);
7452 	}
7453 
7454 	if (qg->qg_maxqrun > 1 && !bitnset(QD_FORK, qg->qg_flags))
7455 	{
7456 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7457 				     "Warning: Q=%s: R=%d: multiple queue runners specified\n\tbut flag '%c' is not set\n",
7458 				     qg->qg_name, qg->qg_maxqrun, QD_FORK);
7459 	}
7460 
7461 	/* enter the queue into the symbol table */
7462 	if (tTd(37, 8))
7463 		sm_syslog(LOG_INFO, NOQID,
7464 			  "Adding %s to stab, path: %s", qg->qg_name,
7465 			  qg->qg_qdir);
7466 	s = stab(qg->qg_name, ST_QUEUE, ST_ENTER);
7467 	if (s->s_quegrp != NULL)
7468 	{
7469 		i = s->s_quegrp->qg_index;
7470 
7471 		/* XXX what about the pointers inside this struct? */
7472 		sm_free(s->s_quegrp); /* XXX */
7473 	}
7474 	else
7475 		i = NumQueue++;
7476 	Queue[i] = s->s_quegrp = qg;
7477 	qg->qg_index = i;
7478 
7479 	/* set default value for max queue runners */
7480 	if (qg->qg_maxqrun < 0)
7481 	{
7482 		if (MaxRunnersPerQueue > 0)
7483 			qg->qg_maxqrun = MaxRunnersPerQueue;
7484 		else
7485 			qg->qg_maxqrun = 1;
7486 	}
7487 	if (qdef)
7488 		setbitn(QD_DEFINED, qg->qg_flags);
7489 }
7490 #if 0
7491 /*
7492 **  HASHFQN -- calculate a hash value for a fully qualified host name
7493 **
7494 **	Arguments:
7495 **		fqn -- an all lower-case host.domain string
7496 **		buckets -- the number of buckets (queue directories)
7497 **
7498 **	Returns:
7499 **		a bucket number (signed integer)
7500 **		-1 on error
7501 **
7502 **	Contributed by Exactis.com, Inc.
7503 */
7504 
7505 int
7506 hashfqn(fqn, buckets)
7507 	register char *fqn;
7508 	int buckets;
7509 {
7510 	register char *p;
7511 	register int h = 0, hash, cnt;
7512 
7513 	if (fqn == NULL)
7514 		return -1;
7515 
7516 	/*
7517 	**  A variation on the gdb hash
7518 	**  This is the best as of Feb 19, 1996 --bcx
7519 	*/
7520 
7521 	p = fqn;
7522 	h = 0x238F13AF * strlen(p);
7523 	for (cnt = 0; *p != 0; ++p, cnt++)
7524 	{
7525 		h = (h + (*p << (cnt * 5 % 24))) & 0x7FFFFFFF;
7526 	}
7527 	h = (1103515243 * h + 12345) & 0x7FFFFFFF;
7528 	if (buckets < 2)
7529 		hash = 0;
7530 	else
7531 		hash = (h % buckets);
7532 
7533 	return hash;
7534 }
7535 #endif /* 0 */
7536 
7537 /*
7538 **  A structure for sorting Queue according to maxqrun without
7539 **	screwing up Queue itself.
7540 */
7541 
7542 struct sortqgrp
7543 {
7544 	int sg_idx;		/* original index */
7545 	int sg_maxqrun;		/* max queue runners */
7546 };
7547 typedef struct sortqgrp	SORTQGRP_T;
7548 static int cmpidx __P((const void *, const void *));
7549 
7550 static int
7551 cmpidx(a, b)
7552 	const void *a;
7553 	const void *b;
7554 {
7555 	/* The sort is highest to lowest, so the comparison is reversed */
7556 	if (((SORTQGRP_T *)a)->sg_maxqrun < ((SORTQGRP_T *)b)->sg_maxqrun)
7557 		return 1;
7558 	else if (((SORTQGRP_T *)a)->sg_maxqrun > ((SORTQGRP_T *)b)->sg_maxqrun)
7559 		return -1;
7560 	else
7561 		return 0;
7562 }
7563 
7564 /*
7565 **  MAKEWORKGROUP -- balance queue groups into work groups per MaxQueueChildren
7566 **
7567 **  Take the now defined queue groups and assign them to work groups.
7568 **  This is done to balance out the number of concurrently active
7569 **  queue runners such that MaxQueueChildren is not exceeded. This may
7570 **  result in more than one queue group per work group. In such a case
7571 **  the number of running queue groups in that work group will have no
7572 **  more than the work group maximum number of runners (a "fair" portion
7573 **  of MaxQueueRunners). All queue groups within a work group will get a
7574 **  chance at running.
7575 **
7576 **	Parameters:
7577 **		none.
7578 **
7579 **	Returns:
7580 **		nothing.
7581 **
7582 **	Side Effects:
7583 **		Sets up WorkGrp structure.
7584 */
7585 
7586 void
7587 makeworkgroups()
7588 {
7589 	int i, j, total_runners, dir, h;
7590 	SORTQGRP_T si[MAXQUEUEGROUPS + 1];
7591 
7592 	total_runners = 0;
7593 	if (NumQueue == 1 && strcmp(Queue[0]->qg_name, "mqueue") == 0)
7594 	{
7595 		/*
7596 		**  There is only the "mqueue" queue group (a default)
7597 		**  containing all of the queues. We want to provide to
7598 		**  this queue group the maximum allowable queue runners.
7599 		**  To match older behavior (8.10/8.11) we'll try for
7600 		**  1 runner per queue capping it at MaxQueueChildren.
7601 		**  So if there are N queues, then there will be N runners
7602 		**  for the "mqueue" queue group (where N is kept less than
7603 		**  MaxQueueChildren).
7604 		*/
7605 
7606 		NumWorkGroups = 1;
7607 		WorkGrp[0].wg_numqgrp = 1;
7608 		WorkGrp[0].wg_qgs = (QUEUEGRP **) xalloc(sizeof(QUEUEGRP *));
7609 		WorkGrp[0].wg_qgs[0] = Queue[0];
7610 		if (MaxQueueChildren > 0 &&
7611 		    Queue[0]->qg_numqueues > MaxQueueChildren)
7612 			WorkGrp[0].wg_runners = MaxQueueChildren;
7613 		else
7614 			WorkGrp[0].wg_runners = Queue[0]->qg_numqueues;
7615 
7616 		Queue[0]->qg_wgrp = 0;
7617 
7618 		/* can't have more runners than allowed total */
7619 		if (MaxQueueChildren > 0 &&
7620 		    Queue[0]->qg_maxqrun > MaxQueueChildren)
7621 			Queue[0]->qg_maxqrun = MaxQueueChildren;
7622 		WorkGrp[0].wg_maxact = Queue[0]->qg_maxqrun;
7623 		WorkGrp[0].wg_lowqintvl = Queue[0]->qg_queueintvl;
7624 		return;
7625 	}
7626 
7627 	for (i = 0; i < NumQueue; i++)
7628 	{
7629 		si[i].sg_maxqrun = Queue[i]->qg_maxqrun;
7630 		si[i].sg_idx = i;
7631 	}
7632 	qsort(si, NumQueue, sizeof(si[0]), cmpidx);
7633 
7634 	NumWorkGroups = 0;
7635 	for (i = 0; i < NumQueue; i++)
7636 	{
7637 		total_runners += si[i].sg_maxqrun;
7638 		if (MaxQueueChildren <= 0 || total_runners <= MaxQueueChildren)
7639 			NumWorkGroups++;
7640 		else
7641 			break;
7642 	}
7643 
7644 	if (NumWorkGroups < 1)
7645 		NumWorkGroups = 1; /* gotta have one at least */
7646 	else if (NumWorkGroups > MAXWORKGROUPS)
7647 		NumWorkGroups = MAXWORKGROUPS; /* the limit */
7648 
7649 	/*
7650 	**  We now know the number of work groups to pack the queue groups
7651 	**  into. The queue groups in 'Queue' are sorted from highest
7652 	**  to lowest for the number of runners per queue group.
7653 	**  We put the queue groups with the largest number of runners
7654 	**  into work groups first. Then the smaller ones are fitted in
7655 	**  where it looks best.
7656 	*/
7657 
7658 	j = 0;
7659 	dir = 1;
7660 	for (i = 0; i < NumQueue; i++)
7661 	{
7662 		/* a to-and-fro packing scheme, continue from last position */
7663 		if (j >= NumWorkGroups)
7664 		{
7665 			dir = -1;
7666 			j = NumWorkGroups - 1;
7667 		}
7668 		else if (j < 0)
7669 		{
7670 			j = 0;
7671 			dir = 1;
7672 		}
7673 
7674 		if (WorkGrp[j].wg_qgs == NULL)
7675 			WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_malloc(sizeof(QUEUEGRP *) *
7676 							(WorkGrp[j].wg_numqgrp + 1));
7677 		else
7678 			WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_realloc(WorkGrp[j].wg_qgs,
7679 							sizeof(QUEUEGRP *) *
7680 							(WorkGrp[j].wg_numqgrp + 1));
7681 		if (WorkGrp[j].wg_qgs == NULL)
7682 		{
7683 			syserr("!cannot allocate memory for work queues, need %d bytes",
7684 			       (int) (sizeof(QUEUEGRP *) *
7685 				      (WorkGrp[j].wg_numqgrp + 1)));
7686 		}
7687 
7688 		h = si[i].sg_idx;
7689 		WorkGrp[j].wg_qgs[WorkGrp[j].wg_numqgrp] = Queue[h];
7690 		WorkGrp[j].wg_numqgrp++;
7691 		WorkGrp[j].wg_runners += Queue[h]->qg_maxqrun;
7692 		Queue[h]->qg_wgrp = j;
7693 
7694 		if (WorkGrp[j].wg_maxact == 0)
7695 		{
7696 			/* can't have more runners than allowed total */
7697 			if (MaxQueueChildren > 0 &&
7698 			    Queue[h]->qg_maxqrun > MaxQueueChildren)
7699 				Queue[h]->qg_maxqrun = MaxQueueChildren;
7700 			WorkGrp[j].wg_maxact = Queue[h]->qg_maxqrun;
7701 		}
7702 
7703 		/*
7704 		**  XXX: must wg_lowqintvl be the GCD?
7705 		**  qg1: 2m, qg2: 3m, minimum: 2m, when do queue runs for
7706 		**  qg2 occur?
7707 		*/
7708 
7709 		/* keep track of the lowest interval for a persistent runner */
7710 		if (Queue[h]->qg_queueintvl > 0 &&
7711 		    WorkGrp[j].wg_lowqintvl < Queue[h]->qg_queueintvl)
7712 			WorkGrp[j].wg_lowqintvl = Queue[h]->qg_queueintvl;
7713 		j += dir;
7714 	}
7715 	if (tTd(41, 9))
7716 	{
7717 		for (i = 0; i < NumWorkGroups; i++)
7718 		{
7719 			sm_dprintf("Workgroup[%d]=", i);
7720 			for (j = 0; j < WorkGrp[i].wg_numqgrp; j++)
7721 			{
7722 				sm_dprintf("%s, ",
7723 					WorkGrp[i].wg_qgs[j]->qg_name);
7724 			}
7725 			sm_dprintf("\n");
7726 		}
7727 	}
7728 }
7729 
7730 /*
7731 **  DUP_DF -- duplicate envelope data file
7732 **
7733 **	Copy the data file from the 'old' envelope to the 'new' envelope
7734 **	in the most efficient way possible.
7735 **
7736 **	Create a hard link from the 'old' data file to the 'new' data file.
7737 **	If the old and new queue directories are on different file systems,
7738 **	then the new data file link is created in the old queue directory,
7739 **	and the new queue file will contain a 'd' record pointing to the
7740 **	directory containing the new data file.
7741 **
7742 **	Parameters:
7743 **		old -- old envelope.
7744 **		new -- new envelope.
7745 **
7746 **	Results:
7747 **		Returns true on success, false on failure.
7748 **
7749 **	Side Effects:
7750 **		On success, the new data file is created.
7751 **		On fatal failure, EF_FATALERRS is set in old->e_flags.
7752 */
7753 
7754 static bool	dup_df __P((ENVELOPE *, ENVELOPE *));
7755 
7756 static bool
7757 dup_df(old, new)
7758 	ENVELOPE *old;
7759 	ENVELOPE *new;
7760 {
7761 	int ofs, nfs, r;
7762 	char opath[MAXPATHLEN];
7763 	char npath[MAXPATHLEN];
7764 
7765 	if (!bitset(EF_HAS_DF, old->e_flags))
7766 	{
7767 		/*
7768 		**  this can happen if: SuperSafe != True
7769 		**  and a bounce mail is sent that is split.
7770 		*/
7771 
7772 		queueup(old, false, true);
7773 	}
7774 	SM_REQUIRE(ISVALIDQGRP(old->e_qgrp) && ISVALIDQDIR(old->e_qdir));
7775 	SM_REQUIRE(ISVALIDQGRP(new->e_qgrp) && ISVALIDQDIR(new->e_qdir));
7776 
7777 	(void) sm_strlcpy(opath, queuename(old, DATAFL_LETTER), sizeof(opath));
7778 	(void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof(npath));
7779 
7780 	if (old->e_dfp != NULL)
7781 	{
7782 		r = sm_io_setinfo(old->e_dfp, SM_BF_COMMIT, NULL);
7783 		if (r < 0 && errno != EINVAL)
7784 		{
7785 			syserr("@can't commit %s", opath);
7786 			old->e_flags |= EF_FATALERRS;
7787 			return false;
7788 		}
7789 	}
7790 
7791 	/*
7792 	**  Attempt to create a hard link, if we think both old and new
7793 	**  are on the same file system, otherwise copy the file.
7794 	**
7795 	**  Don't waste time attempting a hard link unless old and new
7796 	**  are on the same file system.
7797 	*/
7798 
7799 	SM_REQUIRE(ISVALIDQGRP(old->e_dfqgrp) && ISVALIDQDIR(old->e_dfqdir));
7800 	SM_REQUIRE(ISVALIDQGRP(new->e_dfqgrp) && ISVALIDQDIR(new->e_dfqdir));
7801 
7802 	ofs = Queue[old->e_dfqgrp]->qg_qpaths[old->e_dfqdir].qp_fsysidx;
7803 	nfs = Queue[new->e_dfqgrp]->qg_qpaths[new->e_dfqdir].qp_fsysidx;
7804 	if (FILE_SYS_DEV(ofs) == FILE_SYS_DEV(nfs))
7805 	{
7806 		if (link(opath, npath) == 0)
7807 		{
7808 			new->e_flags |= EF_HAS_DF;
7809 			SYNC_DIR(npath, true);
7810 			return true;
7811 		}
7812 		goto error;
7813 	}
7814 
7815 	/*
7816 	**  Can't link across queue directories, so try to create a hard
7817 	**  link in the same queue directory as the old df file.
7818 	**  The qf file will refer to the new df file using a 'd' record.
7819 	*/
7820 
7821 	new->e_dfqgrp = old->e_dfqgrp;
7822 	new->e_dfqdir = old->e_dfqdir;
7823 	(void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof(npath));
7824 	if (link(opath, npath) == 0)
7825 	{
7826 		new->e_flags |= EF_HAS_DF;
7827 		SYNC_DIR(npath, true);
7828 		return true;
7829 	}
7830 
7831   error:
7832 	if (LogLevel > 0)
7833 		sm_syslog(LOG_ERR, old->e_id,
7834 			  "dup_df: can't link %s to %s, error=%s, envelope splitting failed",
7835 			  opath, npath, sm_errstring(errno));
7836 	return false;
7837 }
7838 
7839 /*
7840 **  SPLIT_ENV -- Allocate a new envelope based on a given envelope.
7841 **
7842 **	Parameters:
7843 **		e -- envelope.
7844 **		sendqueue -- sendqueue for new envelope.
7845 **		qgrp -- index of queue group.
7846 **		qdir -- queue directory.
7847 **
7848 **	Results:
7849 **		new envelope.
7850 **
7851 */
7852 
7853 static ENVELOPE	*split_env __P((ENVELOPE *, ADDRESS *, int, int));
7854 
7855 static ENVELOPE *
7856 split_env(e, sendqueue, qgrp, qdir)
7857 	ENVELOPE *e;
7858 	ADDRESS *sendqueue;
7859 	int qgrp;
7860 	int qdir;
7861 {
7862 	ENVELOPE *ee;
7863 
7864 	ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, sizeof(*ee));
7865 	STRUCTCOPY(*e, *ee);
7866 	ee->e_message = NULL;	/* XXX use original message? */
7867 	ee->e_id = NULL;
7868 	assign_queueid(ee);
7869 	ee->e_sendqueue = sendqueue;
7870 	ee->e_flags &= ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS
7871 			 |EF_SENDRECEIPT|EF_RET_PARAM|EF_HAS_DF);
7872 	ee->e_flags |= EF_NORECEIPT;	/* XXX really? */
7873 	ee->e_from.q_state = QS_SENDER;
7874 	ee->e_dfp = NULL;
7875 	ee->e_lockfp = NULL;
7876 	if (e->e_xfp != NULL)
7877 		ee->e_xfp = sm_io_dup(e->e_xfp);
7878 
7879 	/* failed to dup e->e_xfp, start a new transcript */
7880 	if (ee->e_xfp == NULL)
7881 		openxscript(ee);
7882 
7883 	ee->e_qgrp = ee->e_dfqgrp = qgrp;
7884 	ee->e_qdir = ee->e_dfqdir = qdir;
7885 	ee->e_errormode = EM_MAIL;
7886 	ee->e_statmsg = NULL;
7887 	if (e->e_quarmsg != NULL)
7888 		ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
7889 						  e->e_quarmsg);
7890 
7891 	/*
7892 	**  XXX Not sure if this copying is necessary.
7893 	**  sendall() does this copying, but I (dm) don't know if that is
7894 	**  because of the storage management discipline we were using
7895 	**  before rpools were introduced, or if it is because these lists
7896 	**  can be modified later.
7897 	*/
7898 
7899 	ee->e_header = copyheader(e->e_header, ee->e_rpool);
7900 	ee->e_errorqueue = copyqueue(e->e_errorqueue, ee->e_rpool);
7901 
7902 	return ee;
7903 }
7904 
7905 /* return values from split functions, check also below! */
7906 #define SM_SPLIT_FAIL	(0)
7907 #define SM_SPLIT_NONE	(1)
7908 #define SM_SPLIT_NEW(n)	(1 + (n))
7909 
7910 /*
7911 **  SPLIT_ACROSS_QUEUE_GROUPS
7912 **
7913 **	This function splits an envelope across multiple queue groups
7914 **	based on the queue group of each recipient.
7915 **
7916 **	Parameters:
7917 **		e -- envelope.
7918 **
7919 **	Results:
7920 **		SM_SPLIT_FAIL on failure
7921 **		SM_SPLIT_NONE if no splitting occurred,
7922 **		or 1 + the number of additional envelopes created.
7923 **
7924 **	Side Effects:
7925 **		On success, e->e_sibling points to a list of zero or more
7926 **		additional envelopes, and the associated data files exist
7927 **		on disk.  But the queue files are not created.
7928 **
7929 **		On failure, e->e_sibling is not changed.
7930 **		The order of recipients in e->e_sendqueue is permuted.
7931 **		Abandoned data files for additional envelopes that failed
7932 **		to be created may exist on disk.
7933 */
7934 
7935 static int	q_qgrp_compare __P((const void *, const void *));
7936 static int	e_filesys_compare __P((const void *, const void *));
7937 
7938 static int
7939 q_qgrp_compare(p1, p2)
7940 	const void *p1;
7941 	const void *p2;
7942 {
7943 	ADDRESS **pq1 = (ADDRESS **) p1;
7944 	ADDRESS **pq2 = (ADDRESS **) p2;
7945 
7946 	return (*pq1)->q_qgrp - (*pq2)->q_qgrp;
7947 }
7948 
7949 static int
7950 e_filesys_compare(p1, p2)
7951 	const void *p1;
7952 	const void *p2;
7953 {
7954 	ENVELOPE **pe1 = (ENVELOPE **) p1;
7955 	ENVELOPE **pe2 = (ENVELOPE **) p2;
7956 	int fs1, fs2;
7957 
7958 	fs1 = Queue[(*pe1)->e_qgrp]->qg_qpaths[(*pe1)->e_qdir].qp_fsysidx;
7959 	fs2 = Queue[(*pe2)->e_qgrp]->qg_qpaths[(*pe2)->e_qdir].qp_fsysidx;
7960 	if (FILE_SYS_DEV(fs1) < FILE_SYS_DEV(fs2))
7961 		return -1;
7962 	if (FILE_SYS_DEV(fs1) > FILE_SYS_DEV(fs2))
7963 		return 1;
7964 	return 0;
7965 }
7966 
7967 static int split_across_queue_groups __P((ENVELOPE *));
7968 static int
7969 split_across_queue_groups(e)
7970 	ENVELOPE *e;
7971 {
7972 	int naddrs, nsplits, i;
7973 	bool changed;
7974 	char **pvp;
7975 	ADDRESS *q, **addrs;
7976 	ENVELOPE *ee, *es;
7977 	ENVELOPE *splits[MAXQUEUEGROUPS];
7978 	char pvpbuf[PSBUFSIZE];
7979 
7980 	SM_REQUIRE(ISVALIDQGRP(e->e_qgrp));
7981 
7982 	/* Count addresses and assign queue groups. */
7983 	naddrs = 0;
7984 	changed = false;
7985 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
7986 	{
7987 		if (QS_IS_DEAD(q->q_state))
7988 			continue;
7989 		++naddrs;
7990 
7991 		/* bad addresses and those already sent stay put */
7992 		if (QS_IS_BADADDR(q->q_state) ||
7993 		    QS_IS_SENT(q->q_state))
7994 			q->q_qgrp = e->e_qgrp;
7995 		else if (!ISVALIDQGRP(q->q_qgrp))
7996 		{
7997 			/* call ruleset which should return a queue group */
7998 			i = rscap(RS_QUEUEGROUP, q->q_user, NULL, e, &pvp,
7999 				  pvpbuf, sizeof(pvpbuf));
8000 			if (i == EX_OK &&
8001 			    pvp != NULL && pvp[0] != NULL &&
8002 			    (pvp[0][0] & 0377) == CANONNET &&
8003 			    pvp[1] != NULL && pvp[1][0] != '\0')
8004 			{
8005 				i = name2qid(pvp[1]);
8006 				if (ISVALIDQGRP(i))
8007 				{
8008 					q->q_qgrp = i;
8009 					changed = true;
8010 					if (tTd(20, 4))
8011 						sm_syslog(LOG_INFO, NOQID,
8012 							"queue group name %s -> %d",
8013 							pvp[1], i);
8014 					continue;
8015 				}
8016 				else if (LogLevel > 10)
8017 					sm_syslog(LOG_INFO, NOQID,
8018 						"can't find queue group name %s, selection ignored",
8019 						pvp[1]);
8020 			}
8021 			if (q->q_mailer != NULL &&
8022 			    ISVALIDQGRP(q->q_mailer->m_qgrp))
8023 			{
8024 				changed = true;
8025 				q->q_qgrp = q->q_mailer->m_qgrp;
8026 			}
8027 			else if (ISVALIDQGRP(e->e_qgrp))
8028 				q->q_qgrp = e->e_qgrp;
8029 			else
8030 				q->q_qgrp = 0;
8031 		}
8032 	}
8033 
8034 	/* only one address? nothing to split. */
8035 	if (naddrs <= 1 && !changed)
8036 		return SM_SPLIT_NONE;
8037 
8038 	/* sort the addresses by queue group */
8039 	addrs = sm_rpool_malloc_x(e->e_rpool, naddrs * sizeof(ADDRESS *));
8040 	for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next)
8041 	{
8042 		if (QS_IS_DEAD(q->q_state))
8043 			continue;
8044 		addrs[i++] = q;
8045 	}
8046 	qsort(addrs, naddrs, sizeof(ADDRESS *), q_qgrp_compare);
8047 
8048 	/* split into multiple envelopes, by queue group */
8049 	nsplits = 0;
8050 	es = NULL;
8051 	e->e_sendqueue = NULL;
8052 	for (i = 0; i < naddrs; ++i)
8053 	{
8054 		if (i == naddrs - 1 || addrs[i]->q_qgrp != addrs[i + 1]->q_qgrp)
8055 			addrs[i]->q_next = NULL;
8056 		else
8057 			addrs[i]->q_next = addrs[i + 1];
8058 
8059 		/* same queue group as original envelope? */
8060 		if (addrs[i]->q_qgrp == e->e_qgrp)
8061 		{
8062 			if (e->e_sendqueue == NULL)
8063 				e->e_sendqueue = addrs[i];
8064 			continue;
8065 		}
8066 
8067 		/* different queue group than original envelope */
8068 		if (es == NULL || addrs[i]->q_qgrp != es->e_qgrp)
8069 		{
8070 			ee = split_env(e, addrs[i], addrs[i]->q_qgrp, NOQDIR);
8071 			es = ee;
8072 			splits[nsplits++] = ee;
8073 		}
8074 	}
8075 
8076 	/* no splits? return right now. */
8077 	if (nsplits <= 0)
8078 		return SM_SPLIT_NONE;
8079 
8080 	/* assign a queue directory to each additional envelope */
8081 	for (i = 0; i < nsplits; ++i)
8082 	{
8083 		es = splits[i];
8084 #if 0
8085 		es->e_qdir = pickqdir(Queue[es->e_qgrp], es->e_msgsize, es);
8086 #endif /* 0 */
8087 		if (!setnewqueue(es))
8088 			goto failure;
8089 	}
8090 
8091 	/* sort the additional envelopes by queue file system */
8092 	qsort(splits, nsplits, sizeof(ENVELOPE *), e_filesys_compare);
8093 
8094 	/* create data files for each additional envelope */
8095 	if (!dup_df(e, splits[0]))
8096 	{
8097 		i = 0;
8098 		goto failure;
8099 	}
8100 	for (i = 1; i < nsplits; ++i)
8101 	{
8102 		/* copy or link to the previous data file */
8103 		if (!dup_df(splits[i - 1], splits[i]))
8104 			goto failure;
8105 	}
8106 
8107 	/* success: prepend the new envelopes to the e->e_sibling list */
8108 	for (i = 0; i < nsplits; ++i)
8109 	{
8110 		es = splits[i];
8111 		es->e_sibling = e->e_sibling;
8112 		e->e_sibling = es;
8113 	}
8114 	return SM_SPLIT_NEW(nsplits);
8115 
8116 	/* failure: clean up */
8117   failure:
8118 	if (i > 0)
8119 	{
8120 		int j;
8121 
8122 		for (j = 0; j < i; j++)
8123 			(void) unlink(queuename(splits[j], DATAFL_LETTER));
8124 	}
8125 	e->e_sendqueue = addrs[0];
8126 	for (i = 0; i < naddrs - 1; ++i)
8127 		addrs[i]->q_next = addrs[i + 1];
8128 	addrs[naddrs - 1]->q_next = NULL;
8129 	return SM_SPLIT_FAIL;
8130 }
8131 
8132 /*
8133 **  SPLIT_WITHIN_QUEUE
8134 **
8135 **	Split an envelope with multiple recipients into several
8136 **	envelopes within the same queue directory, if the number of
8137 **	recipients exceeds the limit for the queue group.
8138 **
8139 **	Parameters:
8140 **		e -- envelope.
8141 **
8142 **	Results:
8143 **		SM_SPLIT_FAIL on failure
8144 **		SM_SPLIT_NONE if no splitting occurred,
8145 **		or 1 + the number of additional envelopes created.
8146 */
8147 
8148 #define SPLIT_LOG_LEVEL	8
8149 
8150 static int	split_within_queue __P((ENVELOPE *));
8151 
8152 static int
8153 split_within_queue(e)
8154 	ENVELOPE *e;
8155 {
8156 	int maxrcpt, nrcpt, ndead, nsplit, i;
8157 	int j, l;
8158 	char *lsplits;
8159 	ADDRESS *q, **addrs;
8160 	ENVELOPE *ee, *firstsibling;
8161 
8162 	if (!ISVALIDQGRP(e->e_qgrp) || bitset(EF_SPLIT, e->e_flags))
8163 		return SM_SPLIT_NONE;
8164 
8165 	/* don't bother if there is no recipient limit */
8166 	maxrcpt = Queue[e->e_qgrp]->qg_maxrcpt;
8167 	if (maxrcpt <= 0)
8168 		return SM_SPLIT_NONE;
8169 
8170 	/* count recipients */
8171 	nrcpt = 0;
8172 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
8173 	{
8174 		if (QS_IS_DEAD(q->q_state))
8175 			continue;
8176 		++nrcpt;
8177 	}
8178 	if (nrcpt <= maxrcpt)
8179 		return SM_SPLIT_NONE;
8180 
8181 	/*
8182 	**  Preserve the recipient list
8183 	**  so that we can restore it in case of error.
8184 	**  (But we discard dead addresses.)
8185 	*/
8186 
8187 	addrs = sm_rpool_malloc_x(e->e_rpool, nrcpt * sizeof(ADDRESS *));
8188 	for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next)
8189 	{
8190 		if (QS_IS_DEAD(q->q_state))
8191 			continue;
8192 		addrs[i++] = q;
8193 	}
8194 
8195 	/*
8196 	**  Partition the recipient list so that bad and sent addresses
8197 	**  come first. These will go with the original envelope, and
8198 	**  do not count towards the maxrcpt limit.
8199 	**  addrs[] does not contain QS_IS_DEAD() addresses.
8200 	*/
8201 
8202 	ndead = 0;
8203 	for (i = 0; i < nrcpt; ++i)
8204 	{
8205 		if (QS_IS_BADADDR(addrs[i]->q_state) ||
8206 		    QS_IS_SENT(addrs[i]->q_state) ||
8207 		    QS_IS_DEAD(addrs[i]->q_state)) /* for paranoia's sake */
8208 		{
8209 			if (i > ndead)
8210 			{
8211 				ADDRESS *tmp = addrs[i];
8212 
8213 				addrs[i] = addrs[ndead];
8214 				addrs[ndead] = tmp;
8215 			}
8216 			++ndead;
8217 		}
8218 	}
8219 
8220 	/* Check if no splitting required. */
8221 	if (nrcpt - ndead <= maxrcpt)
8222 		return SM_SPLIT_NONE;
8223 
8224 	/* fix links */
8225 	for (i = 0; i < nrcpt - 1; ++i)
8226 		addrs[i]->q_next = addrs[i + 1];
8227 	addrs[nrcpt - 1]->q_next = NULL;
8228 	e->e_sendqueue = addrs[0];
8229 
8230 	/* prepare buffer for logging */
8231 	if (LogLevel > SPLIT_LOG_LEVEL)
8232 	{
8233 		l = MAXLINE;
8234 		lsplits = sm_malloc(l);
8235 		if (lsplits != NULL)
8236 			*lsplits = '\0';
8237 		j = 0;
8238 	}
8239 	else
8240 	{
8241 		/* get rid of stupid compiler warnings */
8242 		lsplits = NULL;
8243 		j = l = 0;
8244 	}
8245 
8246 	/* split the envelope */
8247 	firstsibling = e->e_sibling;
8248 	i = maxrcpt + ndead;
8249 	nsplit = 0;
8250 	for (;;)
8251 	{
8252 		addrs[i - 1]->q_next = NULL;
8253 		ee = split_env(e, addrs[i], e->e_qgrp, e->e_qdir);
8254 		if (!dup_df(e, ee))
8255 		{
8256 
8257 			ee = firstsibling;
8258 			while (ee != NULL)
8259 			{
8260 				(void) unlink(queuename(ee, DATAFL_LETTER));
8261 				ee = ee->e_sibling;
8262 			}
8263 
8264 			/* Error.  Restore e's sibling & recipient lists. */
8265 			e->e_sibling = firstsibling;
8266 			for (i = 0; i < nrcpt - 1; ++i)
8267 				addrs[i]->q_next = addrs[i + 1];
8268 			if (lsplits != NULL)
8269 				sm_free(lsplits);
8270 			return SM_SPLIT_FAIL;
8271 		}
8272 
8273 		/* prepend the new envelope to e->e_sibling */
8274 		ee->e_sibling = e->e_sibling;
8275 		e->e_sibling = ee;
8276 		++nsplit;
8277 		if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8278 		{
8279 			if (j >= l - strlen(ee->e_id) - 3)
8280 			{
8281 				char *p;
8282 
8283 				l += MAXLINE;
8284 				p = sm_realloc(lsplits, l);
8285 				if (p == NULL)
8286 				{
8287 					/* let's try to get this done */
8288 					sm_free(lsplits);
8289 					lsplits = NULL;
8290 				}
8291 				else
8292 					lsplits = p;
8293 			}
8294 			if (lsplits != NULL)
8295 			{
8296 				if (j == 0)
8297 					j += sm_strlcat(lsplits + j,
8298 							ee->e_id,
8299 							l - j);
8300 				else
8301 					j += sm_strlcat2(lsplits + j,
8302 							 "; ",
8303 							 ee->e_id,
8304 							 l - j);
8305 				SM_ASSERT(j < l);
8306 			}
8307 		}
8308 		if (nrcpt - i <= maxrcpt)
8309 			break;
8310 		i += maxrcpt;
8311 	}
8312 	if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8313 	{
8314 		if (nsplit > 0)
8315 		{
8316 			sm_syslog(LOG_NOTICE, e->e_id,
8317 				  "split: maxrcpts=%d, rcpts=%d, count=%d, id%s=%s",
8318 				  maxrcpt, nrcpt - ndead, nsplit,
8319 				  nsplit > 1 ? "s" : "", lsplits);
8320 		}
8321 		sm_free(lsplits);
8322 	}
8323 	return SM_SPLIT_NEW(nsplit);
8324 }
8325 /*
8326 **  SPLIT_BY_RECIPIENT
8327 **
8328 **	Split an envelope with multiple recipients into multiple
8329 **	envelopes as required by the sendmail configuration.
8330 **
8331 **	Parameters:
8332 **		e -- envelope.
8333 **
8334 **	Results:
8335 **		Returns true on success, false on failure.
8336 **
8337 **	Side Effects:
8338 **		see split_across_queue_groups(), split_within_queue(e)
8339 */
8340 
8341 bool
8342 split_by_recipient(e)
8343 	ENVELOPE *e;
8344 {
8345 	int split, n, i, j, l;
8346 	char *lsplits;
8347 	ENVELOPE *ee, *next, *firstsibling;
8348 
8349 	if (OpMode == SM_VERIFY || !ISVALIDQGRP(e->e_qgrp) ||
8350 	    bitset(EF_SPLIT, e->e_flags))
8351 		return true;
8352 	n = split_across_queue_groups(e);
8353 	if (n == SM_SPLIT_FAIL)
8354 		return false;
8355 	firstsibling = ee = e->e_sibling;
8356 	if (n > 1 && LogLevel > SPLIT_LOG_LEVEL)
8357 	{
8358 		l = MAXLINE;
8359 		lsplits = sm_malloc(l);
8360 		if (lsplits != NULL)
8361 			*lsplits = '\0';
8362 		j = 0;
8363 	}
8364 	else
8365 	{
8366 		/* get rid of stupid compiler warnings */
8367 		lsplits = NULL;
8368 		j = l = 0;
8369 	}
8370 	for (i = 1; i < n; ++i)
8371 	{
8372 		next = ee->e_sibling;
8373 		if (split_within_queue(ee) == SM_SPLIT_FAIL)
8374 		{
8375 			e->e_sibling = firstsibling;
8376 			return false;
8377 		}
8378 		ee->e_flags |= EF_SPLIT;
8379 		if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8380 		{
8381 			if (j >= l - strlen(ee->e_id) - 3)
8382 			{
8383 				char *p;
8384 
8385 				l += MAXLINE;
8386 				p = sm_realloc(lsplits, l);
8387 				if (p == NULL)
8388 				{
8389 					/* let's try to get this done */
8390 					sm_free(lsplits);
8391 					lsplits = NULL;
8392 				}
8393 				else
8394 					lsplits = p;
8395 			}
8396 			if (lsplits != NULL)
8397 			{
8398 				if (j == 0)
8399 					j += sm_strlcat(lsplits + j,
8400 							ee->e_id, l - j);
8401 				else
8402 					j += sm_strlcat2(lsplits + j, "; ",
8403 							 ee->e_id, l - j);
8404 				SM_ASSERT(j < l);
8405 			}
8406 		}
8407 		ee = next;
8408 	}
8409 	if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL && n > 1)
8410 	{
8411 		sm_syslog(LOG_NOTICE, e->e_id, "split: count=%d, id%s=%s",
8412 			  n - 1, n > 2 ? "s" : "", lsplits);
8413 		sm_free(lsplits);
8414 	}
8415 	split = split_within_queue(e) != SM_SPLIT_FAIL;
8416 	if (split)
8417 		e->e_flags |= EF_SPLIT;
8418 	return split;
8419 }
8420 
8421 /*
8422 **  QUARANTINE_QUEUE_ITEM -- {un,}quarantine a single envelope
8423 **
8424 **	Add/remove quarantine reason and requeue appropriately.
8425 **
8426 **	Parameters:
8427 **		qgrp -- queue group for the item
8428 **		qdir -- queue directory in the given queue group
8429 **		e -- envelope information for the item
8430 **		reason -- quarantine reason, NULL means unquarantine.
8431 **
8432 **	Results:
8433 **		true if item changed, false otherwise
8434 **
8435 **	Side Effects:
8436 **		Changes quarantine tag in queue file and renames it.
8437 */
8438 
8439 static bool
8440 quarantine_queue_item(qgrp, qdir, e, reason)
8441 	int qgrp;
8442 	int qdir;
8443 	ENVELOPE *e;
8444 	char *reason;
8445 {
8446 	bool dirty = false;
8447 	bool failing = false;
8448 	bool foundq = false;
8449 	bool finished = false;
8450 	int fd;
8451 	int flags;
8452 	int oldtype;
8453 	int newtype;
8454 	int save_errno;
8455 	MODE_T oldumask = 0;
8456 	SM_FILE_T *oldqfp, *tempqfp;
8457 	char *bp;
8458 	int bufsize;
8459 	char oldqf[MAXPATHLEN];
8460 	char tempqf[MAXPATHLEN];
8461 	char newqf[MAXPATHLEN];
8462 	char buf[MAXLINE];
8463 
8464 	oldtype = queue_letter(e, ANYQFL_LETTER);
8465 	(void) sm_strlcpy(oldqf, queuename(e, ANYQFL_LETTER), sizeof(oldqf));
8466 	(void) sm_strlcpy(tempqf, queuename(e, NEWQFL_LETTER), sizeof(tempqf));
8467 
8468 	/*
8469 	**  Instead of duplicating all the open
8470 	**  and lock code here, tell readqf() to
8471 	**  do that work and return the open
8472 	**  file pointer in e_lockfp.  Note that
8473 	**  we must release the locks properly when
8474 	**  we are done.
8475 	*/
8476 
8477 	if (!readqf(e, true))
8478 	{
8479 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8480 				     "Skipping %s\n", qid_printname(e));
8481 		return false;
8482 	}
8483 	oldqfp = e->e_lockfp;
8484 
8485 	/* open the new queue file */
8486 	flags = O_CREAT|O_WRONLY|O_EXCL;
8487 	if (bitset(S_IWGRP, QueueFileMode))
8488 		oldumask = umask(002);
8489 	fd = open(tempqf, flags, QueueFileMode);
8490 	if (bitset(S_IWGRP, QueueFileMode))
8491 		(void) umask(oldumask);
8492 	RELEASE_QUEUE;
8493 
8494 	if (fd < 0)
8495 	{
8496 		save_errno = errno;
8497 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8498 				     "Skipping %s: Could not open %s: %s\n",
8499 				     qid_printname(e), tempqf,
8500 				     sm_errstring(save_errno));
8501 		(void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8502 		return false;
8503 	}
8504 	if (!lockfile(fd, tempqf, NULL, LOCK_EX|LOCK_NB))
8505 	{
8506 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8507 				     "Skipping %s: Could not lock %s\n",
8508 				     qid_printname(e), tempqf);
8509 		(void) close(fd);
8510 		(void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8511 		return false;
8512 	}
8513 
8514 	tempqfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd,
8515 			     SM_IO_WRONLY_B, NULL);
8516 	if (tempqfp == NULL)
8517 	{
8518 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8519 				     "Skipping %s: Could not lock %s\n",
8520 				     qid_printname(e), tempqf);
8521 		(void) close(fd);
8522 		(void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8523 		return false;
8524 	}
8525 
8526 	/* Copy the data over, changing the quarantine reason */
8527 	while (bufsize = sizeof(buf),
8528 	       (bp = fgetfolded(buf, &bufsize, oldqfp)) != NULL)
8529 	{
8530 		if (tTd(40, 4))
8531 			sm_dprintf("+++++ %s\n", bp);
8532 		switch (bp[0])
8533 		{
8534 		  case 'q':		/* quarantine reason */
8535 			foundq = true;
8536 			if (reason == NULL)
8537 			{
8538 				if (Verbose)
8539 				{
8540 					(void) sm_io_fprintf(smioout,
8541 							     SM_TIME_DEFAULT,
8542 							     "%s: Removed quarantine of \"%s\"\n",
8543 							     e->e_id, &bp[1]);
8544 				}
8545 				sm_syslog(LOG_INFO, e->e_id, "unquarantine");
8546 				dirty = true;
8547 			}
8548 			else if (strcmp(reason, &bp[1]) == 0)
8549 			{
8550 				if (Verbose)
8551 				{
8552 					(void) sm_io_fprintf(smioout,
8553 							     SM_TIME_DEFAULT,
8554 							     "%s: Already quarantined with \"%s\"\n",
8555 							     e->e_id, reason);
8556 				}
8557 				(void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8558 						     "q%s\n", reason);
8559 			}
8560 			else
8561 			{
8562 				if (Verbose)
8563 				{
8564 					(void) sm_io_fprintf(smioout,
8565 							     SM_TIME_DEFAULT,
8566 							     "%s: Quarantine changed from \"%s\" to \"%s\"\n",
8567 							     e->e_id, &bp[1],
8568 							     reason);
8569 				}
8570 				(void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8571 						     "q%s\n", reason);
8572 				sm_syslog(LOG_INFO, e->e_id, "quarantine=%s",
8573 					  reason);
8574 				dirty = true;
8575 			}
8576 			break;
8577 
8578 		  case 'S':
8579 			/*
8580 			**  If we are quarantining an unquarantined item,
8581 			**  need to put in a new 'q' line before it's
8582 			**  too late.
8583 			*/
8584 
8585 			if (!foundq && reason != NULL)
8586 			{
8587 				if (Verbose)
8588 				{
8589 					(void) sm_io_fprintf(smioout,
8590 							     SM_TIME_DEFAULT,
8591 							     "%s: Quarantined with \"%s\"\n",
8592 							     e->e_id, reason);
8593 				}
8594 				(void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8595 						     "q%s\n", reason);
8596 				sm_syslog(LOG_INFO, e->e_id, "quarantine=%s",
8597 					  reason);
8598 				foundq = true;
8599 				dirty = true;
8600 			}
8601 
8602 			/* Copy the line to the new file */
8603 			(void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8604 					     "%s\n", bp);
8605 			break;
8606 
8607 		  case '.':
8608 			finished = true;
8609 			/* FALLTHROUGH */
8610 
8611 		  default:
8612 			/* Copy the line to the new file */
8613 			(void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8614 					     "%s\n", bp);
8615 			break;
8616 		}
8617 		if (bp != buf)
8618 			sm_free(bp);
8619 	}
8620 
8621 	/* Make sure we read the whole old file */
8622 	errno = sm_io_error(tempqfp);
8623 	if (errno != 0 && errno != SM_IO_EOF)
8624 	{
8625 		save_errno = errno;
8626 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8627 				     "Skipping %s: Error reading %s: %s\n",
8628 				     qid_printname(e), oldqf,
8629 				     sm_errstring(save_errno));
8630 		failing = true;
8631 	}
8632 
8633 	if (!failing && !finished)
8634 	{
8635 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8636 				     "Skipping %s: Incomplete file: %s\n",
8637 				     qid_printname(e), oldqf);
8638 		failing = true;
8639 	}
8640 
8641 	/* Check if we actually changed anything or we can just bail now */
8642 	if (!dirty)
8643 	{
8644 		/* pretend we failed, even though we technically didn't */
8645 		failing = true;
8646 	}
8647 
8648 	/* Make sure we wrote things out safely */
8649 	if (!failing &&
8650 	    (sm_io_flush(tempqfp, SM_TIME_DEFAULT) != 0 ||
8651 	     ((SuperSafe == SAFE_REALLY ||
8652 	       SuperSafe == SAFE_REALLY_POSTMILTER ||
8653 	       SuperSafe == SAFE_INTERACTIVE) &&
8654 	      fsync(sm_io_getinfo(tempqfp, SM_IO_WHAT_FD, NULL)) < 0) ||
8655 	     ((errno = sm_io_error(tempqfp)) != 0)))
8656 	{
8657 		save_errno = errno;
8658 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8659 				     "Skipping %s: Error writing %s: %s\n",
8660 				     qid_printname(e), tempqf,
8661 				     sm_errstring(save_errno));
8662 		failing = true;
8663 	}
8664 
8665 
8666 	/* Figure out the new filename */
8667 	newtype = (reason == NULL ? NORMQF_LETTER : QUARQF_LETTER);
8668 	if (oldtype == newtype)
8669 	{
8670 		/* going to rename tempqf to oldqf */
8671 		(void) sm_strlcpy(newqf, oldqf, sizeof(newqf));
8672 	}
8673 	else
8674 	{
8675 		/* going to rename tempqf to new name based on newtype */
8676 		(void) sm_strlcpy(newqf, queuename(e, newtype), sizeof(newqf));
8677 	}
8678 
8679 	save_errno = 0;
8680 
8681 	/* rename tempqf to newqf */
8682 	if (!failing &&
8683 	    rename(tempqf, newqf) < 0)
8684 		save_errno = (errno == 0) ? EINVAL : errno;
8685 
8686 	/* Check rename() success */
8687 	if (!failing && save_errno != 0)
8688 	{
8689 		sm_syslog(LOG_DEBUG, e->e_id,
8690 			  "quarantine_queue_item: rename(%s, %s): %s",
8691 			  tempqf, newqf, sm_errstring(save_errno));
8692 
8693 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8694 				     "Error renaming %s to %s: %s\n",
8695 				     tempqf, newqf,
8696 				     sm_errstring(save_errno));
8697 		if (oldtype == newtype)
8698 		{
8699 			/*
8700 			**  Bail here since we don't know the state of
8701 			**  the filesystem and may need to keep tempqf
8702 			**  for the user to rescue us.
8703 			*/
8704 
8705 			RELEASE_QUEUE;
8706 			errno = save_errno;
8707 			syserr("!452 Error renaming control file %s", tempqf);
8708 			/* NOTREACHED */
8709 		}
8710 		else
8711 		{
8712 			/* remove new file (if rename() half completed) */
8713 			if (xunlink(newqf) < 0)
8714 			{
8715 				save_errno = errno;
8716 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8717 						     "Error removing %s: %s\n",
8718 						     newqf,
8719 						     sm_errstring(save_errno));
8720 			}
8721 
8722 			/* tempqf removed below */
8723 			failing = true;
8724 		}
8725 
8726 	}
8727 
8728 	/* If changing file types, need to remove old type */
8729 	if (!failing && oldtype != newtype)
8730 	{
8731 		if (xunlink(oldqf) < 0)
8732 		{
8733 			save_errno = errno;
8734 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8735 					     "Error removing %s: %s\n",
8736 					     oldqf, sm_errstring(save_errno));
8737 		}
8738 	}
8739 
8740 	/* see if anything above failed */
8741 	if (failing)
8742 	{
8743 		/* Something failed: remove new file, old file still there */
8744 		(void) xunlink(tempqf);
8745 	}
8746 
8747 	/*
8748 	**  fsync() after file operations to make sure metadata is
8749 	**  written to disk on filesystems in which renames are
8750 	**  not guaranteed.  It's ok if they fail, mail won't be lost.
8751 	*/
8752 
8753 	if (SuperSafe != SAFE_NO)
8754 	{
8755 		/* for soft-updates */
8756 		(void) fsync(sm_io_getinfo(tempqfp,
8757 					   SM_IO_WHAT_FD, NULL));
8758 
8759 		if (!failing)
8760 		{
8761 			/* for soft-updates */
8762 			(void) fsync(sm_io_getinfo(oldqfp,
8763 						   SM_IO_WHAT_FD, NULL));
8764 		}
8765 
8766 		/* for other odd filesystems */
8767 		SYNC_DIR(tempqf, false);
8768 	}
8769 
8770 	/* Close up shop */
8771 	RELEASE_QUEUE;
8772 	if (tempqfp != NULL)
8773 		(void) sm_io_close(tempqfp, SM_TIME_DEFAULT);
8774 	if (oldqfp != NULL)
8775 		(void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8776 
8777 	/* All went well */
8778 	return !failing;
8779 }
8780 
8781 /*
8782 **  QUARANTINE_QUEUE -- {un,}quarantine matching items in the queue
8783 **
8784 **	Read all matching queue items, add/remove quarantine
8785 **	reason, and requeue appropriately.
8786 **
8787 **	Parameters:
8788 **		reason -- quarantine reason, "." means unquarantine.
8789 **		qgrplimit -- limit to single queue group unless NOQGRP
8790 **
8791 **	Results:
8792 **		none.
8793 **
8794 **	Side Effects:
8795 **		Lots of changes to the queue.
8796 */
8797 
8798 void
8799 quarantine_queue(reason, qgrplimit)
8800 	char *reason;
8801 	int qgrplimit;
8802 {
8803 	int changed = 0;
8804 	int qgrp;
8805 
8806 	/* Convert internal representation of unquarantine */
8807 	if (reason != NULL && reason[0] == '.' && reason[1] == '\0')
8808 		reason = NULL;
8809 
8810 	if (reason != NULL)
8811 	{
8812 		/* clean it */
8813 		reason = newstr(denlstring(reason, true, true));
8814 	}
8815 
8816 	for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++)
8817 	{
8818 		int qdir;
8819 
8820 		if (qgrplimit != NOQGRP && qgrplimit != qgrp)
8821 			continue;
8822 
8823 		for (qdir = 0; qdir < Queue[qgrp]->qg_numqueues; qdir++)
8824 		{
8825 			int i;
8826 			int nrequests;
8827 
8828 			if (StopRequest)
8829 				stop_sendmail();
8830 
8831 			nrequests = gatherq(qgrp, qdir, true, NULL, NULL);
8832 
8833 			/* first see if there is anything */
8834 			if (nrequests <= 0)
8835 			{
8836 				if (Verbose)
8837 				{
8838 					(void) sm_io_fprintf(smioout,
8839 							     SM_TIME_DEFAULT, "%s: no matches\n",
8840 							     qid_printqueue(qgrp, qdir));
8841 				}
8842 				continue;
8843 			}
8844 
8845 			if (Verbose)
8846 			{
8847 				(void) sm_io_fprintf(smioout,
8848 						     SM_TIME_DEFAULT, "Processing %s:\n",
8849 						     qid_printqueue(qgrp, qdir));
8850 			}
8851 
8852 			for (i = 0; i < WorkListCount; i++)
8853 			{
8854 				ENVELOPE e;
8855 
8856 				if (StopRequest)
8857 					stop_sendmail();
8858 
8859 				/* setup envelope */
8860 				clearenvelope(&e, true, sm_rpool_new_x(NULL));
8861 				e.e_id = WorkList[i].w_name + 2;
8862 				e.e_qgrp = qgrp;
8863 				e.e_qdir = qdir;
8864 
8865 				if (tTd(70, 101))
8866 				{
8867 					sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8868 						      "Would do %s\n", e.e_id);
8869 					changed++;
8870 				}
8871 				else if (quarantine_queue_item(qgrp, qdir,
8872 							       &e, reason))
8873 					changed++;
8874 
8875 				/* clean up */
8876 				sm_rpool_free(e.e_rpool);
8877 				e.e_rpool = NULL;
8878 			}
8879 			if (WorkList != NULL)
8880 				sm_free(WorkList); /* XXX */
8881 			WorkList = NULL;
8882 			WorkListSize = 0;
8883 			WorkListCount = 0;
8884 		}
8885 	}
8886 	if (Verbose)
8887 	{
8888 		if (changed == 0)
8889 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8890 					     "No changes\n");
8891 		else
8892 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8893 					     "%d change%s\n",
8894 					     changed,
8895 					     changed == 1 ? "" : "s");
8896 	}
8897 }
8898