queue.c revision 3ee0e49223f178da635734759b9167f924321ff0
/*
* Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers.
* All rights reserved.
* Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include <sendmail.h>
#include <dirent.h>
# define RELEASE_QUEUE (void) 0
# define SM_OPEN_EXLOCK 1
# else /* HASFLOCK && defined(O_EXLOCK) */
# endif /* HASFLOCK && defined(O_EXLOCK) */
#ifndef SM_OPEN_EXLOCK
# define SM_OPEN_EXLOCK 0
#endif /* ! SM_OPEN_EXLOCK */
/*
** Historical notes:
** QF_VERSION == 4 was sendmail 8.10/8.11 without _FFR_QUEUEDELAY
** QF_VERSION == 5 was sendmail 8.10/8.11 with _FFR_QUEUEDELAY
** QF_VERSION == 6 was sendmail 8.12 without _FFR_QUEUEDELAY
** QF_VERSION == 7 was sendmail 8.12 with _FFR_QUEUEDELAY
** QF_VERSION == 8 is sendmail 8.13
*/
/* Naming convention: qgrp: index of queue group, qg: QUEUEGROUP */
/*
** Work queue.
*/
struct work
{
char *w_name; /* name of control file */
char *w_host; /* name of recipient host */
bool w_lock; /* is message locked? */
bool w_tooyoung; /* is it too young to run? */
long w_pri; /* priority of message, see below */
int w_qgrp; /* queue group located in */
int w_qdir; /* queue directory located in */
};
static int NumWorkGroups; /* number of work groups */
static time_t Current_LA_time = 0;
/* Get new load average every 30 seconds. */
#define GET_NEW_LA_TIME 30
do \
{ \
{ \
sm_getla(); \
Current_LA_time = now; \
} \
} while (0)
/*
** DoQueueRun indicates that a queue run is needed.
** Notice: DoQueueRun is modified in a signal handler!
*/
static bool volatile DoQueueRun; /* non-interrupt time queue run needed */
/*
** Work group definition structure.
** Each work group contains one or more queue groups. This is done
** to manage the number of queue group runners active at the same time
** to be within the constraints of MaxQueueChildren (if it is set).
** The number of queue groups that can be run on the next work run
** is kept track of. The queue groups are run in a round robin.
*/
struct workgrp
{
int wg_numqgrp; /* number of queue groups in work grp */
int wg_runners; /* total runners */
int wg_curqgrp; /* current queue group */
int wg_maxact; /* max # of active runners */
int wg_restart; /* needs restarting? */
int wg_restartcnt; /* count of times restarted */
};
#if SM_HEAP_CHECK
"@(#)$Debug: leak_q - trace memory leaks during queue processing $");
#endif /* SM_HEAP_CHECK */
/*
** We use EmptyString instead of "" to avoid
** 'zero-length format string' warnings from gcc
*/
static const char EmptyString[] = "";
static void grow_wlist __P((int, int));
static void restart_work_group __P((int));
static void schedule_queue_runs __P((bool, int, bool));
#if _FFR_RHS
static int sm_strshufflecmp __P((char *, char *));
static void init_shuffle_alphabet __P(());
#endif /* _FFR_RHS */
static int workcmpf0();
static int workcmpf1();
static int workcmpf2();
static int workcmpf3();
static int workcmpf4();
static int workcmpf5();
static int workcmpf6();
#if _FFR_RHS
static int workcmpf7();
#endif /* _FFR_RHS */
#if RANDOMSHIFT
#else /* RANDOMSHIFT */
# define get_rand_mod(m) (get_random() % (m))
#endif /* RANDOMSHIFT */
/*
** File system definition.
** Used to keep track of how much free space is available
** on a file system in which one or more queue directories reside.
*/
typedef struct filesys_shared FILESYS;
struct filesys_shared
{
long fs_avail; /* number of free blocks available */
long fs_blksize; /* block size, in bytes */
};
/* probably kept in shared memory */
#if SM_CONF_SHM
/*
** Shared memory data
**
** Current layout:
** size -- size of shared memory segment
** pid -- pid of owner, should be a unique id to avoid misinterpretations
** by other processes.
** tag -- should be a unique id to avoid misinterpretations by others.
** idea: hash over configuration data that will be stored here.
** NumFileSys -- number of file systems.
** FileSys -- (arrary of) structure for used file systems.
** RSATmpCnt -- counter for number of uses of ephemeral RSA key.
** QShm -- (array of) structure for information about queue directories.
*/
/*
** Queue data in shared memory
*/
typedef struct queue_shared QUEUE_SHM_T;
struct queue_shared
{
int qs_entries; /* number of entries */
/* XXX more to follow? */
};
static void *Pshm; /* pointer to shared memory */
# define SHM_OFF_PID(p) (((char *) (p)) + sizeof(int))
# define SHM_OFF_TAG(p) (((char *) (p)) + sizeof(pid_t) + sizeof(int))
/* how to access FileSys */
# define FILE_SYS(i) (PtrFileSys[i])
/* first entry is a tag, for now just the size */
# define OFF_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD)
/* offset for PNumFileSys */
/* offset for PRSATmpCnt */
int *PRSATmpCnt;
/* offset for queue_shm */
/* basic size of shared memory segment */
/*
** HASH_Q -- simple hash function
**
** Parameters:
** p -- string to hash.
** h -- hash start value (from previous run).
**
** Returns:
** hash value.
*/
static unsigned int
hash_q(p, h)
char *p;
unsigned int h;
{
int c, d;
while (*p != '\0')
{
d = *p++;
c = d;
c ^= c<<6;
h += (c<<11) ^ (c>>1);
h ^= (d<<14) + (d<<7) + (d<<4) + d;
}
return h;
}
#else /* SM_CONF_SHM */
#endif /* SM_CONF_SHM */
/* access to the various components of file system data */
#define FILE_SYS_NAME(i) FSPath[i]
/*
** Current qf file field assignments:
**
** A AUTH= parameter
** B body type
** C controlling user
** D data file name
** d data file directory name (added in 8.12)
** E error recipient
** F flag bits
** G free (was: queue delay algorithm if _FFR_QUEUEDELAY)
** H header
** I data file's inode number
** K time of last delivery attempt
** L Solaris Content-Length: header (obsolete)
** M message
** N number of delivery attempts
** P message priority
** q quarantine reason
** Q original recipient (ORCPT=)
** r final recipient (Final-Recipient: DSN field)
** R recipient
** S sender
** T init time
** V queue file version
** X free (was: character set if _FFR_SAVE_CHARSET)
** Y free (was: current delay if _FFR_QUEUEDELAY)
** Z original envelope id from ESMTP
** ! deliver by (added in 8.12)
** $ define macro
** . terminate file
*/
/*
** QUEUEUP -- queue a message up for future transmission.
**
** Parameters:
** e -- the envelope to queue up.
** announce -- if true, tell when you are queueing up.
** msync -- if true, then fsync() if SuperSafe interactive mode.
**
** Returns:
** none.
**
** Side Effects:
** The current request is saved in a control file.
** The queue file is left locked.
*/
void
register ENVELOPE *e;
bool announce;
bool msync;
{
register HDR *h;
register ADDRESS *q;
int tfd = -1;
int i;
bool newid;
register char *p;
char qf[MAXPATHLEN];
char tf[MAXPATHLEN];
char df[MAXPATHLEN];
/*
** Create control file.
*/
#define OPEN_TF do \
{ \
\
} while (0)
{
/*
** open qf file directly: this will give an error if the file
** already exists and hence prevent problems if a queue-id
** is reused (e.g., because the clock is set back).
*/
if (tfd < 0 ||
#if !SM_OPEN_EXLOCK
#endif /* !SM_OPEN_EXLOCK */
(void *) &tfd, SM_IO_WRONLY,
{
int save_errno = errno;
printopenfds(true);
errno = save_errno;
syserr("!queueup: cannot create queue file %s, euid=%d, fd=%d, fp=%p",
/* NOTREACHED */
}
}
/* if newid, write the queue file directly (instead of temp file) */
if (!newid)
{
/* get a locked tf file */
for (i = 0; i < 128; i++)
{
if (tfd < 0)
{
if (tfd < 0)
{
break;
if (LogLevel > 0 && (i % 32) == 0)
"queueup: cannot create %s, uid=%d: %s",
}
#if SM_OPEN_EXLOCK
else
break;
#endif /* SM_OPEN_EXLOCK */
}
if (tfd >= 0)
{
#if SM_OPEN_EXLOCK
/* file is locked by open() */
break;
#else /* SM_OPEN_EXLOCK */
break;
else
#endif /* SM_OPEN_EXLOCK */
if (LogLevel > 0 && (i % 32) == 0)
"queueup: cannot lock %s: %s",
if ((i % 32) == 31)
{
tfd = -1;
}
}
if ((i % 32) == 31)
{
/* save the old temp file away */
}
else
(void) sleep(i % 32);
}
(void *) &tfd, SM_IO_WRONLY_B,
{
int save_errno = errno;
printopenfds(true);
errno = save_errno;
syserr("!queueup: cannot create queue temp file %s, uid=%d",
}
}
sm_dprintf("\n>>>>> queueing %s/%s%s >>>>>\n",
queuename(e, ANYQFL_LETTER),
{
sm_dprintf(" e_flags=");
printenvflags(e);
}
{
sm_dprintf(" sendq=");
}
{
sm_dprintf(" tfp=");
sm_dprintf(" lockfp=");
sm_dprintf("NULL\n");
else
true, false);
}
/*
** If there is no data file yet, create one.
*/
{
SuperSafe != SAFE_REALLY &&
{
syserr("!queueup: cannot commit data file %s, uid=%d",
}
{
"queueup: fsync(e->e_dfp)");
NULL)) < 0)
{
if (newid)
syserr("!552 Error writing data file %s",
df);
else
syserr("!452 Error writing data file %s",
df);
}
}
}
else
{
int dfd;
syserr("committing over bf file");
(void *) &dfd, SM_IO_WRONLY_B,
syserr("!queueup: cannot create data temp file %s, uid=%d",
e->e_dfino = -1;
else
{
}
if (SuperSafe == SAFE_REALLY ||
{
"queueup: fsync(dfp)");
{
if (newid)
syserr("!552 Error writing data file %s",
df);
else
syserr("!452 Error writing data file %s",
df);
}
}
syserr("!queueup: cannot save data temp file %s, uid=%d",
}
/*
** Output future work requests.
** Priority and creation time should be first, since
** they are required by gatherq.
*/
/* output queue version number (must be first!) */
/* output creation time */
/* output last delivery time */
/* output number of delivery attempts */
/* output message priority */
/*
** If data file is in a different directory than the queue file,
** output a "d" record naming the directory of the data file.
*/
{
}
/* output inode number of data file */
if (e->e_dfino != -1)
{
(ULONGLONG_T) e->e_dfino);
}
/* output body type */
if (e->e_bodytype != NULL)
denlstring(e->e_bodytype, true, false));
/* quarantine reason */
denlstring(e->e_quarmsg, true, false));
/* message from envelope, if it exists */
denlstring(e->e_message, true, false));
/* send various flag bits through */
p = buf;
*p++ = 'w';
*p++ = 'r';
*p++ = '8';
*p++ = 'b';
*p++ = 'd';
*p++ = 'n';
*p++ = 's';
*p++ = '\0';
if (buf[0] != '\0')
/* save $={persistentMacros} macro values */
/* output name of sender */
p = e->e_sender;
else
denlstring(p, true, false));
/* output ESMTP-supplied "original" information */
denlstring(e->e_envid, true, false));
/* output AUTH= parameter */
if (e->e_auth_param != NULL)
denlstring(e->e_auth_param, true, false));
if (e->e_dlvr_flag != 0)
(char) e->e_dlvr_flag, e->e_deliver_by);
/* output list of recipient addresses */
{
if (!QS_IS_UNDELIVERED(q->q_state))
continue;
/* message for this recipient, if it exists */
denlstring(q->q_message, true,
false));
printctladdr(q, tfp);
denlstring(q->q_orcpt, true,
false));
if (q->q_finalrcpt != NULL)
denlstring(q->q_finalrcpt, true,
false));
denlstring(q->q_paddr, true, false));
if (announce)
{
char *tag = "queued";
tag = "quarantined";
if (LogLevel > 8)
}
{
sm_dprintf("queueing ");
printaddr(sm_debug_file(), q, false);
}
}
/*
** Output headers for this message.
** Expand macros completely here. Queue run will deal with
** everything as absolute headers.
** All headers that must be relative to the recipient
** can be cracked later.
** We set up a "null mailer" -- i.e., a mailer that will have
** no effect on the addresses as they are output.
*/
{
continue;
/* don't output resent headers on non-resent messages */
continue;
/* expand macros; if null, don't output header at all */
{
if (buf[0] == '\0')
continue;
}
/* output this header */
/* output conditional macro if present */
if (h->h_macro != '\0')
{
"${%s}",
else
"$%c", h->h_macro);
}
{
int j;
/* if conditional, output the set of conditions */
for (j = '\0'; j <= '\177'; j++)
j);
}
/* output the header: expand macros, convert addresses */
{
h->h_field,
denlstring(buf, false, true));
}
{
oldstyle = false;
}
else
{
h->h_field,
denlstring(h->h_value, false,
true));
}
}
/*
** Clean up.
**
** Write a terminator record -- this is to prevent
** scurrilous crackers from appending any data.
*/
((SuperSafe == SAFE_REALLY ||
{
if (newid)
else
}
if (!newid)
{
/* rename (locked) tf to be (locked) [qh]f */
sizeof qf);
syserr("cannot rename(%s, %s), uid=%d",
else
{
/*
** Check if type has changed and only
** remove the old item if the rename above
** succeeded.
*/
if (e->e_qfletter != '\0' &&
e->e_qfletter != new)
{
{
sm_dprintf("type changed from %c to %c\n",
e->e_qfletter, new);
}
{
/* XXX: something more drastic? */
if (LogLevel > 0)
"queueup: unlink(%s) failed: %s",
queuename(e, e->e_qfletter),
}
}
}
e->e_qfletter = new;
/*
** fsync() after renaming to make sure metadata is
** written to disk on filesystems in which renames are
** not guaranteed.
*/
{
/* for softupdates */
{
syserr("!queueup: cannot fsync queue temp file %s",
tf);
}
}
/* close and unlock old (locked) queue file */
/* save log info */
if (LogLevel > 79)
}
else
{
/* save log info */
if (LogLevel > 79)
}
errno = 0;
e->e_flags |= EF_INQUEUE;
return;
}
/*
** PRINTCTLADDR -- print control address to file.
**
** Parameters:
** a -- address.
** tfp -- file pointer.
**
** Returns:
** none.
**
** Side Effects:
** The control address (if changed) is printed to the file.
** The last control address and uid are saved.
*/
static void
printctladdr(a, tfp)
register ADDRESS *a;
{
char *user;
register ADDRESS *q;
/* initialization */
{
lastctladdr = NULL;
lastuid = 0;
return;
}
/* find the active uid */
q = getctladdr(a);
if (q == NULL)
{
uid = 0;
gid = 0;
}
else
{
}
a = a->q_alias;
/* check to see if this is the same as last time */
return;
lastctladdr = a;
else
(long) gid);
denlstring(a->q_paddr, true, false));
}
/*
** RUNNERS_SIGTERM -- propagate a SIGTERM to queue runner process
**
** This propagates the signal to the child processes that are queue
** runners. This is for a queue runner "cleanup". After all of the
** child queue runner processes are signaled (it should be SIGTERM
** being the sig) then the old signal handler (Oldsh) is called
** to handle any cleanup set for this process (provided it is not
** SIG_DFL or SIG_IGN). The signal may not be handled immediately
** if the BlockOldsh flag is set. If the current process doesn't
** have a parent then handle the signal immediately, regardless of
** BlockOldsh.
**
** Parameters:
** sig -- the signal number being sent
**
** Returns:
** none.
**
** Side Effects:
** Sets the NoMoreRunners boolean to true to stop more runners
** from being started in runqueue().
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
static bool volatile NoMoreRunners = false;
static bool BlockOldsh = false;
static int volatile Oldsig = 0;
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
errno = save_errno;
NoMoreRunners = true;
Oldsh = Oldsh_term;
{
/* Check that a valid 'old signal handler' is callable */
(*Oldsh_term)(sig);
}
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** RUNNERS_SIGHUP -- propagate a SIGHUP to queue runner process
**
** This propagates the signal to the child processes that are queue
** runners. This is for a queue runner "cleanup". After all of the
** child queue runner processes are signaled (it should be SIGHUP
** being the sig) then the old signal handler (Oldsh) is called to
** handle any cleanup set for this process (provided it is not SIG_DFL
** or SIG_IGN). The signal may not be handled immediately if the
** BlockOldsh flag is set. If the current process doesn't have
** a parent then handle the signal immediately, regardless of
** BlockOldsh.
**
** Parameters:
** sig -- the signal number being sent
**
** Returns:
** none.
**
** Side Effects:
** Sets the NoMoreRunners boolean to true to stop more runners
** from being started in runqueue().
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
errno = save_errno;
NoMoreRunners = true;
{
/* Check that a valid 'old signal handler' is callable */
}
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** MARK_WORK_GROUP_RESTART -- mark a work group as needing a restart
**
** Sets a workgroup for restarting.
**
** Parameters:
** wgrp -- the work group id to restart.
** reason -- why (signal?), -1 to turn off restart
**
** Returns:
** none.
**
** Side effects:
** May set global RestartWorkGroup to true.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
void
int wgrp;
int reason;
{
return;
if (reason >= 0)
RestartWorkGroup = true;
}
/*
** RESTART_MARKED_WORK_GROUPS -- restart work groups marked as needing restart
**
** Restart any workgroup marked as needing a restart provided more
** runners are allowed.
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side effects:
** Sets global RestartWorkGroup to false.
*/
void
{
int i;
int wasblocked;
if (NoMoreRunners)
return;
/* Block SIGCHLD so reapchild() doesn't mess with us */
for (i = 0; i < NumWorkGroups; i++)
{
if (WorkGrp[i].wg_restart >= 0)
{
if (LogLevel > 8)
"restart queue runner=%d due to signal 0x%x",
i, WorkGrp[i].wg_restart);
}
}
RestartWorkGroup = false;
if (wasblocked == 0)
(void) sm_releasesignal(SIGCHLD);
}
/*
** RESTART_WORK_GROUP -- restart a specific work group
**
** Restart a specific workgroup provided more runners are allowed.
** If the requested work group has been restarted too many times log
** this and refuse to restart.
**
** Parameters:
** wgrp -- the work group id to restart
**
** Returns:
** none.
**
** Side Effects:
** starts another process doing the work of wgrp
*/
static void
int wgrp;
{
if (NoMoreRunners ||
return;
{
/* avoid overflow; increment here */
}
else
{
"ERROR: persistent queue runner=%d restarted too many times, queue runner lost",
wgrp);
}
}
/*
** SCHEDULE_QUEUE_RUNS -- schedule the next queue run for a work group.
**
** Parameters:
** runall -- schedule even if individual bit is not set.
** wgrp -- the work group id to schedule.
** didit -- the queue run was performed for this work group.
**
** Returns:
** nothing
*/
#define INCR_MOD(v, m) if (++v >= m) \
v = 0; \
else
static void
bool runall;
int wgrp;
bool didit;
{
bool sched;
#endif /* _FFR_QUEUE_SCHED_DBG */
/*
** This is a bit ugly since we have to duplicate the
** code that "walks" through a work queue group.
*/
minqintvl = 0;
do
{
lastsched = 0;
sched = false;
#endif /* _FFR_QUEUE_SCHED_DBG */
else if (QueueIntvl > 0)
qintvl = QueueIntvl;
else
#endif /* _FFR_QUEUE_SCHED_DBG */
{
sched = true;
#endif /* _FFR_QUEUE_SCHED_DBG */
/*
** Only set a new time if a queue run was performed
** for this queue group. If the queue was not run,
** we could starve it by setting a new time on each
** call.
*/
if (didit)
}
"sqr: wgrp=%d, cgrp=%d, qgrp=%d, intvl=%ld, QI=%ld, runall=%d, lastrun=%ld, nextrun=%ld, sched=%d",
#endif /* _FFR_QUEUE_SCHED_DBG */
if (minqintvl > 0)
}
/*
** CHECKQUEUERUNNER -- check whether a queue group hasn't been run.
**
** Use this if events may get lost and hence queue runners may not
** be started and mail will pile up in a queue.
**
** Parameters:
** none.
**
** Returns:
** true if a queue run is necessary.
**
** Side Effects:
** may schedule a queue run.
*/
bool
{
int qgrp;
minqintvl = 0;
{
else if (QueueIntvl > 0)
qintvl = QueueIntvl;
else
{
if (LogLevel > 1)
"checkqueuerunner: queue %d should have been run at %s, queue interval %ld",
qgrp,
qintvl);
}
}
if (minqintvl > 0)
{
return true;
}
return false;
}
#endif /* _FFR_QUEUE_RUN_PARANOIA */
/*
** RUNQUEUE -- run the jobs in the queue.
**
** Gets the stuff out of the queue in some presumably logical
** order and processes them.
**
** Parameters:
** forkflag -- true if the queue scanning should be done in
** a child process. We double-fork so it is not our
** child and we don't have to clean up after it.
** false can be ignored if we have multiple queues.
** verbose -- if true, print out status information.
** persistent -- persistent queue runner?
** runall -- run all groups or only a subset (DoQueueRun)?
**
** Returns:
** true if the queue run successfully began.
**
** Side Effects:
** runs things in the mail queue using run_work_group().
** maybe schedules next queue run.
*/
/* values for qp_supdirs */
bool
bool forkflag;
bool verbose;
bool persistent;
bool runall;
{
int i;
bool ret = true;
static int curnum = 0;
#if SM_HEAP_CHECK
SM_NONVOLATILE int oldgroup = 0;
{
oldgroup = sm_heap_group();
}
#endif /* SM_HEAP_CHECK */
/* queue run has been started, don't do any more this time */
DoQueueRun = false;
/* more than one queue or more than one directory per queue */
forkflag = true;
/*
** For controlling queue runners via signals sent to this process.
** Oldsh* will get called too by runners_sig* (if it is not SIG_IGN
** or SIG_DFL) to preserve cleanup behavior. Now that this process
** will have children (and perhaps grandchildren) this handler will
** be left in place. This is because this process, once it has
** finished spinning off queue runners, may go back to doing something
** else (like being a daemon). And we still want on a SIG{TERM,HUP} to
** clean up the child queue runners. Only install 'runners_sig*' once
** else we'll get stuck looping forever.
*/
if (cursh != runners_sigterm)
Oldsh_term = cursh;
if (cursh != runners_sighup)
for (i = 0; i < NumWorkGroups && !NoMoreRunners; i++)
{
/*
** If MaxQueueChildren active then test whether the start
** of the next queue group's additional queue runners (maximum)
** will result in MaxQueueChildren being exceeded.
**
** Note: do not use continue; even though another workgroup
** may have fewer queue runners, this would be "unfair",
** i.e., this work group might "starve" then.
*/
"rq: curnum=%d, MaxQueueChildren=%d, CurRunners=%d, WorkGrp[curnum].wg_maxact=%d",
#endif /* _FFR_QUEUE_SCHED_DBG */
if (MaxQueueChildren > 0 &&
break;
/*
** Pick up where we left off (curnum), in case we
** used up all the children last time without finishing.
** This give a round-robin fairness to queue runs.
**
** Increment CurRunners before calling run_work_group()
** to avoid a "race condition" with proc_list_drop() which
** decrements CurRunners if the queue runners terminate.
** Notice: CurRunners is an upper limit, in some cases
** (too few jobs in the queue) this value is larger than
** the actual number of queue runners. The discrepancy can
** increase if some queue runners "hang" for a long time.
*/
if (forkflag)
if (verbose)
rwgflags |= RWG_VERBOSE;
if (persistent)
if (runall)
rwgflags |= RWG_RUNALL;
/*
** Failure means a message was printed for ETRN
** and subsequent queues are likely to fail as well.
** Decrement CurRunners in that case because
** none have been started.
*/
if (!ret)
{
break;
}
if (!persistent)
}
/* schedule left over queue runs */
{
int h;
for (h = curnum; i < NumWorkGroups; i++)
{
schedule_queue_runs(runall, h, false);
INCR_MOD(h, NumWorkGroups);
}
}
#if SM_HEAP_CHECK
#endif /* SM_HEAP_CHECK */
return ret;
}
/*
** SKIP_DOMAINS -- Skip 'skip' number of domains in the WorkQ.
**
** Added by Stephen Frost <sfrost@snowman.net> to support
** having each runner process every N'th domain instead of
** every N'th message.
**
** Parameters:
** skip -- number of domains in WorkQ to skip.
**
** Returns:
** total number of messages skipped.
**
** Side Effects:
** may change WorkQ
*/
static int
int skip;
{
int n, seqjump;
{
{
{
n++;
}
else
{
n++;
}
}
}
return seqjump;
}
#endif /* _FFR_SKIP_DOMAINS */
/*
** RUNNER_WORK -- have a queue runner do its work
**
** Have a queue runner do its work a list of entries.
** When work isn't directly being done then this process can take a signal
** and terminate immediately (in a clean fashion of course).
** When work is directly being done, it's not to be interrupted
** immediately: the work should be allowed to finish at a clean point
** before termination (in a clean fashion of course).
**
** Parameters:
** e -- envelope.
** sequenceno -- 'th process to run WorkQ.
** didfork -- did the calling process fork()?
** skip -- process only each skip'th item.
** njobs -- number of jobs in WorkQ.
**
** Returns:
** none.
**
** Side Effects:
** runs things in the mail queue.
*/
static void
register ENVELOPE *e;
int sequenceno;
bool didfork;
int skip;
int njobs;
{
int n, seqjump;
WORK *w;
/*
** Here we temporarily block the second calling of the handlers.
** This allows us to handle the signal without terminating in the
** middle of direct work. If a signal does come, the test for
** NoMoreRunners will find it.
*/
BlockOldsh = true;
/* process them once at a time */
{
#if SM_HEAP_CHECK
SM_NONVOLATILE int oldgroup = 0;
{
oldgroup = sm_heap_group();
sm_dprintf("run_queue_group() heap group #%d\n",
sm_heap_group());
}
#endif /* SM_HEAP_CHECK */
/* do no more work */
if (NoMoreRunners)
{
/* Check that a valid signal handler is callable */
Oldsh != runners_sighup &&
Oldsh != runners_sigterm)
break;
}
w = WorkQ; /* assign current work item */
/*
** Set the head of the WorkQ to the next work item.
** It is set 'skip' ahead (the number of parallel queue
** runners working on WorkQ together) since each runner
** works on every 'skip'th (N-th) item.
#if _FFR_SKIP_DOMAINS
** In the case of the BYHOST Queue Sort Order, the 'item'
** is a domain, so we work on every 'skip'th (N-th) domain.
#endif * _FFR_SKIP_DOMAINS *
*/
if (QueueSortOrder == QSO_BYHOST)
{
seqjump = 1;
{
{
!= 0)
else
}
else
{
else
}
}
else
}
else
#endif /* _FFR_SKIP_DOMAINS */
{
}
/*
** Ignore jobs that are too expensive for the moment.
**
** Get new load average every GET_NEW_LA_TIME seconds.
*/
{
char *msg = "Aborting queue run: load average too high";
if (Verbose)
if (LogLevel > 8)
break;
}
{
if (Verbose)
if (QueueSortOrder == QSO_BYPRIORITY)
{
if (Verbose)
message("Skipping %s/%s (sequence %d of %d) and flushing rest of queue",
qid_printqueue(w->w_qgrp,
w->w_qdir),
njobs);
if (LogLevel > 8)
"runqueue: Flushing queue from %s/%s (pri %ld, LA %d, %d of %d)",
qid_printqueue(w->w_qgrp,
w->w_qdir),
njobs);
break;
}
else if (Verbose)
message("Skipping %s/%s (sequence %d of %d)",
}
else
{
if (Verbose)
{
message("Running %s/%s (sequence %d of %d)",
}
if (didfork && MaxQueueChildren > 0)
{
}
"runqueue %s dowork(%s)",
w->w_name + 2);
ForkQueueRuns, false, e);
errno = 0;
}
sm_free((char *) w); /* XXX */
#if SM_HEAP_CHECK
#endif /* SM_HEAP_CHECK */
}
BlockOldsh = false;
/* check the signals didn't happen during the revert */
if (NoMoreRunners)
{
/* Check that a valid signal handler is callable */
}
}
/*
** RUN_WORK_GROUP -- run the jobs in a queue group from a work group.
**
** Gets the stuff out of the queue in some presumably logical
** order and processes them.
**
** Parameters:
** wgrp -- work group to process.
** flags -- RWG_* flags
**
** Returns:
** true if the queue run successfully began.
**
** Side Effects:
** runs things in the mail queue.
*/
/* Minimum sleep time for persistent queue runners */
#define MIN_SLEEP_TIME 5
bool
int wgrp;
int flags;
{
register ENVELOPE *e;
int sequenceno = 1;
extern ENVELOPE BlankEnvelope;
if (wgrp < 0)
return false;
/*
** If no work will ever be selected, don't even bother reading
** the queue.
*/
{
char *msg = "Skipping queue run -- load average too high";
if (LogLevel > 8)
return false;
}
/*
** See if we already have too many children.
*/
{
char *msg = "Skipping queue run -- too many children";
if (LogLevel > 8)
msg, CurChildren);
return false;
}
/*
** See if we want to go off and do other useful work.
*/
{
(void) sm_blocksignal(SIGCHLD);
if (pid == -1)
{
const char *msg = "Skipping queue run -- fork() failed";
if (LogLevel > 8)
(void) sm_releasesignal(SIGCHLD);
return false;
}
if (pid != 0)
{
/* parent -- pick up intermediate zombie */
(void) sm_blocksignal(SIGALRM);
/* wgrp only used when queue runners are persistent */
NULL);
(void) sm_releasesignal(SIGALRM);
(void) sm_releasesignal(SIGCHLD);
return true;
}
/* child -- clean up signals */
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
CurrentPid = getpid();
/*
** Initialize exception stack and default exception
** handler for child process.
*/
clrcontrol();
/* Add parent process as first child item */
(void) sm_releasesignal(SIGCHLD);
}
/*
** Release any resources used by the daemon code.
*/
clrdaemon();
/* force it to run expensive jobs */
NoConnect = false;
/* drop privileges */
(void) drop_privileges(false);
/*
** Create ourselves an envelope
*/
CurEnv = &QueueEnvelope;
/* make sure we have disconnected from parent */
{
disconnect(1, e);
QuickAbort = false;
}
/*
** If we are running part of the queue, always ignore stored
** host status.
*/
QueueLimitQuarantine != NULL ||
{
IgnoreHostStatus = true;
MinQueueAge = 0;
}
/*
** Here is where we choose the queue group from the work group.
** The caller of the "domorework" label must setup a new envelope.
*/
/*
** Run a queue group if:
** RWG_RUNALL bit is set or the bit for this group is set.
*/
for (;;)
{
/*
** Find the next queue group within the work group that
** has been marked as needing a run.
*/
break;
{
return true; /* we're done */
}
}
"rwg: wgrp=%d, qgrp=%d, qdir=%d, name=%s, curqgrp=%d, numgrps=%d",
#endif /* _FFR_QUEUE_SCHED_DBG */
#if HASNICE
/* tweak niceness of queue runs */
#endif /* HASNICE */
/* XXX running queue group... */
"runqueue %s, pid=%d, forkflag=%d",
/*
** Start making passes through the queue.
** First, read and sort the entire queue.
** Then, process the work in that order.
** But if you take too long, start over.
*/
{
#if SM_CONF_SHM
if (ShmId != SM_SHM_NO_ID)
#endif /* SM_CONF_SHM */
/* If there are no more items in this queue advance */
if (!more)
{
/* A round-robin advance */
qdir++;
}
/* Has the WorkList reached the limit? */
if (full)
break; /* don't try to gather more */
}
/* order the existing work requests */
{
int loop, maxrunners;
/*
** For this WorkQ we want to fork off N children (maxrunners)
** at this point. Each child has a copy of WorkQ. Each child
** will process every N-th item. The parent will wait for all
** of the children to finish before moving on to the next
** queue group within the work group. This saves us forking
** a new runner-child for each work item.
** It's valid for qg_maxqrun == 0 since this may be an
** explicit "don't run this queue" setting.
*/
/* No need to have more runners then there are jobs */
if (maxrunners > njobs)
maxrunners = njobs;
{
/*
** Since the delivery may happen in a child and the
** parent does not wait, the parent may close the
** maps thereby removing any shared memory used by
** the map. Therefore, close the maps now so the
** child will dynamically open them if necessary.
*/
closemaps(false);
if (pid < 0)
{
syserr("run_work_group: cannot fork");
return false;
}
else if (pid > 0)
{
/* parent -- clean out connection cache */
if (QueueSortOrder == QSO_BYHOST)
{
}
else
#endif /* _FFR_SKIP_DOMAINS */
{
/* for the skip */
sequenceno++;
}
/* No additional work, no additional runners */
break;
}
else
{
/* child -- Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
CurrentPid = getpid();
/*
** Initialize exception stack and default
** exception handler for child process.
** When fork()'d the child now has a private
** copy of WorkQ at its current position.
*/
/*
** SMTP processes (whether -bd or -bs) set
** SIGCHLD to reapchild to collect
** children status. However, at delivery
** time, that status must be collected
** by sm_wait() to be dealt with properly
** (check success of delivery based
** on status code, etc). Therefore, if we
** are an SMTP process, reset SIGCHLD
** back to the default so reapchild
** doesn't collect status before
** sm_wait().
*/
MaxQueueChildren > 0)
{
}
/* child -- error messages to the transcript */
QuickAbort = OnlyOneError = false;
runner_work(e, sequenceno, true,
maxrunners, njobs);
/* This child is done */
/* NOTREACHED */
}
}
/*
** Wait until all of the runners have completed before
** seeing if there is another queue group in the
** work group to process.
** XXX Future enhancement: don't wait() for all children
** here, just go ahead and make sure that overall the number
** of children is not exceeded.
*/
while (CurChildren > 0)
{
int status;
continue;
}
}
{
/*
** When current process will not fork children to do the work,
** it will do the work itself. The 'skip' will be 1 since
** there are no child runners to divide the work across.
*/
}
/* free memory allocated by newenvelope() above */
/* Are there still more queues in the work group to process? */
{
goto domorework;
}
/* No more queues in work group to process. Now check persistent. */
{
sequenceno = 1;
/*
** close bogus maps, i.e., maps which caused a tempfail,
** so we get fresh map connections on the next lookup.
** closemaps() is also called when children are started.
*/
closemaps(true);
/* Close any cached connections. */
/* Clean out expired related entries. */
rmexpstab();
#if NAMED_BIND
/* Update MX records for FallbackMX. */
if (FallbackMX != NULL)
(void) getfallbackmxrr(FallbackMX);
#endif /* NAMED_BIND */
#if USERDB
/* close UserDatabase */
_udbx_close();
#endif /* USERDB */
#if SM_HEAP_CHECK
)
{
remove("memdump");
{
}
}
#endif /* SM_HEAP_CHECK */
/* let me rest for a second to catch my breath */
else
/*
** Get the LA outside the WorkQ loop if necessary.
** In a persistent queue runner the code is repeated over
** and over but gatherq() may ignore entries due to
** shouldqueue() (do we really have to do this twice?).
** Hence the queue runners would just idle around when once
** CurrentLA caused all entries in a queue to be ignored.
*/
if (njobs == 0)
goto domorework;
}
/* exit without the usual cleanup */
/* NOTREACHED */
return true;
}
/*
** DOQUEUERUN -- do a queue run?
*/
bool
{
return DoQueueRun;
}
/*
** RUNQUEUEEVENT -- Sets a flag to indicate that a queue run should be done.
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** The invocation of this function via an alarm may interrupt
** a set of actions. Thus errno may be set in that context.
** We need to restore errno at the end of this function to ensure
** that any work done here that sets errno doesn't return a
** misleading/false errno value. Errno may be EINTR upon entry to
** this function because of non-restartable/continuable system
** API was active. Iff this is true we will override errno as
** a timeout (as a more accurate error message).
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
void
int ignore;
{
int save_errno = errno;
/*
** Set the general bit that we want a queue run,
** tested in doqueuerun()
*/
DoQueueRun = true;
#endif /* _FFR_QUEUE_SCHED_DBG */
errno = save_errno;
}
/*
** GATHERQ -- gather messages from the message queue(s) the work queue.
**
** Parameters:
** qgrp -- the index of the queue group.
** qdir -- the index of the queue directory.
** doall -- if set, include everything in the queue (even
** the jobs that cannot be run because the load
** average is too high, or MaxQueueRun is reached).
** Otherwise, exclude those jobs.
** full -- (optional) to be set 'true' if WorkList is full
** more -- (optional) to be set 'true' if there are still more
** messages in this queue not added to WorkList
**
** Returns:
** The number of request in the queue (not necessarily
** the number of requests in WorkList however).
**
** Side Effects:
** prepares available work into WorkList
*/
static int WorkListSize = 0; /* current max size of WorkList */
static int WorkListCount = 0; /* # of work items in WorkList */
static int
int qgrp;
int qdir;
bool doall;
bool *full;
bool *more;
{
register struct dirent *d;
register WORK *w;
register char *p;
DIR *f;
int i, num_ent;
int wn;
char qd[MAXPATHLEN];
char qf[MAXPATHLEN];
num_ent = 0;
else
? "/qf" : ""));
{
sm_dprintf("gatherq:\n");
{
sm_dprintf("\tQueueLimitId = %s%s\n",
check->queue_match);
}
{
sm_dprintf("\tQueueLimitSender = %s%s\n",
check->queue_match);
}
{
sm_dprintf("\tQueueLimitRecipient = %s%s\n",
check->queue_match);
}
if (QueueMode == QM_QUARANTINE)
{
{
sm_dprintf("\tQueueLimitQuarantine = %s%s\n",
check->queue_match);
}
}
}
/* open the queue directory */
if (f == NULL)
{
syserr("gatherq: cannot open \"%s\"",
*more = false;
return 0;
}
/*
** Read the work directory.
*/
{
int qfver = 0;
/* is this an interesting entry? */
d->d_name[0] == NORMQF_LETTER) ||
(QueueMode == QM_QUARANTINE &&
d->d_name[0] == QUARQF_LETTER) ||
d->d_name[0] == LOSEQF_LETTER)) &&
{
sm_dprintf(" skipping\n");
continue;
}
sm_dprintf("\n");
{
if (Verbose)
"gatherq: %s too long, %d max characters\n",
if (LogLevel > 0)
"gatherq: %s too long, %d max characters",
continue;
}
{
break;
else
}
continue;
/* grow work list if necessary */
{
"WorkList for %s maxed out at %d",
if (doall)
continue; /* just count entries */
break;
}
if (wn >= WorkListSize)
{
if (wn >= WorkListSize)
continue;
}
{
"gatherq: can't stat %s/%s",
d->d_name);
wn--;
continue;
}
{
/* Yikes! Skip it or we will hang on open! */
if (!((d->d_name[0] == DATAFL_LETTER ||
d->d_name[0] == NORMQF_LETTER ||
d->d_name[0] == QUARQF_LETTER ||
d->d_name[0] == LOSEQF_LETTER ||
d->d_name[0] == XSCRPT_LETTER) &&
syserr("gatherq: %s/%s is not a regular file",
wn--;
continue;
}
/* avoid work if possible */
if ((QueueSortOrder == QSO_BYFILENAME ||
QueueSortOrder == QSO_BYMODTIME ||
QueueSortOrder == QSO_RANDOM) &&
QueueLimitQuarantine == NULL &&
QueueLimitSender == NULL &&
{
w->w_lock = w->w_tooyoung = false;
w->w_pri = 0;
w->w_ctime = 0;
++num_ent;
continue;
}
/* open control file */
NULL);
{
/* this may be some random person sending hir msgs */
sm_dprintf("gatherq: cannot open %s: %s\n",
errno = 0;
wn--;
continue;
}
{
NULL),
}
w->w_tooyoung = false;
/* make sure jobs in creation don't clog queue */
w->w_pri = 0x7fffffff;
w->w_ctime = 0;
/* extract useful information */
if (QueueSortOrder == QSO_BYHOST
#if _FFR_RHS
|| QueueSortOrder == QSO_BYSHUFFLE
#endif /* _FFR_RHS */
)
{
/* need w_host set for host sort order */
i |= NEED_H;
}
if (QueueLimitSender != NULL)
i |= NEED_S;
if (QueueLimitRecipient != NULL)
i |= NEED_R;
if (QueueLimitQuarantine != NULL)
i |= NEED_QUARANTINE;
{
int c;
if (p != NULL)
*p = '\0';
else
{
/* flush rest of overly long line */
!= SM_IO_EOF && c != '\n')
continue;
}
switch (lbuf[0])
{
case 'V':
break;
case 'P':
i &= ~NEED_P;
break;
case 'T':
i &= ~NEED_T;
break;
case 'q':
if (QueueMode != QM_QUARANTINE &&
{
sm_dprintf("%s not marked as quarantined but has a 'q' line\n",
w->w_name);
i |= HAS_QUARANTINE;
}
else if (QueueMode == QM_QUARANTINE)
{
if (QueueLimitQuarantine == NULL)
{
i &= ~NEED_QUARANTINE;
break;
}
p = &lbuf[1];
{
if (strcontainedin(false,
p) !=
break;
else
}
i &= ~NEED_QUARANTINE;
}
break;
case 'R':
{
#if _FFR_RHS
if (QueueSortOrder == QSO_BYSHUFFLE)
else
#endif /* _FFR_RHS */
i &= ~NEED_H;
}
if (QueueLimitRecipient == NULL)
{
i &= ~NEED_R;
break;
}
if (qfver > 0)
{
if (p == NULL)
p = &lbuf[1];
else
++p; /* skip over ':' */
}
else
p = &lbuf[1];
{
if (strcontainedin(true,
p) !=
break;
else
}
i &= ~NEED_R;
break;
case 'S':
{
if (strcontainedin(true,
&lbuf[1]) !=
break;
else
}
i &= ~NEED_S;
break;
case 'K':
if (age >= 0 && MinQueueAge > 0 &&
age < MinQueueAge)
w->w_tooyoung = true;
break;
case 'N':
w->w_tooyoung = false;
break;
}
}
w->w_tooyoung)) ||
bitset(HAS_QUARANTINE, i) ||
bitset(NEED_QUARANTINE, i) ||
{
/* don't even bother sorting this job in */
wn--;
}
else
++num_ent;
}
(void) closedir(f);
wn++;
i = wn - WorkListCount;
return i;
}
/*
** SORTQ -- sort the work list
**
** First the old WorkQ is cleared away. Then the WorkList is sorted
** for all items so that important (higher sorting value) items are not
** trunctated off. Then the most important items are moved from
** WorkList to WorkQ. The lower count of 'max' or MaxListCount items
** are moved.
**
** Parameters:
** max -- maximum number of items to be placed in WorkQ
**
** Returns:
** the number of items in WorkQ
**
** Side Effects:
** WorkQ gets released and filled with new work. WorkList
** gets released. Work items get sorted in order.
*/
static int
int max;
{
register int i; /* local counter */
register WORK *w; /* tmp item pointer */
{
/* Clear out old WorkQ. */
{
sm_free((char *) w); /* XXX */
}
}
return 0;
/*
** The sort now takes place using all of the items in WorkList.
** The list gets trimmed to the most important items after the sort.
** If the trim were to happen before the sort then one or more
** important items might get truncated off -- not what we want.
*/
if (QueueSortOrder == QSO_BYHOST)
{
/*
** Sort the work directory for the first time,
** based on host name, lock status, and priority.
*/
/*
** If one message to host is locked, "lock" all messages
** to that host.
*/
i = 0;
while (i < wc)
{
{
i++;
continue;
}
w = &WorkList[i];
while (++i < wc)
{
w->w_host) == 0)
else
break;
}
}
/*
** Sort the work directory for the second time,
** based on lock status, host name, and priority.
*/
}
else if (QueueSortOrder == QSO_BYTIME)
{
/*
** Simple sort based on submission time only.
*/
}
else if (QueueSortOrder == QSO_BYFILENAME)
{
/*
** Sort based on queue filename.
*/
}
else if (QueueSortOrder == QSO_RANDOM)
{
/*
** Sort randomly. To avoid problems with an instable sort,
** use a random index into the queue file name to start
** comparison.
*/
if (randi < 2)
randi = 3;
}
else if (QueueSortOrder == QSO_BYMODTIME)
{
/*
** Simple sort based on modification time of queue file.
** This puts the oldest items first.
*/
}
#if _FFR_RHS
else if (QueueSortOrder == QSO_BYSHUFFLE)
{
/*
** Simple sort based on shuffled host name.
*/
}
#endif /* _FFR_RHS */
else if (QueueSortOrder == QSO_BYPRIORITY)
{
/*
** Simple sort based on queue priority only.
*/
}
/* else don't sort at all */
/* Check if the per queue group item limit will be exceeded */
/*
** Convert the work list into canonical form.
** Should be turning it into a list of envelopes here perhaps.
** Only take the most important items up to the per queue group
** maximum.
*/
for (i = wc; --i >= 0; )
{
WorkQ = w;
}
/* free the rest of the list */
for (i = WorkListCount; --i >= wc; )
{
}
WorkListSize = 0;
WorkListCount = 0;
{
{
sm_dprintf("%22s: pri=%ld %s\n",
else
sm_dprintf("%32s: pri=%ld\n",
}
}
return wc; /* return number of WorkQ items */
}
/*
** GROW_WLIST -- make the work list larger
**
** Parameters:
** qgrp -- the index for the queue group.
** qdir -- the index for the queue directory.
**
** Returns:
** none.
**
** Side Effects:
** Adds another QUEUESEGSIZE entries to WorkList if possible.
** It can fail if there isn't enough memory, so WorkListSize
** should be checked again upon return.
*/
static void
int qgrp;
int qdir;
{
{
(QUEUESEGSIZE + 1));
}
else
{
{
if (LogLevel > 1)
{
"grew WorkList for %s to %d",
}
}
else if (LogLevel > 0)
{
"FAILED to grow WorkList for %s to %d",
}
}
}
/*
** WORKCMPF0 -- simple priority-only compare function.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** -1 if a < b
** 0 if a == b
** +1 if a > b
**
*/
static int
workcmpf0(a, b)
register WORK *a;
register WORK *b;
{
return 0;
return 1;
else
return -1;
}
/*
** WORKCMPF1 -- first compare function for ordering work based on host name.
**
** Sorts on host name, lock status, and priority in that order.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** <0 if a < b
** 0 if a == b
** >0 if a > b
**
*/
static int
workcmpf1(a, b)
register WORK *a;
register WORK *b;
{
int i;
/* host name */
return 1;
return -1;
return i;
/* lock status */
/* job priority */
return workcmpf0(a, b);
}
/*
** WORKCMPF2 -- second compare function for ordering work based on host name.
**
** Sorts on lock status, host name, and priority in that order.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** <0 if a < b
** 0 if a == b
** >0 if a > b
**
*/
static int
workcmpf2(a, b)
register WORK *a;
register WORK *b;
{
int i;
/* lock status */
/* host name */
return 1;
return -1;
return i;
/* job priority */
return workcmpf0(a, b);
}
/*
** WORKCMPF3 -- simple submission-time-only compare function.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** -1 if a < b
** 0 if a == b
** +1 if a > b
**
*/
static int
workcmpf3(a, b)
register WORK *a;
register WORK *b;
{
return 1;
return -1;
else
return 0;
}
/*
** WORKCMPF4 -- compare based on file name
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** -1 if a < b
** 0 if a == b
** +1 if a > b
**
*/
static int
workcmpf4(a, b)
register WORK *a;
register WORK *b;
{
}
/*
** WORKCMPF5 -- compare based on assigned random number
**
** Parameters:
** a -- the first argument (ignored).
** b -- the second argument (ignored).
**
** Returns:
** randomly 1/-1
*/
/* ARGSUSED0 */
static int
workcmpf5(a, b)
register WORK *a;
register WORK *b;
{
return -1;
}
/*
** WORKCMPF6 -- simple modification-time-only compare function.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** -1 if a < b
** 0 if a == b
** +1 if a > b
**
*/
static int
workcmpf6(a, b)
register WORK *a;
register WORK *b;
{
return 1;
return -1;
else
return 0;
}
#if _FFR_RHS
/*
** WORKCMPF7 -- compare function for ordering work based on shuffled host name.
**
** Sorts on lock status, host name, and priority in that order.
**
** Parameters:
** a -- the first argument.
** b -- the second argument.
**
** Returns:
** <0 if a < b
** 0 if a == b
** >0 if a > b
**
*/
static int
workcmpf7(a, b)
register WORK *a;
register WORK *b;
{
int i;
/* lock status */
/* host name */
return 1;
return -1;
return i;
/* job priority */
return workcmpf0(a, b);
}
#endif /* _FFR_RHS */
/*
** STRREV -- reverse string
**
** Returns a pointer to a new string that is the reverse of
** the string pointed to by fwd. The space for the new
** string is obtained using xalloc().
**
** Parameters:
** fwd -- the string to reverse.
**
** Returns:
** the reversed string.
*/
static char *
char *fwd;
{
return rev;
}
#if _FFR_RHS
# define NASCII 128
# define NCHAR 256
static unsigned char ShuffledAlphabet[NCHAR];
void
{
static bool init = false;
int i;
if (init)
return;
/* fill the ShuffledAlphabet */
for (i = 0; i < NASCII; i++)
ShuffledAlphabet[i] = i;
/* mix it */
for (i = 1; i < NASCII; i++)
{
register int j = get_random() % NASCII;
register int tmp;
tmp = ShuffledAlphabet[j];
ShuffledAlphabet[j] = ShuffledAlphabet[i];
ShuffledAlphabet[i] = tmp;
}
/* make it case insensitive */
for (i = 'A'; i <= 'Z'; i++)
/* fill the upper part */
for (i = 0; i < NASCII; i++)
init = true;
}
static int
sm_strshufflecmp(a, b)
char *a;
char *b;
{
const unsigned char *us1 = (const unsigned char *) a;
const unsigned char *us2 = (const unsigned char *) b;
{
if (*us1++ == '\0')
return 0;
}
}
#endif /* _FFR_RHS */
/*
** DOWORK -- do a work request.
**
** Parameters:
** qgrp -- the index of the queue group for the job.
** qdir -- the index of the queue directory for the job.
** id -- the ID of the job to run.
** forkflag -- if set, run this in background.
** requeueflag -- if set, reinstantiate the queue quickly.
** This is used when expanding aliases in the queue.
** If forkflag is also set, it doesn't wait for the
** child.
** e - the envelope in which to run it.
**
** Returns:
** process id of process that is running the queue job.
**
** Side Effects:
** The work request is satisfied if possible.
*/
int qgrp;
int qdir;
char *id;
bool forkflag;
bool requeueflag;
register ENVELOPE *e;
{
/*
** Fork for work.
*/
if (forkflag)
{
/*
** Since the delivery may happen in a child and the
** parent does not wait, the parent may close the
** maps thereby removing any shared memory used by
** the map. Therefore, close the maps now so the
** child will dynamically open them if necessary.
*/
closemaps(false);
if (pid < 0)
{
syserr("dowork: cannot fork");
return 0;
}
else if (pid > 0)
{
/* parent -- clean out connection cache */
}
else
{
/*
** Initialize exception stack and default exception
** handler for child process.
*/
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
CurrentPid = getpid();
/*
** See note above about SMTP processes and SIGCHLD.
*/
MaxQueueChildren > 0)
{
}
/* child -- error messages to the transcript */
QuickAbort = OnlyOneError = false;
}
}
else
{
pid = 0;
}
if (pid == 0)
{
/*
** CHILD
** Lock the control file to avoid duplicate deliveries.
** Then run the file as though we had just read it.
** We save an idea of the temporary name so we
** can recover on interrupt.
*/
if (forkflag)
{
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
}
/* set basic modes, etc. */
clearstats();
clearenvelope(e, false, rpool);
e->e_errormode = EM_MAIL;
GrabTo = UseErrorsTo = false;
if (forkflag)
{
disconnect(1, e);
}
if (LogLevel > 76)
(int) CurrentPid);
/* don't use the headers from sendmail.cf... */
/* read the queue control file -- return if locked */
if (!readqf(e, false))
{
sm_dprintf("readqf(%s) failed\n",
qid_printname(e));
if (forkflag)
else
{
/* adding this frees 8 bytes */
clearenvelope(e, false, rpool);
/* adding this frees 12 bytes */
return 0;
}
}
e->e_flags |= EF_INQUEUE;
eatheader(e, requeueflag, true);
if (requeueflag)
queueup(e, false, false);
/* do the delivery */
sendall(e, SM_DELIVER);
/* finish up and exit */
if (forkflag)
else
{
dropenvelope(e, true, false);
}
}
return pid;
}
/*
** DOWORKLIST -- process a list of envelopes as work requests
**
** Similar to dowork(), except that after forking, it processes an
** envelope and its siblings, treating each envelope as a work request.
**
** Parameters:
** el -- envelope to be processed including its siblings.
** forkflag -- if set, run this in background.
** requeueflag -- if set, reinstantiate the queue quickly.
** This is used when expanding aliases in the queue.
** If forkflag is also set, it doesn't wait for the
** child.
**
** Returns:
** process id of process that is running the queue job.
**
** Side Effects:
** The work request is satisfied if possible.
*/
bool forkflag;
bool requeueflag;
{
sm_dprintf("doworklist()\n");
/*
** Fork for work.
*/
if (forkflag)
{
/*
** Since the delivery may happen in a child and the
** parent does not wait, the parent may close the
** maps thereby removing any shared memory used by
** the map. Therefore, close the maps now so the
** child will dynamically open them if necessary.
*/
closemaps(false);
if (pid < 0)
{
syserr("doworklist: cannot fork");
return 0;
}
else if (pid > 0)
{
/* parent -- clean out connection cache */
}
else
{
/*
** Initialize exception stack and default exception
** handler for child process.
*/
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
CurrentPid = getpid();
/*
** See note above about SMTP processes and SIGCHLD.
*/
MaxQueueChildren > 0)
{
}
/* child -- error messages to the transcript */
QuickAbort = OnlyOneError = false;
}
}
else
{
pid = 0;
}
if (pid != 0)
return pid;
/*
** IN CHILD
** Lock the control file to avoid duplicate deliveries.
** Then run the file as though we had just read it.
** We save an idea of the temporary name so we
** can recover on interrupt.
*/
if (forkflag)
{
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
}
/* set basic modes, etc. */
clearstats();
GrabTo = UseErrorsTo = false;
if (forkflag)
{
}
if (LogLevel > 76)
(int) CurrentPid);
{
ENVELOPE e;
continue;
else if (QueueMode != QM_QUARANTINE &&
continue;
clearenvelope(&e, true, rpool);
set_delivery_mode(SM_DELIVER, &e);
e.e_errormode = EM_MAIL;
openxscript(&e);
/* don't use the headers from sendmail.cf... */
CurEnv = &e;
/* read the queue control file -- return if locked */
if (readqf(&e, false))
{
e.e_flags |= EF_INQUEUE;
eatheader(&e, requeueflag, true);
if (requeueflag)
queueup(&e, false, false);
/* do the delivery */
sendall(&e, SM_DELIVER);
dropenvelope(&e, true, false);
}
else
{
sm_dprintf("readqf(%s) failed\n",
qid_printname(&e));
}
}
/* restore CurEnv */
/* finish up and exit */
if (forkflag)
return 0;
}
/*
** READQF -- read queue file and set up environment.
**
** Parameters:
** e -- the envelope of the job to run.
** openonly -- only open the qf (returned as e_lockfp)
**
** Returns:
** true if it successfully read the queue file.
** false otherwise.
**
** Side Effects:
** The queue file is returned locked.
*/
static bool
register ENVELOPE *e;
bool openonly;
{
char *bp;
int qfver = 0;
long hdrsize = 0;
register char *p;
bool nomore = false;
bool bogus = false;
char *err;
char qf[MAXPATHLEN];
/*
** Read and process the file.
*/
{
int save_errno = errno;
sm_dprintf("readqf(%s): sm_io_open failure (%s)\n",
errno = save_errno;
)
return false;
}
{
/* being processed by another queuer */
if (Verbose)
"%s: locked\n", e->e_id);
if (LogLevel > 19)
return false;
}
/*
** Prevent locking race condition.
**
** Process A: readqf(): qfp = fopen(qffile)
** Process B: queueup(): rename(tf, qf)
** Process B: unlocks(tf)
** Process A: lockfile(qf);
**
** Process A (us) has the old qf file (before the rename deleted
** the directory entry) and will be delivering based on old data.
** This can lead to multiple deliveries of the same recipients.
**
** Catch this by checking if the underlying qf file has changed
** *after* acquiring our lock and if so, act as though the file
** was still locked (i.e., just return like the lockfile() case
** above.
*/
{
/* must have been being processed by someone else */
sm_dprintf("readqf(%s): [f]stat failure (%s)\n",
return false;
}
#if HAS_ST_GEN && 0 /* AFS returns garbage in st_gen */
#endif /* HAS_ST_GEN && 0 */
{
/* changed after opened */
if (Verbose)
"%s: changed\n", e->e_id);
if (LogLevel > 19)
return false;
}
/*
** Check the queue file for plausibility to avoid attacks.
*/
/*
** If this qf file results from a set-group-ID binary, then
** we check whether the directory is group-writable,
** the queue file mode contains the group-writable bit, and
** the groups are the same.
** Notice: this requires that the set-group-ID binary is used to
** run the queue!
*/
{
char delim;
delim = '\0';
else
{
*bp = '\0';
}
syserr("readqf: cannot stat directory %s",
else
{
}
if (delim != '\0')
}
if (!bogus)
if (bogus)
{
if (LogLevel > 0)
{
"bogus queue file, uid=%d, gid=%d, mode=%o",
}
e->e_flags |= EF_INQUEUE;
if (!openonly)
return false;
}
{
/* must be a bogus file -- if also old, just remove it */
{
}
return false;
}
{
/*
** Race condition -- we got a file just as it was being
** unlinked. Just assume it is zero length.
*/
return false;
}
#if _FFR_TRUSTED_QF
/*
** If we don't own the file mark it as unsafe.
** However, allow TrustedUser to own it as well
** in case TrustedUser manipulates the queue.
*/
#else /* _FFR_TRUSTED_QF */
/* If we don't own the file mark it as unsafe */
#endif /* _FFR_TRUSTED_QF */
/* good file -- save this lock */
/* Just wanted the open file */
if (openonly)
return true;
/* do basic system initialization */
initsys(e);
LineNumber = 0;
e->e_flags |= EF_GLOBALERRS;
#if _FFR_QUEUE_MACRO
#endif /* _FFR_QUEUE_MACRO */
e->e_dfino = -1;
e->e_msgsize = -1;
{
unsigned long qflags;
ADDRESS *q;
int r;
auto char *ep;
if (nomore)
{
/* hack attack */
syserr("SECURITY ALERT: extra or bogus data in queue file: %s",
bp);
err = "bogus queue line";
goto fail;
}
switch (bp[0])
{
case 'A': /* AUTH= parameter */
goto hackattack;
break;
case 'B': /* body type */
if (!BODYTYPE_VALID(r))
goto hackattack;
break;
case 'C': /* specify controlling user */
break;
case 'D': /* data file name */
/* obsolete -- ignore */
break;
case 'd': /* data file directory name */
{
/* forbid queue groups in MSP? */
if (UseMSP)
goto hackattack;
#endif /* _FFR_MSP_PARANOIA */
for (qgrp = 0;
++qgrp)
{
for (qdir = 0;
++qdir)
{
== 0)
{
goto done;
}
}
}
err = "bogus queue file directory";
goto fail;
done:
break;
}
case 'E': /* specify error recipient */
/* no longer used */
break;
case 'F': /* flag bits */
{
/* we are being spoofed! */
err = "bogus queue line";
goto fail;
}
{
switch (*p)
{
case '8': /* has 8 bit data */
e->e_flags |= EF_HAS8BIT;
break;
case 'b': /* delete Bcc: header */
e->e_flags |= EF_DELETE_BCC;
break;
case 'd': /* envelope has DSN RET= */
e->e_flags |= EF_RET_PARAM;
break;
case 'n': /* don't return body */
e->e_flags |= EF_NO_BODY_RETN;
break;
case 'r': /* response */
e->e_flags |= EF_RESPONSE;
break;
case 's': /* split */
break;
case 'w': /* warning sent */
e->e_flags |= EF_WARNING;
break;
}
}
break;
case 'q': /* quarantine reason */
break;
case 'H': /* header */
/*
** count size before chompheader() destroys the line.
** this isn't accurate due to macro expansion, but
** better than before. "-3" to skip H?? at least.
*/
break;
case 'I': /* data file's inode number */
/* regenerated below */
break;
case 'K': /* time of last delivery attempt */
break;
case 'L': /* Solaris Content-Length: */
case 'M': /* message */
/* ignore this; we want a new message next time */
break;
case 'N': /* number of delivery attempts */
/* if this has been tried recently, let it be */
{
char *howlong;
if (Verbose)
(void) sm_io_fprintf(smioout,
"%s: too young (%s)\n",
sm_dprintf("%s: too young (%s)\n",
if (LogLevel > 19)
"too young (%s)",
howlong);
unlockqueue(e);
return false;
}
#if NAMED_BIND
/* adjust BIND parameters immediately */
if (e->e_ntries == 0)
{
}
else
{
}
#endif /* NAMED_BIND */
break;
case 'P': /* message priority */
break;
case 'Q': /* original recipient */
break;
case 'r': /* final recipient */
break;
case 'R': /* specify recipient */
p = bp;
qflags = 0;
if (qfver >= 1)
{
/* get flag bits */
while (*++p != '\0' && *p != ':')
{
switch (*p)
{
case 'N':
qflags |= QHASNOTIFY;
break;
case 'S':
qflags |= QPINGONSUCCESS;
break;
case 'F':
qflags |= QPINGONFAILURE;
break;
case 'D':
qflags |= QPINGONDELAY;
break;
case 'P':
break;
case 'A':
break;
default: /* ignore or complain? */
break;
}
}
}
else
"e r");
if (*p != '\0')
NULL, e, true);
else
q = NULL;
if (q != NULL)
{
/* make sure we keep the current qgrp */
if (ISVALIDQGRP(e->e_qgrp))
if (qfver >= 1)
q->q_flags &= ~Q_PINGFLAGS;
q->q_finalrcpt = frcpt;
(void) recipient(q, &e->e_sendqueue, 0, e);
}
NULL);
break;
case 'S': /* sender */
e, NULL, '\0', true);
break;
case 'T': /* init time */
break;
case 'V': /* queue file version number */
if (qfver <= QF_VERSION)
break;
syserr("Version number in queue file (%d) greater than max (%d)",
qfver, QF_VERSION);
err = "unsupported queue file version";
goto fail;
/* NOTREACHED */
break;
case 'Z': /* original envelope id from ESMTP */
break;
case '!': /* deliver by */
/* format: flag (1 char) space long-integer */
case '$': /* define macro */
{
char *p;
/* XXX elimate p? */
if (r == 0)
break;
}
break;
case '.': /* terminate file */
nomore = true;
break;
#if _FFR_QUEUEDELAY
case 'G':
case 'Y':
/*
** Maintain backward compatibility for
** users who defined _FFR_QUEUEDELAY in
** previous releases. Remove this
** code in 8.14 or 8.15.
*/
break;
/* If not qfver 5 or 7, then 'G' or 'Y' is invalid */
/* FALLTHROUGH */
#endif /* _FFR_QUEUEDELAY */
default:
syserr("readqf: %s: line %d: bad line \"%s\"",
err = "unrecognized line";
goto fail;
}
{
}
}
/*
** If we haven't read any lines, this queue file is empty.
** Arrange to remove it without referencing any null pointers.
*/
if (LineNumber == 0)
{
errno = 0;
return true;
}
/* Check to make sure we have a complete queue file read */
if (!nomore)
{
return false;
}
/* possibly set ${dsn_ret} macro */
{
else
}
/*
** Arrange to read the data file.
*/
p = queuename(e, DATAFL_LETTER);
NULL);
{
syserr("readqf: cannot open %s", p);
}
else
{
>= 0)
{
e->e_msgsize);
buf);
}
}
return true;
fail:
/*
** There was some error reading the qf file (reason is in err var.)
** Cleanup:
** close file; clear e_lockfp since it is the same as qfp,
** hence it is invalid (as file) after qfp is closed;
** the qf file is on disk, so set the flag to avoid calling
** queueup() with bogus data.
*/
{
}
e->e_flags |= EF_INQUEUE;
return false;
}
/*
** PRTSTR -- print a string, "unprintable" characters are shown as \oct
**
** Parameters:
** s -- string to print
** ml -- maximum length of output
**
** Returns:
** number of entries
**
** Side Effects:
** Prints a string on stdout.
*/
static void
char *s;
int ml;
{
int c;
if (s == NULL)
return;
while (ml-- > 0 && ((c = *s++) != '\0'))
{
if (c == '\\')
{
if (ml-- > 0)
{
}
}
else
{
if ((ml -= 3) > 0)
"\\%03o", c & 0xFF);
}
}
}
/*
** PRINTNQE -- print out number of entries in the mail queue
**
** Parameters:
** out -- output file pointer.
** prefix -- string to output in front of each line.
**
** Returns:
** none.
*/
void
char *prefix;
{
#if SM_CONF_SHM
int i, k = 0, nrequests = 0;
bool unknown = false;
if (ShmId == SM_SHM_NO_ID)
{
"Data unavailable: shared memory not updated\n");
else
"%sNOTCONFIGURED:-1\r\n", prefix);
return;
}
{
int j;
k++;
for (j = 0; j < Queue[i]->qg_numqueues; j++)
{
int n;
if (StopRequest)
"%s%s:%d\r\n",
prefix, qid_printqueue(i, j), n);
else if (n < 0)
{
"%s: unknown number of entries\n",
qid_printqueue(i, j));
unknown = true;
}
else if (n == 0)
{
"%s is empty\n",
qid_printqueue(i, j));
}
else if (n > 0)
{
"%s: entries=%d\n",
qid_printqueue(i, j), n);
nrequests += n;
k++;
}
}
}
"\t\tTotal requests: %d%s\n",
#else /* SM_CONF_SHM */
"Data unavailable without shared memory support\n");
else
"%sNOTAVAILABLE:-1\r\n", prefix);
#endif /* SM_CONF_SHM */
}
/*
** PRINTQUEUE -- print out a representation of the mail queue
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** Prints a listing of the mail queue on the standard output.
*/
void
{
int i, k = 0, nrequests = 0;
{
int j;
k++;
for (j = 0; j < Queue[i]->qg_numqueues; j++)
{
if (StopRequest)
nrequests += print_single_queue(i, j);
k++;
}
}
if (k > 1)
"\t\tTotal requests: %d\n",
}
/*
** PRINT_SINGLE_QUEUE -- print out a representation of a single mail queue
**
** Parameters:
** qgrp -- the index of the queue group.
** qdir -- the queue directory.
**
** Returns:
** number of requests in mail queue.
**
** Side Effects:
** Prints a listing of the mail queue on the standard output.
*/
int
int qgrp;
int qdir;
{
register WORK *w;
SM_FILE_T *f;
int nrequests;
char qd[MAXPATHLEN];
char qddf[MAXPATHLEN];
{
}
else
{
? "/qf" : ""));
? "/df" : ""));
}
/*
** Check for permission to print the queue
*/
{
#ifdef NGROUPS_MAX
int n;
#endif /* NGROUPS_MAX */
{
syserr("Cannot stat %s",
return 0;
}
#ifdef NGROUPS_MAX
n = NGROUPS_MAX;
while (--n >= 0)
{
break;
}
#else /* NGROUPS_MAX */
#endif /* NGROUPS_MAX */
{
usrerr("510 You are not permitted to see the queue");
return 0;
}
}
/*
** Read and order the queue.
*/
/*
** Print the work list that we have read.
*/
/* first see if there is anything */
if (nrequests <= 0)
{
return 0;
}
sm_getla(); /* get load average */
", only %d printed", MaxQueueRun);
if (Verbose)
else
{
auto time_t submittime = 0;
long dfsize;
int flags = 0;
int qfver;
char qf[MAXPATHLEN];
if (StopRequest)
w->w_name + 2);
NULL);
if (f == NULL)
{
" (permission denied)\n");
" (job completed)\n");
else
" (%s)\n",
errno = 0;
continue;
}
w->w_name[0] = DATAFL_LETTER;
else
{
ENVELOPE e;
/*
** Maybe the df file can't be statted because
** it is in a different directory than the qf file.
** In order to find out, we must read the qf file.
*/
dfsize = -1;
if (readqf(&e, false))
{
}
{
}
clearenvelope(&e, false, e.e_rpool);
sm_rpool_free(e.e_rpool);
}
if (w->w_lock)
else if (w->w_tooyoung)
else
errno = 0;
quarmsg[0] = '\0';
qfver = 0;
{
register int i;
register char *p;
if (StopRequest)
switch (buf[0])
{
case 'V': /* queue file version */
break;
case 'M': /* error message */
i = sizeof statmsg - 1;
statmsg[i] = '\0';
break;
case 'q': /* quarantine reason */
i = sizeof quarmsg - 1;
quarmsg[i] = '\0';
break;
case 'B': /* body type */
i = sizeof bodytype - 1;
bodytype[i] = '\0';
break;
case 'S': /* sender name */
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"%8ld %10ld%c%.12s ",
w->w_pri,
? '+' : ' ',
}
else
{
(void) sm_io_fprintf(smioout,
"%8ld %.16s ",
ctime(&submittime));
}
if (quarmsg[0] != '\0')
{
(void) sm_io_fprintf(smioout,
"\n QUARANTINE: %.*s",
quarmsg);
quarmsg[0] = '\0';
}
{
(void) sm_io_fprintf(smioout,
"\n %10.10s",
bodytype);
if (statmsg[0] != '\0')
(void) sm_io_fprintf(smioout,
" (%.*s)",
statmsg);
statmsg[0] = '\0';
}
break;
case 'C': /* controlling user */
if (Verbose)
(void) sm_io_fprintf(smioout,
"\n\t\t\t\t\t\t(---%.64s---)",
&buf[1]);
break;
case 'R': /* recipient name */
p = &buf[1];
if (qfver >= 1)
{
p = strchr(p, ':');
if (p == NULL)
break;
p++;
}
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"\n\t\t\t\t\t\t");
prtstr(p, 71);
}
else
{
(void) sm_io_fprintf(smioout,
"\n\t\t\t\t\t ");
prtstr(p, 38);
}
{
(void) sm_io_fprintf(smioout,
"\n\t\t (%.100s)",
statmsg);
statmsg[0] = '\0';
}
break;
case 'T': /* creation time */
break;
case 'F': /* flag bits */
{
switch (*p)
{
case 'w':
flags |= EF_WARNING;
break;
}
}
}
}
if (submittime == (time_t) 0)
" (no control file)");
(void) sm_io_close(f, SM_TIME_DEFAULT);
}
return nrequests;
}
/*
** QUEUE_LETTER -- get the proper queue letter for the current QueueMode.
**
** Parameters:
** type -- the file type, used as the first character
** of the file name.
**
** Returns:
** the letter to use
*/
static char
queue_letter(e, type)
ENVELOPE *e;
int type;
{
/* Change type according to QueueMode */
if (type == ANYQFL_LETTER)
{
else
{
switch (QueueMode)
{
case QM_NORMAL:
break;
case QM_QUARANTINE:
break;
case QM_LOST:
break;
default:
/* should never happen */
abort();
/* NOTREACHED */
}
}
}
return type;
}
/*
** QUEUENAME -- build a file name in the queue directory for this envelope.
**
** Parameters:
** type -- the file type, used as the first character
** of the file name.
**
** Returns:
** a pointer to the queue name (in a static buffer).
**
** Side Effects:
** If no id code is already assigned, queuename() will
** assign an id code with assign_queueid(). If no queue
** directory is assigned, one will be set with setnewqueue().
*/
char *
register ENVELOPE *e;
int type;
{
char *sub = "/";
char pref[3];
static char buf[MAXPATHLEN];
/* Assign an ID if needed */
assign_queueid(e);
/* begin of filename */
if (type == XSCRPT_LETTER)
{
/*
** We don't want to call setnewqueue() if we are fetching
** the pathname of the transcript file, because setnewqueue
** chooses a queue, and sometimes we need to write to the
** transcript file before we have gathered enough information
** to choose a queue.
*/
{
{
}
else
{
e->e_xfqgrp = 0;
e->e_xfqdir = 0;
else
{
e->e_xfqdir = get_rand_mod(
}
}
}
}
else
{
(void) setnewqueue(e);
if (type == DATAFL_LETTER)
{
}
else
{
}
}
/* xf files always have a valid qd and qg picked above */
else
{
switch (type)
{
case DATAFL_LETTER:
sub = "/df/";
break;
case QUARQF_LETTER:
case TEMPQF_LETTER:
case NEWQFL_LETTER:
case LOSEQF_LETTER:
case NORMQF_LETTER:
sub = "/qf/";
break;
case XSCRPT_LETTER:
sub = "/xf/";
break;
default:
}
}
return buf;
}
/*
** INIT_QID_ALG -- Initialize the (static) parameters that are used to
** generate a queue ID.
**
** This function is called by the daemon to reset
** LastQueueTime and LastQueuePid which are used by assign_queueid().
** Otherwise the algorithm may cause problems because
** LastQueueTime and LastQueuePid are set indirectly by main()
** before the daemon process is started, hence LastQueuePid is not
** the pid of the daemon and therefore a child of the daemon can
** actually have the same pid as LastQueuePid which means the section
** in assign_queueid():
** is NOT triggered which will cause the same queue id to be generated.
**
** Parameters:
** none
**
** Returns:
** none.
*/
void
{
LastQueueTime = 0;
LastQueuePid = -1;
}
/*
** ASSIGN_QUEUEID -- assign a queue ID for this envelope.
**
** Assigns an id code if one does not already exist.
** This code assumes that nothing will remain in the queue for
** longer than 60 years. It is critical that files with the given
** name do not already exist in the queue.
** [No longer initializes e_qdir to NOQDIR.]
**
** Parameters:
** e -- envelope to set it in.
**
** Returns:
** none.
*/
static const char QueueIdChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
# define QIC_LEN 60
# define QIC_LEN_R 62
/*
** Note: the length is "officially" 60 because minutes and seconds are
** usually only 0-59. However (Linux):
** tm_sec The number of seconds after the minute, normally in
** the range 0 to 59, but can be up to 61 to allow for
** leap seconds.
** Hence the real length of the string is 62 to take this into account.
** Alternatively % QIC_LEN can (should) be used for access everywhere.
*/
# define queuenextid() CurrentPid
void
register ENVELOPE *e;
{
static int cX = 0;
static long random_offset;
int seq;
return;
LastQueuePid != pid)
{
/* if the first time through, pick a random offset */
if (LastQueueTime == 0)
random_offset = get_random();
LastQueuePid == pid)
{
(void) sleep(1);
}
LastQueuePid = queuenextid();
cX = 0;
}
/*
** Generate a new sequence number between 0 and QIC_LEN*QIC_LEN-1.
** This lets us generate up to QIC_LEN*QIC_LEN unique queue ids
** per second, per process. With envelope splitting,
** a single message can consume many queue ids.
*/
++cX;
sm_dprintf("assign_queueid: random_offset = %ld (%d)\n",
random_offset, seq);
(int) LastQueuePid);
#if 0
/* XXX: inherited from MainEnvelope */
#endif /* 0 */
/* New ID means it's not on disk yet */
e->e_qfletter = '\0';
sm_dprintf("assign_queueid: assigned id %s, e=%p\n",
e->e_id, e);
if (LogLevel > 93)
}
/*
** SYNC_QUEUE_TIME -- Assure exclusive PID in any given second
**
** Make sure one PID can't be used by two processes in any one second.
**
** If the system rotates PIDs fast enough, may get the
** same pid in the same second for two distinct processes.
** This will interfere with the queue file naming system.
**
** Parameters:
** none
**
** Returns:
** none
*/
void
{
#if FAST_PID_RECYCLE
LastQueueTime > 0 &&
LastQueuePid == CurrentPid &&
curtime() == LastQueueTime)
(void) sleep(1);
#endif /* FAST_PID_RECYCLE */
}
/*
** UNLOCKQUEUE -- unlock the queue entry for a specified envelope
**
** Parameters:
** e -- the envelope to unlock.
**
** Returns:
** none
**
** Side Effects:
** unlocks the queue for `e'.
*/
void
unlockqueue(e)
ENVELOPE *e;
{
sm_dprintf("unlockqueue(%s)\n",
/* if there is a lock file in the envelope, close it */
/* don't create a queue id if we don't already have one */
return;
/* remove the transcript */
if (LogLevel > 87)
}
/*
** SETCTLUSER -- create a controlling address
**
** Create a fake "address" given only a local login name; this is
** used as a "controlling user" for future recipient addresses.
**
** Parameters:
** user -- the user name of the controlling user.
** qfver -- the version stamp of this queue file.
** e -- envelope
**
** Returns:
** An address descriptor for the controlling user,
** using storage allocated from e->e_rpool.
**
*/
static ADDRESS *
char *user;
int qfver;
ENVELOPE *e;
{
register ADDRESS *a;
char *p;
/*
** See if this clears our concept of controlling user.
*/
return NULL;
/*
** Set up addr fields for controlling user.
*/
memset((char *) a, '\0', sizeof *a);
if (*user == ':')
{
p = &user[1];
}
else
{
if (qfver >= 2)
{
{
char *o;
/* if there is another ':': restore it */
o[-1] = ':';
}
}
{
a->q_home = "";
else
}
}
a->q_mailer = LocalMailer;
if (p == NULL)
else
return a;
}
/*
** LOSEQFILE -- rename queue file with LOSEQF_LETTER & try to let someone know
**
** Parameters:
** e -- the envelope (e->e_id will be used).
** why -- reported to whomever can hear.
**
** Returns:
** none.
*/
void
register ENVELOPE *e;
char *why;
{
bool loseit = true;
char *p;
char buf[MAXPATHLEN];
return;
p = queuename(e, ANYQFL_LETTER);
return;
queueup(e, false, true);
loseit = false;
/* if already lost, no need to re-lose */
if (loseit)
{
p = queuename(e, LOSEQF_LETTER);
syserr("cannot rename(%s, %s), uid=%d",
else if (LogLevel > 0)
}
{
}
}
/*
** NAME2QID -- translate a queue group name to a queue group id
**
** Parameters:
** queuename -- name of queue group.
**
** Returns:
** queue group id if found.
** NOQGRP otherwise.
*/
int
char *queuename;
{
register STAB *s;
if (s == NULL)
return NOQGRP;
}
/*
** QID_PRINTNAME -- create externally printable version of queue id
**
** Parameters:
** e -- the envelope.
**
** Returns:
** a printable version
*/
char *
ENVELOPE *e;
{
char *id;
if (e == NULL)
return "";
id = "";
else
return id;
id);
return idbuf;
}
/*
** QID_PRINTQUEUE -- create full version of queue directory for data files
**
** Parameters:
** qgrp -- index in queue group.
** qdir -- the short version of the queue directory
**
** Returns:
** the full pathname to the queue (might point to a static var)
*/
char *
int qgrp;
int qdir;
{
char *subdir;
static char dir[MAXPATHLEN];
else
? "/df" : ""));
return dir;
}
/*
** PICKQDIR -- Pick a queue directory from a queue group
**
** Parameters:
** qg -- queue group
** fsize -- file size in bytes
** e -- envelope, or NULL
**
** Result:
** NOQDIR if no queue directory in qg has enough free space to
** hold a file of size 'fsize', otherwise the index of
** a randomly selected queue directory which resides on a
** file system with enough disk space.
** XXX This could be extended to select a queuedir with
** a few (the fewest?) number of entries. That data
** is available if shared memory is used.
**
** Side Effects:
** If the request fails and e != NULL then sm_syslog is called.
*/
int
long fsize;
ENVELOPE *e;
{
int qdir;
int i;
long avail = 0;
/* Pick a random directory, as a starting point. */
qdir = 0;
else
if (MinBlocksFree <= 0 && fsize <= 0)
return qdir;
/*
** Now iterate over the queue directories,
** looking for a directory with enough space for this message.
*/
i = qdir;
do
{
long needed = 0;
long fsavail = 0;
if (fsize > 0)
> 0) ? 1 : 0);
if (MinBlocksFree > 0)
needed += MinBlocksFree;
#if SM_CONF_SHM
if (fsavail <= 0)
{
long blksize;
/*
** might be not correctly updated,
** let's try to get the info directly.
*/
&blksize);
if (fsavail < 0)
fsavail = 0;
}
#endif /* SM_CONF_SHM */
return i;
if (qg->qg_numqueues > 0)
} while (i != qdir);
"low on space (%s needs %ld bytes + %ld blocks in %s), max avail: %ld",
return NOQDIR;
}
/*
** SETNEWQUEUE -- Sets a new queue group and directory
**
** Assign a queue group and directory to an envelope and store the
** directory in e->e_qdir.
**
** Parameters:
** e -- envelope to assign a queue for.
**
** Returns:
** true if successful
** false otherwise
**
** Side Effects:
** On success, e->e_qgrp and e->e_qdir are non-negative.
** On failure (not enough disk space),
** e->qgrp = NOQGRP, e->e_qdir = NOQDIR
** and usrerr() is invoked (which could raise an exception).
*/
bool
setnewqueue(e)
ENVELOPE *e;
{
sm_dprintf("setnewqueue: called\n");
/* not set somewhere else */
{
ADDRESS *q;
/*
** Use the queue group of the "first" recipient, as set by
** the "queuegroup" rule set. If that is not defined, then
** use the queue group of the mailer of the first recipient.
** If that is not defined either, then use the default
** queue group.
** Notice: "first" depends on the sorting of sendqueue
** in recipient().
** To avoid problems with "bad" recipients look
** for a valid address first.
*/
q = e->e_sendqueue;
while (q != NULL &&
{
q = q->q_next;
}
if (q == NULL)
e->e_qgrp = 0;
else if (q->q_qgrp >= 0)
else
e->e_qgrp = 0;
}
{
sm_dprintf("setnewqueue: e_qdir already assigned (%s)\n",
return true;
}
{
usrerr("452 4.4.5 Insufficient disk space; try again later");
e->e_flags |= EF_FATALERRS;
return false;
}
sm_dprintf("setnewqueue: Assigned queue directory %s\n",
{
}
return true;
}
/*
** CHKQDIR -- check a queue directory
**
** Parameters:
** name -- name of queue directory
** sff -- flags for safefile()
**
** Returns:
** is it a queue directory?
*/
static bool
char *name;
long sff;
{
int i;
/* skip over . and .. directories */
if (name[0] == '.' &&
return false;
#if HASLSTAT
#else /* HASLSTAT */
#endif /* HASLSTAT */
{
sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
return false;
}
#if HASLSTAT
{
/*
** For a symlink we need to make sure the
** target is a directory
*/
{
sm_dprintf("chkqdir: stat(\"%s\"): %s\n",
return false;
}
}
#endif /* HASLSTAT */
{
sm_dprintf("chkqdir: \"%s\": Not a directory\n",
name);
return false;
}
/* Print a warning if unsafe (but still use it) */
/* XXX do this only if we want the warning? */
if (i != 0)
{
sm_dprintf("chkqdir: \"%s\": Not safe: %s\n",
name, sm_errstring(i));
#if _FFR_CHK_QUEUE
if (LogLevel > 8)
"queue directory \"%s\": Not safe: %s",
name, sm_errstring(i));
#endif /* _FFR_CHK_QUEUE */
}
return true;
}
/*
** MULTIQUEUE_CACHE -- cache a list of paths to queues.
**
** Each potential queue is checked as the cache is built.
** Thereafter, each is blindly trusted.
** Note that we can be called again after a timeout to rebuild
** (although code for that is not ready yet).
**
** Parameters:
** basedir -- base of all queue directories.
** blen -- strlen(basedir).
** qg -- queue group.
** qn -- number of queue directories already cached.
** phash -- pointer to hash value over queue dirs.
#if SM_CONF_SHM
** only used if shared memory is active.
#endif * SM_CONF_SHM *
**
** Returns:
** new number of queue directories.
*/
#define INITIAL_SLOTS 20
#define ADD_SLOTS 10
static int
char *basedir;
int blen;
int qn;
unsigned int *phash;
{
char *cp;
int i, len;
int slotsleft = 0;
long sff = SFF_ANYFILE;
char qpath[MAXPATHLEN];
char subdir[MAXPATHLEN];
sm_dprintf("multiqueue_cache: called\n");
/* Initialize to current directory */
prefix[0] = '.';
{
for (i = 0; i < qg->qg_numqueues; i++)
{
}
qg->qg_numqueues = 0;
}
/* If running as root, allow safedirpath() checks to use privs */
if (RunAsUid == 0)
sff |= SFF_ROOTOK;
#if _FFR_CHK_QUEUE
if (!UseMSP)
sff |= SFF_NOGWFILES;
#endif /* _FFR_CHK_QUEUE */
{
/*
** XXX we could add basedir, but then we have to realloc()
** the string... Maybe another time.
*/
return qn;
}
/* qpath: directory of current workgroup */
{
syserr("QueuePath %.256s too long (%d max)",
return qn;
}
/* begin of qpath must be same as basedir */
{
syserr("QueuePath %s not subpath of QueueDirectory %s",
return qn;
}
/* Do we have a nested subdirectory? */
{
/* Copy subdirectory into prefix for later use */
sizeof prefix)
{
syserr("QueuePath %.256s too long (%d max)",
return qn;
}
}
/* This is guaranteed by the basedir check above */
if (*cp == '*')
{
register struct dirent *d;
int off;
char *delim;
char relpath[MAXPATHLEN];
{
syserr("QueueDirectory: can not wildcard relative path");
sm_dprintf("multiqueue_cache: \"%s*\": Can not wildcard relative path.\n",
qpath);
return qn;
}
{
/*
** Special case of top level wildcard, like /foo*
** Change to //foo*
*/
++cp;
}
/*
** Path relative to basedir, with trailing /
** It will be modified below to specify the subdirectories
** so they can be opened without chdir().
*/
sm_dprintf("multiqueue_cache: prefix=\"%s%s\"\n",
/* It is always basedir: we don't need to store it per group */
/* XXX: optimize this! -> one more global? */
/*
** XXX Should probably wrap this whole loop in a timeout
** in case some wag decides to NFS mount the queues.
*/
/* Test path to get warning messages. */
if (qn == 0)
{
/* XXX qg_runasuid and qg_runasgid for specials? */
sff, 0, 0);
sm_dprintf("multiqueue_cache: \"%s\": Not safe: %s\n",
basedir, sm_errstring(i));
}
{
sm_dprintf("multiqueue_cache: opendir(\"%s/%s\"): %s\n",
return qn;
}
{
{
sm_dprintf("multiqueue_cache: \"%s\", skipped\n",
d->d_name);
continue;
}
/* Create relative pathname: prefix + local directory */
continue; /* way too long */
continue;
{
qg->qg_numqueues = 0;
}
else if (slotsleft < 1)
{
(qg->qg_numqueues +
ADD_SLOTS));
{
return qn;
}
}
/* check subdirs */
else
/* assert(strlen(d->d_name) < MAXPATHLEN - 14) */
/* maybe even - 17 (subdirs) */
if (prefix[0] != '.')
else
sm_dprintf("multiqueue_cache: %d: \"%s\" cached (%x).\n",
#if SM_CONF_SHM
#endif /* SM_CONF_SHM */
qg->qg_numqueues++;
++qn;
slotsleft--;
}
/* undo damage */
*delim = '/';
}
if (qg->qg_numqueues == 0)
{
/* test path to get warning messages */
if (i == ENOENT)
{
sm_dprintf("multiqueue_cache: opendir(\"%s\"): %s\n",
qpath, sm_errstring(i));
return qn;
}
/* check subdirs */
else
{
/*
** Copy the last component into qpaths and
** cut off qdir
*/
}
else
#if SM_CONF_SHM
#endif /* SM_CONF_SHM */
++qn;
}
return qn;
}
/*
** FILESYS_FIND -- find entry in FileSys table, or add new one
**
** Given the pathname of a directory, determine the file system
** in which that directory resides, and return a pointer to the
** entry in the FileSys table that describes the file system.
** A new entry is added if necessary (and requested).
** If the directory does not exist, -1 is returned.
**
** Parameters:
** name -- name of directory (must be persistent!)
** path -- pathname of directory (name plus maybe "/df")
** add -- add to structure if not found.
**
** Returns:
** >=0: found: index in file system table
** <0: some error, i.e.,
** FSF_TOO_MANY: too many filesystems (-> syserr())
** FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
** FSF_NOT_FOUND: not in list
*/
static short filesys_find __P((char *, char *, bool));
#define FSF_NOT_FOUND (-1)
#define FSF_STAT_FAIL (-2)
#define FSF_TOO_MANY (-3)
static short
char *name;
char *path;
bool add;
{
short i;
{
return FSF_STAT_FAIL;
}
for (i = 0; i < NumFileSys; ++i)
{
return i;
}
if (i >= MAXFILESYS)
{
return FSF_TOO_MANY;
}
if (!add)
return FSF_NOT_FOUND;
++NumFileSys;
FILE_SYS_NAME(i) = name;
FILE_SYS_AVAIL(i) = 0;
return i;
}
/*
** FILESYS_SETUP -- set up mapping from queue directories to file systems
**
** This data structure is used to efficiently check the amount of
** free space available in a set of queue directories.
**
** Parameters:
** add -- initialize structure if necessary.
**
** Returns:
** 0: success
** <0: some error, i.e.,
** FSF_NOT_FOUND: not in list
** FSF_STAT_FAIL: can't stat() filesystem (-> syserr())
** FSF_TOO_MANY: too many filesystems (-> syserr())
*/
static int filesys_setup __P((bool));
static int
bool add;
{
int i, j;
short fs;
int ret;
ret = 0;
{
for (j = 0; j < Queue[i]->qg_numqueues; ++j)
{
char qddf[MAXPATHLEN];
? "/df" : ""));
if (fs >= 0)
else
qp->qp_fsysidx = 0;
}
}
return ret;
}
/*
** FILESYS_UPDATE -- update amount of free space on all file systems
**
** The FileSys table is used to cache the amount of free space
** available on all queue directory file systems.
** This function updates the cached information if it has expired.
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** Updates FileSys table.
*/
void
{
int i;
static time_t nextupdate = 0;
#if SM_CONF_SHM
/* only the daemon updates this structure */
return;
#endif /* SM_CONF_SHM */
if (now < nextupdate)
return;
for (i = 0; i < NumFileSys; ++i)
{
{
if (LogLevel > 5)
"filesys_update failed: %s, fs=%s, avail=%ld, blocksize=%ld",
}
else
{
}
}
}
#if _FFR_ANY_FREE_FS
/*
** FILESYS_FREE -- check whether there is at least one fs with enough space.
**
** Parameters:
** fsize -- file size in bytes
**
** Returns:
** true iff there is one fs with more than fsize bytes free.
*/
bool
long fsize;
{
int i;
if (fsize <= 0)
return true;
for (i = 0; i < NumFileSys; ++i)
{
long needed = 0;
if (FILE_SYS_AVAIL(i) < 0 || FILE_SYS_BLKSIZE(i) <= 0)
continue;
+ ((fsize % FILE_SYS_BLKSIZE(i)
> 0) ? 1 : 0)
if (needed <= FILE_SYS_AVAIL(i))
return true;
}
return false;
}
#endif /* _FFR_ANY_FREE_FS */
/*
** DISK_STATUS -- show amount of free space in queue directories
**
** Parameters:
** out -- output file pointer.
** prefix -- string to output in front of each line.
**
** Returns:
** none.
*/
void
char *prefix;
{
int i;
long free;
for (i = 0; i < NumFileSys; ++i)
{
{
((double) blksize / 1024));
}
else
free = -1;
"%s%d/%s/%ld\r\n",
prefix, i,
FILE_SYS_NAME(i),
free);
}
}
#endif /* _FFR_CONTROL_MSTAT */
#if SM_CONF_SHM
/*
** INIT_SEM -- initialize semaphore system
**
** Parameters:
** owner -- is this the owner of semaphores?
**
** Returns:
** none.
*/
#if SM_CONF_SEM
int SemKey = SM_SEM_KEY;
#endif /* SM_CONF_SEM */
#endif /* _FFR_USE_SEM_LOCKING */
static void
bool owner;
{
#if SM_CONF_SEM
if (SemId < 0)
{
"func=init_sem, sem_key=%ld, sm_sem_start=%d",
return;
}
#endif /* SM_CONF_SEM */
#endif /* _FFR_USE_SEM_LOCKING */
return;
}
/*
** STOP_SEM -- stop semaphore system
**
** Parameters:
** owner -- is this the owner of semaphores?
**
** Returns:
** none.
*/
static void
bool owner;
{
#if SM_CONF_SEM
#endif /* SM_CONF_SEM */
#endif /* _FFR_USE_SEM_LOCKING */
return;
}
/*
**
** Parameters:
** e -- envelope.
** space -- update the space available as well.
** where -- caller (for logging)
**
** Returns:
** none.
**
** Side Effects:
** Modifies available space in filesystem.
** Changes number of entries in queue directory.
*/
void
ENVELOPE *e;
int count;
int space;
char *where;
{
short fidx;
int idx;
# if _FFR_USE_SEM_LOCKING
int r;
# endif /* _FFR_USE_SEM_LOCKING */
long s;
return;
return;
sm_dprintf("func=upd_qs, count=%d, space=%d, where=%s, idx=%d, entries=%d\n",
/* XXX in theory this needs to be protected with a mutex */
{
# if _FFR_USE_SEM_LOCKING
# endif /* _FFR_USE_SEM_LOCKING */
# if _FFR_USE_SEM_LOCKING
if (r >= 0)
# endif /* _FFR_USE_SEM_LOCKING */
}
if (fidx < 0)
return;
/* update available space also? (might be loseqfile) */
if (space == 0)
return;
/* convert size to blocks; this causes rounding errors */
if (s == 0)
return;
/* XXX in theory this needs to be protected with a mutex */
if (space > 0)
FILE_SYS_AVAIL(fidx) += s;
else
FILE_SYS_AVAIL(fidx) -= s;
}
#if _FFR_SELECT_SHM
static bool write_key_file __P((char *, long));
static long read_key_file __P((char *, long));
/*
** WRITE_KEY_FILE -- record some key into a file.
**
** Parameters:
** keypath -- file name.
** key -- key to write.
**
** Returns:
** true iff file could be written.
**
** Side Effects:
** writes file.
*/
static bool
char *keypath;
long key;
{
bool ok;
long sff;
ok = false;
return ok;
sff |= SFF_OPENASROOT;
{
}
else
{
{
# if HASFCHOWN
int fd;
{
"ownership change on %s to %d failed: %s",
}
# endif /* HASFCHOWN */
}
}
return ok;
}
/*
** READ_KEY_FILE -- read a key from a file.
**
** Parameters:
** keypath -- file name.
** key -- default key.
**
** Returns:
** key.
*/
static long
char *keypath;
long key;
{
int r;
long sff, n;
return key;
sff |= SFF_OPENASROOT;
{
}
else
{
if (r == 1)
key = n;
}
return key;
}
#endif /* _FFR_SELECT_SHM */
/*
** INIT_SHM -- initialize shared memory structure
**
** Initialize or attach to shared memory segment.
** Currently it is not a fatal error if this doesn't work.
** However, it causes us to have a "fallback" storage location
** for everything that is supposed to be in the shared memory,
** which makes the code slightly ugly.
**
** Parameters:
** qn -- number of queue directories.
** owner -- owner of shared memory.
** hash -- identifies data that is stored in shared memory.
**
** Returns:
** none.
*/
static void
int qn;
bool owner;
unsigned int hash;
{
int i;
int count;
int save_errno;
#if _FFR_SELECT_SHM
bool keyselect;
#endif /* _FFR_SELECT_SHM */
PtrFileSys = &FileSys[0];
#if _FFR_SELECT_SHM
/* if this "key" is specified: select one yourself */
# define FIRST_SHM_KEY 25
#endif /* _FFR_SELECT_SHM */
/* This allows us to disable shared memory at runtime. */
if (ShmKey == 0)
return;
count = 0;
#if _FFR_SELECT_SHM
if (keyselect)
{
if (owner)
else
{
keyselect = false;
if (ShmKey == SEL_SHM_KEY)
goto error;
}
}
#endif /* _FFR_SELECT_SHM */
for (;;)
{
save_errno = errno;
break;
if (++count >= 3)
{
#if _FFR_SELECT_SHM
if (keyselect)
{
++ShmKey;
/* back where we started? */
if (ShmKey == SEL_SHM_KEY)
break;
continue;
}
#endif /* _FFR_SELECT_SHM */
break;
}
#if _FFR_SELECT_SHM
/* only sleep if we are at the first key */
#endif /* _FFR_SELECT_SHM */
}
{
int *p;
#if _FFR_SELECT_SHM
if (keyselect)
#endif /* _FFR_SELECT_SHM */
{
if (i != 0)
"key=%ld, sm_shmsetowner=%d, RunAsUid=%d, RunAsGid=%d",
}
p = (int *) Pshm;
if (owner)
{
*p = (int) shms;
p = (int *) SHM_OFF_TAG(Pshm);
*p = hash;
}
else
{
if (*p != (int) shms)
{
save_errno = EINVAL;
cleanup_shm(false);
goto error;
}
p = (int *) SHM_OFF_TAG(Pshm);
if (*p != (int) hash)
{
save_errno = EINVAL;
cleanup_shm(false);
goto error;
}
/*
** XXX how to check the pid?
** Read it from the pid-file? That does
** not need to exist.
** We could disable shm if we can't confirm
** that it is the right one.
*/
}
*PRSATmpCnt = 0;
if (owner)
{
/* initialize values in shared memory */
NumFileSys = 0;
for (i = 0; i < qn; i++)
}
return;
}
{
"can't %s shared memory, key=%ld: %s",
}
}
#endif /* SM_CONF_SHM */
/*
** SETUP_QUEUES -- setup all queue groups
**
** Parameters:
** owner -- owner of shared memory.
**
** Returns:
** none.
**
#if SM_CONF_SHM
** Side Effects:
** attaches shared memory.
#endif * SM_CONF_SHM *
*/
void
bool owner;
{
unsigned int hashval;
char basedir[MAXPATHLEN];
/*
** Determine basedir for all queue directories.
** All queue directories must be (first level) subdirectories
** of the basedir. The basedir is the QueueDir
** without wildcards, but with trailing /
*/
hashval = 0;
errno = 0;
/* Provide space for trailing '/' */
{
syserr("QueueDirectory: path too long: %d, max %d",
return;
}
{
char *cp;
{
syserr("QueueDirectory: can not wildcard relative path \"%s\"",
QueueDir);
sm_dprintf("setup_queues: \"%s\": Can not wildcard relative path.\n",
QueueDir);
return;
}
/* cut off wildcard pattern */
*++cp = '\0';
}
{
/* append trailing slash since it is a directory */
}
/* len counts up to the last directory delimiter */
{
int save_errno = errno;
if (save_errno == EACCES)
"Program mode requires special privileges, e.g., root or TrustedUser.\n");
sm_dprintf("setup_queues: \"%s\": %s\n",
return;
}
#if SM_CONF_SHM
#endif /* SM_CONF_SHM */
/* initialize for queue runs */
DoQueueRun = false;
{
{
sm_dprintf("setup_queues: \"%s\": %s\n",
return;
}
if (RunAsUid == 0)
sff |= SFF_ROOTOK;
/*
** Check queue directory permissions.
** Can we write to a group writable queue directory?
*/
QueueFileMode, NULL) != 0)
{
syserr("can not write to queue directory %s (RunAsGid=%d, required=%d)",
}
{
syserr("dangerous permissions=%o on queue directory %s",
#else /* _FFR_MSP_PARANOIA */
if (LogLevel > 0)
"dangerous permissions=%o on queue directory %s",
#endif /* _FFR_MSP_PARANOIA */
}
if (NumQueue > 1)
syserr("can not use multiple queues for MSP");
#endif /* _FFR_MSP_PARANOIA */
}
/* initial number of queue directories */
qn = 0;
#if SM_CONF_SHM
if (i == FSF_NOT_FOUND)
{
/*
** We didn't get the right filesystem data
** This may happen if we don't have the right shared memory.
** So let's do this without shared memory.
*/
cleanup_shm(false); /* release shared memory */
i = filesys_setup(false);
if (i < 0)
syserr("filesys_setup failed twice, result=%d", i);
else if (LogLevel > 8)
"shared memory does not contain expected data, ignored");
}
#else /* SM_CONF_SHM */
i = filesys_setup(true);
#endif /* SM_CONF_SHM */
if (i < 0)
}
#if SM_CONF_SHM
/*
** CLEANUP_SHM -- do some cleanup work for shared memory etc
**
** Parameters:
** owner -- owner of shared memory?
**
** Returns:
** none.
**
** Side Effects:
** detaches shared memory.
*/
void
bool owner;
{
if (ShmId != SM_SHM_NO_ID)
{
}
}
#endif /* SM_CONF_SHM */
/*
** CLEANUP_QUEUES -- do some cleanup work for queues
**
** Parameters:
** none.
**
** Returns:
** none.
**
*/
void
{
}
/*
** SET_DEF_QUEUEVAL -- set default values for a queue group.
**
** Parameters:
** qg -- queue group
** all -- set all values (true for default group)?
**
** Returns:
** none.
**
** Side Effects:
** sets default values for the queue group.
*/
void
bool all;
{
return;
if (all)
#endif /* _FFR_QUEUE_GROUP_SORTORDER */
}
/*
** MAKEQUEUE -- define a new queue.
**
** Parameters:
** line -- description of queue. This is in labeled fields.
** The fields are:
** F -- the flags associated with the queue
** I -- the interval between running the queue
** J -- the maximum # of jobs in work list
** [M -- the maximum # of jobs in a queue run]
** N -- the niceness at which to run
** P -- the path to the queue
** S -- the queue sorting order
** R -- number of parallel queue runners
** r -- max recipients per envelope
** The first word is the canonical name of the queue.
** qdef -- this is a 'Q' definition from .cf
**
** Returns:
** none.
**
** Side Effects:
** enters the queue into the queue table.
*/
void
char *line;
bool qdef;
{
register char *p;
register STAB *s;
int i;
char fcode;
/* allocate a queue and set up defaults */
if (line[0] == '\0')
{
syserr("name required for queue");
return;
}
/* collect the queue name */
for (p = line;
p++)
continue;
if (*p != '\0')
*p++ = '\0';
/* set default values, can be overridden below */
set_def_queueval(qg, false);
/* now scan through and assign info from the fields */
while (*p != '\0')
{
auto char *delimptr;
while (*p != '\0' &&
p++;
/* p now points to field code */
fcode = *p;
while (*p != '\0' && *p != '=' && *p != ',')
p++;
if (*p++ != '=')
{
return;
}
p++;
/* p now points to the field body */
/* install the field into the queue struct */
switch (fcode)
{
case 'P': /* pathname */
if (*p == '\0')
syserr("queue %s: empty path name",
else
break;
case 'F': /* flags */
for (; *p != '\0'; p++)
break;
/*
** Do we need two intervals here:
** One for persistent queue runners,
** one for "normal" queue runs?
*/
case 'I': /* interval between running the queue */
break;
case 'N': /* run niceness */
break;
case 'R': /* maximum # of runners for the group */
i = atoi(p);
/* can't have more runners than allowed total */
if (MaxQueueChildren > 0 && i > MaxQueueChildren)
{
"Q=%s: R=%d exceeds MaxQueueChildren=%d, set to MaxQueueChildren\n",
}
else
qg->qg_maxqrun = i;
break;
case 'J': /* maximum # of jobs in work list */
break;
case 'r': /* max recipients per envelope */
break;
case 'S': /* queue sorting order */
switch (*p)
{
case 'h': /* Host first */
case 'H':
break;
case 'p': /* Priority order */
case 'P':
break;
case 't': /* Submission time */
case 'T':
break;
case 'f': /* File name */
case 'F':
break;
case 'm': /* Modification time */
case 'M':
break;
case 'r': /* Random */
case 'R':
break;
# if _FFR_RHS
case 's': /* Shuffled host name */
case 'S':
break;
# endif /* _FFR_RHS */
case 'n': /* none */
case 'N':
break;
default:
syserr("Invalid queue sort order \"%s\"", p);
}
break;
#endif /* _FFR_QUEUE_GROUP_SORTORDER */
default:
syserr("Q%s: unknown queue equate %c=",
break;
}
p = delimptr;
}
#if !HASNICE
{
"Q%s: Warning: N= set on system that doesn't support nice()\n",
}
#endif /* !HASNICE */
/* do some rationality checking */
if (NumQueue >= MAXQUEUEGROUPS)
{
syserr("too many queue groups defined (%d max)",
return;
}
{
{
syserr("QueueDir must be defined before queue groups");
return;
}
}
{
"Warning: Q=%s: R=%d: multiple queue runners specified\n\tbut flag '%c' is not set\n",
}
/* enter the queue into the symbol table */
{
/* XXX what about the pointers inside this struct? */
}
else
i = NumQueue++;
/* set default value for max queue runners */
if (qg->qg_maxqrun < 0)
{
if (MaxRunnersPerQueue > 0)
else
}
if (qdef)
}
#if 0
/*
** HASHFQN -- calculate a hash value for a fully qualified host name
**
** Arguments:
** fqn -- an all lower-case host.domain string
** buckets -- the number of buckets (queue directories)
**
** Returns:
** a bucket number (signed integer)
** -1 on error
**
** Contributed by Exactis.com, Inc.
*/
int
register char *fqn;
int buckets;
{
register char *p;
return -1;
/*
** A variation on the gdb hash
** This is the best as of Feb 19, 1996 --bcx
*/
p = fqn;
h = 0x238F13AF * strlen(p);
{
}
h = (1103515243 * h + 12345) & 0x7FFFFFFF;
if (buckets < 2)
hash = 0;
else
return hash;
}
#endif /* 0 */
/*
** A structure for sorting Queue according to maxqrun without
** screwing up Queue itself.
*/
struct sortqgrp
{
int sg_idx; /* original index */
int sg_maxqrun; /* max queue runners */
};
typedef struct sortqgrp SORTQGRP_T;
static int
cmpidx(a, b)
const void *a;
const void *b;
{
/* The sort is highest to lowest, so the comparison is reversed */
return 1;
return -1;
else
return 0;
}
/*
** MAKEWORKGROUP -- balance queue groups into work groups per MaxQueueChildren
**
** Take the now defined queue groups and assign them to work groups.
** This is done to balance out the number of concurrently active
** queue runners such that MaxQueueChildren is not exceeded. This may
** result in more than one queue group per work group. In such a case
** the number of running queue groups in that work group will have no
** more than the work group maximum number of runners (a "fair" portion
** of MaxQueueRunners). All queue groups within a work group will get a
** chance at running.
**
** Parameters:
** none.
**
** Returns:
** nothing.
**
** Side Effects:
** Sets up WorkGrp structure.
*/
void
{
int i, j, total_runners, dir, h;
total_runners = 0;
{
/*
** There is only the "mqueue" queue group (a default)
** containing all of the queues. We want to provide to
** this queue group the maximum allowable queue runners.
** To match older behavior (8.10/8.11) we'll try for
** 1 runner per queue capping it at MaxQueueChildren.
** So if there are N queues, then there will be N runners
** for the "mqueue" queue group (where N is kept less than
** MaxQueueChildren).
*/
NumWorkGroups = 1;
if (MaxQueueChildren > 0 &&
else
/* can't have more runners than allowed total */
if (MaxQueueChildren > 0 &&
return;
}
for (i = 0; i < NumQueue; i++)
{
}
NumWorkGroups = 0;
for (i = 0; i < NumQueue; i++)
{
else
break;
}
if (NumWorkGroups < 1)
else if (NumWorkGroups > MAXWORKGROUPS)
/*
** We now know the number of work groups to pack the queue groups
** into. The queue groups in 'Queue' are sorted from highest
** to lowest for the number of runners per queue group.
** We put the queue groups with the largest number of runners
** into work groups first. Then the smaller ones are fitted in
** where it looks best.
*/
j = 0;
dir = 1;
for (i = 0; i < NumQueue; i++)
{
/* a to-and-fro packing scheme, continue from last position */
if (j >= NumWorkGroups)
{
dir = -1;
j = NumWorkGroups - 1;
}
else if (j < 0)
{
j = 0;
dir = 1;
}
else
sizeof(QUEUEGRP *) *
{
syserr("!cannot allocate memory for work queues, need %d bytes",
(int) (sizeof(QUEUEGRP *) *
}
WorkGrp[j].wg_numqgrp++;
{
/* can't have more runners than allowed total */
if (MaxQueueChildren > 0 &&
}
/*
** XXX: must wg_lowqintvl be the GCD?
** qg1: 2m, qg2: 3m, minimum: 2m, when do queue runs for
** qg2 occur?
*/
/* keep track of the lowest interval for a persistent runner */
if (Queue[h]->qg_queueintvl > 0 &&
j += dir;
}
{
for (i = 0; i < NumWorkGroups; i++)
{
sm_dprintf("Workgroup[%d]=", i);
for (j = 0; j < WorkGrp[i].wg_numqgrp; j++)
{
sm_dprintf("%s, ",
}
sm_dprintf("\n");
}
}
}
/*
** DUP_DF -- duplicate envelope data file
**
** Copy the data file from the 'old' envelope to the 'new' envelope
** in the most efficient way possible.
**
** Create a hard link from the 'old' data file to the 'new' data file.
** If the old and new queue directories are on different file systems,
** then the new data file link is created in the old queue directory,
** and the new queue file will contain a 'd' record pointing to the
** directory containing the new data file.
**
** Parameters:
** old -- old envelope.
** new -- new envelope.
**
** Results:
** Returns true on success, false on failure.
**
** Side Effects:
** On success, the new data file is created.
** On fatal failure, EF_FATALERRS is set in old->e_flags.
*/
static bool
{
char opath[MAXPATHLEN];
char npath[MAXPATHLEN];
{
/*
** this can happen if: SuperSafe != True
** and a bounce mail is sent that is split.
*/
}
{
{
return false;
}
}
/*
** Attempt to create a hard link, if we think both old and new
** are on the same file system, otherwise copy the file.
**
** Don't waste time attempting a hard link unless old and new
** are on the same file system.
*/
{
{
return true;
}
goto error;
}
/*
** Can't link across queue directories, so try to create a hard
** link in the same queue directory as the old df file.
** The qf file will refer to the new df file using a 'd' record.
*/
{
return true;
}
if (LogLevel > 0)
"dup_df: can't link %s to %s, error=%s, envelope splitting failed",
return false;
}
/*
** SPLIT_ENV -- Allocate a new envelope based on a given envelope.
**
** Parameters:
** e -- envelope.
** sendqueue -- sendqueue for new envelope.
** qgrp -- index of queue group.
** qdir -- queue directory.
**
** Results:
** new envelope.
**
*/
static ENVELOPE *
ENVELOPE *e;
int qgrp;
int qdir;
{
STRUCTCOPY(*e, *ee);
/* failed to dup e->e_xfp, start a new transcript */
e->e_quarmsg);
/*
** XXX Not sure if this copying is necessary.
** sendall() does this copying, but I (dm) don't know if that is
** because of the storage management discipline we were using
** before rpools were introduced, or if it is because these lists
** can be modified later.
*/
return ee;
}
/* return values from split functions, check also below! */
#define SM_SPLIT_FAIL (0)
#define SM_SPLIT_NONE (1)
#define SM_SPLIT_NEW(n) (1 + (n))
/*
** SPLIT_ACROSS_QUEUE_GROUPS
**
** This function splits an envelope across multiple queue groups
** based on the queue group of each recipient.
**
** Parameters:
** e -- envelope.
**
** Results:
** SM_SPLIT_FAIL on failure
** SM_SPLIT_NONE if no splitting occurred,
** or 1 + the number of additional envelopes created.
**
** Side Effects:
** On success, e->e_sibling points to a list of zero or more
** additional envelopes, and the associated data files exist
** on disk. But the queue files are not created.
**
** On failure, e->e_sibling is not changed.
** The order of recipients in e->e_sendqueue is permuted.
** Abandoned data files for additional envelopes that failed
** to be created may exist on disk.
*/
static int q_qgrp_compare __P((const void *, const void *));
static int e_filesys_compare __P((const void *, const void *));
static int
const void *p1;
const void *p2;
{
}
static int
const void *p1;
const void *p2;
{
return -1;
return 1;
return 0;
}
static int
ENVELOPE *e;
{
bool changed;
char **pvp;
/* Count addresses and assign queue groups. */
naddrs = 0;
changed = false;
{
if (QS_IS_DEAD(q->q_state))
continue;
++naddrs;
/* bad addresses and those already sent stay put */
if (QS_IS_BADADDR(q->q_state) ||
QS_IS_SENT(q->q_state))
else if (!ISVALIDQGRP(q->q_qgrp))
{
/* call ruleset which should return a queue group */
if (i == EX_OK &&
{
if (ISVALIDQGRP(i))
{
q->q_qgrp = i;
changed = true;
"queue group name %s -> %d",
pvp[1], i);
continue;
}
else if (LogLevel > 10)
"can't find queue group name %s, selection ignored",
pvp[1]);
}
{
changed = true;
}
else if (ISVALIDQGRP(e->e_qgrp))
else
q->q_qgrp = 0;
}
}
/* only one address? nothing to split. */
return SM_SPLIT_NONE;
/* sort the addresses by queue group */
{
if (QS_IS_DEAD(q->q_state))
continue;
addrs[i++] = q;
}
/* split into multiple envelopes, by queue group */
nsplits = 0;
e->e_sendqueue = NULL;
for (i = 0; i < naddrs; ++i)
{
else
/* same queue group as original envelope? */
{
if (e->e_sendqueue == NULL)
e->e_sendqueue = addrs[i];
continue;
}
/* different queue group than original envelope */
{
}
}
/* no splits? return right now. */
if (nsplits <= 0)
return SM_SPLIT_NONE;
/* assign a queue directory to each additional envelope */
for (i = 0; i < nsplits; ++i)
{
#if 0
#endif /* 0 */
if (!setnewqueue(es))
goto failure;
}
/* sort the additional envelopes by queue file system */
/* create data files for each additional envelope */
{
i = 0;
goto failure;
}
for (i = 1; i < nsplits; ++i)
{
/* copy or link to the previous data file */
goto failure;
}
/* success: prepend the new envelopes to the e->e_sibling list */
for (i = 0; i < nsplits; ++i)
{
}
return SM_SPLIT_NEW(nsplits);
/* failure: clean up */
if (i > 0)
{
int j;
for (j = 0; j < i; j++)
}
e->e_sendqueue = addrs[0];
for (i = 0; i < naddrs - 1; ++i)
return SM_SPLIT_FAIL;
}
/*
** SPLIT_WITHIN_QUEUE
**
** Split an envelope with multiple recipients into several
** envelopes within the same queue directory, if the number of
** recipients exceeds the limit for the queue group.
**
** Parameters:
** e -- envelope.
**
** Results:
** SM_SPLIT_FAIL on failure
** SM_SPLIT_NONE if no splitting occurred,
** or 1 + the number of additional envelopes created.
*/
#define SPLIT_LOG_LEVEL 8
static int
ENVELOPE *e;
{
int j, l;
char *lsplits;
return SM_SPLIT_NONE;
/* don't bother if there is no recipient limit */
if (maxrcpt <= 0)
return SM_SPLIT_NONE;
/* count recipients */
nrcpt = 0;
{
if (QS_IS_DEAD(q->q_state))
continue;
++nrcpt;
}
return SM_SPLIT_NONE;
/*
** Preserve the recipient list
** so that we can restore it in case of error.
** (But we discard dead addresses.)
*/
{
if (QS_IS_DEAD(q->q_state))
continue;
addrs[i++] = q;
}
/*
** Partition the recipient list so that bad and sent addresses
** come first. These will go with the original envelope, and
** do not count towards the maxrcpt limit.
** addrs[] does not contain QS_IS_DEAD() addresses.
*/
ndead = 0;
for (i = 0; i < nrcpt; ++i)
{
{
if (i > ndead)
{
}
++ndead;
}
}
/* Check if no splitting required. */
return SM_SPLIT_NONE;
/* fix links */
for (i = 0; i < nrcpt - 1; ++i)
e->e_sendqueue = addrs[0];
/* prepare buffer for logging */
if (LogLevel > SPLIT_LOG_LEVEL)
{
l = MAXLINE;
*lsplits = '\0';
j = 0;
}
else
{
/* get rid of stupid compiler warnings */
j = l = 0;
}
/* split the envelope */
firstsibling = e->e_sibling;
nsplit = 0;
for (;;)
{
{
ee = firstsibling;
{
}
/* Error. Restore e's sibling & recipient lists. */
e->e_sibling = firstsibling;
for (i = 0; i < nrcpt - 1; ++i)
return SM_SPLIT_FAIL;
}
/* prepend the new envelope to e->e_sibling */
++nsplit;
{
{
char *p;
l += MAXLINE;
p = sm_realloc(lsplits, l);
if (p == NULL)
{
/* let's try to get this done */
}
else
lsplits = p;
}
{
if (j == 0)
j += sm_strlcat(lsplits + j,
l - j);
else
j += sm_strlcat2(lsplits + j,
"; ",
l - j);
SM_ASSERT(j < l);
}
}
break;
i += maxrcpt;
}
{
if (nsplit > 0)
{
"split: maxrcpts=%d, rcpts=%d, count=%d, id%s=%s",
}
}
return SM_SPLIT_NEW(nsplit);
}
/*
** SPLIT_BY_RECIPIENT
**
** Split an envelope with multiple recipients into multiple
** envelopes as required by the sendmail configuration.
**
** Parameters:
** e -- envelope.
**
** Results:
** Returns true on success, false on failure.
**
** Side Effects:
** see split_across_queue_groups(), split_within_queue(e)
*/
bool
ENVELOPE *e;
{
int split, n, i, j, l;
char *lsplits;
return true;
n = split_across_queue_groups(e);
if (n == SM_SPLIT_FAIL)
return false;
{
l = MAXLINE;
*lsplits = '\0';
j = 0;
}
else
{
/* get rid of stupid compiler warnings */
j = l = 0;
}
for (i = 1; i < n; ++i)
{
{
e->e_sibling = firstsibling;
return false;
}
{
{
char *p;
l += MAXLINE;
p = sm_realloc(lsplits, l);
if (p == NULL)
{
/* let's try to get this done */
}
else
lsplits = p;
}
{
if (j == 0)
j += sm_strlcat(lsplits + j,
else
SM_ASSERT(j < l);
}
}
}
{
}
if (split)
return split;
}
/*
** QUARANTINE_QUEUE_ITEM -- {un,}quarantine a single envelope
**
**
** Parameters:
** qgrp -- queue group for the item
** qdir -- queue directory in the given queue group
** e -- envelope information for the item
** reason -- quarantine reason, NULL means unquarantine.
**
** Results:
** true if item changed, false otherwise
**
** Side Effects:
** Changes quarantine tag in queue file and renames it.
*/
static bool
int qgrp;
int qdir;
ENVELOPE *e;
char *reason;
{
bool dirty = false;
bool failing = false;
bool foundq = false;
bool finished = false;
int fd;
int flags;
int oldtype;
int newtype;
int save_errno;
char *bp;
char oldqf[MAXPATHLEN];
char tempqf[MAXPATHLEN];
char newqf[MAXPATHLEN];
/*
** Instead of duplicating all the open
** and lock code here, tell readqf() to
** do that work and return the open
** file pointer in e_lockfp. Note that
** we must release the locks properly when
** we are done.
*/
if (!readqf(e, true))
{
"Skipping %s\n", qid_printname(e));
return false;
}
/* open the new queue file */
if (fd < 0)
{
save_errno = errno;
"Skipping %s: Could not open %s: %s\n",
qid_printname(e), tempqf,
return false;
}
{
"Skipping %s: Could not lock %s\n",
qid_printname(e), tempqf);
return false;
}
{
"Skipping %s: Could not lock %s\n",
qid_printname(e), tempqf);
return false;
}
/* Copy the data over, changing the quarantine reason */
{
switch (bp[0])
{
case 'q': /* quarantine reason */
foundq = true;
{
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"%s: Removed quarantine of \"%s\"\n",
}
dirty = true;
continue;
}
{
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"%s: Already quarantined with \"%s\"\n",
}
"q%s\n", reason);
}
else
{
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"%s: Quarantine changed from \"%s\" to \"%s\"\n",
reason);
}
"q%s\n", reason);
reason);
dirty = true;
}
break;
case 'S':
/*
** If we are quarantining an unquarantined item,
** need to put in a new 'q' line before it's
** too late.
*/
{
if (Verbose)
{
(void) sm_io_fprintf(smioout,
"%s: Quarantined with \"%s\"\n",
}
"q%s\n", reason);
reason);
foundq = true;
dirty = true;
}
/* Copy the line to the new file */
"%s\n", bp);
break;
case '.':
finished = true;
/* FALLTHROUGH */
default:
/* Copy the line to the new file */
"%s\n", bp);
break;
}
}
/* Make sure we read the whole old file */
{
save_errno = errno;
"Skipping %s: Error reading %s: %s\n",
qid_printname(e), oldqf,
failing = true;
}
{
"Skipping %s: Incomplete file: %s\n",
qid_printname(e), oldqf);
failing = true;
}
/* Check if we actually changed anything or we can just bail now */
if (!dirty)
{
/* pretend we failed, even though we technically didn't */
failing = true;
}
/* Make sure we wrote things out safely */
if (!failing &&
((SuperSafe == SAFE_REALLY ||
SuperSafe == SAFE_INTERACTIVE) &&
{
save_errno = errno;
"Skipping %s: Error writing %s: %s\n",
qid_printname(e), tempqf,
failing = true;
}
/* Figure out the new filename */
{
/* going to rename tempqf to oldqf */
}
else
{
/* going to rename tempqf to new name based on newtype */
}
save_errno = 0;
/* rename tempqf to newqf */
if (!failing &&
/* Check rename() success */
if (!failing && save_errno != 0)
{
"quarantine_queue_item: rename(%s, %s): %s",
"Error renaming %s to %s: %s\n",
{
/*
** Bail here since we don't know the state of
** the filesystem and may need to keep tempqf
** for the user to rescue us.
*/
errno = save_errno;
/* NOTREACHED */
}
else
{
/* remove new file (if rename() half completed) */
{
save_errno = errno;
"Error removing %s: %s\n",
}
/* tempqf removed below */
failing = true;
}
}
/* If changing file types, need to remove old type */
{
{
save_errno = errno;
"Error removing %s: %s\n",
}
}
/* see if anything above failed */
if (failing)
{
/* Something failed: remove new file, old file still there */
}
/*
** fsync() after file operations to make sure metadata is
** written to disk on filesystems in which renames are
** not guaranteed. It's ok if they fail, mail won't be lost.
*/
{
/* for soft-updates */
SM_IO_WHAT_FD, NULL));
if (!failing)
{
/* for soft-updates */
SM_IO_WHAT_FD, NULL));
}
/* for other odd filesystems */
}
/* Close up shop */
/* All went well */
return !failing;
}
/*
** QUARANTINE_QUEUE -- {un,}quarantine matching items in the queue
**
** reason, and requeue appropriately.
**
** Parameters:
** reason -- quarantine reason, "." means unquarantine.
** qgrplimit -- limit to single queue group unless NOQGRP
**
** Results:
** none.
**
** Side Effects:
** Lots of changes to the queue.
*/
void
char *reason;
int qgrplimit;
{
int changed = 0;
int qgrp;
/* Convert internal representation of unquarantine */
{
/* clean it */
}
{
int qdir;
continue;
{
int i;
int nrequests;
if (StopRequest)
/* first see if there is anything */
if (nrequests <= 0)
{
if (Verbose)
{
(void) sm_io_fprintf(smioout,
SM_TIME_DEFAULT, "%s: no matches\n",
}
continue;
}
if (Verbose)
{
(void) sm_io_fprintf(smioout,
SM_TIME_DEFAULT, "Processing %s:\n",
}
for (i = 0; i < WorkListCount; i++)
{
ENVELOPE e;
if (StopRequest)
/* setup envelope */
{
"Would do %s\n", e.e_id);
changed++;
}
&e, reason))
changed++;
/* clean up */
sm_rpool_free(e.e_rpool);
}
WorkListSize = 0;
WorkListCount = 0;
}
}
if (Verbose)
{
if (changed == 0)
"No changes\n");
else
"%d change%s\n",
}
}