2 * Copyright (c) 1998-2005 Sendmail, Inc. and its suppliers.
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.
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.
17 SM_RCSID("@(#)$Id: queue.c,v 8.944 2005/02/17 23:58:58 ca Exp $")
21 # define RELEASE_QUEUE (void) 0
22 # define ST_INODE(st) (st).st_ino
24 # define sm_file_exists(errno) ((errno) == EEXIST)
26 # if HASFLOCK && defined(O_EXLOCK)
27 # define SM_OPEN_EXLOCK 1
28 # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL|O_EXLOCK)
29 # else /* HASFLOCK && defined(O_EXLOCK) */
30 # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL)
31 # endif /* HASFLOCK && defined(O_EXLOCK) */
33 #ifndef SM_OPEN_EXLOCK
34 # define SM_OPEN_EXLOCK 0
35 #endif /* ! SM_OPEN_EXLOCK */
39 ** QF_VERSION == 4 was sendmail 8.10/8.11 without _FFR_QUEUEDELAY
40 ** QF_VERSION == 5 was sendmail 8.10/8.11 with _FFR_QUEUEDELAY
41 ** QF_VERSION == 6 was sendmail 8.12 without _FFR_QUEUEDELAY
42 ** QF_VERSION == 7 was sendmail 8.12 with _FFR_QUEUEDELAY
43 ** QF_VERSION == 8 is sendmail 8.13
46 #define QF_VERSION 8 /* version number of this queue format */
48 static char queue_letter __P((ENVELOPE *, int));
49 static bool quarantine_queue_item __P((int, int, ENVELOPE *, char *));
51 /* Naming convention: qgrp: index of queue group, qg: QUEUEGROUP */
59 char *w_name; /* name of control file */
60 char *w_host; /* name of recipient host */
61 bool w_lock; /* is message locked? */
62 bool w_tooyoung; /* is it too young to run? */
63 long w_pri; /* priority of message, see below */
64 time_t w_ctime; /* creation time */
65 time_t w_mtime; /* modification time */
66 int w_qgrp; /* queue group located in */
67 int w_qdir; /* queue directory located in */
68 struct work *w_next; /* next in queue */
71 typedef struct work WORK;
73 static WORK *WorkQ; /* queue of things to be done */
74 static int NumWorkGroups; /* number of work groups */
75 static time_t Current_LA_time = 0;
77 /* Get new load average every 30 seconds. */
78 #define GET_NEW_LA_TIME 30
80 #define SM_GET_LA(now) \
84 if (Current_LA_time < now - GET_NEW_LA_TIME) \
87 Current_LA_time = now; \
92 ** DoQueueRun indicates that a queue run is needed.
93 ** Notice: DoQueueRun is modified in a signal handler!
96 static bool volatile DoQueueRun; /* non-interrupt time queue run needed */
99 ** Work group definition structure.
100 ** Each work group contains one or more queue groups. This is done
101 ** to manage the number of queue group runners active at the same time
102 ** to be within the constraints of MaxQueueChildren (if it is set).
103 ** The number of queue groups that can be run on the next work run
104 ** is kept track of. The queue groups are run in a round robin.
109 int wg_numqgrp; /* number of queue groups in work grp */
110 int wg_runners; /* total runners */
111 int wg_curqgrp; /* current queue group */
112 QUEUEGRP **wg_qgs; /* array of queue groups */
113 int wg_maxact; /* max # of active runners */
114 time_t wg_lowqintvl; /* lowest queue interval */
115 int wg_restart; /* needs restarting? */
116 int wg_restartcnt; /* count of times restarted */
119 typedef struct workgrp WORKGRP;
121 static WORKGRP volatile WorkGrp[MAXWORKGROUPS + 1]; /* work groups */
124 static SM_DEBUG_T DebugLeakQ = SM_DEBUG_INITIALIZER("leak_q",
125 "@(#)$Debug: leak_q - trace memory leaks during queue processing $");
126 #endif /* SM_HEAP_CHECK */
129 ** We use EmptyString instead of "" to avoid
130 ** 'zero-length format string' warnings from gcc
133 static const char EmptyString[] = "";
135 static void grow_wlist __P((int, int));
136 static int multiqueue_cache __P((char *, int, QUEUEGRP *, int, unsigned int *));
137 static int gatherq __P((int, int, bool, bool *, bool *));
138 static int sortq __P((int));
139 static void printctladdr __P((ADDRESS *, SM_FILE_T *));
140 static bool readqf __P((ENVELOPE *, bool));
141 static void restart_work_group __P((int));
142 static void runner_work __P((ENVELOPE *, int, bool, int, int));
143 static void schedule_queue_runs __P((bool, int, bool));
144 static char *strrev __P((char *));
145 static ADDRESS *setctluser __P((char *, int, ENVELOPE *));
147 static int sm_strshufflecmp __P((char *, char *));
148 static void init_shuffle_alphabet __P(());
149 #endif /* _FFR_RHS */
150 static int workcmpf0();
151 static int workcmpf1();
152 static int workcmpf2();
153 static int workcmpf3();
154 static int workcmpf4();
155 static int randi = 3; /* index for workcmpf5() */
156 static int workcmpf5();
157 static int workcmpf6();
159 static int workcmpf7();
160 #endif /* _FFR_RHS */
163 # define get_rand_mod(m) ((get_random() >> RANDOMSHIFT) % (m))
164 #else /* RANDOMSHIFT */
165 # define get_rand_mod(m) (get_random() % (m))
166 #endif /* RANDOMSHIFT */
169 ** File system definition.
170 ** Used to keep track of how much free space is available
171 ** on a file system in which one or more queue directories reside.
174 typedef struct filesys_shared FILESYS;
176 struct filesys_shared
178 dev_t fs_dev; /* unique device id */
179 long fs_avail; /* number of free blocks available */
180 long fs_blksize; /* block size, in bytes */
183 /* probably kept in shared memory */
184 static FILESYS FileSys[MAXFILESYS]; /* queue file systems */
185 static char *FSPath[MAXFILESYS]; /* pathnames for file systems */
190 ** Shared memory data
193 ** size -- size of shared memory segment
194 ** pid -- pid of owner, should be a unique id to avoid misinterpretations
195 ** by other processes.
196 ** tag -- should be a unique id to avoid misinterpretations by others.
197 ** idea: hash over configuration data that will be stored here.
198 ** NumFileSys -- number of file systems.
199 ** FileSys -- (arrary of) structure for used file systems.
200 ** RSATmpCnt -- counter for number of uses of ephemeral RSA key.
201 ** QShm -- (array of) structure for information about queue directories.
205 ** Queue data in shared memory
208 typedef struct queue_shared QUEUE_SHM_T;
212 int qs_entries; /* number of entries */
213 /* XXX more to follow? */
216 static void *Pshm; /* pointer to shared memory */
217 static FILESYS *PtrFileSys; /* pointer to queue file system array */
218 int ShmId = SM_SHM_NO_ID; /* shared memory id */
219 static QUEUE_SHM_T *QShm; /* pointer to shared queue data */
222 # define SHM_OFF_PID(p) (((char *) (p)) + sizeof(int))
223 # define SHM_OFF_TAG(p) (((char *) (p)) + sizeof(pid_t) + sizeof(int))
224 # define SHM_OFF_HEAD (sizeof(pid_t) + sizeof(int) * 2)
226 /* how to access FileSys */
227 # define FILE_SYS(i) (PtrFileSys[i])
229 /* first entry is a tag, for now just the size */
230 # define OFF_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD)
232 /* offset for PNumFileSys */
233 # define OFF_NUM_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys))
235 /* offset for PRSATmpCnt */
236 # define OFF_RSA_TMP_CNT(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int))
239 /* offset for queue_shm */
240 # define OFF_QUEUE_SHM(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2)
242 # define QSHM_ENTRIES(i) QShm[i].qs_entries
244 /* basic size of shared memory segment */
245 # define SM_T_SIZE (SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2)
247 static unsigned int hash_q __P((char *, unsigned int));
250 ** HASH_Q -- simple hash function
253 ** p -- string to hash.
254 ** h -- hash start value (from previous run).
272 h += (c<<11) ^ (c>>1);
273 h ^= (d<<14) + (d<<7) + (d<<4) + d;
279 #else /* SM_CONF_SHM */
280 # define FILE_SYS(i) FileSys[i]
281 #endif /* SM_CONF_SHM */
283 /* access to the various components of file system data */
284 #define FILE_SYS_NAME(i) FSPath[i]
285 #define FILE_SYS_AVAIL(i) FILE_SYS(i).fs_avail
286 #define FILE_SYS_BLKSIZE(i) FILE_SYS(i).fs_blksize
287 #define FILE_SYS_DEV(i) FILE_SYS(i).fs_dev
291 ** Current qf file field assignments:
295 ** C controlling user
297 ** d data file directory name (added in 8.12)
300 ** G free (was: queue delay algorithm if _FFR_QUEUEDELAY)
302 ** I data file's inode number
303 ** K time of last delivery attempt
304 ** L Solaris Content-Length: header (obsolete)
306 ** N number of delivery attempts
307 ** P message priority
308 ** q quarantine reason
309 ** Q original recipient (ORCPT=)
310 ** r final recipient (Final-Recipient: DSN field)
314 ** V queue file version
315 ** X free (was: character set if _FFR_SAVE_CHARSET)
316 ** Y free (was: current delay if _FFR_QUEUEDELAY)
317 ** Z original envelope id from ESMTP
318 ** ! deliver by (added in 8.12)
324 ** QUEUEUP -- queue a message up for future transmission.
327 ** e -- the envelope to queue up.
328 ** announce -- if true, tell when you are queueing up.
329 ** msync -- if true, then fsync() if SuperSafe interactive mode.
335 ** The current request is saved in a control file.
336 ** The queue file is left locked.
340 queueup(e, announce, msync)
341 register ENVELOPE *e;
345 register SM_FILE_T *tfp;
360 ** Create control file.
365 MODE_T oldumask = 0; \
367 if (bitset(S_IWGRP, QueueFileMode)) \
368 oldumask = umask(002); \
369 tfd = open(tf, TF_OPEN_FLAGS, QueueFileMode); \
370 if (bitset(S_IWGRP, QueueFileMode)) \
371 (void) umask(oldumask); \
375 newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags);
376 (void) sm_strlcpy(tf, queuename(e, NEWQFL_LETTER), sizeof tf);
378 if (tfp == NULL && newid)
381 ** open qf file directly: this will give an error if the file
382 ** already exists and hence prevent problems if a queue-id
383 ** is reused (e.g., because the clock is set back).
386 (void) sm_strlcpy(tf, queuename(e, ANYQFL_LETTER), sizeof tf);
390 !lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB) ||
391 #endif /* !SM_OPEN_EXLOCK */
392 (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
393 (void *) &tfd, SM_IO_WRONLY,
396 int save_errno = errno;
400 syserr("!queueup: cannot create queue file %s, euid=%d, fd=%d, fp=%p",
401 tf, (int) geteuid(), tfd, tfp);
405 upd_qs(e, 1, 0, "queueup");
408 /* if newid, write the queue file directly (instead of temp file) */
411 /* get a locked tf file */
412 for (i = 0; i < 128; i++)
421 if (LogLevel > 0 && (i % 32) == 0)
422 sm_syslog(LOG_ALERT, e->e_id,
423 "queueup: cannot create %s, uid=%d: %s",
425 sm_errstring(errno));
430 #endif /* SM_OPEN_EXLOCK */
435 /* file is locked by open() */
437 #else /* SM_OPEN_EXLOCK */
438 if (lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB))
441 #endif /* SM_OPEN_EXLOCK */
442 if (LogLevel > 0 && (i % 32) == 0)
443 sm_syslog(LOG_ALERT, e->e_id,
444 "queueup: cannot lock %s: %s",
445 tf, sm_errstring(errno));
455 /* save the old temp file away */
456 (void) rename(tf, queuename(e, TEMPQF_LETTER));
459 (void) sleep(i % 32);
461 if (tfd < 0 || (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
462 (void *) &tfd, SM_IO_WRONLY_B,
465 int save_errno = errno;
469 syserr("!queueup: cannot create queue temp file %s, uid=%d",
470 tf, (int) geteuid());
475 sm_dprintf("\n>>>>> queueing %s/%s%s >>>>>\n",
476 qid_printqueue(e->e_qgrp, e->e_qdir),
477 queuename(e, ANYQFL_LETTER),
478 newid ? " (new id)" : "");
481 sm_dprintf(" e_flags=");
486 sm_dprintf(" sendq=");
487 printaddr(sm_debug_file(), e->e_sendqueue, true);
492 dumpfd(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL), true, false);
493 sm_dprintf(" lockfp=");
494 if (e->e_lockfp == NULL)
495 sm_dprintf("NULL\n");
497 dumpfd(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL),
502 ** If there is no data file yet, create one.
505 (void) sm_strlcpy(df, queuename(e, DATAFL_LETTER), sizeof df);
506 if (bitset(EF_HAS_DF, e->e_flags))
508 if (e->e_dfp != NULL &&
509 SuperSafe != SAFE_REALLY &&
510 SuperSafe != SAFE_REALLY_POSTMILTER &&
511 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 &&
514 syserr("!queueup: cannot commit data file %s, uid=%d",
515 queuename(e, DATAFL_LETTER), (int) geteuid());
517 if (e->e_dfp != NULL &&
518 SuperSafe == SAFE_INTERACTIVE && msync)
521 sm_syslog(LOG_INFO, e->e_id,
522 "queueup: fsync(e->e_dfp)");
524 if (fsync(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD,
528 syserr("!552 Error writing data file %s",
531 syserr("!452 Error writing data file %s",
540 register SM_FILE_T *dfp = NULL;
543 if (e->e_dfp != NULL &&
544 sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE))
545 syserr("committing over bf file");
547 if (bitset(S_IWGRP, QueueFileMode))
548 oldumask = umask(002);
549 dfd = open(df, O_WRONLY|O_CREAT|O_TRUNC|QF_O_EXTRA,
551 if (bitset(S_IWGRP, QueueFileMode))
552 (void) umask(oldumask);
553 if (dfd < 0 || (dfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
554 (void *) &dfd, SM_IO_WRONLY_B,
556 syserr("!queueup: cannot create data temp file %s, uid=%d",
557 df, (int) geteuid());
558 if (fstat(dfd, &stbuf) < 0)
562 e->e_dfdev = stbuf.st_dev;
563 e->e_dfino = ST_INODE(stbuf);
565 e->e_flags |= EF_HAS_DF;
566 memset(&mcibuf, '\0', sizeof mcibuf);
567 mcibuf.mci_out = dfp;
568 mcibuf.mci_mailer = FileMailer;
569 (*e->e_putbody)(&mcibuf, e, NULL);
571 if (SuperSafe == SAFE_REALLY ||
572 SuperSafe == SAFE_REALLY_POSTMILTER ||
573 (SuperSafe == SAFE_INTERACTIVE && msync))
576 sm_syslog(LOG_INFO, e->e_id,
577 "queueup: fsync(dfp)");
579 if (fsync(sm_io_getinfo(dfp, SM_IO_WHAT_FD, NULL)) < 0)
582 syserr("!552 Error writing data file %s",
585 syserr("!452 Error writing data file %s",
590 if (sm_io_close(dfp, SM_TIME_DEFAULT) < 0)
591 syserr("!queueup: cannot save data temp file %s, uid=%d",
592 df, (int) geteuid());
593 e->e_putbody = putbody;
597 ** Output future work requests.
598 ** Priority and creation time should be first, since
599 ** they are required by gatherq.
602 /* output queue version number (must be first!) */
603 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "V%d\n", QF_VERSION);
605 /* output creation time */
606 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "T%ld\n", (long) e->e_ctime);
608 /* output last delivery time */
609 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "K%ld\n", (long) e->e_dtime);
611 /* output number of delivery attempts */
612 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "N%d\n", e->e_ntries);
614 /* output message priority */
615 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "P%ld\n", e->e_msgpriority);
618 ** If data file is in a different directory than the queue file,
619 ** output a "d" record naming the directory of the data file.
622 if (e->e_dfqgrp != e->e_qgrp)
624 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "d%s\n",
625 Queue[e->e_dfqgrp]->qg_qpaths[e->e_dfqdir].qp_name);
628 /* output inode number of data file */
629 /* XXX should probably include device major/minor too */
630 if (e->e_dfino != -1)
632 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "I%ld/%ld/%llu\n",
633 (long) major(e->e_dfdev),
634 (long) minor(e->e_dfdev),
635 (ULONGLONG_T) e->e_dfino);
638 /* output body type */
639 if (e->e_bodytype != NULL)
640 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "B%s\n",
641 denlstring(e->e_bodytype, true, false));
643 /* quarantine reason */
644 if (e->e_quarmsg != NULL)
645 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "q%s\n",
646 denlstring(e->e_quarmsg, true, false));
648 /* message from envelope, if it exists */
649 if (e->e_message != NULL)
650 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n",
651 denlstring(e->e_message, true, false));
653 /* send various flag bits through */
655 if (bitset(EF_WARNING, e->e_flags))
657 if (bitset(EF_RESPONSE, e->e_flags))
659 if (bitset(EF_HAS8BIT, e->e_flags))
661 if (bitset(EF_DELETE_BCC, e->e_flags))
663 if (bitset(EF_RET_PARAM, e->e_flags))
665 if (bitset(EF_NO_BODY_RETN, e->e_flags))
667 if (bitset(EF_SPLIT, e->e_flags))
671 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "F%s\n", buf);
673 /* save $={persistentMacros} macro values */
674 queueup_macros(macid("{persistentMacros}"), tfp, e);
676 /* output name of sender */
677 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
680 p = e->e_from.q_paddr;
681 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "S%s\n",
682 denlstring(p, true, false));
684 /* output ESMTP-supplied "original" information */
685 if (e->e_envid != NULL)
686 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Z%s\n",
687 denlstring(e->e_envid, true, false));
689 /* output AUTH= parameter */
690 if (e->e_auth_param != NULL)
691 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "A%s\n",
692 denlstring(e->e_auth_param, true, false));
693 if (e->e_dlvr_flag != 0)
694 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "!%c %ld\n",
695 (char) e->e_dlvr_flag, e->e_deliver_by);
697 /* output list of recipient addresses */
698 printctladdr(NULL, NULL);
699 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
701 if (!QS_IS_UNDELIVERED(q->q_state))
704 /* message for this recipient, if it exists */
705 if (q->q_message != NULL)
706 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n",
707 denlstring(q->q_message, true,
710 printctladdr(q, tfp);
711 if (q->q_orcpt != NULL)
712 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Q%s\n",
713 denlstring(q->q_orcpt, true,
715 if (q->q_finalrcpt != NULL)
716 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "r%s\n",
717 denlstring(q->q_finalrcpt, true,
719 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'R');
720 if (bitset(QPRIMARY, q->q_flags))
721 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'P');
722 if (bitset(QHASNOTIFY, q->q_flags))
723 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'N');
724 if (bitset(QPINGONSUCCESS, q->q_flags))
725 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'S');
726 if (bitset(QPINGONFAILURE, q->q_flags))
727 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'F');
728 if (bitset(QPINGONDELAY, q->q_flags))
729 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'D');
730 if (q->q_alias != NULL &&
731 bitset(QALIAS, q->q_alias->q_flags))
732 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'A');
733 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, ':');
734 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s\n",
735 denlstring(q->q_paddr, true, false));
738 char *tag = "queued";
740 if (e->e_quarmsg != NULL)
743 e->e_to = q->q_paddr;
746 logdelivery(q->q_mailer, NULL, q->q_status,
747 tag, NULL, (time_t) 0, e);
752 sm_dprintf("queueing ");
753 printaddr(sm_debug_file(), q, false);
758 ** Output headers for this message.
759 ** Expand macros completely here. Queue run will deal with
760 ** everything as absolute headers.
761 ** All headers that must be relative to the recipient
762 ** can be cracked later.
763 ** We set up a "null mailer" -- i.e., a mailer that will have
764 ** no effect on the addresses as they are output.
767 memset((char *) &nullmailer, '\0', sizeof nullmailer);
768 nullmailer.m_re_rwset = nullmailer.m_rh_rwset =
769 nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1;
770 nullmailer.m_eol = "\n";
771 memset(&mcibuf, '\0', sizeof mcibuf);
772 mcibuf.mci_mailer = &nullmailer;
773 mcibuf.mci_out = tfp;
775 macdefine(&e->e_macro, A_PERM, 'g', "\201f");
776 for (h = e->e_header; h != NULL; h = h->h_link)
778 if (h->h_value == NULL)
781 /* don't output resent headers on non-resent messages */
782 if (bitset(H_RESENT, h->h_flags) &&
783 !bitset(EF_RESENT, e->e_flags))
786 /* expand macros; if null, don't output header at all */
787 if (bitset(H_DEFAULT, h->h_flags))
789 (void) expand(h->h_value, buf, sizeof buf, e);
794 /* output this header */
795 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "H?");
797 /* output conditional macro if present */
798 if (h->h_macro != '\0')
800 if (bitset(0200, h->h_macro))
801 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT,
803 macname(bitidx(h->h_macro)));
805 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT,
808 else if (!bitzerop(h->h_mflags) &&
809 bitset(H_CHECK|H_ACHECK, h->h_flags))
813 /* if conditional, output the set of conditions */
814 for (j = '\0'; j <= '\177'; j++)
815 if (bitnset(j, h->h_mflags))
816 (void) sm_io_putc(tfp, SM_TIME_DEFAULT,
819 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, '?');
821 /* output the header: expand macros, convert addresses */
822 if (bitset(H_DEFAULT, h->h_flags) &&
823 !bitset(H_BINDLATE, h->h_flags))
825 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s: %s\n",
827 denlstring(buf, false, true));
829 else if (bitset(H_FROM|H_RCPT, h->h_flags) &&
830 !bitset(H_BINDLATE, h->h_flags))
832 bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
833 SM_FILE_T *savetrace = TrafficLogFile;
835 TrafficLogFile = NULL;
837 if (bitset(H_FROM, h->h_flags))
840 commaize(h, h->h_value, oldstyle, &mcibuf, e);
842 TrafficLogFile = savetrace;
846 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s: %s\n",
848 denlstring(h->h_value, false,
856 ** Write a terminator record -- this is to prevent
857 ** scurrilous crackers from appending any data.
860 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ".\n");
862 if (sm_io_flush(tfp, SM_TIME_DEFAULT) != 0 ||
863 ((SuperSafe == SAFE_REALLY ||
864 SuperSafe == SAFE_REALLY_POSTMILTER ||
865 (SuperSafe == SAFE_INTERACTIVE && msync)) &&
866 fsync(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL)) < 0) ||
870 syserr("!552 Error writing control file %s", tf);
872 syserr("!452 Error writing control file %s", tf);
877 char new = queue_letter(e, ANYQFL_LETTER);
879 /* rename (locked) tf to be (locked) [qh]f */
880 (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER),
882 if (rename(tf, qf) < 0)
883 syserr("cannot rename(%s, %s), uid=%d",
884 tf, qf, (int) geteuid());
888 ** Check if type has changed and only
889 ** remove the old item if the rename above
893 if (e->e_qfletter != '\0' &&
894 e->e_qfletter != new)
898 sm_dprintf("type changed from %c to %c\n",
902 if (unlink(queuename(e, e->e_qfletter)) < 0)
904 /* XXX: something more drastic? */
906 sm_syslog(LOG_ERR, e->e_id,
907 "queueup: unlink(%s) failed: %s",
908 queuename(e, e->e_qfletter),
909 sm_errstring(errno));
916 ** fsync() after renaming to make sure metadata is
917 ** written to disk on filesystems in which renames are
921 if (SuperSafe != SAFE_NO)
923 /* for softupdates */
924 if (tfd >= 0 && fsync(tfd) < 0)
926 syserr("!queueup: cannot fsync queue temp file %s",
932 /* close and unlock old (locked) queue file */
933 if (e->e_lockfp != NULL)
934 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
939 sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", qf);
945 sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", tf);
947 e->e_qfletter = queue_letter(e, ANYQFL_LETTER);
951 e->e_flags |= EF_INQUEUE;
954 sm_dprintf("<<<<< done queueing %s <<<<<\n\n", e->e_id);
959 ** PRINTCTLADDR -- print control address to file.
963 ** tfp -- file pointer.
969 ** The control address (if changed) is printed to the file.
970 ** The last control address and uid are saved.
982 static ADDRESS *lastctladdr = NULL;
983 static uid_t lastuid;
986 if (a == NULL || a->q_alias == NULL || tfp == NULL)
988 if (lastctladdr != NULL && tfp != NULL)
989 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C\n");
995 /* find the active uid */
1005 user = q->q_ruser != NULL ? q->q_ruser : q->q_user;
1011 /* check to see if this is the same as last time */
1012 if (lastctladdr != NULL && uid == lastuid &&
1013 strcmp(lastctladdr->q_paddr, a->q_paddr) == 0)
1018 if (uid == 0 || user == NULL || user[0] == '\0')
1019 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C");
1021 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C%s:%ld:%ld",
1022 denlstring(user, true, false), (long) uid,
1024 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ":%s\n",
1025 denlstring(a->q_paddr, true, false));
1029 ** RUNNERS_SIGTERM -- propagate a SIGTERM to queue runner process
1031 ** This propagates the signal to the child processes that are queue
1032 ** runners. This is for a queue runner "cleanup". After all of the
1033 ** child queue runner processes are signaled (it should be SIGTERM
1034 ** being the sig) then the old signal handler (Oldsh) is called
1035 ** to handle any cleanup set for this process (provided it is not
1036 ** SIG_DFL or SIG_IGN). The signal may not be handled immediately
1037 ** if the BlockOldsh flag is set. If the current process doesn't
1038 ** have a parent then handle the signal immediately, regardless of
1042 ** sig -- the signal number being sent
1048 ** Sets the NoMoreRunners boolean to true to stop more runners
1049 ** from being started in runqueue().
1051 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1052 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1056 static bool volatile NoMoreRunners = false;
1057 static sigfunc_t Oldsh_term = SIG_DFL;
1058 static sigfunc_t Oldsh_hup = SIG_DFL;
1059 static sigfunc_t volatile Oldsh = SIG_DFL;
1060 static bool BlockOldsh = false;
1061 static int volatile Oldsig = 0;
1062 static SIGFUNC_DECL runners_sigterm __P((int));
1063 static SIGFUNC_DECL runners_sighup __P((int));
1066 runners_sigterm(sig)
1069 int save_errno = errno;
1071 FIX_SYSV_SIGNAL(sig, runners_sigterm);
1073 CHECK_CRITICAL(sig);
1074 NoMoreRunners = true;
1077 proc_list_signal(PROC_QUEUE, sig);
1079 if (!BlockOldsh || getppid() <= 1)
1081 /* Check that a valid 'old signal handler' is callable */
1082 if (Oldsh_term != SIG_DFL && Oldsh_term != SIG_IGN &&
1083 Oldsh_term != runners_sigterm)
1087 return SIGFUNC_RETURN;
1090 ** RUNNERS_SIGHUP -- propagate a SIGHUP to queue runner process
1092 ** This propagates the signal to the child processes that are queue
1093 ** runners. This is for a queue runner "cleanup". After all of the
1094 ** child queue runner processes are signaled (it should be SIGHUP
1095 ** being the sig) then the old signal handler (Oldsh) is called to
1096 ** handle any cleanup set for this process (provided it is not SIG_DFL
1097 ** or SIG_IGN). The signal may not be handled immediately if the
1098 ** BlockOldsh flag is set. If the current process doesn't have
1099 ** a parent then handle the signal immediately, regardless of
1103 ** sig -- the signal number being sent
1109 ** Sets the NoMoreRunners boolean to true to stop more runners
1110 ** from being started in runqueue().
1112 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1113 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1121 int save_errno = errno;
1123 FIX_SYSV_SIGNAL(sig, runners_sighup);
1125 CHECK_CRITICAL(sig);
1126 NoMoreRunners = true;
1129 proc_list_signal(PROC_QUEUE, sig);
1131 if (!BlockOldsh || getppid() <= 1)
1133 /* Check that a valid 'old signal handler' is callable */
1134 if (Oldsh_hup != SIG_DFL && Oldsh_hup != SIG_IGN &&
1135 Oldsh_hup != runners_sighup)
1139 return SIGFUNC_RETURN;
1142 ** MARK_WORK_GROUP_RESTART -- mark a work group as needing a restart
1144 ** Sets a workgroup for restarting.
1147 ** wgrp -- the work group id to restart.
1148 ** reason -- why (signal?), -1 to turn off restart
1154 ** May set global RestartWorkGroup to true.
1156 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
1157 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1162 mark_work_group_restart(wgrp, reason)
1166 if (wgrp < 0 || wgrp > NumWorkGroups)
1169 WorkGrp[wgrp].wg_restart = reason;
1171 RestartWorkGroup = true;
1174 ** RESTART_MARKED_WORK_GROUPS -- restart work groups marked as needing restart
1176 ** Restart any workgroup marked as needing a restart provided more
1177 ** runners are allowed.
1186 ** Sets global RestartWorkGroup to false.
1190 restart_marked_work_groups()
1198 /* Block SIGCHLD so reapchild() doesn't mess with us */
1199 wasblocked = sm_blocksignal(SIGCHLD);
1201 for (i = 0; i < NumWorkGroups; i++)
1203 if (WorkGrp[i].wg_restart >= 0)
1206 sm_syslog(LOG_ERR, NOQID,
1207 "restart queue runner=%d due to signal 0x%x",
1208 i, WorkGrp[i].wg_restart);
1209 restart_work_group(i);
1212 RestartWorkGroup = false;
1214 if (wasblocked == 0)
1215 (void) sm_releasesignal(SIGCHLD);
1218 ** RESTART_WORK_GROUP -- restart a specific work group
1220 ** Restart a specific workgroup provided more runners are allowed.
1221 ** If the requested work group has been restarted too many times log
1222 ** this and refuse to restart.
1225 ** wgrp -- the work group id to restart
1231 ** starts another process doing the work of wgrp
1234 #define MAX_PERSIST_RESTART 10 /* max allowed number of restarts */
1237 restart_work_group(wgrp)
1240 if (NoMoreRunners ||
1241 wgrp < 0 || wgrp > NumWorkGroups)
1244 WorkGrp[wgrp].wg_restart = -1;
1245 if (WorkGrp[wgrp].wg_restartcnt < MAX_PERSIST_RESTART)
1247 /* avoid overflow; increment here */
1248 WorkGrp[wgrp].wg_restartcnt++;
1249 (void) run_work_group(wgrp, RWG_FORK|RWG_PERSISTENT|RWG_RUNALL);
1253 sm_syslog(LOG_ERR, NOQID,
1254 "ERROR: persistent queue runner=%d restarted too many times, queue runner lost",
1259 ** SCHEDULE_QUEUE_RUNS -- schedule the next queue run for a work group.
1262 ** runall -- schedule even if individual bit is not set.
1263 ** wgrp -- the work group id to schedule.
1264 ** didit -- the queue run was performed for this work group.
1270 #define INCR_MOD(v, m) if (++v >= m) \
1275 schedule_queue_runs(runall, wgrp, didit)
1280 int qgrp, cgrp, endgrp;
1281 #if _FFR_QUEUE_SCHED_DBG
1284 #endif /* _FFR_QUEUE_SCHED_DBG */
1289 ** This is a bit ugly since we have to duplicate the
1290 ** code that "walks" through a work queue group.
1295 cgrp = endgrp = WorkGrp[wgrp].wg_curqgrp;
1300 #if _FFR_QUEUE_SCHED_DBG
1303 #endif /* _FFR_QUEUE_SCHED_DBG */
1304 qgrp = WorkGrp[wgrp].wg_qgs[cgrp]->qg_index;
1305 if (Queue[qgrp]->qg_queueintvl > 0)
1306 qintvl = Queue[qgrp]->qg_queueintvl;
1307 else if (QueueIntvl > 0)
1308 qintvl = QueueIntvl;
1310 qintvl = (time_t) 0;
1311 #if _FFR_QUEUE_SCHED_DBG
1312 lastsched = Queue[qgrp]->qg_nextrun;
1313 #endif /* _FFR_QUEUE_SCHED_DBG */
1314 if ((runall || Queue[qgrp]->qg_nextrun <= now) && qintvl > 0)
1316 #if _FFR_QUEUE_SCHED_DBG
1318 #endif /* _FFR_QUEUE_SCHED_DBG */
1319 if (minqintvl == 0 || qintvl < minqintvl)
1323 ** Only set a new time if a queue run was performed
1324 ** for this queue group. If the queue was not run,
1325 ** we could starve it by setting a new time on each
1330 Queue[qgrp]->qg_nextrun += qintvl;
1332 #if _FFR_QUEUE_SCHED_DBG
1334 sm_syslog(LOG_INFO, NOQID,
1335 "sqr: wgrp=%d, cgrp=%d, qgrp=%d, intvl=%ld, QI=%ld, runall=%d, lastrun=%ld, nextrun=%ld, sched=%d",
1336 wgrp, cgrp, qgrp, Queue[qgrp]->qg_queueintvl,
1337 QueueIntvl, runall, lastsched,
1338 Queue[qgrp]->qg_nextrun, sched);
1339 #endif /* _FFR_QUEUE_SCHED_DBG */
1340 INCR_MOD(cgrp, WorkGrp[wgrp].wg_numqgrp);
1341 } while (endgrp != cgrp);
1343 (void) sm_setevent(minqintvl, runqueueevent, 0);
1346 #if _FFR_QUEUE_RUN_PARANOIA
1348 ** CHECKQUEUERUNNER -- check whether a queue group hasn't been run.
1350 ** Use this if events may get lost and hence queue runners may not
1351 ** be started and mail will pile up in a queue.
1357 ** true if a queue run is necessary.
1360 ** may schedule a queue run.
1367 time_t now, minqintvl;
1371 for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++)
1375 if (Queue[qgrp]->qg_queueintvl > 0)
1376 qintvl = Queue[qgrp]->qg_queueintvl;
1377 else if (QueueIntvl > 0)
1378 qintvl = QueueIntvl;
1380 qintvl = (time_t) 0;
1381 if (Queue[qgrp]->qg_nextrun <= now - qintvl)
1383 if (minqintvl == 0 || qintvl < minqintvl)
1386 sm_syslog(LOG_WARNING, NOQID,
1387 "checkqueuerunner: queue %d should have been run at %s, queue interval %ld",
1389 arpadate(ctime(&Queue[qgrp]->qg_nextrun)),
1395 (void) sm_setevent(minqintvl, runqueueevent, 0);
1400 #endif /* _FFR_QUEUE_RUN_PARANOIA */
1403 ** RUNQUEUE -- run the jobs in the queue.
1405 ** Gets the stuff out of the queue in some presumably logical
1406 ** order and processes them.
1409 ** forkflag -- true if the queue scanning should be done in
1410 ** a child process. We double-fork so it is not our
1411 ** child and we don't have to clean up after it.
1412 ** false can be ignored if we have multiple queues.
1413 ** verbose -- if true, print out status information.
1414 ** persistent -- persistent queue runner?
1415 ** runall -- run all groups or only a subset (DoQueueRun)?
1418 ** true if the queue run successfully began.
1421 ** runs things in the mail queue using run_work_group().
1422 ** maybe schedules next queue run.
1425 static ENVELOPE QueueEnvelope; /* the queue run envelope */
1426 static time_t LastQueueTime = 0; /* last time a queue ID assigned */
1427 static pid_t LastQueuePid = -1; /* last PID which had a queue ID */
1429 /* values for qp_supdirs */
1430 #define QP_NOSUB 0x0000 /* No subdirectories */
1431 #define QP_SUBDF 0x0001 /* "df" subdirectory */
1432 #define QP_SUBQF 0x0002 /* "qf" subdirectory */
1433 #define QP_SUBXF 0x0004 /* "xf" subdirectory */
1436 runqueue(forkflag, verbose, persistent, runall)
1444 static int curnum = 0;
1447 SM_NONVOLATILE int oldgroup = 0;
1449 if (sm_debug_active(&DebugLeakQ, 1))
1451 oldgroup = sm_heap_group();
1453 sm_dprintf("runqueue() heap group #%d\n", sm_heap_group());
1455 #endif /* SM_HEAP_CHECK */
1457 /* queue run has been started, don't do any more this time */
1460 /* more than one queue or more than one directory per queue */
1461 if (!forkflag && !verbose &&
1462 (WorkGrp[0].wg_qgs[0]->qg_numqueues > 1 || NumWorkGroups > 1 ||
1463 WorkGrp[0].wg_numqgrp > 1))
1467 ** For controlling queue runners via signals sent to this process.
1468 ** Oldsh* will get called too by runners_sig* (if it is not SIG_IGN
1469 ** or SIG_DFL) to preserve cleanup behavior. Now that this process
1470 ** will have children (and perhaps grandchildren) this handler will
1471 ** be left in place. This is because this process, once it has
1472 ** finished spinning off queue runners, may go back to doing something
1473 ** else (like being a daemon). And we still want on a SIG{TERM,HUP} to
1474 ** clean up the child queue runners. Only install 'runners_sig*' once
1475 ** else we'll get stuck looping forever.
1478 cursh = sm_signal(SIGTERM, runners_sigterm);
1479 if (cursh != runners_sigterm)
1481 cursh = sm_signal(SIGHUP, runners_sighup);
1482 if (cursh != runners_sighup)
1485 for (i = 0; i < NumWorkGroups && !NoMoreRunners; i++)
1487 int rwgflags = RWG_NONE;
1490 ** If MaxQueueChildren active then test whether the start
1491 ** of the next queue group's additional queue runners (maximum)
1492 ** will result in MaxQueueChildren being exceeded.
1494 ** Note: do not use continue; even though another workgroup
1495 ** may have fewer queue runners, this would be "unfair",
1496 ** i.e., this work group might "starve" then.
1499 #if _FFR_QUEUE_SCHED_DBG
1501 sm_syslog(LOG_INFO, NOQID,
1502 "rq: curnum=%d, MaxQueueChildren=%d, CurRunners=%d, WorkGrp[curnum].wg_maxact=%d",
1503 curnum, MaxQueueChildren, CurRunners,
1504 WorkGrp[curnum].wg_maxact);
1505 #endif /* _FFR_QUEUE_SCHED_DBG */
1506 if (MaxQueueChildren > 0 &&
1507 CurRunners + WorkGrp[curnum].wg_maxact > MaxQueueChildren)
1511 ** Pick up where we left off (curnum), in case we
1512 ** used up all the children last time without finishing.
1513 ** This give a round-robin fairness to queue runs.
1515 ** Increment CurRunners before calling run_work_group()
1516 ** to avoid a "race condition" with proc_list_drop() which
1517 ** decrements CurRunners if the queue runners terminate.
1518 ** Notice: CurRunners is an upper limit, in some cases
1519 ** (too few jobs in the queue) this value is larger than
1520 ** the actual number of queue runners. The discrepancy can
1521 ** increase if some queue runners "hang" for a long time.
1524 CurRunners += WorkGrp[curnum].wg_maxact;
1526 rwgflags |= RWG_FORK;
1528 rwgflags |= RWG_VERBOSE;
1530 rwgflags |= RWG_PERSISTENT;
1532 rwgflags |= RWG_RUNALL;
1533 ret = run_work_group(curnum, rwgflags);
1536 ** Failure means a message was printed for ETRN
1537 ** and subsequent queues are likely to fail as well.
1538 ** Decrement CurRunners in that case because
1539 ** none have been started.
1544 CurRunners -= WorkGrp[curnum].wg_maxact;
1549 schedule_queue_runs(runall, curnum, true);
1550 INCR_MOD(curnum, NumWorkGroups);
1553 /* schedule left over queue runs */
1554 if (i < NumWorkGroups && !NoMoreRunners && !persistent)
1558 for (h = curnum; i < NumWorkGroups; i++)
1560 schedule_queue_runs(runall, h, false);
1561 INCR_MOD(h, NumWorkGroups);
1567 if (sm_debug_active(&DebugLeakQ, 1))
1568 sm_heap_setgroup(oldgroup);
1569 #endif /* SM_HEAP_CHECK */
1573 #if _FFR_SKIP_DOMAINS
1575 ** SKIP_DOMAINS -- Skip 'skip' number of domains in the WorkQ.
1577 ** Added by Stephen Frost <sfrost@snowman.net> to support
1578 ** having each runner process every N'th domain instead of
1579 ** every N'th message.
1582 ** skip -- number of domains in WorkQ to skip.
1585 ** total number of messages skipped.
1597 for (n = 0, seqjump = 0; n < skip && WorkQ != NULL; seqjump++)
1599 if (WorkQ->w_next != NULL)
1601 if (WorkQ->w_host != NULL &&
1602 WorkQ->w_next->w_host != NULL)
1604 if (sm_strcasecmp(WorkQ->w_host,
1605 WorkQ->w_next->w_host) != 0)
1610 if ((WorkQ->w_host != NULL &&
1611 WorkQ->w_next->w_host == NULL) ||
1612 (WorkQ->w_host == NULL &&
1613 WorkQ->w_next->w_host != NULL))
1617 WorkQ = WorkQ->w_next;
1621 #endif /* _FFR_SKIP_DOMAINS */
1624 ** RUNNER_WORK -- have a queue runner do its work
1626 ** Have a queue runner do its work a list of entries.
1627 ** When work isn't directly being done then this process can take a signal
1628 ** and terminate immediately (in a clean fashion of course).
1629 ** When work is directly being done, it's not to be interrupted
1630 ** immediately: the work should be allowed to finish at a clean point
1631 ** before termination (in a clean fashion of course).
1635 ** sequenceno -- 'th process to run WorkQ.
1636 ** didfork -- did the calling process fork()?
1637 ** skip -- process only each skip'th item.
1638 ** njobs -- number of jobs in WorkQ.
1644 ** runs things in the mail queue.
1648 runner_work(e, sequenceno, didfork, skip, njobs)
1649 register ENVELOPE *e;
1662 ** Here we temporarily block the second calling of the handlers.
1663 ** This allows us to handle the signal without terminating in the
1664 ** middle of direct work. If a signal does come, the test for
1665 ** NoMoreRunners will find it.
1671 /* process them once at a time */
1672 while (WorkQ != NULL)
1675 SM_NONVOLATILE int oldgroup = 0;
1677 if (sm_debug_active(&DebugLeakQ, 1))
1679 oldgroup = sm_heap_group();
1681 sm_dprintf("run_queue_group() heap group #%d\n",
1684 #endif /* SM_HEAP_CHECK */
1686 /* do no more work */
1689 /* Check that a valid signal handler is callable */
1690 if (Oldsh != SIG_DFL && Oldsh != SIG_IGN &&
1691 Oldsh != runners_sighup &&
1692 Oldsh != runners_sigterm)
1697 w = WorkQ; /* assign current work item */
1700 ** Set the head of the WorkQ to the next work item.
1701 ** It is set 'skip' ahead (the number of parallel queue
1702 ** runners working on WorkQ together) since each runner
1703 ** works on every 'skip'th (N-th) item.
1704 #if _FFR_SKIP_DOMAINS
1705 ** In the case of the BYHOST Queue Sort Order, the 'item'
1706 ** is a domain, so we work on every 'skip'th (N-th) domain.
1707 #endif * _FFR_SKIP_DOMAINS *
1710 #if _FFR_SKIP_DOMAINS
1711 if (QueueSortOrder == QSO_BYHOST)
1714 if (WorkQ->w_next != NULL)
1716 if (WorkQ->w_host != NULL &&
1717 WorkQ->w_next->w_host != NULL)
1719 if (sm_strcasecmp(WorkQ->w_host,
1720 WorkQ->w_next->w_host)
1722 seqjump = skip_domains(skip);
1724 WorkQ = WorkQ->w_next;
1728 if ((WorkQ->w_host != NULL &&
1729 WorkQ->w_next->w_host == NULL) ||
1730 (WorkQ->w_host == NULL &&
1731 WorkQ->w_next->w_host != NULL))
1732 seqjump = skip_domains(skip);
1734 WorkQ = WorkQ->w_next;
1738 WorkQ = WorkQ->w_next;
1741 #endif /* _FFR_SKIP_DOMAINS */
1743 for (n = 0; n < skip && WorkQ != NULL; n++)
1744 WorkQ = WorkQ->w_next;
1750 ** Ignore jobs that are too expensive for the moment.
1752 ** Get new load average every GET_NEW_LA_TIME seconds.
1756 if (shouldqueue(WkRecipFact, Current_LA_time))
1758 char *msg = "Aborting queue run: load average too high";
1763 sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg);
1766 if (shouldqueue(w->w_pri, w->w_ctime))
1769 message(EmptyString);
1770 if (QueueSortOrder == QSO_BYPRIORITY)
1773 message("Skipping %s/%s (sequence %d of %d) and flushing rest of queue",
1774 qid_printqueue(w->w_qgrp,
1776 w->w_name + 2, sequenceno,
1779 sm_syslog(LOG_INFO, NOQID,
1780 "runqueue: Flushing queue from %s/%s (pri %ld, LA %d, %d of %d)",
1781 qid_printqueue(w->w_qgrp,
1783 w->w_name + 2, w->w_pri,
1784 CurrentLA, sequenceno,
1789 message("Skipping %s/%s (sequence %d of %d)",
1790 qid_printqueue(w->w_qgrp, w->w_qdir),
1791 w->w_name + 2, sequenceno, njobs);
1797 message(EmptyString);
1798 message("Running %s/%s (sequence %d of %d)",
1799 qid_printqueue(w->w_qgrp, w->w_qdir),
1800 w->w_name + 2, sequenceno, njobs);
1802 if (didfork && MaxQueueChildren > 0)
1804 sm_blocksignal(SIGCHLD);
1805 (void) sm_signal(SIGCHLD, reapchild);
1808 sm_syslog(LOG_DEBUG, NOQID,
1809 "runqueue %s dowork(%s)",
1810 qid_printqueue(w->w_qgrp, w->w_qdir),
1813 (void) dowork(w->w_qgrp, w->w_qdir, w->w_name + 2,
1814 ForkQueueRuns, false, e);
1817 sm_free(w->w_name); /* XXX */
1818 if (w->w_host != NULL)
1819 sm_free(w->w_host); /* XXX */
1820 sm_free((char *) w); /* XXX */
1821 sequenceno += seqjump; /* next sequence number */
1823 if (sm_debug_active(&DebugLeakQ, 1))
1824 sm_heap_setgroup(oldgroup);
1825 #endif /* SM_HEAP_CHECK */
1830 /* check the signals didn't happen during the revert */
1833 /* Check that a valid signal handler is callable */
1834 if (Oldsh != SIG_DFL && Oldsh != SIG_IGN &&
1835 Oldsh != runners_sighup && Oldsh != runners_sigterm)
1839 Oldsh = SIG_DFL; /* after the NoMoreRunners check */
1842 ** RUN_WORK_GROUP -- run the jobs in a queue group from a work group.
1844 ** Gets the stuff out of the queue in some presumably logical
1845 ** order and processes them.
1848 ** wgrp -- work group to process.
1849 ** flags -- RWG_* flags
1852 ** true if the queue run successfully began.
1855 ** runs things in the mail queue.
1858 /* Minimum sleep time for persistent queue runners */
1859 #define MIN_SLEEP_TIME 5
1862 run_work_group(wgrp, flags)
1866 register ENVELOPE *e;
1869 int qgrp, endgrp, h, i;
1873 extern void rmexpstab __P((void));
1874 extern ENVELOPE BlankEnvelope;
1875 extern SIGFUNC_DECL reapchild __P((int));
1881 ** If no work will ever be selected, don't even bother reading
1887 if (!bitset(RWG_PERSISTENT, flags) &&
1888 shouldqueue(WkRecipFact, Current_LA_time))
1890 char *msg = "Skipping queue run -- load average too high";
1892 if (bitset(RWG_VERBOSE, flags))
1893 message("458 %s\n", msg);
1895 sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg);
1900 ** See if we already have too many children.
1903 if (bitset(RWG_FORK, flags) &&
1904 WorkGrp[wgrp].wg_lowqintvl > 0 &&
1905 !bitset(RWG_PERSISTENT, flags) &&
1906 MaxChildren > 0 && CurChildren >= MaxChildren)
1908 char *msg = "Skipping queue run -- too many children";
1910 if (bitset(RWG_VERBOSE, flags))
1911 message("458 %s (%d)\n", msg, CurChildren);
1913 sm_syslog(LOG_INFO, NOQID, "runqueue: %s (%d)",
1919 ** See if we want to go off and do other useful work.
1922 if (bitset(RWG_FORK, flags))
1926 (void) sm_blocksignal(SIGCHLD);
1927 (void) sm_signal(SIGCHLD, reapchild);
1932 const char *msg = "Skipping queue run -- fork() failed";
1933 const char *err = sm_errstring(errno);
1935 if (bitset(RWG_VERBOSE, flags))
1936 message("458 %s: %s\n", msg, err);
1938 sm_syslog(LOG_INFO, NOQID, "runqueue: %s: %s",
1940 (void) sm_releasesignal(SIGCHLD);
1945 /* parent -- pick up intermediate zombie */
1946 (void) sm_blocksignal(SIGALRM);
1948 /* wgrp only used when queue runners are persistent */
1949 proc_list_add(pid, "Queue runner", PROC_QUEUE,
1950 WorkGrp[wgrp].wg_maxact,
1951 bitset(RWG_PERSISTENT, flags) ? wgrp : -1,
1953 (void) sm_releasesignal(SIGALRM);
1954 (void) sm_releasesignal(SIGCHLD);
1958 /* child -- clean up signals */
1960 /* Reset global flags */
1961 RestartRequest = NULL;
1962 RestartWorkGroup = false;
1963 ShutdownRequest = NULL;
1965 CurrentPid = getpid();
1966 close_sendmail_pid();
1969 ** Initialize exception stack and default exception
1970 ** handler for child process.
1973 sm_exc_newthread(fatal_error);
1977 /* Add parent process as first child item */
1978 proc_list_add(CurrentPid, "Queue runner child process",
1979 PROC_QUEUE_CHILD, 0, -1, NULL);
1980 (void) sm_releasesignal(SIGCHLD);
1981 (void) sm_signal(SIGCHLD, SIG_DFL);
1982 (void) sm_signal(SIGHUP, SIG_DFL);
1983 (void) sm_signal(SIGTERM, intsig);
1987 ** Release any resources used by the daemon code.
1992 /* force it to run expensive jobs */
1995 /* drop privileges */
1996 if (geteuid() == (uid_t) 0)
1997 (void) drop_privileges(false);
2000 ** Create ourselves an envelope
2003 CurEnv = &QueueEnvelope;
2004 rpool = sm_rpool_new_x(NULL);
2005 e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2006 e->e_flags = BlankEnvelope.e_flags;
2009 /* make sure we have disconnected from parent */
2010 if (bitset(RWG_FORK, flags))
2017 ** If we are running part of the queue, always ignore stored
2021 if (QueueLimitId != NULL || QueueLimitSender != NULL ||
2022 QueueLimitQuarantine != NULL ||
2023 QueueLimitRecipient != NULL)
2025 IgnoreHostStatus = true;
2030 ** Here is where we choose the queue group from the work group.
2031 ** The caller of the "domorework" label must setup a new envelope.
2034 endgrp = WorkGrp[wgrp].wg_curqgrp; /* to not spin endlessly */
2039 ** Run a queue group if:
2040 ** RWG_RUNALL bit is set or the bit for this group is set.
2047 ** Find the next queue group within the work group that
2048 ** has been marked as needing a run.
2051 qgrp = WorkGrp[wgrp].wg_qgs[WorkGrp[wgrp].wg_curqgrp]->qg_index;
2052 WorkGrp[wgrp].wg_curqgrp++; /* advance */
2053 WorkGrp[wgrp].wg_curqgrp %= WorkGrp[wgrp].wg_numqgrp; /* wrap */
2054 if (bitset(RWG_RUNALL, flags) ||
2055 (Queue[qgrp]->qg_nextrun <= now &&
2056 Queue[qgrp]->qg_nextrun != (time_t) -1))
2058 if (endgrp == WorkGrp[wgrp].wg_curqgrp)
2061 if (bitset(RWG_FORK, flags))
2062 finis(true, true, ExitStat);
2063 return true; /* we're done */
2067 qdir = Queue[qgrp]->qg_curnum; /* round-robin init of queue position */
2068 #if _FFR_QUEUE_SCHED_DBG
2070 sm_syslog(LOG_INFO, NOQID,
2071 "rwg: wgrp=%d, qgrp=%d, qdir=%d, name=%s, curqgrp=%d, numgrps=%d",
2072 wgrp, qgrp, qdir, qid_printqueue(qgrp, qdir),
2073 WorkGrp[wgrp].wg_curqgrp, WorkGrp[wgrp].wg_numqgrp);
2074 #endif /* _FFR_QUEUE_SCHED_DBG */
2077 /* tweak niceness of queue runs */
2078 if (Queue[qgrp]->qg_nice > 0)
2079 (void) nice(Queue[qgrp]->qg_nice);
2080 #endif /* HASNICE */
2082 /* XXX running queue group... */
2083 sm_setproctitle(true, CurEnv, "running queue: %s",
2084 qid_printqueue(qgrp, qdir));
2086 if (LogLevel > 69 || tTd(63, 99))
2087 sm_syslog(LOG_DEBUG, NOQID,
2088 "runqueue %s, pid=%d, forkflag=%d",
2089 qid_printqueue(qgrp, qdir), (int) CurrentPid,
2090 bitset(RWG_FORK, flags));
2093 ** Start making passes through the queue.
2094 ** First, read and sort the entire queue.
2095 ** Then, process the work in that order.
2096 ** But if you take too long, start over.
2099 for (i = 0; i < Queue[qgrp]->qg_numqueues; i++)
2101 h = gatherq(qgrp, qdir, false, &full, &more);
2103 if (ShmId != SM_SHM_NO_ID)
2104 QSHM_ENTRIES(Queue[qgrp]->qg_qpaths[qdir].qp_idx) = h;
2105 #endif /* SM_CONF_SHM */
2106 /* If there are no more items in this queue advance */
2109 /* A round-robin advance */
2111 qdir %= Queue[qgrp]->qg_numqueues;
2114 /* Has the WorkList reached the limit? */
2116 break; /* don't try to gather more */
2119 /* order the existing work requests */
2120 njobs = sortq(Queue[qgrp]->qg_maxlist);
2121 Queue[qgrp]->qg_curnum = qdir; /* update */
2124 if (!Verbose && bitnset(QD_FORK, Queue[qgrp]->qg_flags))
2126 int loop, maxrunners;
2130 ** For this WorkQ we want to fork off N children (maxrunners)
2131 ** at this point. Each child has a copy of WorkQ. Each child
2132 ** will process every N-th item. The parent will wait for all
2133 ** of the children to finish before moving on to the next
2134 ** queue group within the work group. This saves us forking
2135 ** a new runner-child for each work item.
2136 ** It's valid for qg_maxqrun == 0 since this may be an
2137 ** explicit "don't run this queue" setting.
2140 maxrunners = Queue[qgrp]->qg_maxqrun;
2142 /* No need to have more runners then there are jobs */
2143 if (maxrunners > njobs)
2145 for (loop = 0; loop < maxrunners; loop++)
2148 ** Since the delivery may happen in a child and the
2149 ** parent does not wait, the parent may close the
2150 ** maps thereby removing any shared memory used by
2151 ** the map. Therefore, close the maps now so the
2152 ** child will dynamically open them if necessary.
2160 syserr("run_work_group: cannot fork");
2165 /* parent -- clean out connection cache */
2166 mci_flush(false, NULL);
2167 #if _FFR_SKIP_DOMAINS
2168 if (QueueSortOrder == QSO_BYHOST)
2170 sequenceno += skip_domains(1);
2173 #endif /* _FFR_SKIP_DOMAINS */
2176 WorkQ = WorkQ->w_next;
2179 proc_list_add(pid, "Queue child runner process",
2180 PROC_QUEUE_CHILD, 0, -1, NULL);
2182 /* No additional work, no additional runners */
2188 /* child -- Reset global flags */
2189 RestartRequest = NULL;
2190 RestartWorkGroup = false;
2191 ShutdownRequest = NULL;
2193 CurrentPid = getpid();
2194 close_sendmail_pid();
2197 ** Initialize exception stack and default
2198 ** exception handler for child process.
2199 ** When fork()'d the child now has a private
2200 ** copy of WorkQ at its current position.
2203 sm_exc_newthread(fatal_error);
2206 ** SMTP processes (whether -bd or -bs) set
2207 ** SIGCHLD to reapchild to collect
2208 ** children status. However, at delivery
2209 ** time, that status must be collected
2210 ** by sm_wait() to be dealt with properly
2211 ** (check success of delivery based
2212 ** on status code, etc). Therefore, if we
2213 ** are an SMTP process, reset SIGCHLD
2214 ** back to the default so reapchild
2215 ** doesn't collect status before
2219 if (OpMode == MD_SMTP ||
2220 OpMode == MD_DAEMON ||
2221 MaxQueueChildren > 0)
2224 sm_releasesignal(SIGCHLD);
2225 (void) sm_signal(SIGCHLD, SIG_DFL);
2228 /* child -- error messages to the transcript */
2229 QuickAbort = OnlyOneError = false;
2230 runner_work(e, sequenceno, true,
2233 /* This child is done */
2234 finis(true, true, ExitStat);
2239 sm_releasesignal(SIGCHLD);
2242 ** Wait until all of the runners have completed before
2243 ** seeing if there is another queue group in the
2244 ** work group to process.
2245 ** XXX Future enhancement: don't wait() for all children
2246 ** here, just go ahead and make sure that overall the number
2247 ** of children is not exceeded.
2250 while (CurChildren > 0)
2255 while ((ret = sm_wait(&status)) <= 0)
2257 proc_list_drop(ret, status, NULL);
2260 else if (Queue[qgrp]->qg_maxqrun > 0 || bitset(RWG_FORCE, flags))
2263 ** When current process will not fork children to do the work,
2264 ** it will do the work itself. The 'skip' will be 1 since
2265 ** there are no child runners to divide the work across.
2268 runner_work(e, sequenceno, false, 1, njobs);
2271 /* free memory allocated by newenvelope() above */
2272 sm_rpool_free(rpool);
2273 QueueEnvelope.e_rpool = NULL;
2275 /* Are there still more queues in the work group to process? */
2276 if (endgrp != WorkGrp[wgrp].wg_curqgrp)
2278 rpool = sm_rpool_new_x(NULL);
2279 e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2280 e->e_flags = BlankEnvelope.e_flags;
2284 /* No more queues in work group to process. Now check persistent. */
2285 if (bitset(RWG_PERSISTENT, flags))
2288 sm_setproctitle(true, CurEnv, "running queue: %s",
2289 qid_printqueue(qgrp, qdir));
2292 ** close bogus maps, i.e., maps which caused a tempfail,
2293 ** so we get fresh map connections on the next lookup.
2294 ** closemaps() is also called when children are started.
2299 /* Close any cached connections. */
2300 mci_flush(true, NULL);
2302 /* Clean out expired related entries. */
2306 /* Update MX records for FallbackMX. */
2307 if (FallbackMX != NULL)
2308 (void) getfallbackmxrr(FallbackMX);
2309 #endif /* NAMED_BIND */
2312 /* close UserDatabase */
2317 if (sm_debug_active(&SmHeapCheck, 2)
2318 && access("memdump", F_OK) == 0
2324 out = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
2325 "memdump.out", SM_IO_APPEND, NULL);
2328 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "----------------------\n");
2330 sm_debug_level(&SmHeapCheck) - 1);
2331 (void) sm_io_close(out, SM_TIME_DEFAULT);
2334 #endif /* SM_HEAP_CHECK */
2336 /* let me rest for a second to catch my breath */
2337 if (njobs == 0 && WorkGrp[wgrp].wg_lowqintvl < MIN_SLEEP_TIME)
2338 sleep(MIN_SLEEP_TIME);
2339 else if (WorkGrp[wgrp].wg_lowqintvl <= 0)
2340 sleep(QueueIntvl > 0 ? QueueIntvl : MIN_SLEEP_TIME);
2342 sleep(WorkGrp[wgrp].wg_lowqintvl);
2345 ** Get the LA outside the WorkQ loop if necessary.
2346 ** In a persistent queue runner the code is repeated over
2347 ** and over but gatherq() may ignore entries due to
2348 ** shouldqueue() (do we really have to do this twice?).
2349 ** Hence the queue runners would just idle around when once
2350 ** CurrentLA caused all entries in a queue to be ignored.
2355 rpool = sm_rpool_new_x(NULL);
2356 e = newenvelope(&QueueEnvelope, CurEnv, rpool);
2357 e->e_flags = BlankEnvelope.e_flags;
2361 /* exit without the usual cleanup */
2363 if (bitset(RWG_FORK, flags))
2364 finis(true, true, ExitStat);
2370 ** DOQUEUERUN -- do a queue run?
2380 ** RUNQUEUEEVENT -- Sets a flag to indicate that a queue run should be done.
2389 ** The invocation of this function via an alarm may interrupt
2390 ** a set of actions. Thus errno may be set in that context.
2391 ** We need to restore errno at the end of this function to ensure
2392 ** that any work done here that sets errno doesn't return a
2393 ** misleading/false errno value. Errno may be EINTR upon entry to
2394 ** this function because of non-restartable/continuable system
2395 ** API was active. Iff this is true we will override errno as
2396 ** a timeout (as a more accurate error message).
2398 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2399 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2404 runqueueevent(ignore)
2407 int save_errno = errno;
2410 ** Set the general bit that we want a queue run,
2411 ** tested in doqueuerun()
2415 #if _FFR_QUEUE_SCHED_DBG
2417 sm_syslog(LOG_INFO, NOQID, "rqe: done");
2418 #endif /* _FFR_QUEUE_SCHED_DBG */
2425 ** GATHERQ -- gather messages from the message queue(s) the work queue.
2428 ** qgrp -- the index of the queue group.
2429 ** qdir -- the index of the queue directory.
2430 ** doall -- if set, include everything in the queue (even
2431 ** the jobs that cannot be run because the load
2432 ** average is too high, or MaxQueueRun is reached).
2433 ** Otherwise, exclude those jobs.
2434 ** full -- (optional) to be set 'true' if WorkList is full
2435 ** more -- (optional) to be set 'true' if there are still more
2436 ** messages in this queue not added to WorkList
2439 ** The number of request in the queue (not necessarily
2440 ** the number of requests in WorkList however).
2443 ** prepares available work into WorkList
2446 #define NEED_P 0001 /* 'P': priority */
2447 #define NEED_T 0002 /* 'T': time */
2448 #define NEED_R 0004 /* 'R': recipient */
2449 #define NEED_S 0010 /* 'S': sender */
2450 #define NEED_H 0020 /* host */
2451 #define HAS_QUARANTINE 0040 /* has an unexpected 'q' line */
2452 #define NEED_QUARANTINE 0100 /* 'q': reason */
2454 static WORK *WorkList = NULL; /* list of unsort work */
2455 static int WorkListSize = 0; /* current max size of WorkList */
2456 static int WorkListCount = 0; /* # of work items in WorkList */
2459 gatherq(qgrp, qdir, doall, full, more)
2466 register struct dirent *d;
2473 char qd[MAXPATHLEN];
2474 char qf[MAXPATHLEN];
2476 wn = WorkListCount - 1;
2479 (void) sm_strlcpy(qd, ".", sizeof qd);
2481 (void) sm_strlcpyn(qd, sizeof qd, 2,
2482 Queue[qgrp]->qg_qpaths[qdir].qp_name,
2484 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
2489 sm_dprintf("gatherq:\n");
2491 check = QueueLimitId;
2492 while (check != NULL)
2494 sm_dprintf("\tQueueLimitId = %s%s\n",
2495 check->queue_negate ? "!" : "",
2496 check->queue_match);
2497 check = check->queue_next;
2500 check = QueueLimitSender;
2501 while (check != NULL)
2503 sm_dprintf("\tQueueLimitSender = %s%s\n",
2504 check->queue_negate ? "!" : "",
2505 check->queue_match);
2506 check = check->queue_next;
2509 check = QueueLimitRecipient;
2510 while (check != NULL)
2512 sm_dprintf("\tQueueLimitRecipient = %s%s\n",
2513 check->queue_negate ? "!" : "",
2514 check->queue_match);
2515 check = check->queue_next;
2518 if (QueueMode == QM_QUARANTINE)
2520 check = QueueLimitQuarantine;
2521 while (check != NULL)
2523 sm_dprintf("\tQueueLimitQuarantine = %s%s\n",
2524 check->queue_negate ? "!" : "",
2525 check->queue_match);
2526 check = check->queue_next;
2531 /* open the queue directory */
2535 syserr("gatherq: cannot open \"%s\"",
2536 qid_printqueue(qgrp, qdir));
2538 *full = WorkListCount >= MaxQueueRun && MaxQueueRun > 0;
2545 ** Read the work directory.
2548 while ((d = readdir(f)) != NULL)
2552 char lbuf[MAXNAME + 1];
2556 sm_dprintf("gatherq: checking %s..", d->d_name);
2558 /* is this an interesting entry? */
2559 if (!(((QueueMode == QM_NORMAL &&
2560 d->d_name[0] == NORMQF_LETTER) ||
2561 (QueueMode == QM_QUARANTINE &&
2562 d->d_name[0] == QUARQF_LETTER) ||
2563 (QueueMode == QM_LOST &&
2564 d->d_name[0] == LOSEQF_LETTER)) &&
2565 d->d_name[1] == 'f'))
2568 sm_dprintf(" skipping\n");
2574 if (strlen(d->d_name) >= MAXQFNAME)
2577 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2578 "gatherq: %s too long, %d max characters\n",
2579 d->d_name, MAXQFNAME);
2581 sm_syslog(LOG_ALERT, NOQID,
2582 "gatherq: %s too long, %d max characters",
2583 d->d_name, MAXQFNAME);
2587 check = QueueLimitId;
2588 while (check != NULL)
2590 if (strcontainedin(false, check->queue_match,
2591 d->d_name) != check->queue_negate)
2594 check = check->queue_next;
2596 if (QueueLimitId != NULL && check == NULL)
2599 /* grow work list if necessary */
2600 if (++wn >= MaxQueueRun && MaxQueueRun > 0)
2602 if (wn == MaxQueueRun && LogLevel > 0)
2603 sm_syslog(LOG_WARNING, NOQID,
2604 "WorkList for %s maxed out at %d",
2605 qid_printqueue(qgrp, qdir),
2608 continue; /* just count entries */
2611 if (wn >= WorkListSize)
2613 grow_wlist(qgrp, qdir);
2614 if (wn >= WorkListSize)
2620 (void) sm_strlcpyn(qf, sizeof qf, 3, qd, "/", d->d_name);
2621 if (stat(qf, &sbuf) < 0)
2623 if (errno != ENOENT)
2624 sm_syslog(LOG_INFO, NOQID,
2625 "gatherq: can't stat %s/%s",
2626 qid_printqueue(qgrp, qdir),
2631 if (!bitset(S_IFREG, sbuf.st_mode))
2633 /* Yikes! Skip it or we will hang on open! */
2634 if (!((d->d_name[0] == DATAFL_LETTER ||
2635 d->d_name[0] == NORMQF_LETTER ||
2636 d->d_name[0] == QUARQF_LETTER ||
2637 d->d_name[0] == LOSEQF_LETTER ||
2638 d->d_name[0] == XSCRPT_LETTER) &&
2639 d->d_name[1] == 'f' && d->d_name[2] == '\0'))
2640 syserr("gatherq: %s/%s is not a regular file",
2641 qid_printqueue(qgrp, qdir), d->d_name);
2646 /* avoid work if possible */
2647 if ((QueueSortOrder == QSO_BYFILENAME ||
2648 QueueSortOrder == QSO_BYMODTIME ||
2649 QueueSortOrder == QSO_RANDOM) &&
2650 QueueLimitQuarantine == NULL &&
2651 QueueLimitSender == NULL &&
2652 QueueLimitRecipient == NULL)
2656 w->w_name = newstr(d->d_name);
2658 w->w_lock = w->w_tooyoung = false;
2661 w->w_mtime = sbuf.st_mtime;
2666 /* open control file */
2667 cf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B,
2669 if (cf == NULL && OpMode != MD_PRINT)
2671 /* this may be some random person sending hir msgs */
2673 sm_dprintf("gatherq: cannot open %s: %s\n",
2674 d->d_name, sm_errstring(errno));
2681 w->w_name = newstr(d->d_name);
2685 w->w_lock = !lockfile(sm_io_getinfo(cf, SM_IO_WHAT_FD,
2690 w->w_tooyoung = false;
2692 /* make sure jobs in creation don't clog queue */
2693 w->w_pri = 0x7fffffff;
2695 w->w_mtime = sbuf.st_mtime;
2697 /* extract useful information */
2699 if (QueueSortOrder == QSO_BYHOST
2701 || QueueSortOrder == QSO_BYSHUFFLE
2702 #endif /* _FFR_RHS */
2705 /* need w_host set for host sort order */
2708 if (QueueLimitSender != NULL)
2710 if (QueueLimitRecipient != NULL)
2712 if (QueueLimitQuarantine != NULL)
2713 i |= NEED_QUARANTINE;
2714 while (cf != NULL && i != 0 &&
2715 sm_io_fgets(cf, SM_TIME_DEFAULT, lbuf,
2716 sizeof lbuf) != NULL)
2721 p = strchr(lbuf, '\n');
2726 /* flush rest of overly long line */
2727 while ((c = sm_io_getc(cf, SM_TIME_DEFAULT))
2728 != SM_IO_EOF && c != '\n')
2735 qfver = atoi(&lbuf[1]);
2739 w->w_pri = atol(&lbuf[1]);
2744 w->w_ctime = atol(&lbuf[1]);
2749 if (QueueMode != QM_QUARANTINE &&
2750 QueueMode != QM_LOST)
2753 sm_dprintf("%s not marked as quarantined but has a 'q' line\n",
2755 i |= HAS_QUARANTINE;
2757 else if (QueueMode == QM_QUARANTINE)
2759 if (QueueLimitQuarantine == NULL)
2761 i &= ~NEED_QUARANTINE;
2765 check = QueueLimitQuarantine;
2766 while (check != NULL)
2768 if (strcontainedin(false,
2771 check->queue_negate)
2774 check = check->queue_next;
2777 i &= ~NEED_QUARANTINE;
2782 if (w->w_host == NULL &&
2783 (p = strrchr(&lbuf[1], '@')) != NULL)
2786 if (QueueSortOrder == QSO_BYSHUFFLE)
2787 w->w_host = newstr(&p[1]);
2789 #endif /* _FFR_RHS */
2790 w->w_host = strrev(&p[1]);
2791 makelower(w->w_host);
2794 if (QueueLimitRecipient == NULL)
2801 p = strchr(&lbuf[1], ':');
2805 ++p; /* skip over ':' */
2809 check = QueueLimitRecipient;
2810 while (check != NULL)
2812 if (strcontainedin(true,
2815 check->queue_negate)
2818 check = check->queue_next;
2825 check = QueueLimitSender;
2826 while (check != NULL)
2828 if (strcontainedin(true,
2831 check->queue_negate)
2834 check = check->queue_next;
2841 age = curtime() - (time_t) atol(&lbuf[1]);
2842 if (age >= 0 && MinQueueAge > 0 &&
2844 w->w_tooyoung = true;
2848 if (atol(&lbuf[1]) == 0)
2849 w->w_tooyoung = false;
2854 (void) sm_io_close(cf, SM_TIME_DEFAULT);
2856 if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) ||
2857 bitset(HAS_QUARANTINE, i) ||
2858 bitset(NEED_QUARANTINE, i) ||
2859 bitset(NEED_R|NEED_S, i))
2861 /* don't even bother sorting this job in */
2863 sm_dprintf("skipping %s (%x)\n", w->w_name, i);
2864 sm_free(w->w_name); /* XXX */
2865 if (w->w_host != NULL)
2866 sm_free(w->w_host); /* XXX */
2875 i = wn - WorkListCount;
2876 WorkListCount += SM_MIN(num_ent, WorkListSize);
2879 *more = WorkListCount < wn;
2882 *full = (wn >= MaxQueueRun && MaxQueueRun > 0) ||
2883 (WorkList == NULL && wn > 0);
2888 ** SORTQ -- sort the work list
2890 ** First the old WorkQ is cleared away. Then the WorkList is sorted
2891 ** for all items so that important (higher sorting value) items are not
2892 ** trunctated off. Then the most important items are moved from
2893 ** WorkList to WorkQ. The lower count of 'max' or MaxListCount items
2897 ** max -- maximum number of items to be placed in WorkQ
2900 ** the number of items in WorkQ
2903 ** WorkQ gets released and filled with new work. WorkList
2904 ** gets released. Work items get sorted in order.
2911 register int i; /* local counter */
2912 register WORK *w; /* tmp item pointer */
2913 int wc = WorkListCount; /* trim size for WorkQ */
2919 /* Clear out old WorkQ. */
2920 for (w = WorkQ; w != NULL; w = nw)
2923 sm_free(w->w_name); /* XXX */
2924 if (w->w_host != NULL)
2925 sm_free(w->w_host); /* XXX */
2926 sm_free((char *) w); /* XXX */
2931 if (WorkList == NULL || wc <= 0)
2934 /* Check if the per queue group item limit will be exceeded */
2935 if (wc > max && max > 0)
2939 ** The sort now takes place using all of the items in WorkList.
2940 ** The list gets trimmed to the most important items after the sort.
2941 ** If the trim were to happen before the sort then one or more
2942 ** important items might get truncated off -- not what we want.
2945 if (QueueSortOrder == QSO_BYHOST)
2948 ** Sort the work directory for the first time,
2949 ** based on host name, lock status, and priority.
2952 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf1);
2955 ** If one message to host is locked, "lock" all messages
2962 if (!WorkList[i].w_lock)
2970 if (WorkList[i].w_host == NULL &&
2972 WorkList[i].w_lock = true;
2973 else if (WorkList[i].w_host != NULL &&
2974 w->w_host != NULL &&
2975 sm_strcasecmp(WorkList[i].w_host,
2977 WorkList[i].w_lock = true;
2984 ** Sort the work directory for the second time,
2985 ** based on lock status, host name, and priority.
2988 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf2);
2990 else if (QueueSortOrder == QSO_BYTIME)
2993 ** Simple sort based on submission time only.
2996 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf3);
2998 else if (QueueSortOrder == QSO_BYFILENAME)
3001 ** Sort based on queue filename.
3004 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf4);
3006 else if (QueueSortOrder == QSO_RANDOM)
3009 ** Sort randomly. To avoid problems with an instable sort,
3010 ** use a random index into the queue file name to start
3014 randi = get_rand_mod(MAXQFNAME);
3017 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf5);
3019 else if (QueueSortOrder == QSO_BYMODTIME)
3022 ** Simple sort based on modification time of queue file.
3023 ** This puts the oldest items first.
3026 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf6);
3029 else if (QueueSortOrder == QSO_BYSHUFFLE)
3032 ** Simple sort based on shuffled host name.
3035 init_shuffle_alphabet();
3036 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf7);
3038 #endif /* _FFR_RHS */
3039 else if (QueueSortOrder == QSO_BYPRIORITY)
3042 ** Simple sort based on queue priority only.
3045 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf0);
3047 /* else don't sort at all */
3050 ** Convert the work list into canonical form.
3051 ** Should be turning it into a list of envelopes here perhaps.
3052 ** Only take the most important items up to the per queue group
3056 for (i = wc; --i >= 0; )
3058 w = (WORK *) xalloc(sizeof *w);
3059 w->w_qgrp = WorkList[i].w_qgrp;
3060 w->w_qdir = WorkList[i].w_qdir;
3061 w->w_name = WorkList[i].w_name;
3062 w->w_host = WorkList[i].w_host;
3063 w->w_lock = WorkList[i].w_lock;
3064 w->w_tooyoung = WorkList[i].w_tooyoung;
3065 w->w_pri = WorkList[i].w_pri;
3066 w->w_ctime = WorkList[i].w_ctime;
3067 w->w_mtime = WorkList[i].w_mtime;
3072 /* free the rest of the list */
3073 for (i = WorkListCount; --i >= wc; )
3075 sm_free(WorkList[i].w_name);
3076 if (WorkList[i].w_host != NULL)
3077 sm_free(WorkList[i].w_host);
3080 if (WorkList != NULL)
3081 sm_free(WorkList); /* XXX */
3088 for (w = WorkQ; w != NULL; w = w->w_next)
3090 if (w->w_host != NULL)
3091 sm_dprintf("%22s: pri=%ld %s\n",
3092 w->w_name, w->w_pri, w->w_host);
3094 sm_dprintf("%32s: pri=%ld\n",
3095 w->w_name, w->w_pri);
3099 return wc; /* return number of WorkQ items */
3102 ** GROW_WLIST -- make the work list larger
3105 ** qgrp -- the index for the queue group.
3106 ** qdir -- the index for the queue directory.
3112 ** Adds another QUEUESEGSIZE entries to WorkList if possible.
3113 ** It can fail if there isn't enough memory, so WorkListSize
3114 ** should be checked again upon return.
3118 grow_wlist(qgrp, qdir)
3123 sm_dprintf("grow_wlist: WorkListSize=%d\n", WorkListSize);
3124 if (WorkList == NULL)
3126 WorkList = (WORK *) xalloc((sizeof *WorkList) *
3127 (QUEUESEGSIZE + 1));
3128 WorkListSize = QUEUESEGSIZE;
3132 int newsize = WorkListSize + QUEUESEGSIZE;
3133 WORK *newlist = (WORK *) sm_realloc((char *) WorkList,
3134 (unsigned) sizeof(WORK) * (newsize + 1));
3136 if (newlist != NULL)
3138 WorkListSize = newsize;
3142 sm_syslog(LOG_INFO, NOQID,
3143 "grew WorkList for %s to %d",
3144 qid_printqueue(qgrp, qdir),
3148 else if (LogLevel > 0)
3150 sm_syslog(LOG_ALERT, NOQID,
3151 "FAILED to grow WorkList for %s to %d",
3152 qid_printqueue(qgrp, qdir), newsize);
3156 sm_dprintf("grow_wlist: WorkListSize now %d\n", WorkListSize);
3159 ** WORKCMPF0 -- simple priority-only compare function.
3162 ** a -- the first argument.
3163 ** b -- the second argument.
3188 ** WORKCMPF1 -- first compare function for ordering work based on host name.
3190 ** Sorts on host name, lock status, and priority in that order.
3193 ** a -- the first argument.
3194 ** b -- the second argument.
3211 if (a->w_host != NULL && b->w_host == NULL)
3213 else if (a->w_host == NULL && b->w_host != NULL)
3215 if (a->w_host != NULL && b->w_host != NULL &&
3216 (i = sm_strcasecmp(a->w_host, b->w_host)) != 0)
3220 if (a->w_lock != b->w_lock)
3221 return b->w_lock - a->w_lock;
3224 return workcmpf0(a, b);
3227 ** WORKCMPF2 -- second compare function for ordering work based on host name.
3229 ** Sorts on lock status, host name, and priority in that order.
3232 ** a -- the first argument.
3233 ** b -- the second argument.
3250 if (a->w_lock != b->w_lock)
3251 return a->w_lock - b->w_lock;
3254 if (a->w_host != NULL && b->w_host == NULL)
3256 else if (a->w_host == NULL && b->w_host != NULL)
3258 if (a->w_host != NULL && b->w_host != NULL &&
3259 (i = sm_strcasecmp(a->w_host, b->w_host)) != 0)
3263 return workcmpf0(a, b);
3266 ** WORKCMPF3 -- simple submission-time-only compare function.
3269 ** a -- the first argument.
3270 ** b -- the second argument.
3284 if (a->w_ctime > b->w_ctime)
3286 else if (a->w_ctime < b->w_ctime)
3292 ** WORKCMPF4 -- compare based on file name
3295 ** a -- the first argument.
3296 ** b -- the second argument.
3310 return strcmp(a->w_name, b->w_name);
3313 ** WORKCMPF5 -- compare based on assigned random number
3316 ** a -- the first argument (ignored).
3317 ** b -- the second argument (ignored).
3329 if (strlen(a->w_name) < randi || strlen(b->w_name) < randi)
3331 return a->w_name[randi] - b->w_name[randi];
3334 ** WORKCMPF6 -- simple modification-time-only compare function.
3337 ** a -- the first argument.
3338 ** b -- the second argument.
3352 if (a->w_mtime > b->w_mtime)
3354 else if (a->w_mtime < b->w_mtime)
3361 ** WORKCMPF7 -- compare function for ordering work based on shuffled host name.
3363 ** Sorts on lock status, host name, and priority in that order.
3366 ** a -- the first argument.
3367 ** b -- the second argument.
3384 if (a->w_lock != b->w_lock)
3385 return a->w_lock - b->w_lock;
3388 if (a->w_host != NULL && b->w_host == NULL)
3390 else if (a->w_host == NULL && b->w_host != NULL)
3392 if (a->w_host != NULL && b->w_host != NULL &&
3393 (i = sm_strshufflecmp(a->w_host, b->w_host)) != 0)
3397 return workcmpf0(a, b);
3399 #endif /* _FFR_RHS */
3401 ** STRREV -- reverse string
3403 ** Returns a pointer to a new string that is the reverse of
3404 ** the string pointed to by fwd. The space for the new
3405 ** string is obtained using xalloc().
3408 ** fwd -- the string to reverse.
3411 ** the reversed string.
3422 rev = xalloc(len + 1);
3423 for (cnt = 0; cnt < len; ++cnt)
3424 rev[cnt] = fwd[len - cnt - 1];
3434 static unsigned char ShuffledAlphabet[NCHAR];
3437 init_shuffle_alphabet()
3439 static bool init = false;
3445 /* fill the ShuffledAlphabet */
3446 for (i = 0; i < NCHAR; i++)
3447 ShuffledAlphabet[i] = i;
3450 for (i = 1; i < NCHAR; i++)
3452 register int j = get_random() % NCHAR;
3455 tmp = ShuffledAlphabet[j];
3456 ShuffledAlphabet[j] = ShuffledAlphabet[i];
3457 ShuffledAlphabet[i] = tmp;
3460 /* make it case insensitive */
3461 for (i = 'A'; i <= 'Z'; i++)
3462 ShuffledAlphabet[i] = ShuffledAlphabet[i + 'a' - 'A'];
3464 /* fill the upper part */
3465 for (i = 0; i < NCHAR; i++)
3466 ShuffledAlphabet[i + NCHAR] = ShuffledAlphabet[i];
3471 sm_strshufflecmp(a, b)
3475 const unsigned char *us1 = (const unsigned char *) a;
3476 const unsigned char *us2 = (const unsigned char *) b;
3478 while (ShuffledAlphabet[*us1] == ShuffledAlphabet[*us2++])
3483 return (ShuffledAlphabet[*us1] - ShuffledAlphabet[*--us2]);
3485 #endif /* _FFR_RHS */
3488 ** DOWORK -- do a work request.
3491 ** qgrp -- the index of the queue group for the job.
3492 ** qdir -- the index of the queue directory for the job.
3493 ** id -- the ID of the job to run.
3494 ** forkflag -- if set, run this in background.
3495 ** requeueflag -- if set, reinstantiate the queue quickly.
3496 ** This is used when expanding aliases in the queue.
3497 ** If forkflag is also set, it doesn't wait for the
3499 ** e - the envelope in which to run it.
3502 ** process id of process that is running the queue job.
3505 ** The work request is satisfied if possible.
3509 dowork(qgrp, qdir, id, forkflag, requeueflag, e)
3515 register ENVELOPE *e;
3521 sm_dprintf("dowork(%s/%s)\n", qid_printqueue(qgrp, qdir), id);
3530 ** Since the delivery may happen in a child and the
3531 ** parent does not wait, the parent may close the
3532 ** maps thereby removing any shared memory used by
3533 ** the map. Therefore, close the maps now so the
3534 ** child will dynamically open them if necessary.
3542 syserr("dowork: cannot fork");
3547 /* parent -- clean out connection cache */
3548 mci_flush(false, NULL);
3553 ** Initialize exception stack and default exception
3554 ** handler for child process.
3557 /* Reset global flags */
3558 RestartRequest = NULL;
3559 RestartWorkGroup = false;
3560 ShutdownRequest = NULL;
3562 CurrentPid = getpid();
3563 sm_exc_newthread(fatal_error);
3566 ** See note above about SMTP processes and SIGCHLD.
3569 if (OpMode == MD_SMTP ||
3570 OpMode == MD_DAEMON ||
3571 MaxQueueChildren > 0)
3574 sm_releasesignal(SIGCHLD);
3575 (void) sm_signal(SIGCHLD, SIG_DFL);
3578 /* child -- error messages to the transcript */
3579 QuickAbort = OnlyOneError = false;
3591 ** Lock the control file to avoid duplicate deliveries.
3592 ** Then run the file as though we had just read it.
3593 ** We save an idea of the temporary name so we
3594 ** can recover on interrupt.
3599 /* Reset global flags */
3600 RestartRequest = NULL;
3601 RestartWorkGroup = false;
3602 ShutdownRequest = NULL;
3606 /* set basic modes, etc. */
3609 rpool = sm_rpool_new_x(NULL);
3610 clearenvelope(e, false, rpool);
3611 e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
3612 set_delivery_mode(SM_DELIVER, e);
3613 e->e_errormode = EM_MAIL;
3617 GrabTo = UseErrorsTo = false;
3622 set_op_mode(MD_QUEUERUN);
3624 sm_setproctitle(true, e, "%s from queue", qid_printname(e));
3626 sm_syslog(LOG_DEBUG, e->e_id, "dowork, pid=%d",
3629 /* don't use the headers from sendmail.cf... */
3632 /* read the queue control file -- return if locked */
3633 if (!readqf(e, false))
3635 if (tTd(40, 4) && e->e_id != NULL)
3636 sm_dprintf("readqf(%s) failed\n",
3640 finis(false, true, EX_OK);
3643 /* adding this frees 8 bytes */
3644 clearenvelope(e, false, rpool);
3646 /* adding this frees 12 bytes */
3647 sm_rpool_free(rpool);
3653 e->e_flags |= EF_INQUEUE;
3654 eatheader(e, requeueflag, true);
3657 queueup(e, false, false);
3659 /* do the delivery */
3660 sendall(e, SM_DELIVER);
3662 /* finish up and exit */
3664 finis(true, true, ExitStat);
3667 dropenvelope(e, true, false);
3668 sm_rpool_free(rpool);
3677 ** DOWORKLIST -- process a list of envelopes as work requests
3679 ** Similar to dowork(), except that after forking, it processes an
3680 ** envelope and its siblings, treating each envelope as a work request.
3683 ** el -- envelope to be processed including its siblings.
3684 ** forkflag -- if set, run this in background.
3685 ** requeueflag -- if set, reinstantiate the queue quickly.
3686 ** This is used when expanding aliases in the queue.
3687 ** If forkflag is also set, it doesn't wait for the
3691 ** process id of process that is running the queue job.
3694 ** The work request is satisfied if possible.
3698 doworklist(el, forkflag, requeueflag)
3707 sm_dprintf("doworklist()\n");
3716 ** Since the delivery may happen in a child and the
3717 ** parent does not wait, the parent may close the
3718 ** maps thereby removing any shared memory used by
3719 ** the map. Therefore, close the maps now so the
3720 ** child will dynamically open them if necessary.
3728 syserr("doworklist: cannot fork");
3733 /* parent -- clean out connection cache */
3734 mci_flush(false, NULL);
3739 ** Initialize exception stack and default exception
3740 ** handler for child process.
3743 /* Reset global flags */
3744 RestartRequest = NULL;
3745 RestartWorkGroup = false;
3746 ShutdownRequest = NULL;
3748 CurrentPid = getpid();
3749 sm_exc_newthread(fatal_error);
3752 ** See note above about SMTP processes and SIGCHLD.
3755 if (OpMode == MD_SMTP ||
3756 OpMode == MD_DAEMON ||
3757 MaxQueueChildren > 0)
3760 sm_releasesignal(SIGCHLD);
3761 (void) sm_signal(SIGCHLD, SIG_DFL);
3764 /* child -- error messages to the transcript */
3765 QuickAbort = OnlyOneError = false;
3778 ** Lock the control file to avoid duplicate deliveries.
3779 ** Then run the file as though we had just read it.
3780 ** We save an idea of the temporary name so we
3781 ** can recover on interrupt.
3786 /* Reset global flags */
3787 RestartRequest = NULL;
3788 RestartWorkGroup = false;
3789 ShutdownRequest = NULL;
3793 /* set basic modes, etc. */
3796 GrabTo = UseErrorsTo = false;
3801 set_op_mode(MD_QUEUERUN);
3804 sm_syslog(LOG_DEBUG, el->e_id, "doworklist, pid=%d",
3807 for (ei = el; ei != NULL; ei = ei->e_sibling)
3812 if (WILL_BE_QUEUED(ei->e_sendmode))
3814 else if (QueueMode != QM_QUARANTINE &&
3815 ei->e_quarmsg != NULL)
3818 rpool = sm_rpool_new_x(NULL);
3819 clearenvelope(&e, true, rpool);
3820 e.e_flags |= EF_QUEUERUN|EF_GLOBALERRS;
3821 set_delivery_mode(SM_DELIVER, &e);
3822 e.e_errormode = EM_MAIL;
3824 e.e_qgrp = ei->e_qgrp;
3825 e.e_qdir = ei->e_qdir;
3827 sm_setproctitle(true, &e, "%s from queue", qid_printname(&e));
3829 /* don't use the headers from sendmail.cf... */
3833 /* read the queue control file -- return if locked */
3834 if (readqf(&e, false))
3836 e.e_flags |= EF_INQUEUE;
3837 eatheader(&e, requeueflag, true);
3840 queueup(&e, false, false);
3842 /* do the delivery */
3843 sendall(&e, SM_DELIVER);
3844 dropenvelope(&e, true, false);
3848 if (tTd(40, 4) && e.e_id != NULL)
3849 sm_dprintf("readqf(%s) failed\n",
3852 sm_rpool_free(rpool);
3856 /* restore CurEnv */
3859 /* finish up and exit */
3861 finis(true, true, ExitStat);
3865 ** READQF -- read queue file and set up environment.
3868 ** e -- the envelope of the job to run.
3869 ** openonly -- only open the qf (returned as e_lockfp)
3872 ** true if it successfully read the queue file.
3876 ** The queue file is returned locked.
3881 register ENVELOPE *e;
3884 register SM_FILE_T *qfp;
3886 struct stat st, stf;
3893 bool nomore = false;
3897 char qf[MAXPATHLEN];
3901 ** Read and process the file.
3904 (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), sizeof qf);
3905 qfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDWR_B, NULL);
3908 int save_errno = errno;
3911 sm_dprintf("readqf(%s): sm_io_open failure (%s)\n",
3912 qf, sm_errstring(errno));
3916 syserr("readqf: no control file %s", qf);
3921 if (!lockfile(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), qf, NULL,
3924 /* being processed by another queuer */
3926 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3927 "%s: locked\n", e->e_id);
3929 sm_dprintf("%s: locked\n", e->e_id);
3931 sm_syslog(LOG_DEBUG, e->e_id, "locked");
3932 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
3940 ** Prevent locking race condition.
3942 ** Process A: readqf(): qfp = fopen(qffile)
3943 ** Process B: queueup(): rename(tf, qf)
3944 ** Process B: unlocks(tf)
3945 ** Process A: lockfile(qf);
3947 ** Process A (us) has the old qf file (before the rename deleted
3948 ** the directory entry) and will be delivering based on old data.
3949 ** This can lead to multiple deliveries of the same recipients.
3951 ** Catch this by checking if the underlying qf file has changed
3952 ** *after* acquiring our lock and if so, act as though the file
3953 ** was still locked (i.e., just return like the lockfile() case
3957 if (stat(qf, &stf) < 0 ||
3958 fstat(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), &st) < 0)
3960 /* must have been being processed by someone else */
3962 sm_dprintf("readqf(%s): [f]stat failure (%s)\n",
3963 qf, sm_errstring(errno));
3964 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
3968 if (st.st_nlink != stf.st_nlink ||
3969 st.st_dev != stf.st_dev ||
3970 ST_INODE(st) != ST_INODE(stf) ||
3971 #if HAS_ST_GEN && 0 /* AFS returns garbage in st_gen */
3972 st.st_gen != stf.st_gen ||
3973 #endif /* HAS_ST_GEN && 0 */
3974 st.st_uid != stf.st_uid ||
3975 st.st_gid != stf.st_gid ||
3976 st.st_size != stf.st_size)
3978 /* changed after opened */
3980 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3981 "%s: changed\n", e->e_id);
3983 sm_dprintf("%s: changed\n", e->e_id);
3985 sm_syslog(LOG_DEBUG, e->e_id, "changed");
3986 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
3991 ** Check the queue file for plausibility to avoid attacks.
3994 qsafe = S_IWOTH|S_IWGRP;
3995 if (bitset(S_IWGRP, QueueFileMode))
3998 bogus = st.st_uid != geteuid() &&
3999 st.st_uid != TrustedUid &&
4000 geteuid() != RealUid;
4003 ** If this qf file results from a set-group-ID binary, then
4004 ** we check whether the directory is group-writable,
4005 ** the queue file mode contains the group-writable bit, and
4006 ** the groups are the same.
4007 ** Notice: this requires that the set-group-ID binary is used to
4011 if (bogus && st.st_gid == getegid() && UseMSP)
4016 bp = SM_LAST_DIR_DELIM(qf);
4024 if (stat(delim == '\0' ? "." : qf, &dst) < 0)
4025 syserr("readqf: cannot stat directory %s",
4026 delim == '\0' ? "." : qf);
4029 bogus = !(bitset(S_IWGRP, QueueFileMode) &&
4030 bitset(S_IWGRP, dst.st_mode) &&
4031 dst.st_gid == st.st_gid);
4037 bogus = bitset(qsafe, st.st_mode);
4042 sm_syslog(LOG_ALERT, e->e_id,
4043 "bogus queue file, uid=%d, gid=%d, mode=%o",
4044 st.st_uid, st.st_gid, st.st_mode);
4047 sm_dprintf("readqf(%s): bogus file\n", qf);
4048 e->e_flags |= EF_INQUEUE;
4050 loseqfile(e, "bogus file uid/gid in mqueue");
4051 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
4055 if (st.st_size == 0)
4057 /* must be a bogus file -- if also old, just remove it */
4058 if (!openonly && st.st_ctime + 10 * 60 < curtime())
4060 (void) xunlink(queuename(e, DATAFL_LETTER));
4061 (void) xunlink(queuename(e, ANYQFL_LETTER));
4063 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
4067 if (st.st_nlink == 0)
4070 ** Race condition -- we got a file just as it was being
4071 ** unlinked. Just assume it is zero length.
4074 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
4080 ** If we don't own the file mark it as unsafe.
4081 ** However, allow TrustedUser to own it as well
4082 ** in case TrustedUser manipulates the queue.
4085 if (st.st_uid != geteuid() && st.st_uid != TrustedUid)
4086 e->e_flags |= EF_UNSAFE;
4087 #else /* _FFR_TRUSTED_QF */
4088 /* If we don't own the file mark it as unsafe */
4089 if (st.st_uid != geteuid())
4090 e->e_flags |= EF_UNSAFE;
4091 #endif /* _FFR_TRUSTED_QF */
4093 /* good file -- save this lock */
4096 /* Just wanted the open file */
4100 /* do basic system initialization */
4102 macdefine(&e->e_macro, A_PERM, 'i', e->e_id);
4105 e->e_flags |= EF_GLOBALERRS;
4106 set_op_mode(MD_QUEUERUN);
4108 e->e_qfletter = queue_letter(e, ANYQFL_LETTER);
4109 e->e_dfqgrp = e->e_qgrp;
4110 e->e_dfqdir = e->e_qdir;
4111 #if _FFR_QUEUE_MACRO
4112 macdefine(&e->e_macro, A_TEMP, macid("{queue}"),
4113 qid_printqueue(e->e_qgrp, e->e_qdir));
4114 #endif /* _FFR_QUEUE_MACRO */
4117 while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL)
4119 unsigned long qflags;
4126 sm_dprintf("+++++ %s\n", bp);
4131 syserr("SECURITY ALERT: extra or bogus data in queue file: %s",
4133 err = "bogus queue line";
4138 case 'A': /* AUTH= parameter */
4139 if (!xtextok(&bp[1]))
4141 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4144 case 'B': /* body type */
4145 r = check_bodytype(&bp[1]);
4146 if (!BODYTYPE_VALID(r))
4148 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4151 case 'C': /* specify controlling user */
4152 ctladdr = setctluser(&bp[1], qfver, e);
4155 case 'D': /* data file name */
4156 /* obsolete -- ignore */
4159 case 'd': /* data file directory name */
4163 #if _FFR_MSP_PARANOIA
4164 /* forbid queue groups in MSP? */
4167 #endif /* _FFR_MSP_PARANOIA */
4169 qgrp < NumQueue && Queue[qgrp] != NULL;
4173 qdir < Queue[qgrp]->qg_numqueues;
4177 Queue[qgrp]->qg_qpaths[qdir].qp_name)
4186 err = "bogus queue file directory";
4192 case 'E': /* specify error recipient */
4193 /* no longer used */
4196 case 'F': /* flag bits */
4197 if (strncmp(bp, "From ", 5) == 0)
4199 /* we are being spoofed! */
4200 syserr("SECURITY ALERT: bogus qf line %s", bp);
4201 err = "bogus queue line";
4204 for (p = &bp[1]; *p != '\0'; p++)
4208 case '8': /* has 8 bit data */
4209 e->e_flags |= EF_HAS8BIT;
4212 case 'b': /* delete Bcc: header */
4213 e->e_flags |= EF_DELETE_BCC;
4216 case 'd': /* envelope has DSN RET= */
4217 e->e_flags |= EF_RET_PARAM;
4220 case 'n': /* don't return body */
4221 e->e_flags |= EF_NO_BODY_RETN;
4224 case 'r': /* response */
4225 e->e_flags |= EF_RESPONSE;
4228 case 's': /* split */
4229 e->e_flags |= EF_SPLIT;
4232 case 'w': /* warning sent */
4233 e->e_flags |= EF_WARNING;
4239 case 'q': /* quarantine reason */
4240 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4241 macdefine(&e->e_macro, A_PERM,
4242 macid("{quarantine}"), e->e_quarmsg);
4245 case 'H': /* header */
4248 ** count size before chompheader() destroys the line.
4249 ** this isn't accurate due to macro expansion, but
4250 ** better than before. "-3" to skip H?? at least.
4253 hdrsize += strlen(bp) - 3;
4254 (void) chompheader(&bp[1], CHHDR_QUEUE, NULL, e);
4257 case 'I': /* data file's inode number */
4258 /* regenerated below */
4261 case 'K': /* time of last delivery attempt */
4262 e->e_dtime = atol(&buf[1]);
4265 case 'L': /* Solaris Content-Length: */
4266 case 'M': /* message */
4267 /* ignore this; we want a new message next time */
4270 case 'N': /* number of delivery attempts */
4271 e->e_ntries = atoi(&buf[1]);
4273 /* if this has been tried recently, let it be */
4275 if (e->e_ntries > 0 && e->e_dtime <= now &&
4276 now < e->e_dtime + MinQueueAge)
4280 howlong = pintvl(now - e->e_dtime, true);
4282 (void) sm_io_fprintf(smioout,
4284 "%s: too young (%s)\n",
4287 sm_dprintf("%s: too young (%s)\n",
4290 sm_syslog(LOG_DEBUG, e->e_id,
4297 macdefine(&e->e_macro, A_TEMP,
4298 macid("{ntries}"), &buf[1]);
4301 /* adjust BIND parameters immediately */
4302 if (e->e_ntries == 0)
4304 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
4305 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
4309 _res.retry = TimeOuts.res_retry[RES_TO_NORMAL];
4310 _res.retrans = TimeOuts.res_retrans[RES_TO_NORMAL];
4312 #endif /* NAMED_BIND */
4315 case 'P': /* message priority */
4316 e->e_msgpriority = atol(&bp[1]) + WkTimeFact;
4319 case 'Q': /* original recipient */
4320 orcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4323 case 'r': /* final recipient */
4324 frcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4327 case 'R': /* specify recipient */
4333 while (*++p != '\0' && *p != ':')
4338 qflags |= QHASNOTIFY;
4342 qflags |= QPINGONSUCCESS;
4346 qflags |= QPINGONFAILURE;
4350 qflags |= QPINGONDELAY;
4358 if (ctladdr != NULL)
4359 ctladdr->q_flags |= QALIAS;
4362 default: /* ignore or complain? */
4369 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
4372 q = parseaddr(++p, NULLADDR, RF_COPYALL, '\0',
4378 /* make sure we keep the current qgrp */
4379 if (ISVALIDQGRP(e->e_qgrp))
4380 q->q_qgrp = e->e_qgrp;
4381 q->q_alias = ctladdr;
4383 q->q_flags &= ~Q_PINGFLAGS;
4384 q->q_flags |= qflags;
4385 q->q_finalrcpt = frcpt;
4387 (void) recipient(q, &e->e_sendqueue, 0, e);
4391 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"),
4395 case 'S': /* sender */
4396 setsender(sm_rpool_strdup_x(e->e_rpool, &bp[1]),
4397 e, NULL, '\0', true);
4400 case 'T': /* init time */
4401 e->e_ctime = atol(&bp[1]);
4404 case 'V': /* queue file version number */
4405 qfver = atoi(&bp[1]);
4406 if (qfver <= QF_VERSION)
4408 syserr("Version number in queue file (%d) greater than max (%d)",
4410 err = "unsupported queue file version";
4415 case 'Z': /* original envelope id from ESMTP */
4416 e->e_envid = sm_rpool_strdup_x(e->e_rpool, &bp[1]);
4417 macdefine(&e->e_macro, A_PERM,
4418 macid("{dsn_envid}"), e->e_envid);
4421 case '!': /* deliver by */
4423 /* format: flag (1 char) space long-integer */
4424 e->e_dlvr_flag = buf[1];
4425 e->e_deliver_by = strtol(&buf[3], NULL, 10);
4427 case '$': /* define macro */
4431 /* XXX elimate p? */
4432 r = macid_parse(&bp[1], &ep);
4435 p = sm_rpool_strdup_x(e->e_rpool, ep);
4436 macdefine(&e->e_macro, A_PERM, r, p);
4440 case '.': /* terminate file */
4449 ** Maintain backward compatibility for
4450 ** users who defined _FFR_QUEUEDELAY in
4451 ** previous releases. Remove this
4452 ** code in 8.14 or 8.15.
4455 if (qfver == 5 || qfver == 7)
4458 /* If not qfver 5 or 7, then 'G' or 'Y' is invalid */
4460 #endif /* _FFR_QUEUEDELAY */
4463 syserr("readqf: %s: line %d: bad line \"%s\"",
4464 qf, LineNumber, shortenstring(bp, MAXSHORTSTR));
4465 err = "unrecognized line";
4470 sm_free(bp); /* XXX */
4474 ** If we haven't read any lines, this queue file is empty.
4475 ** Arrange to remove it without referencing any null pointers.
4478 if (LineNumber == 0)
4481 e->e_flags |= EF_CLRQUEUE|EF_FATALERRS|EF_RESPONSE;
4485 /* Check to make sure we have a complete queue file read */
4488 syserr("readqf: %s: incomplete queue file read", qf);
4489 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
4493 /* possibly set ${dsn_ret} macro */
4494 if (bitset(EF_RET_PARAM, e->e_flags))
4496 if (bitset(EF_NO_BODY_RETN, e->e_flags))
4497 macdefine(&e->e_macro, A_PERM,
4498 macid("{dsn_ret}"), "hdrs");
4500 macdefine(&e->e_macro, A_PERM,
4501 macid("{dsn_ret}"), "full");
4505 ** Arrange to read the data file.
4508 p = queuename(e, DATAFL_LETTER);
4509 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, p, SM_IO_RDONLY_B,
4511 if (e->e_dfp == NULL)
4513 syserr("readqf: cannot open %s", p);
4517 e->e_flags |= EF_HAS_DF;
4518 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &st)
4521 e->e_msgsize = st.st_size + hdrsize;
4522 e->e_dfdev = st.st_dev;
4523 e->e_dfino = ST_INODE(st);
4524 (void) sm_snprintf(buf, sizeof buf, "%ld",
4526 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"),
4535 ** There was some error reading the qf file (reason is in err var.)
4537 ** close file; clear e_lockfp since it is the same as qfp,
4538 ** hence it is invalid (as file) after qfp is closed;
4539 ** the qf file is on disk, so set the flag to avoid calling
4540 ** queueup() with bogus data.
4544 (void) sm_io_close(qfp, SM_TIME_DEFAULT);
4546 e->e_flags |= EF_INQUEUE;
4551 ** PRTSTR -- print a string, "unprintable" characters are shown as \oct
4554 ** s -- string to print
4555 ** ml -- maximum length of output
4558 ** number of entries
4561 ** Prints a string on stdout.
4573 while (ml-- > 0 && ((c = *s++) != '\0'))
4579 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4580 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4583 else if (isascii(c) && isprint(c))
4584 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c);
4588 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4589 "\\%03o", c & 0xFF);
4594 ** PRINTNQE -- print out number of entries in the mail queue
4597 ** out -- output file pointer.
4598 ** prefix -- string to output in front of each line.
4605 printnqe(out, prefix)
4610 int i, k = 0, nrequests = 0;
4611 bool unknown = false;
4613 if (ShmId == SM_SHM_NO_ID)
4616 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4617 "Data unavailable: shared memory not updated\n");
4619 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4620 "%sNOTCONFIGURED:-1\r\n", prefix);
4623 for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
4628 for (j = 0; j < Queue[i]->qg_numqueues; j++)
4635 n = QSHM_ENTRIES(Queue[i]->qg_qpaths[j].qp_idx);
4637 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4639 prefix, qid_printqueue(i, j), n);
4642 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4643 "%s: unknown number of entries\n",
4644 qid_printqueue(i, j));
4649 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4651 qid_printqueue(i, j));
4655 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4657 qid_printqueue(i, j), n);
4663 if (prefix == NULL && k > 1)
4664 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4665 "\t\tTotal requests: %d%s\n",
4666 nrequests, unknown ? " (about)" : "");
4667 #else /* SM_CONF_SHM */
4669 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4670 "Data unavailable without shared memory support\n");
4672 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
4673 "%sNOTAVAILABLE:-1\r\n", prefix);
4674 #endif /* SM_CONF_SHM */
4677 ** PRINTQUEUE -- print out a representation of the mail queue
4686 ** Prints a listing of the mail queue on the standard output.
4692 int i, k = 0, nrequests = 0;
4694 for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
4699 for (j = 0; j < Queue[i]->qg_numqueues; j++)
4703 nrequests += print_single_queue(i, j);
4708 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4709 "\t\tTotal requests: %d\n",
4713 ** PRINT_SINGLE_QUEUE -- print out a representation of a single mail queue
4716 ** qgrp -- the index of the queue group.
4717 ** qdir -- the queue directory.
4720 ** number of requests in mail queue.
4723 ** Prints a listing of the mail queue on the standard output.
4727 print_single_queue(qgrp, qdir)
4734 char qd[MAXPATHLEN];
4735 char qddf[MAXPATHLEN];
4740 (void) sm_strlcpy(qd, ".", sizeof qd);
4741 (void) sm_strlcpy(qddf, ".", sizeof qddf);
4745 (void) sm_strlcpyn(qd, sizeof qd, 2,
4746 Queue[qgrp]->qg_qpaths[qdir].qp_name,
4748 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
4750 (void) sm_strlcpyn(qddf, sizeof qddf, 2,
4751 Queue[qgrp]->qg_qpaths[qdir].qp_name,
4753 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
4758 ** Check for permission to print the queue
4761 if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0)
4766 extern GIDSET_T InitialGidSet[NGROUPS_MAX];
4767 #endif /* NGROUPS_MAX */
4769 if (stat(qd, &st) < 0)
4771 syserr("Cannot stat %s",
4772 qid_printqueue(qgrp, qdir));
4779 if (InitialGidSet[n] == st.st_gid)
4782 if (n < 0 && RealGid != st.st_gid)
4783 #else /* NGROUPS_MAX */
4784 if (RealGid != st.st_gid)
4785 #endif /* NGROUPS_MAX */
4787 usrerr("510 You are not permitted to see the queue");
4794 ** Read and order the queue.
4797 nrequests = gatherq(qgrp, qdir, true, NULL, NULL);
4798 (void) sortq(Queue[qgrp]->qg_maxlist);
4801 ** Print the work list that we have read.
4804 /* first see if there is anything */
4807 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s is empty\n",
4808 qid_printqueue(qgrp, qdir));
4812 sm_getla(); /* get load average */
4814 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t\t%s (%d request%s",
4815 qid_printqueue(qgrp, qdir),
4816 nrequests, nrequests == 1 ? "" : "s");
4817 if (MaxQueueRun > 0 && nrequests > MaxQueueRun)
4818 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4819 ", only %d printed", MaxQueueRun);
4821 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4822 ")\n-----Q-ID----- --Size-- -Priority- ---Q-Time--- --------Sender/Recipient--------\n");
4824 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4825 ")\n-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------\n");
4826 for (w = WorkQ; w != NULL; w = w->w_next)
4829 auto time_t submittime = 0;
4833 char quarmsg[MAXLINE];
4834 char statmsg[MAXLINE];
4835 char bodytype[MAXNAME + 1];
4836 char qf[MAXPATHLEN];
4841 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%13s",
4843 (void) sm_strlcpyn(qf, sizeof qf, 3, qd, "/", w->w_name);
4844 f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B,
4849 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4850 " (permission denied)\n");
4851 else if (errno == ENOENT)
4852 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4853 " (job completed)\n");
4855 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4857 sm_errstring(errno));
4861 w->w_name[0] = DATAFL_LETTER;
4862 (void) sm_strlcpyn(qf, sizeof qf, 3, qddf, "/", w->w_name);
4863 if (stat(qf, &st) >= 0)
4864 dfsize = st.st_size;
4870 ** Maybe the df file can't be statted because
4871 ** it is in a different directory than the qf file.
4872 ** In order to find out, we must read the qf file.
4875 newenvelope(&e, &BlankEnvelope, sm_rpool_new_x(NULL));
4876 e.e_id = w->w_name + 2;
4880 if (readqf(&e, false))
4882 char *df = queuename(&e, DATAFL_LETTER);
4883 if (stat(df, &st) >= 0)
4884 dfsize = st.st_size;
4886 if (e.e_lockfp != NULL)
4888 (void) sm_io_close(e.e_lockfp, SM_TIME_DEFAULT);
4891 clearenvelope(&e, false, e.e_rpool);
4892 sm_rpool_free(e.e_rpool);
4895 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "*");
4896 else if (QueueMode == QM_LOST)
4897 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "?");
4898 else if (w->w_tooyoung)
4899 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "-");
4900 else if (shouldqueue(w->w_pri, w->w_ctime))
4901 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "X");
4903 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " ");
4908 statmsg[0] = bodytype[0] = '\0';
4910 while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof buf) != NULL)
4921 case 'V': /* queue file version */
4922 qfver = atoi(&buf[1]);
4925 case 'M': /* error message */
4926 if ((i = strlen(&buf[1])) >= sizeof statmsg)
4927 i = sizeof statmsg - 1;
4928 memmove(statmsg, &buf[1], i);
4932 case 'q': /* quarantine reason */
4933 if ((i = strlen(&buf[1])) >= sizeof quarmsg)
4934 i = sizeof quarmsg - 1;
4935 memmove(quarmsg, &buf[1], i);
4939 case 'B': /* body type */
4940 if ((i = strlen(&buf[1])) >= sizeof bodytype)
4941 i = sizeof bodytype - 1;
4942 memmove(bodytype, &buf[1], i);
4946 case 'S': /* sender name */
4949 (void) sm_io_fprintf(smioout,
4951 "%8ld %10ld%c%.12s ",
4954 bitset(EF_WARNING, flags)
4956 ctime(&submittime) + 4);
4957 prtstr(&buf[1], 78);
4961 (void) sm_io_fprintf(smioout,
4965 ctime(&submittime));
4966 prtstr(&buf[1], 39);
4969 if (quarmsg[0] != '\0')
4971 (void) sm_io_fprintf(smioout,
4973 "\n QUARANTINE: %.*s",
4979 if (statmsg[0] != '\0' || bodytype[0] != '\0')
4981 (void) sm_io_fprintf(smioout,
4985 if (statmsg[0] != '\0')
4986 (void) sm_io_fprintf(smioout,
4995 case 'C': /* controlling user */
4997 (void) sm_io_fprintf(smioout,
4999 "\n\t\t\t\t\t\t(---%.64s---)",
5003 case 'R': /* recipient name */
5014 (void) sm_io_fprintf(smioout,
5021 (void) sm_io_fprintf(smioout,
5026 if (Verbose && statmsg[0] != '\0')
5028 (void) sm_io_fprintf(smioout,
5036 case 'T': /* creation time */
5037 submittime = atol(&buf[1]);
5040 case 'F': /* flag bits */
5041 for (p = &buf[1]; *p != '\0'; p++)
5046 flags |= EF_WARNING;
5052 if (submittime == (time_t) 0)
5053 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
5054 " (no control file)");
5055 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n");
5056 (void) sm_io_close(f, SM_TIME_DEFAULT);
5062 ** QUEUE_LETTER -- get the proper queue letter for the current QueueMode.
5065 ** e -- envelope to build it in/from.
5066 ** type -- the file type, used as the first character
5067 ** of the file name.
5070 ** the letter to use
5074 queue_letter(e, type)
5078 /* Change type according to QueueMode */
5079 if (type == ANYQFL_LETTER)
5081 if (e->e_quarmsg != NULL)
5082 type = QUARQF_LETTER;
5088 type = NORMQF_LETTER;
5092 type = QUARQF_LETTER;
5096 type = LOSEQF_LETTER;
5100 /* should never happen */
5110 ** QUEUENAME -- build a file name in the queue directory for this envelope.
5113 ** e -- envelope to build it in/from.
5114 ** type -- the file type, used as the first character
5115 ** of the file name.
5118 ** a pointer to the queue name (in a static buffer).
5121 ** If no id code is already assigned, queuename() will
5122 ** assign an id code with assign_queueid(). If no queue
5123 ** directory is assigned, one will be set with setnewqueue().
5128 register ENVELOPE *e;
5134 static char buf[MAXPATHLEN];
5136 /* Assign an ID if needed */
5137 if (e->e_id == NULL)
5139 type = queue_letter(e, type);
5141 /* begin of filename */
5142 pref[0] = (char) type;
5146 /* Assign a queue group/directory if needed */
5147 if (type == XSCRPT_LETTER)
5150 ** We don't want to call setnewqueue() if we are fetching
5151 ** the pathname of the transcript file, because setnewqueue
5152 ** chooses a queue, and sometimes we need to write to the
5153 ** transcript file before we have gathered enough information
5154 ** to choose a queue.
5157 if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR)
5159 if (e->e_qgrp != NOQGRP && e->e_qdir != NOQDIR)
5161 e->e_xfqgrp = e->e_qgrp;
5162 e->e_xfqdir = e->e_qdir;
5167 if (Queue[e->e_xfqgrp]->qg_numqueues <= 1)
5171 e->e_xfqdir = get_rand_mod(
5172 Queue[e->e_xfqgrp]->qg_numqueues);
5181 if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR)
5183 if (type == DATAFL_LETTER)
5195 /* xf files always have a valid qd and qg picked above */
5196 if (e->e_qdir == NOQDIR && type != XSCRPT_LETTER)
5197 (void) sm_strlcpyn(buf, sizeof buf, 2, pref, e->e_id);
5203 if (bitset(QP_SUBDF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5212 if (bitset(QP_SUBQF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5217 if (bitset(QP_SUBXF, Queue[qg]->qg_qpaths[qd].qp_subdirs))
5222 sm_abort("queuename: bad queue file type %d", type);
5225 (void) sm_strlcpyn(buf, sizeof buf, 4,
5226 Queue[qg]->qg_qpaths[qd].qp_name,
5227 sub, pref, e->e_id);
5231 sm_dprintf("queuename: %s\n", buf);
5236 ** INIT_QID_ALG -- Initialize the (static) parameters that are used to
5237 ** generate a queue ID.
5239 ** This function is called by the daemon to reset
5240 ** LastQueueTime and LastQueuePid which are used by assign_queueid().
5241 ** Otherwise the algorithm may cause problems because
5242 ** LastQueueTime and LastQueuePid are set indirectly by main()
5243 ** before the daemon process is started, hence LastQueuePid is not
5244 ** the pid of the daemon and therefore a child of the daemon can
5245 ** actually have the same pid as LastQueuePid which means the section
5246 ** in assign_queueid():
5247 ** * see if we need to get a new base time/pid *
5248 ** is NOT triggered which will cause the same queue id to be generated.
5265 ** ASSIGN_QUEUEID -- assign a queue ID for this envelope.
5267 ** Assigns an id code if one does not already exist.
5268 ** This code assumes that nothing will remain in the queue for
5269 ** longer than 60 years. It is critical that files with the given
5270 ** name do not already exist in the queue.
5271 ** [No longer initializes e_qdir to NOQDIR.]
5274 ** e -- envelope to set it in.
5280 static const char QueueIdChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
5282 # define QIC_LEN_R 62
5285 ** Note: the length is "officially" 60 because minutes and seconds are
5286 ** usually only 0-59. However (Linux):
5287 ** tm_sec The number of seconds after the minute, normally in
5288 ** the range 0 to 59, but can be up to 61 to allow for
5290 ** Hence the real length of the string is 62 to take this into account.
5291 ** Alternatively % QIC_LEN can (should) be used for access everywhere.
5294 # define queuenextid() CurrentPid
5299 register ENVELOPE *e;
5301 pid_t pid = queuenextid();
5303 static long random_offset;
5305 char idbuf[MAXQFNAME - 2];
5308 if (e->e_id != NULL)
5311 /* see if we need to get a new base time/pid */
5312 if (cX >= QIC_LEN * QIC_LEN || LastQueueTime == 0 ||
5313 LastQueuePid != pid)
5315 time_t then = LastQueueTime;
5317 /* if the first time through, pick a random offset */
5318 if (LastQueueTime == 0)
5319 random_offset = get_random();
5321 while ((LastQueueTime = curtime()) == then &&
5322 LastQueuePid == pid)
5326 LastQueuePid = queuenextid();
5331 ** Generate a new sequence number between 0 and QIC_LEN*QIC_LEN-1.
5332 ** This lets us generate up to QIC_LEN*QIC_LEN unique queue ids
5333 ** per second, per process. With envelope splitting,
5334 ** a single message can consume many queue ids.
5337 seq = (int)((cX + random_offset) % (QIC_LEN * QIC_LEN));
5340 sm_dprintf("assign_queueid: random_offset = %ld (%d)\n",
5341 random_offset, seq);
5343 tm = gmtime(&LastQueueTime);
5344 idbuf[0] = QueueIdChars[tm->tm_year % QIC_LEN];
5345 idbuf[1] = QueueIdChars[tm->tm_mon];
5346 idbuf[2] = QueueIdChars[tm->tm_mday];
5347 idbuf[3] = QueueIdChars[tm->tm_hour];
5348 idbuf[4] = QueueIdChars[tm->tm_min % QIC_LEN_R];
5349 idbuf[5] = QueueIdChars[tm->tm_sec % QIC_LEN_R];
5350 idbuf[6] = QueueIdChars[seq / QIC_LEN];
5351 idbuf[7] = QueueIdChars[seq % QIC_LEN];
5352 (void) sm_snprintf(&idbuf[8], sizeof idbuf - 8, "%06d",
5353 (int) LastQueuePid);
5354 e->e_id = sm_rpool_strdup_x(e->e_rpool, idbuf);
5355 macdefine(&e->e_macro, A_PERM, 'i', e->e_id);
5357 /* XXX: inherited from MainEnvelope */
5358 e->e_qgrp = NOQGRP; /* too early to do anything else */
5360 e->e_xfqgrp = NOQGRP;
5363 /* New ID means it's not on disk yet */
5364 e->e_qfletter = '\0';
5367 sm_dprintf("assign_queueid: assigned id %s, e=%p\n",
5370 sm_syslog(LOG_DEBUG, e->e_id, "assigned id");
5373 ** SYNC_QUEUE_TIME -- Assure exclusive PID in any given second
5375 ** Make sure one PID can't be used by two processes in any one second.
5377 ** If the system rotates PIDs fast enough, may get the
5378 ** same pid in the same second for two distinct processes.
5379 ** This will interfere with the queue file naming system.
5391 #if FAST_PID_RECYCLE
5392 if (OpMode != MD_TEST &&
5393 OpMode != MD_VERIFY &&
5394 LastQueueTime > 0 &&
5395 LastQueuePid == CurrentPid &&
5396 curtime() == LastQueueTime)
5398 #endif /* FAST_PID_RECYCLE */
5401 ** UNLOCKQUEUE -- unlock the queue entry for a specified envelope
5404 ** e -- the envelope to unlock.
5410 ** unlocks the queue for `e'.
5418 sm_dprintf("unlockqueue(%s)\n",
5419 e->e_id == NULL ? "NOQUEUE" : e->e_id);
5422 /* if there is a lock file in the envelope, close it */
5423 if (e->e_lockfp != NULL)
5424 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT);
5427 /* don't create a queue id if we don't already have one */
5428 if (e->e_id == NULL)
5431 /* remove the transcript */
5433 sm_syslog(LOG_DEBUG, e->e_id, "unlock");
5435 (void) xunlink(queuename(e, XSCRPT_LETTER));
5438 ** SETCTLUSER -- create a controlling address
5440 ** Create a fake "address" given only a local login name; this is
5441 ** used as a "controlling user" for future recipient addresses.
5444 ** user -- the user name of the controlling user.
5445 ** qfver -- the version stamp of this queue file.
5449 ** An address descriptor for the controlling user,
5450 ** using storage allocated from e->e_rpool.
5455 setctluser(user, qfver, e)
5460 register ADDRESS *a;
5465 ** See if this clears our concept of controlling user.
5468 if (user == NULL || *user == '\0')
5472 ** Set up addr fields for controlling user.
5475 a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof *a);
5476 memset((char *) a, '\0', sizeof *a);
5481 a->q_user = sm_rpool_strdup_x(e->e_rpool, p);
5485 p = strtok(user, ":");
5486 a->q_user = sm_rpool_strdup_x(e->e_rpool, user);
5489 if ((p = strtok(NULL, ":")) != NULL)
5491 if ((p = strtok(NULL, ":")) != NULL)
5493 if ((p = strtok(NULL, ":")) != NULL)
5497 a->q_flags |= QGOODUID;
5499 /* if there is another ':': restore it */
5500 if ((o = strtok(NULL, ":")) != NULL && o > p)
5504 else if ((pw = sm_getpwnam(user)) != NULL)
5506 if (*pw->pw_dir == '\0')
5508 else if (strcmp(pw->pw_dir, "/") == 0)
5511 a->q_home = sm_rpool_strdup_x(e->e_rpool, pw->pw_dir);
5512 a->q_uid = pw->pw_uid;
5513 a->q_gid = pw->pw_gid;
5514 a->q_flags |= QGOODUID;
5518 a->q_flags |= QPRIMARY; /* flag as a "ctladdr" */
5519 a->q_mailer = LocalMailer;
5521 a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user);
5523 a->q_paddr = sm_rpool_strdup_x(e->e_rpool, p);
5527 ** LOSEQFILE -- rename queue file with LOSEQF_LETTER & try to let someone know
5530 ** e -- the envelope (e->e_id will be used).
5531 ** why -- reported to whomever can hear.
5539 register ENVELOPE *e;
5544 char buf[MAXPATHLEN];
5546 if (e == NULL || e->e_id == NULL)
5548 p = queuename(e, ANYQFL_LETTER);
5549 if (sm_strlcpy(buf, p, sizeof buf) >= sizeof buf)
5551 if (!bitset(EF_INQUEUE, e->e_flags))
5552 queueup(e, false, true);
5553 else if (QueueMode == QM_LOST)
5556 /* if already lost, no need to re-lose */
5559 p = queuename(e, LOSEQF_LETTER);
5560 if (rename(buf, p) < 0)
5561 syserr("cannot rename(%s, %s), uid=%d",
5562 buf, p, (int) geteuid());
5563 else if (LogLevel > 0)
5564 sm_syslog(LOG_ALERT, e->e_id,
5565 "Losing %s: %s", buf, why);
5567 if (e->e_dfp != NULL)
5569 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
5572 e->e_flags &= ~EF_HAS_DF;
5575 ** NAME2QID -- translate a queue group name to a queue group id
5578 ** queuename -- name of queue group.
5581 ** queue group id if found.
5582 ** NOQGRP otherwise.
5591 s = stab(queuename, ST_QUEUE, ST_FIND);
5594 return s->s_quegrp->qg_index;
5597 ** QID_PRINTNAME -- create externally printable version of queue id
5600 ** e -- the envelope.
5603 ** a printable version
5611 static char idbuf[MAXQFNAME + 34];
5616 if (e->e_id == NULL)
5621 if (e->e_qdir == NOQDIR)
5624 (void) sm_snprintf(idbuf, sizeof idbuf, "%.32s/%s",
5625 Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_name,
5630 ** QID_PRINTQUEUE -- create full version of queue directory for data files
5633 ** qgrp -- index in queue group.
5634 ** qdir -- the short version of the queue directory
5637 ** the full pathname to the queue (might point to a static var)
5641 qid_printqueue(qgrp, qdir)
5646 static char dir[MAXPATHLEN];
5649 return Queue[qgrp]->qg_qdir;
5651 if (strcmp(Queue[qgrp]->qg_qpaths[qdir].qp_name, ".") == 0)
5654 subdir = Queue[qgrp]->qg_qpaths[qdir].qp_name;
5656 (void) sm_strlcpyn(dir, sizeof dir, 4,
5657 Queue[qgrp]->qg_qdir,
5658 subdir == NULL ? "" : "/",
5659 subdir == NULL ? "" : subdir,
5661 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs)
5667 ** PICKQDIR -- Pick a queue directory from a queue group
5670 ** qg -- queue group
5671 ** fsize -- file size in bytes
5672 ** e -- envelope, or NULL
5675 ** NOQDIR if no queue directory in qg has enough free space to
5676 ** hold a file of size 'fsize', otherwise the index of
5677 ** a randomly selected queue directory which resides on a
5678 ** file system with enough disk space.
5679 ** XXX This could be extended to select a queuedir with
5680 ** a few (the fewest?) number of entries. That data
5681 ** is available if shared memory is used.
5684 ** If the request fails and e != NULL then sm_syslog is called.
5688 pickqdir(qg, fsize, e)
5697 /* Pick a random directory, as a starting point. */
5698 if (qg->qg_numqueues <= 1)
5701 qdir = get_rand_mod(qg->qg_numqueues);
5703 if (MinBlocksFree <= 0 && fsize <= 0)
5707 ** Now iterate over the queue directories,
5708 ** looking for a directory with enough space for this message.
5714 QPATHS *qp = &qg->qg_qpaths[i];
5719 needed += fsize / FILE_SYS_BLKSIZE(qp->qp_fsysidx)
5720 + ((fsize % FILE_SYS_BLKSIZE(qp->qp_fsysidx)
5722 if (MinBlocksFree > 0)
5723 needed += MinBlocksFree;
5724 fsavail = FILE_SYS_AVAIL(qp->qp_fsysidx);
5731 ** might be not correctly updated,
5732 ** let's try to get the info directly.
5735 fsavail = freediskspace(FILE_SYS_NAME(qp->qp_fsysidx),
5740 #endif /* SM_CONF_SHM */
5741 if (needed <= fsavail)
5743 if (avail < fsavail)
5746 if (qg->qg_numqueues > 0)
5747 i = (i + 1) % qg->qg_numqueues;
5748 } while (i != qdir);
5750 if (e != NULL && LogLevel > 0)
5751 sm_syslog(LOG_ALERT, e->e_id,
5752 "low on space (%s needs %ld bytes + %ld blocks in %s), max avail: %ld",
5753 CurHostName == NULL ? "SMTP-DAEMON" : CurHostName,
5754 fsize, MinBlocksFree,
5755 qg->qg_qdir, avail);
5759 ** SETNEWQUEUE -- Sets a new queue group and directory
5761 ** Assign a queue group and directory to an envelope and store the
5762 ** directory in e->e_qdir.
5765 ** e -- envelope to assign a queue for.
5768 ** true if successful
5772 ** On success, e->e_qgrp and e->e_qdir are non-negative.
5773 ** On failure (not enough disk space),
5774 ** e->qgrp = NOQGRP, e->e_qdir = NOQDIR
5775 ** and usrerr() is invoked (which could raise an exception).
5783 sm_dprintf("setnewqueue: called\n");
5785 /* not set somewhere else */
5786 if (e->e_qgrp == NOQGRP)
5791 ** Use the queue group of the "first" recipient, as set by
5792 ** the "queuegroup" rule set. If that is not defined, then
5793 ** use the queue group of the mailer of the first recipient.
5794 ** If that is not defined either, then use the default
5796 ** Notice: "first" depends on the sorting of sendqueue
5798 ** To avoid problems with "bad" recipients look
5799 ** for a valid address first.
5804 (QS_IS_BADADDR(q->q_state) || QS_IS_DEAD(q->q_state)))
5810 else if (q->q_qgrp >= 0)
5811 e->e_qgrp = q->q_qgrp;
5812 else if (q->q_mailer != NULL &&
5813 ISVALIDQGRP(q->q_mailer->m_qgrp))
5814 e->e_qgrp = q->q_mailer->m_qgrp;
5817 e->e_dfqgrp = e->e_qgrp;
5820 if (ISVALIDQDIR(e->e_qdir) && ISVALIDQDIR(e->e_dfqdir))
5823 sm_dprintf("setnewqueue: e_qdir already assigned (%s)\n",
5824 qid_printqueue(e->e_qgrp, e->e_qdir));
5829 e->e_qdir = pickqdir(Queue[e->e_qgrp], e->e_msgsize, e);
5830 if (e->e_qdir == NOQDIR)
5833 if (!bitset(EF_FATALERRS, e->e_flags))
5834 usrerr("452 4.4.5 Insufficient disk space; try again later");
5835 e->e_flags |= EF_FATALERRS;
5840 sm_dprintf("setnewqueue: Assigned queue directory %s\n",
5841 qid_printqueue(e->e_qgrp, e->e_qdir));
5843 if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR)
5845 e->e_xfqgrp = e->e_qgrp;
5846 e->e_xfqdir = e->e_qdir;
5848 e->e_dfqdir = e->e_qdir;
5852 ** CHKQDIR -- check a queue directory
5855 ** name -- name of queue directory
5856 ** sff -- flags for safefile()
5859 ** is it a queue directory?
5870 /* skip over . and .. directories */
5871 if (name[0] == '.' &&
5872 (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
5875 if (lstat(name, &statb) < 0)
5876 #else /* HASLSTAT */
5877 if (stat(name, &statb) < 0)
5878 #endif /* HASLSTAT */
5881 sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
5882 name, sm_errstring(errno));
5886 if (S_ISLNK(statb.st_mode))
5889 ** For a symlink we need to make sure the
5890 ** target is a directory
5893 if (stat(name, &statb) < 0)
5896 sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
5897 name, sm_errstring(errno));
5901 #endif /* HASLSTAT */
5903 if (!S_ISDIR(statb.st_mode))
5906 sm_dprintf("chkqdir: \"%s\": Not a directory\n",
5911 /* Print a warning if unsafe (but still use it) */
5912 /* XXX do this only if we want the warning? */
5913 i = safedirpath(name, RunAsUid, RunAsGid, NULL, sff, 0, 0);
5917 sm_dprintf("chkqdir: \"%s\": Not safe: %s\n",
5918 name, sm_errstring(i));
5921 sm_syslog(LOG_WARNING, NOQID,
5922 "queue directory \"%s\": Not safe: %s",
5923 name, sm_errstring(i));
5924 #endif /* _FFR_CHK_QUEUE */
5929 ** MULTIQUEUE_CACHE -- cache a list of paths to queues.
5931 ** Each potential queue is checked as the cache is built.
5932 ** Thereafter, each is blindly trusted.
5933 ** Note that we can be called again after a timeout to rebuild
5934 ** (although code for that is not ready yet).
5937 ** basedir -- base of all queue directories.
5938 ** blen -- strlen(basedir).
5939 ** qg -- queue group.
5940 ** qn -- number of queue directories already cached.
5941 ** phash -- pointer to hash value over queue dirs.
5943 ** only used if shared memory is active.
5944 #endif * SM_CONF_SHM *
5947 ** new number of queue directories.
5950 #define INITIAL_SLOTS 20
5951 #define ADD_SLOTS 10
5954 multiqueue_cache(basedir, blen, qg, qn, phash)
5959 unsigned int *phash;
5964 long sff = SFF_ANYFILE;
5965 char qpath[MAXPATHLEN];
5966 char subdir[MAXPATHLEN];
5967 char prefix[MAXPATHLEN]; /* dir relative to basedir */
5970 sm_dprintf("multiqueue_cache: called\n");
5972 /* Initialize to current directory */
5975 if (qg->qg_numqueues != 0 && qg->qg_qpaths != NULL)
5977 for (i = 0; i < qg->qg_numqueues; i++)
5979 if (qg->qg_qpaths[i].qp_name != NULL)
5980 (void) sm_free(qg->qg_qpaths[i].qp_name); /* XXX */
5982 (void) sm_free((char *) qg->qg_qpaths); /* XXX */
5983 qg->qg_qpaths = NULL;
5984 qg->qg_numqueues = 0;
5987 /* If running as root, allow safedirpath() checks to use privs */
5991 sff |= SFF_SAFEDIRPATH|SFF_NOWWFILES;
5993 sff |= SFF_NOGWFILES;
5994 #endif /* _FFR_CHK_QUEUE */
5996 if (!SM_IS_DIR_START(qg->qg_qdir))
5999 ** XXX we could add basedir, but then we have to realloc()
6000 ** the string... Maybe another time.
6003 syserr("QueuePath %s not absolute", qg->qg_qdir);
6004 ExitStat = EX_CONFIG;
6008 /* qpath: directory of current workgroup */
6009 len = sm_strlcpy(qpath, qg->qg_qdir, sizeof qpath);
6010 if (len >= sizeof qpath)
6012 syserr("QueuePath %.256s too long (%d max)",
6013 qg->qg_qdir, (int) sizeof qpath);
6014 ExitStat = EX_CONFIG;
6018 /* begin of qpath must be same as basedir */
6019 if (strncmp(basedir, qpath, blen) != 0 &&
6020 (strncmp(basedir, qpath, blen - 1) != 0 || len != blen - 1))
6022 syserr("QueuePath %s not subpath of QueueDirectory %s",
6024 ExitStat = EX_CONFIG;
6028 /* Do we have a nested subdirectory? */
6029 if (blen < len && SM_FIRST_DIR_DELIM(qg->qg_qdir + blen) != NULL)
6032 /* Copy subdirectory into prefix for later use */
6033 if (sm_strlcpy(prefix, qg->qg_qdir + blen, sizeof prefix) >=
6036 syserr("QueuePath %.256s too long (%d max)",
6037 qg->qg_qdir, (int) sizeof qpath);
6038 ExitStat = EX_CONFIG;
6041 cp = SM_LAST_DIR_DELIM(prefix);
6042 SM_ASSERT(cp != NULL);
6043 *cp = '\0'; /* cut off trailing / */
6046 /* This is guaranteed by the basedir check above */
6047 SM_ASSERT(len >= blen - 1);
6048 cp = &qpath[len - 1];
6052 register struct dirent *d;
6055 char relpath[MAXPATHLEN];
6057 *cp = '\0'; /* Overwrite wildcard */
6058 if ((cp = SM_LAST_DIR_DELIM(qpath)) == NULL)
6060 syserr("QueueDirectory: can not wildcard relative path");
6062 sm_dprintf("multiqueue_cache: \"%s*\": Can not wildcard relative path.\n",
6064 ExitStat = EX_CONFIG;
6070 ** Special case of top level wildcard, like /foo*
6074 (void) sm_strlcpy(qpath + 1, qpath, sizeof qpath - 1);
6078 *(cp++) = '\0'; /* Replace / with \0 */
6079 len = strlen(cp); /* Last component of queue directory */
6082 ** Path relative to basedir, with trailing /
6083 ** It will be modified below to specify the subdirectories
6084 ** so they can be opened without chdir().
6087 off = sm_strlcpyn(relpath, sizeof relpath, 2, prefix, "/");
6088 SM_ASSERT(off < sizeof relpath);
6091 sm_dprintf("multiqueue_cache: prefix=\"%s%s\"\n",
6094 /* It is always basedir: we don't need to store it per group */
6095 /* XXX: optimize this! -> one more global? */
6096 qg->qg_qdir = newstr(basedir);
6097 qg->qg_qdir[blen - 1] = '\0'; /* cut off trailing / */
6100 ** XXX Should probably wrap this whole loop in a timeout
6101 ** in case some wag decides to NFS mount the queues.
6104 /* Test path to get warning messages. */
6107 /* XXX qg_runasuid and qg_runasgid for specials? */
6108 i = safedirpath(basedir, RunAsUid, RunAsGid, NULL,
6110 if (i != 0 && tTd(41, 2))
6111 sm_dprintf("multiqueue_cache: \"%s\": Not safe: %s\n",
6112 basedir, sm_errstring(i));
6115 if ((dp = opendir(prefix)) == NULL)
6117 syserr("can not opendir(%s/%s)", qg->qg_qdir, prefix);
6119 sm_dprintf("multiqueue_cache: opendir(\"%s/%s\"): %s\n",
6120 qg->qg_qdir, prefix,
6121 sm_errstring(errno));
6122 ExitStat = EX_CONFIG;
6125 while ((d = readdir(dp)) != NULL)
6127 i = strlen(d->d_name);
6128 if (i < len || strncmp(d->d_name, cp, len) != 0)
6131 sm_dprintf("multiqueue_cache: \"%s\", skipped\n",
6136 /* Create relative pathname: prefix + local directory */
6137 i = sizeof(relpath) - off;
6138 if (sm_strlcpy(relpath + off, d->d_name, i) >= i)
6139 continue; /* way too long */
6141 if (!chkqdir(relpath, sff))
6144 if (qg->qg_qpaths == NULL)
6146 slotsleft = INITIAL_SLOTS;
6147 qg->qg_qpaths = (QPATHS *)xalloc((sizeof *qg->qg_qpaths) *
6149 qg->qg_numqueues = 0;
6151 else if (slotsleft < 1)
6153 qg->qg_qpaths = (QPATHS *)sm_realloc((char *)qg->qg_qpaths,
6154 (sizeof *qg->qg_qpaths) *
6157 if (qg->qg_qpaths == NULL)
6159 (void) closedir(dp);
6162 slotsleft += ADD_SLOTS;
6166 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs = QP_NOSUB;
6168 #define CHKRSUBDIR(name, flag) \
6169 (void) sm_strlcpyn(subdir, sizeof subdir, 3, relpath, "/", name); \
6170 if (chkqdir(subdir, sff)) \
6171 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs |= flag; \
6175 CHKRSUBDIR("qf", QP_SUBQF);
6176 CHKRSUBDIR("df", QP_SUBDF);
6177 CHKRSUBDIR("xf", QP_SUBXF);
6179 /* assert(strlen(d->d_name) < MAXPATHLEN - 14) */
6180 /* maybe even - 17 (subdirs) */
6182 if (prefix[0] != '.')
6183 qg->qg_qpaths[qg->qg_numqueues].qp_name =
6186 qg->qg_qpaths[qg->qg_numqueues].qp_name =
6190 sm_dprintf("multiqueue_cache: %d: \"%s\" cached (%x).\n",
6191 qg->qg_numqueues, relpath,
6192 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs);
6194 qg->qg_qpaths[qg->qg_numqueues].qp_idx = qn;
6195 *phash = hash_q(relpath, *phash);
6196 #endif /* SM_CONF_SHM */
6201 (void) closedir(dp);
6206 if (qg->qg_numqueues == 0)
6208 qg->qg_qpaths = (QPATHS *) xalloc(sizeof *qg->qg_qpaths);
6210 /* test path to get warning messages */
6211 i = safedirpath(qpath, RunAsUid, RunAsGid, NULL, sff, 0, 0);
6214 syserr("can not opendir(%s)", qpath);
6216 sm_dprintf("multiqueue_cache: opendir(\"%s\"): %s\n",
6217 qpath, sm_errstring(i));
6218 ExitStat = EX_CONFIG;
6222 qg->qg_qpaths[0].qp_subdirs = QP_NOSUB;
6223 qg->qg_numqueues = 1;
6226 #define CHKSUBDIR(name, flag) \
6227 (void) sm_strlcpyn(subdir, sizeof subdir, 3, qg->qg_qdir, "/", name); \
6228 if (chkqdir(subdir, sff)) \
6229 qg->qg_qpaths[0].qp_subdirs |= flag; \
6232 CHKSUBDIR("qf", QP_SUBQF);
6233 CHKSUBDIR("df", QP_SUBDF);
6234 CHKSUBDIR("xf", QP_SUBXF);
6236 if (qg->qg_qdir[blen - 1] != '\0' &&
6237 qg->qg_qdir[blen] != '\0')
6240 ** Copy the last component into qpaths and
6244 qg->qg_qpaths[0].qp_name = newstr(qg->qg_qdir + blen);
6245 qg->qg_qdir[blen - 1] = '\0';
6248 qg->qg_qpaths[0].qp_name = newstr(".");
6251 qg->qg_qpaths[0].qp_idx = qn;
6252 *phash = hash_q(qg->qg_qpaths[0].qp_name, *phash);
6253 #endif /* SM_CONF_SHM */
6260 ** FILESYS_FIND -- find entry in FileSys table, or add new one
6262 ** Given the pathname of a directory, determine the file system
6263 ** in which that directory resides, and return a pointer to the
6264 ** entry in the FileSys table that describes the file system.
6265 ** A new entry is added if necessary (and requested).
6266 ** If the directory does not exist, -1 is returned.
6269 ** path -- pathname of directory
6270 ** add -- add to structure if not found.
6273 ** >=0: found: index in file system table
6274 ** <0: some error, i.e.,
6275 ** FSF_TOO_MANY: too many filesystems (-> syserr())
6276 ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
6277 ** FSF_NOT_FOUND: not in list
6280 static short filesys_find __P((char *, bool));
6282 #define FSF_NOT_FOUND (-1)
6283 #define FSF_STAT_FAIL (-2)
6284 #define FSF_TOO_MANY (-3)
6287 filesys_find(path, add)
6294 if (stat(path, &st) < 0)
6296 syserr("cannot stat queue directory %s", path);
6297 return FSF_STAT_FAIL;
6299 for (i = 0; i < NumFileSys; ++i)
6301 if (FILE_SYS_DEV(i) == st.st_dev)
6304 if (i >= MAXFILESYS)
6306 syserr("too many queue file systems (%d max)", MAXFILESYS);
6307 return FSF_TOO_MANY;
6310 return FSF_NOT_FOUND;
6313 FILE_SYS_NAME(i) = path;
6314 FILE_SYS_DEV(i) = st.st_dev;
6315 FILE_SYS_AVAIL(i) = 0;
6316 FILE_SYS_BLKSIZE(i) = 1024; /* avoid divide by zero */
6321 ** FILESYS_SETUP -- set up mapping from queue directories to file systems
6323 ** This data structure is used to efficiently check the amount of
6324 ** free space available in a set of queue directories.
6327 ** add -- initialize structure if necessary.
6331 ** <0: some error, i.e.,
6332 ** FSF_NOT_FOUND: not in list
6333 ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
6334 ** FSF_TOO_MANY: too many filesystems (-> syserr())
6337 static int filesys_setup __P((bool));
6348 for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
6350 for (j = 0; j < Queue[i]->qg_numqueues; ++j)
6352 QPATHS *qp = &Queue[i]->qg_qpaths[j];
6354 fs = filesys_find(qp->qp_name, add);
6356 qp->qp_fsysidx = fs;
6367 ** FILESYS_UPDATE -- update amount of free space on all file systems
6369 ** The FileSys table is used to cache the amount of free space
6370 ** available on all queue directory file systems.
6371 ** This function updates the cached information if it has expired.
6380 ** Updates FileSys table.
6387 long avail, blksize;
6389 static time_t nextupdate = 0;
6392 /* only the daemon updates this structure */
6393 if (ShmId != SM_SHM_NO_ID && DaemonPid != CurrentPid)
6395 #endif /* SM_CONF_SHM */
6397 if (now < nextupdate)
6399 nextupdate = now + FILESYS_UPDATE_INTERVAL;
6400 for (i = 0; i < NumFileSys; ++i)
6402 FILESYS *fs = &FILE_SYS(i);
6404 avail = freediskspace(FILE_SYS_NAME(i), &blksize);
6405 if (avail < 0 || blksize <= 0)
6408 sm_syslog(LOG_ERR, NOQID,
6409 "filesys_update failed: %s, fs=%s, avail=%ld, blocksize=%ld",
6410 sm_errstring(errno),
6411 FILE_SYS_NAME(i), avail, blksize);
6413 fs->fs_blksize = 1024; /* avoid divide by zero */
6414 nextupdate = now + 2; /* let's do this soon again */
6418 fs->fs_avail = avail;
6419 fs->fs_blksize = blksize;
6424 #if _FFR_ANY_FREE_FS
6426 ** FILESYS_FREE -- check whether there is at least one fs with enough space.
6429 ** fsize -- file size in bytes
6432 ** true iff there is one fs with more than fsize bytes free.
6443 for (i = 0; i < NumFileSys; ++i)
6447 if (FILE_SYS_AVAIL(i) < 0 || FILE_SYS_BLKSIZE(i) <= 0)
6449 needed += fsize / FILE_SYS_BLKSIZE(i)
6450 + ((fsize % FILE_SYS_BLKSIZE(i)
6453 if (needed <= FILE_SYS_AVAIL(i))
6458 #endif /* _FFR_ANY_FREE_FS */
6460 #if _FFR_CONTROL_MSTAT
6462 ** DISK_STATUS -- show amount of free space in queue directories
6465 ** out -- output file pointer.
6466 ** prefix -- string to output in front of each line.
6473 disk_status(out, prefix)
6478 long avail, blksize;
6481 for (i = 0; i < NumFileSys; ++i)
6483 avail = freediskspace(FILE_SYS_NAME(i), &blksize);
6484 if (avail >= 0 && blksize > 0)
6486 free = (long)((double) avail *
6487 ((double) blksize / 1024));
6491 (void) sm_io_fprintf(out, SM_TIME_DEFAULT,
6498 #endif /* _FFR_CONTROL_MSTAT */
6503 ** INIT_SEM -- initialize semaphore system
6506 ** owner -- is this the owner of semaphores?
6512 #if _FFR_USE_SEM_LOCKING
6514 static int SemId = -1; /* Semaphore Id */
6515 int SemKey = SM_SEM_KEY;
6516 #endif /* SM_CONF_SEM */
6517 #endif /* _FFR_USE_SEM_LOCKING */
6519 static void init_sem __P((bool));
6525 #if _FFR_USE_SEM_LOCKING
6527 SemId = sm_sem_start(SemKey, 1, 0, owner);
6530 sm_syslog(LOG_ERR, NOQID,
6531 "func=init_sem, sem_key=%ld, sm_sem_start=%d",
6532 (long) SemKey, SemId);
6535 #endif /* SM_CONF_SEM */
6536 #endif /* _FFR_USE_SEM_LOCKING */
6541 ** STOP_SEM -- stop semaphore system
6544 ** owner -- is this the owner of semaphores?
6550 static void stop_sem __P((bool));
6556 #if _FFR_USE_SEM_LOCKING
6558 if (owner && SemId >= 0)
6560 #endif /* SM_CONF_SEM */
6561 #endif /* _FFR_USE_SEM_LOCKING */
6566 ** UPD_QS -- update information about queue when adding/deleting an entry
6570 ** count -- add/remove entry (+1/0/-1: add/no change/remove)
6571 ** space -- update the space available as well.
6572 ** (>0/0/<0: add/no change/remove)
6573 ** where -- caller (for logging)
6579 ** Modifies available space in filesystem.
6580 ** Changes number of entries in queue directory.
6584 upd_qs(e, count, space, where)
6592 # if _FFR_USE_SEM_LOCKING
6594 # endif /* _FFR_USE_SEM_LOCKING */
6597 if (ShmId == SM_SHM_NO_ID || e == NULL)
6599 if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR)
6601 idx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_idx;
6603 sm_dprintf("func=upd_qs, count=%d, space=%d, where=%s, idx=%d, entries=%d\n",
6604 count, space, where, idx, QSHM_ENTRIES(idx));
6606 /* XXX in theory this needs to be protected with a mutex */
6607 if (QSHM_ENTRIES(idx) >= 0 && count != 0)
6609 # if _FFR_USE_SEM_LOCKING
6610 r = sm_sem_acq(SemId, 0, 1);
6611 # endif /* _FFR_USE_SEM_LOCKING */
6612 QSHM_ENTRIES(idx) += count;
6613 # if _FFR_USE_SEM_LOCKING
6615 r = sm_sem_rel(SemId, 0, 1);
6616 # endif /* _FFR_USE_SEM_LOCKING */
6619 fidx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_fsysidx;
6623 /* update available space also? (might be loseqfile) */
6627 /* convert size to blocks; this causes rounding errors */
6628 s = e->e_msgsize / FILE_SYS_BLKSIZE(fidx);
6632 /* XXX in theory this needs to be protected with a mutex */
6634 FILE_SYS_AVAIL(fidx) += s;
6636 FILE_SYS_AVAIL(fidx) -= s;
6642 static bool write_key_file __P((char *, long));
6643 static long read_key_file __P((char *, long));
6646 ** WRITE_KEY_FILE -- record some key into a file.
6649 ** keypath -- file name.
6650 ** key -- key to write.
6653 ** true iff file could be written.
6660 write_key_file(keypath, key)
6669 if (keypath == NULL || *keypath == '\0')
6671 sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT;
6672 if (TrustedUid != 0 && RealUid == TrustedUid)
6673 sff |= SFF_OPENASROOT;
6674 keyf = safefopen(keypath, O_WRONLY|O_TRUNC, FileMode, sff);
6677 sm_syslog(LOG_ERR, NOQID, "unable to write %s: %s",
6678 keypath, sm_errstring(errno));
6682 ok = sm_io_fprintf(keyf, SM_TIME_DEFAULT, "%ld\n", key) !=
6684 ok = (sm_io_close(keyf, SM_TIME_DEFAULT) != SM_IO_EOF) && ok;
6690 ** READ_KEY_FILE -- read a key from a file.
6693 ** keypath -- file name.
6694 ** key -- default key.
6701 read_key_file(keypath, key)
6709 if (keypath == NULL || *keypath == '\0')
6711 sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY;
6712 if (RealUid == 0 || (TrustedUid != 0 && RealUid == TrustedUid))
6713 sff |= SFF_OPENASROOT;
6714 keyf = safefopen(keypath, O_RDONLY, FileMode, sff);
6717 sm_syslog(LOG_ERR, NOQID, "unable to read %s: %s",
6718 keypath, sm_errstring(errno));
6722 r = sm_io_fscanf(keyf, SM_TIME_DEFAULT, "%ld", &n);
6725 (void) sm_io_close(keyf, SM_TIME_DEFAULT);
6729 #endif /* _FFR_SELECT_SHM */
6732 ** INIT_SHM -- initialize shared memory structure
6734 ** Initialize or attach to shared memory segment.
6735 ** Currently it is not a fatal error if this doesn't work.
6736 ** However, it causes us to have a "fallback" storage location
6737 ** for everything that is supposed to be in the shared memory,
6738 ** which makes the code slightly ugly.
6741 ** qn -- number of queue directories.
6742 ** owner -- owner of shared memory.
6743 ** hash -- identifies data that is stored in shared memory.
6749 static void init_shm __P((int, bool, unsigned int));
6752 init_shm(qn, owner, hash)
6762 #endif /* _FFR_SELECT_SHM */
6764 PtrFileSys = &FileSys[0];
6765 PNumFileSys = &Numfilesys;
6767 /* if this "key" is specified: select one yourself */
6768 # define SEL_SHM_KEY ((key_t) -1)
6769 # define FIRST_SHM_KEY 25
6770 #endif /* _FFR_SELECT_SHM */
6772 /* This allows us to disable shared memory at runtime. */
6777 shms = SM_T_SIZE + qn * sizeof(QUEUE_SHM_T);
6779 keyselect = ShmKey == SEL_SHM_KEY;
6783 ShmKey = FIRST_SHM_KEY;
6786 ShmKey = read_key_file(ShmKeyFile, ShmKey);
6788 if (ShmKey == SEL_SHM_KEY)
6792 #endif /* _FFR_SELECT_SHM */
6795 /* allow read/write access for group? */
6796 Pshm = sm_shmstart(ShmKey, shms,
6797 SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3),
6800 if (Pshm != NULL || !sm_file_exists(save_errno))
6809 /* back where we started? */
6810 if (ShmKey == SEL_SHM_KEY)
6814 #endif /* _FFR_SELECT_SHM */
6818 /* only sleep if we are at the first key */
6819 if (!keyselect || ShmKey == SEL_SHM_KEY)
6820 #endif /* _FFR_SELECT_SHM */
6829 (void) write_key_file(ShmKeyFile, (long) ShmKey);
6830 #endif /* _FFR_SELECT_SHM */
6831 if (owner && RunAsUid != 0)
6833 i = sm_shmsetowner(ShmId, RunAsUid, RunAsGid,
6836 sm_syslog(LOG_ERR, NOQID,
6837 "key=%ld, sm_shmsetowner=%d, RunAsUid=%d, RunAsGid=%d",
6839 RunAsUid, RunAsGid);
6845 *((pid_t *) SHM_OFF_PID(Pshm)) = CurrentPid;
6846 p = (int *) SHM_OFF_TAG(Pshm);
6851 if (*p != (int) shms)
6853 save_errno = EINVAL;
6857 p = (int *) SHM_OFF_TAG(Pshm);
6858 if (*p != (int) hash)
6860 save_errno = EINVAL;
6866 ** XXX how to check the pid?
6867 ** Read it from the pid-file? That does
6868 ** not need to exist.
6869 ** We could disable shm if we can't confirm
6870 ** that it is the right one.
6874 PtrFileSys = (FILESYS *) OFF_FILE_SYS(Pshm);
6875 PNumFileSys = (int *) OFF_NUM_FILE_SYS(Pshm);
6876 QShm = (QUEUE_SHM_T *) OFF_QUEUE_SHM(Pshm);
6877 PRSATmpCnt = (int *) OFF_RSA_TMP_CNT(Pshm);
6881 /* initialize values in shared memory */
6883 for (i = 0; i < qn; i++)
6884 QShm[i].qs_entries = -1;
6890 if (LogLevel > (owner ? 8 : 11))
6892 sm_syslog(owner ? LOG_ERR : LOG_NOTICE, NOQID,
6893 "can't %s shared memory, key=%ld: %s",
6894 owner ? "initialize" : "attach to",
6895 (long) ShmKey, sm_errstring(save_errno));
6898 #endif /* SM_CONF_SHM */
6902 ** SETUP_QUEUES -- setup all queue groups
6905 ** owner -- owner of shared memory.
6912 ** attaches shared memory.
6913 #endif * SM_CONF_SHM *
6921 unsigned int hashval;
6923 char basedir[MAXPATHLEN];
6927 ** Determine basedir for all queue directories.
6928 ** All queue directories must be (first level) subdirectories
6929 ** of the basedir. The basedir is the QueueDir
6930 ** without wildcards, but with trailing /
6935 len = sm_strlcpy(basedir, QueueDir, sizeof basedir);
6937 /* Provide space for trailing '/' */
6938 if (len >= sizeof basedir - 1)
6940 syserr("QueueDirectory: path too long: %d, max %d",
6941 len, (int) sizeof basedir - 1);
6942 ExitStat = EX_CONFIG;
6946 if (basedir[len - 1] == '*')
6950 cp = SM_LAST_DIR_DELIM(basedir);
6953 syserr("QueueDirectory: can not wildcard relative path \"%s\"",
6956 sm_dprintf("setup_queues: \"%s\": Can not wildcard relative path.\n",
6958 ExitStat = EX_CONFIG;
6962 /* cut off wildcard pattern */
6966 else if (!SM_IS_DIR_DELIM(basedir[len - 1]))
6968 /* append trailing slash since it is a directory */
6970 basedir[++len] = '\0';
6973 /* len counts up to the last directory delimiter */
6974 SM_ASSERT(basedir[len - 1] == '/');
6976 if (chdir(basedir) < 0)
6978 int save_errno = errno;
6980 syserr("can not chdir(%s)", basedir);
6981 if (save_errno == EACCES)
6982 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
6983 "Program mode requires special privileges, e.g., root or TrustedUser.\n");
6985 sm_dprintf("setup_queues: \"%s\": %s\n",
6986 basedir, sm_errstring(errno));
6987 ExitStat = EX_CONFIG;
6991 hashval = hash_q(basedir, hashval);
6992 #endif /* SM_CONF_SHM */
6994 /* initialize for queue runs */
6997 for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
6998 Queue[i]->qg_nextrun = now;
7001 if (UseMSP && OpMode != MD_TEST)
7003 long sff = SFF_CREAT;
7005 if (stat(".", &st) < 0)
7007 syserr("can not stat(%s)", basedir);
7009 sm_dprintf("setup_queues: \"%s\": %s\n",
7010 basedir, sm_errstring(errno));
7011 ExitStat = EX_CONFIG;
7018 ** Check queue directory permissions.
7019 ** Can we write to a group writable queue directory?
7022 if (bitset(S_IWGRP, QueueFileMode) &&
7023 bitset(S_IWGRP, st.st_mode) &&
7024 safefile(" ", RunAsUid, RunAsGid, RunAsUserName, sff,
7025 QueueFileMode, NULL) != 0)
7027 syserr("can not write to queue directory %s (RunAsGid=%d, required=%d)",
7028 basedir, (int) RunAsGid, (int) st.st_gid);
7030 if (bitset(S_IWOTH|S_IXOTH, st.st_mode))
7032 #if _FFR_MSP_PARANOIA
7033 syserr("dangerous permissions=%o on queue directory %s",
7034 (int) st.st_mode, basedir);
7035 #else /* _FFR_MSP_PARANOIA */
7037 sm_syslog(LOG_ERR, NOQID,
7038 "dangerous permissions=%o on queue directory %s",
7039 (int) st.st_mode, basedir);
7040 #endif /* _FFR_MSP_PARANOIA */
7042 #if _FFR_MSP_PARANOIA
7044 syserr("can not use multiple queues for MSP");
7045 #endif /* _FFR_MSP_PARANOIA */
7048 /* initial number of queue directories */
7050 for (i = 0; i < NumQueue && Queue[i] != NULL; i++)
7051 qn = multiqueue_cache(basedir, len, Queue[i], qn, &hashval);
7054 init_shm(qn, owner, hashval);
7055 i = filesys_setup(owner || ShmId == SM_SHM_NO_ID);
7056 if (i == FSF_NOT_FOUND)
7059 ** We didn't get the right filesystem data
7060 ** This may happen if we don't have the right shared memory.
7061 ** So let's do this without shared memory.
7065 cleanup_shm(false); /* release shared memory */
7066 i = filesys_setup(false);
7068 syserr("filesys_setup failed twice, result=%d", i);
7069 else if (LogLevel > 8)
7070 sm_syslog(LOG_WARNING, NOQID,
7071 "shared memory does not contain expected data, ignored");
7073 #else /* SM_CONF_SHM */
7074 i = filesys_setup(true);
7075 #endif /* SM_CONF_SHM */
7077 ExitStat = EX_CONFIG;
7082 ** CLEANUP_SHM -- do some cleanup work for shared memory etc
7085 ** owner -- owner of shared memory?
7091 ** detaches shared memory.
7098 if (ShmId != SM_SHM_NO_ID)
7100 if (sm_shmstop(Pshm, ShmId, owner) < 0 && LogLevel > 8)
7101 sm_syslog(LOG_INFO, NOQID, "sm_shmstop failed=%s",
7102 sm_errstring(errno));
7104 ShmId = SM_SHM_NO_ID;
7108 #endif /* SM_CONF_SHM */
7111 ** CLEANUP_QUEUES -- do some cleanup work for queues
7127 ** SET_DEF_QUEUEVAL -- set default values for a queue group.
7130 ** qg -- queue group
7131 ** all -- set all values (true for default group)?
7137 ** sets default values for the queue group.
7141 set_def_queueval(qg, all)
7145 if (bitnset(QD_DEFINED, qg->qg_flags))
7148 qg->qg_qdir = QueueDir;
7149 #if _FFR_QUEUE_GROUP_SORTORDER
7150 qg->qg_sortorder = QueueSortOrder;
7151 #endif /* _FFR_QUEUE_GROUP_SORTORDER */
7152 qg->qg_maxqrun = all ? MaxRunnersPerQueue : -1;
7153 qg->qg_nice = NiceQueueRun;
7156 ** MAKEQUEUE -- define a new queue.
7159 ** line -- description of queue. This is in labeled fields.
7161 ** F -- the flags associated with the queue
7162 ** I -- the interval between running the queue
7163 ** J -- the maximum # of jobs in work list
7164 ** [M -- the maximum # of jobs in a queue run]
7165 ** N -- the niceness at which to run
7166 ** P -- the path to the queue
7167 ** S -- the queue sorting order
7168 ** R -- number of parallel queue runners
7169 ** r -- max recipients per envelope
7170 ** The first word is the canonical name of the queue.
7171 ** qdef -- this is a 'Q' definition from .cf
7177 ** enters the queue into the queue table.
7181 makequeue(line, qdef)
7186 register QUEUEGRP *qg;
7191 /* allocate a queue and set up defaults */
7192 qg = (QUEUEGRP *) xalloc(sizeof *qg);
7193 memset((char *) qg, '\0', sizeof *qg);
7195 if (line[0] == '\0')
7197 syserr("name required for queue");
7201 /* collect the queue name */
7203 *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p));
7208 qg->qg_name = newstr(line);
7210 /* set default values, can be overridden below */
7211 set_def_queueval(qg, false);
7213 /* now scan through and assign info from the fields */
7216 auto char *delimptr;
7218 while (*p != '\0' &&
7219 (*p == ',' || (isascii(*p) && isspace(*p))))
7222 /* p now points to field code */
7224 while (*p != '\0' && *p != '=' && *p != ',')
7228 syserr("queue %s: `=' expected", qg->qg_name);
7231 while (isascii(*p) && isspace(*p))
7234 /* p now points to the field body */
7235 p = munchstring(p, &delimptr, ',');
7237 /* install the field into the queue struct */
7240 case 'P': /* pathname */
7242 syserr("queue %s: empty path name",
7245 qg->qg_qdir = newstr(p);
7248 case 'F': /* flags */
7249 for (; *p != '\0'; p++)
7250 if (!(isascii(*p) && isspace(*p)))
7251 setbitn(*p, qg->qg_flags);
7255 ** Do we need two intervals here:
7256 ** One for persistent queue runners,
7257 ** one for "normal" queue runs?
7260 case 'I': /* interval between running the queue */
7261 qg->qg_queueintvl = convtime(p, 'm');
7264 case 'N': /* run niceness */
7265 qg->qg_nice = atoi(p);
7268 case 'R': /* maximum # of runners for the group */
7271 /* can't have more runners than allowed total */
7272 if (MaxQueueChildren > 0 && i > MaxQueueChildren)
7274 qg->qg_maxqrun = MaxQueueChildren;
7275 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7276 "Q=%s: R=%d exceeds MaxQueueChildren=%d, set to MaxQueueChildren\n",
7284 case 'J': /* maximum # of jobs in work list */
7285 qg->qg_maxlist = atoi(p);
7288 case 'r': /* max recipients per envelope */
7289 qg->qg_maxrcpt = atoi(p);
7292 #if _FFR_QUEUE_GROUP_SORTORDER
7293 case 'S': /* queue sorting order */
7296 case 'h': /* Host first */
7298 qg->qg_sortorder = QSO_BYHOST;
7301 case 'p': /* Priority order */
7303 qg->qg_sortorder = QSO_BYPRIORITY;
7306 case 't': /* Submission time */
7308 qg->qg_sortorder = QSO_BYTIME;
7311 case 'f': /* File name */
7313 qg->qg_sortorder = QSO_BYFILENAME;
7316 case 'm': /* Modification time */
7318 qg->qg_sortorder = QSO_BYMODTIME;
7321 case 'r': /* Random */
7323 qg->qg_sortorder = QSO_RANDOM;
7327 case 's': /* Shuffled host name */
7329 qg->qg_sortorder = QSO_BYSHUFFLE;
7331 # endif /* _FFR_RHS */
7333 case 'n': /* none */
7335 qg->qg_sortorder = QSO_NONE;
7339 syserr("Invalid queue sort order \"%s\"", p);
7342 #endif /* _FFR_QUEUE_GROUP_SORTORDER */
7345 syserr("Q%s: unknown queue equate %c=",
7346 qg->qg_name, fcode);
7354 if (qg->qg_nice != NiceQueueRun)
7356 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7357 "Q%s: Warning: N= set on system that doesn't support nice()\n",
7360 #endif /* !HASNICE */
7362 /* do some rationality checking */
7363 if (NumQueue >= MAXQUEUEGROUPS)
7365 syserr("too many queue groups defined (%d max)",
7370 if (qg->qg_qdir == NULL)
7372 if (QueueDir == NULL || *QueueDir == '\0')
7374 syserr("QueueDir must be defined before queue groups");
7377 qg->qg_qdir = newstr(QueueDir);
7380 if (qg->qg_maxqrun > 1 && !bitnset(QD_FORK, qg->qg_flags))
7382 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
7383 "Warning: Q=%s: R=%d: multiple queue runners specified\n\tbut flag '%c' is not set\n",
7384 qg->qg_name, qg->qg_maxqrun, QD_FORK);
7387 /* enter the queue into the symbol table */
7389 sm_syslog(LOG_INFO, NOQID,
7390 "Adding %s to stab, path: %s", qg->qg_name,
7392 s = stab(qg->qg_name, ST_QUEUE, ST_ENTER);
7393 if (s->s_quegrp != NULL)
7395 i = s->s_quegrp->qg_index;
7397 /* XXX what about the pointers inside this struct? */
7398 sm_free(s->s_quegrp); /* XXX */
7402 Queue[i] = s->s_quegrp = qg;
7405 /* set default value for max queue runners */
7406 if (qg->qg_maxqrun < 0)
7408 if (MaxRunnersPerQueue > 0)
7409 qg->qg_maxqrun = MaxRunnersPerQueue;
7414 setbitn(QD_DEFINED, qg->qg_flags);
7418 ** HASHFQN -- calculate a hash value for a fully qualified host name
7421 ** fqn -- an all lower-case host.domain string
7422 ** buckets -- the number of buckets (queue directories)
7425 ** a bucket number (signed integer)
7428 ** Contributed by Exactis.com, Inc.
7432 hashfqn(fqn, buckets)
7437 register int h = 0, hash, cnt;
7443 ** A variation on the gdb hash
7444 ** This is the best as of Feb 19, 1996 --bcx
7448 h = 0x238F13AF * strlen(p);
7449 for (cnt = 0; *p != 0; ++p, cnt++)
7451 h = (h + (*p << (cnt * 5 % 24))) & 0x7FFFFFFF;
7453 h = (1103515243 * h + 12345) & 0x7FFFFFFF;
7457 hash = (h % buckets);
7464 ** A structure for sorting Queue according to maxqrun without
7465 ** screwing up Queue itself.
7470 int sg_idx; /* original index */
7471 int sg_maxqrun; /* max queue runners */
7473 typedef struct sortqgrp SORTQGRP_T;
7474 static int cmpidx __P((const void *, const void *));
7481 /* The sort is highest to lowest, so the comparison is reversed */
7482 if (((SORTQGRP_T *)a)->sg_maxqrun < ((SORTQGRP_T *)b)->sg_maxqrun)
7484 else if (((SORTQGRP_T *)a)->sg_maxqrun > ((SORTQGRP_T *)b)->sg_maxqrun)
7491 ** MAKEWORKGROUP -- balance queue groups into work groups per MaxQueueChildren
7493 ** Take the now defined queue groups and assign them to work groups.
7494 ** This is done to balance out the number of concurrently active
7495 ** queue runners such that MaxQueueChildren is not exceeded. This may
7496 ** result in more than one queue group per work group. In such a case
7497 ** the number of running queue groups in that work group will have no
7498 ** more than the work group maximum number of runners (a "fair" portion
7499 ** of MaxQueueRunners). All queue groups within a work group will get a
7500 ** chance at running.
7509 ** Sets up WorkGrp structure.
7515 int i, j, total_runners, dir, h;
7516 SORTQGRP_T si[MAXQUEUEGROUPS + 1];
7519 if (NumQueue == 1 && strcmp(Queue[0]->qg_name, "mqueue") == 0)
7522 ** There is only the "mqueue" queue group (a default)
7523 ** containing all of the queues. We want to provide to
7524 ** this queue group the maximum allowable queue runners.
7525 ** To match older behavior (8.10/8.11) we'll try for
7526 ** 1 runner per queue capping it at MaxQueueChildren.
7527 ** So if there are N queues, then there will be N runners
7528 ** for the "mqueue" queue group (where N is kept less than
7529 ** MaxQueueChildren).
7533 WorkGrp[0].wg_numqgrp = 1;
7534 WorkGrp[0].wg_qgs = (QUEUEGRP **) xalloc(sizeof(QUEUEGRP *));
7535 WorkGrp[0].wg_qgs[0] = Queue[0];
7536 if (MaxQueueChildren > 0 &&
7537 Queue[0]->qg_numqueues > MaxQueueChildren)
7538 WorkGrp[0].wg_runners = MaxQueueChildren;
7540 WorkGrp[0].wg_runners = Queue[0]->qg_numqueues;
7542 Queue[0]->qg_wgrp = 0;
7544 /* can't have more runners than allowed total */
7545 if (MaxQueueChildren > 0 &&
7546 Queue[0]->qg_maxqrun > MaxQueueChildren)
7547 Queue[0]->qg_maxqrun = MaxQueueChildren;
7548 WorkGrp[0].wg_maxact = Queue[0]->qg_maxqrun;
7549 WorkGrp[0].wg_lowqintvl = Queue[0]->qg_queueintvl;
7553 for (i = 0; i < NumQueue; i++)
7555 si[i].sg_maxqrun = Queue[i]->qg_maxqrun;
7558 qsort(si, NumQueue, sizeof(si[0]), cmpidx);
7561 for (i = 0; i < NumQueue; i++)
7563 total_runners += si[i].sg_maxqrun;
7564 if (MaxQueueChildren <= 0 || total_runners <= MaxQueueChildren)
7570 if (NumWorkGroups < 1)
7571 NumWorkGroups = 1; /* gotta have one at least */
7572 else if (NumWorkGroups > MAXWORKGROUPS)
7573 NumWorkGroups = MAXWORKGROUPS; /* the limit */
7576 ** We now know the number of work groups to pack the queue groups
7577 ** into. The queue groups in 'Queue' are sorted from highest
7578 ** to lowest for the number of runners per queue group.
7579 ** We put the queue groups with the largest number of runners
7580 ** into work groups first. Then the smaller ones are fitted in
7581 ** where it looks best.
7586 for (i = 0; i < NumQueue; i++)
7588 /* a to-and-fro packing scheme, continue from last position */
7589 if (j >= NumWorkGroups)
7592 j = NumWorkGroups - 1;
7600 if (WorkGrp[j].wg_qgs == NULL)
7601 WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_malloc(sizeof(QUEUEGRP *) *
7602 (WorkGrp[j].wg_numqgrp + 1));
7604 WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_realloc(WorkGrp[j].wg_qgs,
7605 sizeof(QUEUEGRP *) *
7606 (WorkGrp[j].wg_numqgrp + 1));
7607 if (WorkGrp[j].wg_qgs == NULL)
7609 syserr("!cannot allocate memory for work queues, need %d bytes",
7610 (int) (sizeof(QUEUEGRP *) *
7611 (WorkGrp[j].wg_numqgrp + 1)));
7615 WorkGrp[j].wg_qgs[WorkGrp[j].wg_numqgrp] = Queue[h];
7616 WorkGrp[j].wg_numqgrp++;
7617 WorkGrp[j].wg_runners += Queue[h]->qg_maxqrun;
7618 Queue[h]->qg_wgrp = j;
7620 if (WorkGrp[j].wg_maxact == 0)
7622 /* can't have more runners than allowed total */
7623 if (MaxQueueChildren > 0 &&
7624 Queue[h]->qg_maxqrun > MaxQueueChildren)
7625 Queue[h]->qg_maxqrun = MaxQueueChildren;
7626 WorkGrp[j].wg_maxact = Queue[h]->qg_maxqrun;
7630 ** XXX: must wg_lowqintvl be the GCD?
7631 ** qg1: 2m, qg2: 3m, minimum: 2m, when do queue runs for
7635 /* keep track of the lowest interval for a persistent runner */
7636 if (Queue[h]->qg_queueintvl > 0 &&
7637 WorkGrp[j].wg_lowqintvl < Queue[h]->qg_queueintvl)
7638 WorkGrp[j].wg_lowqintvl = Queue[h]->qg_queueintvl;
7643 for (i = 0; i < NumWorkGroups; i++)
7645 sm_dprintf("Workgroup[%d]=", i);
7646 for (j = 0; j < WorkGrp[i].wg_numqgrp; j++)
7649 WorkGrp[i].wg_qgs[j]->qg_name);
7657 ** DUP_DF -- duplicate envelope data file
7659 ** Copy the data file from the 'old' envelope to the 'new' envelope
7660 ** in the most efficient way possible.
7662 ** Create a hard link from the 'old' data file to the 'new' data file.
7663 ** If the old and new queue directories are on different file systems,
7664 ** then the new data file link is created in the old queue directory,
7665 ** and the new queue file will contain a 'd' record pointing to the
7666 ** directory containing the new data file.
7669 ** old -- old envelope.
7670 ** new -- new envelope.
7673 ** Returns true on success, false on failure.
7676 ** On success, the new data file is created.
7677 ** On fatal failure, EF_FATALERRS is set in old->e_flags.
7680 static bool dup_df __P((ENVELOPE *, ENVELOPE *));
7688 char opath[MAXPATHLEN];
7689 char npath[MAXPATHLEN];
7691 if (!bitset(EF_HAS_DF, old->e_flags))
7694 ** this can happen if: SuperSafe != True
7695 ** and a bounce mail is sent that is split.
7698 queueup(old, false, true);
7700 SM_REQUIRE(ISVALIDQGRP(old->e_qgrp) && ISVALIDQDIR(old->e_qdir));
7701 SM_REQUIRE(ISVALIDQGRP(new->e_qgrp) && ISVALIDQDIR(new->e_qdir));
7703 (void) sm_strlcpy(opath, queuename(old, DATAFL_LETTER), sizeof opath);
7704 (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof npath);
7706 if (old->e_dfp != NULL)
7708 r = sm_io_setinfo(old->e_dfp, SM_BF_COMMIT, NULL);
7709 if (r < 0 && errno != EINVAL)
7711 syserr("@can't commit %s", opath);
7712 old->e_flags |= EF_FATALERRS;
7718 ** Attempt to create a hard link, if we think both old and new
7719 ** are on the same file system, otherwise copy the file.
7721 ** Don't waste time attempting a hard link unless old and new
7722 ** are on the same file system.
7725 ofs = Queue[old->e_qgrp]->qg_qpaths[old->e_qdir].qp_fsysidx;
7726 nfs = Queue[new->e_qgrp]->qg_qpaths[new->e_qdir].qp_fsysidx;
7727 if (FILE_SYS_DEV(ofs) == FILE_SYS_DEV(nfs))
7729 if (link(opath, npath) == 0)
7731 new->e_flags |= EF_HAS_DF;
7732 SYNC_DIR(npath, true);
7739 ** Can't link across queue directories, so try to create a hard
7740 ** link in the same queue directory as the old df file.
7741 ** The qf file will refer to the new df file using a 'd' record.
7744 new->e_dfqgrp = old->e_dfqgrp;
7745 new->e_dfqdir = old->e_dfqdir;
7746 (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof npath);
7747 if (link(opath, npath) == 0)
7749 new->e_flags |= EF_HAS_DF;
7750 SYNC_DIR(npath, true);
7756 sm_syslog(LOG_ERR, old->e_id,
7757 "dup_df: can't link %s to %s, error=%s, envelope splitting failed",
7758 opath, npath, sm_errstring(errno));
7763 ** SPLIT_ENV -- Allocate a new envelope based on a given envelope.
7767 ** sendqueue -- sendqueue for new envelope.
7768 ** qgrp -- index of queue group.
7769 ** qdir -- queue directory.
7776 static ENVELOPE *split_env __P((ENVELOPE *, ADDRESS *, int, int));
7779 split_env(e, sendqueue, qgrp, qdir)
7787 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, sizeof *ee);
7788 STRUCTCOPY(*e, *ee);
7789 ee->e_message = NULL; /* XXX use original message? */
7792 ee->e_sendqueue = sendqueue;
7793 ee->e_flags &= ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS
7794 |EF_SENDRECEIPT|EF_RET_PARAM|EF_HAS_DF);
7795 ee->e_flags |= EF_NORECEIPT; /* XXX really? */
7796 ee->e_from.q_state = QS_SENDER;
7798 ee->e_lockfp = NULL;
7799 if (e->e_xfp != NULL)
7800 ee->e_xfp = sm_io_dup(e->e_xfp);
7802 /* failed to dup e->e_xfp, start a new transcript */
7803 if (ee->e_xfp == NULL)
7806 ee->e_qgrp = ee->e_dfqgrp = qgrp;
7807 ee->e_qdir = ee->e_dfqdir = qdir;
7808 ee->e_errormode = EM_MAIL;
7809 ee->e_statmsg = NULL;
7810 if (e->e_quarmsg != NULL)
7811 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool,
7815 ** XXX Not sure if this copying is necessary.
7816 ** sendall() does this copying, but I (dm) don't know if that is
7817 ** because of the storage management discipline we were using
7818 ** before rpools were introduced, or if it is because these lists
7819 ** can be modified later.
7822 ee->e_header = copyheader(e->e_header, ee->e_rpool);
7823 ee->e_errorqueue = copyqueue(e->e_errorqueue, ee->e_rpool);
7828 /* return values from split functions, check also below! */
7829 #define SM_SPLIT_FAIL (0)
7830 #define SM_SPLIT_NONE (1)
7831 #define SM_SPLIT_NEW(n) (1 + (n))
7834 ** SPLIT_ACROSS_QUEUE_GROUPS
7836 ** This function splits an envelope across multiple queue groups
7837 ** based on the queue group of each recipient.
7843 ** SM_SPLIT_FAIL on failure
7844 ** SM_SPLIT_NONE if no splitting occurred,
7845 ** or 1 + the number of additional envelopes created.
7848 ** On success, e->e_sibling points to a list of zero or more
7849 ** additional envelopes, and the associated data files exist
7850 ** on disk. But the queue files are not created.
7852 ** On failure, e->e_sibling is not changed.
7853 ** The order of recipients in e->e_sendqueue is permuted.
7854 ** Abandoned data files for additional envelopes that failed
7855 ** to be created may exist on disk.
7858 static int q_qgrp_compare __P((const void *, const void *));
7859 static int e_filesys_compare __P((const void *, const void *));
7862 q_qgrp_compare(p1, p2)
7866 ADDRESS **pq1 = (ADDRESS **) p1;
7867 ADDRESS **pq2 = (ADDRESS **) p2;
7869 return (*pq1)->q_qgrp - (*pq2)->q_qgrp;
7873 e_filesys_compare(p1, p2)
7877 ENVELOPE **pe1 = (ENVELOPE **) p1;
7878 ENVELOPE **pe2 = (ENVELOPE **) p2;
7881 fs1 = Queue[(*pe1)->e_qgrp]->qg_qpaths[(*pe1)->e_qdir].qp_fsysidx;
7882 fs2 = Queue[(*pe2)->e_qgrp]->qg_qpaths[(*pe2)->e_qdir].qp_fsysidx;
7883 if (FILE_SYS_DEV(fs1) < FILE_SYS_DEV(fs2))
7885 if (FILE_SYS_DEV(fs1) > FILE_SYS_DEV(fs2))
7891 split_across_queue_groups(e)
7894 int naddrs, nsplits, i;
7897 ADDRESS *q, **addrs;
7899 ENVELOPE *splits[MAXQUEUEGROUPS];
7900 char pvpbuf[PSBUFSIZE];
7902 SM_REQUIRE(ISVALIDQGRP(e->e_qgrp));
7904 /* Count addresses and assign queue groups. */
7907 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
7909 if (QS_IS_DEAD(q->q_state))
7913 /* bad addresses and those already sent stay put */
7914 if (QS_IS_BADADDR(q->q_state) ||
7915 QS_IS_SENT(q->q_state))
7916 q->q_qgrp = e->e_qgrp;
7917 else if (!ISVALIDQGRP(q->q_qgrp))
7919 /* call ruleset which should return a queue group */
7920 i = rscap(RS_QUEUEGROUP, q->q_user, NULL, e, &pvp,
7921 pvpbuf, sizeof(pvpbuf));
7923 pvp != NULL && pvp[0] != NULL &&
7924 (pvp[0][0] & 0377) == CANONNET &&
7925 pvp[1] != NULL && pvp[1][0] != '\0')
7927 i = name2qid(pvp[1]);
7933 sm_syslog(LOG_INFO, NOQID,
7934 "queue group name %s -> %d",
7938 else if (LogLevel > 10)
7939 sm_syslog(LOG_INFO, NOQID,
7940 "can't find queue group name %s, selection ignored",
7943 if (q->q_mailer != NULL &&
7944 ISVALIDQGRP(q->q_mailer->m_qgrp))
7947 q->q_qgrp = q->q_mailer->m_qgrp;
7949 else if (ISVALIDQGRP(e->e_qgrp))
7950 q->q_qgrp = e->e_qgrp;
7956 /* only one address? nothing to split. */
7957 if (naddrs <= 1 && !changed)
7958 return SM_SPLIT_NONE;
7960 /* sort the addresses by queue group */
7961 addrs = sm_rpool_malloc_x(e->e_rpool, naddrs * sizeof(ADDRESS *));
7962 for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next)
7964 if (QS_IS_DEAD(q->q_state))
7968 qsort(addrs, naddrs, sizeof(ADDRESS *), q_qgrp_compare);
7970 /* split into multiple envelopes, by queue group */
7973 e->e_sendqueue = NULL;
7974 for (i = 0; i < naddrs; ++i)
7976 if (i == naddrs - 1 || addrs[i]->q_qgrp != addrs[i + 1]->q_qgrp)
7977 addrs[i]->q_next = NULL;
7979 addrs[i]->q_next = addrs[i + 1];
7981 /* same queue group as original envelope? */
7982 if (addrs[i]->q_qgrp == e->e_qgrp)
7984 if (e->e_sendqueue == NULL)
7985 e->e_sendqueue = addrs[i];
7989 /* different queue group than original envelope */
7990 if (es == NULL || addrs[i]->q_qgrp != es->e_qgrp)
7992 ee = split_env(e, addrs[i], addrs[i]->q_qgrp, NOQDIR);
7994 splits[nsplits++] = ee;
7998 /* no splits? return right now. */
8000 return SM_SPLIT_NONE;
8002 /* assign a queue directory to each additional envelope */
8003 for (i = 0; i < nsplits; ++i)
8007 es->e_qdir = pickqdir(Queue[es->e_qgrp], es->e_msgsize, es);
8009 if (!setnewqueue(es))
8013 /* sort the additional envelopes by queue file system */
8014 qsort(splits, nsplits, sizeof(ENVELOPE *), e_filesys_compare);
8016 /* create data files for each additional envelope */
8017 if (!dup_df(e, splits[0]))
8022 for (i = 1; i < nsplits; ++i)
8024 /* copy or link to the previous data file */
8025 if (!dup_df(splits[i - 1], splits[i]))
8029 /* success: prepend the new envelopes to the e->e_sibling list */
8030 for (i = 0; i < nsplits; ++i)
8033 es->e_sibling = e->e_sibling;
8036 return SM_SPLIT_NEW(nsplits);
8038 /* failure: clean up */
8044 for (j = 0; j < i; j++)
8045 (void) unlink(queuename(splits[j], DATAFL_LETTER));
8047 e->e_sendqueue = addrs[0];
8048 for (i = 0; i < naddrs - 1; ++i)
8049 addrs[i]->q_next = addrs[i + 1];
8050 addrs[naddrs - 1]->q_next = NULL;
8051 return SM_SPLIT_FAIL;
8055 ** SPLIT_WITHIN_QUEUE
8057 ** Split an envelope with multiple recipients into several
8058 ** envelopes within the same queue directory, if the number of
8059 ** recipients exceeds the limit for the queue group.
8065 ** SM_SPLIT_FAIL on failure
8066 ** SM_SPLIT_NONE if no splitting occurred,
8067 ** or 1 + the number of additional envelopes created.
8070 #define SPLIT_LOG_LEVEL 8
8072 static int split_within_queue __P((ENVELOPE *));
8075 split_within_queue(e)
8078 int maxrcpt, nrcpt, ndead, nsplit, i;
8081 ADDRESS *q, **addrs;
8082 ENVELOPE *ee, *firstsibling;
8084 if (!ISVALIDQGRP(e->e_qgrp) || bitset(EF_SPLIT, e->e_flags))
8085 return SM_SPLIT_NONE;
8087 /* don't bother if there is no recipient limit */
8088 maxrcpt = Queue[e->e_qgrp]->qg_maxrcpt;
8090 return SM_SPLIT_NONE;
8092 /* count recipients */
8094 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
8096 if (QS_IS_DEAD(q->q_state))
8100 if (nrcpt <= maxrcpt)
8101 return SM_SPLIT_NONE;
8104 ** Preserve the recipient list
8105 ** so that we can restore it in case of error.
8106 ** (But we discard dead addresses.)
8109 addrs = sm_rpool_malloc_x(e->e_rpool, nrcpt * sizeof(ADDRESS *));
8110 for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next)
8112 if (QS_IS_DEAD(q->q_state))
8118 ** Partition the recipient list so that bad and sent addresses
8119 ** come first. These will go with the original envelope, and
8120 ** do not count towards the maxrcpt limit.
8121 ** addrs[] does not contain QS_IS_DEAD() addresses.
8125 for (i = 0; i < nrcpt; ++i)
8127 if (QS_IS_BADADDR(addrs[i]->q_state) ||
8128 QS_IS_SENT(addrs[i]->q_state) ||
8129 QS_IS_DEAD(addrs[i]->q_state)) /* for paranoia's sake */
8133 ADDRESS *tmp = addrs[i];
8135 addrs[i] = addrs[ndead];
8142 /* Check if no splitting required. */
8143 if (nrcpt - ndead <= maxrcpt)
8144 return SM_SPLIT_NONE;
8147 for (i = 0; i < nrcpt - 1; ++i)
8148 addrs[i]->q_next = addrs[i + 1];
8149 addrs[nrcpt - 1]->q_next = NULL;
8150 e->e_sendqueue = addrs[0];
8152 /* prepare buffer for logging */
8153 if (LogLevel > SPLIT_LOG_LEVEL)
8156 lsplits = sm_malloc(l);
8157 if (lsplits != NULL)
8163 /* get rid of stupid compiler warnings */
8168 /* split the envelope */
8169 firstsibling = e->e_sibling;
8170 i = maxrcpt + ndead;
8174 addrs[i - 1]->q_next = NULL;
8175 ee = split_env(e, addrs[i], e->e_qgrp, e->e_qdir);
8182 (void) unlink(queuename(ee, DATAFL_LETTER));
8186 /* Error. Restore e's sibling & recipient lists. */
8187 e->e_sibling = firstsibling;
8188 for (i = 0; i < nrcpt - 1; ++i)
8189 addrs[i]->q_next = addrs[i + 1];
8190 if (lsplits != NULL)
8192 return SM_SPLIT_FAIL;
8195 /* prepend the new envelope to e->e_sibling */
8196 ee->e_sibling = e->e_sibling;
8199 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8201 if (j >= l - strlen(ee->e_id) - 3)
8206 p = sm_realloc(lsplits, l);
8209 /* let's try to get this done */
8216 if (lsplits != NULL)
8219 j += sm_strlcat(lsplits + j,
8223 j += sm_strlcat2(lsplits + j,
8230 if (nrcpt - i <= maxrcpt)
8234 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8238 sm_syslog(LOG_NOTICE, e->e_id,
8239 "split: maxrcpts=%d, rcpts=%d, count=%d, id%s=%s",
8240 maxrcpt, nrcpt - ndead, nsplit,
8241 nsplit > 1 ? "s" : "", lsplits);
8245 return SM_SPLIT_NEW(nsplit);
8248 ** SPLIT_BY_RECIPIENT
8250 ** Split an envelope with multiple recipients into multiple
8251 ** envelopes as required by the sendmail configuration.
8257 ** Returns true on success, false on failure.
8260 ** see split_across_queue_groups(), split_within_queue(e)
8264 split_by_recipient(e)
8267 int split, n, i, j, l;
8269 ENVELOPE *ee, *next, *firstsibling;
8271 if (OpMode == SM_VERIFY || !ISVALIDQGRP(e->e_qgrp) ||
8272 bitset(EF_SPLIT, e->e_flags))
8274 n = split_across_queue_groups(e);
8275 if (n == SM_SPLIT_FAIL)
8277 firstsibling = ee = e->e_sibling;
8278 if (n > 1 && LogLevel > SPLIT_LOG_LEVEL)
8281 lsplits = sm_malloc(l);
8282 if (lsplits != NULL)
8288 /* get rid of stupid compiler warnings */
8292 for (i = 1; i < n; ++i)
8294 next = ee->e_sibling;
8295 if (split_within_queue(ee) == SM_SPLIT_FAIL)
8297 e->e_sibling = firstsibling;
8300 ee->e_flags |= EF_SPLIT;
8301 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL)
8303 if (j >= l - strlen(ee->e_id) - 3)
8308 p = sm_realloc(lsplits, l);
8311 /* let's try to get this done */
8318 if (lsplits != NULL)
8321 j += sm_strlcat(lsplits + j,
8324 j += sm_strlcat2(lsplits + j, "; ",
8331 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL && n > 1)
8333 sm_syslog(LOG_NOTICE, e->e_id, "split: count=%d, id%s=%s",
8334 n - 1, n > 2 ? "s" : "", lsplits);
8337 split = split_within_queue(e) != SM_SPLIT_FAIL;
8339 e->e_flags |= EF_SPLIT;
8344 ** QUARANTINE_QUEUE_ITEM -- {un,}quarantine a single envelope
8346 ** Add/remove quarantine reason and requeue appropriately.
8349 ** qgrp -- queue group for the item
8350 ** qdir -- queue directory in the given queue group
8351 ** e -- envelope information for the item
8352 ** reason -- quarantine reason, NULL means unquarantine.
8355 ** true if item changed, false otherwise
8358 ** Changes quarantine tag in queue file and renames it.
8362 quarantine_queue_item(qgrp, qdir, e, reason)
8369 bool failing = false;
8370 bool foundq = false;
8371 bool finished = false;
8377 MODE_T oldumask = 0;
8378 SM_FILE_T *oldqfp, *tempqfp;
8380 char oldqf[MAXPATHLEN];
8381 char tempqf[MAXPATHLEN];
8382 char newqf[MAXPATHLEN];
8385 oldtype = queue_letter(e, ANYQFL_LETTER);
8386 (void) sm_strlcpy(oldqf, queuename(e, ANYQFL_LETTER), sizeof oldqf);
8387 (void) sm_strlcpy(tempqf, queuename(e, NEWQFL_LETTER), sizeof tempqf);
8390 ** Instead of duplicating all the open
8391 ** and lock code here, tell readqf() to
8392 ** do that work and return the open
8393 ** file pointer in e_lockfp. Note that
8394 ** we must release the locks properly when
8398 if (!readqf(e, true))
8400 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8401 "Skipping %s\n", qid_printname(e));
8404 oldqfp = e->e_lockfp;
8406 /* open the new queue file */
8407 flags = O_CREAT|O_WRONLY|O_EXCL;
8408 if (bitset(S_IWGRP, QueueFileMode))
8409 oldumask = umask(002);
8410 fd = open(tempqf, flags, QueueFileMode);
8411 if (bitset(S_IWGRP, QueueFileMode))
8412 (void) umask(oldumask);
8418 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8419 "Skipping %s: Could not open %s: %s\n",
8420 qid_printname(e), tempqf,
8421 sm_errstring(save_errno));
8422 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8425 if (!lockfile(fd, tempqf, NULL, LOCK_EX|LOCK_NB))
8427 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8428 "Skipping %s: Could not lock %s\n",
8429 qid_printname(e), tempqf);
8431 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8435 tempqfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd,
8436 SM_IO_WRONLY_B, NULL);
8437 if (tempqfp == NULL)
8439 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8440 "Skipping %s: Could not lock %s\n",
8441 qid_printname(e), tempqf);
8443 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8447 /* Copy the data over, changing the quarantine reason */
8448 while ((bp = fgetfolded(buf, sizeof buf, oldqfp)) != NULL)
8451 sm_dprintf("+++++ %s\n", bp);
8454 case 'q': /* quarantine reason */
8460 (void) sm_io_fprintf(smioout,
8462 "%s: Removed quarantine of \"%s\"\n",
8465 sm_syslog(LOG_INFO, e->e_id, "unquarantine");
8469 else if (strcmp(reason, &bp[1]) == 0)
8473 (void) sm_io_fprintf(smioout,
8475 "%s: Already quarantined with \"%s\"\n",
8478 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8485 (void) sm_io_fprintf(smioout,
8487 "%s: Quarantine changed from \"%s\" to \"%s\"\n",
8491 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8493 sm_syslog(LOG_INFO, e->e_id, "quarantine=%s",
8501 ** If we are quarantining an unquarantined item,
8502 ** need to put in a new 'q' line before it's
8506 if (!foundq && reason != NULL)
8510 (void) sm_io_fprintf(smioout,
8512 "%s: Quarantined with \"%s\"\n",
8515 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8517 sm_syslog(LOG_INFO, e->e_id, "quarantine=%s",
8523 /* Copy the line to the new file */
8524 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8533 /* Copy the line to the new file */
8534 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT,
8540 /* Make sure we read the whole old file */
8541 errno = sm_io_error(tempqfp);
8542 if (errno != 0 && errno != SM_IO_EOF)
8545 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8546 "Skipping %s: Error reading %s: %s\n",
8547 qid_printname(e), oldqf,
8548 sm_errstring(save_errno));
8552 if (!failing && !finished)
8554 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8555 "Skipping %s: Incomplete file: %s\n",
8556 qid_printname(e), oldqf);
8560 /* Check if we actually changed anything or we can just bail now */
8563 /* pretend we failed, even though we technically didn't */
8567 /* Make sure we wrote things out safely */
8569 (sm_io_flush(tempqfp, SM_TIME_DEFAULT) != 0 ||
8570 ((SuperSafe == SAFE_REALLY ||
8571 SuperSafe == SAFE_REALLY_POSTMILTER ||
8572 SuperSafe == SAFE_INTERACTIVE) &&
8573 fsync(sm_io_getinfo(tempqfp, SM_IO_WHAT_FD, NULL)) < 0) ||
8574 ((errno = sm_io_error(tempqfp)) != 0)))
8577 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8578 "Skipping %s: Error writing %s: %s\n",
8579 qid_printname(e), tempqf,
8580 sm_errstring(save_errno));
8585 /* Figure out the new filename */
8586 newtype = (reason == NULL ? NORMQF_LETTER : QUARQF_LETTER);
8587 if (oldtype == newtype)
8589 /* going to rename tempqf to oldqf */
8590 (void) sm_strlcpy(newqf, oldqf, sizeof newqf);
8594 /* going to rename tempqf to new name based on newtype */
8595 (void) sm_strlcpy(newqf, queuename(e, newtype), sizeof newqf);
8600 /* rename tempqf to newqf */
8602 rename(tempqf, newqf) < 0)
8603 save_errno = (errno == 0) ? EINVAL : errno;
8605 /* Check rename() success */
8606 if (!failing && save_errno != 0)
8608 sm_syslog(LOG_DEBUG, e->e_id,
8609 "quarantine_queue_item: rename(%s, %s): %s",
8610 tempqf, newqf, sm_errstring(save_errno));
8612 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8613 "Error renaming %s to %s: %s\n",
8615 sm_errstring(save_errno));
8616 if (oldtype == newtype)
8619 ** Bail here since we don't know the state of
8620 ** the filesystem and may need to keep tempqf
8621 ** for the user to rescue us.
8626 syserr("!452 Error renaming control file %s", tempqf);
8631 /* remove new file (if rename() half completed) */
8632 if (xunlink(newqf) < 0)
8635 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8636 "Error removing %s: %s\n",
8638 sm_errstring(save_errno));
8641 /* tempqf removed below */
8647 /* If changing file types, need to remove old type */
8648 if (!failing && oldtype != newtype)
8650 if (xunlink(oldqf) < 0)
8653 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8654 "Error removing %s: %s\n",
8655 oldqf, sm_errstring(save_errno));
8659 /* see if anything above failed */
8662 /* Something failed: remove new file, old file still there */
8663 (void) xunlink(tempqf);
8667 ** fsync() after file operations to make sure metadata is
8668 ** written to disk on filesystems in which renames are
8669 ** not guaranteed. It's ok if they fail, mail won't be lost.
8672 if (SuperSafe != SAFE_NO)
8674 /* for soft-updates */
8675 (void) fsync(sm_io_getinfo(tempqfp,
8676 SM_IO_WHAT_FD, NULL));
8680 /* for soft-updates */
8681 (void) fsync(sm_io_getinfo(oldqfp,
8682 SM_IO_WHAT_FD, NULL));
8685 /* for other odd filesystems */
8686 SYNC_DIR(tempqf, false);
8691 if (tempqfp != NULL)
8692 (void) sm_io_close(tempqfp, SM_TIME_DEFAULT);
8694 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT);
8701 ** QUARANTINE_QUEUE -- {un,}quarantine matching items in the queue
8703 ** Read all matching queue items, add/remove quarantine
8704 ** reason, and requeue appropriately.
8707 ** reason -- quarantine reason, "." means unquarantine.
8708 ** qgrplimit -- limit to single queue group unless NOQGRP
8714 ** Lots of changes to the queue.
8718 quarantine_queue(reason, qgrplimit)
8725 /* Convert internal representation of unquarantine */
8726 if (reason != NULL && reason[0] == '.' && reason[1] == '\0')
8732 reason = newstr(denlstring(reason, true, true));
8735 for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++)
8739 if (qgrplimit != NOQGRP && qgrplimit != qgrp)
8742 for (qdir = 0; qdir < Queue[qgrp]->qg_numqueues; qdir++)
8750 nrequests = gatherq(qgrp, qdir, true, NULL, NULL);
8752 /* first see if there is anything */
8757 (void) sm_io_fprintf(smioout,
8758 SM_TIME_DEFAULT, "%s: no matches\n",
8759 qid_printqueue(qgrp, qdir));
8766 (void) sm_io_fprintf(smioout,
8767 SM_TIME_DEFAULT, "Processing %s:\n",
8768 qid_printqueue(qgrp, qdir));
8771 for (i = 0; i < WorkListCount; i++)
8778 /* setup envelope */
8779 clearenvelope(&e, true, sm_rpool_new_x(NULL));
8780 e.e_id = WorkList[i].w_name + 2;
8786 sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8787 "Would do %s\n", e.e_id);
8790 else if (quarantine_queue_item(qgrp, qdir,
8795 sm_rpool_free(e.e_rpool);
8798 if (WorkList != NULL)
8799 sm_free(WorkList); /* XXX */
8808 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8811 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
8814 changed == 1 ? "" : "s");