Index: vendor/sendmail/dist/src/conf.c =================================================================== --- vendor/sendmail/dist/src/conf.c (revision 351552) +++ vendor/sendmail/dist/src/conf.c (revision 351553) @@ -1,6592 +1,6606 @@ /* * Copyright (c) 1998-2013 Proofpoint, 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. * */ #include SM_RCSID("@(#)$Id: conf.c,v 8.1192 2014-01-27 18:23:21 ca Exp $") #include #include #if NEWDB # include "sm/bdb.h" #endif /* NEWDB */ #include #include "map.h" #ifdef DEC # if NETINET6 /* for the IPv6 device lookup */ # define _SOCKADDR_LEN # include # endif /* NETINET6 */ #endif /* DEC */ # include # include #include #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #if HASULIMIT && defined(HPUX11) # include #endif /* HASULIMIT && defined(HPUX11) */ static void setupmaps __P((void)); static void setupmailers __P((void)); static void setupqueues __P((void)); static int get_num_procs_online __P((void)); static int add_hostnames __P((SOCKADDR *)); #if NETINET6 && NEEDSGETIPNODE static struct hostent *sm_getipnodebyname __P((const char *, int, int, int *)); static struct hostent *sm_getipnodebyaddr __P((const void *, size_t, int, int *)); #else /* NETINET6 && NEEDSGETIPNODE */ #define sm_getipnodebyname getipnodebyname #define sm_getipnodebyaddr getipnodebyaddr #endif /* NETINET6 && NEEDSGETIPNODE */ /* ** CONF.C -- Sendmail Configuration Tables. ** ** Defines the configuration of this installation. ** ** Configuration Variables: ** HdrInfo -- a table describing well-known header fields. ** Each entry has the field name and some flags, ** which are described in sendmail.h. ** ** Notes: ** I have tried to put almost all the reasonable ** configuration information into the configuration ** file read at runtime. My intent is that anything ** here is a function of the version of UNIX you ** are running, or is really static -- for example ** the headers are a superset of widely used ** protocols. If you find yourself playing with ** this file too much, you may be making a mistake! */ /* ** Header info table ** Final (null) entry contains the flags used for any other field. ** ** Not all of these are actually handled specially by sendmail ** at this time. They are included as placeholders, to let ** you know that "someday" I intend to have sendmail do ** something with them. */ struct hdrinfo HdrInfo[] = { /* originator fields, most to least significant */ { "resent-sender", H_FROM|H_RESENT, NULL }, { "resent-from", H_FROM|H_RESENT, NULL }, { "resent-reply-to", H_FROM|H_RESENT, NULL }, { "sender", H_FROM, NULL }, { "from", H_FROM, NULL }, { "reply-to", H_FROM, NULL }, { "errors-to", H_FROM|H_ERRORSTO, NULL }, { "full-name", H_ACHECK, NULL }, { "return-receipt-to", H_RECEIPTTO, NULL }, { "delivery-receipt-to", H_RECEIPTTO, NULL }, { "disposition-notification-to", H_FROM, NULL }, /* destination fields */ { "to", H_RCPT, NULL }, { "resent-to", H_RCPT|H_RESENT, NULL }, { "cc", H_RCPT, NULL }, { "resent-cc", H_RCPT|H_RESENT, NULL }, { "bcc", H_RCPT|H_BCC, NULL }, { "resent-bcc", H_RCPT|H_BCC|H_RESENT, NULL }, { "apparently-to", H_RCPT, NULL }, /* message identification and control */ { "message-id", 0, NULL }, { "resent-message-id", H_RESENT, NULL }, { "message", H_EOH, NULL }, { "text", H_EOH, NULL }, /* date fields */ { "date", 0, NULL }, { "resent-date", H_RESENT, NULL }, /* trace fields */ { "received", H_TRACE|H_FORCE, NULL }, { "x400-received", H_TRACE|H_FORCE, NULL }, { "via", H_TRACE|H_FORCE, NULL }, { "mail-from", H_TRACE|H_FORCE, NULL }, /* miscellaneous fields */ { "comments", H_FORCE|H_ENCODABLE, NULL }, { "return-path", H_FORCE|H_ACHECK|H_BINDLATE, NULL }, { "content-transfer-encoding", H_CTE, NULL }, { "content-type", H_CTYPE, NULL }, { "content-length", H_ACHECK, NULL }, { "subject", H_ENCODABLE, NULL }, { "x-authentication-warning", H_FORCE, NULL }, { NULL, 0, NULL } }; /* ** Privacy values */ struct prival PrivacyValues[] = { { "public", PRIV_PUBLIC }, { "needmailhelo", PRIV_NEEDMAILHELO }, { "needexpnhelo", PRIV_NEEDEXPNHELO }, { "needvrfyhelo", PRIV_NEEDVRFYHELO }, { "noexpn", PRIV_NOEXPN }, { "novrfy", PRIV_NOVRFY }, { "restrictexpand", PRIV_RESTRICTEXPAND }, { "restrictmailq", PRIV_RESTRICTMAILQ }, { "restrictqrun", PRIV_RESTRICTQRUN }, { "noetrn", PRIV_NOETRN }, { "noverb", PRIV_NOVERB }, { "authwarnings", PRIV_AUTHWARNINGS }, { "noreceipts", PRIV_NORECEIPTS }, { "nobodyreturn", PRIV_NOBODYRETN }, { "goaway", PRIV_GOAWAY }, { "noactualrecipient", PRIV_NOACTUALRECIPIENT }, { NULL, 0 } }; /* ** DontBlameSendmail values */ struct dbsval DontBlameSendmailValues[] = { { "safe", DBS_SAFE }, { "assumesafechown", DBS_ASSUMESAFECHOWN }, { "groupwritabledirpathsafe", DBS_GROUPWRITABLEDIRPATHSAFE }, { "groupwritableforwardfilesafe", DBS_GROUPWRITABLEFORWARDFILESAFE }, { "groupwritableincludefilesafe", DBS_GROUPWRITABLEINCLUDEFILESAFE }, { "groupwritablealiasfile", DBS_GROUPWRITABLEALIASFILE }, { "worldwritablealiasfile", DBS_WORLDWRITABLEALIASFILE }, { "forwardfileinunsafedirpath", DBS_FORWARDFILEINUNSAFEDIRPATH }, { "includefileinunsafedirpath", DBS_INCLUDEFILEINUNSAFEDIRPATH }, { "mapinunsafedirpath", DBS_MAPINUNSAFEDIRPATH }, { "linkedaliasfileinwritabledir", DBS_LINKEDALIASFILEINWRITABLEDIR }, { "linkedclassfileinwritabledir", DBS_LINKEDCLASSFILEINWRITABLEDIR }, { "linkedforwardfileinwritabledir", DBS_LINKEDFORWARDFILEINWRITABLEDIR }, { "linkedincludefileinwritabledir", DBS_LINKEDINCLUDEFILEINWRITABLEDIR }, { "linkedmapinwritabledir", DBS_LINKEDMAPINWRITABLEDIR }, { "linkedserviceswitchfileinwritabledir", DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR }, { "filedeliverytohardlink", DBS_FILEDELIVERYTOHARDLINK }, { "filedeliverytosymlink", DBS_FILEDELIVERYTOSYMLINK }, { "writemaptohardlink", DBS_WRITEMAPTOHARDLINK }, { "writemaptosymlink", DBS_WRITEMAPTOSYMLINK }, { "writestatstohardlink", DBS_WRITESTATSTOHARDLINK }, { "writestatstosymlink", DBS_WRITESTATSTOSYMLINK }, { "forwardfileingroupwritabledirpath", DBS_FORWARDFILEINGROUPWRITABLEDIRPATH }, { "includefileingroupwritabledirpath", DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH }, { "classfileinunsafedirpath", DBS_CLASSFILEINUNSAFEDIRPATH }, { "errorheaderinunsafedirpath", DBS_ERRORHEADERINUNSAFEDIRPATH }, { "helpfileinunsafedirpath", DBS_HELPFILEINUNSAFEDIRPATH }, { "forwardfileinunsafedirpathsafe", DBS_FORWARDFILEINUNSAFEDIRPATHSAFE }, { "includefileinunsafedirpathsafe", DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE }, { "runprograminunsafedirpath", DBS_RUNPROGRAMINUNSAFEDIRPATH }, { "runwritableprogram", DBS_RUNWRITABLEPROGRAM }, { "nonrootsafeaddr", DBS_NONROOTSAFEADDR }, { "truststickybit", DBS_TRUSTSTICKYBIT }, { "dontwarnforwardfileinunsafedirpath", DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH }, { "insufficiententropy", DBS_INSUFFICIENTENTROPY }, { "groupreadablesasldbfile", DBS_GROUPREADABLESASLDBFILE }, { "groupwritablesasldbfile", DBS_GROUPWRITABLESASLDBFILE }, { "groupwritableforwardfile", DBS_GROUPWRITABLEFORWARDFILE }, { "groupwritableincludefile", DBS_GROUPWRITABLEINCLUDEFILE }, { "worldwritableforwardfile", DBS_WORLDWRITABLEFORWARDFILE }, { "worldwritableincludefile", DBS_WORLDWRITABLEINCLUDEFILE }, { "groupreadablekeyfile", DBS_GROUPREADABLEKEYFILE }, { "groupreadabledefaultauthinfofile", DBS_GROUPREADABLEAUTHINFOFILE }, { NULL, 0 } }; /* ** Miscellaneous stuff. */ int DtableSize = 50; /* max open files; reset in 4.2bsd */ /* ** SETDEFAULTS -- set default values ** ** Some of these must be initialized using direct code since they ** depend on run-time values. So let's do all of them this way. ** ** Parameters: ** e -- the default envelope. ** ** Returns: ** none. ** ** Side Effects: ** Initializes a bunch of global variables to their ** default values. */ #define MINUTES * 60 #define HOURS * 60 MINUTES #define DAYS * 24 HOURS #ifndef MAXRULERECURSION # define MAXRULERECURSION 50 /* max ruleset recursion depth */ #endif /* ! MAXRULERECURSION */ void setdefaults(e) register ENVELOPE *e; { int i; int numprocs; struct passwd *pw; numprocs = get_num_procs_online(); SpaceSub = ' '; /* option B */ QueueLA = 8 * numprocs; /* option x */ RefuseLA = 12 * numprocs; /* option X */ WkRecipFact = 30000L; /* option y */ WkClassFact = 1800L; /* option z */ WkTimeFact = 90000L; /* option Z */ QueueFactor = WkRecipFact * 20; /* option q */ QueueMode = QM_NORMAL; /* what queue items to act upon */ FileMode = (RealUid != geteuid()) ? 0644 : 0600; /* option F */ QueueFileMode = (RealUid != geteuid()) ? 0644 : 0600; /* option QueueFileMode */ if (((pw = sm_getpwnam("mailnull")) != NULL && pw->pw_uid != 0) || ((pw = sm_getpwnam("sendmail")) != NULL && pw->pw_uid != 0) || ((pw = sm_getpwnam("daemon")) != NULL && pw->pw_uid != 0)) { DefUid = pw->pw_uid; /* option u */ DefGid = pw->pw_gid; /* option g */ DefUser = newstr(pw->pw_name); } else { DefUid = 1; /* option u */ DefGid = 1; /* option g */ setdefuser(); } TrustedUid = 0; if (tTd(37, 4)) sm_dprintf("setdefaults: DefUser=%s, DefUid=%ld, DefGid=%ld\n", DefUser != NULL ? DefUser : "<1:1>", (long) DefUid, (long) DefGid); CheckpointInterval = 10; /* option C */ MaxHopCount = 25; /* option h */ set_delivery_mode(SM_FORK, e); /* option d */ e->e_errormode = EM_PRINT; /* option e */ e->e_qgrp = NOQGRP; e->e_qdir = NOQDIR; e->e_xfqgrp = NOQGRP; e->e_xfqdir = NOQDIR; e->e_ctime = curtime(); SevenBitInput = false; /* option 7 */ MaxMciCache = 1; /* option k */ MciCacheTimeout = 5 MINUTES; /* option K */ LogLevel = 9; /* option L */ #if MILTER MilterLogLevel = -1; #endif /* MILTER */ inittimeouts(NULL, false); /* option r */ PrivacyFlags = PRIV_PUBLIC; /* option p */ MeToo = true; /* option m */ SendMIMEErrors = true; /* option f */ SuperSafe = SAFE_REALLY; /* option s */ clrbitmap(DontBlameSendmail); /* DontBlameSendmail option */ #if MIME8TO7 MimeMode = MM_CVTMIME|MM_PASS8BIT; /* option 8 */ #else /* MIME8TO7 */ MimeMode = MM_PASS8BIT; #endif /* MIME8TO7 */ for (i = 0; i < MAXTOCLASS; i++) { TimeOuts.to_q_return[i] = 5 DAYS; /* option T */ TimeOuts.to_q_warning[i] = 0; /* option T */ } ServiceSwitchFile = "/etc/mail/service.switch"; ServiceCacheMaxAge = (time_t) 10; HostsFile = _PATH_HOSTS; PidFile = newstr(_PATH_SENDMAILPID); MustQuoteChars = "@,;:\\()[].'"; MciInfoTimeout = 30 MINUTES; MaxRuleRecursion = MAXRULERECURSION; MaxAliasRecursion = 10; MaxMacroRecursion = 10; ColonOkInAddr = true; DontLockReadFiles = true; DontProbeInterfaces = DPI_PROBEALL; DoubleBounceAddr = "postmaster"; MaxHeadersLength = MAXHDRSLEN; MaxMimeHeaderLength = MAXLINE; MaxMimeFieldLength = MaxMimeHeaderLength / 2; MaxForwardEntries = 0; FastSplit = 1; MaxNOOPCommands = MAXNOOPCOMMANDS; #if SASL AuthMechanisms = newstr(AUTH_MECHANISMS); AuthRealm = NULL; MaxSLBits = INT_MAX; #endif /* SASL */ #if STARTTLS TLS_Srv_Opts = TLS_I_SRV; if (NULL == EVP_digest) EVP_digest = EVP_md5(); + Srv_SSL_Options = SSL_OP_ALL; + Clt_SSL_Options = SSL_OP_ALL +# ifdef SSL_OP_NO_SSLv2 + | SSL_OP_NO_SSLv2 +# endif +# ifdef SSL_OP_NO_TICKET + | SSL_OP_NO_TICKET +# endif + ; +# ifdef SSL_OP_TLSEXT_PADDING + /* SSL_OP_TLSEXT_PADDING breaks compatibility with some sites */ + Srv_SSL_Options &= ~SSL_OP_TLSEXT_PADDING; + Clt_SSL_Options &= ~SSL_OP_TLSEXT_PADDING; +# endif /* SSL_OP_TLSEXT_PADDING */ #endif /* STARTTLS */ #ifdef HESIOD_INIT HesiodContext = NULL; #endif /* HESIOD_INIT */ #if NETINET6 /* Detect if IPv6 is available at run time */ i = socket(AF_INET6, SOCK_STREAM, 0); if (i >= 0) { InetMode = AF_INET6; (void) close(i); } else InetMode = AF_INET; #if !IPV6_FULL UseCompressedIPv6Addresses = true; #endif #else /* NETINET6 */ InetMode = AF_INET; #endif /* NETINET6 */ ControlSocketName = NULL; memset(&ConnectOnlyTo, '\0', sizeof(ConnectOnlyTo)); DataFileBufferSize = 4096; XscriptFileBufferSize = 4096; for (i = 0; i < MAXRWSETS; i++) RuleSetNames[i] = NULL; #if MILTER InputFilters[0] = NULL; #endif /* MILTER */ RejectLogInterval = 3 HOURS; #if REQUIRES_DIR_FSYNC RequiresDirfsync = true; #endif /* REQUIRES_DIR_FSYNC */ #if _FFR_RCPTTHROTDELAY BadRcptThrottleDelay = 1; #endif /* _FFR_RCPTTHROTDELAY */ ConnectionRateWindowSize = 60; #if _FFR_BOUNCE_QUEUE BounceQueue = NOQGRP; #endif /* _FFR_BOUNCE_QUEUE */ setupmaps(); setupqueues(); setupmailers(); setupheaders(); } /* ** SETDEFUSER -- set/reset DefUser using DefUid (for initgroups()) */ void setdefuser() { struct passwd *defpwent; static char defuserbuf[40]; DefUser = defuserbuf; defpwent = sm_getpwuid(DefUid); (void) sm_strlcpy(defuserbuf, (defpwent == NULL || defpwent->pw_name == NULL) ? "nobody" : defpwent->pw_name, sizeof(defuserbuf)); if (tTd(37, 4)) sm_dprintf("setdefuser: DefUid=%ld, DefUser=%s\n", (long) DefUid, DefUser); } /* ** SETUPQUEUES -- initialize default queues ** ** The mqueue QUEUE structure gets filled in after readcf() but ** we need something to point to now for the mailer setup, ** which use "mqueue" as default queue. */ static void setupqueues() { char buf[100]; MaxRunnersPerQueue = 1; (void) sm_strlcpy(buf, "mqueue, P=/var/spool/mqueue", sizeof(buf)); makequeue(buf, false); } /* ** SETUPMAILERS -- initialize default mailers */ static void setupmailers() { char buf[100]; (void) sm_strlcpy(buf, "prog, P=/bin/sh, F=lsouDq9, T=X-Unix/X-Unix/X-Unix, A=sh -c \201u", sizeof(buf)); makemailer(buf); (void) sm_strlcpy(buf, "*file*, P=[FILE], F=lsDFMPEouq9, T=X-Unix/X-Unix/X-Unix, A=FILE \201u", sizeof(buf)); makemailer(buf); (void) sm_strlcpy(buf, "*include*, P=/dev/null, F=su, A=INCLUDE \201u", sizeof(buf)); makemailer(buf); initerrmailers(); } /* ** SETUPMAPS -- set up map classes */ #define MAPDEF(name, ext, flags, parse, open, close, lookup, store) \ { \ extern bool parse __P((MAP *, char *)); \ extern bool open __P((MAP *, int)); \ extern void close __P((MAP *)); \ extern char *lookup __P((MAP *, char *, char **, int *)); \ extern void store __P((MAP *, char *, char *)); \ s = stab(name, ST_MAPCLASS, ST_ENTER); \ s->s_mapclass.map_cname = name; \ s->s_mapclass.map_ext = ext; \ s->s_mapclass.map_cflags = flags; \ s->s_mapclass.map_parse = parse; \ s->s_mapclass.map_open = open; \ s->s_mapclass.map_close = close; \ s->s_mapclass.map_lookup = lookup; \ s->s_mapclass.map_store = store; \ } static void setupmaps() { register STAB *s; #if NEWDB # if DB_VERSION_MAJOR > 1 int major_v, minor_v, patch_v; (void) db_version(&major_v, &minor_v, &patch_v); if (major_v != DB_VERSION_MAJOR || minor_v != DB_VERSION_MINOR) { errno = 0; syserr("Berkeley DB version mismatch: compiled against %d.%d.%d, run-time linked against %d.%d.%d", DB_VERSION_MAJOR, DB_VERSION_MINOR, DB_VERSION_PATCH, major_v, minor_v, patch_v); } # endif /* DB_VERSION_MAJOR > 1 */ MAPDEF("hash", ".db", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, hash_map_open, db_map_close, db_map_lookup, db_map_store); MAPDEF("btree", ".db", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, bt_map_open, db_map_close, db_map_lookup, db_map_store); #endif /* NEWDB */ #if NDBM MAPDEF("dbm", ".dir", MCF_ALIASOK|MCF_REBUILDABLE, map_parseargs, ndbm_map_open, ndbm_map_close, ndbm_map_lookup, ndbm_map_store); #endif /* NDBM */ #if NIS MAPDEF("nis", NULL, MCF_ALIASOK, map_parseargs, nis_map_open, null_map_close, nis_map_lookup, null_map_store); #endif /* NIS */ #if NISPLUS MAPDEF("nisplus", NULL, MCF_ALIASOK, map_parseargs, nisplus_map_open, null_map_close, nisplus_map_lookup, null_map_store); #endif /* NISPLUS */ #if LDAPMAP MAPDEF("ldap", NULL, MCF_ALIASOK|MCF_NOTPERSIST, ldapmap_parseargs, ldapmap_open, ldapmap_close, ldapmap_lookup, null_map_store); #endif /* LDAPMAP */ #if PH_MAP MAPDEF("ph", NULL, MCF_NOTPERSIST, ph_map_parseargs, ph_map_open, ph_map_close, ph_map_lookup, null_map_store); #endif /* PH_MAP */ #if MAP_NSD /* IRIX 6.5 nsd support */ MAPDEF("nsd", NULL, MCF_ALIASOK, map_parseargs, null_map_open, null_map_close, nsd_map_lookup, null_map_store); #endif /* MAP_NSD */ #if HESIOD MAPDEF("hesiod", NULL, MCF_ALIASOK|MCF_ALIASONLY, map_parseargs, hes_map_open, hes_map_close, hes_map_lookup, null_map_store); #endif /* HESIOD */ #if NETINFO MAPDEF("netinfo", NULL, MCF_ALIASOK, map_parseargs, ni_map_open, null_map_close, ni_map_lookup, null_map_store); #endif /* NETINFO */ #if 0 MAPDEF("dns", NULL, 0, dns_map_init, null_map_open, null_map_close, dns_map_lookup, null_map_store); #endif /* 0 */ #if NAMED_BIND # if DNSMAP # if _FFR_DNSMAP_ALIASABLE MAPDEF("dns", NULL, MCF_ALIASOK, dns_map_parseargs, dns_map_open, null_map_close, dns_map_lookup, null_map_store); # else /* _FFR_DNSMAP_ALIASABLE */ MAPDEF("dns", NULL, 0, dns_map_parseargs, dns_map_open, null_map_close, dns_map_lookup, null_map_store); # endif /* _FFR_DNSMAP_ALIASABLE */ # endif /* DNSMAP */ #endif /* NAMED_BIND */ #if NAMED_BIND /* best MX DNS lookup */ MAPDEF("bestmx", NULL, MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, bestmx_map_lookup, null_map_store); #endif /* NAMED_BIND */ MAPDEF("host", NULL, 0, host_map_init, null_map_open, null_map_close, host_map_lookup, null_map_store); MAPDEF("text", NULL, MCF_ALIASOK, map_parseargs, text_map_open, null_map_close, text_map_lookup, null_map_store); MAPDEF("stab", NULL, MCF_ALIASOK|MCF_ALIASONLY, map_parseargs, stab_map_open, null_map_close, stab_map_lookup, stab_map_store); MAPDEF("implicit", NULL, MCF_ALIASOK|MCF_ALIASONLY|MCF_REBUILDABLE, map_parseargs, impl_map_open, impl_map_close, impl_map_lookup, impl_map_store); /* access to system passwd file */ MAPDEF("user", NULL, MCF_OPTFILE, map_parseargs, user_map_open, null_map_close, user_map_lookup, null_map_store); /* dequote map */ MAPDEF("dequote", NULL, 0, dequote_init, null_map_open, null_map_close, dequote_map, null_map_store); #if MAP_REGEX MAPDEF("regex", NULL, 0, regex_map_init, null_map_open, null_map_close, regex_map_lookup, null_map_store); #endif /* MAP_REGEX */ #if USERDB /* user database */ MAPDEF("userdb", ".db", 0, map_parseargs, null_map_open, null_map_close, udb_map_lookup, null_map_store); #endif /* USERDB */ /* arbitrary programs */ MAPDEF("program", NULL, MCF_ALIASOK, map_parseargs, null_map_open, null_map_close, prog_map_lookup, null_map_store); /* sequenced maps */ MAPDEF("sequence", NULL, MCF_ALIASOK, seq_map_parse, null_map_open, null_map_close, seq_map_lookup, seq_map_store); /* switched interface to sequenced maps */ MAPDEF("switch", NULL, MCF_ALIASOK, map_parseargs, switch_map_open, null_map_close, seq_map_lookup, seq_map_store); /* null map lookup -- really for internal use only */ MAPDEF("null", NULL, MCF_ALIASOK|MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, null_map_lookup, null_map_store); /* syslog map -- logs information to syslog */ MAPDEF("syslog", NULL, 0, syslog_map_parseargs, null_map_open, null_map_close, syslog_map_lookup, null_map_store); /* macro storage map -- rulesets can set macros */ MAPDEF("macro", NULL, 0, dequote_init, null_map_open, null_map_close, macro_map_lookup, null_map_store); /* arithmetic map -- add/subtract/compare */ MAPDEF("arith", NULL, 0, dequote_init, null_map_open, null_map_close, arith_map_lookup, null_map_store); /* "arpa" map -- IP -> arpa */ MAPDEF("arpa", NULL, 0, dequote_init, null_map_open, null_map_close, arpa_map_lookup, null_map_store); #if SOCKETMAP /* arbitrary daemons */ MAPDEF("socket", NULL, MCF_ALIASOK, map_parseargs, socket_map_open, socket_map_close, socket_map_lookup, null_map_store); #endif /* SOCKETMAP */ #if _FFR_DPRINTF_MAP /* dprintf map -- logs information to syslog */ MAPDEF("dprintf", NULL, 0, dprintf_map_parseargs, null_map_open, null_map_close, dprintf_map_lookup, null_map_store); #endif /* _FFR_DPRINTF_MAP */ if (tTd(38, 2)) { /* bogus map -- always return tempfail */ MAPDEF("bogus", NULL, MCF_ALIASOK|MCF_OPTFILE, map_parseargs, null_map_open, null_map_close, bogus_map_lookup, null_map_store); } } #undef MAPDEF /* ** INITHOSTMAPS -- initial host-dependent maps ** ** This should act as an interface to any local service switch ** provided by the host operating system. ** ** Parameters: ** none ** ** Returns: ** none ** ** Side Effects: ** Should define maps "host" and "users" as necessary ** for this OS. If they are not defined, they will get ** a default value later. It should check to make sure ** they are not defined first, since it's possible that ** the config file has provided an override. */ void inithostmaps() { register int i; int nmaps; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; char buf[MAXLINE]; /* ** Make sure we have a host map. */ if (stab("host", ST_MAP, ST_FIND) == NULL) { /* user didn't initialize: set up host map */ (void) sm_strlcpy(buf, "host host", sizeof(buf)); #if NAMED_BIND if (ConfigLevel >= 2) (void) sm_strlcat(buf, " -a. -D", sizeof(buf)); #endif /* NAMED_BIND */ (void) makemapentry(buf); } /* ** Set up default aliases maps */ nmaps = switch_map_find("aliases", maptype, mapreturn); for (i = 0; i < nmaps; i++) { if (strcmp(maptype[i], "files") == 0 && stab("aliases.files", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.files null", sizeof(buf)); (void) makemapentry(buf); } #if NISPLUS else if (strcmp(maptype[i], "nisplus") == 0 && stab("aliases.nisplus", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.nisplus nisplus -kalias -vexpansion mail_aliases.org_dir", sizeof(buf)); (void) makemapentry(buf); } #endif /* NISPLUS */ #if NIS else if (strcmp(maptype[i], "nis") == 0 && stab("aliases.nis", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.nis nis mail.aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* NIS */ #if NETINFO else if (strcmp(maptype[i], "netinfo") == 0 && stab("aliases.netinfo", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.netinfo netinfo -z, /aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* NETINFO */ #if HESIOD else if (strcmp(maptype[i], "hesiod") == 0 && stab("aliases.hesiod", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.hesiod hesiod aliases", sizeof(buf)); (void) makemapentry(buf); } #endif /* HESIOD */ #if LDAPMAP && defined(SUN_EXTENSIONS) && \ defined(SUN_SIMPLIFIED_LDAP) && HASLDAPGETALIASBYNAME else if (strcmp(maptype[i], "ldap") == 0 && stab("aliases.ldap", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases.ldap ldap -b . -h localhost -k mail=%0 -v mailgroup", sizeof buf); (void) makemapentry(buf); } #endif /* LDAPMAP && defined(SUN_EXTENSIONS) && ... */ } if (stab("aliases", ST_MAP, ST_FIND) == NULL) { (void) sm_strlcpy(buf, "aliases switch aliases", sizeof(buf)); (void) makemapentry(buf); } } /* ** SWITCH_MAP_FIND -- find the list of types associated with a map ** ** This is the system-dependent interface to the service switch. ** ** Parameters: ** service -- the name of the service of interest. ** maptype -- an out-array of strings containing the types ** of access to use for this service. There can ** be at most MAXMAPSTACK types for a single service. ** mapreturn -- an out-array of return information bitmaps ** for the map. ** ** Returns: ** The number of map types filled in, or -1 for failure. ** ** Side effects: ** Preserves errno so nothing in the routine clobbers it. */ #if defined(SOLARIS) || (defined(sony_news) && defined(__svr4)) # define _USE_SUN_NSSWITCH_ #endif /* defined(SOLARIS) || (defined(sony_news) && defined(__svr4)) */ #if _FFR_HPUX_NSSWITCH # ifdef __hpux # define _USE_SUN_NSSWITCH_ # endif /* __hpux */ #endif /* _FFR_HPUX_NSSWITCH */ #ifdef _USE_SUN_NSSWITCH_ # include #endif /* _USE_SUN_NSSWITCH_ */ #if defined(ultrix) || (defined(__osf__) && defined(__alpha)) # define _USE_DEC_SVC_CONF_ #endif /* defined(ultrix) || (defined(__osf__) && defined(__alpha)) */ #ifdef _USE_DEC_SVC_CONF_ # include #endif /* _USE_DEC_SVC_CONF_ */ int switch_map_find(service, maptype, mapreturn) char *service; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; { int svcno = 0; int save_errno = errno; #ifdef _USE_SUN_NSSWITCH_ struct __nsw_switchconfig *nsw_conf; enum __nsw_parse_err pserr; struct __nsw_lookup *lk; static struct __nsw_lookup lkp0 = { "files", {1, 0, 0, 0}, NULL, NULL }; static struct __nsw_switchconfig lkp_default = { 0, "sendmail", 3, &lkp0 }; for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; if ((nsw_conf = __nsw_getconfig(service, &pserr)) == NULL) lk = lkp_default.lookups; else lk = nsw_conf->lookups; svcno = 0; while (lk != NULL && svcno < MAXMAPSTACK) { maptype[svcno] = lk->service_name; if (lk->actions[__NSW_NOTFOUND] == __NSW_RETURN) mapreturn[MA_NOTFOUND] |= 1 << svcno; if (lk->actions[__NSW_TRYAGAIN] == __NSW_RETURN) mapreturn[MA_TRYAGAIN] |= 1 << svcno; if (lk->actions[__NSW_UNAVAIL] == __NSW_RETURN) mapreturn[MA_TRYAGAIN] |= 1 << svcno; svcno++; lk = lk->next; } errno = save_errno; return svcno; #endif /* _USE_SUN_NSSWITCH_ */ #ifdef _USE_DEC_SVC_CONF_ struct svcinfo *svcinfo; int svc; for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; svcinfo = getsvc(); if (svcinfo == NULL) goto punt; if (strcmp(service, "hosts") == 0) svc = SVC_HOSTS; else if (strcmp(service, "aliases") == 0) svc = SVC_ALIASES; else if (strcmp(service, "passwd") == 0) svc = SVC_PASSWD; else { errno = save_errno; return -1; } for (svcno = 0; svcno < SVC_PATHSIZE && svcno < MAXMAPSTACK; svcno++) { switch (svcinfo->svcpath[svc][svcno]) { case SVC_LOCAL: maptype[svcno] = "files"; break; case SVC_YP: maptype[svcno] = "nis"; break; case SVC_BIND: maptype[svcno] = "dns"; break; # ifdef SVC_HESIOD case SVC_HESIOD: maptype[svcno] = "hesiod"; break; # endif /* SVC_HESIOD */ case SVC_LAST: errno = save_errno; return svcno; } } errno = save_errno; return svcno; #endif /* _USE_DEC_SVC_CONF_ */ #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) /* ** Fall-back mechanism. */ STAB *st; static time_t servicecachetime; /* time service switch was cached */ time_t now = curtime(); for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; if ((now - servicecachetime) > (time_t) ServiceCacheMaxAge) { /* (re)read service switch */ register SM_FILE_T *fp; long sff = SFF_REGONLY|SFF_OPENASROOT|SFF_NOLOCK; if (!bitnset(DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (ConfigFileRead) servicecachetime = now; fp = safefopen(ServiceSwitchFile, O_RDONLY, 0, sff); if (fp != NULL) { char buf[MAXLINE]; while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *p; p = strpbrk(buf, "#\n"); if (p != NULL) *p = '\0'; #ifndef SM_NSSWITCH_DELIMS # define SM_NSSWITCH_DELIMS " \t" #endif /* SM_NSSWITCH_DELIMS */ p = strpbrk(buf, SM_NSSWITCH_DELIMS); if (p != NULL) *p++ = '\0'; if (buf[0] == '\0') continue; if (p == NULL) { sm_syslog(LOG_ERR, NOQID, "Bad line on %.100s: %.100s", ServiceSwitchFile, buf); continue; } while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') continue; /* ** Find/allocate space for this service entry. ** Space for all of the service strings ** are allocated at once. This means ** that we only have to free the first ** one to free all of them. */ st = stab(buf, ST_SERVICE, ST_ENTER); if (st->s_service[0] != NULL) sm_free((void *) st->s_service[0]); /* XXX */ p = newstr(p); for (svcno = 0; svcno < MAXMAPSTACK; ) { if (*p == '\0') break; st->s_service[svcno++] = p; p = strpbrk(p, " \t"); if (p == NULL) break; *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; } if (svcno < MAXMAPSTACK) st->s_service[svcno] = NULL; } (void) sm_io_close(fp, SM_TIME_DEFAULT); } } /* look up entry in cache */ st = stab(service, ST_SERVICE, ST_FIND); if (st != NULL && st->s_service[0] != NULL) { /* extract data */ svcno = 0; while (svcno < MAXMAPSTACK) { maptype[svcno] = st->s_service[svcno]; if (maptype[svcno++] == NULL) break; } errno = save_errno; return --svcno; } #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */ #if !defined(_USE_SUN_NSSWITCH_) /* if the service file doesn't work, use an absolute fallback */ # ifdef _USE_DEC_SVC_CONF_ punt: # endif /* _USE_DEC_SVC_CONF_ */ for (svcno = 0; svcno < MAXMAPACTIONS; svcno++) mapreturn[svcno] = 0; svcno = 0; if (strcmp(service, "aliases") == 0) { maptype[svcno++] = "files"; # if defined(AUTO_NETINFO_ALIASES) && defined (NETINFO) maptype[svcno++] = "netinfo"; # endif /* defined(AUTO_NETINFO_ALIASES) && defined (NETINFO) */ # ifdef AUTO_NIS_ALIASES # if NISPLUS maptype[svcno++] = "nisplus"; # endif /* NISPLUS */ # if NIS maptype[svcno++] = "nis"; # endif /* NIS */ # endif /* AUTO_NIS_ALIASES */ errno = save_errno; return svcno; } if (strcmp(service, "hosts") == 0) { # if NAMED_BIND maptype[svcno++] = "dns"; # else /* NAMED_BIND */ # if defined(sun) && !defined(BSD) /* SunOS */ maptype[svcno++] = "nis"; # endif /* defined(sun) && !defined(BSD) */ # endif /* NAMED_BIND */ # if defined(AUTO_NETINFO_HOSTS) && defined (NETINFO) maptype[svcno++] = "netinfo"; # endif /* defined(AUTO_NETINFO_HOSTS) && defined (NETINFO) */ maptype[svcno++] = "files"; errno = save_errno; return svcno; } errno = save_errno; return -1; #endif /* !defined(_USE_SUN_NSSWITCH_) */ } /* ** USERNAME -- return the user id of the logged in user. ** ** Parameters: ** none. ** ** Returns: ** The login name of the logged in user. ** ** Side Effects: ** none. ** ** Notes: ** The return value is statically allocated. */ char * username() { static char *myname = NULL; extern char *getlogin(); register struct passwd *pw; /* cache the result */ if (myname == NULL) { myname = getlogin(); if (myname == NULL || myname[0] == '\0') { pw = sm_getpwuid(RealUid); if (pw != NULL) myname = pw->pw_name; } else { uid_t uid = RealUid; if ((pw = sm_getpwnam(myname)) == NULL || (uid != 0 && uid != pw->pw_uid)) { pw = sm_getpwuid(uid); if (pw != NULL) myname = pw->pw_name; } } if (myname == NULL || myname[0] == '\0') { syserr("554 5.3.0 Who are you?"); myname = "postmaster"; } else if (strpbrk(myname, ",;:/|\"\\") != NULL) myname = addquotes(myname, NULL); else myname = sm_pstrdup_x(myname); } return myname; } /* ** TTYPATH -- Get the path of the user's tty ** ** Returns the pathname of the user's tty. Returns NULL if ** the user is not logged in or if s/he has write permission ** denied. ** ** Parameters: ** none ** ** Returns: ** pathname of the user's tty. ** NULL if not logged in or write permission denied. ** ** Side Effects: ** none. ** ** WARNING: ** Return value is in a local buffer. ** ** Called By: ** savemail */ char * ttypath() { struct stat stbuf; register char *pathn; extern char *ttyname(); extern char *getlogin(); /* compute the pathname of the controlling tty */ if ((pathn = ttyname(2)) == NULL && (pathn = ttyname(1)) == NULL && (pathn = ttyname(0)) == NULL) { errno = 0; return NULL; } /* see if we have write permission */ if (stat(pathn, &stbuf) < 0 || !bitset(S_IWOTH, stbuf.st_mode)) { errno = 0; return NULL; } /* see if the user is logged in */ if (getlogin() == NULL) return NULL; /* looks good */ return pathn; } /* ** CHECKCOMPAT -- check for From and To person compatible. ** ** This routine can be supplied on a per-installation basis ** to determine whether a person is allowed to send a message. ** This allows restriction of certain types of internet ** forwarding or registration of users. ** ** If the hosts are found to be incompatible, an error ** message should be given using "usrerr" and an EX_ code ** should be returned. You can also set to->q_status to ** a DSN-style status code. ** ** EF_NO_BODY_RETN can be set in e->e_flags to suppress the ** body during the return-to-sender function; this should be done ** on huge messages. This bit may already be set by the ESMTP ** protocol. ** ** Parameters: ** to -- the person being sent to. ** ** Returns: ** an exit status ** ** Side Effects: ** none (unless you include the usrerr stuff) */ int checkcompat(to, e) register ADDRESS *to; register ENVELOPE *e; { if (tTd(49, 1)) sm_dprintf("checkcompat(to=%s, from=%s)\n", to->q_paddr, e->e_from.q_paddr); #ifdef EXAMPLE_CODE /* this code is intended as an example only */ register STAB *s; s = stab("arpa", ST_MAILER, ST_FIND); if (s != NULL && strcmp(e->e_from.q_mailer->m_name, "local") != 0 && to->q_mailer == s->s_mailer) { usrerr("553 No ARPA mail through this machine: see your system administration"); /* e->e_flags |= EF_NO_BODY_RETN; to suppress body on return */ to->q_status = "5.7.1"; return EX_UNAVAILABLE; } #endif /* EXAMPLE_CODE */ return EX_OK; } #ifdef SUN_EXTENSIONS static void init_md_sun() { struct stat sbuf; /* Check for large file descriptor */ if (fstat(fileno(stdin), &sbuf) < 0) { if (errno == EOVERFLOW) { perror("stdin"); exit(EX_NOINPUT); } } } #endif /* SUN_EXTENSIONS */ /* ** INIT_MD -- do machine dependent initializations ** ** Systems that have global modes that should be set should do ** them here rather than in main. */ #ifdef _AUX_SOURCE # include #endif /* _AUX_SOURCE */ #if SHARE_V1 # include #endif /* SHARE_V1 */ void init_md(argc, argv) int argc; char **argv; { #ifdef _AUX_SOURCE setcompat(getcompat() | COMPAT_BSDPROT); #endif /* _AUX_SOURCE */ #ifdef SUN_EXTENSIONS init_md_sun(); #endif /* SUN_EXTENSIONS */ #if _CONVEX_SOURCE /* keep gethostby*() from stripping the local domain name */ set_domain_trim_off(); #endif /* _CONVEX_SOURCE */ #if defined(__QNX__) && !defined(__QNXNTO__) /* ** Due to QNX's network distributed nature, you can target a tcpip ** stack on a different node in the qnx network; this patch lets ** this feature work. The __sock_locate() must be done before the ** environment is clear. */ __sock_locate(); #endif /* __QNX__ */ #if SECUREWARE || defined(_SCO_unix_) set_auth_parameters(argc, argv); # ifdef _SCO_unix_ /* ** This is required for highest security levels (the kernel ** won't let it call set*uid() or run setuid binaries without ** it). It may be necessary on other SECUREWARE systems. */ if (getluid() == -1) setluid(0); # endif /* _SCO_unix_ */ #endif /* SECUREWARE || defined(_SCO_unix_) */ #ifdef VENDOR_DEFAULT VendorCode = VENDOR_DEFAULT; #else /* VENDOR_DEFAULT */ VendorCode = VENDOR_BERKELEY; #endif /* VENDOR_DEFAULT */ } /* ** INIT_VENDOR_MACROS -- vendor-dependent macro initializations ** ** Called once, on startup. ** ** Parameters: ** e -- the global envelope. ** ** Returns: ** none. ** ** Side Effects: ** vendor-dependent. */ void init_vendor_macros(e) register ENVELOPE *e; { } /* ** GETLA -- get the current load average ** ** This code stolen from la.c. ** ** Parameters: ** none. ** ** Returns: ** The current load average as an integer. ** ** Side Effects: ** none. */ /* try to guess what style of load average we have */ #define LA_ZERO 1 /* always return load average as zero */ #define LA_INT 2 /* read kmem for avenrun; interpret as long */ #define LA_FLOAT 3 /* read kmem for avenrun; interpret as float */ #define LA_SUBR 4 /* call getloadavg */ #define LA_MACH 5 /* MACH load averages (as on NeXT boxes) */ #define LA_SHORT 6 /* read kmem for avenrun; interpret as short */ #define LA_PROCSTR 7 /* read string ("1.17") from /proc/loadavg */ #define LA_READKSYM 8 /* SVR4: use MIOC_READKSYM ioctl call */ #define LA_DGUX 9 /* special DGUX implementation */ #define LA_HPUX 10 /* special HPUX implementation */ #define LA_IRIX6 11 /* special IRIX 6.2 implementation */ #define LA_KSTAT 12 /* special Solaris kstat(3k) implementation */ #define LA_DEVSHORT 13 /* read short from a device */ #define LA_ALPHAOSF 14 /* Digital UNIX (OSF/1 on Alpha) table() call */ #define LA_PSET 15 /* Solaris per-processor-set load average */ #define LA_LONGLONG 17 /* read kmem for avenrun; interpret as long long */ /* do guesses based on general OS type */ #ifndef LA_TYPE # define LA_TYPE LA_ZERO #endif /* ! LA_TYPE */ #ifndef FSHIFT # if defined(unixpc) # define FSHIFT 5 # endif /* defined(unixpc) */ # if defined(__alpha) || defined(IRIX) # define FSHIFT 10 # endif /* defined(__alpha) || defined(IRIX) */ #endif /* ! FSHIFT */ #ifndef FSHIFT # define FSHIFT 8 #endif /* ! FSHIFT */ #ifndef FSCALE # define FSCALE (1 << FSHIFT) #endif /* ! FSCALE */ #ifndef LA_AVENRUN # ifdef SYSTEM5 # define LA_AVENRUN "avenrun" # else /* SYSTEM5 */ # define LA_AVENRUN "_avenrun" # endif /* SYSTEM5 */ #endif /* ! LA_AVENRUN */ /* _PATH_KMEM should be defined in */ #ifndef _PATH_KMEM # define _PATH_KMEM "/dev/kmem" #endif /* ! _PATH_KMEM */ #if (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) # include /* _PATH_UNIX should be defined in */ # ifndef _PATH_UNIX # if defined(SYSTEM5) # define _PATH_UNIX "/unix" # else /* defined(SYSTEM5) */ # define _PATH_UNIX "/vmunix" # endif /* defined(SYSTEM5) */ # endif /* ! _PATH_UNIX */ # ifdef _AUX_SOURCE struct nlist Nl[2]; # else /* _AUX_SOURCE */ struct nlist Nl[] = { { LA_AVENRUN }, { 0 }, }; # endif /* _AUX_SOURCE */ # define X_AVENRUN 0 int getla() { int j; static int kmem = -1; # if LA_TYPE == LA_INT long avenrun[3]; # else /* LA_TYPE == LA_INT */ # if LA_TYPE == LA_SHORT short avenrun[3]; # else # if LA_TYPE == LA_LONGLONG long long avenrun[3]; # else /* LA_TYPE == LA_LONGLONG */ double avenrun[3]; # endif /* LA_TYPE == LA_LONGLONG */ # endif /* LA_TYPE == LA_SHORT */ # endif /* LA_TYPE == LA_INT */ extern off_t lseek(); if (kmem < 0) { # ifdef _AUX_SOURCE (void) sm_strlcpy(Nl[X_AVENRUN].n_name, LA_AVENRUN, sizeof(Nl[X_AVENRUN].n_name)); Nl[1].n_name[0] = '\0'; # endif /* _AUX_SOURCE */ # if defined(_AIX3) || defined(_AIX4) if (knlist(Nl, 1, sizeof(Nl[0])) < 0) # else /* defined(_AIX3) || defined(_AIX4) */ if (nlist(_PATH_UNIX, Nl) < 0) # endif /* defined(_AIX3) || defined(_AIX4) */ { if (tTd(3, 1)) sm_dprintf("getla: nlist(%s): %s\n", _PATH_UNIX, sm_errstring(errno)); return -1; } if (Nl[X_AVENRUN].n_value == 0) { if (tTd(3, 1)) sm_dprintf("getla: nlist(%s, %s) ==> 0\n", _PATH_UNIX, LA_AVENRUN); return -1; } # ifdef NAMELISTMASK Nl[X_AVENRUN].n_value &= NAMELISTMASK; # endif /* NAMELISTMASK */ kmem = open(_PATH_KMEM, 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(/dev/kmem): %s\n", sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } if (tTd(3, 20)) sm_dprintf("getla: symbol address = %#lx\n", (unsigned long) Nl[X_AVENRUN].n_value); if (lseek(kmem, (off_t) Nl[X_AVENRUN].n_value, SEEK_SET) == -1 || read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun)) { /* thank you Ian */ if (tTd(3, 1)) sm_dprintf("getla: lseek or read: %s\n", sm_errstring(errno)); return -1; } # if (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) if (tTd(3, 5)) { # if LA_TYPE == LA_SHORT sm_dprintf("getla: avenrun = %d", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %d, %d", avenrun[1], avenrun[2]); # else /* LA_TYPE == LA_SHORT */ # if LA_TYPE == LA_LONGLONG sm_dprintf("getla: avenrun = %lld", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %lld, %lld", avenrun[1], avenrun[2]); # else /* LA_TYPE == LA_LONGLONG */ sm_dprintf("getla: avenrun = %ld", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %ld, %ld", avenrun[1], avenrun[2]); # endif /* LA_TYPE == LA_LONGLONG */ # endif /* LA_TYPE == LA_SHORT */ sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); # else /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %g", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %g, %g", avenrun[1], avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); # endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ } #endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */ #if LA_TYPE == LA_READKSYM # include int getla() { int j; static int kmem = -1; long avenrun[3]; struct mioc_rksym mirk; if (kmem < 0) { kmem = open("/dev/kmem", 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(/dev/kmem): %s\n", sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } mirk.mirk_symname = LA_AVENRUN; mirk.mirk_buf = avenrun; mirk.mirk_buflen = sizeof(avenrun); if (ioctl(kmem, MIOC_READKSYM, &mirk) < 0) { if (tTd(3, 1)) sm_dprintf("getla: ioctl(MIOC_READKSYM) failed: %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %d", avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %d, %d", avenrun[1], avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); } #endif /* LA_TYPE == LA_READKSYM */ #if LA_TYPE == LA_DGUX # include int getla() { struct dg_sys_info_load_info load_info; dg_sys_info((long *)&load_info, DG_SYS_INFO_LOAD_INFO_TYPE, DG_SYS_INFO_LOAD_VERSION_0); if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (load_info.one_minute + 0.5)); return ((int) (load_info.one_minute + 0.5)); } #endif /* LA_TYPE == LA_DGUX */ #if LA_TYPE == LA_HPUX /* forward declarations to keep gcc from complaining */ struct pst_dynamic; struct pst_status; struct pst_static; struct pst_vminfo; struct pst_diskinfo; struct pst_processor; struct pst_lv; struct pst_swapinfo; # include # include int getla() { struct pst_dynamic pstd; if (pstat_getdynamic(&pstd, sizeof(struct pst_dynamic), (size_t) 1, 0) == -1) return 0; if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (pstd.psd_avg_1_min + 0.5)); return (int) (pstd.psd_avg_1_min + 0.5); } #endif /* LA_TYPE == LA_HPUX */ #if LA_TYPE == LA_SUBR int getla() { double avenrun[3]; if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0) { if (tTd(3, 1)) sm_dprintf("getla: getloadavg failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); } #endif /* LA_TYPE == LA_SUBR */ #if LA_TYPE == LA_MACH /* ** This has been tested on NEXTSTEP release 2.1/3.X. */ # if defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 # include # else /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */ # include # endif /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */ int getla() { processor_set_t default_set; kern_return_t error; unsigned int info_count; struct processor_set_basic_info info; host_t host; error = processor_set_default(host_self(), &default_set); if (error != KERN_SUCCESS) { if (tTd(3, 1)) sm_dprintf("getla: processor_set_default failed: %s", sm_errstring(errno)); return -1; } info_count = PROCESSOR_SET_BASIC_INFO_COUNT; if (processor_set_info(default_set, PROCESSOR_SET_BASIC_INFO, &host, (processor_set_info_t)&info, &info_count) != KERN_SUCCESS) { if (tTd(3, 1)) sm_dprintf("getla: processor_set_info failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) ((info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE)); return (int) (info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE; } #endif /* LA_TYPE == LA_MACH */ #if LA_TYPE == LA_PROCSTR # if SM_CONF_BROKEN_STRTOD ERROR: This OS has most likely a broken strtod() implemenentation. ERROR: The function is required for getla(). ERROR: Check the compilation options _LA_PROCSTR and ERROR: _SM_CONF_BROKEN_STRTOD (without the leading _). # endif /* SM_CONF_BROKEN_STRTOD */ /* ** Read /proc/loadavg for the load average. This is assumed to be ** in a format like "0.15 0.12 0.06". ** ** Initially intended for Linux. This has been in the kernel ** since at least 0.99.15. */ # ifndef _PATH_LOADAVG # define _PATH_LOADAVG "/proc/loadavg" # endif /* ! _PATH_LOADAVG */ int getla() { double avenrun; register int result; SM_FILE_T *fp; fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_LOADAVG, SM_IO_RDONLY, NULL); if (fp == NULL) { if (tTd(3, 1)) sm_dprintf("getla: sm_io_open(%s): %s\n", _PATH_LOADAVG, sm_errstring(errno)); return -1; } result = sm_io_fscanf(fp, SM_TIME_DEFAULT, "%lf", &avenrun); (void) sm_io_close(fp, SM_TIME_DEFAULT); if (result != 1) { if (tTd(3, 1)) sm_dprintf("getla: sm_io_fscanf() = %d: %s\n", result, sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla(): %.2f\n", avenrun); return ((int) (avenrun + 0.5)); } #endif /* LA_TYPE == LA_PROCSTR */ #if LA_TYPE == LA_IRIX6 # include # ifdef _UNICOSMP # define CAST_SYSMP(x) (x) # else /* _UNICOSMP */ # define CAST_SYSMP(x) ((x) & 0x7fffffff) # endif /* _UNICOSMP */ int getla(void) { int j; static int kmem = -1; int avenrun[3]; if (kmem < 0) { kmem = open(_PATH_KMEM, 0, 0); if (kmem < 0) { if (tTd(3, 1)) sm_dprintf("getla: open(%s): %s\n", _PATH_KMEM, sm_errstring(errno)); return -1; } if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { if (tTd(3, 1)) sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n", sm_errstring(errno)); (void) close(kmem); kmem = -1; return -1; } } if (lseek(kmem, CAST_SYSMP(sysmp(MP_KERNADDR, MPKA_AVENRUN)), SEEK_SET) == -1 || read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun)) { if (tTd(3, 1)) sm_dprintf("getla: lseek or read: %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 5)) { sm_dprintf("getla: avenrun = %ld", (long int) avenrun[0]); if (tTd(3, 15)) sm_dprintf(", %ld, %ld", (long int) avenrun[1], (long int) avenrun[2]); sm_dprintf("\n"); } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT); return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT); } #endif /* LA_TYPE == LA_IRIX6 */ #if LA_TYPE == LA_KSTAT # include int getla() { static kstat_ctl_t *kc = NULL; static kstat_t *ksp = NULL; kstat_named_t *ksn; int la; if (kc == NULL) /* if not initialized before */ kc = kstat_open(); if (kc == NULL) { if (tTd(3, 1)) sm_dprintf("getla: kstat_open(): %s\n", sm_errstring(errno)); return -1; } if (ksp == NULL) ksp = kstat_lookup(kc, "unix", 0, "system_misc"); if (ksp == NULL) { if (tTd(3, 1)) sm_dprintf("getla: kstat_lookup(): %s\n", sm_errstring(errno)); return -1; } if (kstat_read(kc, ksp, NULL) < 0) { if (tTd(3, 1)) sm_dprintf("getla: kstat_read(): %s\n", sm_errstring(errno)); return -1; } ksn = (kstat_named_t *) kstat_data_lookup(ksp, "avenrun_1min"); la = ((double) ksn->value.ul + FSCALE/2) / FSCALE; /* kstat_close(kc); /o do not close for fast access */ return la; } #endif /* LA_TYPE == LA_KSTAT */ #if LA_TYPE == LA_DEVSHORT /* ** Read /dev/table/avenrun for the load average. This should contain ** three shorts for the 1, 5, and 15 minute loads. We only read the ** first, since that's all we care about. ** ** Intended for SCO OpenServer 5. */ # ifndef _PATH_AVENRUN # define _PATH_AVENRUN "/dev/table/avenrun" # endif /* ! _PATH_AVENRUN */ int getla() { static int afd = -1; short avenrun; int loadav; int r; errno = EBADF; if (afd == -1 || lseek(afd, 0L, SEEK_SET) == -1) { if (errno != EBADF) return -1; afd = open(_PATH_AVENRUN, O_RDONLY|O_SYNC); if (afd < 0) { sm_syslog(LOG_ERR, NOQID, "can't open %s: %s", _PATH_AVENRUN, sm_errstring(errno)); return -1; } } r = read(afd, &avenrun, sizeof(avenrun)); if (r != sizeof(avenrun)) { sm_syslog(LOG_ERR, NOQID, "can't read %s: %s", _PATH_AVENRUN, r == -1 ? sm_errstring(errno) : "short read"); return -1; } if (tTd(3, 5)) sm_dprintf("getla: avenrun = %d\n", avenrun); loadav = (int) (avenrun + FSCALE/2) >> FSHIFT; if (tTd(3, 1)) sm_dprintf("getla: %d\n", loadav); return loadav; } #endif /* LA_TYPE == LA_DEVSHORT */ #if LA_TYPE == LA_ALPHAOSF struct rtentry; struct mbuf; # include int getla() { int ave = 0; struct tbl_loadavg tab; if (table(TBL_LOADAVG, 0, &tab, 1, sizeof(tab)) == -1) { if (tTd(3, 1)) sm_dprintf("getla: table %s\n", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: scale = %d\n", tab.tl_lscale); if (tab.tl_lscale) ave = ((tab.tl_avenrun.l[2] + (tab.tl_lscale/2)) / tab.tl_lscale); else ave = (int) (tab.tl_avenrun.d[2] + 0.5); if (tTd(3, 1)) sm_dprintf("getla: %d\n", ave); return ave; } #endif /* LA_TYPE == LA_ALPHAOSF */ #if LA_TYPE == LA_PSET int getla() { double avenrun[3]; if (pset_getloadavg(PS_MYID, avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0) { if (tTd(3, 1)) sm_dprintf("getla: pset_getloadavg failed: %s", sm_errstring(errno)); return -1; } if (tTd(3, 1)) sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5)); return ((int) (avenrun[0] + 0.5)); } #endif /* LA_TYPE == LA_PSET */ #if LA_TYPE == LA_ZERO int getla() { if (tTd(3, 1)) sm_dprintf("getla: ZERO\n"); return 0; } #endif /* LA_TYPE == LA_ZERO */ /* * Copyright 1989 Massachusetts Institute of Technology * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of M.I.T. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. M.I.T. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T. * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Authors: Many and varied... */ /* Non Apollo stuff removed by Don Lewis 11/15/93 */ #ifndef lint SM_UNUSED(static char rcsid[]) = "@(#)$OrigId: getloadavg.c,v 1.16 1991/06/21 12:51:15 paul Exp $"; #endif /* ! lint */ #ifdef apollo # undef volatile # include /* ARGSUSED */ int getloadavg( call_data ) caddr_t call_data; /* pointer to (double) return value */ { double *avenrun = (double *) call_data; int i; status_$t st; long loadav[3]; proc1_$get_loadav(loadav, &st); *avenrun = loadav[0] / (double) (1 << 16); return 0; } #endif /* apollo */ /* ** SM_GETLA -- get the current load average ** ** Parameters: ** none ** ** Returns: ** none ** ** Side Effects: ** Set CurrentLA to the current load average. ** Set {load_avg} in GlobalMacros to the current load average. */ void sm_getla() { char labuf[8]; CurrentLA = getla(); (void) sm_snprintf(labuf, sizeof(labuf), "%d", CurrentLA); macdefine(&GlobalMacros, A_TEMP, macid("{load_avg}"), labuf); } /* ** SHOULDQUEUE -- should this message be queued or sent? ** ** Compares the message cost to the load average to decide. ** ** Note: Do NOT change this API! It is documented in op.me ** and theoretically the user can change this function... ** ** Parameters: ** pri -- the priority of the message in question. ** ct -- the message creation time (unused, but see above). ** ** Returns: ** true -- if this message should be queued up for the ** time being. ** false -- if the load is low enough to send this message. ** ** Side Effects: ** none. */ /* ARGSUSED1 */ bool shouldqueue(pri, ct) long pri; time_t ct; { bool rval; #if _FFR_MEMSTAT long memfree; #endif /* _FFR_MEMSTAT */ if (tTd(3, 30)) sm_dprintf("shouldqueue: CurrentLA=%d, pri=%ld: ", CurrentLA, pri); #if _FFR_MEMSTAT if (QueueLowMem > 0 && sm_memstat_get(MemoryResource, &memfree) >= 0 && memfree < QueueLowMem) { if (tTd(3, 30)) sm_dprintf("true (memfree=%ld < QueueLowMem=%ld)\n", memfree, QueueLowMem); return true; } #endif /* _FFR_MEMSTAT */ if (CurrentLA < QueueLA) { if (tTd(3, 30)) sm_dprintf("false (CurrentLA < QueueLA)\n"); return false; } rval = pri > (QueueFactor / (CurrentLA - QueueLA + 1)); if (tTd(3, 30)) sm_dprintf("%s (by calculation)\n", rval ? "true" : "false"); return rval; } /* ** REFUSECONNECTIONS -- decide if connections should be refused ** ** Parameters: ** e -- the current envelope. ** dn -- number of daemon. ** active -- was this daemon actually active? ** ** Returns: ** true if incoming SMTP connections should be refused ** (for now). ** false if we should accept new work. ** ** Side Effects: ** Sets process title when it is rejecting connections. */ bool refuseconnections(e, dn, active) ENVELOPE *e; int dn; bool active; { static time_t lastconn[MAXDAEMONS]; static int conncnt[MAXDAEMONS]; static time_t firstrejtime[MAXDAEMONS]; static time_t nextlogtime[MAXDAEMONS]; int limit; #if _FFR_MEMSTAT long memfree; #endif /* _FFR_MEMSTAT */ #if XLA if (!xla_smtp_ok()) return true; #endif /* XLA */ SM_ASSERT(dn >= 0); SM_ASSERT(dn < MAXDAEMONS); if (ConnRateThrottle > 0) { time_t now; now = curtime(); if (active) { if (now != lastconn[dn]) { lastconn[dn] = now; conncnt[dn] = 1; } else if (conncnt[dn]++ > ConnRateThrottle) { #define D_MSG_CRT "deferring connections on daemon %s: %d per second" /* sleep to flatten out connection load */ sm_setproctitle(true, e, D_MSG_CRT, Daemons[dn].d_name, ConnRateThrottle); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, D_MSG_CRT, Daemons[dn].d_name, ConnRateThrottle); (void) sleep(1); } } else if (now != lastconn[dn]) conncnt[dn] = 0; } #if _FFR_MEMSTAT if (RefuseLowMem > 0 && sm_memstat_get(MemoryResource, &memfree) >= 0 && memfree < RefuseLowMem) { # define R_MSG_LM "rejecting connections on daemon %s: free memory: %ld" sm_setproctitle(true, e, R_MSG_LM, Daemons[dn].d_name, memfree); if (LogLevel > 8) sm_syslog(LOG_NOTICE, NOQID, R_MSG_LM, Daemons[dn].d_name, memfree); return true; } #endif /* _FFR_MEMSTAT */ sm_getla(); limit = (Daemons[dn].d_refuseLA != DPO_NOTSET) ? Daemons[dn].d_refuseLA : RefuseLA; if (limit > 0 && CurrentLA >= limit) { time_t now; # define R_MSG_LA "rejecting connections on daemon %s: load average: %d" # define R2_MSG_LA "have been rejecting connections on daemon %s for %s" sm_setproctitle(true, e, R_MSG_LA, Daemons[dn].d_name, CurrentLA); if (LogLevel > 8) sm_syslog(LOG_NOTICE, NOQID, R_MSG_LA, Daemons[dn].d_name, CurrentLA); now = curtime(); if (firstrejtime[dn] == 0) { firstrejtime[dn] = now; nextlogtime[dn] = now + RejectLogInterval; } else if (nextlogtime[dn] < now) { sm_syslog(LOG_ERR, NOQID, R2_MSG_LA, Daemons[dn].d_name, pintvl(now - firstrejtime[dn], true)); nextlogtime[dn] = now + RejectLogInterval; } return true; } else firstrejtime[dn] = 0; limit = (Daemons[dn].d_delayLA != DPO_NOTSET) ? Daemons[dn].d_delayLA : DelayLA; if (limit > 0 && CurrentLA >= limit) { time_t now; static time_t log_delay = (time_t) 0; # define MIN_DELAY_LOG 90 /* wait before logging this again */ # define D_MSG_LA "delaying connections on daemon %s: load average=%d >= %d" /* sleep to flatten out connection load */ sm_setproctitle(true, e, D_MSG_LA, Daemons[dn].d_name, CurrentLA, limit); if (LogLevel > 8 && (now = curtime()) > log_delay) { sm_syslog(LOG_INFO, NOQID, D_MSG_LA, Daemons[dn].d_name, CurrentLA, limit); log_delay = now + MIN_DELAY_LOG; } (void) sleep(1); } limit = (Daemons[dn].d_maxchildren != DPO_NOTSET) ? Daemons[dn].d_maxchildren : MaxChildren; if (limit > 0 && CurChildren >= limit) { proc_list_probe(); if (CurChildren >= limit) { #define R_MSG_CHILD "rejecting connections on daemon %s: %d children, max %d" sm_setproctitle(true, e, R_MSG_CHILD, Daemons[dn].d_name, CurChildren, limit); if (LogLevel > 8) sm_syslog(LOG_INFO, NOQID, R_MSG_CHILD, Daemons[dn].d_name, CurChildren, limit); return true; } } return false; } /* ** SETPROCTITLE -- set process title for ps ** ** Parameters: ** fmt -- a printf style format string. ** a, b, c -- possible parameters to fmt. ** ** Returns: ** none. ** ** Side Effects: ** Clobbers argv of our main procedure so ps(1) will ** display the title. */ #define SPT_NONE 0 /* don't use it at all */ #define SPT_REUSEARGV 1 /* cover argv with title information */ #define SPT_BUILTIN 2 /* use libc builtin */ #define SPT_PSTAT 3 /* use pstat(PSTAT_SETCMD, ...) */ #define SPT_PSSTRINGS 4 /* use PS_STRINGS->... */ #define SPT_SYSMIPS 5 /* use sysmips() supported by NEWS-OS 6 */ #define SPT_SCO 6 /* write kernel u. area */ #define SPT_CHANGEARGV 7 /* write our own strings into argv[] */ #ifndef SPT_TYPE # define SPT_TYPE SPT_REUSEARGV #endif /* ! SPT_TYPE */ #if SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN # if SPT_TYPE == SPT_PSTAT # include # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_PSSTRINGS # include # include # ifndef PS_STRINGS /* hmmmm.... apparently not available after all */ # undef SPT_TYPE # define SPT_TYPE SPT_REUSEARGV # else /* ! PS_STRINGS */ # ifndef NKPDE /* FreeBSD 2.0 */ # define NKPDE 63 typedef unsigned int *pt_entry_t; # endif /* ! NKPDE */ # endif /* ! PS_STRINGS */ # endif /* SPT_TYPE == SPT_PSSTRINGS */ # if SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV # define SETPROC_STATIC static # else /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */ # define SETPROC_STATIC # endif /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */ # if SPT_TYPE == SPT_SYSMIPS # include # include # endif /* SPT_TYPE == SPT_SYSMIPS */ # if SPT_TYPE == SPT_SCO # include # include # include # include # if PSARGSZ > MAXLINE # define SPT_BUFSIZE PSARGSZ # endif /* PSARGSZ > MAXLINE */ # endif /* SPT_TYPE == SPT_SCO */ # ifndef SPT_PADCHAR # define SPT_PADCHAR ' ' # endif /* ! SPT_PADCHAR */ #endif /* SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN */ #ifndef SPT_BUFSIZE # define SPT_BUFSIZE MAXLINE #endif /* ! SPT_BUFSIZE */ #if _FFR_SPT_ALIGN /* ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to ** 64 bit alignment, so unless each piece of argv and envp is a multiple ** of 8 bytes (including terminating NULL), initsetproctitle() won't use ** any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE if ** you use this FFR. */ # ifdef SPT_ALIGN_SIZE # define SPT_ALIGN(x, align) (((((x) + SPT_ALIGN_SIZE) >> (align)) << (align)) - 1) # else /* SPT_ALIGN_SIZE */ # define SPT_ALIGN(x, align) (x) # endif /* SPT_ALIGN_SIZE */ #else /* _FFR_SPT_ALIGN */ # define SPT_ALIGN(x, align) (x) #endif /* _FFR_SPT_ALIGN */ /* ** Pointers for setproctitle. ** This allows "ps" listings to give more useful information. */ static char **Argv = NULL; /* pointer to argument vector */ static char *LastArgv = NULL; /* end of argv */ #if SPT_TYPE != SPT_BUILTIN static void setproctitle __P((const char *, ...)); #endif /* SPT_TYPE != SPT_BUILTIN */ void initsetproctitle(argc, argv, envp) int argc; char **argv; char **envp; { register int i; int align; extern char **environ; /* ** Move the environment so setproctitle can use the space at ** the top of memory. */ if (envp != NULL) { for (i = 0; envp[i] != NULL; i++) continue; environ = (char **) xalloc(sizeof(char *) * (i + 1)); for (i = 0; envp[i] != NULL; i++) environ[i] = newstr(envp[i]); environ[i] = NULL; } /* ** Save start and extent of argv for setproctitle. */ Argv = argv; /* ** Determine how much space we can use for setproctitle. ** Use all contiguous argv and envp pointers starting at argv[0] */ align = -1; # if _FFR_SPT_ALIGN # ifdef SPT_ALIGN_SIZE for (i = SPT_ALIGN_SIZE; i > 0; i >>= 1) align++; # endif /* SPT_ALIGN_SIZE */ # endif /* _FFR_SPT_ALIGN */ for (i = 0; i < argc; i++) { if (i == 0 || LastArgv + 1 == argv[i]) LastArgv = argv[i] + SPT_ALIGN(strlen(argv[i]), align); } for (i = 0; LastArgv != NULL && envp != NULL && envp[i] != NULL; i++) { if (LastArgv + 1 == envp[i]) LastArgv = envp[i] + SPT_ALIGN(strlen(envp[i]), align); } } #if SPT_TYPE != SPT_BUILTIN /*VARARGS1*/ static void # ifdef __STDC__ setproctitle(const char *fmt, ...) # else /* __STDC__ */ setproctitle(fmt, va_alist) const char *fmt; va_dcl # endif /* __STDC__ */ { # if SPT_TYPE != SPT_NONE register int i; register char *p; SETPROC_STATIC char buf[SPT_BUFSIZE]; SM_VA_LOCAL_DECL # if SPT_TYPE == SPT_PSTAT union pstun pst; # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_SCO int j; off_t seek_off; static int kmem = -1; static pid_t kmempid = -1; struct user u; # endif /* SPT_TYPE == SPT_SCO */ p = buf; /* print sendmail: heading for grep */ (void) sm_strlcpy(p, "sendmail: ", SPACELEFT(buf, p)); p += strlen(p); /* print the argument string */ SM_VA_START(ap, fmt); (void) sm_vsnprintf(p, SPACELEFT(buf, p), fmt, ap); SM_VA_END(ap); i = (int) strlen(buf); if (i < 0) return; # if SPT_TYPE == SPT_PSTAT pst.pst_command = buf; pstat(PSTAT_SETCMD, pst, i, 0, 0); # endif /* SPT_TYPE == SPT_PSTAT */ # if SPT_TYPE == SPT_PSSTRINGS PS_STRINGS->ps_nargvstr = 1; PS_STRINGS->ps_argvstr = buf; # endif /* SPT_TYPE == SPT_PSSTRINGS */ # if SPT_TYPE == SPT_SYSMIPS sysmips(SONY_SYSNEWS, NEWS_SETPSARGS, buf); # endif /* SPT_TYPE == SPT_SYSMIPS */ # if SPT_TYPE == SPT_SCO if (kmem < 0 || kmempid != CurrentPid) { if (kmem >= 0) (void) close(kmem); kmem = open(_PATH_KMEM, O_RDWR, 0); if (kmem < 0) return; if ((j = fcntl(kmem, F_GETFD, 0)) < 0 || fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0) { (void) close(kmem); kmem = -1; return; } kmempid = CurrentPid; } buf[PSARGSZ - 1] = '\0'; seek_off = UVUBLK + (off_t) u.u_psargs - (off_t) &u; if (lseek(kmem, (off_t) seek_off, SEEK_SET) == seek_off) (void) write(kmem, buf, PSARGSZ); # endif /* SPT_TYPE == SPT_SCO */ # if SPT_TYPE == SPT_REUSEARGV if (LastArgv == NULL) return; if (i > LastArgv - Argv[0] - 2) { i = LastArgv - Argv[0] - 2; buf[i] = '\0'; } (void) sm_strlcpy(Argv[0], buf, i + 1); p = &Argv[0][i]; while (p < LastArgv) *p++ = SPT_PADCHAR; Argv[1] = NULL; # endif /* SPT_TYPE == SPT_REUSEARGV */ # if SPT_TYPE == SPT_CHANGEARGV Argv[0] = buf; Argv[1] = 0; # endif /* SPT_TYPE == SPT_CHANGEARGV */ # endif /* SPT_TYPE != SPT_NONE */ } #endif /* SPT_TYPE != SPT_BUILTIN */ /* ** SM_SETPROCTITLE -- set process task and set process title for ps ** ** Possibly set process status and call setproctitle() to ** change the ps display. ** ** Parameters: ** status -- whether or not to store as process status ** e -- the current envelope. ** fmt -- a printf style format string. ** a, b, c -- possible parameters to fmt. ** ** Returns: ** none. */ /*VARARGS3*/ void #ifdef __STDC__ sm_setproctitle(bool status, ENVELOPE *e, const char *fmt, ...) #else /* __STDC__ */ sm_setproctitle(status, e, fmt, va_alist) bool status; ENVELOPE *e; const char *fmt; va_dcl #endif /* __STDC__ */ { char buf[SPT_BUFSIZE]; SM_VA_LOCAL_DECL /* print the argument string */ SM_VA_START(ap, fmt); (void) sm_vsnprintf(buf, sizeof(buf), fmt, ap); SM_VA_END(ap); if (status) proc_list_set(CurrentPid, buf); if (ProcTitlePrefix != NULL) { char prefix[SPT_BUFSIZE]; expand(ProcTitlePrefix, prefix, sizeof(prefix), e); setproctitle("%s: %s", prefix, buf); } else setproctitle("%s", buf); } /* ** WAITFOR -- wait for a particular process id. ** ** Parameters: ** pid -- process id to wait for. ** ** Returns: ** status of pid. ** -1 if pid never shows up. ** ** Side Effects: ** none. */ int waitfor(pid) pid_t pid; { int st; pid_t i; do { errno = 0; i = sm_wait(&st); if (i > 0) proc_list_drop(i, st, NULL); } while ((i >= 0 || errno == EINTR) && i != pid); if (i < 0) return -1; return st; } /* ** SM_WAIT -- wait ** ** Parameters: ** status -- pointer to status (return value) ** ** Returns: ** pid */ pid_t sm_wait(status) int *status; { # ifdef WAITUNION union wait st; # else /* WAITUNION */ auto int st; # endif /* WAITUNION */ pid_t i; # if defined(ISC_UNIX) || defined(_SCO_unix_) int savesig; # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ # if defined(ISC_UNIX) || defined(_SCO_unix_) savesig = sm_releasesignal(SIGCHLD); # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ i = wait(&st); # if defined(ISC_UNIX) || defined(_SCO_unix_) if (savesig > 0) sm_blocksignal(SIGCHLD); # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */ # ifdef WAITUNION *status = st.w_status; # else /* WAITUNION */ *status = st; # endif /* WAITUNION */ return i; } /* ** REAPCHILD -- pick up the body of my child, lest it become a zombie ** ** Parameters: ** sig -- the signal that got us here (unused). ** ** Returns: ** none. ** ** Side Effects: ** Picks up extant zombies. ** Control socket exits may restart/shutdown daemon. ** ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ /* ARGSUSED0 */ SIGFUNC_DECL reapchild(sig) int sig; { int save_errno = errno; int st; pid_t pid; # if HASWAITPID auto int status; int count; count = 0; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { st = status; if (count++ > 1000) break; # else /* HASWAITPID */ # ifdef WNOHANG union wait status; while ((pid = wait3(&status, WNOHANG, (struct rusage *) NULL)) > 0) { st = status.w_status; # else /* WNOHANG */ auto int status; /* ** Catch one zombie -- we will be re-invoked (we hope) if there ** are more. Unreliable signals probably break this, but this ** is the "old system" situation -- waitpid or wait3 are to be ** strongly preferred. */ if ((pid = wait(&status)) > 0) { st = status; # endif /* WNOHANG */ # endif /* HASWAITPID */ /* Drop PID and check if it was a control socket child */ proc_list_drop(pid, st, NULL); } FIX_SYSV_SIGNAL(sig, reapchild); errno = save_errno; return SIGFUNC_RETURN; } /* ** GETDTSIZE -- return number of file descriptors ** ** Only on non-BSD systems ** ** Parameters: ** none ** ** Returns: ** size of file descriptor table ** ** Side Effects: ** none */ #ifdef SOLARIS # include #endif /* SOLARIS */ int getdtsize() { # ifdef RLIMIT_NOFILE struct rlimit rl; if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) return rl.rlim_cur; # endif /* RLIMIT_NOFILE */ # if HASGETDTABLESIZE return getdtablesize(); # else /* HASGETDTABLESIZE */ # ifdef _SC_OPEN_MAX return sysconf(_SC_OPEN_MAX); # else /* _SC_OPEN_MAX */ return NOFILE; # endif /* _SC_OPEN_MAX */ # endif /* HASGETDTABLESIZE */ } /* ** UNAME -- get the UUCP name of this system. */ #if !HASUNAME int uname(name) struct utsname *name; { SM_FILE_T *file; char *n; name->nodename[0] = '\0'; /* try /etc/whoami -- one line with the node name */ if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/etc/whoami", SM_IO_RDONLY, NULL)) != NULL) { (void) sm_io_fgets(file, SM_TIME_DEFAULT, name->nodename, NODE_LENGTH + 1); (void) sm_io_close(file, SM_TIME_DEFAULT); n = strchr(name->nodename, '\n'); if (n != NULL) *n = '\0'; if (name->nodename[0] != '\0') return 0; } /* try /usr/include/whoami.h -- has a #define somewhere */ if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/usr/include/whoami.h", SM_IO_RDONLY, NULL)) != NULL) { char buf[MAXLINE]; while (sm_io_fgets(file, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { if (sm_io_sscanf(buf, "#define sysname \"%*[^\"]\"", NODE_LENGTH, name->nodename) > 0) break; } (void) sm_io_close(file, SM_TIME_DEFAULT); if (name->nodename[0] != '\0') return 0; } return -1; } #endif /* !HASUNAME */ /* ** INITGROUPS -- initialize groups ** ** Stub implementation for System V style systems */ #if !HASINITGROUPS initgroups(name, basegid) char *name; int basegid; { return 0; } #endif /* !HASINITGROUPS */ /* ** SETGROUPS -- set group list ** ** Stub implementation for systems that don't have group lists */ #ifndef NGROUPS_MAX int setgroups(ngroups, grouplist) int ngroups; GIDSET_T grouplist[]; { return 0; } #endif /* ! NGROUPS_MAX */ /* ** SETSID -- set session id (for non-POSIX systems) */ #if !HASSETSID pid_t setsid __P ((void)) { # ifdef TIOCNOTTY int fd; fd = open("/dev/tty", O_RDWR, 0); if (fd >= 0) { (void) ioctl(fd, TIOCNOTTY, (char *) 0); (void) close(fd); } # endif /* TIOCNOTTY */ # ifdef SYS5SETPGRP return setpgrp(); # else /* SYS5SETPGRP */ return setpgid(0, CurrentPid); # endif /* SYS5SETPGRP */ } #endif /* !HASSETSID */ /* ** FSYNC -- dummy fsync */ #if NEEDFSYNC fsync(fd) int fd; { # ifdef O_SYNC return fcntl(fd, F_SETFL, O_SYNC); # else /* O_SYNC */ /* nothing we can do */ return 0; # endif /* O_SYNC */ } #endif /* NEEDFSYNC */ /* ** DGUX_INET_ADDR -- inet_addr for DG/UX ** ** Data General DG/UX version of inet_addr returns a struct in_addr ** instead of a long. This patches things. Only needed on versions ** prior to 5.4.3. */ #ifdef DGUX_5_4_2 # undef inet_addr long dgux_inet_addr(host) char *host; { struct in_addr haddr; haddr = inet_addr(host); return haddr.s_addr; } #endif /* DGUX_5_4_2 */ /* ** GETOPT -- for old systems or systems with bogus implementations */ #if !SM_CONF_GETOPT /* * Copyright (c) 1985 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ /* ** this version hacked to add `atend' flag to allow state machine ** to reset if invoked by the program to scan args for a 2nd time */ # if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)getopt.c 4.3 (Berkeley) 3/9/86"; # endif /* defined(LIBC_SCCS) && !defined(lint) */ /* ** get option letter from argument vector */ # ifdef _CONVEX_SOURCE extern int optind, opterr, optopt; extern char *optarg; # else /* _CONVEX_SOURCE */ int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = 0; /* character checked for validity */ char *optarg = NULL; /* argument associated with option */ # endif /* _CONVEX_SOURCE */ # define BADCH (int)'?' # define EMSG "" # define tell(s) if (opterr) \ {sm_io_fputs(smioerr, SM_TIME_DEFAULT, *nargv); \ (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, s); \ (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, optopt); \ (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, '\n'); \ return BADCH;} int getopt(nargc,nargv,ostr) int nargc; char *const *nargv; const char *ostr; { static char *place = EMSG; /* option letter processing */ static char atend = 0; register char *oli = NULL; /* option letter list index */ if (atend) { atend = 0; place = EMSG; } if(!*place) { /* update scanning pointer */ if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) { atend++; return -1; } if (*place == '-') { /* found "--" */ ++optind; atend++; return -1; } } /* option letter okay? */ if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) { if (!*place) ++optind; tell(": illegal option -- "); } if (oli && *++oli != ':') { /* don't need argument */ optarg = NULL; if (!*place) ++optind; } else { /* need an argument */ if (*place) optarg = place; /* no white space */ else if (nargc <= ++optind) { /* no arg */ place = EMSG; tell(": option requires an argument -- "); } else optarg = nargv[optind]; /* white space */ place = EMSG; ++optind; } return optopt; /* dump back option letter */ } #endif /* !SM_CONF_GETOPT */ /* ** USERSHELLOK -- tell if a user's shell is ok for unrestricted use ** ** Parameters: ** user -- the name of the user we are checking. ** shell -- the user's shell from /etc/passwd ** ** Returns: ** true -- if it is ok to use this for unrestricted access. ** false -- if the shell is restricted. */ #if !HASGETUSERSHELL # ifndef _PATH_SHELLS # define _PATH_SHELLS "/etc/shells" # endif /* ! _PATH_SHELLS */ # if defined(_AIX3) || defined(_AIX4) # include # if _AIX4 >= 40200 # include # endif /* _AIX4 >= 40200 */ # include # endif /* defined(_AIX3) || defined(_AIX4) */ static char *DefaultUserShells[] = { "/bin/sh", /* standard shell */ # ifdef MPE "/SYS/PUB/CI", # else /* MPE */ "/usr/bin/sh", "/bin/csh", /* C shell */ "/usr/bin/csh", # endif /* MPE */ # ifdef __hpux # ifdef V4FS "/usr/bin/rsh", /* restricted Bourne shell */ "/usr/bin/ksh", /* Korn shell */ "/usr/bin/rksh", /* restricted Korn shell */ "/usr/bin/pam", "/usr/bin/keysh", /* key shell (extended Korn shell) */ "/usr/bin/posix/sh", # else /* V4FS */ "/bin/rsh", /* restricted Bourne shell */ "/bin/ksh", /* Korn shell */ "/bin/rksh", /* restricted Korn shell */ "/bin/pam", "/usr/bin/keysh", /* key shell (extended Korn shell) */ "/bin/posix/sh", "/sbin/sh", # endif /* V4FS */ # endif /* __hpux */ # if defined(_AIX3) || defined(_AIX4) "/bin/ksh", /* Korn shell */ "/usr/bin/ksh", "/bin/tsh", /* trusted shell */ "/usr/bin/tsh", "/bin/bsh", /* Bourne shell */ "/usr/bin/bsh", # endif /* defined(_AIX3) || defined(_AIX4) */ # if defined(__svr4__) || defined(__svr5__) "/bin/ksh", /* Korn shell */ "/usr/bin/ksh", # endif /* defined(__svr4__) || defined(__svr5__) */ # ifdef sgi "/sbin/sh", /* SGI's shells really live in /sbin */ "/usr/bin/sh", "/sbin/bsh", /* classic Bourne shell */ "/bin/bsh", "/usr/bin/bsh", "/sbin/csh", /* standard csh */ "/bin/csh", "/usr/bin/csh", "/sbin/jsh", /* classic Bourne shell w/ job control*/ "/bin/jsh", "/usr/bin/jsh", "/bin/ksh", /* Korn shell */ "/sbin/ksh", "/usr/bin/ksh", "/sbin/tcsh", /* Extended csh */ "/bin/tcsh", "/usr/bin/tcsh", # endif /* sgi */ NULL }; #endif /* !HASGETUSERSHELL */ #define WILDCARD_SHELL "/SENDMAIL/ANY/SHELL/" bool usershellok(user, shell) char *user; char *shell; { # if HASGETUSERSHELL register char *p; extern char *getusershell(); if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') || ConfigLevel <= 1) return true; setusershell(); while ((p = getusershell()) != NULL) if (strcmp(p, shell) == 0 || strcmp(p, WILDCARD_SHELL) == 0) break; endusershell(); return p != NULL; # else /* HASGETUSERSHELL */ # if USEGETCONFATTR auto char *v; # endif /* USEGETCONFATTR */ register SM_FILE_T *shellf; char buf[MAXLINE]; if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') || ConfigLevel <= 1) return true; # if USEGETCONFATTR /* ** Naturally IBM has a "better" idea..... ** ** What a crock. This interface isn't documented, it is ** considered part of the security library (-ls), and it ** only works if you are running as root (since the list ** of valid shells is obviously a source of great concern). ** I recommend that you do NOT define USEGETCONFATTR, ** especially since you are going to have to set up an ** /etc/shells anyhow to handle the cases where getconfattr ** fails. */ if (getconfattr(SC_SYS_LOGIN, SC_SHELLS, &v, SEC_LIST) == 0 && v != NULL) { while (*v != '\0') { if (strcmp(v, shell) == 0 || strcmp(v, WILDCARD_SHELL) == 0) return true; v += strlen(v) + 1; } return false; } # endif /* USEGETCONFATTR */ shellf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_SHELLS, SM_IO_RDONLY, NULL); if (shellf == NULL) { /* no /etc/shells; see if it is one of the std shells */ char **d; if (errno != ENOENT && LogLevel > 3) sm_syslog(LOG_ERR, NOQID, "usershellok: cannot open %s: %s", _PATH_SHELLS, sm_errstring(errno)); for (d = DefaultUserShells; *d != NULL; d++) { if (strcmp(shell, *d) == 0) return true; } return false; } while (sm_io_fgets(shellf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { register char *p, *q; p = buf; while (*p != '\0' && *p != '#' && *p != '/') p++; if (*p == '#' || *p == '\0') continue; q = p; while (*p != '\0' && *p != '#' && !(isascii(*p) && isspace(*p))) p++; *p = '\0'; if (strcmp(shell, q) == 0 || strcmp(WILDCARD_SHELL, q) == 0) { (void) sm_io_close(shellf, SM_TIME_DEFAULT); return true; } } (void) sm_io_close(shellf, SM_TIME_DEFAULT); return false; # endif /* HASGETUSERSHELL */ } /* ** FREEDISKSPACE -- see how much free space is on the queue filesystem ** ** Only implemented if you have statfs. ** ** Parameters: ** dir -- the directory in question. ** bsize -- a variable into which the filesystem ** block size is stored. ** ** Returns: ** The number of blocks free on the queue filesystem. ** -1 if the statfs call fails. ** ** Side effects: ** Puts the filesystem block size into bsize. */ /* statfs types */ # define SFS_NONE 0 /* no statfs implementation */ # define SFS_USTAT 1 /* use ustat */ # define SFS_4ARGS 2 /* use four-argument statfs call */ # define SFS_VFS 3 /* use implementation */ # define SFS_MOUNT 4 /* use implementation */ # define SFS_STATFS 5 /* use implementation */ # define SFS_STATVFS 6 /* use implementation */ # ifndef SFS_TYPE # define SFS_TYPE SFS_NONE # endif /* ! SFS_TYPE */ # if SFS_TYPE == SFS_USTAT # include # endif /* SFS_TYPE == SFS_USTAT */ # if SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS # include # endif /* SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS */ # if SFS_TYPE == SFS_VFS # include # endif /* SFS_TYPE == SFS_VFS */ # if SFS_TYPE == SFS_MOUNT # include # endif /* SFS_TYPE == SFS_MOUNT */ # if SFS_TYPE == SFS_STATVFS # include # endif /* SFS_TYPE == SFS_STATVFS */ long freediskspace(dir, bsize) const char *dir; long *bsize; { # if SFS_TYPE == SFS_NONE if (bsize != NULL) *bsize = 4096L; /* assume free space is plentiful */ return (long) LONG_MAX; # else /* SFS_TYPE == SFS_NONE */ # if SFS_TYPE == SFS_USTAT struct ustat fs; struct stat statbuf; # define FSBLOCKSIZE DEV_BSIZE # define SFS_BAVAIL f_tfree # else /* SFS_TYPE == SFS_USTAT */ # if defined(ultrix) struct fs_data fs; # define SFS_BAVAIL fd_bfreen # define FSBLOCKSIZE 1024L # else /* defined(ultrix) */ # if SFS_TYPE == SFS_STATVFS struct statvfs fs; # define FSBLOCKSIZE fs.f_frsize # else /* SFS_TYPE == SFS_STATVFS */ struct statfs fs; # define FSBLOCKSIZE fs.f_bsize # endif /* SFS_TYPE == SFS_STATVFS */ # endif /* defined(ultrix) */ # endif /* SFS_TYPE == SFS_USTAT */ # ifndef SFS_BAVAIL # define SFS_BAVAIL f_bavail # endif /* ! SFS_BAVAIL */ # if SFS_TYPE == SFS_USTAT if (stat(dir, &statbuf) == 0 && ustat(statbuf.st_dev, &fs) == 0) # else /* SFS_TYPE == SFS_USTAT */ # if SFS_TYPE == SFS_4ARGS if (statfs(dir, &fs, sizeof(fs), 0) == 0) # else /* SFS_TYPE == SFS_4ARGS */ # if SFS_TYPE == SFS_STATVFS if (statvfs(dir, &fs) == 0) # else /* SFS_TYPE == SFS_STATVFS */ # if defined(ultrix) if (statfs(dir, &fs) > 0) # else /* defined(ultrix) */ if (statfs(dir, &fs) == 0) # endif /* defined(ultrix) */ # endif /* SFS_TYPE == SFS_STATVFS */ # endif /* SFS_TYPE == SFS_4ARGS */ # endif /* SFS_TYPE == SFS_USTAT */ { if (bsize != NULL) *bsize = FSBLOCKSIZE; if (fs.SFS_BAVAIL <= 0) return 0; else if (fs.SFS_BAVAIL > LONG_MAX) return (long) LONG_MAX; else return (long) fs.SFS_BAVAIL; } return -1; # endif /* SFS_TYPE == SFS_NONE */ } /* ** ENOUGHDISKSPACE -- is there enough free space on the queue file systems? ** ** Parameters: ** msize -- the size to check against. If zero, we don't yet ** know how big the message will be, so just check for ** a "reasonable" amount. ** e -- envelope, or NULL -- controls logging ** ** Returns: ** true if in every queue group there is at least one ** queue directory whose file system contains enough free space. ** false otherwise. ** ** Side Effects: ** If there is not enough disk space and e != NULL ** then sm_syslog is called. */ bool enoughdiskspace(msize, e) long msize; ENVELOPE *e; { int i; #if _FFR_TESTS if (tTd(4, 101)) return false; #endif /* _FFR_TESTS */ if (MinBlocksFree <= 0 && msize <= 0) { if (tTd(4, 80)) sm_dprintf("enoughdiskspace: no threshold\n"); return true; } filesys_update(); for (i = 0; i < NumQueue; ++i) { if (pickqdir(Queue[i], msize, e) < 0) return false; } return true; } /* ** TRANSIENTERROR -- tell if an error code indicates a transient failure ** ** This looks at an errno value and tells if this is likely to ** go away if retried later. ** ** Parameters: ** err -- the errno code to classify. ** ** Returns: ** true if this is probably transient. ** false otherwise. */ bool transienterror(err) int err; { switch (err) { case EIO: /* I/O error */ case ENXIO: /* Device not configured */ case EAGAIN: /* Resource temporarily unavailable */ case ENOMEM: /* Cannot allocate memory */ case ENODEV: /* Operation not supported by device */ case ENFILE: /* Too many open files in system */ case EMFILE: /* Too many open files */ case ENOSPC: /* No space left on device */ case ETIMEDOUT: /* Connection timed out */ #ifdef ESTALE case ESTALE: /* Stale NFS file handle */ #endif /* ESTALE */ #ifdef ENETDOWN case ENETDOWN: /* Network is down */ #endif /* ENETDOWN */ #ifdef ENETUNREACH case ENETUNREACH: /* Network is unreachable */ #endif /* ENETUNREACH */ #ifdef ENETRESET case ENETRESET: /* Network dropped connection on reset */ #endif /* ENETRESET */ #ifdef ECONNABORTED case ECONNABORTED: /* Software caused connection abort */ #endif /* ECONNABORTED */ #ifdef ECONNRESET case ECONNRESET: /* Connection reset by peer */ #endif /* ECONNRESET */ #ifdef ENOBUFS case ENOBUFS: /* No buffer space available */ #endif /* ENOBUFS */ #ifdef ESHUTDOWN case ESHUTDOWN: /* Can't send after socket shutdown */ #endif /* ESHUTDOWN */ #ifdef ECONNREFUSED case ECONNREFUSED: /* Connection refused */ #endif /* ECONNREFUSED */ #ifdef EHOSTDOWN case EHOSTDOWN: /* Host is down */ #endif /* EHOSTDOWN */ #ifdef EHOSTUNREACH case EHOSTUNREACH: /* No route to host */ #endif /* EHOSTUNREACH */ #ifdef EDQUOT case EDQUOT: /* Disc quota exceeded */ #endif /* EDQUOT */ #ifdef EPROCLIM case EPROCLIM: /* Too many processes */ #endif /* EPROCLIM */ #ifdef EUSERS case EUSERS: /* Too many users */ #endif /* EUSERS */ #ifdef EDEADLK case EDEADLK: /* Resource deadlock avoided */ #endif /* EDEADLK */ #ifdef EISCONN case EISCONN: /* Socket already connected */ #endif /* EISCONN */ #ifdef EINPROGRESS case EINPROGRESS: /* Operation now in progress */ #endif /* EINPROGRESS */ #ifdef EALREADY case EALREADY: /* Operation already in progress */ #endif /* EALREADY */ #ifdef EADDRINUSE case EADDRINUSE: /* Address already in use */ #endif /* EADDRINUSE */ #ifdef EADDRNOTAVAIL case EADDRNOTAVAIL: /* Can't assign requested address */ #endif /* EADDRNOTAVAIL */ #ifdef ETXTBSY case ETXTBSY: /* (Apollo) file locked */ #endif /* ETXTBSY */ #if defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR)) case ENOSR: /* Out of streams resources */ #endif /* defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR)) */ #ifdef ENOLCK case ENOLCK: /* No locks available */ #endif /* ENOLCK */ case E_SM_OPENTIMEOUT: /* PSEUDO: open timed out */ return true; } /* nope, must be permanent */ return false; } /* ** LOCKFILE -- lock a file using flock or (shudder) fcntl locking ** ** Parameters: ** fd -- the file descriptor of the file. ** filename -- the file name (for error messages). ** ext -- the filename extension. ** type -- type of the lock. Bits can be: ** LOCK_EX -- exclusive lock. ** LOCK_NB -- non-blocking. ** LOCK_UN -- unlock. ** ** Returns: ** true if the lock was acquired. ** false otherwise. */ bool lockfile(fd, filename, ext, type) int fd; char *filename; char *ext; int type; { int i; int save_errno; # if !HASFLOCK int action; struct flock lfd; if (ext == NULL) ext = ""; memset(&lfd, '\0', sizeof(lfd)); if (bitset(LOCK_UN, type)) lfd.l_type = F_UNLCK; else if (bitset(LOCK_EX, type)) lfd.l_type = F_WRLCK; else lfd.l_type = F_RDLCK; if (bitset(LOCK_NB, type)) action = F_SETLK; else action = F_SETLKW; if (tTd(55, 60)) sm_dprintf("lockfile(%s%s, action=%d, type=%d): ", filename, ext, action, lfd.l_type); while ((i = fcntl(fd, action, &lfd)) < 0 && errno == EINTR) continue; if (i >= 0) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } save_errno = errno; if (tTd(55, 60)) sm_dprintf("(%s) ", sm_errstring(save_errno)); /* ** On SunOS, if you are testing using -oQ/tmp/mqueue or ** -oA/tmp/aliases or anything like that, and /tmp is mounted ** as type "tmp" (that is, served from swap space), the ** previous fcntl will fail with "Invalid argument" errors. ** Since this is fairly common during testing, we will assume ** that this indicates that the lock is successfully grabbed. */ if (save_errno == EINVAL) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } if (!bitset(LOCK_NB, type) || (save_errno != EACCES && save_errno != EAGAIN)) { int omode = fcntl(fd, F_GETFL, 0); uid_t euid = geteuid(); errno = save_errno; syserr("cannot lockf(%s%s, fd=%d, type=%o, omode=%o, euid=%ld)", filename, ext, fd, type, omode, (long) euid); dumpfd(fd, true, true); } # else /* !HASFLOCK */ if (ext == NULL) ext = ""; if (tTd(55, 60)) sm_dprintf("lockfile(%s%s, type=%o): ", filename, ext, type); while ((i = flock(fd, type)) < 0 && errno == EINTR) continue; if (i >= 0) { if (tTd(55, 60)) sm_dprintf("SUCCESS\n"); return true; } save_errno = errno; if (tTd(55, 60)) sm_dprintf("(%s) ", sm_errstring(save_errno)); if (!bitset(LOCK_NB, type) || save_errno != EWOULDBLOCK) { int omode = fcntl(fd, F_GETFL, 0); uid_t euid = geteuid(); errno = save_errno; syserr("cannot flock(%s%s, fd=%d, type=%o, omode=%o, euid=%ld)", filename, ext, fd, type, omode, (long) euid); dumpfd(fd, true, true); } # endif /* !HASFLOCK */ if (tTd(55, 60)) sm_dprintf("FAIL\n"); errno = save_errno; return false; } /* ** CHOWNSAFE -- tell if chown is "safe" (executable only by root) ** ** Unfortunately, given that we can't predict other systems on which ** a remote mounted (NFS) filesystem will be mounted, the answer is ** almost always that this is unsafe. ** ** Note also that many operating systems have non-compliant ** implementations of the _POSIX_CHOWN_RESTRICTED variable and the ** fpathconf() routine. According to IEEE 1003.1-1990, if ** _POSIX_CHOWN_RESTRICTED is defined and not equal to -1, then ** no non-root process can give away the file. However, vendors ** don't take NFS into account, so a comfortable value of ** _POSIX_CHOWN_RESTRICTED tells us nothing. ** ** Also, some systems (e.g., IRIX 6.2) return 1 from fpathconf() ** even on files where chown is not restricted. Many systems get ** this wrong on NFS-based filesystems (that is, they say that chown ** is restricted [safe] on NFS filesystems where it may not be, since ** other systems can access the same filesystem and do file giveaway; ** only the NFS server knows for sure!) Hence, it is important to ** get the value of SAFENFSPATHCONF correct -- it should be defined ** _only_ after testing (see test/t_pathconf.c) a system on an unsafe ** NFS-based filesystem to ensure that you can get meaningful results. ** If in doubt, assume unsafe! ** ** You may also need to tweak IS_SAFE_CHOWN -- it should be a ** condition indicating whether the return from pathconf indicates ** that chown is safe (typically either > 0 or >= 0 -- there isn't ** even any agreement about whether a zero return means that a file ** is or is not safe). It defaults to "> 0". ** ** If the parent directory is safe (writable only by owner back ** to the root) then we can relax slightly and trust fpathconf ** in more circumstances. This is really a crock -- if this is an ** NFS mounted filesystem then we really know nothing about the ** underlying implementation. However, most systems pessimize and ** return an error (EINVAL or EOPNOTSUPP) on NFS filesystems, which ** we interpret as unsafe, as we should. Thus, this heuristic gets ** us into a possible problem only on systems that have a broken ** pathconf implementation and which are also poorly configured ** (have :include: files in group- or world-writable directories). ** ** Parameters: ** fd -- the file descriptor to check. ** safedir -- set if the parent directory is safe. ** ** Returns: ** true -- if the chown(2) operation is "safe" -- that is, ** only root can chown the file to an arbitrary user. ** false -- if an arbitrary user can give away a file. */ #ifndef IS_SAFE_CHOWN # define IS_SAFE_CHOWN > 0 #endif /* ! IS_SAFE_CHOWN */ bool chownsafe(fd, safedir) int fd; bool safedir; { # if (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && \ (defined(_PC_CHOWN_RESTRICTED) || defined(_GNU_TYPES_H)) int rval; /* give the system administrator a chance to override */ if (bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail)) return true; /* ** Some systems (e.g., SunOS) seem to have the call and the ** #define _PC_CHOWN_RESTRICTED, but don't actually implement ** the call. This heuristic checks for that. */ errno = 0; rval = fpathconf(fd, _PC_CHOWN_RESTRICTED); # if SAFENFSPATHCONF return errno == 0 && rval IS_SAFE_CHOWN; # else /* SAFENFSPATHCONF */ return safedir && errno == 0 && rval IS_SAFE_CHOWN; # endif /* SAFENFSPATHCONF */ # else /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */ return bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail); # endif /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */ } /* ** RESETLIMITS -- reset system controlled resource limits ** ** This is to avoid denial-of-service attacks ** ** Parameters: ** none ** ** Returns: ** none */ #if HASSETRLIMIT # ifdef RLIMIT_NEEDS_SYS_TIME_H # include # endif /* RLIMIT_NEEDS_SYS_TIME_H */ # include #endif /* HASSETRLIMIT */ void resetlimits() { #if HASSETRLIMIT struct rlimit lim; lim.rlim_cur = lim.rlim_max = RLIM_INFINITY; (void) setrlimit(RLIMIT_CPU, &lim); (void) setrlimit(RLIMIT_FSIZE, &lim); # ifdef RLIMIT_NOFILE lim.rlim_cur = lim.rlim_max = FD_SETSIZE; (void) setrlimit(RLIMIT_NOFILE, &lim); # endif /* RLIMIT_NOFILE */ #else /* HASSETRLIMIT */ # if HASULIMIT (void) ulimit(2, 0x3fffff); (void) ulimit(4, FD_SETSIZE); # endif /* HASULIMIT */ #endif /* HASSETRLIMIT */ errno = 0; } /* ** SETVENDOR -- process vendor code from V configuration line ** ** Parameters: ** vendor -- string representation of vendor. ** ** Returns: ** true -- if ok. ** false -- if vendor code could not be processed. ** ** Side Effects: ** It is reasonable to set mode flags here to tweak ** processing in other parts of the code if necessary. ** For example, if you are a vendor that uses $%y to ** indicate YP lookups, you could enable that here. */ bool setvendor(vendor) char *vendor; { if (sm_strcasecmp(vendor, "Berkeley") == 0) { VendorCode = VENDOR_BERKELEY; return true; } /* add vendor extensions here */ #ifdef SUN_EXTENSIONS if (sm_strcasecmp(vendor, "Sun") == 0) { VendorCode = VENDOR_SUN; return true; } #endif /* SUN_EXTENSIONS */ #ifdef DEC if (sm_strcasecmp(vendor, "Digital") == 0) { VendorCode = VENDOR_DEC; return true; } #endif /* DEC */ #if defined(VENDOR_NAME) && defined(VENDOR_CODE) if (sm_strcasecmp(vendor, VENDOR_NAME) == 0) { VendorCode = VENDOR_CODE; return true; } #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */ return false; } /* ** GETVENDOR -- return vendor name based on vendor code ** ** Parameters: ** vendorcode -- numeric representation of vendor. ** ** Returns: ** string containing vendor name. */ char * getvendor(vendorcode) int vendorcode; { #if defined(VENDOR_NAME) && defined(VENDOR_CODE) /* ** Can't have the same switch case twice so need to ** handle VENDOR_CODE outside of switch. It might ** match one of the existing VENDOR_* codes. */ if (vendorcode == VENDOR_CODE) return VENDOR_NAME; #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */ switch (vendorcode) { case VENDOR_BERKELEY: return "Berkeley"; case VENDOR_SUN: return "Sun"; case VENDOR_HP: return "HP"; case VENDOR_IBM: return "IBM"; case VENDOR_SENDMAIL: return "Sendmail"; default: return "Unknown"; } } /* ** VENDOR_PRE_DEFAULTS, VENDOR_POST_DEFAULTS -- set vendor-specific defaults ** ** Vendor_pre_defaults is called before reading the configuration ** file; vendor_post_defaults is called immediately after. ** ** Parameters: ** e -- the global environment to initialize. ** ** Returns: ** none. */ #if SHARE_V1 int DefShareUid; /* default share uid to run as -- unused??? */ #endif /* SHARE_V1 */ void vendor_pre_defaults(e) ENVELOPE *e; { #if SHARE_V1 /* OTHERUID is defined in shares.h, do not be alarmed */ DefShareUid = OTHERUID; #endif /* SHARE_V1 */ #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) sun_pre_defaults(e); #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */ #ifdef apollo /* ** stupid domain/os can't even open ** /etc/mail/sendmail.cf without this */ sm_setuserenv("ISP", NULL); sm_setuserenv("SYSTYPE", NULL); #endif /* apollo */ } void vendor_post_defaults(e) ENVELOPE *e; { #ifdef __QNX__ /* Makes sure the SOCK environment variable remains */ sm_setuserenv("SOCK", NULL); #endif /* __QNX__ */ #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) sun_post_defaults(e); #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */ } /* ** VENDOR_DAEMON_SETUP -- special vendor setup needed for daemon mode */ void vendor_daemon_setup(e) ENVELOPE *e; { #if HASSETLOGIN (void) setlogin(RunAsUserName); #endif /* HASSETLOGIN */ #if SECUREWARE if (getluid() != -1) { usrerr("Daemon cannot have LUID"); finis(false, true, EX_USAGE); } #endif /* SECUREWARE */ } /* ** VENDOR_SET_UID -- do setup for setting a user id ** ** This is called when we are still root. ** ** Parameters: ** uid -- the uid we are about to become. ** ** Returns: ** none. */ void vendor_set_uid(uid) UID_T uid; { /* ** We need to setup the share groups (lnodes) ** and add auditing information (luid's) ** before we loose our ``root''ness. */ #if SHARE_V1 if (setupshares(uid, syserr) != 0) syserr("Unable to set up shares"); #endif /* SHARE_V1 */ #if SECUREWARE (void) setup_secure(uid); #endif /* SECUREWARE */ } /* ** VALIDATE_CONNECTION -- check connection for rationality ** ** If the connection is rejected, this routine should log an ** appropriate message -- but should never issue any SMTP protocol. ** ** Parameters: ** sap -- a pointer to a SOCKADDR naming the peer. ** hostname -- the name corresponding to sap. ** e -- the current envelope. ** ** Returns: ** error message from rejection. ** NULL if not rejected. */ #if TCPWRAPPERS # include /* tcpwrappers does no logging, but you still have to declare these -- ugh */ int allow_severity = LOG_INFO; int deny_severity = LOG_NOTICE; #endif /* TCPWRAPPERS */ char * validate_connection(sap, hostname, e) SOCKADDR *sap; char *hostname; ENVELOPE *e; { #if TCPWRAPPERS char *host; char *addr; extern int hosts_ctl(); #endif /* TCPWRAPPERS */ if (tTd(48, 3)) sm_dprintf("validate_connection(%s, %s)\n", hostname, anynet_ntoa(sap)); connection_rate_check(sap, e); if (rscheck("check_relay", hostname, anynet_ntoa(sap), e, RSF_RMCOMM|RSF_COUNT, 3, NULL, NOQID, NULL, NULL) != EX_OK) { static char reject[BUFSIZ*2]; extern char MsgBuf[]; if (tTd(48, 4)) sm_dprintf(" ... validate_connection: BAD (rscheck)\n"); if (strlen(MsgBuf) >= 3) (void) sm_strlcpy(reject, MsgBuf, sizeof(reject)); else (void) sm_strlcpy(reject, "Access denied", sizeof(reject)); return reject; } #if TCPWRAPPERS if (hostname[0] == '[' && hostname[strlen(hostname) - 1] == ']') host = "unknown"; else host = hostname; addr = anynet_ntoa(sap); # if NETINET6 /* TCP/Wrappers don't want the IPv6: protocol label */ if (addr != NULL && sm_strncasecmp(addr, "IPv6:", 5) == 0) addr += 5; # endif /* NETINET6 */ if (!hosts_ctl("sendmail", host, addr, STRING_UNKNOWN)) { if (tTd(48, 4)) sm_dprintf(" ... validate_connection: BAD (tcpwrappers)\n"); if (LogLevel > 3) sm_syslog(LOG_NOTICE, e->e_id, "tcpwrappers (%s, %s) rejection", host, addr); return "Access denied"; } #endif /* TCPWRAPPERS */ if (tTd(48, 4)) sm_dprintf(" ... validate_connection: OK\n"); return NULL; } /* ** STRTOL -- convert string to long integer ** ** For systems that don't have it in the C library. ** ** This is taken verbatim from the 4.4-Lite C library. */ #if NEEDSTRTOL # if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strtol.c 8.1 (Berkeley) 6/4/93"; # endif /* defined(LIBC_SCCS) && !defined(lint) */ /* ** Convert a string to a long integer. ** ** Ignores `locale' stuff. Assumes that the upper and lower case ** alphabets and digits are each contiguous. */ long strtol(nptr, endptr, base) const char *nptr; char **endptr; register int base; { register const char *s = nptr; register unsigned long acc; register int c; register unsigned long cutoff; register int neg = 0, any, cutlim; /* ** Skip white space and pick up leading +/- sign if any. ** If base is 0, allow 0x for hex and 0 for octal, else ** assume decimal; if base is already 16, allow 0x. */ do { c = *s++; } while (isascii(c) && isspace(c)); if (c == '-') { neg = 1; c = *s++; } else if (c == '+') c = *s++; if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; /* ** Compute the cutoff value between legal numbers and illegal ** numbers. That is the largest legal value, divided by the ** base. An input number that is greater than this value, if ** followed by a legal input character, is too big. One that ** is equal to this value may be valid or not; the limit ** between valid and invalid numbers is then based on the last ** digit. For instance, if the range for longs is ** [-2147483648..2147483647] and the input base is 10, ** cutoff will be set to 214748364 and cutlim to either ** 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated ** a value > 214748364, or equal but the next digit is > 7 (or 8), ** the number is too big, and we will return a range error. ** ** Set any if any `digits' consumed; make it negative to indicate ** overflow. */ cutoff = neg ? -(unsigned long) LONG_MIN : LONG_MAX; cutlim = cutoff % (unsigned long) base; cutoff /= (unsigned long) base; for (acc = 0, any = 0;; c = *s++) { if (isascii(c) && isdigit(c)) c -= '0'; else if (isascii(c) && isalpha(c)) c -= isupper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim) any = -1; else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; errno = ERANGE; } else if (neg) acc = -acc; if (endptr != 0) *endptr = (char *)(any ? s - 1 : nptr); return acc; } #endif /* NEEDSTRTOL */ /* ** STRSTR -- find first substring in string ** ** Parameters: ** big -- the big (full) string. ** little -- the little (sub) string. ** ** Returns: ** A pointer to the first instance of little in big. ** big if little is the null string. ** NULL if little is not contained in big. */ #if NEEDSTRSTR char * strstr(big, little) char *big; char *little; { register char *p = big; int l; if (*little == '\0') return big; l = strlen(little); while ((p = strchr(p, *little)) != NULL) { if (strncmp(p, little, l) == 0) return p; p++; } return NULL; } #endif /* NEEDSTRSTR */ /* ** SM_GETHOSTBY{NAME,ADDR} -- compatibility routines for gethostbyXXX ** ** Some operating systems have weird problems with the gethostbyXXX ** routines. For example, Solaris versions at least through 2.3 ** don't properly deliver a canonical h_name field. This tries to ** work around these problems. ** ** Support IPv6 as well as IPv4. */ #if NETINET6 && NEEDSGETIPNODE # ifndef AI_DEFAULT # define AI_DEFAULT 0 /* dummy */ # endif /* ! AI_DEFAULT */ # ifndef AI_ADDRCONFIG # define AI_ADDRCONFIG 0 /* dummy */ # endif /* ! AI_ADDRCONFIG */ # ifndef AI_V4MAPPED # define AI_V4MAPPED 0 /* dummy */ # endif /* ! AI_V4MAPPED */ # ifndef AI_ALL # define AI_ALL 0 /* dummy */ # endif /* ! AI_ALL */ static struct hostent * sm_getipnodebyname(name, family, flags, err) const char *name; int family; int flags; int *err; { struct hostent *h; # if HAS_GETHOSTBYNAME2 h = gethostbyname2(name, family); if (h == NULL) *err = h_errno; return h; # else /* HAS_GETHOSTBYNAME2 */ bool resv6 = true; if (family == AF_INET6) { /* From RFC2133, section 6.1 */ resv6 = bitset(RES_USE_INET6, _res.options); _res.options |= RES_USE_INET6; } SM_SET_H_ERRNO(0); h = gethostbyname(name); if (!resv6) _res.options &= ~RES_USE_INET6; /* the function is supposed to return only the requested family */ if (h != NULL && h->h_addrtype != family) { # if NETINET6 freehostent(h); # endif /* NETINET6 */ h = NULL; *err = NO_DATA; } else *err = h_errno; return h; # endif /* HAS_GETHOSTBYNAME2 */ } static struct hostent * sm_getipnodebyaddr(addr, len, family, err) const void *addr; size_t len; int family; int *err; { struct hostent *h; SM_SET_H_ERRNO(0); h = gethostbyaddr(addr, len, family); *err = h_errno; return h; } void freehostent(h) struct hostent *h; { /* ** Stub routine -- if they don't have getipnodeby*(), ** they probably don't have the free routine either. */ return; } #endif /* NETINET6 && NEEDSGETIPNODE */ struct hostent * sm_gethostbyname(name, family) char *name; int family; { int save_errno; struct hostent *h = NULL; #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) # if SOLARIS == 20300 || SOLARIS == 203 static struct hostent hp; static char buf[1000]; extern struct hostent *_switch_gethostbyname_r(); if (tTd(61, 10)) sm_dprintf("_switch_gethostbyname_r(%s)... ", name); h = _switch_gethostbyname_r(name, &hp, buf, sizeof(buf), &h_errno); save_errno = errno; # else /* SOLARIS == 20300 || SOLARIS == 203 */ extern struct hostent *__switch_gethostbyname(); if (tTd(61, 10)) sm_dprintf("__switch_gethostbyname(%s)... ", name); h = __switch_gethostbyname(name); save_errno = errno; # endif /* SOLARIS == 20300 || SOLARIS == 203 */ #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ int nmaps; # if NETINET6 # ifndef SM_IPNODEBYNAME_FLAGS /* For IPv4-mapped addresses, use: AI_DEFAULT|AI_ALL */ # define SM_IPNODEBYNAME_FLAGS AI_ADDRCONFIG # endif /* SM_IPNODEBYNAME_FLAGS */ int flags = SM_IPNODEBYNAME_FLAGS; int err; # endif /* NETINET6 */ char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; char hbuf[MAXNAME]; if (tTd(61, 10)) sm_dprintf("sm_gethostbyname(%s, %d)... ", name, family); # if NETINET6 # if ADDRCONFIG_IS_BROKEN flags &= ~AI_ADDRCONFIG; # endif /* ADDRCONFIG_IS_BROKEN */ h = sm_getipnodebyname(name, family, flags, &err); SM_SET_H_ERRNO(err); # else /* NETINET6 */ h = gethostbyname(name); # endif /* NETINET6 */ save_errno = errno; if (h == NULL) { if (tTd(61, 10)) sm_dprintf("failure\n"); nmaps = switch_map_find("hosts", maptype, mapreturn); while (--nmaps >= 0) { if (strcmp(maptype[nmaps], "nis") == 0 || strcmp(maptype[nmaps], "files") == 0) break; } if (nmaps >= 0) { /* try short name */ if (strlen(name) > sizeof(hbuf) - 1) { errno = save_errno; return NULL; } (void) sm_strlcpy(hbuf, name, sizeof(hbuf)); (void) shorten_hostname(hbuf); /* if it hasn't been shortened, there's no point */ if (strcmp(hbuf, name) != 0) { if (tTd(61, 10)) sm_dprintf("sm_gethostbyname(%s, %d)... ", hbuf, family); # if NETINET6 h = sm_getipnodebyname(hbuf, family, flags, &err); SM_SET_H_ERRNO(err); save_errno = errno; # else /* NETINET6 */ h = gethostbyname(hbuf); save_errno = errno; # endif /* NETINET6 */ } } } #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */ /* the function is supposed to return only the requested family */ if (h != NULL && h->h_addrtype != family) { # if NETINET6 freehostent(h); # endif /* NETINET6 */ h = NULL; SM_SET_H_ERRNO(NO_DATA); } if (tTd(61, 10)) { if (h == NULL) sm_dprintf("failure\n"); else { sm_dprintf("%s\n", h->h_name); if (tTd(61, 11)) { struct in_addr ia; size_t i; #if NETINET6 struct in6_addr ia6; char buf6[INET6_ADDRSTRLEN]; #endif /* NETINET6 */ if (h->h_aliases != NULL) for (i = 0; h->h_aliases[i] != NULL; i++) sm_dprintf("\talias: %s\n", h->h_aliases[i]); for (i = 0; h->h_addr_list[i] != NULL; i++) { char *addr; addr = NULL; #if NETINET6 if (h->h_addrtype == AF_INET6) { memmove(&ia6, h->h_addr_list[i], IN6ADDRSZ); addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); } else #endif /* NETINET6 */ /* "else" in #if code above */ { memmove(&ia, h->h_addr_list[i], INADDRSZ); addr = (char *) inet_ntoa(ia); } if (addr != NULL) sm_dprintf("\taddr: %s\n", addr); } } } } errno = save_errno; return h; } struct hostent * sm_gethostbyaddr(addr, len, type) char *addr; int len; int type; { struct hostent *hp; #if NETINET6 if (type == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *) addr)) { /* Avoid reverse lookup for IPv6 unspecified address */ SM_SET_H_ERRNO(HOST_NOT_FOUND); return NULL; } #endif /* NETINET6 */ #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) # if SOLARIS == 20300 || SOLARIS == 203 { static struct hostent he; static char buf[1000]; extern struct hostent *_switch_gethostbyaddr_r(); hp = _switch_gethostbyaddr_r(addr, len, type, &he, buf, sizeof(buf), &h_errno); } # else /* SOLARIS == 20300 || SOLARIS == 203 */ { extern struct hostent *__switch_gethostbyaddr(); hp = __switch_gethostbyaddr(addr, len, type); } # endif /* SOLARIS == 20300 || SOLARIS == 203 */ #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */ # if NETINET6 { int err; hp = sm_getipnodebyaddr(addr, len, type, &err); SM_SET_H_ERRNO(err); } # else /* NETINET6 */ hp = gethostbyaddr(addr, len, type); # endif /* NETINET6 */ #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */ return hp; } /* ** SM_GETPW{NAM,UID} -- wrapper for getpwnam and getpwuid */ struct passwd * sm_getpwnam(user) char *user; { #ifdef _AIX4 extern struct passwd *_getpwnam_shadow(const char *, const int); return _getpwnam_shadow(user, 0); #else /* _AIX4 */ return getpwnam(user); #endif /* _AIX4 */ } struct passwd * sm_getpwuid(uid) UID_T uid; { #if defined(_AIX4) && 0 extern struct passwd *_getpwuid_shadow(const int, const int); return _getpwuid_shadow(uid,0); #else /* defined(_AIX4) && 0 */ return getpwuid(uid); #endif /* defined(_AIX4) && 0 */ } /* ** SECUREWARE_SETUP_SECURE -- Convex SecureWare setup ** ** Set up the trusted computing environment for C2 level security ** under SecureWare. ** ** Parameters: ** uid -- uid of the user to initialize in the TCB ** ** Returns: ** none ** ** Side Effects: ** Initialized the user in the trusted computing base */ #if SECUREWARE # include # include void secureware_setup_secure(uid) UID_T uid; { int rc; if (getluid() != -1) return; if ((rc = set_secure_info(uid)) != SSI_GOOD_RETURN) { switch (rc) { case SSI_NO_PRPW_ENTRY: syserr("No protected passwd entry, uid = %d", (int) uid); break; case SSI_LOCKED: syserr("Account has been disabled, uid = %d", (int) uid); break; case SSI_RETIRED: syserr("Account has been retired, uid = %d", (int) uid); break; case SSI_BAD_SET_LUID: syserr("Could not set LUID, uid = %d", (int) uid); break; case SSI_BAD_SET_PRIVS: syserr("Could not set kernel privs, uid = %d", (int) uid); default: syserr("Unknown return code (%d) from set_secure_info(%d)", rc, (int) uid); break; } finis(false, true, EX_NOPERM); } } #endif /* SECUREWARE */ /* ** ADD_HOSTNAMES -- Add a hostname to class 'w' based on IP address ** ** Add hostnames to class 'w' based on the IP address read from ** the network interface. ** ** Parameters: ** sa -- a pointer to a SOCKADDR containing the address ** ** Returns: ** 0 if successful, -1 if host lookup fails. */ static int add_hostnames(sa) SOCKADDR *sa; { struct hostent *hp; char **ha; char hnb[MAXHOSTNAMELEN]; /* lookup name with IP address */ switch (sa->sa.sa_family) { #if NETINET case AF_INET: hp = sm_gethostbyaddr((char *) &sa->sin.sin_addr, sizeof(sa->sin.sin_addr), sa->sa.sa_family); break; #endif /* NETINET */ #if NETINET6 case AF_INET6: hp = sm_gethostbyaddr((char *) &sa->sin6.sin6_addr, sizeof(sa->sin6.sin6_addr), sa->sa.sa_family); break; #endif /* NETINET6 */ default: /* Give warning about unsupported family */ if (LogLevel > 3) sm_syslog(LOG_WARNING, NOQID, "Unsupported address family %d: %.100s", sa->sa.sa_family, anynet_ntoa(sa)); return -1; } if (hp == NULL) { int save_errno = errno; if (LogLevel > 3 && #if NETINET && defined(IN_LINKLOCAL) !(sa->sa.sa_family == AF_INET && IN_LINKLOCAL(ntohl(sa->sin.sin_addr.s_addr))) && #endif /* NETINET && defined(IN_LINKLOCAL) */ #if NETINET6 !(sa->sa.sa_family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr)) && #endif /* NETINET6 */ true) sm_syslog(LOG_WARNING, NOQID, "gethostbyaddr(%.100s) failed: %d", anynet_ntoa(sa), #if NAMED_BIND h_errno #else /* NAMED_BIND */ -1 #endif /* NAMED_BIND */ ); errno = save_errno; return -1; } /* save its cname */ if (!wordinclass((char *) hp->h_name, 'w')) { setclass('w', (char *) hp->h_name); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", hp->h_name); if (sm_snprintf(hnb, sizeof(hnb), "[%s]", hp->h_name) < sizeof(hnb) && !wordinclass((char *) hnb, 'w')) setclass('w', hnb); } else { if (tTd(0, 43)) sm_dprintf("\ta.k.a.: %s (already in $=w)\n", hp->h_name); } /* save all it aliases name */ for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++) { if (!wordinclass(*ha, 'w')) { setclass('w', *ha); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", *ha); if (sm_snprintf(hnb, sizeof(hnb), "[%s]", *ha) < sizeof(hnb) && !wordinclass((char *) hnb, 'w')) setclass('w', hnb); } else { if (tTd(0, 43)) sm_dprintf("\ta.k.a.: %s (already in $=w)\n", *ha); } } #if NETINET6 freehostent(hp); #endif /* NETINET6 */ return 0; } /* ** LOAD_IF_NAMES -- load interface-specific names into $=w ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** Loads $=w with the names of all the interfaces. */ #if !NETINET # define SIOCGIFCONF_IS_BROKEN 1 /* XXX */ #endif /* !NETINET */ #if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN struct rtentry; struct mbuf; # ifndef SUNOS403 # include # endif /* ! SUNOS403 */ # if (_AIX4 >= 40300) && !defined(_NET_IF_H) # undef __P # endif /* (_AIX4 >= 40300) && !defined(_NET_IF_H) */ # include #endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */ void load_if_names() { # if NETINET6 && defined(SIOCGLIFCONF) # ifdef __hpux /* ** Unfortunately, HP has changed all of the structures, ** making life difficult for implementors. */ # define lifconf if_laddrconf # define lifc_len iflc_len # define lifc_buf iflc_buf # define lifreq if_laddrreq # define lifr_addr iflr_addr # define lifr_name iflr_name # define lifr_flags iflr_flags # define ss_family sa_family # undef SIOCGLIFNUM # endif /* __hpux */ int s; int i; size_t len; int numifs; char *buf; struct lifconf lifc; # ifdef SIOCGLIFNUM struct lifnum lifn; # endif /* SIOCGLIFNUM */ s = socket(InetMode, SOCK_DGRAM, 0); if (s == -1) return; /* get the list of known IP address from the kernel */ # ifdef __hpux i = ioctl(s, SIOCGIFNUM, (char *) &numifs); # endif /* __hpux */ # ifdef SIOCGLIFNUM lifn.lifn_family = AF_UNSPEC; lifn.lifn_flags = 0; i = ioctl(s, SIOCGLIFNUM, (char *)&lifn); numifs = lifn.lifn_count; # endif /* SIOCGLIFNUM */ # if defined(__hpux) || defined(SIOCGLIFNUM) if (i < 0) { /* can't get number of interfaces -- fall back */ if (tTd(0, 4)) sm_dprintf("SIOCGLIFNUM failed: %s\n", sm_errstring(errno)); numifs = -1; } else if (tTd(0, 42)) sm_dprintf("system has %d interfaces\n", numifs); if (numifs < 0) # endif /* defined(__hpux) || defined(SIOCGLIFNUM) */ numifs = MAXINTERFACES; if (numifs <= 0) { (void) close(s); return; } len = lifc.lifc_len = numifs * sizeof(struct lifreq); buf = lifc.lifc_buf = xalloc(lifc.lifc_len); # ifndef __hpux lifc.lifc_family = AF_UNSPEC; lifc.lifc_flags = 0; # endif /* ! __hpux */ if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGLIFCONF failed: %s\n", sm_errstring(errno)); (void) close(s); sm_free(buf); return; } /* scan the list of IP address */ if (tTd(0, 40)) sm_dprintf("scanning for interface specific names, lifc_len=%ld\n", (long) len); for (i = 0; i < len && i >= 0; ) { int flags; struct lifreq *ifr = (struct lifreq *)&buf[i]; SOCKADDR *sa = (SOCKADDR *) &ifr->lifr_addr; int af = ifr->lifr_addr.ss_family; char *addr; char *name; struct in6_addr ia6; struct in_addr ia; # ifdef SIOCGLIFFLAGS struct lifreq ifrf; # endif /* SIOCGLIFFLAGS */ char ip_addr[256]; char buf6[INET6_ADDRSTRLEN]; /* ** We must close and recreate the socket each time ** since we don't know what type of socket it is now ** (each status function may change it). */ (void) close(s); s = socket(af, SOCK_DGRAM, 0); if (s == -1) { sm_free(buf); /* XXX */ return; } /* ** If we don't have a complete ifr structure, ** don't try to use it. */ if ((len - i) < sizeof(*ifr)) break; # ifdef BSD4_4_SOCKADDR if (sa->sa.sa_len > sizeof(ifr->lifr_addr)) i += sizeof(ifr->lifr_name) + sa->sa.sa_len; else # endif /* BSD4_4_SOCKADDR */ # ifdef DEC /* fix for IPv6 size differences */ i += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len); # else /* DEC */ i += sizeof(*ifr); # endif /* DEC */ if (tTd(0, 20)) sm_dprintf("%s\n", anynet_ntoa(sa)); if (af != AF_INET && af != AF_INET6) continue; # ifdef SIOCGLIFFLAGS memset(&ifrf, '\0', sizeof(struct lifreq)); (void) sm_strlcpy(ifrf.lifr_name, ifr->lifr_name, sizeof(ifrf.lifr_name)); if (ioctl(s, SIOCGLIFFLAGS, (char *) &ifrf) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGLIFFLAGS failed: %s\n", sm_errstring(errno)); continue; } name = ifr->lifr_name; flags = ifrf.lifr_flags; if (tTd(0, 41)) sm_dprintf("\tflags: %lx\n", (unsigned long) flags); if (!bitset(IFF_UP, flags)) continue; # endif /* SIOCGLIFFLAGS */ ip_addr[0] = '\0'; /* extract IP address from the list*/ switch (af) { case AF_INET6: SETV6LOOPBACKADDRFOUND(*sa); # ifdef __KAME__ /* convert into proper scoped address */ if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) || IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) && sa->sin6.sin6_scope_id == 0) { struct in6_addr *ia6p; ia6p = &sa->sin6.sin6_addr; sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] | ((unsigned int)ia6p->s6_addr[2] << 8)); ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0; } # endif /* __KAME__ */ ia6 = sa->sin6.sin6_addr; if (IN6_IS_ADDR_UNSPECIFIED(&ia6)) { addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); message("WARNING: interface %s is UP with %s address", name, addr == NULL ? "(NULL)" : addr); continue; } /* save IP address in text from */ addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); if (addr != NULL) (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, addr); break; case AF_INET: ia = sa->sin.sin_addr; if (ia.s_addr == INADDR_ANY || ia.s_addr == INADDR_NONE) { message("WARNING: interface %s is UP with %s address", name, inet_ntoa(ia)); continue; } /* save IP address in text from */ (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, inet_ntoa(ia)); break; } if (*ip_addr == '\0') continue; if (!wordinclass(ip_addr, 'w')) { setclass('w', ip_addr); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", ip_addr); } # ifdef SIOCGLIFFLAGS /* skip "loopback" interface "lo" */ if (DontProbeInterfaces == DPI_SKIPLOOPBACK && bitset(IFF_LOOPBACK, flags)) continue; # endif /* SIOCGLIFFLAGS */ (void) add_hostnames(sa); } sm_free(buf); /* XXX */ (void) close(s); # else /* NETINET6 && defined(SIOCGLIFCONF) */ # if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN int s; int i; struct ifconf ifc; int numifs; s = socket(AF_INET, SOCK_DGRAM, 0); if (s == -1) return; /* get the list of known IP address from the kernel */ # if defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN if (ioctl(s, SIOCGIFNUM, (char *) &numifs) < 0) { /* can't get number of interfaces -- fall back */ if (tTd(0, 4)) sm_dprintf("SIOCGIFNUM failed: %s\n", sm_errstring(errno)); numifs = -1; } else if (tTd(0, 42)) sm_dprintf("system has %d interfaces\n", numifs); if (numifs < 0) # endif /* defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN */ numifs = MAXINTERFACES; if (numifs <= 0) { (void) close(s); return; } ifc.ifc_len = numifs * sizeof(struct ifreq); ifc.ifc_buf = xalloc(ifc.ifc_len); if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) { if (tTd(0, 4)) sm_dprintf("SIOCGIFCONF failed: %s\n", sm_errstring(errno)); (void) close(s); return; } /* scan the list of IP address */ if (tTd(0, 40)) sm_dprintf("scanning for interface specific names, ifc_len=%d\n", ifc.ifc_len); for (i = 0; i < ifc.ifc_len && i >= 0; ) { int af; struct ifreq *ifr = (struct ifreq *) &ifc.ifc_buf[i]; SOCKADDR *sa = (SOCKADDR *) &ifr->ifr_addr; # if NETINET6 char *addr; struct in6_addr ia6; # endif /* NETINET6 */ struct in_addr ia; # ifdef SIOCGIFFLAGS struct ifreq ifrf; # endif /* SIOCGIFFLAGS */ char ip_addr[256]; # if NETINET6 char buf6[INET6_ADDRSTRLEN]; # endif /* NETINET6 */ /* ** If we don't have a complete ifr structure, ** don't try to use it. */ if ((ifc.ifc_len - i) < sizeof(*ifr)) break; # ifdef BSD4_4_SOCKADDR if (sa->sa.sa_len > sizeof(ifr->ifr_addr)) i += sizeof(ifr->ifr_name) + sa->sa.sa_len; else # endif /* BSD4_4_SOCKADDR */ i += sizeof(*ifr); if (tTd(0, 20)) sm_dprintf("%s\n", anynet_ntoa(sa)); af = ifr->ifr_addr.sa_family; if (af != AF_INET # if NETINET6 && af != AF_INET6 # endif /* NETINET6 */ ) continue; # ifdef SIOCGIFFLAGS memset(&ifrf, '\0', sizeof(struct ifreq)); (void) sm_strlcpy(ifrf.ifr_name, ifr->ifr_name, sizeof(ifrf.ifr_name)); (void) ioctl(s, SIOCGIFFLAGS, (char *) &ifrf); if (tTd(0, 41)) sm_dprintf("\tflags: %lx\n", (unsigned long) ifrf.ifr_flags); # define IFRFREF ifrf # else /* SIOCGIFFLAGS */ # define IFRFREF (*ifr) # endif /* SIOCGIFFLAGS */ if (!bitset(IFF_UP, IFRFREF.ifr_flags)) continue; ip_addr[0] = '\0'; /* extract IP address from the list*/ switch (af) { case AF_INET: ia = sa->sin.sin_addr; if (ia.s_addr == INADDR_ANY || ia.s_addr == INADDR_NONE) { message("WARNING: interface %s is UP with %s address", ifr->ifr_name, inet_ntoa(ia)); continue; } /* save IP address in text from */ (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, inet_ntoa(ia)); break; # if NETINET6 case AF_INET6: SETV6LOOPBACKADDRFOUND(*sa); # ifdef __KAME__ /* convert into proper scoped address */ if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) || IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) && sa->sin6.sin6_scope_id == 0) { struct in6_addr *ia6p; ia6p = &sa->sin6.sin6_addr; sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] | ((unsigned int)ia6p->s6_addr[2] << 8)); ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0; } # endif /* __KAME__ */ ia6 = sa->sin6.sin6_addr; if (IN6_IS_ADDR_UNSPECIFIED(&ia6)) { addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); message("WARNING: interface %s is UP with %s address", ifr->ifr_name, addr == NULL ? "(NULL)" : addr); continue; } /* save IP address in text from */ addr = anynet_ntop(&ia6, buf6, sizeof(buf6)); if (addr != NULL) (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]", (int) sizeof(ip_addr) - 3, addr); break; # endif /* NETINET6 */ } if (ip_addr[0] == '\0') continue; if (!wordinclass(ip_addr, 'w')) { setclass('w', ip_addr); if (tTd(0, 4)) sm_dprintf("\ta.k.a.: %s\n", ip_addr); } /* skip "loopback" interface "lo" */ if (DontProbeInterfaces == DPI_SKIPLOOPBACK && bitset(IFF_LOOPBACK, IFRFREF.ifr_flags)) continue; (void) add_hostnames(sa); } sm_free(ifc.ifc_buf); /* XXX */ (void) close(s); # undef IFRFREF # endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */ # endif /* NETINET6 && defined(SIOCGLIFCONF) */ } /* ** ISLOOPBACK -- is socket address in the loopback net? ** ** Parameters: ** sa -- socket address. ** ** Returns: ** true -- is socket address in the loopback net? ** false -- otherwise ** */ bool isloopback(sa) SOCKADDR sa; { #if NETINET6 if (IN6_IS_ADDR_LOOPBACK(&sa.sin6.sin6_addr)) return true; #else /* NETINET6 */ /* XXX how to correctly extract IN_LOOPBACKNET part? */ if (((ntohl(sa.sin.sin_addr.s_addr) & IN_CLASSA_NET) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) return true; #endif /* NETINET6 */ return false; } /* ** GET_NUM_PROCS_ONLINE -- return the number of processors currently online ** ** Parameters: ** none. ** ** Returns: ** The number of processors online. */ static int get_num_procs_online() { int nproc = 0; #ifdef USESYSCTL # if defined(CTL_HW) && defined(HW_NCPU) size_t sz; int mib[2]; mib[0] = CTL_HW; mib[1] = HW_NCPU; sz = (size_t) sizeof(nproc); (void) sysctl(mib, 2, &nproc, &sz, NULL, 0); # endif /* defined(CTL_HW) && defined(HW_NCPU) */ #else /* USESYSCTL */ # ifdef _SC_NPROCESSORS_ONLN nproc = (int) sysconf(_SC_NPROCESSORS_ONLN); # else /* _SC_NPROCESSORS_ONLN */ # ifdef __hpux # include struct pst_dynamic psd; if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) != -1) nproc = psd.psd_proc_cnt; # endif /* __hpux */ # endif /* _SC_NPROCESSORS_ONLN */ #endif /* USESYSCTL */ if (nproc <= 0) nproc = 1; return nproc; } /* ** SM_CLOSEFROM -- close file descriptors ** ** Parameters: ** lowest -- first fd to close ** highest -- last fd + 1 to close ** ** Returns: ** none */ void sm_closefrom(lowest, highest) int lowest, highest; { #if HASCLOSEFROM closefrom(lowest); #else /* HASCLOSEFROM */ int i; for (i = lowest; i < highest; i++) (void) close(i); #endif /* HASCLOSEFROM */ } #if HASFDWALK /* ** CLOSEFD_WALK -- walk fd's arranging to close them ** Callback for fdwalk() ** ** Parameters: ** lowest -- first fd to arrange to be closed ** fd -- fd to arrange to be closed ** ** Returns: ** zero */ static int closefd_walk(lowest, fd) void *lowest; int fd; { if (fd >= *(int *)lowest) (void) fcntl(fd, F_SETFD, FD_CLOEXEC); return 0; } #endif /* HASFDWALK */ /* ** SM_CLOSE_ON_EXEC -- arrange for file descriptors to be closed ** ** Parameters: ** lowest -- first fd to arrange to be closed ** highest -- last fd + 1 to arrange to be closed ** ** Returns: ** none */ void sm_close_on_exec(lowest, highest) int lowest, highest; { #if HASFDWALK (void) fdwalk(closefd_walk, &lowest); #else /* HASFDWALK */ int i, j; for (i = lowest; i < highest; i++) { if ((j = fcntl(i, F_GETFD, 0)) != -1) (void) fcntl(i, F_SETFD, j | FD_CLOEXEC); } #endif /* HASFDWALK */ } /* ** SEED_RANDOM -- seed the random number generator ** ** Parameters: ** none ** ** Returns: ** none */ void seed_random() { #if HASSRANDOMDEV srandomdev(); #else /* HASSRANDOMDEV */ long seed; struct timeval t; seed = (long) CurrentPid; if (gettimeofday(&t, NULL) >= 0) seed += t.tv_sec + t.tv_usec; # if HASRANDOM (void) srandom(seed); # else /* HASRANDOM */ (void) srand((unsigned int) seed); # endif /* HASRANDOM */ #endif /* HASSRANDOMDEV */ } /* ** SM_SYSLOG -- syslog wrapper to keep messages under SYSLOG_BUFSIZE ** ** Parameters: ** level -- syslog level ** id -- envelope ID or NULL (NOQUEUE) ** fmt -- format string ** arg... -- arguments as implied by fmt. ** ** Returns: ** none */ /* VARARGS3 */ void #ifdef __STDC__ sm_syslog(int level, const char *id, const char *fmt, ...) #else /* __STDC__ */ sm_syslog(level, id, fmt, va_alist) int level; const char *id; const char *fmt; va_dcl #endif /* __STDC__ */ { char *buf; size_t bufsize; char *begin, *end; int save_errno; int seq = 1; int idlen; char buf0[MAXLINE]; char *newstring; extern int SyslogPrefixLen; SM_VA_LOCAL_DECL save_errno = errno; if (id == NULL) id = "NOQUEUE"; idlen = strlen(id) + SyslogPrefixLen; buf = buf0; bufsize = sizeof(buf0); for (;;) { int n; /* print log message into buf */ SM_VA_START(ap, fmt); n = sm_vsnprintf(buf, bufsize, fmt, ap); SM_VA_END(ap); SM_ASSERT(n >= 0); if (n < bufsize) break; /* String too small, redo with correct size */ bufsize = n + 1; if (buf != buf0) { sm_free(buf); buf = NULL; } buf = sm_malloc_x(bufsize); } /* clean up buf after it has been expanded with args */ newstring = str2prt(buf); if ((strlen(newstring) + idlen + 1) < SYSLOG_BUFSIZE) { #if LOG if (*id == '\0') { if (tTd(89, 10)) { struct timeval tv; gettimeofday(&tv, NULL); sm_dprintf("%ld.%06ld %s\n", (long) tv.tv_sec, (long) tv.tv_usec, newstring); } else if (tTd(89, 8)) sm_dprintf("%s\n", newstring); else syslog(level, "%s", newstring); } else { if (tTd(89, 10)) { struct timeval tv; gettimeofday(&tv, NULL); sm_dprintf("%ld.%06ld %s: %s\n", (long) tv.tv_sec, (long) tv.tv_usec, id, newstring); } else if (tTd(89, 8)) sm_dprintf("%s: %s\n", id, newstring); else syslog(level, "%s: %s", id, newstring); } #else /* LOG */ /*XXX should do something more sensible */ if (*id == '\0') (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s\n", newstring); else (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: %s\n", id, newstring); #endif /* LOG */ if (buf != buf0) sm_free(buf); errno = save_errno; return; } /* ** additional length for splitting: " ..." + 3, where 3 is magic to ** have some data for the next entry. */ #define SL_SPLIT 7 begin = newstring; idlen += 5; /* strlen("[999]"), see below */ while (*begin != '\0' && (strlen(begin) + idlen) > SYSLOG_BUFSIZE) { char save; if (seq >= 999) { /* Too many messages */ break; } end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT; while (end > begin) { /* Break on comma or space */ if (*end == ',' || *end == ' ') { end++; /* Include separator */ break; } end--; } /* No separator, break midstring... */ if (end == begin) end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT; save = *end; *end = 0; #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: %s ...\n", id, seq++, begin); else syslog(level, "%s[%d]: %s ...", id, seq++, begin); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: %s ...\n", id, seq++, begin); #endif /* LOG */ *end = save; begin = end; } if (seq >= 999) { #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: log terminated, too many parts\n", id, seq); else syslog(level, "%s[%d]: log terminated, too many parts", id, seq); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: log terminated, too many parts\n", id, seq); #endif /* LOG */ } else if (*begin != '\0') { #if LOG if (tTd(89, 8)) sm_dprintf("%s[%d]: %s\n", id, seq, begin); else syslog(level, "%s[%d]: %s", id, seq, begin); #else /* LOG */ (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s[%d]: %s\n", id, seq, begin); #endif /* LOG */ } if (buf != buf0) sm_free(buf); errno = save_errno; } /* ** HARD_SYSLOG -- call syslog repeatedly until it works ** ** Needed on HP-UX, which apparently doesn't guarantee that ** syslog succeeds during interrupt handlers. */ #if defined(__hpux) && !defined(HPUX11) # define MAXSYSLOGTRIES 100 # undef syslog # ifdef V4FS # define XCNST const # define CAST (const char *) # else /* V4FS */ # define XCNST # define CAST # endif /* V4FS */ void # ifdef __STDC__ hard_syslog(int pri, XCNST char *msg, ...) # else /* __STDC__ */ hard_syslog(pri, msg, va_alist) int pri; XCNST char *msg; va_dcl # endif /* __STDC__ */ { int i; char buf[SYSLOG_BUFSIZE]; SM_VA_LOCAL_DECL SM_VA_START(ap, msg); (void) sm_vsnprintf(buf, sizeof(buf), msg, ap); SM_VA_END(ap); for (i = MAXSYSLOGTRIES; --i >= 0 && syslog(pri, CAST "%s", buf) < 0; ) continue; } # undef CAST #endif /* defined(__hpux) && !defined(HPUX11) */ #if NEEDLOCAL_HOSTNAME_LENGTH /* ** LOCAL_HOSTNAME_LENGTH ** ** This is required to get sendmail to compile against BIND 4.9.x ** on Ultrix. ** ** Unfortunately, a Compaq Y2K patch kit provides it without ** bumping __RES in /usr/include/resolv.h so we can't automatically ** figure out whether it is needed. */ int local_hostname_length(hostname) char *hostname; { size_t len_host, len_domain; if (!*_res.defdname) res_init(); len_host = strlen(hostname); len_domain = strlen(_res.defdname); if (len_host > len_domain && (sm_strcasecmp(hostname + len_host - len_domain, _res.defdname) == 0) && hostname[len_host - len_domain - 1] == '.') return len_host - len_domain - 1; else return 0; } #endif /* NEEDLOCAL_HOSTNAME_LENGTH */ #if NEEDLINK /* ** LINK -- clone a file ** ** Some OS's lacks link() and hard links. Since sendmail is using ** link() as an efficient way to clone files, this implementation ** will simply do a file copy. ** ** NOTE: This link() replacement is not a generic replacement as it ** does not handle all of the semantics of the real link(2). ** ** Parameters: ** source -- pathname of existing file. ** target -- pathname of link (clone) to be created. ** ** Returns: ** 0 -- success. ** -1 -- failure, see errno for details. */ int link(source, target) const char *source; const char *target; { int save_errno; int sff; int src = -1, dst = -1; ssize_t readlen; ssize_t writelen; char buf[BUFSIZ]; struct stat st; sff = SFF_REGONLY|SFF_OPENASROOT; if (DontLockReadFiles) sff |= SFF_NOLOCK; /* Open the original file */ src = safeopen((char *)source, O_RDONLY, 0, sff); if (src < 0) goto fail; /* Obtain the size and the mode */ if (fstat(src, &st) < 0) goto fail; /* Create the duplicate copy */ sff &= ~SFF_NOLOCK; sff |= SFF_CREAT; dst = safeopen((char *)target, O_CREAT|O_EXCL|O_WRONLY, st.st_mode, sff); if (dst < 0) goto fail; /* Copy all of the bytes one buffer at a time */ while ((readlen = read(src, &buf, sizeof(buf))) > 0) { ssize_t left = readlen; char *p = buf; while (left > 0 && (writelen = write(dst, p, (size_t) left)) >= 0) { left -= writelen; p += writelen; } if (writelen < 0) break; } /* Any trouble reading? */ if (readlen < 0 || writelen < 0) goto fail; /* Close the input file */ if (close(src) < 0) { src = -1; goto fail; } src = -1; /* Close the output file */ if (close(dst) < 0) { /* don't set dst = -1 here so we unlink the file */ goto fail; } /* Success */ return 0; fail: save_errno = errno; if (src >= 0) (void) close(src); if (dst >= 0) { (void) unlink(target); (void) close(dst); } errno = save_errno; return -1; } #endif /* NEEDLINK */ /* ** Compile-Time options */ char *CompileOptions[] = { #if ALLOW_255 "ALLOW_255", #endif #if NAMED_BIND # if DNSMAP "DNSMAP", # endif #endif #if EGD "EGD", #endif #if HESIOD "HESIOD", #endif #if HESIOD_ALLOW_NUMERIC_LOGIN "HESIOD_ALLOW_NUMERIC_LOGIN", #endif #if HES_GETMAILHOST "HES_GETMAILHOST", #endif #if IPV6_FULL /* Use uncompressed IPv6 address format (no "::") by default */ "IPV6_FULL", #endif #if LDAPMAP "LDAPMAP", #endif #if LDAP_REFERRALS "LDAP_REFERRALS", #endif #if LOG "LOG", #endif #if MAP_NSD "MAP_NSD", #endif #if MAP_REGEX "MAP_REGEX", #endif #if MATCHGECOS "MATCHGECOS", #endif #if MILTER "MILTER", #endif #if MIME7TO8 "MIME7TO8", #endif #if MIME7TO8_OLD "MIME7TO8_OLD", #endif #if MIME8TO7 "MIME8TO7", #endif #if NAMED_BIND "NAMED_BIND", #endif #if NDBM "NDBM", #endif #if NETINET "NETINET", #endif #if NETINET6 "NETINET6", #endif #if NETINFO "NETINFO", #endif #if NETISO "NETISO", #endif #if NETNS "NETNS", #endif #if NETUNIX "NETUNIX", #endif #if NETX25 "NETX25", #endif #if NEWDB "NEWDB", #endif #if NIS "NIS", #endif #if NISPLUS "NISPLUS", #endif #if NO_DH "NO_DH", #endif #if PH_MAP "PH_MAP", #endif #ifdef PICKY_HELO_CHECK "PICKY_HELO_CHECK", #endif #if PIPELINING "PIPELINING", #endif #if SASL # if SASL >= 20000 "SASLv2", # else /* SASL >= 20000 */ "SASL", # endif #endif #if SCANF "SCANF", #endif #if SM_LDAP_ERROR_ON_MISSING_ARGS "SM_LDAP_ERROR_ON_MISSING_ARGS", #endif #if SMTPDEBUG "SMTPDEBUG", #endif #if SOCKETMAP "SOCKETMAP", #endif #if STARTTLS "STARTTLS", #endif #if SUID_ROOT_FILES_OK "SUID_ROOT_FILES_OK", #endif #if TCPWRAPPERS "TCPWRAPPERS", #endif #if TLS_NO_RSA "TLS_NO_RSA", #endif #if TLS_VRFY_PER_CTX "TLS_VRFY_PER_CTX", #endif #if USERDB "USERDB", #endif #if USE_LDAP_INIT "USE_LDAP_INIT", #endif #if USE_TTYPATH "USE_TTYPATH", #endif #if XDEBUG "XDEBUG", #endif #if XLA "XLA", #endif NULL }; /* ** OS compile options. */ char *OsCompileOptions[] = { #if ADDRCONFIG_IS_BROKEN "ADDRCONFIG_IS_BROKEN", #endif #ifdef AUTO_NETINFO_HOSTS "AUTO_NETINFO_HOSTS", #endif #ifdef AUTO_NIS_ALIASES "AUTO_NIS_ALIASES", #endif #if BROKEN_RES_SEARCH "BROKEN_RES_SEARCH", #endif #ifdef BSD4_4_SOCKADDR "BSD4_4_SOCKADDR", #endif #if BOGUS_O_EXCL "BOGUS_O_EXCL", #endif #if DEC_OSF_BROKEN_GETPWENT "DEC_OSF_BROKEN_GETPWENT", #endif #if FAST_PID_RECYCLE "FAST_PID_RECYCLE", #endif #if HASCLOSEFROM "HASCLOSEFROM", #endif #if HASFCHOWN "HASFCHOWN", #endif #if HASFCHMOD "HASFCHMOD", #endif #if HASFDWALK "HASFDWALK", #endif #if HASFLOCK "HASFLOCK", #endif #if HASGETDTABLESIZE "HASGETDTABLESIZE", #endif #if HASGETUSERSHELL "HASGETUSERSHELL", #endif #if HASINITGROUPS "HASINITGROUPS", #endif #if HASLDAPGETALIASBYNAME "HASLDAPGETALIASBYNAME", #endif #if HASLSTAT "HASLSTAT", #endif #if HASNICE "HASNICE", #endif #if HASRANDOM "HASRANDOM", #endif #if HASRRESVPORT "HASRRESVPORT", #endif #if HASSETEGID "HASSETEGID", #endif #if HASSETLOGIN "HASSETLOGIN", #endif #if HASSETREGID "HASSETREGID", #endif #if HASSETRESGID "HASSETRESGID", #endif #if HASSETREUID "HASSETREUID", #endif #if HASSETRLIMIT "HASSETRLIMIT", #endif #if HASSETSID "HASSETSID", #endif #if HASSETUSERCONTEXT "HASSETUSERCONTEXT", #endif #if HASSETVBUF "HASSETVBUF", #endif #if HAS_ST_GEN "HAS_ST_GEN", #endif #if HASSRANDOMDEV "HASSRANDOMDEV", #endif #if HASURANDOMDEV "HASURANDOMDEV", #endif #if HASSTRERROR "HASSTRERROR", #endif #if HASULIMIT "HASULIMIT", #endif #if HASUNAME "HASUNAME", #endif #if HASUNSETENV "HASUNSETENV", #endif #if HASWAITPID "HASWAITPID", #endif #if HAVE_NANOSLEEP "HAVE_NANOSLEEP", #endif #if IDENTPROTO "IDENTPROTO", #endif #if IP_SRCROUTE "IP_SRCROUTE", #endif #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL "LOCK_ON_OPEN", #endif #if MILTER_NO_NAGLE "MILTER_NO_NAGLE ", #endif #if NEEDFSYNC "NEEDFSYNC", #endif #if NEEDLINK "NEEDLINK", #endif #if NEEDLOCAL_HOSTNAME_LENGTH "NEEDLOCAL_HOSTNAME_LENGTH", #endif #if NEEDSGETIPNODE "NEEDSGETIPNODE", #endif #if NEEDSTRSTR "NEEDSTRSTR", #endif #if NEEDSTRTOL "NEEDSTRTOL", #endif #ifdef NO_GETSERVBYNAME "NO_GETSERVBYNAME", #endif #if NOFTRUNCATE "NOFTRUNCATE", #endif #if REQUIRES_DIR_FSYNC "REQUIRES_DIR_FSYNC", #endif #if RLIMIT_NEEDS_SYS_TIME_H "RLIMIT_NEEDS_SYS_TIME_H", #endif #if SAFENFSPATHCONF "SAFENFSPATHCONF", #endif #if SECUREWARE "SECUREWARE", #endif #if SFS_TYPE == SFS_4ARGS "SFS_4ARGS", #elif SFS_TYPE == SFS_MOUNT "SFS_MOUNT", #elif SFS_TYPE == SFS_NONE "SFS_NONE", #elif SFS_TYPE == SFS_NT "SFS_NT", #elif SFS_TYPE == SFS_STATFS "SFS_STATFS", #elif SFS_TYPE == SFS_STATVFS "SFS_STATVFS", #elif SFS_TYPE == SFS_USTAT "SFS_USTAT", #elif SFS_TYPE == SFS_VFS "SFS_VFS", #endif #if SHARE_V1 "SHARE_V1", #endif #if SIOCGIFCONF_IS_BROKEN "SIOCGIFCONF_IS_BROKEN", #endif #if SIOCGIFNUM_IS_BROKEN "SIOCGIFNUM_IS_BROKEN", #endif #if SNPRINTF_IS_BROKEN "SNPRINTF_IS_BROKEN", #endif #if SO_REUSEADDR_IS_BROKEN "SO_REUSEADDR_IS_BROKEN", #endif #if SYS5SETPGRP "SYS5SETPGRP", #endif #if SYSTEM5 "SYSTEM5", #endif #if USE_DOUBLE_FORK "USE_DOUBLE_FORK", #endif #if USE_ENVIRON "USE_ENVIRON", #endif #if USE_SA_SIGACTION "USE_SA_SIGACTION", #endif #if USE_SIGLONGJMP "USE_SIGLONGJMP", #endif #if USEGETCONFATTR "USEGETCONFATTR", #endif #if USESETEUID "USESETEUID", #endif #ifdef USESYSCTL "USESYSCTL", #endif #if USE_OPENSSL_ENGINE "USE_OPENSSL_ENGINE", #endif #if USING_NETSCAPE_LDAP "USING_NETSCAPE_LDAP", #endif #ifdef WAITUNION "WAITUNION", #endif NULL }; /* ** FFR compile options. */ char *FFRCompileOptions[] = { #if _FFR_ADD_BCC "_FFR_ADD_BCC", #endif #if _FFR_ADDR_TYPE_MODES /* more info in {addr_type}, requires m4 changes! */ "_FFR_ADDR_TYPE_MODES", #endif #if _FFR_ALIAS_DETAIL /* try to handle +detail for aliases */ "_FFR_ALIAS_DETAIL", #endif #if _FFR_ALLOW_SASLINFO /* DefaultAuthInfo can be specified by user. */ /* DefaultAuthInfo doesn't really work in 8.13 anymore. */ "_FFR_ALLOW_SASLINFO", #endif #if _FFR_BADRCPT_SHUTDOWN /* shut down connection (421) if there are too many bad RCPTs */ "_FFR_BADRCPT_SHUTDOWN", #endif #if _FFR_BESTMX_BETTER_TRUNCATION /* Better truncation of list of MX records for dns map. */ "_FFR_BESTMX_BETTER_TRUNCATION", #endif #if _FFR_BOUNCE_QUEUE /* Separate, unprocessed queue for DSNs */ /* John Gardiner Myers of Proofpoint */ "_FFR_BOUNCE_QUEUE", #endif #if _FFR_CATCH_BROKEN_MTAS /* Deal with MTAs that send a reply during the DATA phase. */ "_FFR_CATCH_BROKEN_MTAS", #endif #if _FFR_CHK_QUEUE /* Stricter checks about queue directory permissions. */ "_FFR_CHK_QUEUE", #endif #if _FFR_CLIENT_SIZE /* Don't try to send mail if its size exceeds SIZE= of server. */ "_FFR_CLIENT_SIZE", #endif #if _FFR_CRLPATH /* CRLPath; needs documentation; Al Smith */ "_FFR_CRLPATH", #endif #if _FFR_DM_ONE /* deliver first TA in background, then queue */ "_FFR_DM_ONE", #endif #if _FFR_DIGUNIX_SAFECHOWN /* Properly set SAFECHOWN (include/sm/conf.h) for Digital UNIX */ /* Problem noted by Anne Bennett of Concordia University */ "_FFR_DIGUNIX_SAFECHOWN", #endif #if _FFR_DNSMAP_ALIASABLE /* Allow dns map type to be used for aliases. */ /* Don Lewis of TDK */ "_FFR_DNSMAP_ALIASABLE", #endif #if _FFR_DONTLOCKFILESFORREAD_OPTION /* Enable DontLockFilesForRead option. */ "_FFR_DONTLOCKFILESFORREAD_OPTION", #endif #if _FFR_DOTTED_USERNAMES /* Allow usernames with '.' */ "_FFR_DOTTED_USERNAMES", #endif #if _FFR_DPO_CS /* ** Make DaemonPortOptions case sensitive. ** For some unknown reasons the code converted every option ** to uppercase (first letter only, as that's the only one that ** is actually checked). This prevented all new lower case options ** from working... ** The documentation doesn't say anything about case (in)sensitivity, ** which means it should be case sensitive by default, ** but it's not a good idea to change this within a patch release, ** so let's delay this to 8.15. */ "_FFR_DPO_CS", #endif #if _FFR_DPRINTF_MAP /* dprintf map for logging */ "_FFR_DPRINTF_MAP", #endif #if _FFR_DROP_TRUSTUSER_WARNING /* ** Don't issue this warning: ** "readcf: option TrustedUser may cause problems on systems ** which do not support fchown() if UseMSP is not set. */ "_FFR_DROP_TRUSTUSER_WARNING", #endif #if _FFR_EIGHT_BIT_ADDR_OK /* EightBitAddrOK: allow 8-bit e-mail addresses */ "_FFR_EIGHT_BIT_ADDR_OK", #endif #if _FFR_EXTRA_MAP_CHECK /* perform extra checks on $( $) in R lines */ "_FFR_EXTRA_MAP_CHECK", #endif #if _FFR_GETHBN_ExFILE /* ** According to Motonori Nakamura some gethostbyname() ** implementations (TurboLinux?) may (temporarily) fail ** due to a lack of file descriptors. Enabling this FFR ** will check errno for EMFILE and ENFILE and in case of a match ** cause a temporary error instead of a permanent error. ** The right solution is of course to file a bug against those ** systems such that they actually set h_errno = TRY_AGAIN. */ "_FFR_GETHBN_ExFILE", #endif #if _FFR_FIPSMODE /* FIPSMode (if supported by OpenSSL library) */ "_FFR_FIPSMODE", #endif #if _FFR_FIX_DASHT /* ** If using -t, force not sending to argv recipients, even ** if they are mentioned in the headers. */ "_FFR_FIX_DASHT", #endif #if _FFR_FORWARD_SYSERR /* Cause a "syserr" if forward file isn't "safe". */ "_FFR_FORWARD_SYSERR", #endif #if _FFR_GEN_ORCPT /* Generate a ORCPT DSN arg if not already provided */ "_FFR_GEN_ORCPT", #endif #if _FFR_HANDLE_ISO8859_GECOS /* ** Allow ISO 8859 characters in GECOS field: replace them ** with ASCII "equivalent". */ /* Peter Eriksson of Linkopings universitet */ "_FFR_HANDLE_ISO8859_GECOS", #endif #if _FFR_HANDLE_HDR_RW_TEMPFAIL /* ** Temporary header rewriting problems from remotename() etc ** are not "sticky" for mci (e.g., during queue runs). */ "_FFR_HANDLE_HDR_RW_TEMPFAIL", #endif #if _FFR_HPUX_NSSWITCH /* Use nsswitch on HP-UX */ "_FFR_HPUX_NSSWITCH", #endif #if _FFR_IGNORE_BOGUS_ADDR /* Ignore addresses for which prescan() failed */ "_FFR_IGNORE_BOGUS_ADDR", #endif #if _FFR_IGNORE_EXT_ON_HELO /* Ignore extensions offered in response to HELO */ "_FFR_IGNORE_EXT_ON_HELO", #endif #if _FFR_LINUX_MHNL /* Set MAXHOSTNAMELEN to 256 (Linux) */ "_FFR_LINUX_MHNL", #endif #if _FFR_LOCAL_DAEMON /* Local daemon mode (-bl) which only accepts loopback connections */ "_FFR_LOCAL_DAEMON", #endif #if _FFR_LOG_MORE1 /* log some TLS/AUTH info in from= too */ "_FFR_LOG_MORE1", #endif #if _FFR_LOG_MORE2 /* log some TLS info in to= too */ "_FFR_LOG_MORE2", #endif #if _FFR_LOGREPLY "_FFR_LOGREPLY", #endif #if _FFR_MAIL_MACRO "_FFR_MAIL_MACRO", #endif #if _FFR_MAXDATASIZE /* ** It is possible that a header is larger than MILTER_CHUNK_SIZE, ** hence this shouldn't be used as limit for milter communication. ** see also libmilter/comm.c ** Gurusamy Sarathy of ActiveState */ "_FFR_MAXDATASIZE", #endif #if _FFR_MAX_FORWARD_ENTRIES /* Try to limit number of .forward entries */ /* (doesn't work) */ /* Randall S. Winchester of the University of Maryland */ "_FFR_MAX_FORWARD_ENTRIES", #endif #if _FFR_MAX_SLEEP_TIME /* Limit sleep(2) time in libsm/clock.c */ "_FFR_MAX_SLEEP_TIME", #endif #if _FFR_MDS_NEGOTIATE /* MaxDataSize negotation with libmilter */ "_FFR_MDS_NEGOTIATE", #endif #if _FFR_MEMSTAT /* Check free memory */ "_FFR_MEMSTAT", #endif #if _FFR_MILTER_CHECK "_FFR_MILTER_CHECK", #endif #if _FFR_MILTER_CONNECT_REPLYCODE /* milter: propagate replycode returned by connect commands */ /* John Gardiner Myers of Proofpoint */ "_FFR_MILTER_CONNECT_REPLYCODE ", #endif #if _FFR_MILTER_CONVERT_ALL_LF_TO_CRLF /* ** milter_body() uses the same conversion algorithm as putbody() ** to translate the "local" df format (\n) to SMTP format (\r\n). ** However, putbody() and mime8to7() use different conversion ** algorithms. ** If the input date does not follow the SMTP standard ** (e.g., if it has "naked \r"s), then the output from putbody() ** and mime8to7() will most likely be different. ** By turning on this FFR milter_body() will try to "imitate" ** mime8to7(). ** Note: there is no (simple) way to deal with both conversions ** in a consistent manner. Moreover, as the "GiGo" principle applies, ** it's not really worth to fix it. */ "_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF", #endif #if _FFR_MILTER_CHECK_REJECTIONS_TOO /* ** Also send RCPTs that are rejected by check_rcpt to a milter ** (if requested during option negotiation). */ "_FFR_MILTER_CHECK_REJECTIONS_TOO", #endif #if _FFR_MILTER_ENHSC /* extract enhanced status code from milter replies for dsn= logging */ "_FFR_MILTER_ENHSC", #endif #if _FFR_MIME7TO8_OLD /* Old mime7to8 code, the new is broken for at least one example. */ "_FFR_MIME7TO8_OLD", #endif #if _FFR_MORE_MACROS /* allow more long macro names ("unprintable" characters). */ "_FFR_MORE_MACROS", #endif #if _FFR_MSG_ACCEPT /* allow to override "Message accepted for delivery" */ "_FFR_MSG_ACCEPT", #endif #if _FFR_NODELAYDSN_ON_HOLD /* Do not issue a DELAY DSN for mailers that use the hold flag. */ /* Steven Pitzl */ "_FFR_NODELAYDSN_ON_HOLD", #endif #if _FFR_NO_PIPE /* Disable PIPELINING, delay client if used. */ "_FFR_NO_PIPE", #endif #if _FFR_LDAP_NETWORK_TIMEOUT /* set LDAP_OPT_NETWORK_TIMEOUT if available (-c) */ "_FFR_LDAP_NETWORK_TIMEOUT", #endif #if _FFR_LOG_NTRIES /* log ntries=, from Nik Clayton of FreeBSD */ "_FFR_LOG_NTRIES", #endif #if _FFR_PROXY /* "proxy" (synchronous) delivery mode */ "_FFR_PROXY", #endif #if _FFR_QF_PARANOIA "_FFR_QF_PARANOIA", #endif #if _FFR_QUEUE_GROUP_SORTORDER /* Allow QueueSortOrder per queue group. */ /* XXX: Still need to actually use qgrp->qg_sortorder */ "_FFR_QUEUE_GROUP_SORTORDER", #endif #if _FFR_QUEUE_MACRO /* Define {queue} macro. */ "_FFR_QUEUE_MACRO", #endif #if _FFR_QUEUE_RUN_PARANOIA /* Additional checks when doing queue runs; interval of checks */ "_FFR_QUEUE_RUN_PARANOIA", #endif #if _FFR_QUEUE_SCHED_DBG /* Debug output for the queue scheduler. */ "_FFR_QUEUE_SCHED_DBG", #endif #if _FFR_RCPTFLAGS "_FFR_RCPTFLAGS", #endif #if _FFR_RCPTTHROTDELAY /* configurable delay for BadRcptThrottle */ "_FFR_RCPTTHROTDELAY", #endif #if _FFR_REDIRECTEMPTY /* ** envelope <> can't be sent to mailing lists, only owner- ** send spam of this type to owner- of the list ** ---- to stop spam from going to mailing lists. */ "_FFR_REDIRECTEMPTY", #endif #if _FFR_REJECT_NUL_BYTE /* reject NUL bytes in body */ "_FFR_REJECT_NUL_BYTE", #endif #if _FFR_RESET_MACRO_GLOBALS /* Allow macro 'j' to be set dynamically via rulesets. */ "_FFR_RESET_MACRO_GLOBALS", #endif #if _FFR_RHS /* Random shuffle for queue sorting. */ "_FFR_RHS", #endif #if _FFR_RUNPQG /* ** allow -qGqueue_group -qp to work, i.e., ** restrict a persistent queue runner to a queue group. */ "_FFR_RUNPQG", #endif #if _FFR_SESSID /* session id (for logging) */ "_FFR_SESSID", #endif #if _FFR_SHM_STATUS /* Donated code (unused). */ "_FFR_SHM_STATUS", #endif #if _FFR_LDAP_SINGLEDN /* ** The LDAP database map code in Sendmail 8.12.10, when ** given the -1 switch, would match only a single DN, ** but was able to return multiple attributes for that ** DN. In Sendmail 8.13 this "bug" was corrected to ** only return if exactly one attribute matched. ** ** Unfortunately, our configuration uses the former ** behaviour. Attached is a relatively simple patch ** to 8.13.4 which adds a -2 switch (for lack of a ** better option) which returns the single dn/multiple ** attributes. ** ** Jeffrey T. Eaton, Carnegie-Mellon University */ "_FFR_LDAP_SINGLEDN", #endif #if _FFR_SKIP_DOMAINS /* process every N'th domain instead of every N'th message */ "_FFR_SKIP_DOMAINS", #endif #if _FFR_SLEEP_USE_SELECT /* Use select(2) in libsm/clock.c to emulate sleep(2) */ "_FFR_SLEEP_USE_SELECT ", #endif #if _FFR_SPT_ALIGN /* ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to 64 ** bit alignment, so unless each piece of argv and envp is a multiple ** of 8 bytes (including terminating NULL), initsetproctitle() won't ** use any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE ** if you use this FFR. */ /* Chris Adams of HiWAAY Informations Services */ "_FFR_SPT_ALIGN", #endif #if _FFR_SS_PER_DAEMON /* SuperSafe per DaemonPortOptions: 'T' (better letter?) */ "_FFR_SS_PER_DAEMON", #endif #if _FFR_TESTS /* enable some test code */ "_FFR_TESTS", #endif #if _FFR_TIMERS /* Donated code (unused). */ "_FFR_TIMERS", #endif #if _FFR_TLS_EC "_FFR_TLS_EC", #endif #if _FFR_TLS_USE_CERTIFICATE_CHAIN_FILE /* ** Use SSL_CTX_use_certificate_chain_file() ** instead of SSL_CTX_use_certificate_file() */ "_FFR_TLS_USE_CERTIFICATE_CHAIN_FILE", #endif #if _FFR_TLS_SE_OPTS /* TLS session options */ "_FFR_TLS_SE_OPTS", #endif #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. */ "_FFR_TRUSTED_QF", #endif #if _FFR_USE_GETPWNAM_ERRNO /* ** See libsm/mbdb.c: only enable this on OSs ** that implement the correct (POSIX) semantics. ** This will need to become an OS-specific #if enabled ** in one of the headers files under include/sm/os/ . */ "_FFR_USE_GETPWNAM_ERRNO", #endif #if _FFR_USE_SEM_LOCKING "_FFR_USE_SEM_LOCKING", #endif #if _FFR_USE_SETLOGIN /* Use setlogin() */ /* Peter Philipp */ "_FFR_USE_SETLOGIN", #endif #if _FFR_XCNCT "_FFR_XCNCT", #endif NULL }; Index: vendor/sendmail/dist/src/readcf.c =================================================================== --- vendor/sendmail/dist/src/readcf.c (revision 351552) +++ vendor/sendmail/dist/src/readcf.c (revision 351553) @@ -1,5286 +1,5270 @@ /* * Copyright (c) 1998-2006, 2008-2010, 2013 Proofpoint, 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. * */ #include #include SM_RCSID("@(#)$Id: readcf.c,v 8.692 2013-11-22 20:51:56 ca Exp $") #if NETINET || NETINET6 # include #endif /* NETINET || NETINET6 */ #define SECONDS #define MINUTES * 60 #define HOUR * 3600 #define HOURS HOUR static void fileclass __P((int, char *, char *, bool, bool, bool)); static char **makeargv __P((char *)); static void settimeout __P((char *, char *, bool)); static void toomany __P((int, int)); static char *extrquotstr __P((char *, char **, char *, bool *)); static void parse_class_words __P((int, char *)); #if _FFR_BOUNCE_QUEUE static char *bouncequeue = NULL; static void initbouncequeue __P((void)); /* ** INITBOUNCEQUEUE -- determine BounceQueue if option is set. ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** sets BounceQueue */ static void initbouncequeue() { STAB *s; BounceQueue = NOQGRP; if (bouncequeue == NULL || bouncequeue[0] == '\0') return; s = stab(bouncequeue, ST_QUEUE, ST_FIND); if (s == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: option BounceQueue: unknown queue group %s\n", bouncequeue); } else BounceQueue = s->s_quegrp->qg_index; } #endif /* _FFR_BOUNCE_QUEUE */ #if _FFR_RCPTFLAGS void setupdynmailers __P((void)); #else #define setupdynmailers() #endif /* ** READCF -- read configuration file. ** ** This routine reads the configuration file and builds the internal ** form. ** ** The file is formatted as a sequence of lines, each taken ** atomically. The first character of each line describes how ** the line is to be interpreted. The lines are: ** Dxval Define macro x to have value val. ** Cxword Put word into class x. ** Fxfile [fmt] Read file for lines to put into ** class x. Use scanf string 'fmt' ** or "%s" if not present. Fmt should ** only produce one string-valued result. ** Hname: value Define header with field-name 'name' ** and value as specified; this will be ** macro expanded immediately before ** use. ** Sn Use rewriting set n. ** Rlhs rhs Rewrite addresses that match lhs to ** be rhs. ** Mn arg=val... Define mailer. n is the internal name. ** Args specify mailer parameters. ** Oxvalue Set option x to value. ** O option value Set option (long name) to value. ** Pname=value Set precedence name to value. ** Qn arg=val... Define queue groups. n is the internal name. ** Args specify queue parameters. ** Vversioncode[/vendorcode] ** Version level/vendor name of ** configuration syntax. ** Kmapname mapclass arguments.... ** Define keyed lookup of a given class. ** Arguments are class dependent. ** Eenvar=value Set the environment value to the given value. ** ** Parameters: ** cfname -- configuration file name. ** safe -- true if this is the system config file; ** false otherwise. ** e -- the main envelope. ** ** Returns: ** none. ** ** Side Effects: ** Builds several internal tables. */ void readcf(cfname, safe, e) char *cfname; bool safe; register ENVELOPE *e; { SM_FILE_T *cf; int ruleset = -1; char *q; struct rewrite *rwp = NULL; char *bp; auto char *ep; int nfuzzy; char *file; bool optional; bool ok; bool ismap; int mid; register char *p; long sff = SFF_OPENASROOT; struct stat statb; char buf[MAXLINE]; int bufsize; char exbuf[MAXLINE]; char pvpbuf[MAXLINE + MAXATOM]; static char *null_list[1] = { NULL }; extern unsigned char TokTypeNoC[]; FileName = cfname; LineNumber = 0; -#if STARTTLS - Srv_SSL_Options = SSL_OP_ALL; - Clt_SSL_Options = SSL_OP_ALL -# ifdef SSL_OP_NO_SSLv2 - | SSL_OP_NO_SSLv2 -# endif -# ifdef SSL_OP_NO_TICKET - | SSL_OP_NO_TICKET -# endif - ; -# ifdef SSL_OP_TLSEXT_PADDING - /* SSL_OP_TLSEXT_PADDING breaks compatibility with some sites */ - Srv_SSL_Options &= ~SSL_OP_TLSEXT_PADDING; - Clt_SSL_Options &= ~SSL_OP_TLSEXT_PADDING; -# endif /* SSL_OP_TLSEXT_PADDING */ -#endif /* STARTTLS */ if (DontLockReadFiles) sff |= SFF_NOLOCK; cf = safefopen(cfname, O_RDONLY, 0444, sff); if (cf == NULL) { syserr("cannot open"); finis(false, true, EX_OSFILE); } if (fstat(sm_io_getinfo(cf, SM_IO_WHAT_FD, NULL), &statb) < 0) { syserr("cannot fstat"); finis(false, true, EX_OSFILE); } if (!S_ISREG(statb.st_mode)) { syserr("not a plain file"); finis(false, true, EX_OSFILE); } if (OpMode != MD_TEST && bitset(S_IWGRP|S_IWOTH, statb.st_mode)) { if (OpMode == MD_DAEMON || OpMode == MD_INITALIAS || OpMode == MD_CHECKCONFIG) (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s: WARNING: dangerous write permissions\n", FileName); if (LogLevel > 0) sm_syslog(LOG_CRIT, NOQID, "%s: WARNING: dangerous write permissions", FileName); } #if XLA xla_zero(); #endif /* XLA */ while (bufsize = sizeof(buf), (bp = fgetfolded(buf, &bufsize, cf)) != NULL) { char *nbp; if (bp[0] == '#') { if (bp != buf) sm_free(bp); /* XXX */ continue; } /* do macro expansion mappings */ nbp = translate_dollars(bp, bp, &bufsize); if (nbp != bp && bp != buf) sm_free(bp); bp = nbp; /* interpret this line */ errno = 0; switch (bp[0]) { case '\0': case '#': /* comment */ break; case 'R': /* rewriting rule */ if (ruleset < 0) { syserr("missing valid ruleset for \"%s\"", bp); break; } for (p = &bp[1]; *p != '\0' && *p != '\t'; p++) continue; if (*p == '\0') { syserr("invalid rewrite line \"%s\" (tab expected)", bp); break; } /* allocate space for the rule header */ if (rwp == NULL) { RewriteRules[ruleset] = rwp = (struct rewrite *) xalloc(sizeof(*rwp)); } else { rwp->r_next = (struct rewrite *) xalloc(sizeof(*rwp)); rwp = rwp->r_next; } rwp->r_next = NULL; /* expand and save the LHS */ *p = '\0'; expand(&bp[1], exbuf, sizeof(exbuf), e); rwp->r_lhs = prescan(exbuf, '\t', pvpbuf, sizeof(pvpbuf), NULL, ConfigLevel >= 9 ? TokTypeNoC : IntTokenTab, true); nfuzzy = 0; if (rwp->r_lhs != NULL) { register char **ap; rwp->r_lhs = copyplist(rwp->r_lhs, true, NULL); /* count the number of fuzzy matches in LHS */ for (ap = rwp->r_lhs; *ap != NULL; ap++) { char *botch; botch = NULL; switch (ap[0][0] & 0377) { case MATCHZANY: case MATCHANY: case MATCHONE: case MATCHCLASS: case MATCHNCLASS: nfuzzy++; break; case MATCHREPL: botch = "$1-$9"; break; case CANONUSER: botch = "$:"; break; case CALLSUBR: botch = "$>"; break; case CONDIF: botch = "$?"; break; case CONDFI: botch = "$."; break; case HOSTBEGIN: botch = "$["; break; case HOSTEND: botch = "$]"; break; case LOOKUPBEGIN: botch = "$("; break; case LOOKUPEND: botch = "$)"; break; } if (botch != NULL) syserr("Inappropriate use of %s on LHS", botch); } rwp->r_line = LineNumber; } else { syserr("R line: null LHS"); rwp->r_lhs = null_list; } if (nfuzzy > MAXMATCH) { syserr("R line: too many wildcards"); rwp->r_lhs = null_list; } /* expand and save the RHS */ while (*++p == '\t') continue; q = p; while (*p != '\0' && *p != '\t') p++; *p = '\0'; expand(q, exbuf, sizeof(exbuf), e); rwp->r_rhs = prescan(exbuf, '\t', pvpbuf, sizeof(pvpbuf), NULL, ConfigLevel >= 9 ? TokTypeNoC : IntTokenTab, true); if (rwp->r_rhs != NULL) { register char **ap; int args, endtoken; #if _FFR_EXTRA_MAP_CHECK int nexttoken; #endif /* _FFR_EXTRA_MAP_CHECK */ bool inmap; rwp->r_rhs = copyplist(rwp->r_rhs, true, NULL); /* check no out-of-bounds replacements */ nfuzzy += '0'; inmap = false; args = 0; endtoken = 0; for (ap = rwp->r_rhs; *ap != NULL; ap++) { char *botch; botch = NULL; switch (ap[0][0] & 0377) { case MATCHREPL: if (ap[0][1] <= '0' || ap[0][1] > nfuzzy) { syserr("replacement $%c out of bounds", ap[0][1]); } break; case MATCHZANY: botch = "$*"; break; case MATCHANY: botch = "$+"; break; case MATCHONE: botch = "$-"; break; case MATCHCLASS: botch = "$="; break; case MATCHNCLASS: botch = "$~"; break; case CANONHOST: if (!inmap) break; if (++args >= MAX_MAP_ARGS) syserr("too many arguments for map lookup"); break; case HOSTBEGIN: endtoken = HOSTEND; /* FALLTHROUGH */ case LOOKUPBEGIN: /* see above... */ if ((ap[0][0] & 0377) == LOOKUPBEGIN) endtoken = LOOKUPEND; if (inmap) syserr("cannot nest map lookups"); inmap = true; args = 0; #if _FFR_EXTRA_MAP_CHECK if (ap[1] == NULL) { syserr("syntax error in map lookup"); break; } nexttoken = ap[1][0] & 0377; if (nexttoken == CANONHOST || nexttoken == CANONUSER || nexttoken == endtoken)) { syserr("missing map name for lookup"); break; } if (ap[2] == NULL) { syserr("syntax error in map lookup"); break; } if (ap[0][0] == HOSTBEGIN) break; nexttoken = ap[2][0] & 0377; if (nexttoken == CANONHOST || nexttoken == CANONUSER || nexttoken == endtoken) { syserr("missing key name for lookup"); break; } #endif /* _FFR_EXTRA_MAP_CHECK */ break; case HOSTEND: case LOOKUPEND: if ((ap[0][0] & 0377) != endtoken) break; inmap = false; endtoken = 0; break; #if 0 /* ** This doesn't work yet as there are maps defined *after* the cf ** is read such as host, user, and alias. So for now, it's removed. ** When it comes back, the RELEASE_NOTES entry will be: ** Emit warnings for unknown maps when reading the .cf file. Based on ** patch from Robert Harker of Harker Systems. */ case LOOKUPBEGIN: /* ** Got a database lookup, ** check if map is defined. */ ep = ap[1]; if ((ep[0] & 0377) != MACRODEXPAND && stab(ep, ST_MAP, ST_FIND) == NULL) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: %s: line %d: map %s not found\n", FileName, LineNumber, ep); } break; #endif /* 0 */ } if (botch != NULL) syserr("Inappropriate use of %s on RHS", botch); } if (inmap) syserr("missing map closing token"); } else { syserr("R line: null RHS"); rwp->r_rhs = null_list; } break; case 'S': /* select rewriting set */ expand(&bp[1], exbuf, sizeof(exbuf), e); ruleset = strtorwset(exbuf, NULL, ST_ENTER); if (ruleset < 0) break; rwp = RewriteRules[ruleset]; if (rwp != NULL) { if (OpMode == MD_TEST || OpMode == MD_CHECKCONFIG) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: Ruleset %s has multiple definitions\n", &bp[1]); if (tTd(37, 1)) sm_dprintf("WARNING: Ruleset %s has multiple definitions\n", &bp[1]); while (rwp->r_next != NULL) rwp = rwp->r_next; } break; case 'D': /* macro definition */ mid = macid_parse(&bp[1], &ep); if (mid == 0) break; p = munchstring(ep, NULL, '\0'); macdefine(&e->e_macro, A_TEMP, mid, p); break; case 'H': /* required header line */ (void) chompheader(&bp[1], CHHDR_DEF, NULL, e); break; case 'C': /* word class */ case 'T': /* trusted user (set class `t') */ if (bp[0] == 'C') { mid = macid_parse(&bp[1], &ep); if (mid == 0) break; expand(ep, exbuf, sizeof(exbuf), e); p = exbuf; } else { mid = 't'; p = &bp[1]; } while (*p != '\0') { register char *wd; char delim; while (*p != '\0' && isascii(*p) && isspace(*p)) p++; wd = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; delim = *p; *p = '\0'; if (wd[0] != '\0') setclass(mid, wd); *p = delim; } break; case 'F': /* word class from file */ mid = macid_parse(&bp[1], &ep); if (mid == 0) break; for (p = ep; isascii(*p) && isspace(*p); ) p++; if (p[0] == '-' && p[1] == 'o') { optional = true; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; while (isascii(*p) && isspace(*p)) p++; } else optional = false; /* check if [key]@map:spec */ ismap = false; if (!SM_IS_DIR_DELIM(*p) && *p != '|' && (q = strchr(p, '@')) != NULL) { q++; /* look for @LDAP or @map: in string */ if (strcmp(q, "LDAP") == 0 || (*q != ':' && strchr(q, ':') != NULL)) ismap = true; } if (ismap) { /* use entire spec */ file = p; } else { file = extrquotstr(p, &q, " ", &ok); if (!ok) { syserr("illegal filename '%s'", p); break; } } if (*file == '|' || ismap) p = "%s"; else { p = q; if (*p == '\0') p = "%s"; else { *p = '\0'; while (isascii(*++p) && isspace(*p)) continue; } } fileclass(mid, file, p, ismap, safe, optional); break; #if XLA case 'L': /* extended load average description */ xla_init(&bp[1]); break; #endif /* XLA */ #if defined(SUN_EXTENSIONS) && defined(SUN_LOOKUP_MACRO) case 'L': /* lookup macro */ case 'G': /* lookup class */ /* reserved for Sun -- NIS+ database lookup */ if (VendorCode != VENDOR_SUN) goto badline; sun_lg_config_line(bp, e); break; #endif /* defined(SUN_EXTENSIONS) && defined(SUN_LOOKUP_MACRO) */ case 'M': /* define mailer */ makemailer(&bp[1]); break; case 'O': /* set option */ setoption(bp[1], &bp[2], safe, false, e); break; case 'P': /* set precedence */ if (NumPriorities >= MAXPRIORITIES) { toomany('P', MAXPRIORITIES); break; } for (p = &bp[1]; *p != '\0' && *p != '='; p++) continue; if (*p == '\0') goto badline; *p = '\0'; Priorities[NumPriorities].pri_name = newstr(&bp[1]); Priorities[NumPriorities].pri_val = atoi(++p); NumPriorities++; break; case 'Q': /* define queue */ makequeue(&bp[1], true); break; case 'V': /* configuration syntax version */ for (p = &bp[1]; isascii(*p) && isspace(*p); p++) continue; if (!isascii(*p) || !isdigit(*p)) { syserr("invalid argument to V line: \"%.20s\"", &bp[1]); break; } ConfigLevel = strtol(p, &ep, 10); /* ** Do heuristic tweaking for back compatibility. */ if (ConfigLevel >= 5) { /* level 5 configs have short name in $w */ p = macvalue('w', e); if (p != NULL && (p = strchr(p, '.')) != NULL) { *p = '\0'; macdefine(&e->e_macro, A_TEMP, 'w', macvalue('w', e)); } } if (ConfigLevel >= 6) { ColonOkInAddr = false; } /* ** Look for vendor code. */ if (*ep++ == '/') { /* extract vendor code */ for (p = ep; isascii(*p) && isalpha(*p); ) p++; *p = '\0'; if (!setvendor(ep)) syserr("invalid V line vendor code: \"%s\"", ep); } break; case 'K': expand(&bp[1], exbuf, sizeof(exbuf), e); (void) makemapentry(exbuf); break; case 'E': p = strchr(bp, '='); if (p != NULL) *p++ = '\0'; sm_setuserenv(&bp[1], p); break; case 'X': /* mail filter */ #if MILTER milter_setup(&bp[1]); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Filter usage ('X') requires Milter support (-DMILTER)\n"); #endif /* MILTER */ break; default: badline: syserr("unknown configuration line \"%s\"", bp); } if (bp != buf) sm_free(bp); /* XXX */ } if (sm_io_error(cf)) { syserr("I/O read error"); finis(false, true, EX_OSFILE); } (void) sm_io_close(cf, SM_TIME_DEFAULT); FileName = NULL; #if _FFR_BOUNCE_QUEUE initbouncequeue(); #endif /* initialize host maps from local service tables */ inithostmaps(); /* initialize daemon (if not defined yet) */ initdaemon(); /* determine if we need to do special name-server frotz */ { int nmaps; char *maptype[MAXMAPSTACK]; short mapreturn[MAXMAPACTIONS]; nmaps = switch_map_find("hosts", maptype, mapreturn); UseNameServer = false; if (nmaps > 0 && nmaps <= MAXMAPSTACK) { register int mapno; for (mapno = 0; mapno < nmaps && !UseNameServer; mapno++) { if (strcmp(maptype[mapno], "dns") == 0) UseNameServer = true; } } } setupdynmailers(); } /* ** TRANSLATE_DOLLARS -- convert $x into internal form ** ** Actually does all appropriate pre-processing of a config line ** to turn it into internal form. ** ** Parameters: ** ibp -- the buffer to translate. ** obp -- where to put the translation; may be the same as obp ** bsp -- a pointer to the size of obp; will be updated if ** the buffer needs to be replaced. ** ** Returns: ** The buffer pointer; may differ from obp if the expansion ** is larger then *bsp, in which case this will point to ** malloc()ed memory which must be free()d by the caller. */ char * translate_dollars(ibp, obp, bsp) char *ibp; char *obp; int *bsp; { register char *p; auto char *ep; char *bp; if (tTd(37, 53)) { sm_dprintf("translate_dollars("); xputs(sm_debug_file(), ibp); sm_dprintf(")\n"); } bp = quote_internal_chars(ibp, obp, bsp); for (p = bp; *p != '\0'; p++) { if (*p == '#' && p > bp && ConfigLevel >= 3) { register char *e; switch (*--p & 0377) { case MACROEXPAND: /* it's from $# -- let it go through */ p++; break; case '\\': /* it's backslash escaped */ (void) sm_strlcpy(p, p + 1, strlen(p)); break; default: /* delete leading white space */ while (isascii(*p) && isspace(*p) && *p != '\n' && p > bp) { p--; } if ((e = strchr(++p, '\n')) != NULL) (void) sm_strlcpy(p, e, strlen(p)); else *p-- = '\0'; break; } continue; } if (*p != '$' || p[1] == '\0') continue; if (p[1] == '$') { /* actual dollar sign.... */ (void) sm_strlcpy(p, p + 1, strlen(p)); continue; } /* convert to macro expansion character */ *p++ = MACROEXPAND; /* special handling for $=, $~, $&, and $? */ if (*p == '=' || *p == '~' || *p == '&' || *p == '?') p++; /* convert macro name to code */ *p = macid_parse(p, &ep); if (ep != p + 1) (void) sm_strlcpy(p + 1, ep, strlen(p + 1)); } /* strip trailing white space from the line */ while (--p > bp && isascii(*p) && isspace(*p)) *p = '\0'; if (tTd(37, 53)) { sm_dprintf(" translate_dollars => "); xputs(sm_debug_file(), bp); sm_dprintf("\n"); } return bp; } /* ** TOOMANY -- signal too many of some option ** ** Parameters: ** id -- the id of the error line ** maxcnt -- the maximum possible values ** ** Returns: ** none. ** ** Side Effects: ** gives a syserr. */ static void toomany(id, maxcnt) int id; int maxcnt; { syserr("too many %c lines, %d max", id, maxcnt); } /* ** FILECLASS -- read members of a class from a file ** ** Parameters: ** class -- class to define. ** filename -- name of file to read. ** fmt -- scanf string to use for match. ** ismap -- if set, this is a map lookup. ** safe -- if set, this is a safe read. ** optional -- if set, it is not an error for the file to ** not exist. ** ** Returns: ** none ** ** Side Effects: ** puts all lines in filename that match a scanf into ** the named class. */ /* ** Break up the match into words and add to class. */ static void parse_class_words(class, line) int class; char *line; { while (line != NULL && *line != '\0') { register char *q; /* strip leading spaces */ while (isascii(*line) && isspace(*line)) line++; if (*line == '\0') break; /* find the end of the word */ q = line; while (*line != '\0' && !(isascii(*line) && isspace(*line))) line++; if (*line != '\0') *line++ = '\0'; /* enter the word in the symbol table */ setclass(class, q); } } static void fileclass(class, filename, fmt, ismap, safe, optional) int class; char *filename; char *fmt; bool ismap; bool safe; bool optional; { SM_FILE_T *f; long sff; pid_t pid; register char *p; char buf[MAXLINE]; if (tTd(37, 2)) sm_dprintf("fileclass(%s, fmt=%s)\n", filename, fmt); if (*filename == '\0') { syserr("fileclass: missing file name"); return; } else if (ismap) { int status = 0; char *key; char *mn; char *cl, *spec; STAB *mapclass; MAP map; mn = newstr(macname(class)); key = filename; /* skip past key */ if ((p = strchr(filename, '@')) == NULL) { /* should not happen */ syserr("fileclass: bogus map specification"); sm_free(mn); return; } /* skip past '@' */ *p++ = '\0'; cl = p; #if LDAPMAP if (strcmp(cl, "LDAP") == 0) { int n; char *lc; char jbuf[MAXHOSTNAMELEN]; char lcbuf[MAXLINE]; /* Get $j */ expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope); if (jbuf[0] == '\0') { (void) sm_strlcpy(jbuf, "localhost", sizeof(jbuf)); } /* impose the default schema */ lc = macvalue(macid("{sendmailMTACluster}"), CurEnv); if (lc == NULL) lc = ""; else { expand(lc, lcbuf, sizeof(lcbuf), CurEnv); lc = lcbuf; } cl = "ldap"; n = sm_snprintf(buf, sizeof(buf), "-k (&(objectClass=sendmailMTAClass)(sendmailMTAClassName=%s)(|(sendmailMTACluster=%s)(sendmailMTAHost=%s))) -v sendmailMTAClassValue,sendmailMTAClassSearch:FILTER:sendmailMTAClass,sendmailMTAClassURL:URL:sendmailMTAClass", mn, lc, jbuf); if (n >= sizeof(buf)) { syserr("fileclass: F{%s}: Default LDAP string too long", mn); sm_free(mn); return; } spec = buf; } else #endif /* LDAPMAP */ { if ((spec = strchr(cl, ':')) == NULL) { syserr("fileclass: F{%s}: missing map class", mn); sm_free(mn); return; } *spec++ ='\0'; } /* set up map structure */ mapclass = stab(cl, ST_MAPCLASS, ST_FIND); if (mapclass == NULL) { syserr("fileclass: F{%s}: class %s not available", mn, cl); sm_free(mn); return; } memset(&map, '\0', sizeof(map)); map.map_class = &mapclass->s_mapclass; map.map_mname = mn; map.map_mflags |= MF_FILECLASS; if (tTd(37, 5)) sm_dprintf("fileclass: F{%s}: map class %s, key %s, spec %s\n", mn, cl, key, spec); /* parse map spec */ if (!map.map_class->map_parse(&map, spec)) { /* map_parse() showed the error already */ sm_free(mn); return; } map.map_mflags |= MF_VALID; /* open map */ if (map.map_class->map_open(&map, O_RDONLY)) { map.map_mflags |= MF_OPEN; map.map_pid = getpid(); } else { if (!optional && !bitset(MF_OPTIONAL, map.map_mflags)) syserr("fileclass: F{%s}: map open failed", mn); sm_free(mn); return; } /* lookup */ p = (*map.map_class->map_lookup)(&map, key, NULL, &status); if (status != EX_OK && status != EX_NOTFOUND) { if (!optional) syserr("fileclass: F{%s}: map lookup failed", mn); p = NULL; } /* use the results */ if (p != NULL) parse_class_words(class, p); /* close map */ map.map_mflags |= MF_CLOSING; map.map_class->map_close(&map); map.map_mflags &= ~(MF_OPEN|MF_WRITABLE|MF_CLOSING); sm_free(mn); return; } else if (filename[0] == '|') { auto int fd; int i; char *argv[MAXPV + 1]; i = 0; for (p = strtok(&filename[1], " \t"); p != NULL && i < MAXPV; p = strtok(NULL, " \t")) argv[i++] = p; argv[i] = NULL; pid = prog_open(argv, &fd, CurEnv); if (pid < 0) f = NULL; else f = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd, SM_IO_RDONLY, NULL); } else { pid = -1; sff = SFF_REGONLY; if (!bitnset(DBS_CLASSFILEINUNSAFEDIRPATH, DontBlameSendmail)) sff |= SFF_SAFEDIRPATH; if (!bitnset(DBS_LINKEDCLASSFILEINWRITABLEDIR, DontBlameSendmail)) sff |= SFF_NOWLINK; if (safe) sff |= SFF_OPENASROOT; else if (RealUid == 0) sff |= SFF_ROOTOK; if (DontLockReadFiles) sff |= SFF_NOLOCK; f = safefopen(filename, O_RDONLY, 0, sff); } if (f == NULL) { if (!optional) syserr("fileclass: cannot open '%s'", filename); return; } while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0) { #if SCANF char wordbuf[MAXLINE + 1]; #endif /* SCANF */ if (buf[0] == '#') continue; #if SCANF if (sm_io_sscanf(buf, fmt, wordbuf) != 1) continue; p = wordbuf; #else /* SCANF */ p = buf; #endif /* SCANF */ parse_class_words(class, p); /* ** If anything else is added here, ** check if the '@' map case above ** needs the code as well. */ } (void) sm_io_close(f, SM_TIME_DEFAULT); if (pid > 0) (void) waitfor(pid); } #if _FFR_RCPTFLAGS /* first character for dynamically created mailers */ static char dynmailerp = ' '; /* list of first characters for cf defined mailers */ static char frst[MAXMAILERS + 1]; /* ** SETUPDYNMAILERS -- find a char that isn't used as first element of any ** mailer name. ** ** Parameters: ** none ** ** Returns: ** none ** ** Note: space is not valid in cf defined mailers hence the function ** will always find a char. It's not nice, but this is for ** internal names only. */ void setupdynmailers() { int i; char pp[] = "YXZ0123456789ABCDEFGHIJKLMNOPQRSTUVWyxzabcfghijkmnoqtuvw "; frst[MAXMAILERS] = '\0'; for (i = 0; i < strlen(pp); i++) { if (strchr(frst, pp[i]) == NULL) { dynmailerp = pp[i]; if (tTd(25, 8)) sm_dprintf("dynmailerp=%c\n", dynmailerp); return; } } /* NOTREACHED */ SM_ASSERT(0); } /* ** NEWMODMAILER -- Create a new mailer with modifications ** ** Parameters: ** rcpt -- current RCPT ** fl -- flag to set ** ** Returns: ** true iff successful. ** ** Note: this creates a copy of the mailer for the rcpt and ** modifies exactly one flag. It does not work ** for multiple flags! */ bool newmodmailer(rcpt, fl) ADDRESS *rcpt; int fl; { int idx; struct mailer *m; STAB *s; char mname[256]; SM_REQUIRE(rcpt != NULL); if (rcpt->q_mailer == NULL) return false; if (tTd(25, 8)) sm_dprintf("newmodmailer: rcpt=%s\n", rcpt->q_paddr); SM_REQUIRE(rcpt->q_mailer->m_name != NULL); SM_REQUIRE(rcpt->q_mailer->m_name[0] != '\0'); sm_strlcpy(mname, rcpt->q_mailer->m_name, sizeof(mname)); mname[0] = dynmailerp; if (tTd(25, 8)) sm_dprintf("newmodmailer: name=%s\n", mname); s = stab(mname, ST_MAILER, ST_ENTER); if (s->s_mailer != NULL) { idx = s->s_mailer->m_mno; if (tTd(25, 6)) sm_dprintf("newmodmailer: found idx=%d\n", idx); } else { idx = rcpt->q_mailer->m_mno; idx += MAXMAILERS; if (tTd(25, 6)) sm_dprintf("newmodmailer: idx=%d\n", idx); if (idx > SM_ARRAY_SIZE(Mailer)) return false; } m = Mailer[idx]; if (m == NULL) m = (struct mailer *) xalloc(sizeof(*m)); memset((char *) m, '\0', sizeof(*m)); STRUCTCOPY(*rcpt->q_mailer, *m); Mailer[idx] = m; /* "modify" the mailer */ setbitn(bitidx(fl), m->m_flags); rcpt->q_mailer = m; m->m_mno = idx; m->m_name = newstr(mname); if (tTd(25, 1)) sm_dprintf("newmodmailer: mailer[%d]=%s %p\n", idx, Mailer[idx]->m_name, Mailer[idx]); return true; } #endif /* _FFR_RCPTFLAGS */ /* ** MAKEMAILER -- define a new mailer. ** ** Parameters: ** line -- description of mailer. This is in labeled ** fields. The fields are: ** A -- the argv for this mailer ** C -- the character set for MIME conversions ** D -- the directory to run in ** E -- the eol string ** F -- the flags associated with the mailer ** L -- the maximum line length ** M -- the maximum message size ** N -- the niceness at which to run ** P -- the path to the mailer ** Q -- the queue group for the mailer ** R -- the recipient rewriting set ** S -- the sender rewriting set ** T -- the mailer type (for DSNs) ** U -- the uid to run as ** W -- the time to wait at the end ** m -- maximum messages per connection ** r -- maximum number of recipients per message ** / -- new root directory ** The first word is the canonical name of the mailer. ** ** Returns: ** none. ** ** Side Effects: ** enters the mailer into the mailer table. */ void makemailer(line) char *line; { register char *p; register struct mailer *m; register STAB *s; int i; char fcode; auto char *endp; static int nextmailer = 0; /* "free" index into Mailer struct */ /* allocate a mailer and set up defaults */ m = (struct mailer *) xalloc(sizeof(*m)); memset((char *) m, '\0', sizeof(*m)); errno = 0; /* avoid bogus error text */ /* collect the mailer name */ for (p = line; *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p)); p++) continue; if (*p != '\0') *p++ = '\0'; if (line[0] == '\0') { syserr("name required for mailer"); return; } m->m_name = newstr(line); #if _FFR_RCPTFLAGS frst[nextmailer] = line[0]; #endif m->m_qgrp = NOQGRP; m->m_uid = NO_UID; m->m_gid = NO_GID; /* now scan through and assign info from the fields */ while (*p != '\0') { auto char *delimptr; while (*p != '\0' && (*p == ',' || (isascii(*p) && isspace(*p)))) p++; /* p now points to field code */ fcode = *p; while (*p != '\0' && *p != '=' && *p != ',') p++; if (*p++ != '=') { syserr("mailer %s: `=' expected", m->m_name); return; } while (isascii(*p) && isspace(*p)) p++; /* p now points to the field body */ p = munchstring(p, &delimptr, ','); /* install the field into the mailer struct */ switch (fcode) { case 'P': /* pathname */ if (*p != '\0') /* error is issued below */ m->m_mailer = newstr(p); break; case 'F': /* flags */ for (; *p != '\0'; p++) { if (!(isascii(*p) && isspace(*p))) { if (*p == M_INTERNAL) sm_syslog(LOG_WARNING, NOQID, "WARNING: mailer=%s, flag=%c deprecated", m->m_name, *p); setbitn(bitidx(*p), m->m_flags); } } break; case 'S': /* sender rewriting ruleset */ case 'R': /* recipient rewriting ruleset */ i = strtorwset(p, &endp, ST_ENTER); if (i < 0) return; if (fcode == 'S') m->m_sh_rwset = m->m_se_rwset = i; else m->m_rh_rwset = m->m_re_rwset = i; p = endp; if (*p++ == '/') { i = strtorwset(p, NULL, ST_ENTER); if (i < 0) return; if (fcode == 'S') m->m_sh_rwset = i; else m->m_rh_rwset = i; } break; case 'E': /* end of line string */ if (*p == '\0') syserr("mailer %s: null end-of-line string", m->m_name); else m->m_eol = newstr(p); break; case 'A': /* argument vector */ if (*p != '\0') /* error is issued below */ m->m_argv = makeargv(p); break; case 'M': /* maximum message size */ m->m_maxsize = atol(p); break; case 'm': /* maximum messages per connection */ m->m_maxdeliveries = atoi(p); break; case 'r': /* max recipient per envelope */ m->m_maxrcpt = atoi(p); break; case 'L': /* maximum line length */ m->m_linelimit = atoi(p); if (m->m_linelimit < 0) m->m_linelimit = 0; break; case 'N': /* run niceness */ m->m_nice = atoi(p); break; case 'D': /* working directory */ if (*p == '\0') syserr("mailer %s: null working directory", m->m_name); else m->m_execdir = newstr(p); break; case 'C': /* default charset */ if (*p == '\0') syserr("mailer %s: null charset", m->m_name); else m->m_defcharset = newstr(p); break; case 'Q': /* queue for this mailer */ if (*p == '\0') { syserr("mailer %s: null queue", m->m_name); break; } s = stab(p, ST_QUEUE, ST_FIND); if (s == NULL) syserr("mailer %s: unknown queue %s", m->m_name, p); else m->m_qgrp = s->s_quegrp->qg_index; break; case 'T': /* MTA-Name/Address/Diagnostic types */ /* extract MTA name type; default to "dns" */ m->m_mtatype = newstr(p); p = strchr(m->m_mtatype, '/'); if (p != NULL) { *p++ = '\0'; if (*p == '\0') p = NULL; } if (*m->m_mtatype == '\0') m->m_mtatype = "dns"; /* extract address type; default to "rfc822" */ m->m_addrtype = p; if (p != NULL) p = strchr(p, '/'); if (p != NULL) { *p++ = '\0'; if (*p == '\0') p = NULL; } if (m->m_addrtype == NULL || *m->m_addrtype == '\0') m->m_addrtype = "rfc822"; /* extract diagnostic type; default to "smtp" */ m->m_diagtype = p; if (m->m_diagtype == NULL || *m->m_diagtype == '\0') m->m_diagtype = "smtp"; break; case 'U': /* user id */ if (isascii(*p) && !isdigit(*p)) { char *q = p; struct passwd *pw; while (*p != '\0' && isascii(*p) && # if _FFR_DOTTED_USERNAMES (isalnum(*p) || strchr(SM_PWN_CHARS, *p) != NULL)) # else /* _FFR_DOTTED_USERNAMES */ (isalnum(*p) || strchr("-_", *p) != NULL)) # endif /* _FFR_DOTTED_USERNAMES */ p++; while (isascii(*p) && isspace(*p)) *p++ = '\0'; if (*p != '\0') *p++ = '\0'; if (*q == '\0') { syserr("mailer %s: null user name", m->m_name); break; } pw = sm_getpwnam(q); if (pw == NULL) { syserr("readcf: mailer U= flag: unknown user %s", q); break; } else { m->m_uid = pw->pw_uid; m->m_gid = pw->pw_gid; } } else { auto char *q; m->m_uid = strtol(p, &q, 0); p = q; while (isascii(*p) && isspace(*p)) p++; if (*p != '\0') p++; } while (isascii(*p) && isspace(*p)) p++; if (*p == '\0') break; if (isascii(*p) && !isdigit(*p)) { char *q = p; struct group *gr; while (isascii(*p) && (isalnum(*p) || strchr(SM_PWN_CHARS, *p) != NULL)) p++; *p++ = '\0'; if (*q == '\0') { syserr("mailer %s: null group name", m->m_name); break; } gr = getgrnam(q); if (gr == NULL) { syserr("readcf: mailer U= flag: unknown group %s", q); break; } else m->m_gid = gr->gr_gid; } else { m->m_gid = strtol(p, NULL, 0); } break; case 'W': /* wait timeout */ m->m_wait = convtime(p, 's'); break; case '/': /* new root directory */ if (*p == '\0') syserr("mailer %s: null root directory", m->m_name); else m->m_rootdir = newstr(p); break; default: syserr("M%s: unknown mailer equate %c=", m->m_name, fcode); break; } p = delimptr; } #if !HASRRESVPORT if (bitnset(M_SECURE_PORT, m->m_flags)) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: F=%c set on system that doesn't support rresvport()\n", m->m_name, M_SECURE_PORT); } #endif /* !HASRRESVPORT */ #if !HASNICE if (m->m_nice != 0) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: N= set on system that doesn't support nice()\n", m->m_name); } #endif /* !HASNICE */ /* do some rationality checking */ if (m->m_argv == NULL) { syserr("M%s: A= argument required", m->m_name); return; } if (m->m_mailer == NULL) { syserr("M%s: P= argument required", m->m_name); return; } if (nextmailer >= MAXMAILERS) { syserr("too many mailers defined (%d max)", MAXMAILERS); return; } if (m->m_maxrcpt <= 0) m->m_maxrcpt = DEFAULT_MAX_RCPT; /* do some heuristic cleanup for back compatibility */ if (bitnset(M_LIMITS, m->m_flags)) { if (m->m_linelimit == 0) m->m_linelimit = SMTPLINELIM; if (ConfigLevel < 2) setbitn(M_7BITS, m->m_flags); } if (strcmp(m->m_mailer, "[TCP]") == 0) { syserr("M%s: P=[TCP] must be replaced by P=[IPC]", m->m_name); return; } if (strcmp(m->m_mailer, "[IPC]") == 0) { /* Use the second argument for host or path to socket */ if (m->m_argv[0] == NULL || m->m_argv[1] == NULL || m->m_argv[1][0] == '\0') { syserr("M%s: too few parameters for %s mailer", m->m_name, m->m_mailer); return; } if (strcmp(m->m_argv[0], "TCP") != 0 #if NETUNIX && strcmp(m->m_argv[0], "FILE") != 0 #endif /* NETUNIX */ ) { (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "M%s: Warning: first argument in %s mailer must be %s\n", m->m_name, m->m_mailer, #if NETUNIX "TCP or FILE" #else /* NETUNIX */ "TCP" #endif /* NETUNIX */ ); } if (m->m_mtatype == NULL) m->m_mtatype = "dns"; if (m->m_addrtype == NULL) m->m_addrtype = "rfc822"; if (m->m_diagtype == NULL) { if (m->m_argv[0] != NULL && strcmp(m->m_argv[0], "FILE") == 0) m->m_diagtype = "x-unix"; else m->m_diagtype = "smtp"; } } else if (strcmp(m->m_mailer, "[FILE]") == 0) { /* Use the second argument for filename */ if (m->m_argv[0] == NULL || m->m_argv[1] == NULL || m->m_argv[2] != NULL) { syserr("M%s: too %s parameters for [FILE] mailer", m->m_name, (m->m_argv[0] == NULL || m->m_argv[1] == NULL) ? "few" : "many"); return; } else if (strcmp(m->m_argv[0], "FILE") != 0) { syserr("M%s: first argument in [FILE] mailer must be FILE", m->m_name); return; } } if (m->m_eol == NULL) { char **pp; /* default for SMTP is \r\n; use \n for local delivery */ for (pp = m->m_argv; *pp != NULL; pp++) { for (p = *pp; *p != '\0'; ) { if ((*p++ & 0377) == MACROEXPAND && *p == 'u') break; } if (*p != '\0') break; } if (*pp == NULL) m->m_eol = "\r\n"; else m->m_eol = "\n"; } /* enter the mailer into the symbol table */ s = stab(m->m_name, ST_MAILER, ST_ENTER); if (s->s_mailer != NULL) { i = s->s_mailer->m_mno; sm_free(s->s_mailer); /* XXX */ } else { i = nextmailer++; } Mailer[i] = s->s_mailer = m; m->m_mno = i; } /* ** MUNCHSTRING -- translate a string into internal form. ** ** Parameters: ** p -- the string to munch. ** delimptr -- if non-NULL, set to the pointer of the ** field delimiter character. ** delim -- the delimiter for the field. ** ** Returns: ** the munched string. ** ** Side Effects: ** the munched string is a local static buffer. ** it must be copied before the function is called again. */ char * munchstring(p, delimptr, delim) register char *p; char **delimptr; int delim; { register char *q; bool backslash = false; bool quotemode = false; static char buf[MAXLINE]; for (q = buf; *p != '\0' && q < &buf[sizeof(buf) - 1]; p++) { if (backslash) { /* everything is roughly literal */ backslash = false; switch (*p) { case 'r': /* carriage return */ *q++ = '\r'; continue; case 'n': /* newline */ *q++ = '\n'; continue; case 'f': /* form feed */ *q++ = '\f'; continue; case 'b': /* backspace */ *q++ = '\b'; continue; } *q++ = *p; } else { if (*p == '\\') backslash = true; else if (*p == '"') quotemode = !quotemode; else if (quotemode || *p != delim) *q++ = *p; else break; } } if (delimptr != NULL) *delimptr = p; *q++ = '\0'; return buf; } /* ** EXTRQUOTSTR -- extract a (quoted) string. ** ** This routine deals with quoted (") strings and escaped ** spaces (\\ ). ** ** Parameters: ** p -- source string. ** delimptr -- if non-NULL, set to the pointer of the ** field delimiter character. ** delimbuf -- delimiters for the field. ** st -- if non-NULL, store the return value (whether the ** string was correctly quoted) here. ** ** Returns: ** the extracted string. ** ** Side Effects: ** the returned string is a local static buffer. ** it must be copied before the function is called again. */ static char * extrquotstr(p, delimptr, delimbuf, st) register char *p; char **delimptr; char *delimbuf; bool *st; { register char *q; bool backslash = false; bool quotemode = false; static char buf[MAXLINE]; for (q = buf; *p != '\0' && q < &buf[sizeof(buf) - 1]; p++) { if (backslash) { backslash = false; if (*p != ' ') *q++ = '\\'; } if (*p == '\\') backslash = true; else if (*p == '"') quotemode = !quotemode; else if (quotemode || strchr(delimbuf, (int) *p) == NULL) *q++ = *p; else break; } if (delimptr != NULL) *delimptr = p; *q++ = '\0'; if (st != NULL) *st = !(quotemode || backslash); return buf; } /* ** MAKEARGV -- break up a string into words ** ** Parameters: ** p -- the string to break up. ** ** Returns: ** a char **argv (dynamically allocated) ** ** Side Effects: ** munges p. */ static char ** makeargv(p) register char *p; { char *q; int i; char **avp; char *argv[MAXPV + 1]; /* take apart the words */ i = 0; while (*p != '\0' && i < MAXPV) { q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; while (isascii(*p) && isspace(*p)) *p++ = '\0'; argv[i++] = newstr(q); } argv[i++] = NULL; /* now make a copy of the argv */ avp = (char **) xalloc(sizeof(*avp) * i); memmove((char *) avp, (char *) argv, sizeof(*avp) * i); return avp; } /* ** PRINTRULES -- print rewrite rules (for debugging) ** ** Parameters: ** none. ** ** Returns: ** none. ** ** Side Effects: ** prints rewrite rules. */ void printrules() { register struct rewrite *rwp; register int ruleset; for (ruleset = 0; ruleset < 10; ruleset++) { if (RewriteRules[ruleset] == NULL) continue; sm_dprintf("\n----Rule Set %d:", ruleset); for (rwp = RewriteRules[ruleset]; rwp != NULL; rwp = rwp->r_next) { sm_dprintf("\nLHS:"); printav(sm_debug_file(), rwp->r_lhs); sm_dprintf("RHS:"); printav(sm_debug_file(), rwp->r_rhs); } } } /* ** PRINTMAILER -- print mailer structure (for debugging) ** ** Parameters: ** fp -- output file ** m -- the mailer to print ** ** Returns: ** none. */ void printmailer(fp, m) SM_FILE_T *fp; register MAILER *m; { int j; (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "mailer %d (%s): P=%s S=", m->m_mno, m->m_name, m->m_mailer); if (RuleSetNames[m->m_se_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d/", m->m_se_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s/", RuleSetNames[m->m_se_rwset]); if (RuleSetNames[m->m_sh_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d R=", m->m_sh_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s R=", RuleSetNames[m->m_sh_rwset]); if (RuleSetNames[m->m_re_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d/", m->m_re_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s/", RuleSetNames[m->m_re_rwset]); if (RuleSetNames[m->m_rh_rwset] == NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%d ", m->m_rh_rwset); else (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s ", RuleSetNames[m->m_rh_rwset]); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "M=%ld U=%d:%d F=", m->m_maxsize, (int) m->m_uid, (int) m->m_gid); for (j = '\0'; j <= '\177'; j++) if (bitnset(j, m->m_flags)) (void) sm_io_putc(fp, SM_TIME_DEFAULT, j); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " L=%d E=", m->m_linelimit); xputs(fp, m->m_eol); if (m->m_defcharset != NULL) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " C=%s", m->m_defcharset); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " T=%s/%s/%s", m->m_mtatype == NULL ? "" : m->m_mtatype, m->m_addrtype == NULL ? "" : m->m_addrtype, m->m_diagtype == NULL ? "" : m->m_diagtype); (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " r=%d", m->m_maxrcpt); if (m->m_argv != NULL) { char **a = m->m_argv; (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " A="); while (*a != NULL) { if (a != m->m_argv) (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, " "); xputs(fp, *a++); } } (void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\n"); } #if STARTTLS static struct ssl_options { const char *sslopt_name; /* name of the flag */ long sslopt_bits; /* bits to set/clear */ } SSL_Option[] = { /* Workaround for bugs are turned on by default (as well as some others) */ #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG { "SSL_OP_MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG }, #endif #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG { "SSL_OP_NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG }, #endif #ifdef SSL_OP_LEGACY_SERVER_CONNECT { "SSL_OP_LEGACY_SERVER_CONNECT", SSL_OP_LEGACY_SERVER_CONNECT }, #endif #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG { "SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG }, #endif #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG { "SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG }, #endif #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER { "SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER }, #endif #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING { "SSL_OP_MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING }, #endif #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG { "SSL_OP_SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG }, #endif #ifdef SSL_OP_TLS_D5_BUG { "SSL_OP_TLS_D5_BUG", SSL_OP_TLS_D5_BUG }, #endif #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG { "SSL_OP_TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG }, #endif #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS { "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS }, #endif #ifdef SSL_OP_ALL { "SSL_OP_ALL", SSL_OP_ALL }, #endif #ifdef SSL_OP_NO_QUERY_MTU { "SSL_OP_NO_QUERY_MTU", SSL_OP_NO_QUERY_MTU }, #endif #ifdef SSL_OP_COOKIE_EXCHANGE { "SSL_OP_COOKIE_EXCHANGE", SSL_OP_COOKIE_EXCHANGE }, #endif #ifdef SSL_OP_NO_TICKET { "SSL_OP_NO_TICKET", SSL_OP_NO_TICKET }, #endif #ifdef SSL_OP_CISCO_ANYCONNECT { "SSL_OP_CISCO_ANYCONNECT", SSL_OP_CISCO_ANYCONNECT }, #endif #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION { "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION }, #endif #ifdef SSL_OP_NO_COMPRESSION { "SSL_OP_NO_COMPRESSION", SSL_OP_NO_COMPRESSION }, #endif #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION { "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION }, #endif #ifdef SSL_OP_SINGLE_ECDH_USE { "SSL_OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE }, #endif #ifdef SSL_OP_SINGLE_DH_USE { "SSL_OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE }, #endif #ifdef SSL_OP_EPHEMERAL_RSA { "SSL_OP_EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA }, #endif #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE { "SSL_OP_CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE }, #endif #ifdef SSL_OP_TLS_ROLLBACK_BUG { "SSL_OP_TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG }, #endif #ifdef SSL_OP_NO_SSLv2 { "SSL_OP_NO_SSLv2", SSL_OP_NO_SSLv2 }, #endif #ifdef SSL_OP_NO_SSLv3 { "SSL_OP_NO_SSLv3", SSL_OP_NO_SSLv3 }, #endif #ifdef SSL_OP_NO_TLSv1 { "SSL_OP_NO_TLSv1", SSL_OP_NO_TLSv1 }, #endif #ifdef SSL_OP_NO_TLSv1_2 { "SSL_OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2 }, #endif #ifdef SSL_OP_NO_TLSv1_1 { "SSL_OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1 }, #endif #ifdef SSL_OP_PKCS1_CHECK_1 { "SSL_OP_PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1 }, #endif #ifdef SSL_OP_PKCS1_CHECK_2 { "SSL_OP_PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2 }, #endif #ifdef SSL_OP_NETSCAPE_CA_DN_BUG { "SSL_OP_NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG }, #endif #ifdef SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG { "SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG }, #endif #ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG { "SSL_OP_CRYPTOPRO_TLSEXT_BUG", SSL_OP_CRYPTOPRO_TLSEXT_BUG }, #endif #ifdef SSL_OP_TLSEXT_PADDING { "SSL_OP_TLSEXT_PADDING", SSL_OP_TLSEXT_PADDING }, #endif { NULL, 0 } }; /* ** READSSLOPTIONS -- read SSL_OP_* values ** ** Parameters: ** opt -- name of option (can be NULL) ** val -- string with SSL_OP_* values or hex value ** delim -- end of string (e.g., '\0' or ';') ** pssloptions -- return value (output) ** ** Returns: ** 0 on success. */ #define SSLOPERR_NAN 1 #define SSLOPERR_NOTFOUND 2 #define SM_ISSPACE(c) (isascii(c) && isspace(c)) static int readssloptions(opt, val, pssloptions, delim) char *opt; char *val; unsigned long *pssloptions; int delim; { char *p; int ret; ret = 0; for (p = val; *p != '\0' && *p != delim; ) { bool clearmode; char *q; unsigned long sslopt_val; struct ssl_options *sslopts; while (*p == ' ') p++; if (*p == '\0') break; clearmode = false; if (*p == '-' || *p == '+') clearmode = *p++ == '-'; q = p; while (*p != '\0' && !(SM_ISSPACE(*p)) && *p != ',') p++; if (*p != '\0') *p++ = '\0'; sslopt_val = 0; if (isdigit(*q)) { char *end; sslopt_val = strtoul(q, &end, 0); /* not a complete "syntax" check but good enough */ if (end == q) { errno = 0; ret = SSLOPERR_NAN; if (opt != NULL) syserr("readcf: %s option value %s not a number", opt, q); sslopt_val = 0; } } else { for (sslopts = SSL_Option; sslopts->sslopt_name != NULL; sslopts++) { if (sm_strcasecmp(q, sslopts->sslopt_name) == 0) { sslopt_val = sslopts->sslopt_bits; break; } } if (sslopts->sslopt_name == NULL) { errno = 0; ret = SSLOPERR_NOTFOUND; if (opt != NULL) syserr("readcf: %s option value %s unrecognized", opt, q); } } if (sslopt_val != 0) { if (clearmode) *pssloptions &= ~sslopt_val; else *pssloptions |= sslopt_val; } } return ret; } # if _FFR_TLS_SE_OPTS /* ** GET_TLS_SE_OPTIONS -- get TLS session options (from ruleset) ** ** Parameters: ** e -- envelope ** ssl -- TLS session context ** srv -- server? ** ** Returns: ** 0 on success. */ int get_tls_se_options(e, ssl, srv) ENVELOPE *e; SSL *ssl; bool srv; { bool saveQuickAbort, saveSuprErrs, ok; char *optionlist, *opt, *val; char *keyfile, *certfile; size_t len, i; int ret; # define who (srv ? "server" : "client") # define NAME_C_S macvalue(macid(srv ? "{client_name}" : "{server_name}"), e) # define ADDR_C_S macvalue(macid(srv ? "{client_addr}" : "{server_addr}"), e) # define WHICH srv ? "srv" : "clt" ret = 0; keyfile = certfile = opt = val = NULL; saveQuickAbort = QuickAbort; saveSuprErrs = SuprErrs; SuprErrs = true; QuickAbort = false; optionlist = NULL; ok = rscheck(srv ? "tls_srv_features" : "tls_clt_features", NAME_C_S, ADDR_C_S, e, RSF_RMCOMM|RSF_ADDR|RSF_STRING, 5, NULL, NOQID, NULL, &optionlist) == EX_OK; if (!ok && LogLevel > 8) { sm_syslog(LOG_NOTICE, NOQID, "rscheck(tls_%s_features)=failed, relay=%s [%s], errors=%d", WHICH, NAME_C_S, ADDR_C_S, Errors); } QuickAbort = saveQuickAbort; SuprErrs = saveSuprErrs; if (ok && LogLevel > 9) { sm_syslog(LOG_INFO, NOQID, "tls_%s_features=%s, relay=%s [%s]", WHICH, optionlist, NAME_C_S, ADDR_C_S); } if (!ok || optionlist == NULL || (len = strlen(optionlist)) < 2) { if (LogLevel > 9) sm_syslog(LOG_INFO, NOQID, "tls_%s_features=empty, relay=%s [%s]", WHICH, NAME_C_S, ADDR_C_S); return ok ? 0 : 1; } i = 0; if (optionlist[0] == '"' && optionlist[len - 1] == '"') { optionlist[0] = ' '; optionlist[--len] = '\0'; if (len <= 2) { if (LogLevel > 9 && len > 1) sm_syslog(LOG_INFO, NOQID, "tls_%s_features=too_short, relay=%s [%s]", WHICH, NAME_C_S, ADDR_C_S); /* this is not treated as error! */ return 0; } i = 1; } # define INVALIDSYNTAX \ do { \ if (LogLevel > 7) \ sm_syslog(LOG_INFO, NOQID, \ "tls_%s_features=invalid_syntax, opt=%s, relay=%s [%s]", \ WHICH, opt, NAME_C_S, ADDR_C_S); \ return -1; \ } while (0) # define CHECKLEN \ do { \ if (i >= len) \ INVALIDSYNTAX; \ } while (0) # define SKIPWS \ do { \ while (i < len && SM_ISSPACE(optionlist[i])) \ ++i; \ CHECKLEN; \ } while (0) /* parse and handle opt=val; */ do { char sep; SKIPWS; opt = optionlist + i; sep = '='; while (i < len && optionlist[i] != sep && optionlist[i] != '\0' && !SM_ISSPACE(optionlist[i])) ++i; CHECKLEN; while (i < len && SM_ISSPACE(optionlist[i])) optionlist[i++] = '\0'; CHECKLEN; if (optionlist[i] != sep) INVALIDSYNTAX; optionlist[i++] = '\0'; SKIPWS; val = optionlist + i; sep = ';'; while (i < len && optionlist[i] != sep && optionlist[i] != '\0') ++i; if (optionlist[i] != '\0') { CHECKLEN; optionlist[i++] = '\0'; } if (LogLevel > 13) sm_syslog(LOG_DEBUG, NOQID, "tls_%s_features=parsed, %s=%s, relay=%s [%s]", WHICH, opt, val, NAME_C_S, ADDR_C_S); if (sm_strcasecmp(opt, "options") == 0) { unsigned long ssloptions; ssloptions = 0; ret = readssloptions(NULL, val, &ssloptions, ';'); if (ret == 0) (void) SSL_set_options(ssl, (long) ssloptions); else if (LogLevel > 8) { sm_syslog(LOG_WARNING, NOQID, "tls_%s_features=%s, error=%s, relay=%s [%s]", WHICH, val, (ret == SSLOPERR_NAN) ? "not a number" : ((ret == SSLOPERR_NOTFOUND) ? "SSL_OP not found" : "unknown"), NAME_C_S, ADDR_C_S); } } else if (sm_strcasecmp(opt, "cipherlist") == 0) { if (SSL_set_cipher_list(ssl, val) <= 0) { ret = 1; if (LogLevel > 7) { sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s, error: SSL_set_cipher_list(%s) failed", who, val); if (LogLevel > 9) tlslogerr(LOG_WARNING, who); } } } else if (sm_strcasecmp(opt, "keyfile") == 0) keyfile = val; else if (sm_strcasecmp(opt, "certfile") == 0) certfile = val; else { ret = 1; if (LogLevel > 7) { sm_syslog(LOG_INFO, NOQID, "tls_%s_features=unknown_option, opt=%s, relay=%s [%s]", WHICH, opt, NAME_C_S, ADDR_C_S); } } } while (optionlist[i] != '\0' && i < len); /* need cert and key before we can use the options */ /* does not implement the "," hack for 2nd cert/key pair */ if (keyfile != NULL && certfile != NULL) { load_certkey(ssl, srv, certfile, keyfile); keyfile = certfile = NULL; } else if (keyfile != NULL || certfile != NULL) { ret = 1; if (LogLevel > 7) { sm_syslog(LOG_INFO, NOQID, "tls_%s_features=only_one_of_CertFile/KeyFile_specified, relay=%s [%s]", WHICH, NAME_C_S, ADDR_C_S); } } return ret; # undef who # undef NAME_C_S # undef ADDR_C_S # undef WHICH } # endif /* _FFR_TLS_SE_OPTS */ #endif /* STARTTLS */ /* ** SETOPTION -- set global processing option ** ** Parameters: ** opt -- option name. ** val -- option value (as a text string). ** safe -- set if this came from a configuration file. ** Some options (if set from the command line) will ** reset the user id to avoid security problems. ** sticky -- if set, don't let other setoptions override ** this value. ** e -- the main envelope. ** ** Returns: ** none. ** ** Side Effects: ** Sets options as implied by the arguments. */ static BITMAP256 StickyOpt; /* set if option is stuck */ #if NAMED_BIND static struct resolverflags { char *rf_name; /* name of the flag */ long rf_bits; /* bits to set/clear */ } ResolverFlags[] = { { "debug", RES_DEBUG }, { "aaonly", RES_AAONLY }, { "usevc", RES_USEVC }, { "primary", RES_PRIMARY }, { "igntc", RES_IGNTC }, { "recurse", RES_RECURSE }, { "defnames", RES_DEFNAMES }, { "stayopen", RES_STAYOPEN }, { "dnsrch", RES_DNSRCH }, # ifdef RES_USE_INET6 { "use_inet6", RES_USE_INET6 }, # endif /* RES_USE_INET6 */ { "true", 0 }, /* avoid error on old syntax */ { NULL, 0 } }; #endif /* NAMED_BIND */ #define OI_NONE 0 /* no special treatment */ #define OI_SAFE 0x0001 /* safe for random people to use */ #define OI_SUBOPT 0x0002 /* option has suboptions */ static struct optioninfo { char *o_name; /* long name of option */ unsigned char o_code; /* short name of option */ unsigned short o_flags; /* option flags */ } OptionTab[] = { #if defined(SUN_EXTENSIONS) && defined(REMOTE_MODE) { "RemoteMode", '>', OI_NONE }, #endif /* defined(SUN_EXTENSIONS) && defined(REMOTE_MODE) */ { "SevenBitInput", '7', OI_SAFE }, { "EightBitMode", '8', OI_SAFE }, { "AliasFile", 'A', OI_NONE }, { "AliasWait", 'a', OI_NONE }, { "BlankSub", 'B', OI_NONE }, { "MinFreeBlocks", 'b', OI_SAFE }, { "CheckpointInterval", 'C', OI_SAFE }, { "HoldExpensive", 'c', OI_NONE }, { "DeliveryMode", 'd', OI_SAFE }, { "ErrorHeader", 'E', OI_NONE }, { "ErrorMode", 'e', OI_SAFE }, { "TempFileMode", 'F', OI_NONE }, { "SaveFromLine", 'f', OI_NONE }, { "MatchGECOS", 'G', OI_NONE }, /* no long name, just here to avoid problems in setoption */ { "", 'g', OI_NONE }, { "HelpFile", 'H', OI_NONE }, { "MaxHopCount", 'h', OI_NONE }, { "ResolverOptions", 'I', OI_NONE }, { "IgnoreDots", 'i', OI_SAFE }, { "ForwardPath", 'J', OI_NONE }, { "SendMimeErrors", 'j', OI_SAFE }, { "ConnectionCacheSize", 'k', OI_NONE }, { "ConnectionCacheTimeout", 'K', OI_NONE }, { "UseErrorsTo", 'l', OI_NONE }, { "LogLevel", 'L', OI_SAFE }, { "MeToo", 'm', OI_SAFE }, /* no long name, just here to avoid problems in setoption */ { "", 'M', OI_NONE }, { "CheckAliases", 'n', OI_NONE }, { "OldStyleHeaders", 'o', OI_SAFE }, { "DaemonPortOptions", 'O', OI_NONE }, { "PrivacyOptions", 'p', OI_SAFE }, { "PostmasterCopy", 'P', OI_NONE }, { "QueueFactor", 'q', OI_NONE }, { "QueueDirectory", 'Q', OI_NONE }, { "DontPruneRoutes", 'R', OI_NONE }, { "Timeout", 'r', OI_SUBOPT }, { "StatusFile", 'S', OI_NONE }, { "SuperSafe", 's', OI_SAFE }, { "QueueTimeout", 'T', OI_NONE }, { "TimeZoneSpec", 't', OI_NONE }, { "UserDatabaseSpec", 'U', OI_NONE }, { "DefaultUser", 'u', OI_NONE }, { "FallbackMXhost", 'V', OI_NONE }, { "Verbose", 'v', OI_SAFE }, { "TryNullMXList", 'w', OI_NONE }, { "QueueLA", 'x', OI_NONE }, { "RefuseLA", 'X', OI_NONE }, { "RecipientFactor", 'y', OI_NONE }, { "ForkEachJob", 'Y', OI_NONE }, { "ClassFactor", 'z', OI_NONE }, { "RetryFactor", 'Z', OI_NONE }, #define O_QUEUESORTORD 0x81 { "QueueSortOrder", O_QUEUESORTORD, OI_SAFE }, #define O_HOSTSFILE 0x82 { "HostsFile", O_HOSTSFILE, OI_NONE }, #define O_MQA 0x83 { "MinQueueAge", O_MQA, OI_SAFE }, #define O_DEFCHARSET 0x85 { "DefaultCharSet", O_DEFCHARSET, OI_SAFE }, #define O_SSFILE 0x86 { "ServiceSwitchFile", O_SSFILE, OI_NONE }, #define O_DIALDELAY 0x87 { "DialDelay", O_DIALDELAY, OI_SAFE }, #define O_NORCPTACTION 0x88 { "NoRecipientAction", O_NORCPTACTION, OI_SAFE }, #define O_SAFEFILEENV 0x89 { "SafeFileEnvironment", O_SAFEFILEENV, OI_NONE }, #define O_MAXMSGSIZE 0x8a { "MaxMessageSize", O_MAXMSGSIZE, OI_NONE }, #define O_COLONOKINADDR 0x8b { "ColonOkInAddr", O_COLONOKINADDR, OI_SAFE }, #define O_MAXQUEUERUN 0x8c { "MaxQueueRunSize", O_MAXQUEUERUN, OI_SAFE }, #define O_MAXCHILDREN 0x8d { "MaxDaemonChildren", O_MAXCHILDREN, OI_NONE }, #define O_KEEPCNAMES 0x8e { "DontExpandCnames", O_KEEPCNAMES, OI_NONE }, #define O_MUSTQUOTE 0x8f { "MustQuoteChars", O_MUSTQUOTE, OI_NONE }, #define O_SMTPGREETING 0x90 { "SmtpGreetingMessage", O_SMTPGREETING, OI_NONE }, #define O_UNIXFROM 0x91 { "UnixFromLine", O_UNIXFROM, OI_NONE }, #define O_OPCHARS 0x92 { "OperatorChars", O_OPCHARS, OI_NONE }, #define O_DONTINITGRPS 0x93 { "DontInitGroups", O_DONTINITGRPS, OI_NONE }, #define O_SLFH 0x94 { "SingleLineFromHeader", O_SLFH, OI_SAFE }, #define O_ABH 0x95 { "AllowBogusHELO", O_ABH, OI_SAFE }, #define O_CONNTHROT 0x97 { "ConnectionRateThrottle", O_CONNTHROT, OI_NONE }, #define O_UGW 0x99 { "UnsafeGroupWrites", O_UGW, OI_NONE }, #define O_DBLBOUNCE 0x9a { "DoubleBounceAddress", O_DBLBOUNCE, OI_NONE }, #define O_HSDIR 0x9b { "HostStatusDirectory", O_HSDIR, OI_NONE }, #define O_SINGTHREAD 0x9c { "SingleThreadDelivery", O_SINGTHREAD, OI_NONE }, #define O_RUNASUSER 0x9d { "RunAsUser", O_RUNASUSER, OI_NONE }, #define O_DSN_RRT 0x9e { "RrtImpliesDsn", O_DSN_RRT, OI_NONE }, #define O_PIDFILE 0x9f { "PidFile", O_PIDFILE, OI_NONE }, #define O_DONTBLAMESENDMAIL 0xa0 { "DontBlameSendmail", O_DONTBLAMESENDMAIL, OI_NONE }, #define O_DPI 0xa1 { "DontProbeInterfaces", O_DPI, OI_NONE }, #define O_MAXRCPT 0xa2 { "MaxRecipientsPerMessage", O_MAXRCPT, OI_SAFE }, #define O_DEADLETTER 0xa3 { "DeadLetterDrop", O_DEADLETTER, OI_NONE }, #if _FFR_DONTLOCKFILESFORREAD_OPTION # define O_DONTLOCK 0xa4 { "DontLockFilesForRead", O_DONTLOCK, OI_NONE }, #endif /* _FFR_DONTLOCKFILESFORREAD_OPTION */ #define O_MAXALIASRCSN 0xa5 { "MaxAliasRecursion", O_MAXALIASRCSN, OI_NONE }, #define O_CNCTONLYTO 0xa6 { "ConnectOnlyTo", O_CNCTONLYTO, OI_NONE }, #define O_TRUSTUSER 0xa7 { "TrustedUser", O_TRUSTUSER, OI_NONE }, #define O_MAXMIMEHDRLEN 0xa8 { "MaxMimeHeaderLength", O_MAXMIMEHDRLEN, OI_NONE }, #define O_CONTROLSOCKET 0xa9 { "ControlSocketName", O_CONTROLSOCKET, OI_NONE }, #define O_MAXHDRSLEN 0xaa { "MaxHeadersLength", O_MAXHDRSLEN, OI_NONE }, #if _FFR_MAX_FORWARD_ENTRIES # define O_MAXFORWARD 0xab { "MaxForwardEntries", O_MAXFORWARD, OI_NONE }, #endif /* _FFR_MAX_FORWARD_ENTRIES */ #define O_PROCTITLEPREFIX 0xac { "ProcessTitlePrefix", O_PROCTITLEPREFIX, OI_NONE }, #define O_SASLINFO 0xad #if _FFR_ALLOW_SASLINFO { "DefaultAuthInfo", O_SASLINFO, OI_SAFE }, #else /* _FFR_ALLOW_SASLINFO */ { "DefaultAuthInfo", O_SASLINFO, OI_NONE }, #endif /* _FFR_ALLOW_SASLINFO */ #define O_SASLMECH 0xae { "AuthMechanisms", O_SASLMECH, OI_NONE }, #define O_CLIENTPORT 0xaf { "ClientPortOptions", O_CLIENTPORT, OI_NONE }, #define O_DF_BUFSIZE 0xb0 { "DataFileBufferSize", O_DF_BUFSIZE, OI_NONE }, #define O_XF_BUFSIZE 0xb1 { "XscriptFileBufferSize", O_XF_BUFSIZE, OI_NONE }, #define O_LDAPDEFAULTSPEC 0xb2 { "LDAPDefaultSpec", O_LDAPDEFAULTSPEC, OI_NONE }, #define O_SRVCERTFILE 0xb4 { "ServerCertFile", O_SRVCERTFILE, OI_NONE }, #define O_SRVKEYFILE 0xb5 { "ServerKeyFile", O_SRVKEYFILE, OI_NONE }, #define O_CLTCERTFILE 0xb6 { "ClientCertFile", O_CLTCERTFILE, OI_NONE }, #define O_CLTKEYFILE 0xb7 { "ClientKeyFile", O_CLTKEYFILE, OI_NONE }, #define O_CACERTFILE 0xb8 { "CACertFile", O_CACERTFILE, OI_NONE }, #define O_CACERTPATH 0xb9 { "CACertPath", O_CACERTPATH, OI_NONE }, #define O_DHPARAMS 0xba { "DHParameters", O_DHPARAMS, OI_NONE }, #define O_INPUTMILTER 0xbb { "InputMailFilters", O_INPUTMILTER, OI_NONE }, #define O_MILTER 0xbc { "Milter", O_MILTER, OI_SUBOPT }, #define O_SASLOPTS 0xbd { "AuthOptions", O_SASLOPTS, OI_NONE }, #define O_QUEUE_FILE_MODE 0xbe { "QueueFileMode", O_QUEUE_FILE_MODE, OI_NONE }, #define O_DIG_ALG 0xbf { "CertFingerprintAlgorithm", O_DIG_ALG, OI_NONE }, #define O_CIPHERLIST 0xc0 { "CipherList", O_CIPHERLIST, OI_NONE }, #define O_RANDFILE 0xc1 { "RandFile", O_RANDFILE, OI_NONE }, #define O_TLS_SRV_OPTS 0xc2 { "TLSSrvOptions", O_TLS_SRV_OPTS, OI_NONE }, #define O_RCPTTHROT 0xc3 { "BadRcptThrottle", O_RCPTTHROT, OI_SAFE }, #define O_DLVR_MIN 0xc4 { "DeliverByMin", O_DLVR_MIN, OI_NONE }, #define O_MAXQUEUECHILDREN 0xc5 { "MaxQueueChildren", O_MAXQUEUECHILDREN, OI_NONE }, #define O_MAXRUNNERSPERQUEUE 0xc6 { "MaxRunnersPerQueue", O_MAXRUNNERSPERQUEUE, OI_NONE }, #define O_DIRECTSUBMODIFIERS 0xc7 { "DirectSubmissionModifiers", O_DIRECTSUBMODIFIERS, OI_NONE }, #define O_NICEQUEUERUN 0xc8 { "NiceQueueRun", O_NICEQUEUERUN, OI_NONE }, #define O_SHMKEY 0xc9 { "SharedMemoryKey", O_SHMKEY, OI_NONE }, #define O_SASLBITS 0xca { "AuthMaxBits", O_SASLBITS, OI_NONE }, #define O_MBDB 0xcb { "MailboxDatabase", O_MBDB, OI_NONE }, #define O_MSQ 0xcc { "UseMSP", O_MSQ, OI_NONE }, #define O_DELAY_LA 0xcd { "DelayLA", O_DELAY_LA, OI_NONE }, #define O_FASTSPLIT 0xce { "FastSplit", O_FASTSPLIT, OI_NONE }, #define O_SOFTBOUNCE 0xcf { "SoftBounce", O_SOFTBOUNCE, OI_NONE }, #define O_SHMKEYFILE 0xd0 { "SharedMemoryKeyFile", O_SHMKEYFILE, OI_NONE }, #define O_REJECTLOGINTERVAL 0xd1 { "RejectLogInterval", O_REJECTLOGINTERVAL, OI_NONE }, #define O_REQUIRES_DIR_FSYNC 0xd2 { "RequiresDirfsync", O_REQUIRES_DIR_FSYNC, OI_NONE }, #define O_CONNECTION_RATE_WINDOW_SIZE 0xd3 { "ConnectionRateWindowSize", O_CONNECTION_RATE_WINDOW_SIZE, OI_NONE }, #define O_CRLFILE 0xd4 { "CRLFile", O_CRLFILE, OI_NONE }, #define O_FALLBACKSMARTHOST 0xd5 { "FallbackSmartHost", O_FALLBACKSMARTHOST, OI_NONE }, #define O_SASLREALM 0xd6 { "AuthRealm", O_SASLREALM, OI_NONE }, #if _FFR_CRLPATH # define O_CRLPATH 0xd7 { "CRLPath", O_CRLPATH, OI_NONE }, #endif /* _FFR_CRLPATH */ #define O_HELONAME 0xd8 { "HeloName", O_HELONAME, OI_NONE }, #if _FFR_MEMSTAT # define O_REFUSELOWMEM 0xd9 { "RefuseLowMem", O_REFUSELOWMEM, OI_NONE }, # define O_QUEUELOWMEM 0xda { "QueueLowMem", O_QUEUELOWMEM, OI_NONE }, # define O_MEMRESOURCE 0xdb { "MemoryResource", O_MEMRESOURCE, OI_NONE }, #endif /* _FFR_MEMSTAT */ #define O_MAXNOOPCOMMANDS 0xdc { "MaxNOOPCommands", O_MAXNOOPCOMMANDS, OI_NONE }, #if _FFR_MSG_ACCEPT # define O_MSG_ACCEPT 0xdd { "MessageAccept", O_MSG_ACCEPT, OI_NONE }, #endif /* _FFR_MSG_ACCEPT */ #if _FFR_QUEUE_RUN_PARANOIA # define O_CHK_Q_RUNNERS 0xde { "CheckQueueRunners", O_CHK_Q_RUNNERS, OI_NONE }, #endif /* _FFR_QUEUE_RUN_PARANOIA */ #if _FFR_EIGHT_BIT_ADDR_OK # if !ALLOW_255 # ERROR FFR_EIGHT_BIT_ADDR_OK requires _ALLOW_255 # endif /* !ALLOW_255 */ # define O_EIGHT_BIT_ADDR_OK 0xdf { "EightBitAddrOK", O_EIGHT_BIT_ADDR_OK, OI_NONE }, #endif /* _FFR_EIGHT_BIT_ADDR_OK */ #if _FFR_ADDR_TYPE_MODES # define O_ADDR_TYPE_MODES 0xe0 { "AddrTypeModes", O_ADDR_TYPE_MODES, OI_NONE }, #endif /* _FFR_ADDR_TYPE_MODES */ #if _FFR_BADRCPT_SHUTDOWN # define O_RCPTSHUTD 0xe1 { "BadRcptShutdown", O_RCPTSHUTD, OI_SAFE }, # define O_RCPTSHUTDG 0xe2 { "BadRcptShutdownGood", O_RCPTSHUTDG, OI_SAFE }, #endif /* _FFR_BADRCPT_SHUTDOWN */ #define O_SRV_SSL_OPTIONS 0xe3 { "ServerSSLOptions", O_SRV_SSL_OPTIONS, OI_NONE }, #define O_CLT_SSL_OPTIONS 0xe4 { "ClientSSLOptions", O_CLT_SSL_OPTIONS, OI_NONE }, #define O_MAX_QUEUE_AGE 0xe5 { "MaxQueueAge", O_MAX_QUEUE_AGE, OI_NONE }, #if _FFR_RCPTTHROTDELAY # define O_RCPTTHROTDELAY 0xe6 { "BadRcptThrottleDelay", O_RCPTTHROTDELAY, OI_SAFE }, #endif /* _FFR_RCPTTHROTDELAY */ #if 0 && _FFR_QOS && defined(SOL_IP) && defined(IP_TOS) # define O_INETQOS 0xe7 /* reserved for FFR_QOS */ { "InetQoS", O_INETQOS, OI_NONE }, #endif #if STARTTLS && _FFR_FIPSMODE # define O_FIPSMODE 0xe8 { "FIPSMode", O_FIPSMODE, OI_NONE }, #endif /* STARTTLS && _FFR_FIPSMODE */ #if _FFR_REJECT_NUL_BYTE # define O_REJECTNUL 0xe9 { "RejectNUL", O_REJECTNUL, OI_SAFE }, #endif /* _FFR_REJECT_NUL_BYTE */ #if _FFR_BOUNCE_QUEUE # define O_BOUNCEQUEUE 0xea { "BounceQueue", O_BOUNCEQUEUE, OI_NONE }, #endif /* _FFR_BOUNCE_QUEUE */ #if _FFR_ADD_BCC # define O_ADDBCC 0xeb { "AddBcc", O_ADDBCC, OI_NONE }, #endif #define O_USECOMPRESSEDIPV6ADDRESSES 0xec { "UseCompressedIPv6Addresses", O_USECOMPRESSEDIPV6ADDRESSES, OI_NONE }, { NULL, '\0', OI_NONE } }; # define CANONIFY(val) # define SET_OPT_DEFAULT(opt, val) opt = val /* set a string option by expanding the value and assigning it */ /* WARNING this belongs ONLY into a case statement! */ #define SET_STRING_EXP(str) \ expand(val, exbuf, sizeof(exbuf), e); \ newval = sm_pstrdup_x(exbuf); \ if (str != NULL) \ sm_free(str); \ CANONIFY(newval); \ str = newval; \ break #define OPTNAME o->o_name == NULL ? "" : o->o_name void setoption(opt, val, safe, sticky, e) int opt; char *val; bool safe; bool sticky; register ENVELOPE *e; { register char *p; register struct optioninfo *o; char *subopt; int mid; bool can_setuid = RunAsUid == 0; auto char *ep; char buf[50]; extern bool Warn_Q_option; #if _FFR_ALLOW_SASLINFO extern unsigned int SubmitMode; #endif /* _FFR_ALLOW_SASLINFO */ #if STARTTLS || SM_CONF_SHM char *newval; char exbuf[MAXLINE]; #endif /* STARTTLS || SM_CONF_SHM */ #if STARTTLS unsigned long *pssloptions = NULL; #endif errno = 0; if (opt == ' ') { /* full word options */ struct optioninfo *sel; p = strchr(val, '='); if (p == NULL) p = &val[strlen(val)]; while (*--p == ' ') continue; while (*++p == ' ') *p = '\0'; if (p == val) { syserr("readcf: null option name"); return; } if (*p == '=') *p++ = '\0'; while (*p == ' ') p++; subopt = strchr(val, '.'); if (subopt != NULL) *subopt++ = '\0'; sel = NULL; for (o = OptionTab; o->o_name != NULL; o++) { if (sm_strncasecmp(o->o_name, val, strlen(val)) != 0) continue; if (strlen(o->o_name) == strlen(val)) { /* completely specified -- this must be it */ sel = NULL; break; } if (sel != NULL) break; sel = o; } if (sel != NULL && o->o_name == NULL) o = sel; else if (o->o_name == NULL) { syserr("readcf: unknown option name %s", val); return; } else if (sel != NULL) { syserr("readcf: ambiguous option name %s (matches %s and %s)", val, sel->o_name, o->o_name); return; } if (strlen(val) != strlen(o->o_name)) { int oldVerbose = Verbose; Verbose = 1; message("Option %s used as abbreviation for %s", val, o->o_name); Verbose = oldVerbose; } opt = o->o_code; val = p; } else { for (o = OptionTab; o->o_name != NULL; o++) { if (o->o_code == opt) break; } if (o->o_name == NULL) { syserr("readcf: unknown option name 0x%x", opt & 0xff); return; } subopt = NULL; } if (subopt != NULL && !bitset(OI_SUBOPT, o->o_flags)) { if (tTd(37, 1)) sm_dprintf("setoption: %s does not support suboptions, ignoring .%s\n", OPTNAME, subopt); subopt = NULL; } if (tTd(37, 1)) { sm_dprintf(isascii(opt) && isprint(opt) ? "setoption %s (%c)%s%s=" : "setoption %s (0x%x)%s%s=", OPTNAME, opt, subopt == NULL ? "" : ".", subopt == NULL ? "" : subopt); xputs(sm_debug_file(), val); } /* ** See if this option is preset for us. */ if (!sticky && bitnset(opt, StickyOpt)) { if (tTd(37, 1)) sm_dprintf(" (ignored)\n"); return; } /* ** Check to see if this option can be specified by this user. */ if (!safe && RealUid == 0) safe = true; if (!safe && !bitset(OI_SAFE, o->o_flags)) { if (opt != 'M' || (val[0] != 'r' && val[0] != 's')) { int dp; if (tTd(37, 1)) sm_dprintf(" (unsafe)"); dp = drop_privileges(true); setstat(dp); } } if (tTd(37, 1)) sm_dprintf("\n"); switch (opt & 0xff) { case '7': /* force seven-bit input */ SevenBitInput = atobool(val); break; case '8': /* handling of 8-bit input */ #if MIME8TO7 switch (*val) { case 'p': /* pass 8 bit, convert MIME */ MimeMode = MM_CVTMIME|MM_PASS8BIT; break; case 'm': /* convert 8-bit, convert MIME */ MimeMode = MM_CVTMIME|MM_MIME8BIT; break; case 's': /* strict adherence */ MimeMode = MM_CVTMIME; break; # if 0 case 'r': /* reject 8-bit, don't convert MIME */ MimeMode = 0; break; case 'j': /* "just send 8" */ MimeMode = MM_PASS8BIT; break; case 'a': /* encode 8 bit if available */ MimeMode = MM_MIME8BIT|MM_PASS8BIT|MM_CVTMIME; break; case 'c': /* convert 8 bit to MIME, never 7 bit */ MimeMode = MM_MIME8BIT; break; # endif /* 0 */ default: syserr("Unknown 8-bit mode %c", *val); finis(false, true, EX_USAGE); } #else /* MIME8TO7 */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires MIME8TO7 support\n", OPTNAME); #endif /* MIME8TO7 */ break; case 'A': /* set default alias file */ if (val[0] == '\0') { char *al; SET_OPT_DEFAULT(al, "aliases"); setalias(al); } else setalias(val); break; case 'a': /* look N minutes for "@:@" in alias file */ if (val[0] == '\0') SafeAlias = 5 MINUTES; else SafeAlias = convtime(val, 'm'); break; case 'B': /* substitution for blank character */ SpaceSub = val[0]; if (SpaceSub == '\0') SpaceSub = ' '; break; case 'b': /* min blocks free on queue fs/max msg size */ p = strchr(val, '/'); if (p != NULL) { *p++ = '\0'; MaxMessageSize = atol(p); } MinBlocksFree = atol(val); break; case 'c': /* don't connect to "expensive" mailers */ NoConnect = atobool(val); break; case 'C': /* checkpoint every N addresses */ if (safe || CheckpointInterval > atoi(val)) CheckpointInterval = atoi(val); break; case 'd': /* delivery mode */ switch (*val) { case '\0': set_delivery_mode(SM_DELIVER, e); break; case SM_QUEUE: /* queue only */ case SM_DEFER: /* queue only and defer map lookups */ case SM_DELIVER: /* do everything */ case SM_FORK: /* fork after verification */ #if _FFR_DM_ONE /* deliver first TA in background, then queue */ case SM_DM_ONE: #endif /* _FFR_DM_ONE */ set_delivery_mode(*val, e); break; #if _FFR_PROXY case SM_PROXY_REQ: set_delivery_mode(*val, e); break; #endif /* _FFR_PROXY */ default: syserr("Unknown delivery mode %c", *val); finis(false, true, EX_USAGE); } break; case 'E': /* error message header/header file */ if (*val != '\0') ErrMsgFile = newstr(val); break; case 'e': /* set error processing mode */ switch (*val) { case EM_QUIET: /* be silent about it */ case EM_MAIL: /* mail back */ case EM_BERKNET: /* do berknet error processing */ case EM_WRITE: /* write back (or mail) */ case EM_PRINT: /* print errors normally (default) */ e->e_errormode = *val; break; } break; case 'F': /* file mode */ FileMode = atooct(val) & 0777; break; case 'f': /* save Unix-style From lines on front */ SaveFrom = atobool(val); break; case 'G': /* match recipients against GECOS field */ MatchGecos = atobool(val); break; case 'g': /* default gid */ g_opt: if (isascii(*val) && isdigit(*val)) DefGid = atoi(val); else { register struct group *gr; DefGid = -1; gr = getgrnam(val); if (gr == NULL) syserr("readcf: option %c: unknown group %s", opt, val); else DefGid = gr->gr_gid; } break; case 'H': /* help file */ if (val[0] == '\0') { SET_OPT_DEFAULT(HelpFile, "helpfile"); } else { CANONIFY(val); HelpFile = newstr(val); } break; case 'h': /* maximum hop count */ MaxHopCount = atoi(val); break; case 'I': /* use internet domain name server */ #if NAMED_BIND for (p = val; *p != 0; ) { bool clearmode; char *q; struct resolverflags *rfp; while (*p == ' ') p++; if (*p == '\0') break; clearmode = false; if (*p == '-') clearmode = true; else if (*p != '+') p--; p++; q = p; while (*p != '\0' && !(isascii(*p) && isspace(*p))) p++; if (*p != '\0') *p++ = '\0'; if (sm_strcasecmp(q, "HasWildcardMX") == 0) { HasWildcardMX = !clearmode; continue; } if (sm_strcasecmp(q, "WorkAroundBrokenAAAA") == 0) { WorkAroundBrokenAAAA = !clearmode; continue; } for (rfp = ResolverFlags; rfp->rf_name != NULL; rfp++) { if (sm_strcasecmp(q, rfp->rf_name) == 0) break; } if (rfp->rf_name == NULL) syserr("readcf: I option value %s unrecognized", q); else if (clearmode) _res.options &= ~rfp->rf_bits; else _res.options |= rfp->rf_bits; } if (tTd(8, 2)) sm_dprintf("_res.options = %x, HasWildcardMX = %d\n", (unsigned int) _res.options, HasWildcardMX); #else /* NAMED_BIND */ usrerr("name server (I option) specified but BIND not compiled in"); #endif /* NAMED_BIND */ break; case 'i': /* ignore dot lines in message */ IgnrDot = atobool(val); break; case 'j': /* send errors in MIME (RFC 1341) format */ SendMIMEErrors = atobool(val); break; case 'J': /* .forward search path */ CANONIFY(val); ForwardPath = newstr(val); break; case 'k': /* connection cache size */ MaxMciCache = atoi(val); if (MaxMciCache < 0) MaxMciCache = 0; break; case 'K': /* connection cache timeout */ MciCacheTimeout = convtime(val, 'm'); break; case 'l': /* use Errors-To: header */ UseErrorsTo = atobool(val); break; case 'L': /* log level */ if (safe || LogLevel < atoi(val)) LogLevel = atoi(val); break; case 'M': /* define macro */ sticky = false; mid = macid_parse(val, &ep); if (mid == 0) break; p = newstr(ep); if (!safe) cleanstrcpy(p, p, strlen(p) + 1); macdefine(&CurEnv->e_macro, A_TEMP, mid, p); break; case 'm': /* send to me too */ MeToo = atobool(val); break; case 'n': /* validate RHS in newaliases */ CheckAliases = atobool(val); break; /* 'N' available -- was "net name" */ case 'O': /* daemon options */ if (!setdaemonoptions(val)) syserr("too many daemons defined (%d max)", MAXDAEMONS); break; case 'o': /* assume old style headers */ if (atobool(val)) CurEnv->e_flags |= EF_OLDSTYLE; else CurEnv->e_flags &= ~EF_OLDSTYLE; break; case 'p': /* select privacy level */ p = val; for (;;) { register struct prival *pv; extern struct prival PrivacyValues[]; while (isascii(*p) && (isspace(*p) || ispunct(*p))) p++; if (*p == '\0') break; val = p; while (isascii(*p) && isalnum(*p)) p++; if (*p != '\0') *p++ = '\0'; for (pv = PrivacyValues; pv->pv_name != NULL; pv++) { if (sm_strcasecmp(val, pv->pv_name) == 0) break; } if (pv->pv_name == NULL) syserr("readcf: Op line: %s unrecognized", val); else PrivacyFlags |= pv->pv_flag; } sticky = false; break; case 'P': /* postmaster copy address for returned mail */ PostMasterCopy = newstr(val); break; case 'q': /* slope of queue only function */ QueueFactor = atoi(val); break; case 'Q': /* queue directory */ if (val[0] == '\0') { QueueDir = "mqueue"; } else { QueueDir = newstr(val); } if (RealUid != 0 && !safe) Warn_Q_option = true; break; case 'R': /* don't prune routes */ DontPruneRoutes = atobool(val); break; case 'r': /* read timeout */ if (subopt == NULL) inittimeouts(val, sticky); else settimeout(subopt, val, sticky); break; case 'S': /* status file */ if (val[0] == '\0') { SET_OPT_DEFAULT(StatFile, "statistics"); } else { CANONIFY(val); StatFile = newstr(val); } break; case 's': /* be super safe, even if expensive */ if (tolower(*val) == 'i') SuperSafe = SAFE_INTERACTIVE; else if (tolower(*val) == 'p') #if MILTER SuperSafe = SAFE_REALLY_POSTMILTER; #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: SuperSafe=PostMilter requires Milter support (-DMILTER)\n"); #endif /* MILTER */ else SuperSafe = atobool(val) ? SAFE_REALLY : SAFE_NO; break; case 'T': /* queue timeout */ p = strchr(val, '/'); if (p != NULL) { *p++ = '\0'; settimeout("queuewarn", p, sticky); } settimeout("queuereturn", val, sticky); break; case 't': /* time zone name */ TimeZoneSpec = newstr(val); break; case 'U': /* location of user database */ UdbSpec = newstr(val); break; case 'u': /* set default uid */ for (p = val; *p != '\0'; p++) { # if _FFR_DOTTED_USERNAMES if (*p == '/' || *p == ':') # else /* _FFR_DOTTED_USERNAMES */ if (*p == '.' || *p == '/' || *p == ':') # endif /* _FFR_DOTTED_USERNAMES */ { *p++ = '\0'; break; } } if (isascii(*val) && isdigit(*val)) { DefUid = atoi(val); setdefuser(); } else { register struct passwd *pw; DefUid = -1; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option u: unknown user %s", val); break; } else { DefUid = pw->pw_uid; DefGid = pw->pw_gid; DefUser = newstr(pw->pw_name); } } # ifdef UID_MAX if (DefUid > UID_MAX) { syserr("readcf: option u: uid value (%ld) > UID_MAX (%ld); ignored", (long)DefUid, (long)UID_MAX); break; } # endif /* UID_MAX */ /* handle the group if it is there */ if (*p == '\0') break; val = p; goto g_opt; case 'V': /* fallback MX host */ if (val[0] != '\0') FallbackMX = newstr(val); break; case 'v': /* run in verbose mode */ Verbose = atobool(val) ? 1 : 0; break; case 'w': /* if we are best MX, try host directly */ TryNullMXList = atobool(val); break; /* 'W' available -- was wizard password */ case 'x': /* load avg at which to auto-queue msgs */ QueueLA = atoi(val); break; case 'X': /* load avg at which to auto-reject connections */ RefuseLA = atoi(val); break; case O_DELAY_LA: /* load avg at which to delay connections */ DelayLA = atoi(val); break; case 'y': /* work recipient factor */ WkRecipFact = atoi(val); break; case 'Y': /* fork jobs during queue runs */ ForkQueueRuns = atobool(val); break; case 'z': /* work message class factor */ WkClassFact = atoi(val); break; case 'Z': /* work time factor */ WkTimeFact = atoi(val); break; #if _FFR_QUEUE_GROUP_SORTORDER /* coordinate this with makequeue() */ #endif /* _FFR_QUEUE_GROUP_SORTORDER */ case O_QUEUESORTORD: /* queue sorting order */ switch (*val) { case 'f': /* File Name */ case 'F': QueueSortOrder = QSO_BYFILENAME; break; case 'h': /* Host first */ case 'H': QueueSortOrder = QSO_BYHOST; break; case 'm': /* Modification time */ case 'M': QueueSortOrder = QSO_BYMODTIME; break; case 'p': /* Priority order */ case 'P': QueueSortOrder = QSO_BYPRIORITY; break; case 't': /* Submission time */ case 'T': QueueSortOrder = QSO_BYTIME; break; case 'r': /* Random */ case 'R': QueueSortOrder = QSO_RANDOM; break; #if _FFR_RHS case 's': /* Shuffled host name */ case 'S': QueueSortOrder = QSO_BYSHUFFLE; break; #endif /* _FFR_RHS */ case 'n': /* none */ case 'N': QueueSortOrder = QSO_NONE; break; default: syserr("Invalid queue sort order \"%s\"", val); } break; case O_HOSTSFILE: /* pathname of /etc/hosts file */ CANONIFY(val); HostsFile = newstr(val); break; case O_MQA: /* minimum queue age between deliveries */ MinQueueAge = convtime(val, 'm'); break; case O_MAX_QUEUE_AGE: MaxQueueAge = convtime(val, 'm'); break; case O_DEFCHARSET: /* default character set for mimefying */ DefaultCharSet = newstr(denlstring(val, true, true)); break; case O_SSFILE: /* service switch file */ CANONIFY(val); ServiceSwitchFile = newstr(val); break; case O_DIALDELAY: /* delay for dial-on-demand operation */ DialDelay = convtime(val, 's'); break; case O_NORCPTACTION: /* what to do if no recipient */ if (sm_strcasecmp(val, "none") == 0) NoRecipientAction = NRA_NO_ACTION; else if (sm_strcasecmp(val, "add-to") == 0) NoRecipientAction = NRA_ADD_TO; else if (sm_strcasecmp(val, "add-apparently-to") == 0) NoRecipientAction = NRA_ADD_APPARENTLY_TO; else if (sm_strcasecmp(val, "add-bcc") == 0) NoRecipientAction = NRA_ADD_BCC; else if (sm_strcasecmp(val, "add-to-undisclosed") == 0) NoRecipientAction = NRA_ADD_TO_UNDISCLOSED; else syserr("Invalid NoRecipientAction: %s", val); break; case O_SAFEFILEENV: /* chroot() environ for writing to files */ if (*val == '\0') break; /* strip trailing slashes */ p = val + strlen(val) - 1; while (p >= val && *p == '/') *p-- = '\0'; if (*val == '\0') break; SafeFileEnv = newstr(val); break; case O_MAXMSGSIZE: /* maximum message size */ MaxMessageSize = atol(val); break; case O_COLONOKINADDR: /* old style handling of colon addresses */ ColonOkInAddr = atobool(val); break; case O_MAXQUEUERUN: /* max # of jobs in a single queue run */ MaxQueueRun = atoi(val); break; case O_MAXCHILDREN: /* max # of children of daemon */ MaxChildren = atoi(val); break; case O_MAXQUEUECHILDREN: /* max # of children of daemon */ MaxQueueChildren = atoi(val); break; case O_MAXRUNNERSPERQUEUE: /* max # runners in a queue group */ MaxRunnersPerQueue = atoi(val); break; case O_NICEQUEUERUN: /* nice queue runs */ #if !HASNICE (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: NiceQueueRun set on system that doesn't support nice()\n"); #endif /* !HASNICE */ /* XXX do we want to check the range? > 0 ? */ NiceQueueRun = atoi(val); break; case O_SHMKEY: /* shared memory key */ #if SM_CONF_SHM ShmKey = atol(val); #else /* SM_CONF_SHM */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires shared memory support (-DSM_CONF_SHM)\n", OPTNAME); #endif /* SM_CONF_SHM */ break; case O_SHMKEYFILE: /* shared memory key file */ #if SM_CONF_SHM SET_STRING_EXP(ShmKeyFile); #else /* SM_CONF_SHM */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires shared memory support (-DSM_CONF_SHM)\n", OPTNAME); break; #endif /* SM_CONF_SHM */ #if _FFR_MAX_FORWARD_ENTRIES case O_MAXFORWARD: /* max # of forward entries */ MaxForwardEntries = atoi(val); break; #endif /* _FFR_MAX_FORWARD_ENTRIES */ case O_KEEPCNAMES: /* don't expand CNAME records */ DontExpandCnames = atobool(val); break; case O_MUSTQUOTE: /* must quote these characters in phrases */ (void) sm_strlcpy(buf, "@,;:\\()[]", sizeof(buf)); if (strlen(val) < sizeof(buf) - 10) (void) sm_strlcat(buf, val, sizeof(buf)); else (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MustQuoteChars too long, ignored.\n"); MustQuoteChars = newstr(buf); break; case O_SMTPGREETING: /* SMTP greeting message (old $e macro) */ SmtpGreeting = newstr(munchstring(val, NULL, '\0')); break; case O_UNIXFROM: /* UNIX From_ line (old $l macro) */ UnixFromLine = newstr(munchstring(val, NULL, '\0')); break; case O_OPCHARS: /* operator characters (old $o macro) */ if (OperatorChars != NULL) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: OperatorChars is being redefined.\n It should only be set before ruleset definitions.\n"); OperatorChars = newstr(munchstring(val, NULL, '\0')); break; case O_DONTINITGRPS: /* don't call initgroups(3) */ DontInitGroups = atobool(val); break; case O_SLFH: /* make sure from fits on one line */ SingleLineFromHeader = atobool(val); break; case O_ABH: /* allow HELO commands with syntax errors */ AllowBogusHELO = atobool(val); break; case O_CONNTHROT: /* connection rate throttle */ ConnRateThrottle = atoi(val); break; case O_UGW: /* group writable files are unsafe */ if (!atobool(val)) { setbitn(DBS_GROUPWRITABLEFORWARDFILESAFE, DontBlameSendmail); setbitn(DBS_GROUPWRITABLEINCLUDEFILESAFE, DontBlameSendmail); } break; case O_DBLBOUNCE: /* address to which to send double bounces */ DoubleBounceAddr = newstr(val); break; case O_HSDIR: /* persistent host status directory */ if (val[0] != '\0') { CANONIFY(val); HostStatDir = newstr(val); } break; case O_SINGTHREAD: /* single thread deliveries (requires hsdir) */ SingleThreadDelivery = atobool(val); break; case O_RUNASUSER: /* run bulk of code as this user */ for (p = val; *p != '\0'; p++) { # if _FFR_DOTTED_USERNAMES if (*p == '/' || *p == ':') # else /* _FFR_DOTTED_USERNAMES */ if (*p == '.' || *p == '/' || *p == ':') # endif /* _FFR_DOTTED_USERNAMES */ { *p++ = '\0'; break; } } if (isascii(*val) && isdigit(*val)) { if (can_setuid) RunAsUid = atoi(val); } else { register struct passwd *pw; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option RunAsUser: unknown user %s", val); break; } else if (can_setuid) { if (*p == '\0') RunAsUserName = newstr(val); RunAsUid = pw->pw_uid; RunAsGid = pw->pw_gid; } else if (EffGid == pw->pw_gid) RunAsGid = pw->pw_gid; else if (UseMSP && *p == '\0') (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%ld, want=%ld)\n", (long) EffGid, (long) pw->pw_gid); } # ifdef UID_MAX if (RunAsUid > UID_MAX) { syserr("readcf: option RunAsUser: uid value (%ld) > UID_MAX (%ld); ignored", (long) RunAsUid, (long) UID_MAX); break; } # endif /* UID_MAX */ if (*p != '\0') { if (isascii(*p) && isdigit(*p)) { gid_t runasgid; runasgid = (gid_t) atoi(p); if (can_setuid || EffGid == runasgid) RunAsGid = runasgid; else if (UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%ld, want=%ld)\n", (long) EffGid, (long) runasgid); } else { register struct group *gr; gr = getgrnam(p); if (gr == NULL) syserr("readcf: option RunAsUser: unknown group %s", p); else if (can_setuid || EffGid == gr->gr_gid) RunAsGid = gr->gr_gid; else if (UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "WARNING: RunAsUser for MSP ignored, check group ids (egid=%ld, want=%ld)\n", (long) EffGid, (long) gr->gr_gid); } } if (tTd(47, 5)) sm_dprintf("readcf: RunAsUser = %d:%d\n", (int) RunAsUid, (int) RunAsGid); break; case O_DSN_RRT: RrtImpliesDsn = atobool(val); break; case O_PIDFILE: PSTRSET(PidFile, val); break; case O_DONTBLAMESENDMAIL: p = val; for (;;) { register struct dbsval *dbs; extern struct dbsval DontBlameSendmailValues[]; while (isascii(*p) && (isspace(*p) || ispunct(*p))) p++; if (*p == '\0') break; val = p; while (isascii(*p) && isalnum(*p)) p++; if (*p != '\0') *p++ = '\0'; for (dbs = DontBlameSendmailValues; dbs->dbs_name != NULL; dbs++) { if (sm_strcasecmp(val, dbs->dbs_name) == 0) break; } if (dbs->dbs_name == NULL) syserr("readcf: DontBlameSendmail option: %s unrecognized", val); else if (dbs->dbs_flag == DBS_SAFE) clrbitmap(DontBlameSendmail); else setbitn(dbs->dbs_flag, DontBlameSendmail); } sticky = false; break; case O_DPI: if (sm_strcasecmp(val, "loopback") == 0) DontProbeInterfaces = DPI_SKIPLOOPBACK; else if (atobool(val)) DontProbeInterfaces = DPI_PROBENONE; else DontProbeInterfaces = DPI_PROBEALL; break; case O_MAXRCPT: MaxRcptPerMsg = atoi(val); break; case O_RCPTTHROT: BadRcptThrottle = atoi(val); break; #if _FFR_RCPTTHROTDELAY case O_RCPTTHROTDELAY: BadRcptThrottleDelay = atoi(val); break; #endif /* _FFR_RCPTTHROTDELAY */ case O_DEADLETTER: CANONIFY(val); PSTRSET(DeadLetterDrop, val); break; #if _FFR_DONTLOCKFILESFORREAD_OPTION case O_DONTLOCK: DontLockReadFiles = atobool(val); break; #endif /* _FFR_DONTLOCKFILESFORREAD_OPTION */ case O_MAXALIASRCSN: MaxAliasRecursion = atoi(val); break; case O_CNCTONLYTO: /* XXX should probably use gethostbyname */ #if NETINET || NETINET6 ConnectOnlyTo.sa.sa_family = AF_UNSPEC; # if NETINET6 if (anynet_pton(AF_INET6, val, &ConnectOnlyTo.sin6.sin6_addr) == 1) ConnectOnlyTo.sa.sa_family = AF_INET6; else # endif /* NETINET6 */ # if NETINET { ConnectOnlyTo.sin.sin_addr.s_addr = inet_addr(val); if (ConnectOnlyTo.sin.sin_addr.s_addr != INADDR_NONE) ConnectOnlyTo.sa.sa_family = AF_INET; } # endif /* NETINET */ if (ConnectOnlyTo.sa.sa_family == AF_UNSPEC) { syserr("readcf: option ConnectOnlyTo: invalid IP address %s", val); break; } #endif /* NETINET || NETINET6 */ break; case O_TRUSTUSER: # if !HASFCHOWN && !defined(_FFR_DROP_TRUSTUSER_WARNING) if (!UseMSP) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "readcf: option TrustedUser may cause problems on systems\n which do not support fchown() if UseMSP is not set.\n"); # endif /* !HASFCHOWN && !defined(_FFR_DROP_TRUSTUSER_WARNING) */ if (isascii(*val) && isdigit(*val)) TrustedUid = atoi(val); else { register struct passwd *pw; TrustedUid = 0; pw = sm_getpwnam(val); if (pw == NULL) { syserr("readcf: option TrustedUser: unknown user %s", val); break; } else TrustedUid = pw->pw_uid; } # ifdef UID_MAX if (TrustedUid > UID_MAX) { syserr("readcf: option TrustedUser: uid value (%ld) > UID_MAX (%ld)", (long) TrustedUid, (long) UID_MAX); TrustedUid = 0; } # endif /* UID_MAX */ break; case O_MAXMIMEHDRLEN: p = strchr(val, '/'); if (p != NULL) *p++ = '\0'; MaxMimeHeaderLength = atoi(val); if (p != NULL && *p != '\0') MaxMimeFieldLength = atoi(p); else MaxMimeFieldLength = MaxMimeHeaderLength / 2; if (MaxMimeHeaderLength <= 0) MaxMimeHeaderLength = 0; else if (MaxMimeHeaderLength < 128) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxMimeHeaderLength: header length limit set lower than 128\n"); if (MaxMimeFieldLength <= 0) MaxMimeFieldLength = 0; else if (MaxMimeFieldLength < 40) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxMimeHeaderLength: field length limit set lower than 40\n"); /* ** Headers field values now include leading space, so let's ** adjust the values to be "backward compatible". */ if (MaxMimeHeaderLength > 0) MaxMimeHeaderLength++; if (MaxMimeFieldLength > 0) MaxMimeFieldLength++; break; case O_CONTROLSOCKET: PSTRSET(ControlSocketName, val); break; case O_MAXHDRSLEN: MaxHeadersLength = atoi(val); if (MaxHeadersLength > 0 && MaxHeadersLength < (MAXHDRSLEN / 2)) (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: MaxHeadersLength: headers length limit set lower than %d\n", (MAXHDRSLEN / 2)); break; case O_PROCTITLEPREFIX: PSTRSET(ProcTitlePrefix, val); break; #if SASL case O_SASLINFO: # if _FFR_ALLOW_SASLINFO /* ** Allow users to select their own authinfo file ** under certain circumstances, otherwise just ignore ** the option. If the option isn't ignored, several ** commands don't work very well, e.g., mailq. ** However, this is not a "perfect" solution. ** If mail is queued, the authentication info ** will not be used in subsequent delivery attempts. ** If we really want to support this, then it has ** to be stored in the queue file. */ if (!bitset(SUBMIT_MSA, SubmitMode) && RealUid != 0 && RunAsUid != RealUid) break; # endif /* _FFR_ALLOW_SASLINFO */ PSTRSET(SASLInfo, val); break; case O_SASLMECH: if (AuthMechanisms != NULL) sm_free(AuthMechanisms); /* XXX */ if (*val != '\0') AuthMechanisms = newstr(val); else AuthMechanisms = NULL; break; case O_SASLREALM: if (AuthRealm != NULL) sm_free(AuthRealm); if (*val != '\0') AuthRealm = newstr(val); else AuthRealm = NULL; break; case O_SASLOPTS: while (val != NULL && *val != '\0') { switch (*val) { case 'A': SASLOpts |= SASL_AUTH_AUTH; break; case 'a': SASLOpts |= SASL_SEC_NOACTIVE; break; case 'c': SASLOpts |= SASL_SEC_PASS_CREDENTIALS; break; case 'd': SASLOpts |= SASL_SEC_NODICTIONARY; break; case 'f': SASLOpts |= SASL_SEC_FORWARD_SECRECY; break; # if SASL >= 20101 case 'm': SASLOpts |= SASL_SEC_MUTUAL_AUTH; break; # endif /* SASL >= 20101 */ case 'p': SASLOpts |= SASL_SEC_NOPLAINTEXT; break; case 'y': SASLOpts |= SASL_SEC_NOANONYMOUS; break; case ' ': /* ignore */ case '\t': /* ignore */ case ',': /* ignore */ break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s unknown parameter '%c'\n", OPTNAME, (isascii(*val) && isprint(*val)) ? *val : '?'); break; } ++val; val = strpbrk(val, ", \t"); if (val != NULL) ++val; } break; case O_SASLBITS: MaxSLBits = atoi(val); break; #else /* SASL */ case O_SASLINFO: case O_SASLMECH: case O_SASLREALM: case O_SASLOPTS: case O_SASLBITS: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires SASL support (-DSASL)\n", OPTNAME); break; #endif /* SASL */ #if STARTTLS case O_SRVCERTFILE: SET_STRING_EXP(SrvCertFile); case O_SRVKEYFILE: SET_STRING_EXP(SrvKeyFile); case O_CLTCERTFILE: SET_STRING_EXP(CltCertFile); case O_CLTKEYFILE: SET_STRING_EXP(CltKeyFile); case O_CACERTFILE: SET_STRING_EXP(CACertFile); case O_CACERTPATH: SET_STRING_EXP(CACertPath); case O_DHPARAMS: SET_STRING_EXP(DHParams); case O_CIPHERLIST: SET_STRING_EXP(CipherList); case O_DIG_ALG: SET_STRING_EXP(CertFingerprintAlgorithm); case O_SRV_SSL_OPTIONS: pssloptions = &Srv_SSL_Options; case O_CLT_SSL_OPTIONS: if (pssloptions == NULL) pssloptions = &Clt_SSL_Options; (void) readssloptions(o->o_name, val, pssloptions, '\0'); if (tTd(37, 8)) sm_dprintf("ssloptions=%#lx\n", *pssloptions); pssloptions = NULL; break; case O_CRLFILE: # if OPENSSL_VERSION_NUMBER > 0x00907000L SET_STRING_EXP(CRLFile); # else /* OPENSSL_VERSION_NUMBER > 0x00907000L */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires at least OpenSSL 0.9.7\n", OPTNAME); break; # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # if _FFR_CRLPATH case O_CRLPATH: # if OPENSSL_VERSION_NUMBER > 0x00907000L SET_STRING_EXP(CRLPath); # else /* OPENSSL_VERSION_NUMBER > 0x00907000L */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires at least OpenSSL 0.9.7\n", OPTNAME); break; # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */ # endif /* _FFR_CRLPATH */ /* ** XXX How about options per daemon/client instead of globally? ** This doesn't work well for some options, e.g., no server cert, ** but fine for others. ** ** XXX Some people may want different certs per server. ** ** See also srvfeatures() */ case O_TLS_SRV_OPTS: while (val != NULL && *val != '\0') { switch (*val) { case 'V': TLS_Srv_Opts |= TLS_I_NO_VRFY; break; /* ** Server without a cert? That works only if ** AnonDH is enabled as cipher, which is not in the ** default list. Hence the CipherList option must ** be available. Moreover: which clients support this ** besides sendmail with this setting? */ case 'C': TLS_Srv_Opts &= ~TLS_I_SRV_CERT; break; case ' ': /* ignore */ case '\t': /* ignore */ case ',': /* ignore */ break; default: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s unknown parameter '%c'\n", OPTNAME, (isascii(*val) && isprint(*val)) ? *val : '?'); break; } ++val; val = strpbrk(val, ", \t"); if (val != NULL) ++val; } break; case O_RANDFILE: PSTRSET(RandFile, val); break; #else /* STARTTLS */ case O_SRVCERTFILE: case O_SRVKEYFILE: case O_CLTCERTFILE: case O_CLTKEYFILE: case O_CACERTFILE: case O_CACERTPATH: case O_DHPARAMS: case O_SRV_SSL_OPTIONS: case O_CLT_SSL_OPTIONS: case O_CIPHERLIST: case O_CRLFILE: # if _FFR_CRLPATH case O_CRLPATH: # endif /* _FFR_CRLPATH */ case O_RANDFILE: (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires TLS support\n", OPTNAME); break; #endif /* STARTTLS */ #if STARTTLS && _FFR_FIPSMODE case O_FIPSMODE: FipsMode = atobool(val); break; #endif /* STARTTLS && _FFR_FIPSMODE */ case O_CLIENTPORT: setclientoptions(val); break; case O_DF_BUFSIZE: DataFileBufferSize = atoi(val); break; case O_XF_BUFSIZE: XscriptFileBufferSize = atoi(val); break; case O_LDAPDEFAULTSPEC: #if LDAPMAP ldapmap_set_defaults(val); #else /* LDAPMAP */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires LDAP support (-DLDAPMAP)\n", OPTNAME); #endif /* LDAPMAP */ break; case O_INPUTMILTER: #if MILTER InputFilterList = newstr(val); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires Milter support (-DMILTER)\n", OPTNAME); #endif /* MILTER */ break; case O_MILTER: #if MILTER milter_set_option(subopt, val, sticky); #else /* MILTER */ (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "Warning: Option: %s requires Milter support (-DMILTER)\n", OPTNAME); #endif /* MILTER */ break; case O_QUEUE_FILE_MODE: /* queue file mode */ QueueFileMode = atooct(val) & 0777; break; case O_DLVR_MIN: /* deliver by minimum time */ DeliverByMin = convtime(val, 's'); break; /* modifiers {daemon_flags} for direct submissions */ case O_DIRECTSUBMODIFIERS: { BITMAP256 m; /* ignored */ extern ENVELOPE BlankEnvelope; macdefine(&BlankEnvelope.e_macro, A_PERM, macid("{daemon_flags}"), getmodifiers(val, m)); } break; case O_FASTSPLIT: FastSplit = atoi(val); break; case O_MBDB: Mbdb = newstr(val); break; case O_MSQ: UseMSP = atobool(val); break; case O_SOFTBOUNCE: SoftBounce = atobool(val); break; case O_REJECTLOGINTERVAL: /* time btwn log msgs while refusing */ RejectLogInterval = convtime(val, 'h'); break; case O_REQUIRES_DIR_FSYNC: #if REQUIRES_DIR_FSYNC RequiresDirfsync = atobool(val); #else /* REQUIRES_DIR_FSYNC */ /* silently ignored... required for cf file option */ #endif /* REQUIRES_DIR_FSYNC */ break; case O_CONNECTION_RATE_WINDOW_SIZE: ConnectionRateWindowSize = convtime(val, 's'); break; case O_FALLBACKSMARTHOST: /* fallback smart host */ if (val[0] != '\0') FallbackSmartHost = newstr(val); break; case O_HELONAME: HeloName = newstr(val); break; #if _FFR_MEMSTAT case O_REFUSELOWMEM: RefuseLowMem = atoi(val); break; case O_QUEUELOWMEM: QueueLowMem = atoi(val); break; case O_MEMRESOURCE: MemoryResource = newstr(val); break; #endif /* _FFR_MEMSTAT */ case O_MAXNOOPCOMMANDS: MaxNOOPCommands = atoi(val); break; #if _FFR_MSG_ACCEPT case O_MSG_ACCEPT: MessageAccept = newstr(val); break; #endif /* _FFR_MSG_ACCEPT */ #if _FFR_QUEUE_RUN_PARANOIA case O_CHK_Q_RUNNERS: CheckQueueRunners = atoi(val); break; #endif /* _FFR_QUEUE_RUN_PARANOIA */ #if _FFR_EIGHT_BIT_ADDR_OK case O_EIGHT_BIT_ADDR_OK: EightBitAddrOK = atobool(val); break; #endif /* _FFR_EIGHT_BIT_ADDR_OK */ #if _FFR_ADDR_TYPE_MODES case O_ADDR_TYPE_MODES: AddrTypeModes = atobool(val); break; #endif /* _FFR_ADDR_TYPE_MODES */ #if _FFR_BADRCPT_SHUTDOWN case O_RCPTSHUTD: BadRcptShutdown = atoi(val); break; case O_RCPTSHUTDG: BadRcptShutdownGood = atoi(val); break; #endif /* _FFR_BADRCPT_SHUTDOWN */ #if _FFR_REJECT_NUL_BYTE case O_REJECTNUL: RejectNUL = atobool(val); break; #endif /* _FFR_REJECT_NUL_BYTE */ #if _FFR_BOUNCE_QUEUE case O_BOUNCEQUEUE: bouncequeue = newstr(val); break; #endif /* _FFR_BOUNCE_QUEUE */ #if _FFR_ADD_BCC case O_ADDBCC: AddBcc = atobool(val); break; #endif case O_USECOMPRESSEDIPV6ADDRESSES: UseCompressedIPv6Addresses = atobool(val); break; default: if (tTd(37, 1)) { if (isascii(opt) && isprint(opt)) sm_dprintf("Warning: option %c unknown\n", opt); else sm_dprintf("Warning: option 0x%x unknown\n", opt); } break; } /* ** Options with suboptions are responsible for taking care ** of sticky-ness (e.g., that a command line setting is kept ** when reading in the sendmail.cf file). This has to be done ** when the suboptions are parsed since each suboption must be ** sticky, not the root option. */ if (sticky && !bitset(OI_SUBOPT, o->o_flags)) setbitn(opt, StickyOpt); } /* ** SETCLASS -- set a string into a class ** ** Parameters: ** class -- the class to put the string in. ** str -- the string to enter ** ** Returns: ** none. ** ** Side Effects: ** puts the word into the symbol table. */ void setclass(class, str) int class; char *str; { register STAB *s; if ((str[0] & 0377) == MATCHCLASS) { int mid; str++; mid = macid(str); if (mid == 0) return; if (tTd(37, 8)) sm_dprintf("setclass(%s, $=%s)\n", macname(class), macname(mid)); copy_class(mid, class); } else { if (tTd(37, 8)) sm_dprintf("setclass(%s, %s)\n", macname(class), str); s = stab(str, ST_CLASS, ST_ENTER); setbitn(bitidx(class), s->s_class); } } /* ** MAKEMAPENTRY -- create a map entry ** ** Parameters: ** line -- the config file line ** ** Returns: ** A pointer to the map that has been created. ** NULL if there was a syntax error. ** ** Side Effects: ** Enters the map into the dictionary. */ MAP * makemapentry(line) char *line; { register char *p; char *mapname; char *classname; register STAB *s; STAB *class; for (p = line; isascii(*p) && isspace(*p); p++) continue; if (!(isascii(*p) && isalnum(*p))) { syserr("readcf: config K line: no map name"); return NULL; } mapname = p; while ((isascii(*++p) && isalnum(*p)) || *p == '_' || *p == '.') continue; if (*p != '\0') *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; if (!(isascii(*p) && isalnum(*p))) { syserr("readcf: config K line, map %s: no map class", mapname); return NULL; } classname = p; while (isascii(*++p) && isalnum(*p)) continue; if (*p != '\0') *p++ = '\0'; while (isascii(*p) && isspace(*p)) p++; /* look up the class */ class = stab(classname, ST_MAPCLASS, ST_FIND); if (class == NULL) { syserr("readcf: map %s: class %s not available", mapname, classname); return NULL; } /* enter the map */ s = stab(mapname, ST_MAP, ST_ENTER); s->s_map.map_class = &class->s_mapclass; s->s_map.map_mname = newstr(mapname); if (class->s_mapclass.map_parse(&s->s_map, p)) s->s_map.map_mflags |= MF_VALID; if (tTd(37, 5)) { sm_dprintf("map %s, class %s, flags %lx, file %s,\n", s->s_map.map_mname, s->s_map.map_class->map_cname, s->s_map.map_mflags, s->s_map.map_file); sm_dprintf("\tapp %s, domain %s, rebuild %s\n", s->s_map.map_app, s->s_map.map_domain, s->s_map.map_rebuild); } return &s->s_map; } /* ** STRTORWSET -- convert string to rewriting set number ** ** Parameters: ** p -- the pointer to the string to decode. ** endp -- if set, store the trailing delimiter here. ** stabmode -- ST_ENTER to create this entry, ST_FIND if ** it must already exist. ** ** Returns: ** The appropriate ruleset number. ** -1 if it is not valid (error already printed) */ int strtorwset(p, endp, stabmode) char *p; char **endp; int stabmode; { int ruleset; static int nextruleset = MAXRWSETS; while (isascii(*p) && isspace(*p)) p++; if (!isascii(*p)) { syserr("invalid ruleset name: \"%.20s\"", p); return -1; } if (isdigit(*p)) { ruleset = strtol(p, endp, 10); if (ruleset >= MAXRWSETS / 2 || ruleset < 0) { syserr("bad ruleset %d (%d max)", ruleset, MAXRWSETS / 2); ruleset = -1; } } else { STAB *s; char delim; char *q = NULL; q = p; while (*p != '\0' && isascii(*p) && (isalnum(*p) || *p == '_')) p++; if (q == p || !(isascii(*q) && isalpha(*q))) { /* no valid characters */ syserr("invalid ruleset name: \"%.20s\"", q); return -1; } while (isascii(*p) && isspace(*p)) *p++ = '\0'; delim = *p; if (delim != '\0') *p = '\0'; s = stab(q, ST_RULESET, stabmode); if (delim != '\0') *p = delim; if (s == NULL) return -1; if (stabmode == ST_ENTER && delim == '=') { while (isascii(*++p) && isspace(*p)) continue; if (!(isascii(*p) && isdigit(*p))) { syserr("bad ruleset definition \"%s\" (number required after `=')", q); ruleset = -1; } else { ruleset = strtol(p, endp, 10); if (ruleset >= MAXRWSETS / 2 || ruleset < 0) { syserr("bad ruleset number %d in \"%s\" (%d max)", ruleset, q, MAXRWSETS / 2); ruleset = -1; } } } else { if (endp != NULL) *endp = p; if (s->s_ruleset >= 0) ruleset = s->s_ruleset; else if ((ruleset = --nextruleset) < MAXRWSETS / 2) { syserr("%s: too many named rulesets (%d max)", q, MAXRWSETS / 2); ruleset = -1; } } if (s->s_ruleset >= 0 && ruleset >= 0 && ruleset != s->s_ruleset) { syserr("%s: ruleset changed value (old %d, new %d)", q, s->s_ruleset, ruleset); ruleset = s->s_ruleset; } else if (ruleset >= 0) { s->s_ruleset = ruleset; } if (stabmode == ST_ENTER && ruleset >= 0) { char *h = NULL; if (RuleSetNames[ruleset] != NULL) sm_free(RuleSetNames[ruleset]); /* XXX */ if (delim != '\0' && (h = strchr(q, delim)) != NULL) *h = '\0'; RuleSetNames[ruleset] = newstr(q); if (delim == '/' && h != NULL) *h = delim; /* put back delim */ } } return ruleset; } /* ** SETTIMEOUT -- set an individual timeout ** ** Parameters: ** name -- the name of the timeout. ** val -- the value of the timeout. ** sticky -- if set, don't let other setoptions override ** this value. ** ** Returns: ** none. */ /* set if Timeout sub-option is stuck */ static BITMAP256 StickyTimeoutOpt; static struct timeoutinfo { char *to_name; /* long name of timeout */ unsigned char to_code; /* code for option */ } TimeOutTab[] = { #define TO_INITIAL 0x01 { "initial", TO_INITIAL }, #define TO_MAIL 0x02 { "mail", TO_MAIL }, #define TO_RCPT 0x03 { "rcpt", TO_RCPT }, #define TO_DATAINIT 0x04 { "datainit", TO_DATAINIT }, #define TO_DATABLOCK 0x05 { "datablock", TO_DATABLOCK }, #define TO_DATAFINAL 0x06 { "datafinal", TO_DATAFINAL }, #define TO_COMMAND 0x07 { "command", TO_COMMAND }, #define TO_RSET 0x08 { "rset", TO_RSET }, #define TO_HELO 0x09 { "helo", TO_HELO }, #define TO_QUIT 0x0A { "quit", TO_QUIT }, #define TO_MISC 0x0B { "misc", TO_MISC }, #define TO_IDENT 0x0C { "ident", TO_IDENT }, #define TO_FILEOPEN 0x0D { "fileopen", TO_FILEOPEN }, #define TO_CONNECT 0x0E { "connect", TO_CONNECT }, #define TO_ICONNECT 0x0F { "iconnect", TO_ICONNECT }, #define TO_QUEUEWARN 0x10 { "queuewarn", TO_QUEUEWARN }, { "queuewarn.*", TO_QUEUEWARN }, #define TO_QUEUEWARN_NORMAL 0x11 { "queuewarn.normal", TO_QUEUEWARN_NORMAL }, #define TO_QUEUEWARN_URGENT 0x12 { "queuewarn.urgent", TO_QUEUEWARN_URGENT }, #define TO_QUEUEWARN_NON_URGENT 0x13 { "queuewarn.non-urgent", TO_QUEUEWARN_NON_URGENT }, #define TO_QUEUERETURN 0x14 { "queuereturn", TO_QUEUERETURN }, { "queuereturn.*", TO_QUEUERETURN }, #define TO_QUEUERETURN_NORMAL 0x15 { "queuereturn.normal", TO_QUEUERETURN_NORMAL }, #define TO_QUEUERETURN_URGENT 0x16 { "queuereturn.urgent", TO_QUEUERETURN_URGENT }, #define TO_QUEUERETURN_NON_URGENT 0x17 { "queuereturn.non-urgent", TO_QUEUERETURN_NON_URGENT }, #define TO_HOSTSTATUS 0x18 { "hoststatus", TO_HOSTSTATUS }, #define TO_RESOLVER_RETRANS 0x19 { "resolver.retrans", TO_RESOLVER_RETRANS }, #define TO_RESOLVER_RETRANS_NORMAL 0x1A { "resolver.retrans.normal", TO_RESOLVER_RETRANS_NORMAL }, #define TO_RESOLVER_RETRANS_FIRST 0x1B { "resolver.retrans.first", TO_RESOLVER_RETRANS_FIRST }, #define TO_RESOLVER_RETRY 0x1C { "resolver.retry", TO_RESOLVER_RETRY }, #define TO_RESOLVER_RETRY_NORMAL 0x1D { "resolver.retry.normal", TO_RESOLVER_RETRY_NORMAL }, #define TO_RESOLVER_RETRY_FIRST 0x1E { "resolver.retry.first", TO_RESOLVER_RETRY_FIRST }, #define TO_CONTROL 0x1F { "control", TO_CONTROL }, #define TO_LHLO 0x20 { "lhlo", TO_LHLO }, #define TO_AUTH 0x21 { "auth", TO_AUTH }, #define TO_STARTTLS 0x22 { "starttls", TO_STARTTLS }, #define TO_ACONNECT 0x23 { "aconnect", TO_ACONNECT }, #define TO_QUEUEWARN_DSN 0x24 { "queuewarn.dsn", TO_QUEUEWARN_DSN }, #define TO_QUEUERETURN_DSN 0x25 { "queuereturn.dsn", TO_QUEUERETURN_DSN }, { NULL, 0 }, }; static void settimeout(name, val, sticky) char *name; char *val; bool sticky; { register struct timeoutinfo *to; int i, addopts; time_t toval; if (tTd(37, 2)) sm_dprintf("settimeout(%s = %s)", name, val); for (to = TimeOutTab; to->to_name != NULL; to++) { if (sm_strcasecmp(to->to_name, name) == 0) break; } if (to->to_name == NULL) { errno = 0; /* avoid bogus error text */ syserr("settimeout: invalid timeout %s", name); return; } /* ** See if this option is preset for us. */ if (!sticky && bitnset(to->to_code, StickyTimeoutOpt)) { if (tTd(37, 2)) sm_dprintf(" (ignored)\n"); return; } if (tTd(37, 2)) sm_dprintf("\n"); toval = convtime(val, 'm'); addopts = 0; switch (to->to_code) { case TO_INITIAL: TimeOuts.to_initial = toval; break; case TO_MAIL: TimeOuts.to_mail = toval; break; case TO_RCPT: TimeOuts.to_rcpt = toval; break; case TO_DATAINIT: TimeOuts.to_datainit = toval; break; case TO_DATABLOCK: TimeOuts.to_datablock = toval; break; case TO_DATAFINAL: TimeOuts.to_datafinal = toval; break; case TO_COMMAND: TimeOuts.to_nextcommand = toval; break; case TO_RSET: TimeOuts.to_rset = toval; break; case TO_HELO: TimeOuts.to_helo = toval; break; case TO_QUIT: TimeOuts.to_quit = toval; break; case TO_MISC: TimeOuts.to_miscshort = toval; break; case TO_IDENT: TimeOuts.to_ident = toval; break; case TO_FILEOPEN: TimeOuts.to_fileopen = toval; break; case TO_CONNECT: TimeOuts.to_connect = toval; break; case TO_ICONNECT: TimeOuts.to_iconnect = toval; break; case TO_ACONNECT: TimeOuts.to_aconnect = toval; break; case TO_QUEUEWARN: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NORMAL] = toval; TimeOuts.to_q_warning[TOC_URGENT] = toval; TimeOuts.to_q_warning[TOC_NONURGENT] = toval; TimeOuts.to_q_warning[TOC_DSN] = toval; addopts = 2; break; case TO_QUEUEWARN_NORMAL: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NORMAL] = toval; break; case TO_QUEUEWARN_URGENT: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_URGENT] = toval; break; case TO_QUEUEWARN_NON_URGENT: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_NONURGENT] = toval; break; case TO_QUEUEWARN_DSN: toval = convtime(val, 'h'); TimeOuts.to_q_warning[TOC_DSN] = toval; break; case TO_QUEUERETURN: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NORMAL] = toval; TimeOuts.to_q_return[TOC_URGENT] = toval; TimeOuts.to_q_return[TOC_NONURGENT] = toval; TimeOuts.to_q_return[TOC_DSN] = toval; addopts = 2; break; case TO_QUEUERETURN_NORMAL: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NORMAL] = toval; break; case TO_QUEUERETURN_URGENT: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_URGENT] = toval; break; case TO_QUEUERETURN_NON_URGENT: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_NONURGENT] = toval; break; case TO_QUEUERETURN_DSN: toval = convtime(val, 'd'); TimeOuts.to_q_return[TOC_DSN] = toval; break; case TO_HOSTSTATUS: MciInfoTimeout = toval; break; case TO_RESOLVER_RETRANS: toval = convtime(val, 's'); TimeOuts.res_retrans[RES_TO_DEFAULT] = toval; TimeOuts.res_retrans[RES_TO_FIRST] = toval; TimeOuts.res_retrans[RES_TO_NORMAL] = toval; addopts = 2; break; case TO_RESOLVER_RETRY: i = atoi(val); TimeOuts.res_retry[RES_TO_DEFAULT] = i; TimeOuts.res_retry[RES_TO_FIRST] = i; TimeOuts.res_retry[RES_TO_NORMAL] = i; addopts = 2; break; case TO_RESOLVER_RETRANS_NORMAL: TimeOuts.res_retrans[RES_TO_NORMAL] = convtime(val, 's'); break; case TO_RESOLVER_RETRY_NORMAL: TimeOuts.res_retry[RES_TO_NORMAL] = atoi(val); break; case TO_RESOLVER_RETRANS_FIRST: TimeOuts.res_retrans[RES_TO_FIRST] = convtime(val, 's'); break; case TO_RESOLVER_RETRY_FIRST: TimeOuts.res_retry[RES_TO_FIRST] = atoi(val); break; case TO_CONTROL: TimeOuts.to_control = toval; break; case TO_LHLO: TimeOuts.to_lhlo = toval; break; #if SASL case TO_AUTH: TimeOuts.to_auth = toval; break; #endif /* SASL */ #if STARTTLS case TO_STARTTLS: TimeOuts.to_starttls = toval; break; #endif /* STARTTLS */ default: syserr("settimeout: invalid timeout %s", name); break; } if (sticky) { for (i = 0; i <= addopts; i++) setbitn(to->to_code + i, StickyTimeoutOpt); } } /* ** INITTIMEOUTS -- parse and set timeout values ** ** Parameters: ** val -- a pointer to the values. If NULL, do initial ** settings. ** sticky -- if set, don't let other setoptions override ** this suboption value. ** ** Returns: ** none. ** ** Side Effects: ** Initializes the TimeOuts structure */ void inittimeouts(val, sticky) register char *val; bool sticky; { register char *p; if (tTd(37, 2)) sm_dprintf("inittimeouts(%s)\n", val == NULL ? "" : val); if (val == NULL) { TimeOuts.to_connect = (time_t) 0 SECONDS; TimeOuts.to_aconnect = (time_t) 0 SECONDS; TimeOuts.to_iconnect = (time_t) 0 SECONDS; TimeOuts.to_initial = (time_t) 5 MINUTES; TimeOuts.to_helo = (time_t) 5 MINUTES; TimeOuts.to_mail = (time_t) 10 MINUTES; TimeOuts.to_rcpt = (time_t) 1 HOUR; TimeOuts.to_datainit = (time_t) 5 MINUTES; TimeOuts.to_datablock = (time_t) 1 HOUR; TimeOuts.to_datafinal = (time_t) 1 HOUR; TimeOuts.to_rset = (time_t) 5 MINUTES; TimeOuts.to_quit = (time_t) 2 MINUTES; TimeOuts.to_nextcommand = (time_t) 1 HOUR; TimeOuts.to_miscshort = (time_t) 2 MINUTES; #if IDENTPROTO TimeOuts.to_ident = (time_t) 5 SECONDS; #else /* IDENTPROTO */ TimeOuts.to_ident = (time_t) 0 SECONDS; #endif /* IDENTPROTO */ TimeOuts.to_fileopen = (time_t) 60 SECONDS; TimeOuts.to_control = (time_t) 2 MINUTES; TimeOuts.to_lhlo = (time_t) 2 MINUTES; #if SASL TimeOuts.to_auth = (time_t) 10 MINUTES; #endif /* SASL */ #if STARTTLS TimeOuts.to_starttls = (time_t) 1 HOUR; #endif /* STARTTLS */ if (tTd(37, 5)) { sm_dprintf("Timeouts:\n"); sm_dprintf(" connect = %ld\n", (long) TimeOuts.to_connect); sm_dprintf(" aconnect = %ld\n", (long) TimeOuts.to_aconnect); sm_dprintf(" initial = %ld\n", (long) TimeOuts.to_initial); sm_dprintf(" helo = %ld\n", (long) TimeOuts.to_helo); sm_dprintf(" mail = %ld\n", (long) TimeOuts.to_mail); sm_dprintf(" rcpt = %ld\n", (long) TimeOuts.to_rcpt); sm_dprintf(" datainit = %ld\n", (long) TimeOuts.to_datainit); sm_dprintf(" datablock = %ld\n", (long) TimeOuts.to_datablock); sm_dprintf(" datafinal = %ld\n", (long) TimeOuts.to_datafinal); sm_dprintf(" rset = %ld\n", (long) TimeOuts.to_rset); sm_dprintf(" quit = %ld\n", (long) TimeOuts.to_quit); sm_dprintf(" nextcommand = %ld\n", (long) TimeOuts.to_nextcommand); sm_dprintf(" miscshort = %ld\n", (long) TimeOuts.to_miscshort); sm_dprintf(" ident = %ld\n", (long) TimeOuts.to_ident); sm_dprintf(" fileopen = %ld\n", (long) TimeOuts.to_fileopen); sm_dprintf(" lhlo = %ld\n", (long) TimeOuts.to_lhlo); sm_dprintf(" control = %ld\n", (long) TimeOuts.to_control); } return; } for (;; val = p) { while (isascii(*val) && isspace(*val)) val++; if (*val == '\0') break; for (p = val; *p != '\0' && *p != ','; p++) continue; if (*p != '\0') *p++ = '\0'; if (isascii(*val) && isdigit(*val)) { /* old syntax -- set everything */ TimeOuts.to_mail = convtime(val, 'm'); TimeOuts.to_rcpt = TimeOuts.to_mail; TimeOuts.to_datainit = TimeOuts.to_mail; TimeOuts.to_datablock = TimeOuts.to_mail; TimeOuts.to_datafinal = TimeOuts.to_mail; TimeOuts.to_nextcommand = TimeOuts.to_mail; if (sticky) { setbitn(TO_MAIL, StickyTimeoutOpt); setbitn(TO_RCPT, StickyTimeoutOpt); setbitn(TO_DATAINIT, StickyTimeoutOpt); setbitn(TO_DATABLOCK, StickyTimeoutOpt); setbitn(TO_DATAFINAL, StickyTimeoutOpt); setbitn(TO_COMMAND, StickyTimeoutOpt); } continue; } else { register char *q = strchr(val, ':'); if (q == NULL && (q = strchr(val, '=')) == NULL) { /* syntax error */ continue; } *q++ = '\0'; settimeout(val, q, sticky); } } }