main.c revision e9af4bc0b1cc30cea75d6ad4aa2fde97d985e9be
/*
* Copyright (c) 1998-2006, 2008, 2009 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.
*
*/
/*
* Copyright 1996-2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#define _DEFINE
#include <sendmail.h>
#include <sm/sendmail.h>
#ifndef lint
"@(#) Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.\n\
@(#) All rights reserved.\n\
@(#) Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\
@(#) Copyright (c) 1988, 1993\n\
@(#) The Regents of the University of California. All rights reserved.\n\
@(#) Copyright 1996-2006 Sun Microsystems, Inc. All rights reserved.\n\
@(#) Use is subject to license terms.\n";
#endif /* ! lint */
#endif /* NETINET || NETINET6 */
/* for getcfname() */
#include <sendmail/pathnames.h>
static SM_DEBUG_T
"@(#)$Debug: no_persistent_restart - don't restart, log only $");
static void sm_printoptions __P((char **));
#ifdef SIGUSR1
#endif /* SIGUSR1 */
/*
** SENDMAIL -- Post mail to a set of destinations.
**
** This is the basic mail router. All user mail programs should
** call this routine to actually deliver mail. Sendmail in
** turn calls a bunch of mail servers that do the real work of
** delivering the mail.
**
** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
** (read by readcf.c).
**
** Usage:
**
** See the associated documentation for details.
**
** Authors:
** Britton-Lee, Inc., purveyors of fine
** database computers (11/81 - 10/88).
** International Computer Science Institute
** (11/88 - 9/89).
** InReference, Inc. (8/95 - 1/97).
** Sendmail, Inc. (1/98 - present).
** The support of my employers is gratefully acknowledged.
** Few of them (Britton-Lee in particular) have had
** anything to gain from my involvement in this project.
**
** Gregory Neil Shapiro,
** Worcester Polytechnic Institute (until 3/98).
** Sendmail, Inc. (3/98 - present).
**
** Claus Assmann,
** Sendmail, Inc. (12/98 - present).
*/
char *FullName; /* sender's full name */
char *CommandLineArgs; /* command line args for pid file */
bool Warn_Q_option = false; /* warn about Q option use */
static int MissingFds = 0; /* bit map of fds missing on startup */
#ifdef NGROUPS_MAX
#endif /* NGROUPS_MAX */
#if SASL
static sasl_callback_t srvcallbacks[] =
{
};
#endif /* SASL */
unsigned int SubmitMode;
int SyslogPrefixLen; /* estimated length of syslog prefix */
#ifndef SL_FUDGE
#endif /* ! SL_FUDGE */
/* Some options are dangerous to allow users to use in non-submit mode */
#define CHECK_AGAINST_OPMODE(cmd) \
{ \
if (extraprivs && \
{ \
"WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
(cmd)); \
break; \
} \
if (extraprivs && queuerun) \
{ \
"WARNING: Ignoring submission mode -%c option with -q\n", \
(cmd)); \
break; \
} \
}
int
int argc;
char **argv;
char **envp;
{
register char *p;
char **av;
extern char Version[];
register int i;
int j;
int dp;
int fill_errno;
bool safecf = true;
bool warn_C_flag = false;
bool auth = true; /* whether to set e_auth_param */
char warn_f_flag = '\0';
bool run_in_foreground = false; /* -bD mode */
char *nullserver = NULL;
bool extraprivs;
bool queuepersistent = false; /* queue runner process runs forever */
bool foregroundqueue = false; /* queue run in foreground */
bool save_val; /* to save some bool var. */
int cftype; /* which cf file to use? */
char *emptyenviron[1];
#if STARTTLS
bool tls_ok;
#endif /* STARTTLS */
ENVELOPE *e;
extern int DtableSize;
extern int optind;
extern int opterr;
extern char *optarg;
extern char **environ;
#if SASL
extern void sm_sasl_init __P((void));
#endif /* SASL */
#if USE_ENVIRON
#endif /* USE_ENVIRON */
/* turn off profiling */
SM_PROF(0);
/* install default exception handler */
/*
** Check to see if we reentered.
** This would normally happen if e_putheader or e_putbody
** were NULL when invoked.
*/
if (starttime != 0)
{
syserr("main: reentered!");
abort();
}
/* avoid null pointer dereferences */
/* Check if sendmail is running with extra privs */
extraprivs = (RealUid != 0 &&
CurrentPid = getpid();
/* get whatever .cf file is right for the opmode */
/* in 4.4BSD, the table can be huge; impose a reasonable limit */
DtableSize = getdtsize();
if (DtableSize > 256)
DtableSize = 256;
/*
** Be sure we have enough file descriptors.
** But also be sure that 0, 1, & 2 are open.
*/
/* reset errno and fill_errno; the latter is used way down below */
errno = fill_errno = 0;
if (errno != 0)
fill_errno = errno;
if (errno != 0)
fill_errno = errno;
if (errno != 0)
fill_errno = errno;
errno = 0;
#if LOG
# ifndef SM_LOG_STR
# define SM_LOG_STR "sendmail"
# endif /* ! SM_LOG_STR */
# ifdef LOG_MAIL
# else /* LOG_MAIL */
# endif /* LOG_MAIL */
#endif /* LOG */
/*
** Seed the random number generator.
** Used for queue file names, picking a queue directory, and
** MX randomization.
*/
seed_random();
/* do machine-dependent initializations */
/* reset status from syserr() calls for missing file descriptors */
Errors = 0;
LocalDaemon = false;
#endif /* _FFR_LOCAL_DAEMON */
#if XDEBUG
checkfd012("after openlog");
#endif /* XDEBUG */
#ifdef NGROUPS_MAX
/* save initial group set for future checks */
if (i <= 0)
{
i = 0;
}
while (i < NGROUPS_MAX)
InitialGidSet[i++] = InitialGidSet[0];
#endif /* NGROUPS_MAX */
/* drop group id privileges (RunAsUser not yet set) */
dp = drop_privileges(false);
#ifdef SIGUSR1
/* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
if (!extraprivs)
{
/* arrange to dump state on user-1 signal */
}
else
{
/* ignore user-1 signal */
}
#endif /* SIGUSR1 */
/* initialize for setproctitle */
/* Handle any non-getoptable constructions. */
/*
** Do a quick prescan of the argument list.
*/
/* find initial opMode */
OpMode = MD_DELIVER;
if (p++ == NULL)
p = *av;
if (strcmp(p, "newaliases") == 0)
else if (strcmp(p, "mailq") == 0)
else if (strcmp(p, "smtpd") == 0)
else if (strcmp(p, "hoststat") == 0)
else if (strcmp(p, "purgestat") == 0)
# define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:x"
#endif /* defined(__osf__) || defined(_AIX3) */
#if defined(sony_news)
# define OPTIONS "A:B:b:C:cD:d:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
#endif /* defined(sony_news) */
#ifndef OPTIONS
# define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
#endif /* ! OPTIONS */
/* Set to 0 to allow -b; need to check optarg before using it! */
opterr = 0;
{
switch (j)
{
case 'b': /* operations mode */
switch (j)
{
case MD_DAEMON:
case MD_FGDAEMON:
case MD_SMTP:
case MD_INITALIAS:
case MD_DELIVER:
case MD_VERIFY:
case MD_TEST:
case MD_PRINT:
case MD_PRINTNQE:
case MD_HOSTSTAT:
case MD_PURGESTAT:
case MD_ARPAFTP:
#if _FFR_CHECKCONFIG
case MD_CHECKCONFIG:
#endif /* _FFR_CHECKCONFIG */
OpMode = j;
break;
case MD_LOCAL:
LocalDaemon = true;
break;
#endif /* _FFR_LOCAL_DAEMON */
case MD_FREEZE:
"Frozen configurations unsupported\n");
return EX_USAGE;
default:
"Invalid operation mode %c\n",
j);
return EX_USAGE;
}
break;
case 'D':
if (debug)
{
errno = 0;
syserr("-D file must be before -d");
break;
}
dp = drop_privileges(true);
{
break;
}
break;
case 'd':
debug = true;
break;
case 'G': /* relay (gateway) submission */
break;
case 'L':
{
"option requires an argument -- '%c'",
(char) j);
return EX_USAGE;
}
sysloglabel = xalloc(j);
SL_FUDGE + j;
break;
case 'Q':
case 'q':
/* just check if it is there */
queuerun = true;
break;
}
}
opterr = 1;
/* Don't leak queue information via debug flags */
{
"WARNING: Can not use -d with -q. Disabling debugging.\n");
}
#if LOG
if (sysloglabel != NULL)
{
/* Sanitize the string */
for (p = sysloglabel; *p != '\0'; p++)
{
*p = '*';
}
closelog();
# ifdef LOG_MAIL
# else /* LOG_MAIL */
# endif /* LOG_MAIL */
}
#endif /* LOG */
/* set up the blank envelope */
CurEnv = &BlankEnvelope;
/*
** Set default values for variables.
** These cannot be in initialized data space.
*/
/* reset macro */
else
(int) RealUid);
if (tTd(0, 101))
{
/* NOTREACHED */
}
/*
** if running non-set-user-ID binary as non-root, pretend
** we are the RunAsUid
*/
{
sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
(int) RealUid);
}
else if (geteuid() != 0)
{
sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
sm_dprintf("main: RunAsUser = %d:%d\n",
}
/* save command line arguments */
j = 0;
CommandLineArgs = xalloc(j);
p = CommandLineArgs;
{
int h;
*p++ = ' ';
(void) sm_strlcpy(p, *av++, j);
h = strlen(p);
p += h;
j -= h + 1;
}
if (tTd(0, 1))
{
extern char *CompileOptions[];
}
if (tTd(0, 10))
{
extern char *OsCompileOptions[];
sm_dprintf(" OS Defines:");
#ifdef _PATH_UNIX
#endif /* _PATH_UNIX */
sm_dprintf(" Conf file:\t%s (default for MSP)\n",
conffile));
sm_dprintf(" Conf file:\t%s (default for MTA)\n",
conffile));
}
if (tTd(0, 12))
{
extern char *SmCompileOptions[];
sm_dprintf(" libsm Defines:");
}
if (tTd(0, 13))
{
extern char *FFRCompileOptions[];
sm_dprintf(" FFR Defines:");
}
/* clear sendmail's environment */
emptyenviron[0] = NULL;
/*
** restore any original TZ setting until TimeZoneSpec has been
** determined - or early log messages may get bogus time stamps
*/
{
char *tz;
int tzlen;
/* XXX check for reasonable length? */
/* XXX check return code? */
}
/* prime the child environment */
/*
** Initialize name server if it is going to be used.
*/
#if NAMED_BIND
(void) res_init();
else
# ifdef RES_NOALIASES
# endif /* RES_NOALIASES */
#endif /* NAMED_BIND */
errno = 0;
/* initialize some macros, etc. */
/* version */
/* hostname */
if (jbuf[0] != '\0')
{
if (tTd(0, 4))
else
{
if (tTd(0, 22))
sm_dprintf("uname failed (%s)\n",
p = jbuf;
}
if (tTd(0, 4))
sm_dprintf(" UUCP nodename: %s\n", p);
setclass('k', p);
setclass('w', p);
}
{
{
if (tTd(0, 4))
}
{
# if NETINET6
char *addr;
char buf6[INET6_ADDRSTRLEN];
# endif /* NETINET6 */
# if NETINET
# endif /* NETINET */
char ipbuf[103];
ipbuf[0] = '\0';
switch (hp->h_addrtype)
{
# if NETINET
case AF_INET:
break;
break;
# endif /* NETINET */
# if NETINET6
case AF_INET6:
break;
"[%.100s]", addr);
break;
# endif /* NETINET6 */
}
if (ipbuf[0] == '\0')
break;
if (tTd(0, 4))
}
#endif /* NETINET || NETINET6 */
#if NETINET6
#endif /* NETINET6 */
}
/* current time */
/* current load average */
sm_getla();
/*
** Crack argv.
*/
optind = 1;
{
switch (j)
{
case 'b': /* operations mode */
/* already done */
break;
break;
case 'B': /* body type */
break;
case 'C': /* select configuration file (already done) */
if (RealUid != 0)
warn_C_flag = true;
dp = drop_privileges(true);
safecf = false;
break;
case 'D':
case 'd': /* debugging */
/* already done */
break;
case 'f': /* from address */
case 'r': /* obsolete -f flag */
{
usrerr("More than one \"from\" person");
break;
}
if (optarg[0] == '\0')
else
warn_f_flag = j;
break;
case 'F': /* set full name */
break;
case 'G': /* relay (gateway) submission */
/* already set */
break;
case 'h': /* hop count */
10);
if (*ep)
{
}
break;
case 'L': /* program label */
/* already set */
break;
case 'n': /* don't alias */
NoAlias = true;
break;
case 'N': /* delivery status notifications */
break;
{
p = strchr(p, ',');
if (p != NULL)
*p++ = '\0';
else
{
usrerr("Invalid -N argument");
}
}
break;
case 'o': /* set option */
break;
case 'O': /* set option (long form) */
break;
case 'p': /* set protocol */
if (p != NULL)
{
*p++ = '\0';
if (*p != '\0')
{
i = strlen(p) + 1;
ep = sm_malloc_x(i);
cleanstrcpy(ep, p, i);
}
}
if (*optarg != '\0')
{
ep = sm_malloc_x(i);
'r', ep);
}
break;
case 'Q': /* change quarantining on queued items */
/* sanity check */
if (OpMode != MD_DELIVER &&
OpMode != MD_QUEUERUN)
{
break;
}
if (OpMode == MD_DELIVER)
break;
case 'q': /* run queue files at intervals */
/* sanity check */
if (OpMode != MD_DELIVER &&
OpMode != MD_FGDAEMON &&
OpMode != MD_PRINTNQE &&
OpMode != MD_QUEUERUN)
{
break;
}
/* don't override -bd, -bD or -bp */
if (OpMode == MD_DELIVER)
if (negate)
{
/* negate meaning of pattern match */
optarg++; /* skip '!' for next switch */
}
switch (optarg[0])
{
case 'G': /* Limit by queue group name */
if (negate)
{
usrerr("Can not use -q!G");
break;
}
if (queuegroup != NULL)
{
usrerr("Can not use multiple -qG options");
break;
}
break;
case 'I': /* Limit by ID */
QueueLimitId = new;
break;
case 'R': /* Limit by recipient */
break;
case 'S': /* Limit by sender */
break;
case 'f': /* foreground queue run */
foregroundqueue = true;
break;
case 'Q': /* Limit by quarantine message */
{
}
break;
case 'L': /* act on lost items */
break;
case 'p': /* Persistent queue */
queuepersistent = true;
if (QueueIntvl == 0)
QueueIntvl = 1;
break;
++optarg;
/* FALLTHROUGH */
default:
i = Errors;
if (QueueIntvl < 0)
{
usrerr("Invalid -q value");
}
/* check for bad conversion */
if (i < Errors)
break;
}
break;
case 'R': /* DSN RET: what to return */
{
usrerr("Duplicate -R flag");
break;
}
{
usrerr("Invalid -R value");
}
break;
case 't': /* read recipients from message */
GrabTo = true;
break;
case 'V': /* DSN ENVID: set "original" envelope id */
{
usrerr("Invalid syntax in -V flag");
}
else
{
}
break;
case 'X': /* traffic log file */
dp = drop_privileges(true);
SM_IO_WRONLY, NULL);
else
SM_IO_APPEND, NULL);
if (TrafficLogFile == NULL)
{
break;
}
break;
/* compatibility flags */
case 'c': /* connect to non-local mailers */
case 'i': /* don't let dot stop me */
case 'm': /* send to me too */
case 'T': /* set timeout interval */
case 'v': /* give blow-by-blow description */
break;
case 'e': /* error message disposition */
case 'M': /* define macro */
break;
case 's': /* save From lines in headers */
break;
#ifdef DBM
case 'I': /* initialize alias DBM file */
break;
#endif /* DBM */
case 'x': /* random flag that OSF/1 & AIX mailx passes */
break;
#endif /* defined(__osf__) || defined(_AIX3) */
#if defined(sony_news)
case 'E':
case 'J': /* ignore flags for Japanese code conversion
implemented on Sony NEWS */
break;
#endif /* defined(sony_news) */
default:
/* NOTREACHED */
break;
}
}
/* if we've had errors so far, exit now */
{
/* NOTREACHED */
}
{
/* If set daemon_flags on command line, don't reset it */
}
{
/* If set daemon_flags on command line, don't reset it */
}
/*
** Do basic initialization.
** Read system control file.
** Extract special fields for local use.
*/
#if XDEBUG
checkfd012("before readcf");
#endif /* XDEBUG */
safecf, &BlankEnvelope);
#if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
ConfigFileRead = true;
#endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
/* now we can complain about missing fds */
{
mbuf[0] = '\0';
/* Notice: fill_errno is from high above: fill_fd() */
"File descriptors missing on startup: %s; %s",
}
/* Remove the ability for a normal user to send signals */
{
#if HASSETREUID
/*
** Since we can differentiate between uid and euid,
** make the uid a different user so the real user
** can't send signals. However, it doesn't need to be
** root (euid has root).
*/
if (new_uid == 0)
{
syserr("main: setreuid(%d, %d) failed",
/* NOTREACHED */
}
sm_dprintf("Now running as e/ruid %d:%d\n",
#else /* HASSETREUID */
/*
** Have to change both effective and real so need to
** change them both to effective to keep privs.
*/
{
/* NOTREACHED */
}
sm_dprintf("Now running as e/ruid %d:%d\n",
#endif /* HASSETREUID */
}
#if NAMED_BIND
if (FallbackMX != NULL)
(void) getfallbackmxrr(FallbackMX);
#endif /* NAMED_BIND */
{
"WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
}
{
usrerr("Mail submission program cannot be used as daemon");
}
/* set up the basic signal handlers */
/* Enforce use of local time (null string overrides this) */
if (TimeZoneSpec == NULL)
unsetenv("TZ");
else if (TimeZoneSpec[0] != '\0')
else
tzset();
/* initialize mailbox database */
i = sm_mbdb_initialize(Mbdb);
if (i != EX_OK)
{
usrerr("Can't initialize mailbox database \"%s\": %s",
Mbdb, sm_strexit(i));
ExitStat = i;
}
/* avoid denial-of-service attacks */
resetlimits();
{
/* can't be done after readcf if RunAs* is used */
dp = drop_privileges(true);
{
/* NOTREACHED */
}
}
{
dp = drop_privileges(false);
{
usrerr("Mail submission program must have RunAsUser set to non root user");
/* NOTREACHED */
}
}
#if NAMED_BIND
#endif /* NAMED_BIND */
/*
** Find our real host name for future logging.
*/
/* suppress error printing if errors mailed back or whatever */
HoldErrs = true;
/* set up the $=m class now, after .cf has a chance to redefine $m */
if (jbuf[0] != '\0')
/* probe interfaces and locate any additional names */
if (DontProbeInterfaces != DPI_PROBENONE)
if (tTd(0, 10))
{
char pidpath[MAXPATHLEN];
/* Now we know which .cf file we use */
sm_dprintf(" Conf file:\t%s (selected)\n",
}
if (tTd(0, 1))
{
sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
sm_dprintf("\n (short domain name) $w = ");
sm_dprintf("\n (canonical domain name) $j = ");
sm_dprintf("\n (subdomain name) $m = ");
sm_dprintf("\n (node name) $k = ");
sm_dprintf("\n========================================================\n\n");
}
/*
** Do more command line checking -- these are things that
** have to modify the results of reading the config file.
*/
/* process authorization warnings from command line */
if (warn_C_flag)
QueueDir);
(int) RealUid);
/* check body type for legality */
if (i == BODYTYPE_ILLEGAL)
{
}
else if (i != BODYTYPE_NONE)
SevenBitInput = (i == BODYTYPE_7BIT);
/* tweak default DSN notifications */
if (DefaultNotify == 0)
/* check for sane configuration level */
if (ConfigLevel > MAXCONFIGLEVEL)
{
syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
}
/* need MCI cache to have persistence */
{
HostStatDir = NULL;
"Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
}
/* need HostStatusDir in order to have SingleThreadDelivery */
{
SingleThreadDelivery = false;
"Warning: HostStatusDirectory required for SingleThreadDelivery\n");
}
#if _FFR_MEMSTAT
j = sm_memstat_open();
{
"cannot get memory statistics, settings ignored, error=%d"
, j);
}
#endif /* _FFR_MEMSTAT */
/* check for permissions */
if (RealUid != 0 &&
RealUid != TrustedUid)
{
switch (OpMode)
{
case MD_QUEUERUN:
if (quarantining != NULL)
action = "quarantine jobs";
else
{
/* Normal users can do a single queue run */
if (QueueIntvl == 0)
break;
}
/* but not persistent queue runners */
action = "start a queue runner daemon";
/* FALLTHROUGH */
case MD_PURGESTAT:
action = "purge host status";
/* FALLTHROUGH */
case MD_DAEMON:
case MD_FGDAEMON:
action = "run daemon";
sm_dprintf("Deny user %d attempt to %s\n",
if (LogLevel > 1)
"user %d attempted to %s",
HoldErrs = false;
usrerr("Permission denied (real uid not trusted)");
/* NOTREACHED */
break;
case MD_VERIFY:
{
/*
** If -bv and RestrictExpand,
** drop privs to prevent normal
** users from reading private
*/
sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
(int) RealUid);
dp = drop_privileges(true);
/* Fake address safety */
sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
{
sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
(int) RealUid);
/* NOTREACHED */
}
}
break;
case MD_TEST:
case MD_CHECKCONFIG:
case MD_PRINT:
case MD_PRINTNQE:
case MD_FREEZE:
case MD_HOSTSTAT:
/* Nothing special to check */
break;
case MD_INITALIAS:
{
sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
(int) RealUid);
if (LogLevel > 1)
"user %d attempted to rebuild the alias map",
(int) RealUid);
HoldErrs = false;
usrerr("Permission denied (real uid not trusted)");
/* NOTREACHED */
}
if (UseMSP)
{
HoldErrs = false;
usrerr("User %d cannot rebuild aliases in mail submission program",
(int) RealUid);
/* NOTREACHED */
}
/* FALLTHROUGH */
default:
Verbose != 0)
{
/*
** If -v and RestrictExpand, reset
** Verbose to prevent normal users
** from seeing the expansion of
*/
sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
(int) RealUid);
Verbose = 0;
}
break;
}
}
if (MeToo)
switch (OpMode)
{
case MD_TEST:
/* don't have persistent host status in test mode */
HostStatDir = NULL;
/* FALLTHROUGH */
case MD_CHECKCONFIG:
if (Verbose == 0)
Verbose = 2;
HoldErrs = false;
break;
case MD_VERIFY:
HoldErrs = false;
/* arrange to exit cleanly on hangup signal */
if (geteuid() != 0)
"Notice: -bv may give misleading output for non-privileged user\n");
break;
case MD_FGDAEMON:
run_in_foreground = true;
/* FALLTHROUGH */
case MD_DAEMON:
/* remove things that don't make sense in daemon mode */
GrabTo = false;
/* arrange to restart on hangup signal */
"daemon invoked without full pathname; kill -1 won't work");
break;
case MD_INITALIAS:
Verbose = 2;
HoldErrs = false;
/* FALLTHROUGH */
default:
/* arrange to exit cleanly on hangup signal */
break;
}
/* special considerations for FullName */
{
/* full names can't have newlines */
{
}
/* check for characters that may have to be quoted */
if (!rfc822_string(FullName))
{
/*
** Quote a full name with special characters
** as a comment so crackaddr() doesn't destroy
** the name portion of the address.
*/
}
}
/* do heuristic mode adjustment */
if (Verbose)
{
/* turn off noconnect option */
/* turn on interactive delivery */
}
#ifdef VENDOR_CODE
/* check for vendor mismatch */
if (VendorCode != VENDOR_CODE)
{
message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
}
#endif /* VENDOR_CODE */
/* check for out of date configuration level */
if (ConfigLevel < MAXCONFIGLEVEL)
{
message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
}
if (ConfigLevel < 3)
UseErrorsTo = true;
/* set options that were previous macros */
if (SmtpGreeting == NULL)
{
if (ConfigLevel < 7 &&
SmtpGreeting = newstr(p);
else
SmtpGreeting = "\201j Sendmail \201v ready at \201b";
}
if (UnixFromLine == NULL)
{
if (ConfigLevel < 7 &&
UnixFromLine = newstr(p);
else
UnixFromLine = "From \201g \201d";
}
SmtpError[0] = '\0';
/* our name for SMTP codes */
if (jbuf[0] == '\0')
else
/* make certain that this name is part of the $=w class */
/* fill in the structure of the *default* queue */
syserr("No default queue (mqueue) defined");
else
/* the indices of built-in mailers */
syserr("No local mailer defined");
syserr("No prog mailer defined");
else
{
}
syserr("No *file* mailer defined");
else
{
}
syserr("No *include* mailer defined");
else
if (ConfigLevel < 6)
{
/* heuristic tweaking of local mailer for back compat */
if (LocalMailer != NULL)
{
}
if (ProgMailer != NULL)
if (FileMailer != NULL)
}
if (ConfigLevel < 7)
{
if (LocalMailer != NULL)
if (ProgMailer != NULL)
if (FileMailer != NULL)
}
/* MIME Content-Types that cannot be transfer encoded */
/* MIME Content-Transfer-Encodings that can be encoded */
#ifdef USE_B_CLASS
/* MIME Content-Types that should be treated as binary */
#endif /* USE_B_CLASS */
/* MIME headers which have fields to check for overflow */
/* MIME headers to check for length overflow */
/* MIME headers to check for overflow and rebalance */
/* Macros to save in the queue file -- don't remove any */
/* operate in queue directory */
{
{
syserr("QueueDirectory (Q) option must be set");
}
}
else
{
}
/* check host status directory for validity */
{
/* cannot use this value */
"Warning: Cannot use HostStatusDirectory = %s: %s\n",
HostStatDir = NULL;
}
if (OpMode == MD_QUEUERUN &&
{
/* check to see if we own the queue directory */
{
/* nope, really a botch */
HoldErrs = false;
usrerr("You do not have permission to process the queue");
/* NOTREACHED */
}
}
#if MILTER
/* sanity checks on milter filters */
{
}
#endif /* MILTER */
/* Convert queuegroup string to qgrp number */
if (queuegroup != NULL)
{
{
HoldErrs = false;
/* NOTREACHED */
}
}
/* if checking config or have had errors so far, exit now */
{
/* NOTREACHED */
}
#if SASL
/* sendmail specific SASL initialization */
sm_sasl_init();
#endif /* SASL */
#if XDEBUG
checkfd012("before main() initmaps");
#endif /* XDEBUG */
/*
** Do operation-mode-dependent initialization.
*/
switch (OpMode)
{
case MD_PRINT:
/* print the queue */
HoldErrs = false;
(void) dropenvelope(&BlankEnvelope, true, false);
{
int j;
/* Selecting a particular queue group to run */
{
if (StopRequest)
(void) print_single_queue(qgrp, j);
}
/* NOTREACHED */
}
printqueue();
/* NOTREACHED */
break;
case MD_PRINTNQE:
/* print number of entries in queue */
(void) dropenvelope(&BlankEnvelope, true, false);
/* NOTREACHED */
break;
case MD_QUEUERUN:
/* only handle quarantining here */
if (quarantining == NULL)
break;
if (QueueMode != QM_QUARANTINE &&
{
HoldErrs = false;
/* NOTREACHED */
}
break;
case MD_HOSTSTAT:
/* NOTREACHED */
break;
case MD_PURGESTAT:
/* NOTREACHED */
break;
case MD_INITALIAS:
/* initialize maps */
initmaps();
/* NOTREACHED */
break;
case MD_SMTP:
case MD_DAEMON:
/* reset DSN parameters */
/* don't open maps for daemon -- done below in child */
break;
}
if (tTd(0, 15))
{
/* print configuration table (or at least part of it) */
if (tTd(0, 90))
printrules();
for (i = 0; i < MAXMAILERS; i++)
{
}
}
/*
** Switch to the main envelope.
*/
/*
** If test mode, read addresses from stdin and process.
*/
{
Verbose = 2;
if (Verbose)
{
"ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
"Enter <ruleset> <address>\n");
}
for (;;)
{
{
(void) sm_releasesignal(SIGINT);
if (Verbose == 2)
(void) sm_io_fprintf(smioout,
"> ");
if (p != NULL)
*p = '\0';
if (Verbose < 2)
(void) sm_io_fprintf(smioout,
"> %s\n", buf);
}
{
/*
** 8.10 just prints \n on interrupt.
** I'm printing the exception here in case
** sendmail is extended to raise additional
** exceptions in this context.
*/
"\n");
}
}
}
#if STARTTLS
tls_ok = true;
OpMode == MD_ARPAFTP)
{
/* check whether STARTTLS is turned off for the client */
if (chkclientmodifiers(D_NOTLS))
tls_ok = false;
}
{
/* check whether STARTTLS is turned off */
tls_ok = false;
}
else /* other modes don't need STARTTLS */
tls_ok = false;
if (tls_ok)
{
/* basic TLS initialization */
tls_ok = init_tls_library();
}
{
/* disable TLS for client */
setclttls(false);
}
#endif /* STARTTLS */
/*
** If collecting stuff from the queue, go start doing that.
*/
{
#if STARTTLS
/* init TLS for client, ignore result for now */
(void) initclttls(tls_ok);
#endif /* STARTTLS */
/*
** The parent process of the caller of runqueue() needs
** to stay around for a possible SIGTERM. The SIGTERM will
** tell this process that all of the queue runners children
** need to be sent SIGTERM as well. At the same time, we
** want to return control to the command line. So we do an
** extra fork().
*/
{
/*
** If the fork() failed we should still try to do
** the queue run. If it succeeded then the child
** is going to start the run and wait for all
** of the children to finish.
*/
if (pid == 0)
{
/* Reset global flags */
PendingSignal = 0;
/* disconnect from terminal */
}
CurrentPid = getpid();
{
/*
** To run a specific queue group mark it to
** be run, select the work group it's in and
** increment the work counter.
*/
i++)
if (Verbose)
rwgflags |= RWG_VERBOSE;
if (queuepersistent)
rwgflags);
}
else
queuepersistent, true);
/* set the title to make it easier to find */
while (CurChildren > 0)
{
int status;
errno = 0;
{
{
/*
** Oops... something got messed
** up really bad. Waiting for
** non-existent children
** shouldn't happen. Let's get
** out of here.
*/
CurChildren = 0;
break;
}
continue;
}
/* something is really really wrong */
{
"queue control process: lost all children: wait returned ECHILD");
break;
}
/* Only drop when a child gives status */
if (WIFSTOPPED(status))
continue;
}
}
/* NOTREACHED */
}
# if SASL
{
/* check whether AUTH is turned off for the server */
if (!chkdaemonmodifiers(D_NOAUTH) &&
syserr("!sasl_server_init failed! [%s]",
}
# endif /* SASL */
{
/* clean up background delivery children */
}
/*
** If a daemon, wait for a request.
** getrequests will always return in a child.
** If we should also be processing the queue, start
** doing it in background.
** We check for any errors that might have happened
** during startup.
*/
{
char dtype[200];
/* avoid cleanup in finis(), DaemonPid will be set below */
DaemonPid = 0;
{
/* put us in background */
i = fork();
if (i < 0)
syserr("daemon: cannot fork");
if (i != 0)
{
/* NOTREACHED */
}
/*
** Initialize exception stack and default exception
** handler for child process.
*/
/* Reset global flags */
RestartWorkGroup = false;
PendingSignal = 0;
CurrentPid = getpid();
/* disconnect from our controlling tty */
}
dtype[0] = '\0';
{
}
if (QueueIntvl > 0)
{
(void) sm_strlcat2(dtype,
? "+persistent-queueing@"
: "+queueing@",
pintvl(QueueIntvl, true),
sizeof(dtype));
}
if (tTd(0, 1))
#if XLA
#endif /* XLA */
/* save daemon type in a macro for possible PidFile use */
/* save queue interval in a macro for possible PidFile use */
/* workaround: can't seem to release the signal in the parent */
(void) sm_releasesignal(SIGHUP);
if (QueueIntvl > 0)
{
#if _FFR_RUNPQG
{
/*
** To run a specific queue group mark it to
** be run, select the work group it's in and
** increment the work counter.
*/
i++)
if (Verbose)
rwgflags |= RWG_VERBOSE;
if (queuepersistent)
rwgflags);
}
else
#endif /* _FFR_RUNPQG */
(void) runqueue(true, false, queuepersistent,
true);
/*
** If queuepersistent but not in daemon mode then
** we're going to do the queue runner monitoring here.
** If in daemon mode then the monitoring will happen
** elsewhere.
*/
{
/*
** Write the pid to file
** XXX Overwrites sendmail.pid
*/
/* set the title to make it easier to find */
while (CurChildren > 0)
{
int status;
int group;
errno = 0;
{
/*
** Waiting for non-existent
** children shouldn't happen.
** Let's get out of here if
** it occurs.
*/
{
CurChildren = 0;
break;
}
continue;
}
/* something is really really wrong */
{
"persistent queue runner control process: lost all children: wait returned ECHILD");
break;
}
if (WIFSTOPPED(status))
continue;
/* Probe only on a child status */
if (WIFSIGNALED(status))
{
{
"persistent queue runner=%d core dumped, signal=%d",
/* don't restart this */
group, -1);
continue;
}
"persistent queue runner=%d died, pid=%ld, signal=%d",
}
/*
** When debugging active, don't
** restart the persistent queues.
** But do log this as info.
*/
1))
{
"persistent queue runner=%d, exited",
group);
-1);
}
}
/* NOTREACHED */
}
{
char qtype[200];
/*
** Write the pid to file
** XXX Overwrites sendmail.pid
*/
/* set the title to make it easier to find */
qtype[0] = '\0';
"Queue runner@",
pintvl(QueueIntvl, true),
" for ",
QueueDir);
for (;;)
{
(void) pause();
if (doqueuerun())
(void) runqueue(true, false,
false, false);
}
}
}
(void) dropenvelope(&MainEnvelope, true, false);
#if STARTTLS
/* init TLS for server, ignore result for now */
(void) initsrvtls(tls_ok);
#endif /* STARTTLS */
/* drop privileges */
(void) drop_privileges(false);
/*
** Get authentication data
** Set _ macro in BlankEnvelope before calling newenvelope().
*/
/* at this point we are in a child: reset state */
}
if (LogLevel > 9)
{
/* log connection information */
}
/*
** If running SMTP protocol, start collecting and executing
** commands. This will never return.
*/
{
char pbuf[20];
/*
** Save some macros for check_* rulesets.
*/
if (forged)
{
char ipbuf[103];
}
else
sm_getla();
{
#if NETINET
case AF_INET:
break;
#endif /* NETINET */
#if NETINET6
case AF_INET6:
break;
#endif /* NETINET6 */
default:
break;
}
{
/* validate the connection */
HoldErrs = true;
CurEnv = &BlankEnvelope;
HoldErrs = false;
}
{
}
#if STARTTLS
(void) initsrvtls(tls_ok);
#endif /* STARTTLS */
/* turn off profiling */
SM_PROF(1);
{
/* turn off profiling */
SM_PROF(0);
goto nextreq;
}
}
{
}
else
{
/* interactive -- all errors are global */
}
/*
** Do basic system initialization and set the sender
*/
{
#if SASL
auth = false;
#endif /* SASL */
}
if (auth)
{
char *fv;
/* set the initial sender for AUTH= to $f@$j */
else
{
{
&MainEnvelope)) + 2;
p = sm_malloc_x(i);
macvalue('j',
&MainEnvelope));
}
else
p = sm_strdup_x(fv);
xtextify(p, "="));
sm_free(p); /* XXX */
}
}
{
HoldErrs = false;
usrerr("Recipient names must be specified");
/* collect body for UUCP return */
/* NOTREACHED */
}
/*
** Scan argv and deliver the message to everyone.
*/
LogUsrErrs = true;
/* if we have had errors sofar, arrange a meaningful exit stat */
#if _FFR_FIX_DASHT
/*
** If using -t, force not sending to argv recipients, even
** if they are mentioned in the headers.
*/
if (GrabTo)
{
ADDRESS *q;
q->q_state = QS_REMOVED;
}
#endif /* _FFR_FIX_DASHT */
/*
** Read the input mail.
*/
{
int savederrors;
unsigned long savedflags;
/*
** workaround for compiler warning on Irix:
** do not initialize variable in the definition, but
** later on:
** warning(1548): transfer of control bypasses
** initialization of:
** variable "savederrors" (declared at line 2570)
** variable "savedflags" (declared at line 2571)
** goto giveup;
*/
Errors = 0;
/* header checks failed */
if (Errors > 0)
{
if (!GrabTo)
{
/* Log who the mail would have gone to */
8, false);
}
flush_errors(true);
/* NOTREACHED */
return -1;
}
/* bail out if message too large */
{
: EX_DATAERR);
/* NOTREACHED */
return -1;
}
/* set message size */
}
errno = 0;
sm_dprintf("From person = \"%s\"\n",
/* Check if quarantining stats should be updated */
/*
** Actually send everything.
** If verifying, just ack.
*/
if (Errors == 0)
{
if (!split_by_recipient(&MainEnvelope) &&
goto giveup;
}
/* make sure we deliver at least the first envelope */
i = FastSplit > 0 ? 0 : -1;
{
{
sm_dprintf("main[%d]: QS_SENDER ", i);
}
sm_getla();
GrabTo = false;
#if NAMED_BIND
#endif /* NAMED_BIND */
/* after FastSplit envelopes: queue up */
}
/*
** All done.
** Don't send return error message if in VERIFY mode.
*/
/* NOTREACHED */
return ExitStat;
}
/*
** STOP_SENDMAIL -- Stop the running program
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** exits.
*/
void
{
/* reset uid for process accounting */
endpwent();
}
/*
** FINIS -- Clean up and exit.
**
** Parameters:
** drop -- whether or not to drop CurEnv envelope
** cleanup -- call exit() or _exit()?
** exitstat -- exit status to use for exit() call
**
** Returns:
** never
**
** Side Effects:
** exits sendmail
*/
void
bool drop;
bool cleanup;
volatile int exitstat;
{
char pidpath[MAXPATHLEN];
/* Still want to process new timeouts added below */
(void) sm_releasesignal(SIGALRM);
{
sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
}
printopenfds(false);
/*
** Clean up. This might raise E:mta.quickabort
*/
/* clean up temp files */
if (drop)
{
{
int r;
r = dropenvelope(CurEnv, true, false);
exitstat = r;
/* these may have pointed to the rpool */
}
else
}
/* flush any cached connections */
/* close maps belonging to this pid */
closemaps(false);
#if USERDB
/* close UserDatabase */
_udbx_close();
#endif /* USERDB */
#if SASL
#endif /* SASL */
#if XLA
/* clean up extended load average stuff */
xla_all_end();
#endif /* XLA */
/*
** And exit.
*/
if (LogLevel > 78)
(int) CurrentPid);
if (exitstat == EX_TEMPFAIL ||
/* XXX clean up queues and related data structures */
#if SM_CONF_SHM
#endif /* SM_CONF_SHM */
/* close locked pid file */
{
/* blow away the pid file */
}
/* reset uid for process accounting */
endpwent();
#if _FFR_MEMSTAT
(void) sm_memstat_close();
#endif /* _FFR_MEMSTAT */
#if SM_HEAP_CHECK
/* dump the heap, if we are checking for memory leaks */
#endif /* SM_HEAP_CHECK */
if (cleanup)
else
}
/*
** INTINDEBUG -- signal handler for SIGINT in -bt mode
**
** Parameters:
** sig -- incoming signal.
**
** Returns:
** none.
**
** Side Effects:
** longjmps back to test mode loop.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
/* Type of an exception generated on SIGINT during address test mode. */
static const SM_EXC_TYPE_T EtypeInterrupt =
{
"S:mta.interrupt",
"",
"interrupt",
};
/* ARGSUSED */
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
errno = save_errno;
errno = save_errno;
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** SIGTERM -- SIGTERM handler for the daemon
**
** Parameters:
** sig -- signal number.
**
** Returns:
** none.
**
** Side Effects:
** Sets ShutdownRequest which will hopefully trigger
** the daemon to exit.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
/* ARGSUSED */
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
ShutdownRequest = "signal";
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** SIGHUP -- handle a SIGHUP signal
**
** Parameters:
** sig -- incoming signal.
**
** Returns:
** none.
**
** Side Effects:
** Sets RestartRequest which should cause the daemon
** to restart.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
/* ARGSUSED */
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
RestartRequest = "signal";
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** SIGPIPE -- signal handler for SIGPIPE
**
** Parameters:
** sig -- incoming signal.
**
** Returns:
** none.
**
** Side Effects:
** Sets StopRequest which should cause the mailq/hoststatus
** display to stop.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
*/
/* ARGSUSED */
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
StopRequest = true;
errno = save_errno;
return SIGFUNC_RETURN;
}
/*
** INTSIG -- clean up on interrupt
**
** This just arranges to exit. It pessimizes in that it
** may resend a message.
**
** Parameters:
** none.
**
** Returns:
** none.
**
** Side Effects:
** Unlocks the current job.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
**
** XXX: More work is needed for this signal handler.
*/
/* ARGSUSED */
int sig;
{
bool drop = false;
int save_errno = errno;
errno = save_errno;
sm_allsignals(true);
/* Clean-up on aborted stdin message submission */
OpMode == MD_DELIVER ||
OpMode == MD_ARPAFTP))
{
register ADDRESS *q;
/* don't return an error indication */
/*
** Spin through the addresses and
** mark them dead to prevent bounces
*/
q->q_state = QS_DONTSEND;
drop = true;
}
{
}
/* NOTREACHED */
}
/*
** DISCONNECT -- remove our connection with any foreground process
**
** Parameters:
** droplev -- how "deeply" we should drop the line.
** 0 -- ignore signals, mail back errors, make sure
** output goes to stdout.
** 2 -- also, disconnect from controlling terminal
** (only for daemon mode).
** e -- the current envelope.
**
** Returns:
** none
**
** Side Effects:
** Trys to insure that we are immune to vagaries of
** the controlling tty.
*/
void
disconnect(droplev, e)
int droplev;
register ENVELOPE *e;
{
int fd;
sm_dprintf("disconnect: In %d Out %d, e=%p\n",
{
sm_dprintf("don't\n");
return;
}
if (LogLevel > 93)
"disconnect level %d",
droplev);
/* be sure we don't get nasty signals */
/* we can't communicate with our caller, so.... */
HoldErrs = true;
Verbose = 0;
DisConnected = true;
{
}
"disconnect: sm_io_reopen(\"%s\") failed: %s",
/*
** output to the transcript
** We also compare the fd numbers here since OutChannel
** might be a layer on top of smioout due to encryption
** (see sfsasl.c).
*/
if (OutChannel != smioout &&
{
#if 0
/*
** Has smioout been closed? Reopen it.
** This shouldn't happen anymore, the code is here
** just as a reminder.
*/
"disconnect: sm_io_reopen(\"%s\") failed: %s",
#endif /* 0 */
}
if (droplev > 0)
{
if (fd == -1)
{
"disconnect: open(\"%s\") failed: %s",
}
if (fd >= 0)
{
}
}
/* drop our controlling TTY completely if possible */
if (droplev > 1)
{
(void) setsid();
errno = 0;
}
#if XDEBUG
checkfd012("disconnect");
#endif /* XDEBUG */
if (LogLevel > 71)
(int) CurrentPid);
errno = 0;
}
static void
char *argv[];
{
register char *ap;
register char *op;
{
/* Return if "--" or not an option of any form. */
return;
/* Don't allow users to use "-Q." or "-Q ." */
{
"Can not use -Q.\n");
}
/* skip over options that do have a value */
#if defined(sony_news)
#endif /* defined(sony_news) */
{
argv++;
continue;
}
/* If -C doesn't have an argument, use sendmail.cf. */
#define __DEFPATH "sendmail.cf"
{
"-C", __DEFPATH);
}
/* If -q doesn't have an argument, run it once. */
*argv = "-q0";
/* If -Q doesn't have an argument, disable quarantining */
*argv = "-Q.";
/* if -d doesn't have an argument, use 0-99.1 */
*argv = "-d0-99.1";
#if defined(sony_news)
/* if -E doesn't have an argument, use -EC */
*argv = "-EC";
/* if -J doesn't have an argument, use -JJ */
*argv = "-JJ";
#endif /* defined(sony_news) */
}
}
/*
** AUTH_WARNING -- specify authorization warning
**
** Parameters:
** e -- the current envelope.
** msg -- the text of the message.
** args -- arguments to the message.
**
** Returns:
** none.
*/
void
#ifdef __STDC__
#else /* __STDC__ */
register ENVELOPE *e;
const char *msg;
#endif /* __STDC__ */
{
{
register char *p;
static char hostbuf[48];
if (hostbuf[0] == '\0')
{
#if NETINET6
{
}
#endif /* NETINET6 */
}
if (LogLevel > 3)
"Authentication-Warning: %.400s",
buf);
}
}
/*
** GETEXTENV -- get from external environment
**
** Parameters:
** envar -- the name of the variable to retrieve
**
** Returns:
** The value, if any.
*/
static char *
const char *envar;
{
char **envp;
int l;
{
return &(*envp)[l + 1];
}
return NULL;
}
/*
** SM_SETUSERENV -- set an environment variable in the propagated environment
**
** Parameters:
** envar -- the name of the environment variable.
** value -- the value to which it should be set. If
** null, this is extracted from the incoming
** environment. If that is not set, the call
** to sm_setuserenv is ignored.
**
** Returns:
** none.
*/
void
const char *envar;
const char *value;
{
int i, l;
char **evp = UserEnviron;
char *p;
{
return;
}
/* XXX enforce reasonable size? */
p = (char *) xalloc(l);
evp++;
{
*evp++ = p;
}
{
*evp++ = p;
}
/* make sure it is in our environment as well */
if (putenv(p) < 0)
syserr("sm_setuserenv: putenv(%s) failed", p);
}
/*
** DUMPSTATE -- dump state
**
** For debugging.
*/
void
char *when;
{
int rs;
extern int NextMacroId;
"--- dumping state on %s: $j = %s ---",
when,
j == NULL ? "<NULL>" : j);
if (j != NULL)
{
if (!wordinclass(j, 'w'))
"*** $j not in $=w ***");
}
printopenfds(true);
mci_dump_all(smioout, true);
if (rs > 0)
{
int status;
register char **pvp;
"--- ruleset debug_dumpstate returns stat %d, pv: ---",
status);
}
}
#ifdef SIGUSR1
/*
** SIGUSR1 -- Signal a request to dump state.
**
** Parameters:
** sig -- calling signal.
**
** Returns:
** none.
**
** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
** DOING.
**
** XXX: More work is needed for this signal handler.
*/
/* ARGSUSED */
static SIGFUNC_DECL
int sig;
{
int save_errno = errno;
errno = save_errno;
dumpstate("user signal");
# if SM_HEAP_CHECK
dumpstab();
# endif /* SM_HEAP_CHECK */
errno = save_errno;
return SIGFUNC_RETURN;
}
#endif /* SIGUSR1 */
/*
** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
**
** Parameters:
** to_real_uid -- if set, drop to the real uid instead
** of the RunAsUser.
**
** Returns:
** EX_OSERR if the setuid failed.
** EX_OK otherwise.
*/
int
bool to_real_uid;
{
sm_dprintf("drop_privileges(%d): Real[UG]id=%d:%d, get[ug]id=%d:%d, gete[ug]id=%d:%d, RunAs[UG]id=%d:%d\n",
(int) to_real_uid,
if (to_real_uid)
{
}
/* make sure no one can grab open descriptors for secret files */
endpwent();
/* reset group permissions; these can be set later */
/*
** Notice: on some OS (Linux...) the setgroups() call causes
** a logfile entry if sendmail is not run by root.
** However, it is unclear (no POSIX standard) whether
** setgroups() can only succeed if executed by root.
** So for now we keep it as it is; if you want to change it, use
** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
*/
{
syserr("drop_privileges: setgroups(1, %d) failed",
(int) emptygidset[0]);
}
/* reset primary group id */
if (to_real_uid)
{
/*
** Drop gid to real gid.
** On some OS we must reset the effective[/real[/saved]] gid,
** and then use setgid() to finally drop all group privileges.
** Later on we check whether we can get back the
** effective gid.
*/
#if HASSETEGID
{
syserr("drop_privileges: setegid(%d) failed",
(int) RunAsGid);
}
#else /* HASSETEGID */
# if HASSETREGID
{
syserr("drop_privileges: setregid(%d, %d) failed",
}
# else /* HASSETREGID */
# if HASSETRESGID
{
syserr("drop_privileges: setresgid(%d, %d, %d) failed",
}
# endif /* HASSETRESGID */
# endif /* HASSETREGID */
#endif /* HASSETEGID */
}
{
{
syserr("drop_privileges: setgid(%d) failed",
(int) RunAsGid);
}
errno = 0;
{
syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
}
}
/* fiddle with uid */
if (to_real_uid || RunAsUid != 0)
{
/*
** Try to setuid(RunAsUid).
** euid must be RunAsUid,
** ruid must be RunAsUid unless (e|r)uid wasn't 0
** and we didn't have to drop privileges to the real uid.
*/
{
#if HASSETREUID
/*
** if ruid != RunAsUid, euid == RunAsUid, then
** try resetting just the real uid, then using
** setuid() to drop the saved-uid as well.
*/
{
{
syserr("drop_privileges: setreuid(%d, -1) failed",
(int) RunAsUid);
}
{
syserr("drop_privileges: second setuid(%d) attempt failed",
(int) RunAsUid);
}
}
else
#endif /* HASSETREUID */
{
syserr("drop_privileges: setuid(%d) failed",
(int) RunAsUid);
}
}
{
/*
** Believe it or not, the Linux capability model
** allows a non-root process to override setuid()
** on a process running as root and prevent that
** process from dropping privileges.
*/
syserr("drop_privileges: setuid(0) succeeded (when it should not)");
}
{
/*
** Some operating systems will keep the saved-uid
** if a non-root effective-uid calls setuid(real-uid)
** making it possible to set it back again later.
*/
syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
}
}
if ((to_real_uid || RunAsGid != 0) &&
{
errno = 0;
{
syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
(int) EffGid);
}
}
{
sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
}
return rval;
}
/*
** FILL_FD -- make sure a file descriptor has been properly allocated
**
**
** Parameters:
** fd -- the file descriptor to be filled.
** where -- a string used for logging. If NULL, this is
** being called on startup, and logging should
** not be done.
**
** Returns:
** none
**
** Side Effects:
** possibly changes MissingFds
*/
void
int fd;
char *where;
{
int i;
return;
else
if (i < 0)
{
syserr("!fill_fd: %s: cannot open %s",
}
if (fd != i)
{
(void) close(i);
}
}
/*
** SM_PRINTOPTIONS -- print options
**
** Parameters:
** options -- array of options.
**
** Returns:
** none.
*/
static void
char **options;
{
int ll;
char **av;
ll = 7;
{
{
sm_dprintf("\n");
ll = 0;
}
if (ll == 0)
sm_dprintf("\t\t");
else
sm_dprintf(" ");
}
sm_dprintf("\n");
}
/*
** TO8BIT -- convert \octal sequences in a test mode input line
**
** Parameters:
** str -- the input line.
**
** Returns:
** none.
**
** Side Effects:
** replaces \0octal in str with octal value.
*/
static bool
char *str;
{
int c, len;
bool changed;
return false;
changed = false;
len = 0;
{
++len;
if (c == '\\' &&
{
oct = 0;
{
oct <<= 3;
++str;
++len;
}
changed = true;
c = oct;
}
*out++ = c;
}
*out++ = c;
if (changed)
{
char *q;
if (q != in)
}
return changed;
}
/*
** TESTMODELINE -- process a test mode input line
**
** Parameters:
** line -- the input line.
** e -- the current environment.
** Syntax:
** # a comment
** .X process X as a configuration line
** =X dump a configuration item (such as mailers)
** $X dump a macro or class
** /X try an activity
** X normal process through rule set X
*/
static void
testmodeline(line, e)
char *line;
ENVELOPE *e;
{
register char *p;
char *q;
auto char *delimptr;
int mid;
int i, rs;
char **s;
ADDRESS a;
char *lbp;
auto int lbs;
static int tryflags = RF_COPYNONE;
extern unsigned char TokTypeNoC[];
bool eightbit;
/* skip leading spaces */
while (*line == ' ')
line++;
eightbit = false;
switch (line[0])
{
case '#':
case '\0':
return;
case '?':
help("-bt", e);
return;
case '.': /* config-style settings */
switch (line[1])
{
case 'D':
if (mid == 0)
return;
break;
case 'C':
return;
if (mid == 0)
return;
p = exbuf;
while (*p != '\0')
{
register char *wd;
char delim;
p++;
wd = p;
p++;
delim = *p;
*p = '\0';
if (wd[0] != '\0')
*p = delim;
}
break;
case '\0':
"Usage: .[DC]macro value(s)\n");
break;
default:
"Unknown \".\" command %s\n", line);
break;
}
return;
case '=': /* config-style settings */
switch (line[1])
{
case 'S': /* dump rule set */
if (rs < 0)
{
return;
}
return;
do
{
'R');
while (*s != NULL)
{
(void) sm_io_putc(smioout,
SM_TIME_DEFAULT, ' ');
}
'\t');
'\t');
while (*s != NULL)
{
(void) sm_io_putc(smioout,
SM_TIME_DEFAULT, ' ');
}
'\n');
break;
case 'M':
for (i = 0; i < MAXMAILERS; i++)
{
}
break;
case '\0':
"Usage: =Sruleset or =M\n");
break;
default:
"Unknown \"=\" command %s\n", line);
break;
}
return;
case '-': /* set command-line-like opts */
switch (line[1])
{
case 'd':
break;
case '\0':
"Usage: -d{debug arguments}\n");
break;
default:
"Unknown \"-\" command %s\n", line);
break;
}
return;
case '$':
{
if (mid != 0)
return;
}
if (mid == 0)
return;
if (p == NULL)
"Undefined\n");
else
{
"\n");
}
return;
case '/': /* miscellaneous commands */
*p = '\0';
if (p != NULL)
{
*p++ = '\0';
}
else
p = "";
{
"Usage: /[canon|map|mx|parse|try|tryflags]\n");
return;
}
{
/* NOTREACHED */
}
{
#if NAMED_BIND
/* look up MX records */
int nmx;
auto int rcode;
if (*p == '\0')
{
"Usage: /mx address\n");
return;
}
NULL);
"getmxrr(%s) returns %d value(s):\n",
p, nmx);
for (i = 0; i < nmx; i++)
"\t%s\n", mxhosts[i]);
#else /* NAMED_BIND */
"No MX code compiled in\n");
#endif /* NAMED_BIND */
}
{
char host[MAXHOSTNAMELEN];
if (*p == '\0')
{
"Usage: /canon address\n");
return;
}
{
"Name too long\n");
return;
}
NULL);
"getcanonname(%s) returns %s\n",
p, host);
}
{
char *av[2];
if (*p == '\0')
{
"Usage: /map mapname key\n");
return;
}
continue;
if (*q == '\0')
{
"No key specified\n");
return;
}
*q++ = '\0';
{
"Map named \"%s\" not found\n", p);
return;
}
{
"Map named \"%s\" not open\n", p);
return;
}
"map_lookup: %s (%s) ", p, q);
av[0] = q;
if (p == NULL)
"no match (%d)\n",
rcode);
else
"returns %s (%d)\n", p,
rcode);
}
{
MAILER *m;
q = strpbrk(p, " \t");
if (q != NULL)
{
*q++ = '\0';
}
if (q == NULL || *q == '\0')
{
"Usage: /try mailer address\n");
return;
}
{
"Unknown mailer %s\n", p);
return;
}
"Trying %s %s address %s for mailer %s\n",
: "envelope",
: "recipient", q, p);
"Rcode = %d, addr = %s\n",
}
{
if (*p == '\0')
{
"Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
return;
}
for (; *p != '\0'; p++)
{
switch (*p)
{
case 'H':
case 'h':
break;
case 'E':
case 'e':
tryflags &= ~RF_HEADERADDR;
break;
case 'S':
case 's':
break;
case 'R':
case 'r':
tryflags &= ~RF_SENDERADDR;
break;
}
}
}
{
if (*p == '\0')
{
"Usage: /parse address\n");
return;
}
q = crackaddr(p, e);
"Cracked address = ");
"\nParsing %s %s address\n",
"header" : "envelope",
"sender" : "recipient");
== NULL)
"Cannot parse\n");
"mailer %s, host %s, user %s\n",
a.q_host,
a.q_user);
else
"mailer %s, user %s\n",
a.q_user);
}
{
unsigned long ul;
"ul = %lu\n", ul);
}
else
{
"Unknown \"/\" command %s\n",
line);
}
return;
}
continue;
q = p;
p++;
if (*p == '\0')
{
"No address!\n");
return;
}
*p = '\0';
return;
do
{
register char **pvp;
continue;
p = q;
while (*p != '\0')
{
int status;
if (rs < 0)
{
"Undefined ruleset %s\n",
p);
break;
}
"== Ruleset %s (%d) status %d\n",
else if (eightbit)
{
true);
"cataddr: %s\n",
}
while (*p != '\0' && *p++ != ',')
continue;
}
} while (*(p = delimptr) != '\0');
}
static void
dump_class(s, id)
register STAB *s;
int id;
{
return;
"%s\n", s->s_name);
}
/*
** An exception type used to create QuickAbort exceptions.
** This is my first cut at converting QuickAbort from longjmp to exceptions.
** These exceptions have a single integer argument, which is the argument
** to longjmp in the original code (either 1 or 2). I don't know the
** significance of 1 vs 2: the calls to setjmp don't care.
*/
const SM_EXC_TYPE_T EtypeQuickAbort =
{
"E:mta.quickabort",
"i",
"quick abort %0",
};