2 * Copyright (c) 1998-2013 Proofpoint, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 SM_RCSID("@(#)$Id: conf.c,v 8.1192 2014-01-27 18:23:21 ca Exp $")
18 #include <sm/sendmail.h>
19 #include <sendmail/pathnames.h>
30 /* for the IPv6 device lookup */
31 # define _SOCKADDR_LEN
33 # endif /* NETINET6 */
36 # include <sys/ioctl.h>
37 # include <sys/param.h>
40 #if NETINET || NETINET6
41 # include <arpa/inet.h>
43 #if HASULIMIT && defined(HPUX11)
50 static void setupmaps __P((void));
51 static void setupmailers __P((void));
52 static void setupqueues __P((void));
53 static int get_num_procs_online __P((void));
54 static int add_hostnames __P((SOCKADDR *));
56 #if NETINET6 && NEEDSGETIPNODE
57 static struct hostent *sm_getipnodebyname __P((const char *, int, int, int *));
58 static struct hostent *sm_getipnodebyaddr __P((const void *, size_t, int, int *));
59 #else /* NETINET6 && NEEDSGETIPNODE */
60 #define sm_getipnodebyname getipnodebyname
61 #define sm_getipnodebyaddr getipnodebyaddr
62 #endif /* NETINET6 && NEEDSGETIPNODE */
66 ** CONF.C -- Sendmail Configuration Tables.
68 ** Defines the configuration of this installation.
70 ** Configuration Variables:
71 ** HdrInfo -- a table describing well-known header fields.
72 ** Each entry has the field name and some flags,
73 ** which are described in sendmail.h.
76 ** I have tried to put almost all the reasonable
77 ** configuration information into the configuration
78 ** file read at runtime. My intent is that anything
79 ** here is a function of the version of UNIX you
80 ** are running, or is really static -- for example
81 ** the headers are a superset of widely used
82 ** protocols. If you find yourself playing with
83 ** this file too much, you may be making a mistake!
89 ** Final (null) entry contains the flags used for any other field.
91 ** Not all of these are actually handled specially by sendmail
92 ** at this time. They are included as placeholders, to let
93 ** you know that "someday" I intend to have sendmail do
94 ** something with them.
97 struct hdrinfo HdrInfo[] =
99 /* originator fields, most to least significant */
100 { "resent-sender", H_FROM|H_RESENT, NULL },
101 { "resent-from", H_FROM|H_RESENT, NULL },
102 { "resent-reply-to", H_FROM|H_RESENT, NULL },
103 { "sender", H_FROM, NULL },
104 { "from", H_FROM, NULL },
105 { "reply-to", H_FROM, NULL },
106 { "errors-to", H_FROM|H_ERRORSTO, NULL },
107 { "full-name", H_ACHECK, NULL },
108 { "return-receipt-to", H_RECEIPTTO, NULL },
109 { "delivery-receipt-to", H_RECEIPTTO, NULL },
110 { "disposition-notification-to", H_FROM, NULL },
112 /* destination fields */
113 { "to", H_RCPT, NULL },
114 { "resent-to", H_RCPT|H_RESENT, NULL },
115 { "cc", H_RCPT, NULL },
116 { "resent-cc", H_RCPT|H_RESENT, NULL },
117 { "bcc", H_RCPT|H_BCC, NULL },
118 { "resent-bcc", H_RCPT|H_BCC|H_RESENT, NULL },
119 { "apparently-to", H_RCPT, NULL },
121 /* message identification and control */
122 { "message-id", 0, NULL },
123 { "resent-message-id", H_RESENT, NULL },
125 { "message", H_EOH, NULL },
126 { "text", H_EOH, NULL },
131 { "resent-date", H_RESENT, NULL },
134 { "received", H_TRACE|H_FORCE, NULL },
135 { "x400-received", H_TRACE|H_FORCE, NULL },
136 { "via", H_TRACE|H_FORCE, NULL },
137 { "mail-from", H_TRACE|H_FORCE, NULL },
139 /* miscellaneous fields */
140 { "comments", H_FORCE|H_ENCODABLE, NULL },
141 { "return-path", H_FORCE|H_ACHECK|H_BINDLATE, NULL },
142 { "content-transfer-encoding", H_CTE, NULL },
143 { "content-type", H_CTYPE, NULL },
144 { "content-length", H_ACHECK, NULL },
145 { "subject", H_ENCODABLE, NULL },
146 { "x-authentication-warning", H_FORCE, NULL },
157 struct prival PrivacyValues[] =
159 { "public", PRIV_PUBLIC },
160 { "needmailhelo", PRIV_NEEDMAILHELO },
161 { "needexpnhelo", PRIV_NEEDEXPNHELO },
162 { "needvrfyhelo", PRIV_NEEDVRFYHELO },
163 { "noexpn", PRIV_NOEXPN },
164 { "novrfy", PRIV_NOVRFY },
165 { "restrictexpand", PRIV_RESTRICTEXPAND },
166 { "restrictmailq", PRIV_RESTRICTMAILQ },
167 { "restrictqrun", PRIV_RESTRICTQRUN },
168 { "noetrn", PRIV_NOETRN },
169 { "noverb", PRIV_NOVERB },
170 { "authwarnings", PRIV_AUTHWARNINGS },
171 { "noreceipts", PRIV_NORECEIPTS },
172 { "nobodyreturn", PRIV_NOBODYRETN },
173 { "goaway", PRIV_GOAWAY },
174 { "noactualrecipient", PRIV_NOACTUALRECIPIENT },
179 ** DontBlameSendmail values
182 struct dbsval DontBlameSendmailValues[] =
184 { "safe", DBS_SAFE },
185 { "assumesafechown", DBS_ASSUMESAFECHOWN },
186 { "groupwritabledirpathsafe", DBS_GROUPWRITABLEDIRPATHSAFE },
187 { "groupwritableforwardfilesafe",
188 DBS_GROUPWRITABLEFORWARDFILESAFE },
189 { "groupwritableincludefilesafe",
190 DBS_GROUPWRITABLEINCLUDEFILESAFE },
191 { "groupwritablealiasfile", DBS_GROUPWRITABLEALIASFILE },
192 { "worldwritablealiasfile", DBS_WORLDWRITABLEALIASFILE },
193 { "forwardfileinunsafedirpath", DBS_FORWARDFILEINUNSAFEDIRPATH },
194 { "includefileinunsafedirpath", DBS_INCLUDEFILEINUNSAFEDIRPATH },
195 { "mapinunsafedirpath", DBS_MAPINUNSAFEDIRPATH },
196 { "linkedaliasfileinwritabledir",
197 DBS_LINKEDALIASFILEINWRITABLEDIR },
198 { "linkedclassfileinwritabledir",
199 DBS_LINKEDCLASSFILEINWRITABLEDIR },
200 { "linkedforwardfileinwritabledir",
201 DBS_LINKEDFORWARDFILEINWRITABLEDIR },
202 { "linkedincludefileinwritabledir",
203 DBS_LINKEDINCLUDEFILEINWRITABLEDIR },
204 { "linkedmapinwritabledir", DBS_LINKEDMAPINWRITABLEDIR },
205 { "linkedserviceswitchfileinwritabledir",
206 DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR },
207 { "filedeliverytohardlink", DBS_FILEDELIVERYTOHARDLINK },
208 { "filedeliverytosymlink", DBS_FILEDELIVERYTOSYMLINK },
209 { "writemaptohardlink", DBS_WRITEMAPTOHARDLINK },
210 { "writemaptosymlink", DBS_WRITEMAPTOSYMLINK },
211 { "writestatstohardlink", DBS_WRITESTATSTOHARDLINK },
212 { "writestatstosymlink", DBS_WRITESTATSTOSYMLINK },
213 { "forwardfileingroupwritabledirpath",
214 DBS_FORWARDFILEINGROUPWRITABLEDIRPATH },
215 { "includefileingroupwritabledirpath",
216 DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH },
217 { "classfileinunsafedirpath", DBS_CLASSFILEINUNSAFEDIRPATH },
218 { "errorheaderinunsafedirpath", DBS_ERRORHEADERINUNSAFEDIRPATH },
219 { "helpfileinunsafedirpath", DBS_HELPFILEINUNSAFEDIRPATH },
220 { "forwardfileinunsafedirpathsafe",
221 DBS_FORWARDFILEINUNSAFEDIRPATHSAFE },
222 { "includefileinunsafedirpathsafe",
223 DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE },
224 { "runprograminunsafedirpath", DBS_RUNPROGRAMINUNSAFEDIRPATH },
225 { "runwritableprogram", DBS_RUNWRITABLEPROGRAM },
226 { "nonrootsafeaddr", DBS_NONROOTSAFEADDR },
227 { "truststickybit", DBS_TRUSTSTICKYBIT },
228 { "dontwarnforwardfileinunsafedirpath",
229 DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH },
230 { "insufficiententropy", DBS_INSUFFICIENTENTROPY },
231 { "groupreadablesasldbfile", DBS_GROUPREADABLESASLDBFILE },
232 { "groupwritablesasldbfile", DBS_GROUPWRITABLESASLDBFILE },
233 { "groupwritableforwardfile", DBS_GROUPWRITABLEFORWARDFILE },
234 { "groupwritableincludefile", DBS_GROUPWRITABLEINCLUDEFILE },
235 { "worldwritableforwardfile", DBS_WORLDWRITABLEFORWARDFILE },
236 { "worldwritableincludefile", DBS_WORLDWRITABLEINCLUDEFILE },
237 { "groupreadablekeyfile", DBS_GROUPREADABLEKEYFILE },
238 { "groupreadabledefaultauthinfofile",
239 DBS_GROUPREADABLEAUTHINFOFILE },
244 ** Miscellaneous stuff.
247 int DtableSize = 50; /* max open files; reset in 4.2bsd */
249 ** SETDEFAULTS -- set default values
251 ** Some of these must be initialized using direct code since they
252 ** depend on run-time values. So let's do all of them this way.
255 ** e -- the default envelope.
261 ** Initializes a bunch of global variables to their
266 #define HOURS * 60 MINUTES
267 #define DAYS * 24 HOURS
269 #ifndef MAXRULERECURSION
270 # define MAXRULERECURSION 50 /* max ruleset recursion depth */
275 register ENVELOPE *e;
281 numprocs = get_num_procs_online();
282 SpaceSub = ' '; /* option B */
283 QueueLA = 8 * numprocs; /* option x */
284 RefuseLA = 12 * numprocs; /* option X */
285 WkRecipFact = 30000L; /* option y */
286 WkClassFact = 1800L; /* option z */
287 WkTimeFact = 90000L; /* option Z */
288 QueueFactor = WkRecipFact * 20; /* option q */
289 QueueMode = QM_NORMAL; /* what queue items to act upon */
290 FileMode = (RealUid != geteuid()) ? 0644 : 0600;
292 QueueFileMode = (RealUid != geteuid()) ? 0644 : 0600;
293 /* option QueueFileMode */
295 if (((pw = sm_getpwnam("mailnull")) != NULL && pw->pw_uid != 0) ||
296 ((pw = sm_getpwnam("sendmail")) != NULL && pw->pw_uid != 0) ||
297 ((pw = sm_getpwnam("daemon")) != NULL && pw->pw_uid != 0))
299 DefUid = pw->pw_uid; /* option u */
300 DefGid = pw->pw_gid; /* option g */
301 DefUser = newstr(pw->pw_name);
305 DefUid = 1; /* option u */
306 DefGid = 1; /* option g */
311 sm_dprintf("setdefaults: DefUser=%s, DefUid=%ld, DefGid=%ld\n",
312 DefUser != NULL ? DefUser : "<1:1>",
313 (long) DefUid, (long) DefGid);
314 CheckpointInterval = 10; /* option C */
315 MaxHopCount = 25; /* option h */
316 set_delivery_mode(SM_FORK, e); /* option d */
317 e->e_errormode = EM_PRINT; /* option e */
320 e->e_xfqgrp = NOQGRP;
321 e->e_xfqdir = NOQDIR;
322 e->e_ctime = curtime();
324 e->e_smtputf8 = false;
326 SevenBitInput = false; /* option 7 */
327 MaxMciCache = 1; /* option k */
328 MciCacheTimeout = 5 MINUTES; /* option K */
329 LogLevel = 9; /* option L */
333 inittimeouts(NULL, false); /* option r */
334 PrivacyFlags = PRIV_PUBLIC; /* option p */
335 MeToo = true; /* option m */
336 SendMIMEErrors = true; /* option f */
337 SuperSafe = SAFE_REALLY; /* option s */
338 clrbitmap(DontBlameSendmail); /* DontBlameSendmail option */
340 MimeMode = MM_CVTMIME|MM_PASS8BIT; /* option 8 */
342 MimeMode = MM_PASS8BIT;
344 for (i = 0; i < MAXTOCLASS; i++)
346 TimeOuts.to_q_return[i] = 5 DAYS; /* option T */
347 TimeOuts.to_q_warning[i] = 0; /* option T */
349 ServiceSwitchFile = "/etc/mail/service.switch";
350 ServiceCacheMaxAge = (time_t) 10;
351 HostsFile = _PATH_HOSTS;
352 PidFile = newstr(_PATH_SENDMAILPID);
353 MustQuoteChars = "@,;:\\()[].'";
354 MciInfoTimeout = 30 MINUTES;
355 MaxRuleRecursion = MAXRULERECURSION;
356 MaxAliasRecursion = 10;
357 MaxMacroRecursion = 10;
358 ColonOkInAddr = true;
359 DontLockReadFiles = true;
360 DontProbeInterfaces = DPI_PROBEALL;
361 DoubleBounceAddr = "postmaster";
362 MaxHeadersLength = MAXHDRSLEN;
363 MaxMimeHeaderLength = MAXLINE;
364 MaxMimeFieldLength = MaxMimeHeaderLength / 2;
365 MaxForwardEntries = 0;
367 MaxNOOPCommands = MAXNOOPCOMMANDS;
369 AuthMechanisms = newstr(AUTH_MECHANISMS);
374 TLS_Srv_Opts = TLS_I_SRV;
375 if (NULL == EVP_digest)
376 EVP_digest = EVP_md5();
377 # if _FFR_TLSFB2CLEAR
378 TLSFallbacktoClear = true;
380 Srv_SSL_Options = SSL_OP_ALL;
381 Clt_SSL_Options = SSL_OP_ALL
382 # ifdef SSL_OP_NO_SSLv2
385 # ifdef SSL_OP_NO_TICKET
389 # ifdef SSL_OP_TLSEXT_PADDING
390 /* SSL_OP_TLSEXT_PADDING breaks compatibility with some sites */
391 Srv_SSL_Options &= ~SSL_OP_TLSEXT_PADDING;
392 Clt_SSL_Options &= ~SSL_OP_TLSEXT_PADDING;
393 # endif /* SSL_OP_TLSEXT_PADDING */
394 #endif /* STARTTLS */
396 HesiodContext = NULL;
399 /* Detect if IPv6 is available at run time */
400 i = socket(AF_INET6, SOCK_STREAM, 0);
409 UseCompressedIPv6Addresses = true;
413 #endif /* NETINET6 */
414 ControlSocketName = NULL;
415 memset(&ConnectOnlyTo, '\0', sizeof(ConnectOnlyTo));
416 DataFileBufferSize = 4096;
417 XscriptFileBufferSize = 4096;
418 for (i = 0; i < MAXRWSETS; i++)
419 RuleSetNames[i] = NULL;
421 InputFilters[0] = NULL;
423 RejectLogInterval = 3 HOURS;
424 #if REQUIRES_DIR_FSYNC
425 RequiresDirfsync = true;
427 #if _FFR_RCPTTHROTDELAY
428 BadRcptThrottleDelay = 1;
430 ConnectionRateWindowSize = 60;
431 #if _FFR_BOUNCE_QUEUE
432 BounceQueue = NOQGRP;
441 ** SETDEFUSER -- set/reset DefUser using DefUid (for initgroups())
447 struct passwd *defpwent;
448 static char defuserbuf[40];
450 DefUser = defuserbuf;
451 defpwent = sm_getpwuid(DefUid);
452 (void) sm_strlcpy(defuserbuf,
453 (defpwent == NULL || defpwent->pw_name == NULL)
454 ? "nobody" : defpwent->pw_name,
457 sm_dprintf("setdefuser: DefUid=%ld, DefUser=%s\n",
458 (long) DefUid, DefUser);
461 ** SETUPQUEUES -- initialize default queues
463 ** The mqueue QUEUE structure gets filled in after readcf() but
464 ** we need something to point to now for the mailer setup,
465 ** which use "mqueue" as default queue.
473 MaxRunnersPerQueue = 1;
474 (void) sm_strlcpy(buf, "mqueue, P=/var/spool/mqueue", sizeof(buf));
475 makequeue(buf, false);
478 ** SETUPMAILERS -- initialize default mailers
486 (void) sm_strlcpy(buf, "prog, P=/bin/sh, F=lsouDq9, T=X-Unix/X-Unix/X-Unix, A=sh -c \201u",
490 (void) sm_strlcpy(buf, "*file*, P=[FILE], F=lsDFMPEouq9, T=X-Unix/X-Unix/X-Unix, A=FILE \201u",
494 (void) sm_strlcpy(buf, "*include*, P=/dev/null, F=su, A=INCLUDE \201u",
500 ** SETUPMAPS -- set up map classes
503 #define MAPDEF(name, ext, flags, parse, open, close, lookup, store) \
505 extern bool parse __P((MAP *, char *)); \
506 extern bool open __P((MAP *, int)); \
507 extern void close __P((MAP *)); \
508 extern char *lookup __P((MAP *, char *, char **, int *)); \
509 extern void store __P((MAP *, char *, char *)); \
510 s = stab(name, ST_MAPCLASS, ST_ENTER); \
511 s->s_mapclass.map_cname = name; \
512 s->s_mapclass.map_ext = ext; \
513 s->s_mapclass.map_cflags = flags; \
514 s->s_mapclass.map_parse = parse; \
515 s->s_mapclass.map_open = open; \
516 s->s_mapclass.map_close = close; \
517 s->s_mapclass.map_lookup = lookup; \
518 s->s_mapclass.map_store = store; \
527 # if DB_VERSION_MAJOR > 1
528 int major_v, minor_v, patch_v;
530 (void) db_version(&major_v, &minor_v, &patch_v);
531 if (major_v != DB_VERSION_MAJOR || minor_v != DB_VERSION_MINOR)
534 syserr("Berkeley DB version mismatch: compiled against %d.%d.%d, run-time linked against %d.%d.%d",
535 DB_VERSION_MAJOR, DB_VERSION_MINOR, DB_VERSION_PATCH,
536 major_v, minor_v, patch_v);
538 # endif /* DB_VERSION_MAJOR > 1 */
540 MAPDEF("hash", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
541 map_parseargs, hash_map_open, db_map_close,
542 db_map_lookup, db_map_store);
544 MAPDEF("btree", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
545 map_parseargs, bt_map_open, db_map_close,
546 db_map_lookup, db_map_store);
550 MAPDEF("dbm", ".dir", MCF_ALIASOK|MCF_REBUILDABLE,
551 map_parseargs, ndbm_map_open, ndbm_map_close,
552 ndbm_map_lookup, ndbm_map_store);
556 MAPDEF("cdb", CDBEXT, MCF_ALIASOK|MCF_REBUILDABLE,
557 map_parseargs, cdb_map_open, cdb_map_close,
558 cdb_map_lookup, cdb_map_store);
562 MAPDEF("nis", NULL, MCF_ALIASOK,
563 map_parseargs, nis_map_open, null_map_close,
564 nis_map_lookup, null_map_store);
568 MAPDEF("nisplus", NULL, MCF_ALIASOK,
569 map_parseargs, nisplus_map_open, null_map_close,
570 nisplus_map_lookup, null_map_store);
574 MAPDEF("ldap", NULL, MCF_ALIASOK|MCF_NOTPERSIST,
575 ldapmap_parseargs, ldapmap_open, ldapmap_close,
576 ldapmap_lookup, null_map_store);
580 MAPDEF("ph", NULL, MCF_NOTPERSIST,
581 ph_map_parseargs, ph_map_open, ph_map_close,
582 ph_map_lookup, null_map_store);
586 /* IRIX 6.5 nsd support */
587 MAPDEF("nsd", NULL, MCF_ALIASOK,
588 map_parseargs, null_map_open, null_map_close,
589 nsd_map_lookup, null_map_store);
593 MAPDEF("hesiod", NULL, MCF_ALIASOK,
594 map_parseargs, hes_map_open, hes_map_close,
595 hes_map_lookup, null_map_store);
599 MAPDEF("netinfo", NULL, MCF_ALIASOK,
600 map_parseargs, ni_map_open, null_map_close,
601 ni_map_lookup, null_map_store);
605 MAPDEF("dns", NULL, 0,
606 dns_map_init, null_map_open, null_map_close,
607 dns_map_lookup, null_map_store);
612 # if _FFR_DNSMAP_ALIASABLE
613 MAPDEF("dns", NULL, MCF_ALIASOK,
614 dns_map_parseargs, dns_map_open, null_map_close,
615 dns_map_lookup, null_map_store);
616 # else /* _FFR_DNSMAP_ALIASABLE */
617 MAPDEF("dns", NULL, 0,
618 dns_map_parseargs, dns_map_open, null_map_close,
619 dns_map_lookup, null_map_store);
620 # endif /* _FFR_DNSMAP_ALIASABLE */
622 #endif /* NAMED_BIND */
625 /* best MX DNS lookup */
626 MAPDEF("bestmx", NULL, MCF_OPTFILE,
627 map_parseargs, null_map_open, null_map_close,
628 bestmx_map_lookup, null_map_store);
631 MAPDEF("host", NULL, 0,
632 host_map_init, null_map_open, null_map_close,
633 host_map_lookup, null_map_store);
635 MAPDEF("text", NULL, MCF_ALIASOK,
636 map_parseargs, text_map_open, null_map_close,
637 text_map_lookup, null_map_store);
639 MAPDEF("stab", NULL, MCF_ALIASOK,
640 map_parseargs, stab_map_open, null_map_close,
641 stab_map_lookup, stab_map_store);
643 MAPDEF("implicit", NULL, MCF_ALIASOK|MCF_REBUILDABLE,
644 map_parseargs, impl_map_open, impl_map_close,
645 impl_map_lookup, impl_map_store);
647 /* access to system passwd file */
648 MAPDEF("user", NULL, MCF_OPTFILE,
649 map_parseargs, user_map_open, null_map_close,
650 user_map_lookup, null_map_store);
653 MAPDEF("dequote", NULL, 0,
654 dequote_init, null_map_open, null_map_close,
655 dequote_map, null_map_store);
658 MAPDEF("regex", NULL, 0,
659 regex_map_init, null_map_open, null_map_close,
660 regex_map_lookup, null_map_store);
665 MAPDEF("userdb", ".db", 0,
666 map_parseargs, null_map_open, null_map_close,
667 udb_map_lookup, null_map_store);
670 /* arbitrary programs */
671 MAPDEF("program", NULL, MCF_ALIASOK,
672 map_parseargs, null_map_open, null_map_close,
673 prog_map_lookup, null_map_store);
676 MAPDEF("sequence", NULL, MCF_ALIASOK,
677 seq_map_parse, null_map_open, null_map_close,
678 seq_map_lookup, seq_map_store);
680 /* switched interface to sequenced maps */
681 MAPDEF("switch", NULL, MCF_ALIASOK,
682 map_parseargs, switch_map_open, null_map_close,
683 seq_map_lookup, seq_map_store);
685 /* null map lookup -- really for internal use only */
686 MAPDEF("null", NULL, MCF_ALIASOK|MCF_OPTFILE,
687 map_parseargs, null_map_open, null_map_close,
688 null_map_lookup, null_map_store);
690 /* syslog map -- logs information to syslog */
691 MAPDEF("syslog", NULL, 0,
692 syslog_map_parseargs, null_map_open, null_map_close,
693 syslog_map_lookup, null_map_store);
695 /* macro storage map -- rulesets can set macros */
696 MAPDEF("macro", NULL, 0,
697 dequote_init, null_map_open, null_map_close,
698 macro_map_lookup, null_map_store);
700 /* arithmetic map -- add/subtract/compare */
701 MAPDEF("arith", NULL, 0,
702 dequote_init, null_map_open, null_map_close,
703 arith_map_lookup, null_map_store);
705 /* "arpa" map -- IP -> arpa */
706 MAPDEF("arpa", NULL, 0,
707 dequote_init, null_map_open, null_map_close,
708 arpa_map_lookup, null_map_store);
711 /* arbitrary daemons */
712 MAPDEF("socket", NULL, MCF_ALIASOK,
713 map_parseargs, socket_map_open, socket_map_close,
714 socket_map_lookup, null_map_store);
718 /* dprintf map -- logs information to syslog */
719 MAPDEF("dprintf", NULL, 0,
720 dprintf_map_parseargs, null_map_open, null_map_close,
721 dprintf_map_lookup, null_map_store);
724 #if _FFR_SETDEBUG_MAP
725 /* setdebug map -- set debug levels */
726 MAPDEF("setdebug", NULL, 0,
727 dequote_init, null_map_open, null_map_close,
728 setdebug_map_lookup, null_map_store);
732 /* setopt map -- set option */
733 MAPDEF("setopt", NULL, 0,
734 dequote_init, null_map_open, null_map_close,
735 setopt_map_lookup, null_map_store);
740 /* bogus map -- always return tempfail */
741 MAPDEF("bogus", NULL, MCF_ALIASOK|MCF_OPTFILE,
742 map_parseargs, null_map_open, null_map_close,
743 bogus_map_lookup, null_map_store);
749 ** INITHOSTMAPS -- initial host-dependent maps
751 ** This should act as an interface to any local service switch
752 ** provided by the host operating system.
761 ** Should define maps "host" and "users" as necessary
762 ** for this OS. If they are not defined, they will get
763 ** a default value later. It should check to make sure
764 ** they are not defined first, since it's possible that
765 ** the config file has provided an override.
773 char *maptype[MAXMAPSTACK];
774 short mapreturn[MAXMAPACTIONS];
778 ** Make sure we have a host map.
781 if (stab("host", ST_MAP, ST_FIND) == NULL)
783 /* user didn't initialize: set up host map */
784 (void) sm_strlcpy(buf, "host host", sizeof(buf));
786 if (ConfigLevel >= 2)
787 (void) sm_strlcat(buf, " -a. -D", sizeof(buf));
789 (void) makemapentry(buf);
793 ** Set up default aliases maps
796 nmaps = switch_map_find("aliases", maptype, mapreturn);
797 for (i = 0; i < nmaps; i++)
799 if (strcmp(maptype[i], "files") == 0 &&
800 stab("aliases.files", ST_MAP, ST_FIND) == NULL)
802 (void) sm_strlcpy(buf, "aliases.files null",
804 (void) makemapentry(buf);
807 else if (strcmp(maptype[i], "cdb") == 0 &&
808 stab("aliases.cdb", ST_MAP, ST_FIND) == NULL)
810 (void) sm_strlcpy(buf, "aliases.cdb null", sizeof(buf));
811 (void) makemapentry(buf);
815 else if (strcmp(maptype[i], "nisplus") == 0 &&
816 stab("aliases.nisplus", ST_MAP, ST_FIND) == NULL)
818 (void) sm_strlcpy(buf, "aliases.nisplus nisplus -kalias -vexpansion mail_aliases.org_dir",
820 (void) makemapentry(buf);
824 else if (strcmp(maptype[i], "nis") == 0 &&
825 stab("aliases.nis", ST_MAP, ST_FIND) == NULL)
827 (void) sm_strlcpy(buf, "aliases.nis nis mail.aliases",
829 (void) makemapentry(buf);
833 else if (strcmp(maptype[i], "netinfo") == 0 &&
834 stab("aliases.netinfo", ST_MAP, ST_FIND) == NULL)
836 (void) sm_strlcpy(buf, "aliases.netinfo netinfo -z, /aliases",
838 (void) makemapentry(buf);
842 else if (strcmp(maptype[i], "hesiod") == 0 &&
843 stab("aliases.hesiod", ST_MAP, ST_FIND) == NULL)
845 (void) sm_strlcpy(buf, "aliases.hesiod hesiod aliases",
847 (void) makemapentry(buf);
850 #if LDAPMAP && defined(SUN_EXTENSIONS) && \
851 defined(SUN_SIMPLIFIED_LDAP) && HASLDAPGETALIASBYNAME
852 else if (strcmp(maptype[i], "ldap") == 0 &&
853 stab("aliases.ldap", ST_MAP, ST_FIND) == NULL)
855 (void) sm_strlcpy(buf, "aliases.ldap ldap -b . -h localhost -k mail=%0 -v mailgroup",
857 (void) makemapentry(buf);
859 #endif /* LDAPMAP && defined(SUN_EXTENSIONS) && ... */
861 if (stab("aliases", ST_MAP, ST_FIND) == NULL)
863 (void) sm_strlcpy(buf, "aliases switch aliases", sizeof(buf));
864 (void) makemapentry(buf);
869 ** SWITCH_MAP_FIND -- find the list of types associated with a map
871 ** This is the system-dependent interface to the service switch.
874 ** service -- the name of the service of interest.
875 ** maptype -- an out-array of strings containing the types
876 ** of access to use for this service. There can
877 ** be at most MAXMAPSTACK types for a single service.
878 ** mapreturn -- an out-array of return information bitmaps
882 ** The number of map types filled in, or -1 for failure.
885 ** Preserves errno so nothing in the routine clobbers it.
888 #if defined(SOLARIS) || (defined(sony_news) && defined(__svr4))
889 # define _USE_SUN_NSSWITCH_
892 #if _FFR_HPUX_NSSWITCH
894 # define _USE_SUN_NSSWITCH_
896 #endif /* _FFR_HPUX_NSSWITCH */
898 #ifdef _USE_SUN_NSSWITCH_
899 # include <nsswitch.h>
902 #if defined(ultrix) || (defined(__osf__) && defined(__alpha))
903 # define _USE_DEC_SVC_CONF_
906 #ifdef _USE_DEC_SVC_CONF_
907 # include <sys/svcinfo.h>
911 switch_map_find(service, maptype, mapreturn)
913 char *maptype[MAXMAPSTACK];
914 short mapreturn[MAXMAPACTIONS];
917 int save_errno = errno;
919 #ifdef _USE_SUN_NSSWITCH_
920 struct __nsw_switchconfig *nsw_conf;
921 enum __nsw_parse_err pserr;
922 struct __nsw_lookup *lk;
923 static struct __nsw_lookup lkp0 =
924 { "files", {1, 0, 0, 0}, NULL, NULL };
925 static struct __nsw_switchconfig lkp_default =
926 { 0, "sendmail", 3, &lkp0 };
928 for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
929 mapreturn[svcno] = 0;
931 if ((nsw_conf = __nsw_getconfig(service, &pserr)) == NULL)
932 lk = lkp_default.lookups;
934 lk = nsw_conf->lookups;
936 while (lk != NULL && svcno < MAXMAPSTACK)
938 maptype[svcno] = lk->service_name;
939 if (lk->actions[__NSW_NOTFOUND] == __NSW_RETURN)
940 mapreturn[MA_NOTFOUND] |= 1 << svcno;
941 if (lk->actions[__NSW_TRYAGAIN] == __NSW_RETURN)
942 mapreturn[MA_TRYAGAIN] |= 1 << svcno;
943 if (lk->actions[__NSW_UNAVAIL] == __NSW_RETURN)
944 mapreturn[MA_TRYAGAIN] |= 1 << svcno;
950 #endif /* _USE_SUN_NSSWITCH_ */
952 #ifdef _USE_DEC_SVC_CONF_
953 struct svcinfo *svcinfo;
956 for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
957 mapreturn[svcno] = 0;
962 if (strcmp(service, "hosts") == 0)
964 else if (strcmp(service, "aliases") == 0)
966 else if (strcmp(service, "passwd") == 0)
973 for (svcno = 0; svcno < SVC_PATHSIZE && svcno < MAXMAPSTACK; svcno++)
975 switch (svcinfo->svcpath[svc][svcno])
978 maptype[svcno] = "files";
982 maptype[svcno] = "nis";
986 maptype[svcno] = "dns";
991 maptype[svcno] = "hesiod";
1002 #endif /* _USE_DEC_SVC_CONF_ */
1004 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1006 ** Fall-back mechanism.
1010 static time_t servicecachetime; /* time service switch was cached */
1011 time_t now = curtime();
1013 for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
1014 mapreturn[svcno] = 0;
1016 if ((now - servicecachetime) > (time_t) ServiceCacheMaxAge)
1018 /* (re)read service switch */
1019 register SM_FILE_T *fp;
1020 long sff = SFF_REGONLY|SFF_OPENASROOT|SFF_NOLOCK;
1022 if (!bitnset(DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR,
1027 servicecachetime = now;
1028 fp = safefopen(ServiceSwitchFile, O_RDONLY, 0, sff);
1033 while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf,
1038 p = strpbrk(buf, "#\n");
1041 #ifndef SM_NSSWITCH_DELIMS
1042 # define SM_NSSWITCH_DELIMS " \t"
1044 p = strpbrk(buf, SM_NSSWITCH_DELIMS);
1051 sm_syslog(LOG_ERR, NOQID,
1052 "Bad line on %.100s: %.100s",
1057 while (SM_ISSPACE(*p))
1063 ** Find/allocate space for this service entry.
1064 ** Space for all of the service strings
1065 ** are allocated at once. This means
1066 ** that we only have to free the first
1067 ** one to free all of them.
1070 st = stab(buf, ST_SERVICE, ST_ENTER);
1071 if (st->s_service[0] != NULL)
1072 sm_free((void *) st->s_service[0]); /* XXX */
1074 for (svcno = 0; svcno < MAXMAPSTACK; )
1078 st->s_service[svcno++] = p;
1079 p = strpbrk(p, " \t");
1083 while (SM_ISSPACE(*p))
1086 if (svcno < MAXMAPSTACK)
1087 st->s_service[svcno] = NULL;
1089 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1093 /* look up entry in cache */
1094 st = stab(service, ST_SERVICE, ST_FIND);
1095 if (st != NULL && st->s_service[0] != NULL)
1099 while (svcno < MAXMAPSTACK)
1101 maptype[svcno] = st->s_service[svcno];
1102 if (maptype[svcno++] == NULL)
1108 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1110 #if !defined(_USE_SUN_NSSWITCH_)
1111 /* if the service file doesn't work, use an absolute fallback */
1112 # ifdef _USE_DEC_SVC_CONF_
1115 for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
1116 mapreturn[svcno] = 0;
1118 if (strcmp(service, "aliases") == 0)
1120 SM_ASSERT(svcno < MAXMAPSTACK);
1121 maptype[svcno++] = "files";
1123 SM_ASSERT(svcno < MAXMAPSTACK);
1124 maptype[svcno++] = "cdb";
1126 # if defined(AUTO_NETINFO_ALIASES) && defined (NETINFO)
1127 SM_ASSERT(svcno < MAXMAPSTACK);
1128 maptype[svcno++] = "netinfo";
1130 # ifdef AUTO_NIS_ALIASES
1132 SM_ASSERT(svcno < MAXMAPSTACK);
1133 maptype[svcno++] = "nisplus";
1136 SM_ASSERT(svcno < MAXMAPSTACK);
1137 maptype[svcno++] = "nis";
1139 # endif /* AUTO_NIS_ALIASES */
1143 if (strcmp(service, "hosts") == 0)
1146 SM_ASSERT(svcno < MAXMAPSTACK);
1147 maptype[svcno++] = "dns";
1148 # else /* NAMED_BIND */
1149 # if defined(sun) && !defined(BSD)
1151 SM_ASSERT(svcno < MAXMAPSTACK);
1152 maptype[svcno++] = "nis";
1153 # endif /* defined(sun) && !defined(BSD) */
1154 # endif /* NAMED_BIND */
1155 # if defined(AUTO_NETINFO_HOSTS) && defined (NETINFO)
1156 SM_ASSERT(svcno < MAXMAPSTACK);
1157 maptype[svcno++] = "netinfo";
1159 SM_ASSERT(svcno < MAXMAPSTACK);
1160 maptype[svcno++] = "files";
1166 #endif /* !defined(_USE_SUN_NSSWITCH_) */
1169 ** USERNAME -- return the user id of the logged in user.
1175 ** The login name of the logged in user.
1181 ** The return value is statically allocated.
1187 static char *myname = NULL;
1188 extern char *getlogin();
1189 register struct passwd *pw;
1191 /* cache the result */
1194 myname = getlogin();
1195 if (myname == NULL || myname[0] == '\0')
1197 pw = sm_getpwuid(RealUid);
1199 myname = pw->pw_name;
1203 uid_t uid = RealUid;
1205 if ((pw = sm_getpwnam(myname)) == NULL ||
1206 (uid != 0 && uid != pw->pw_uid))
1208 pw = sm_getpwuid(uid);
1210 myname = pw->pw_name;
1213 if (myname == NULL || myname[0] == '\0')
1215 syserr("554 5.3.0 Who are you?");
1216 myname = "postmaster";
1218 else if (strpbrk(myname, ",;:/|\"\\") != NULL)
1219 myname = addquotes(myname, NULL);
1221 myname = sm_pstrdup_x(myname);
1226 ** TTYPATH -- Get the path of the user's tty
1228 ** Returns the pathname of the user's tty. Returns NULL if
1229 ** the user is not logged in or if s/he has write permission
1236 ** pathname of the user's tty.
1237 ** NULL if not logged in or write permission denied.
1243 ** Return value is in a local buffer.
1253 register char *pathn;
1254 extern char *ttyname();
1255 extern char *getlogin();
1257 /* compute the pathname of the controlling tty */
1258 if ((pathn = ttyname(2)) == NULL && (pathn = ttyname(1)) == NULL &&
1259 (pathn = ttyname(0)) == NULL)
1265 /* see if we have write permission */
1266 if (stat(pathn, &stbuf) < 0 || !bitset(S_IWOTH, stbuf.st_mode))
1272 /* see if the user is logged in */
1273 if (getlogin() == NULL)
1280 ** CHECKCOMPAT -- check for From and To person compatible.
1282 ** This routine can be supplied on a per-installation basis
1283 ** to determine whether a person is allowed to send a message.
1284 ** This allows restriction of certain types of internet
1285 ** forwarding or registration of users.
1287 ** If the hosts are found to be incompatible, an error
1288 ** message should be given using "usrerr" and an EX_ code
1289 ** should be returned. You can also set to->q_status to
1290 ** a DSN-style status code.
1292 ** EF_NO_BODY_RETN can be set in e->e_flags to suppress the
1293 ** body during the return-to-sender function; this should be done
1294 ** on huge messages. This bit may already be set by the ESMTP
1298 ** to -- the person being sent to.
1304 ** none (unless you include the usrerr stuff)
1309 register ADDRESS *to;
1310 register ENVELOPE *e;
1313 sm_dprintf("checkcompat(to=%s, from=%s)\n",
1314 to->q_paddr, e->e_from.q_paddr);
1317 /* this code is intended as an example only */
1320 s = stab("arpa", ST_MAILER, ST_FIND);
1321 if (s != NULL && strcmp(e->e_from.q_mailer->m_name, "local") != 0 &&
1322 to->q_mailer == s->s_mailer)
1324 usrerr("553 No ARPA mail through this machine: see your system administration");
1325 /* e->e_flags |= EF_NO_BODY_RETN; to suppress body on return */
1326 to->q_status = "5.7.1";
1327 return EX_UNAVAILABLE;
1329 #endif /* EXAMPLE_CODE */
1333 #ifdef SUN_EXTENSIONS
1339 /* Check for large file descriptor */
1340 if (fstat(fileno(stdin), &sbuf) < 0)
1342 if (errno == EOVERFLOW)
1349 #endif /* SUN_EXTENSIONS */
1352 ** INIT_MD -- do machine dependent initializations
1354 ** Systems that have global modes that should be set should do
1355 ** them here rather than in main.
1359 # include <compat.h>
1363 # include <shares.h>
1372 setcompat(getcompat() | COMPAT_BSDPROT);
1375 #ifdef SUN_EXTENSIONS
1380 /* keep gethostby*() from stripping the local domain name */
1381 set_domain_trim_off();
1383 #if defined(__QNX__) && !defined(__QNXNTO__)
1385 ** Due to QNX's network distributed nature, you can target a tcpip
1386 ** stack on a different node in the qnx network; this patch lets
1387 ** this feature work. The __sock_locate() must be done before the
1388 ** environment is clear.
1391 #endif /* __QNX__ */
1392 #if SECUREWARE || defined(_SCO_unix_)
1393 set_auth_parameters(argc, argv);
1397 ** This is required for highest security levels (the kernel
1398 ** won't let it call set*uid() or run setuid binaries without
1399 ** it). It may be necessary on other SECUREWARE systems.
1402 if (getluid() == -1)
1404 # endif /* _SCO_unix_ */
1405 #endif /* SECUREWARE || defined(_SCO_unix_) */
1408 #ifdef VENDOR_DEFAULT
1409 VendorCode = VENDOR_DEFAULT;
1411 VendorCode = VENDOR_BERKELEY;
1415 ** INIT_VENDOR_MACROS -- vendor-dependent macro initializations
1417 ** Called once, on startup.
1420 ** e -- the global envelope.
1426 ** vendor-dependent.
1430 init_vendor_macros(e)
1431 register ENVELOPE *e;
1435 ** GETLA -- get the current load average
1437 ** This code stolen from la.c.
1443 ** The current load average as an integer.
1449 /* try to guess what style of load average we have */
1450 #define LA_ZERO 1 /* always return load average as zero */
1451 #define LA_INT 2 /* read kmem for avenrun; interpret as long */
1452 #define LA_FLOAT 3 /* read kmem for avenrun; interpret as float */
1453 #define LA_SUBR 4 /* call getloadavg */
1454 #define LA_MACH 5 /* MACH load averages (as on NeXT boxes) */
1455 #define LA_SHORT 6 /* read kmem for avenrun; interpret as short */
1456 #define LA_PROCSTR 7 /* read string ("1.17") from /proc/loadavg */
1457 #define LA_READKSYM 8 /* SVR4: use MIOC_READKSYM ioctl call */
1458 #define LA_DGUX 9 /* special DGUX implementation */
1459 #define LA_HPUX 10 /* special HPUX implementation */
1460 #define LA_IRIX6 11 /* special IRIX 6.2 implementation */
1461 #define LA_KSTAT 12 /* special Solaris kstat(3k) implementation */
1462 #define LA_DEVSHORT 13 /* read short from a device */
1463 #define LA_ALPHAOSF 14 /* Digital UNIX (OSF/1 on Alpha) table() call */
1464 #define LA_PSET 15 /* Solaris per-processor-set load average */
1465 #define LA_LONGLONG 17 /* read kmem for avenrun; interpret as long long */
1467 /* do guesses based on general OS type */
1469 # define LA_TYPE LA_ZERO
1473 # if defined(unixpc)
1477 # if defined(__alpha) || defined(IRIX)
1481 #endif /* ! FSHIFT */
1488 # define FSCALE (1 << FSHIFT)
1493 # define LA_AVENRUN "avenrun"
1495 # define LA_AVENRUN "_avenrun"
1497 #endif /* ! LA_AVENRUN */
1499 /* _PATH_KMEM should be defined in <paths.h> */
1501 # define _PATH_KMEM "/dev/kmem"
1504 #if (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG)
1508 /* _PATH_UNIX should be defined in <paths.h> */
1510 # if defined(SYSTEM5)
1511 # define _PATH_UNIX "/unix"
1513 # define _PATH_UNIX "/vmunix"
1515 # endif /* ! _PATH_UNIX */
1519 # else /* _AUX_SOURCE */
1525 # endif /* _AUX_SOURCE */
1526 # define X_AVENRUN 0
1532 static int kmem = -1;
1533 # if LA_TYPE == LA_INT
1535 # else /* LA_TYPE == LA_INT */
1536 # if LA_TYPE == LA_SHORT
1539 # if LA_TYPE == LA_LONGLONG
1540 long long avenrun[3];
1544 # endif /* LA_TYPE == LA_SHORT */
1545 # endif /* LA_TYPE == LA_INT */
1546 extern off_t lseek();
1551 (void) sm_strlcpy(Nl[X_AVENRUN].n_name, LA_AVENRUN,
1552 sizeof(Nl[X_AVENRUN].n_name));
1553 Nl[1].n_name[0] = '\0';
1554 # endif /* _AUX_SOURCE */
1556 # if defined(_AIX3) || defined(_AIX4)
1557 if (knlist(Nl, 1, sizeof(Nl[0])) < 0)
1559 if (nlist(_PATH_UNIX, Nl) < 0)
1563 sm_dprintf("getla: nlist(%s): %s\n", _PATH_UNIX,
1564 sm_errstring(errno));
1567 if (Nl[X_AVENRUN].n_value == 0)
1570 sm_dprintf("getla: nlist(%s, %s) ==> 0\n",
1571 _PATH_UNIX, LA_AVENRUN);
1574 # ifdef NAMELISTMASK
1575 Nl[X_AVENRUN].n_value &= NAMELISTMASK;
1578 kmem = open(_PATH_KMEM, 0, 0);
1582 sm_dprintf("getla: open(/dev/kmem): %s\n",
1583 sm_errstring(errno));
1586 if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1587 fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1590 sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1591 sm_errstring(errno));
1598 sm_dprintf("getla: symbol address = %#lx\n",
1599 (unsigned long) Nl[X_AVENRUN].n_value);
1600 if (lseek(kmem, (off_t) Nl[X_AVENRUN].n_value, SEEK_SET) == -1 ||
1601 read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun))
1605 sm_dprintf("getla: lseek or read: %s\n",
1606 sm_errstring(errno));
1609 # if (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG)
1612 # if LA_TYPE == LA_SHORT
1613 sm_dprintf("getla: avenrun = %d", avenrun[0]);
1615 sm_dprintf(", %d, %d", avenrun[1], avenrun[2]);
1616 # else /* LA_TYPE == LA_SHORT */
1617 # if LA_TYPE == LA_LONGLONG
1618 sm_dprintf("getla: avenrun = %lld", avenrun[0]);
1620 sm_dprintf(", %lld, %lld", avenrun[1], avenrun[2]);
1621 # else /* LA_TYPE == LA_LONGLONG */
1622 sm_dprintf("getla: avenrun = %ld", avenrun[0]);
1624 sm_dprintf(", %ld, %ld", avenrun[1], avenrun[2]);
1625 # endif /* LA_TYPE == LA_LONGLONG */
1626 # endif /* LA_TYPE == LA_SHORT */
1630 sm_dprintf("getla: %d\n",
1631 (int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1632 return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1633 # else /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1636 sm_dprintf("getla: avenrun = %g", avenrun[0]);
1638 sm_dprintf(", %g, %g", avenrun[1], avenrun[2]);
1642 sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
1643 return ((int) (avenrun[0] + 0.5));
1644 # endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1647 #endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1649 #if LA_TYPE == LA_READKSYM
1651 # include <sys/ksym.h>
1657 static int kmem = -1;
1659 struct mioc_rksym mirk;
1663 kmem = open("/dev/kmem", 0, 0);
1667 sm_dprintf("getla: open(/dev/kmem): %s\n",
1668 sm_errstring(errno));
1671 if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1672 fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1675 sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1676 sm_errstring(errno));
1682 mirk.mirk_symname = LA_AVENRUN;
1683 mirk.mirk_buf = avenrun;
1684 mirk.mirk_buflen = sizeof(avenrun);
1685 if (ioctl(kmem, MIOC_READKSYM, &mirk) < 0)
1688 sm_dprintf("getla: ioctl(MIOC_READKSYM) failed: %s\n",
1689 sm_errstring(errno));
1694 sm_dprintf("getla: avenrun = %d", avenrun[0]);
1696 sm_dprintf(", %d, %d", avenrun[1], avenrun[2]);
1700 sm_dprintf("getla: %d\n",
1701 (int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1702 return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1705 #endif /* LA_TYPE == LA_READKSYM */
1707 #if LA_TYPE == LA_DGUX
1709 # include <sys/dg_sys_info.h>
1714 struct dg_sys_info_load_info load_info;
1716 dg_sys_info((long *)&load_info,
1717 DG_SYS_INFO_LOAD_INFO_TYPE, DG_SYS_INFO_LOAD_VERSION_0);
1720 sm_dprintf("getla: %d\n", (int) (load_info.one_minute + 0.5));
1722 return ((int) (load_info.one_minute + 0.5));
1725 #endif /* LA_TYPE == LA_DGUX */
1727 #if LA_TYPE == LA_HPUX
1729 /* forward declarations to keep gcc from complaining */
1734 struct pst_diskinfo;
1735 struct pst_processor;
1737 struct pst_swapinfo;
1739 # include <sys/param.h>
1740 # include <sys/pstat.h>
1745 struct pst_dynamic pstd;
1747 if (pstat_getdynamic(&pstd, sizeof(struct pst_dynamic),
1748 (size_t) 1, 0) == -1)
1752 sm_dprintf("getla: %d\n", (int) (pstd.psd_avg_1_min + 0.5));
1754 return (int) (pstd.psd_avg_1_min + 0.5);
1757 #endif /* LA_TYPE == LA_HPUX */
1759 #if LA_TYPE == LA_SUBR
1766 if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0)
1769 sm_dprintf("getla: getloadavg failed: %s",
1770 sm_errstring(errno));
1774 sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
1775 return ((int) (avenrun[0] + 0.5));
1778 #endif /* LA_TYPE == LA_SUBR */
1780 #if LA_TYPE == LA_MACH
1783 ** This has been tested on NEXTSTEP release 2.1/3.X.
1786 # if defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0
1787 # include <mach/mach.h>
1795 processor_set_t default_set;
1796 kern_return_t error;
1797 unsigned int info_count;
1798 struct processor_set_basic_info info;
1801 error = processor_set_default(host_self(), &default_set);
1802 if (error != KERN_SUCCESS)
1805 sm_dprintf("getla: processor_set_default failed: %s",
1806 sm_errstring(errno));
1809 info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
1810 if (processor_set_info(default_set, PROCESSOR_SET_BASIC_INFO,
1811 &host, (processor_set_info_t)&info,
1812 &info_count) != KERN_SUCCESS)
1815 sm_dprintf("getla: processor_set_info failed: %s",
1816 sm_errstring(errno));
1820 sm_dprintf("getla: %d\n",
1821 (int) ((info.load_average + (LOAD_SCALE / 2)) /
1823 return (int) (info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE;
1826 #endif /* LA_TYPE == LA_MACH */
1828 #if LA_TYPE == LA_PROCSTR
1829 # if SM_CONF_BROKEN_STRTOD
1830 ERROR: This OS has most likely a broken strtod() implemenentation.
1831 ERROR: The function is required for getla().
1832 ERROR: Check the compilation options _LA_PROCSTR and
1833 ERROR: _SM_CONF_BROKEN_STRTOD (without the leading _).
1834 # endif /* SM_CONF_BROKEN_STRTOD */
1837 ** Read /proc/loadavg for the load average. This is assumed to be
1838 ** in a format like "0.15 0.12 0.06".
1840 ** Initially intended for Linux. This has been in the kernel
1841 ** since at least 0.99.15.
1844 # ifndef _PATH_LOADAVG
1845 # define _PATH_LOADAVG "/proc/loadavg"
1852 register int result;
1855 fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_LOADAVG, SM_IO_RDONLY,
1860 sm_dprintf("getla: sm_io_open(%s): %s\n",
1861 _PATH_LOADAVG, sm_errstring(errno));
1864 result = sm_io_fscanf(fp, SM_TIME_DEFAULT, "%lf", &avenrun);
1865 (void) sm_io_close(fp, SM_TIME_DEFAULT);
1869 sm_dprintf("getla: sm_io_fscanf() = %d: %s\n",
1870 result, sm_errstring(errno));
1875 sm_dprintf("getla(): %.2f\n", avenrun);
1877 return ((int) (avenrun + 0.5));
1880 #endif /* LA_TYPE == LA_PROCSTR */
1882 #if LA_TYPE == LA_IRIX6
1884 # include <sys/sysmp.h>
1887 # define CAST_SYSMP(x) (x)
1889 # define CAST_SYSMP(x) ((x) & 0x7fffffff)
1896 static int kmem = -1;
1901 kmem = open(_PATH_KMEM, 0, 0);
1905 sm_dprintf("getla: open(%s): %s\n", _PATH_KMEM,
1906 sm_errstring(errno));
1909 if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1910 fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1913 sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1914 sm_errstring(errno));
1921 if (lseek(kmem, CAST_SYSMP(sysmp(MP_KERNADDR, MPKA_AVENRUN)), SEEK_SET)
1923 read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun))
1926 sm_dprintf("getla: lseek or read: %s\n",
1927 sm_errstring(errno));
1932 sm_dprintf("getla: avenrun = %ld", (long int) avenrun[0]);
1934 sm_dprintf(", %ld, %ld",
1935 (long int) avenrun[1], (long int) avenrun[2]);
1940 sm_dprintf("getla: %d\n",
1941 (int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1942 return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1945 #endif /* LA_TYPE == LA_IRIX6 */
1947 #if LA_TYPE == LA_KSTAT
1954 static kstat_ctl_t *kc = NULL;
1955 static kstat_t *ksp = NULL;
1959 if (kc == NULL) /* if not initialized before */
1964 sm_dprintf("getla: kstat_open(): %s\n",
1965 sm_errstring(errno));
1969 ksp = kstat_lookup(kc, "unix", 0, "system_misc");
1973 sm_dprintf("getla: kstat_lookup(): %s\n",
1974 sm_errstring(errno));
1977 if (kstat_read(kc, ksp, NULL) < 0)
1980 sm_dprintf("getla: kstat_read(): %s\n",
1981 sm_errstring(errno));
1984 ksn = (kstat_named_t *) kstat_data_lookup(ksp, "avenrun_1min");
1985 la = ((double) ksn->value.ul + FSCALE/2) / FSCALE;
1986 /* kstat_close(kc); /o do not close for fast access */
1990 #endif /* LA_TYPE == LA_KSTAT */
1992 #if LA_TYPE == LA_DEVSHORT
1995 ** Read /dev/table/avenrun for the load average. This should contain
1996 ** three shorts for the 1, 5, and 15 minute loads. We only read the
1997 ** first, since that's all we care about.
1999 ** Intended for SCO OpenServer 5.
2002 # ifndef _PATH_AVENRUN
2003 # define _PATH_AVENRUN "/dev/table/avenrun"
2009 static int afd = -1;
2016 if (afd == -1 || lseek(afd, 0L, SEEK_SET) == -1)
2020 afd = open(_PATH_AVENRUN, O_RDONLY|O_SYNC);
2023 sm_syslog(LOG_ERR, NOQID,
2024 "can't open %s: %s",
2025 _PATH_AVENRUN, sm_errstring(errno));
2030 r = read(afd, &avenrun, sizeof(avenrun));
2031 if (r != sizeof(avenrun))
2033 sm_syslog(LOG_ERR, NOQID,
2034 "can't read %s: %s", _PATH_AVENRUN,
2035 r == -1 ? sm_errstring(errno) : "short read");
2040 sm_dprintf("getla: avenrun = %d\n", avenrun);
2041 loadav = (int) (avenrun + FSCALE/2) >> FSHIFT;
2043 sm_dprintf("getla: %d\n", loadav);
2047 #endif /* LA_TYPE == LA_DEVSHORT */
2049 #if LA_TYPE == LA_ALPHAOSF
2052 # include <sys/table.h>
2058 struct tbl_loadavg tab;
2060 if (table(TBL_LOADAVG, 0, &tab, 1, sizeof(tab)) == -1)
2063 sm_dprintf("getla: table %s\n", sm_errstring(errno));
2068 sm_dprintf("getla: scale = %d\n", tab.tl_lscale);
2071 ave = ((tab.tl_avenrun.l[2] + (tab.tl_lscale/2)) /
2074 ave = (int) (tab.tl_avenrun.d[2] + 0.5);
2077 sm_dprintf("getla: %d\n", ave);
2082 #endif /* LA_TYPE == LA_ALPHAOSF */
2084 #if LA_TYPE == LA_PSET
2091 if (pset_getloadavg(PS_MYID, avenrun,
2092 sizeof(avenrun) / sizeof(avenrun[0])) < 0)
2095 sm_dprintf("getla: pset_getloadavg failed: %s",
2096 sm_errstring(errno));
2100 sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
2101 return ((int) (avenrun[0] + 0.5));
2104 #endif /* LA_TYPE == LA_PSET */
2106 #if LA_TYPE == LA_ZERO
2112 sm_dprintf("getla: ZERO\n");
2116 #endif /* LA_TYPE == LA_ZERO */
2119 * Copyright 1989 Massachusetts Institute of Technology
2121 * Permission to use, copy, modify, distribute, and sell this software and its
2122 * documentation for any purpose is hereby granted without fee, provided that
2123 * the above copyright notice appear in all copies and that both that
2124 * copyright notice and this permission notice appear in supporting
2125 * documentation, and that the name of M.I.T. not be used in advertising or
2126 * publicity pertaining to distribution of the software without specific,
2127 * written prior permission. M.I.T. makes no representations about the
2128 * suitability of this software for any purpose. It is provided "as is"
2129 * without express or implied warranty.
2131 * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
2132 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T.
2133 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2134 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
2135 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2136 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2138 * Authors: Many and varied...
2141 /* Non Apollo stuff removed by Don Lewis 11/15/93 */
2143 SM_UNUSED(static char rcsid[]) = "@(#)$OrigId: getloadavg.c,v 1.16 1991/06/21 12:51:15 paul Exp $";
2148 # include <apollo/base.h>
2151 int getloadavg( call_data )
2152 caddr_t call_data; /* pointer to (double) return value */
2154 double *avenrun = (double *) call_data;
2159 proc1_$get_loadav(loadav, &st);
2160 *avenrun = loadav[0] / (double) (1 << 16);
2165 ** SM_GETLA -- get the current load average
2174 ** Set CurrentLA to the current load average.
2175 ** Set {load_avg} in GlobalMacros to the current load average.
2183 CurrentLA = getla();
2184 (void) sm_snprintf(labuf, sizeof(labuf), "%d", CurrentLA);
2185 macdefine(&GlobalMacros, A_TEMP, macid("{load_avg}"), labuf);
2188 ** SHOULDQUEUE -- should this message be queued or sent?
2190 ** Compares the message cost to the load average to decide.
2192 ** Note: Do NOT change this API! It is documented in op.me
2193 ** and theoretically the user can change this function...
2196 ** pri -- the priority of the message in question.
2197 ** ct -- the message creation time (unused, but see above).
2200 ** true -- if this message should be queued up for the
2202 ** false -- if the load is low enough to send this message.
2210 shouldqueue(pri, ct)
2220 sm_dprintf("shouldqueue: CurrentLA=%d, pri=%ld: ",
2224 if (QueueLowMem > 0 &&
2225 sm_memstat_get(MemoryResource, &memfree) >= 0 &&
2226 memfree < QueueLowMem)
2229 sm_dprintf("true (memfree=%ld < QueueLowMem=%ld)\n",
2230 memfree, QueueLowMem);
2233 #endif /* _FFR_MEMSTAT */
2234 if (CurrentLA < QueueLA)
2237 sm_dprintf("false (CurrentLA < QueueLA)\n");
2240 rval = pri > (QueueFactor / (CurrentLA - QueueLA + 1));
2242 sm_dprintf("%s (by calculation)\n", rval ? "true" : "false");
2247 ** REFUSECONNECTIONS -- decide if connections should be refused
2250 ** e -- the current envelope.
2251 ** dn -- number of daemon.
2252 ** active -- was this daemon actually active?
2255 ** true if incoming SMTP connections should be refused
2257 ** false if we should accept new work.
2260 ** Sets process title when it is rejecting connections.
2264 refuseconnections(e, dn, active)
2269 static time_t lastconn[MAXDAEMONS];
2270 static int conncnt[MAXDAEMONS];
2271 static time_t firstrejtime[MAXDAEMONS];
2272 static time_t nextlogtime[MAXDAEMONS];
2284 SM_ASSERT(dn < MAXDAEMONS);
2285 if (ConnRateThrottle > 0)
2292 if (now != lastconn[dn])
2297 else if (conncnt[dn]++ > ConnRateThrottle)
2299 #define D_MSG_CRT "deferring connections on daemon %s: %d per second"
2300 /* sleep to flatten out connection load */
2301 sm_setproctitle(true, e, D_MSG_CRT,
2305 sm_syslog(LOG_INFO, NOQID, D_MSG_CRT,
2311 else if (now != lastconn[dn])
2317 if (RefuseLowMem > 0 &&
2318 sm_memstat_get(MemoryResource, &memfree) >= 0 &&
2319 memfree < RefuseLowMem)
2321 # define R_MSG_LM "rejecting connections on daemon %s: free memory: %ld"
2322 sm_setproctitle(true, e, R_MSG_LM, Daemons[dn].d_name, memfree);
2324 sm_syslog(LOG_NOTICE, NOQID, R_MSG_LM,
2325 Daemons[dn].d_name, memfree);
2328 #endif /* _FFR_MEMSTAT */
2330 limit = (Daemons[dn].d_refuseLA != DPO_NOTSET) ?
2331 Daemons[dn].d_refuseLA : RefuseLA;
2332 if (limit > 0 && CurrentLA >= limit)
2336 # define R_MSG_LA "rejecting connections on daemon %s: load average: %d"
2337 # define R2_MSG_LA "have been rejecting connections on daemon %s for %s"
2338 sm_setproctitle(true, e, R_MSG_LA, Daemons[dn].d_name,
2341 sm_syslog(LOG_NOTICE, NOQID, R_MSG_LA,
2342 Daemons[dn].d_name, CurrentLA);
2344 if (firstrejtime[dn] == 0)
2346 firstrejtime[dn] = now;
2347 nextlogtime[dn] = now + RejectLogInterval;
2349 else if (nextlogtime[dn] < now)
2351 sm_syslog(LOG_ERR, NOQID, R2_MSG_LA, Daemons[dn].d_name,
2352 pintvl(now - firstrejtime[dn], true));
2353 nextlogtime[dn] = now + RejectLogInterval;
2358 firstrejtime[dn] = 0;
2360 limit = (Daemons[dn].d_delayLA != DPO_NOTSET) ?
2361 Daemons[dn].d_delayLA : DelayLA;
2362 if (limit > 0 && CurrentLA >= limit)
2365 static time_t log_delay = (time_t) 0;
2367 # define MIN_DELAY_LOG 90 /* wait before logging this again */
2368 # define D_MSG_LA "delaying connections on daemon %s: load average=%d >= %d"
2369 /* sleep to flatten out connection load */
2370 sm_setproctitle(true, e, D_MSG_LA, Daemons[dn].d_name,
2372 if (LogLevel > 8 && (now = curtime()) > log_delay)
2374 sm_syslog(LOG_INFO, NOQID, D_MSG_LA,
2375 Daemons[dn].d_name, CurrentLA, limit);
2376 log_delay = now + MIN_DELAY_LOG;
2381 limit = (Daemons[dn].d_maxchildren != DPO_NOTSET) ?
2382 Daemons[dn].d_maxchildren : MaxChildren;
2383 if (limit > 0 && CurChildren >= limit)
2386 if (CurChildren >= limit)
2388 #define R_MSG_CHILD "rejecting connections on daemon %s: %d children, max %d"
2389 sm_setproctitle(true, e, R_MSG_CHILD,
2390 Daemons[dn].d_name, CurChildren,
2393 sm_syslog(LOG_INFO, NOQID, R_MSG_CHILD,
2394 Daemons[dn].d_name, CurChildren,
2403 ** SETPROCTITLE -- set process title for ps
2406 ** fmt -- a printf style format string.
2407 ** a, b, c -- possible parameters to fmt.
2413 ** Clobbers argv of our main procedure so ps(1) will
2414 ** display the title.
2417 #define SPT_NONE 0 /* don't use it at all */
2418 #define SPT_REUSEARGV 1 /* cover argv with title information */
2419 #define SPT_BUILTIN 2 /* use libc builtin */
2420 #define SPT_PSTAT 3 /* use pstat(PSTAT_SETCMD, ...) */
2421 #define SPT_PSSTRINGS 4 /* use PS_STRINGS->... */
2422 #define SPT_SYSMIPS 5 /* use sysmips() supported by NEWS-OS 6 */
2423 #define SPT_SCO 6 /* write kernel u. area */
2424 #define SPT_CHANGEARGV 7 /* write our own strings into argv[] */
2427 # define SPT_TYPE SPT_REUSEARGV
2431 #if SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN
2433 # if SPT_TYPE == SPT_PSTAT
2434 # include <sys/pstat.h>
2436 # if SPT_TYPE == SPT_PSSTRINGS
2437 # include <machine/vmparam.h>
2438 # include <sys/exec.h>
2439 # ifndef PS_STRINGS /* hmmmm.... apparently not available after all */
2441 # define SPT_TYPE SPT_REUSEARGV
2442 # else /* ! PS_STRINGS */
2443 # ifndef NKPDE /* FreeBSD 2.0 */
2445 typedef unsigned int *pt_entry_t;
2446 # endif /* ! NKPDE */
2447 # endif /* ! PS_STRINGS */
2448 # endif /* SPT_TYPE == SPT_PSSTRINGS */
2450 # if SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV
2451 # define SETPROC_STATIC static
2453 # define SETPROC_STATIC
2456 # if SPT_TYPE == SPT_SYSMIPS
2457 # include <sys/sysmips.h>
2458 # include <sys/sysnews.h>
2461 # if SPT_TYPE == SPT_SCO
2462 # include <sys/immu.h>
2463 # include <sys/dir.h>
2464 # include <sys/user.h>
2465 # include <sys/fs/s5param.h>
2466 # if PSARGSZ > MAXLINE
2467 # define SPT_BUFSIZE PSARGSZ
2469 # endif /* SPT_TYPE == SPT_SCO */
2471 # ifndef SPT_PADCHAR
2472 # define SPT_PADCHAR ' '
2475 #endif /* SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN */
2478 # define SPT_BUFSIZE MAXLINE
2484 ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to
2485 ** 64 bit alignment, so unless each piece of argv and envp is a multiple
2486 ** of 8 bytes (including terminating NULL), initsetproctitle() won't use
2487 ** any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE if
2488 ** you use this FFR.
2491 # ifdef SPT_ALIGN_SIZE
2492 # define SPT_ALIGN(x, align) (((((x) + SPT_ALIGN_SIZE) >> (align)) << (align)) - 1)
2494 # define SPT_ALIGN(x, align) (x)
2496 #else /* _FFR_SPT_ALIGN */
2497 # define SPT_ALIGN(x, align) (x)
2498 #endif /* _FFR_SPT_ALIGN */
2501 ** Pointers for setproctitle.
2502 ** This allows "ps" listings to give more useful information.
2505 static char **Argv = NULL; /* pointer to argument vector */
2506 static char *LastArgv = NULL; /* end of argv */
2507 #if SPT_TYPE != SPT_BUILTIN
2508 static void setproctitle __P((const char *, ...));
2512 initsetproctitle(argc, argv, envp)
2521 extern char **environ;
2524 ** Move the environment so setproctitle can use the space at
2525 ** the top of memory.
2530 for (i = 0; envp[i] != NULL; i++)
2532 environ = (char **) xalloc(sizeof(char *) * (i + 1));
2533 for (i = 0; envp[i] != NULL; i++)
2534 environ[i] = newstr(envp[i]);
2539 ** Save start and extent of argv for setproctitle.
2545 ** Determine how much space we can use for setproctitle.
2546 ** Use all contiguous argv and envp pointers starting at argv[0]
2551 # ifdef SPT_ALIGN_SIZE
2552 for (i = SPT_ALIGN_SIZE; i > 0; i >>= 1)
2555 # endif /* _FFR_SPT_ALIGN */
2557 for (i = 0; i < argc; i++)
2559 if (i == 0 || LastArgv + 1 == argv[i])
2560 LastArgv = argv[i] + SPT_ALIGN(strlen(argv[i]), align);
2562 for (i = 0; LastArgv != NULL && envp != NULL && envp[i] != NULL; i++)
2564 if (LastArgv + 1 == envp[i])
2565 LastArgv = envp[i] + SPT_ALIGN(strlen(envp[i]), align);
2569 #if SPT_TYPE != SPT_BUILTIN
2574 setproctitle(const char *fmt, ...)
2575 # else /* __STDC__ */
2576 setproctitle(fmt, va_alist)
2579 # endif /* __STDC__ */
2581 # if SPT_TYPE != SPT_NONE
2584 SETPROC_STATIC char buf[SPT_BUFSIZE];
2586 # if SPT_TYPE == SPT_PSTAT
2589 # if SPT_TYPE == SPT_SCO
2592 static int kmem = -1;
2593 static pid_t kmempid = -1;
2595 # endif /* SPT_TYPE == SPT_SCO */
2599 /* print sendmail: heading for grep */
2600 (void) sm_strlcpy(p, "sendmail: ", SPACELEFT(buf, p));
2603 /* print the argument string */
2604 SM_VA_START(ap, fmt);
2605 (void) sm_vsnprintf(p, SPACELEFT(buf, p), fmt, ap);
2608 i = (int) strlen(buf);
2612 # if SPT_TYPE == SPT_PSTAT
2613 pst.pst_command = buf;
2614 pstat(PSTAT_SETCMD, pst, i, 0, 0);
2616 # if SPT_TYPE == SPT_PSSTRINGS
2617 PS_STRINGS->ps_nargvstr = 1;
2618 PS_STRINGS->ps_argvstr = buf;
2620 # if SPT_TYPE == SPT_SYSMIPS
2621 sysmips(SONY_SYSNEWS, NEWS_SETPSARGS, buf);
2623 # if SPT_TYPE == SPT_SCO
2624 if (kmem < 0 || kmempid != CurrentPid)
2628 kmem = open(_PATH_KMEM, O_RDWR, 0);
2631 if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
2632 fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
2638 kmempid = CurrentPid;
2640 buf[PSARGSZ - 1] = '\0';
2641 seek_off = UVUBLK + (off_t) u.u_psargs - (off_t) &u;
2642 if (lseek(kmem, (off_t) seek_off, SEEK_SET) == seek_off)
2643 (void) write(kmem, buf, PSARGSZ);
2644 # endif /* SPT_TYPE == SPT_SCO */
2645 # if SPT_TYPE == SPT_REUSEARGV
2646 if (LastArgv == NULL)
2649 if (i > LastArgv - Argv[0] - 2)
2651 i = LastArgv - Argv[0] - 2;
2654 (void) sm_strlcpy(Argv[0], buf, i + 1);
2656 while (p < LastArgv)
2659 # endif /* SPT_TYPE == SPT_REUSEARGV */
2660 # if SPT_TYPE == SPT_CHANGEARGV
2664 # endif /* SPT_TYPE != SPT_NONE */
2666 #endif /* SPT_TYPE != SPT_BUILTIN */
2669 ** SM_SETPROCTITLE -- set process task and set process title for ps
2671 ** Possibly set process status and call setproctitle() to
2672 ** change the ps display.
2675 ** status -- whether or not to store as process status
2676 ** e -- the current envelope.
2677 ** fmt -- a printf style format string.
2678 ** a, b, c -- possible parameters to fmt.
2687 sm_setproctitle(bool status, ENVELOPE *e, const char *fmt, ...)
2688 #else /* __STDC__ */
2689 sm_setproctitle(status, e, fmt, va_alist)
2694 #endif /* __STDC__ */
2696 char buf[SPT_BUFSIZE];
2699 /* print the argument string */
2700 SM_VA_START(ap, fmt);
2701 (void) sm_vsnprintf(buf, sizeof(buf), fmt, ap);
2705 proc_list_set(CurrentPid, buf);
2707 if (ProcTitlePrefix != NULL)
2709 char prefix[SPT_BUFSIZE];
2711 expand(ProcTitlePrefix, prefix, sizeof(prefix), e);
2712 setproctitle("%s: %s", prefix, buf);
2715 setproctitle("%s", buf);
2718 ** WAITFOR -- wait for a particular process id.
2721 ** pid -- process id to wait for.
2725 ** -1 if pid never shows up.
2743 proc_list_drop(i, st, NULL);
2744 } while ((i >= 0 || errno == EINTR) && i != pid);
2753 ** status -- pointer to status (return value)
2769 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2773 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2774 savesig = sm_releasesignal(SIGCHLD);
2777 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2779 sm_blocksignal(SIGCHLD);
2782 *status = st.w_status;
2789 ** REAPCHILD -- pick up the body of my child, lest it become a zombie
2792 ** sig -- the signal that got us here (unused).
2798 ** Picks up extant zombies.
2799 ** Control socket exits may restart/shutdown daemon.
2801 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2802 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2811 int save_errno = errno;
2819 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2824 # else /* HASWAITPID */
2828 while ((pid = wait3(&status, WNOHANG, (struct rusage *) NULL)) > 0)
2830 st = status.w_status;
2831 # else /* WNOHANG */
2835 ** Catch one zombie -- we will be re-invoked (we hope) if there
2836 ** are more. Unreliable signals probably break this, but this
2837 ** is the "old system" situation -- waitpid or wait3 are to be
2838 ** strongly preferred.
2841 if ((pid = wait(&status)) > 0)
2844 # endif /* WNOHANG */
2845 # endif /* HASWAITPID */
2846 /* Drop PID and check if it was a control socket child */
2847 proc_list_drop(pid, st, NULL);
2849 FIX_SYSV_SIGNAL(sig, reapchild);
2851 return SIGFUNC_RETURN;
2854 ** GETDTSIZE -- return number of file descriptors
2856 ** Only on non-BSD systems
2862 ** size of file descriptor table
2869 # include <sys/resource.h>
2875 # ifdef RLIMIT_NOFILE
2878 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
2880 # endif /* RLIMIT_NOFILE */
2882 # if HASGETDTABLESIZE
2883 return getdtablesize();
2884 # else /* HASGETDTABLESIZE */
2885 # ifdef _SC_OPEN_MAX
2886 return sysconf(_SC_OPEN_MAX);
2890 # endif /* HASGETDTABLESIZE */
2893 ** UNAME -- get the UUCP name of this system.
2900 struct utsname *name;
2905 name->nodename[0] = '\0';
2907 /* try /etc/whoami -- one line with the node name */
2908 if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/etc/whoami",
2909 SM_IO_RDONLY, NULL)) != NULL)
2911 (void) sm_io_fgets(file, SM_TIME_DEFAULT, name->nodename,
2913 (void) sm_io_close(file, SM_TIME_DEFAULT);
2914 n = strchr(name->nodename, '\n');
2917 if (name->nodename[0] != '\0')
2921 /* try /usr/include/whoami.h -- has a #define somewhere */
2922 if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
2923 "/usr/include/whoami.h", SM_IO_RDONLY, NULL))
2928 while (sm_io_fgets(file, SM_TIME_DEFAULT,
2929 buf, sizeof(buf)) >= 0)
2931 if (sm_io_sscanf(buf, "#define sysname \"%*[^\"]\"",
2932 NODE_LENGTH, name->nodename) > 0)
2935 (void) sm_io_close(file, SM_TIME_DEFAULT);
2936 if (name->nodename[0] != '\0')
2942 #endif /* !HASUNAME */
2944 ** INITGROUPS -- initialize groups
2946 ** Stub implementation for System V style systems
2950 initgroups(name, basegid)
2956 #endif /* !HASINITGROUPS */
2959 ** SETGROUPS -- set group list
2961 ** Stub implementation for systems that don't have group lists
2966 setgroups(ngroups, grouplist)
2968 GIDSET_T grouplist[];
2972 #endif /* ! NGROUPS_MAX */
2975 ** SETSID -- set session id (for non-POSIX systems)
2986 fd = open("/dev/tty", O_RDWR, 0);
2989 (void) ioctl(fd, TIOCNOTTY, (char *) 0);
2992 # endif /* TIOCNOTTY */
2996 return setpgid(0, CurrentPid);
3000 #endif /* !HASSETSID */
3002 ** FSYNC -- dummy fsync
3011 return fcntl(fd, F_SETFL, O_SYNC);
3013 /* nothing we can do */
3017 #endif /* NEEDFSYNC */
3020 ** DGUX_INET_ADDR -- inet_addr for DG/UX
3022 ** Data General DG/UX version of inet_addr returns a struct in_addr
3023 ** instead of a long. This patches things. Only needed on versions
3032 dgux_inet_addr(host)
3035 struct in_addr haddr;
3037 haddr = inet_addr(host);
3038 return haddr.s_addr;
3041 #endif /* DGUX_5_4_2 */
3043 ** GETOPT -- for old systems or systems with bogus implementations
3049 * Copyright (c) 1985 Regents of the University of California.
3050 * All rights reserved. The Berkeley software License Agreement
3051 * specifies the terms and conditions for redistribution.
3056 ** this version hacked to add `atend' flag to allow state machine
3057 ** to reset if invoked by the program to scan args for a 2nd time
3060 # if defined(LIBC_SCCS) && !defined(lint)
3061 static char sccsid[] = "@(#)getopt.c 4.3 (Berkeley) 3/9/86";
3065 ** get option letter from argument vector
3067 # ifdef _CONVEX_SOURCE
3068 extern int optind, opterr, optopt;
3069 extern char *optarg;
3070 # else /* _CONVEX_SOURCE */
3071 int opterr = 1; /* if error message should be printed */
3072 int optind = 1; /* index into parent argv vector */
3073 int optopt = 0; /* character checked for validity */
3074 char *optarg = NULL; /* argument associated with option */
3075 # endif /* _CONVEX_SOURCE */
3077 # define BADCH (int)'?'
3079 # define tell(s) if (opterr) \
3080 {sm_io_fputs(smioerr, SM_TIME_DEFAULT, *nargv); \
3081 (void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, s); \
3082 (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, optopt); \
3083 (void) sm_io_putc(smioerr, SM_TIME_DEFAULT, '\n'); \
3087 getopt(nargc,nargv,ostr)
3092 static char *place = EMSG; /* option letter processing */
3093 static char atend = 0;
3094 register char *oli = NULL; /* option letter list index */
3100 if(!*place) { /* update scanning pointer */
3101 if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) {
3105 if (*place == '-') { /* found "--" */
3110 } /* option letter okay? */
3111 if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) {
3112 if (!*place) ++optind;
3113 tell(": illegal option -- ");
3115 if (oli && *++oli != ':') { /* don't need argument */
3117 if (!*place) ++optind;
3119 else { /* need an argument */
3120 if (*place) optarg = place; /* no white space */
3121 else if (nargc <= ++optind) { /* no arg */
3123 tell(": option requires an argument -- ");
3125 else optarg = nargv[optind]; /* white space */
3129 return optopt; /* dump back option letter */
3132 #endif /* !SM_CONF_GETOPT */
3134 ** USERSHELLOK -- tell if a user's shell is ok for unrestricted use
3137 ** user -- the name of the user we are checking.
3138 ** shell -- the user's shell from /etc/passwd
3141 ** true -- if it is ok to use this for unrestricted access.
3142 ** false -- if the shell is restricted.
3145 #if !HASGETUSERSHELL
3147 # ifndef _PATH_SHELLS
3148 # define _PATH_SHELLS "/etc/shells"
3151 # if defined(_AIX3) || defined(_AIX4)
3152 # include <userconf.h>
3154 # include <userpw.h>
3156 # include <usersec.h>
3157 # endif /* defined(_AIX3) || defined(_AIX4) */
3159 static char *DefaultUserShells[] =
3161 "/bin/sh", /* standard shell */
3166 "/bin/csh", /* C shell */
3171 "/usr/bin/rsh", /* restricted Bourne shell */
3172 "/usr/bin/ksh", /* Korn shell */
3173 "/usr/bin/rksh", /* restricted Korn shell */
3175 "/usr/bin/keysh", /* key shell (extended Korn shell) */
3176 "/usr/bin/posix/sh",
3178 "/bin/rsh", /* restricted Bourne shell */
3179 "/bin/ksh", /* Korn shell */
3180 "/bin/rksh", /* restricted Korn shell */
3182 "/usr/bin/keysh", /* key shell (extended Korn shell) */
3186 # endif /* __hpux */
3187 # if defined(_AIX3) || defined(_AIX4)
3188 "/bin/ksh", /* Korn shell */
3190 "/bin/tsh", /* trusted shell */
3192 "/bin/bsh", /* Bourne shell */
3194 # endif /* defined(_AIX3) || defined(_AIX4) */
3195 # if defined(__svr4__) || defined(__svr5__)
3196 "/bin/ksh", /* Korn shell */
3198 # endif /* defined(__svr4__) || defined(__svr5__) */
3200 "/sbin/sh", /* SGI's shells really live in /sbin */
3202 "/sbin/bsh", /* classic Bourne shell */
3205 "/sbin/csh", /* standard csh */
3208 "/sbin/jsh", /* classic Bourne shell w/ job control*/
3211 "/bin/ksh", /* Korn shell */
3214 "/sbin/tcsh", /* Extended csh */
3221 #endif /* !HASGETUSERSHELL */
3223 #define WILDCARD_SHELL "/SENDMAIL/ANY/SHELL/"
3226 usershellok(user, shell)
3230 # if HASGETUSERSHELL
3232 extern char *getusershell();
3234 if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') ||
3239 while ((p = getusershell()) != NULL)
3240 if (strcmp(p, shell) == 0 || strcmp(p, WILDCARD_SHELL) == 0)
3244 # else /* HASGETUSERSHELL */
3248 register SM_FILE_T *shellf;
3251 if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') ||
3257 ** Naturally IBM has a "better" idea.....
3259 ** What a crock. This interface isn't documented, it is
3260 ** considered part of the security library (-ls), and it
3261 ** only works if you are running as root (since the list
3262 ** of valid shells is obviously a source of great concern).
3263 ** I recommend that you do NOT define USEGETCONFATTR,
3264 ** especially since you are going to have to set up an
3265 ** /etc/shells anyhow to handle the cases where getconfattr
3269 if (getconfattr(SC_SYS_LOGIN, SC_SHELLS, &v, SEC_LIST) == 0 && v != NULL)
3273 if (strcmp(v, shell) == 0 || strcmp(v, WILDCARD_SHELL) == 0)
3279 # endif /* USEGETCONFATTR */
3281 shellf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_SHELLS,
3282 SM_IO_RDONLY, NULL);
3285 /* no /etc/shells; see if it is one of the std shells */
3288 if (errno != ENOENT && LogLevel > 3)
3289 sm_syslog(LOG_ERR, NOQID,
3290 "usershellok: cannot open %s: %s",
3291 _PATH_SHELLS, sm_errstring(errno));
3293 for (d = DefaultUserShells; *d != NULL; d++)
3295 if (strcmp(shell, *d) == 0)
3301 while (sm_io_fgets(shellf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0)
3303 register char *p, *q;
3306 while (*p != '\0' && *p != '#' && *p != '/')
3308 if (*p == '#' || *p == '\0')
3311 while (*p != '\0' && *p != '#' && !(SM_ISSPACE(*p)))
3314 if (strcmp(shell, q) == 0 || strcmp(WILDCARD_SHELL, q) == 0)
3316 (void) sm_io_close(shellf, SM_TIME_DEFAULT);
3320 (void) sm_io_close(shellf, SM_TIME_DEFAULT);
3322 # endif /* HASGETUSERSHELL */
3325 ** FREEDISKSPACE -- see how much free space is on the queue filesystem
3327 ** Only implemented if you have statfs.
3330 ** dir -- the directory in question.
3331 ** bsize -- a variable into which the filesystem
3332 ** block size is stored.
3335 ** The number of blocks free on the queue filesystem.
3336 ** -1 if the statfs call fails.
3339 ** Puts the filesystem block size into bsize.
3343 # define SFS_NONE 0 /* no statfs implementation */
3344 # define SFS_USTAT 1 /* use ustat */
3345 # define SFS_4ARGS 2 /* use four-argument statfs call */
3346 # define SFS_VFS 3 /* use <sys/vfs.h> implementation */
3347 # define SFS_MOUNT 4 /* use <sys/mount.h> implementation */
3348 # define SFS_STATFS 5 /* use <sys/statfs.h> implementation */
3349 # define SFS_STATVFS 6 /* use <sys/statvfs.h> implementation */
3352 # define SFS_TYPE SFS_NONE
3355 # if SFS_TYPE == SFS_USTAT
3358 # if SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS
3359 # include <sys/statfs.h>
3361 # if SFS_TYPE == SFS_VFS
3362 # include <sys/vfs.h>
3364 # if SFS_TYPE == SFS_MOUNT
3365 # include <sys/mount.h>
3367 # if SFS_TYPE == SFS_STATVFS
3368 # include <sys/statvfs.h>
3372 freediskspace(dir, bsize)
3376 # if SFS_TYPE == SFS_NONE
3380 /* assume free space is plentiful */
3381 return (long) LONG_MAX;
3382 # else /* SFS_TYPE == SFS_NONE */
3383 # if SFS_TYPE == SFS_USTAT
3385 struct stat statbuf;
3386 # define FSBLOCKSIZE DEV_BSIZE
3387 # define SFS_BAVAIL f_tfree
3388 # else /* SFS_TYPE == SFS_USTAT */
3389 # if defined(ultrix)
3391 # define SFS_BAVAIL fd_bfreen
3392 # define FSBLOCKSIZE 1024L
3393 # else /* defined(ultrix) */
3394 # if SFS_TYPE == SFS_STATVFS
3396 # define FSBLOCKSIZE fs.f_frsize
3397 # else /* SFS_TYPE == SFS_STATVFS */
3399 # define FSBLOCKSIZE fs.f_bsize
3400 # endif /* SFS_TYPE == SFS_STATVFS */
3401 # endif /* defined(ultrix) */
3402 # endif /* SFS_TYPE == SFS_USTAT */
3404 # define SFS_BAVAIL f_bavail
3407 # if SFS_TYPE == SFS_USTAT
3408 if (stat(dir, &statbuf) == 0 && ustat(statbuf.st_dev, &fs) == 0)
3409 # else /* SFS_TYPE == SFS_USTAT */
3410 # if SFS_TYPE == SFS_4ARGS
3411 if (statfs(dir, &fs, sizeof(fs), 0) == 0)
3412 # else /* SFS_TYPE == SFS_4ARGS */
3413 # if SFS_TYPE == SFS_STATVFS
3414 if (statvfs(dir, &fs) == 0)
3415 # else /* SFS_TYPE == SFS_STATVFS */
3416 # if defined(ultrix)
3417 if (statfs(dir, &fs) > 0)
3418 # else /* defined(ultrix) */
3419 if (statfs(dir, &fs) == 0)
3420 # endif /* defined(ultrix) */
3421 # endif /* SFS_TYPE == SFS_STATVFS */
3422 # endif /* SFS_TYPE == SFS_4ARGS */
3423 # endif /* SFS_TYPE == SFS_USTAT */
3426 *bsize = FSBLOCKSIZE;
3427 if (fs.SFS_BAVAIL <= 0)
3429 else if (fs.SFS_BAVAIL > LONG_MAX)
3430 return (long) LONG_MAX;
3432 return (long) fs.SFS_BAVAIL;
3435 # endif /* SFS_TYPE == SFS_NONE */
3438 ** ENOUGHDISKSPACE -- is there enough free space on the queue file systems?
3441 ** msize -- the size to check against. If zero, we don't yet
3442 ** know how big the message will be, so just check for
3443 ** a "reasonable" amount.
3444 ** e -- envelope, or NULL -- controls logging
3447 ** true if in every queue group there is at least one
3448 ** queue directory whose file system contains enough free space.
3452 ** If there is not enough disk space and e != NULL
3453 ** then sm_syslog is called.
3457 enoughdiskspace(msize, e)
3467 if (MinBlocksFree <= 0 && msize <= 0)
3470 sm_dprintf("enoughdiskspace: no threshold\n");
3475 for (i = 0; i < NumQueue; ++i)
3477 if (pickqdir(Queue[i], msize, e) < 0)
3483 ** TRANSIENTERROR -- tell if an error code indicates a transient failure
3485 ** This looks at an errno value and tells if this is likely to
3486 ** go away if retried later.
3489 ** err -- the errno code to classify.
3492 ** true if this is probably transient.
3502 case EIO: /* I/O error */
3503 case ENXIO: /* Device not configured */
3504 case EAGAIN: /* Resource temporarily unavailable */
3505 case ENOMEM: /* Cannot allocate memory */
3506 case ENODEV: /* Operation not supported by device */
3507 case ENFILE: /* Too many open files in system */
3508 case EMFILE: /* Too many open files */
3509 case ENOSPC: /* No space left on device */
3510 case ETIMEDOUT: /* Connection timed out */
3512 case ESTALE: /* Stale NFS file handle */
3515 case ENETDOWN: /* Network is down */
3518 case ENETUNREACH: /* Network is unreachable */
3521 case ENETRESET: /* Network dropped connection on reset */
3524 case ECONNABORTED: /* Software caused connection abort */
3527 case ECONNRESET: /* Connection reset by peer */
3530 case ENOBUFS: /* No buffer space available */
3533 case ESHUTDOWN: /* Can't send after socket shutdown */
3536 case ECONNREFUSED: /* Connection refused */
3539 case EHOSTDOWN: /* Host is down */
3542 case EHOSTUNREACH: /* No route to host */
3545 case EDQUOT: /* Disc quota exceeded */
3548 case EPROCLIM: /* Too many processes */
3551 case EUSERS: /* Too many users */
3554 case EDEADLK: /* Resource deadlock avoided */
3557 case EISCONN: /* Socket already connected */
3560 case EINPROGRESS: /* Operation now in progress */
3563 case EALREADY: /* Operation already in progress */
3566 case EADDRINUSE: /* Address already in use */
3568 #ifdef EADDRNOTAVAIL
3569 case EADDRNOTAVAIL: /* Can't assign requested address */
3572 case ETXTBSY: /* (Apollo) file locked */
3574 #if defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR))
3575 case ENOSR: /* Out of streams resources */
3578 case ENOLCK: /* No locks available */
3580 case E_SM_OPENTIMEOUT: /* PSEUDO: open timed out */
3584 /* nope, must be permanent */
3588 ** LOCKFILE -- lock a file using flock or (shudder) fcntl locking
3591 ** fd -- the file descriptor of the file.
3592 ** filename -- the file name (for error messages).
3593 ** ext -- the filename extension.
3594 ** type -- type of the lock. Bits can be:
3595 ** LOCK_EX -- exclusive lock.
3596 ** LOCK_NB -- non-blocking.
3597 ** LOCK_UN -- unlock.
3600 ** true if the lock was acquired.
3605 lockfile(fd, filename, ext, type)
3620 memset(&lfd, '\0', sizeof(lfd));
3621 if (bitset(LOCK_UN, type))
3622 lfd.l_type = F_UNLCK;
3623 else if (bitset(LOCK_EX, type))
3624 lfd.l_type = F_WRLCK;
3626 lfd.l_type = F_RDLCK;
3628 if (bitset(LOCK_NB, type))
3634 sm_dprintf("lockfile(%s%s, action=%d, type=%d): ",
3635 filename, ext, action, lfd.l_type);
3637 while ((i = fcntl(fd, action, &lfd)) < 0 && errno == EINTR)
3642 sm_dprintf("SUCCESS\n");
3648 sm_dprintf("(%s) ", sm_errstring(save_errno));
3651 ** On SunOS, if you are testing using -oQ/tmp/mqueue or
3652 ** -oA/tmp/aliases or anything like that, and /tmp is mounted
3653 ** as type "tmp" (that is, served from swap space), the
3654 ** previous fcntl will fail with "Invalid argument" errors.
3655 ** Since this is fairly common during testing, we will assume
3656 ** that this indicates that the lock is successfully grabbed.
3659 if (save_errno == EINVAL)
3662 sm_dprintf("SUCCESS\n");
3666 if (!bitset(LOCK_NB, type) ||
3667 (save_errno != EACCES && save_errno != EAGAIN))
3669 int omode = fcntl(fd, F_GETFL, 0);
3670 uid_t euid = geteuid();
3673 syserr("cannot lockf(%s%s, fd=%d, type=%o, omode=%o, euid=%ld)",
3674 filename, ext, fd, type, omode, (long) euid);
3675 dumpfd(fd, true, true);
3677 # else /* !HASFLOCK */
3682 sm_dprintf("lockfile(%s%s, type=%o): ", filename, ext, type);
3684 while ((i = flock(fd, type)) < 0 && errno == EINTR)
3689 sm_dprintf("SUCCESS\n");
3695 sm_dprintf("(%s) ", sm_errstring(save_errno));
3697 if (!bitset(LOCK_NB, type) || save_errno != EWOULDBLOCK)
3699 int omode = fcntl(fd, F_GETFL, 0);
3700 uid_t euid = geteuid();
3703 syserr("cannot flock(%s%s, fd=%d, type=%o, omode=%o, euid=%ld)",
3704 filename, ext, fd, type, omode, (long) euid);
3705 dumpfd(fd, true, true);
3707 # endif /* !HASFLOCK */
3709 sm_dprintf("FAIL\n");
3714 ** CHOWNSAFE -- tell if chown is "safe" (executable only by root)
3716 ** Unfortunately, given that we can't predict other systems on which
3717 ** a remote mounted (NFS) filesystem will be mounted, the answer is
3718 ** almost always that this is unsafe.
3720 ** Note also that many operating systems have non-compliant
3721 ** implementations of the _POSIX_CHOWN_RESTRICTED variable and the
3722 ** fpathconf() routine. According to IEEE 1003.1-1990, if
3723 ** _POSIX_CHOWN_RESTRICTED is defined and not equal to -1, then
3724 ** no non-root process can give away the file. However, vendors
3725 ** don't take NFS into account, so a comfortable value of
3726 ** _POSIX_CHOWN_RESTRICTED tells us nothing.
3728 ** Also, some systems (e.g., IRIX 6.2) return 1 from fpathconf()
3729 ** even on files where chown is not restricted. Many systems get
3730 ** this wrong on NFS-based filesystems (that is, they say that chown
3731 ** is restricted [safe] on NFS filesystems where it may not be, since
3732 ** other systems can access the same filesystem and do file giveaway;
3733 ** only the NFS server knows for sure!) Hence, it is important to
3734 ** get the value of SAFENFSPATHCONF correct -- it should be defined
3735 ** _only_ after testing (see test/t_pathconf.c) a system on an unsafe
3736 ** NFS-based filesystem to ensure that you can get meaningful results.
3737 ** If in doubt, assume unsafe!
3739 ** You may also need to tweak IS_SAFE_CHOWN -- it should be a
3740 ** condition indicating whether the return from pathconf indicates
3741 ** that chown is safe (typically either > 0 or >= 0 -- there isn't
3742 ** even any agreement about whether a zero return means that a file
3743 ** is or is not safe). It defaults to "> 0".
3745 ** If the parent directory is safe (writable only by owner back
3746 ** to the root) then we can relax slightly and trust fpathconf
3747 ** in more circumstances. This is really a crock -- if this is an
3748 ** NFS mounted filesystem then we really know nothing about the
3749 ** underlying implementation. However, most systems pessimize and
3750 ** return an error (EINVAL or EOPNOTSUPP) on NFS filesystems, which
3751 ** we interpret as unsafe, as we should. Thus, this heuristic gets
3752 ** us into a possible problem only on systems that have a broken
3753 ** pathconf implementation and which are also poorly configured
3754 ** (have :include: files in group- or world-writable directories).
3757 ** fd -- the file descriptor to check.
3758 ** safedir -- set if the parent directory is safe.
3761 ** true -- if the chown(2) operation is "safe" -- that is,
3762 ** only root can chown the file to an arbitrary user.
3763 ** false -- if an arbitrary user can give away a file.
3766 #ifndef IS_SAFE_CHOWN
3767 # define IS_SAFE_CHOWN > 0
3771 chownsafe(fd, safedir)
3775 # if (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && \
3776 (defined(_PC_CHOWN_RESTRICTED) || defined(_GNU_TYPES_H))
3779 /* give the system administrator a chance to override */
3780 if (bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail))
3784 ** Some systems (e.g., SunOS) seem to have the call and the
3785 ** #define _PC_CHOWN_RESTRICTED, but don't actually implement
3786 ** the call. This heuristic checks for that.
3790 rval = fpathconf(fd, _PC_CHOWN_RESTRICTED);
3791 # if SAFENFSPATHCONF
3792 return errno == 0 && rval IS_SAFE_CHOWN;
3794 return safedir && errno == 0 && rval IS_SAFE_CHOWN;
3796 # else /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */
3797 return bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail);
3798 # endif /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */
3801 ** RESETLIMITS -- reset system controlled resource limits
3803 ** This is to avoid denial-of-service attacks
3813 # ifdef RLIMIT_NEEDS_SYS_TIME_H
3814 # include <sm/time.h>
3816 # include <sys/resource.h>
3817 #endif /* HASSETRLIMIT */
3825 lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
3826 (void) setrlimit(RLIMIT_CPU, &lim);
3827 (void) setrlimit(RLIMIT_FSIZE, &lim);
3828 # ifdef RLIMIT_NOFILE
3829 lim.rlim_cur = lim.rlim_max = FD_SETSIZE;
3830 (void) setrlimit(RLIMIT_NOFILE, &lim);
3832 #else /* HASSETRLIMIT */
3834 (void) ulimit(2, 0x3fffff);
3835 (void) ulimit(4, FD_SETSIZE);
3837 #endif /* HASSETRLIMIT */
3841 ** SETVENDOR -- process vendor code from V configuration line
3844 ** vendor -- string representation of vendor.
3848 ** false -- if vendor code could not be processed.
3851 ** It is reasonable to set mode flags here to tweak
3852 ** processing in other parts of the code if necessary.
3853 ** For example, if you are a vendor that uses $%y to
3854 ** indicate YP lookups, you could enable that here.
3861 if (sm_strcasecmp(vendor, "Berkeley") == 0)
3863 VendorCode = VENDOR_BERKELEY;
3867 /* add vendor extensions here */
3869 #ifdef SUN_EXTENSIONS
3870 if (sm_strcasecmp(vendor, "Sun") == 0)
3872 VendorCode = VENDOR_SUN;
3875 #endif /* SUN_EXTENSIONS */
3877 if (sm_strcasecmp(vendor, "Digital") == 0)
3879 VendorCode = VENDOR_DEC;
3884 #if defined(VENDOR_NAME) && defined(VENDOR_CODE)
3885 if (sm_strcasecmp(vendor, VENDOR_NAME) == 0)
3887 VendorCode = VENDOR_CODE;
3890 #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */
3895 ** GETVENDOR -- return vendor name based on vendor code
3898 ** vendorcode -- numeric representation of vendor.
3901 ** string containing vendor name.
3905 getvendor(vendorcode)
3908 #if defined(VENDOR_NAME) && defined(VENDOR_CODE)
3910 ** Can't have the same switch case twice so need to
3911 ** handle VENDOR_CODE outside of switch. It might
3912 ** match one of the existing VENDOR_* codes.
3915 if (vendorcode == VENDOR_CODE)
3917 #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */
3921 case VENDOR_BERKELEY:
3933 case VENDOR_SENDMAIL:
3941 ** VENDOR_PRE_DEFAULTS, VENDOR_POST_DEFAULTS -- set vendor-specific defaults
3943 ** Vendor_pre_defaults is called before reading the configuration
3944 ** file; vendor_post_defaults is called immediately after.
3947 ** e -- the global environment to initialize.
3954 int DefShareUid; /* default share uid to run as -- unused??? */
3958 vendor_pre_defaults(e)
3962 /* OTHERUID is defined in shares.h, do not be alarmed */
3963 DefShareUid = OTHERUID;
3965 #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES)
3966 sun_pre_defaults(e);
3970 ** stupid domain/os can't even open
3971 ** /etc/mail/sendmail.cf without this
3974 sm_setuserenv("ISP", NULL);
3975 sm_setuserenv("SYSTYPE", NULL);
3981 vendor_post_defaults(e)
3985 /* Makes sure the SOCK environment variable remains */
3986 sm_setuserenv("SOCK", NULL);
3988 #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES)
3989 sun_post_defaults(e);
3993 ** VENDOR_DAEMON_SETUP -- special vendor setup needed for daemon mode
3997 vendor_daemon_setup(e)
4001 (void) setlogin(RunAsUserName);
4004 if (getluid() != -1)
4006 usrerr("Daemon cannot have LUID");
4007 finis(false, true, EX_USAGE);
4009 #endif /* SECUREWARE */
4012 ** VENDOR_SET_UID -- do setup for setting a user id
4014 ** This is called when we are still root.
4017 ** uid -- the uid we are about to become.
4028 ** We need to setup the share groups (lnodes)
4029 ** and add auditing information (luid's)
4030 ** before we loose our ``root''ness.
4033 if (setupshares(uid, syserr) != 0)
4034 syserr("Unable to set up shares");
4037 (void) setup_secure(uid);
4041 ** VALIDATE_CONNECTION -- check connection for rationality
4043 ** If the connection is rejected, this routine should log an
4044 ** appropriate message -- but should never issue any SMTP protocol.
4047 ** sap -- a pointer to a SOCKADDR naming the peer.
4048 ** hostname -- the name corresponding to sap.
4049 ** e -- the current envelope.
4052 ** error message from rejection.
4053 ** NULL if not rejected.
4059 /* tcpwrappers does no logging, but you still have to declare these -- ugh */
4060 int allow_severity = LOG_INFO;
4061 int deny_severity = LOG_NOTICE;
4062 #endif /* TCPWRAPPERS */
4065 validate_connection(sap, hostname, e)
4073 extern int hosts_ctl();
4074 #endif /* TCPWRAPPERS */
4077 sm_dprintf("validate_connection(%s, %s)\n",
4078 hostname, anynet_ntoa(sap));
4080 connection_rate_check(sap, e);
4081 if (rscheck("check_relay", hostname, anynet_ntoa(sap), e,
4082 RSF_RMCOMM|RSF_COUNT, 3, NULL, NOQID, NULL, NULL) != EX_OK)
4084 static char reject[BUFSIZ*2];
4085 extern char MsgBuf[];
4088 sm_dprintf(" ... validate_connection: BAD (rscheck)\n");
4090 if (strlen(MsgBuf) >= 3)
4091 (void) sm_strlcpy(reject, MsgBuf, sizeof(reject));
4093 (void) sm_strlcpy(reject, "Access denied", sizeof(reject));
4099 if (hostname[0] == '[' && hostname[strlen(hostname) - 1] == ']')
4103 addr = anynet_ntoa(sap);
4106 /* TCP/Wrappers don't want the IPv6: protocol label */
4107 if (addr != NULL && sm_strncasecmp(addr, "IPv6:", 5) == 0)
4109 # endif /* NETINET6 */
4111 if (!hosts_ctl("sendmail", host, addr, STRING_UNKNOWN))
4114 sm_dprintf(" ... validate_connection: BAD (tcpwrappers)\n");
4116 sm_syslog(LOG_NOTICE, e->e_id,
4117 "tcpwrappers (%s, %s) rejection",
4119 return "Access denied";
4121 #endif /* TCPWRAPPERS */
4123 sm_dprintf(" ... validate_connection: OK\n");
4128 ** STRTOL -- convert string to long integer
4130 ** For systems that don't have it in the C library.
4132 ** This is taken verbatim from the 4.4-Lite C library.
4137 # if defined(LIBC_SCCS) && !defined(lint)
4138 static char sccsid[] = "@(#)strtol.c 8.1 (Berkeley) 6/4/93";
4142 ** Convert a string to a long integer.
4144 ** Ignores `locale' stuff. Assumes that the upper and lower case
4145 ** alphabets and digits are each contiguous.
4149 strtol(nptr, endptr, base)
4154 register const char *s = nptr;
4155 register unsigned long acc;
4157 register unsigned long cutoff;
4158 register int neg = 0, any, cutlim;
4161 ** Skip white space and pick up leading +/- sign if any.
4162 ** If base is 0, allow 0x for hex and 0 for octal, else
4163 ** assume decimal; if base is already 16, allow 0x.
4167 } while (SM_ISSPACE(c));
4171 } else if (c == '+')
4173 if ((base == 0 || base == 16) &&
4174 c == '0' && (*s == 'x' || *s == 'X')) {
4180 base = c == '0' ? 8 : 10;
4183 ** Compute the cutoff value between legal numbers and illegal
4184 ** numbers. That is the largest legal value, divided by the
4185 ** base. An input number that is greater than this value, if
4186 ** followed by a legal input character, is too big. One that
4187 ** is equal to this value may be valid or not; the limit
4188 ** between valid and invalid numbers is then based on the last
4189 ** digit. For instance, if the range for longs is
4190 ** [-2147483648..2147483647] and the input base is 10,
4191 ** cutoff will be set to 214748364 and cutlim to either
4192 ** 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
4193 ** a value > 214748364, or equal but the next digit is > 7 (or 8),
4194 ** the number is too big, and we will return a range error.
4196 ** Set any if any `digits' consumed; make it negative to indicate
4199 cutoff = neg ? -(unsigned long) LONG_MIN : LONG_MAX;
4200 cutlim = cutoff % (unsigned long) base;
4201 cutoff /= (unsigned long) base;
4202 for (acc = 0, any = 0;; c = *s++) {
4203 if (isascii(c) && isdigit(c))
4205 else if (isascii(c) && isalpha(c))
4206 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4211 if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
4220 acc = neg ? LONG_MIN : LONG_MAX;
4225 *endptr = (char *)(any ? s - 1 : nptr);
4229 #endif /* NEEDSTRTOL */
4231 ** STRSTR -- find first substring in string
4234 ** big -- the big (full) string.
4235 ** little -- the little (sub) string.
4238 ** A pointer to the first instance of little in big.
4239 ** big if little is the null string.
4240 ** NULL if little is not contained in big.
4250 register char *p = big;
4253 if (*little == '\0')
4257 while ((p = strchr(p, *little)) != NULL)
4259 if (strncmp(p, little, l) == 0)
4266 #endif /* NEEDSTRSTR */
4268 ** SM_GETHOSTBY{NAME,ADDR} -- compatibility routines for gethostbyXXX
4270 ** Some operating systems have weird problems with the gethostbyXXX
4271 ** routines. For example, Solaris versions at least through 2.3
4272 ** don't properly deliver a canonical h_name field. This tries to
4273 ** work around these problems.
4275 ** Support IPv6 as well as IPv4.
4278 #if NETINET6 && NEEDSGETIPNODE
4281 # define AI_DEFAULT 0 /* dummy */
4283 # ifndef AI_ADDRCONFIG
4284 # define AI_ADDRCONFIG 0 /* dummy */
4286 # ifndef AI_V4MAPPED
4287 # define AI_V4MAPPED 0 /* dummy */
4290 # define AI_ALL 0 /* dummy */
4293 static struct hostent *
4294 sm_getipnodebyname(name, family, flags, err)
4301 # if HAS_GETHOSTBYNAME2
4303 h = gethostbyname2(name, family);
4308 # else /* HAS_GETHOSTBYNAME2 */
4309 # ifdef RES_USE_INET6
4312 if (family == AF_INET6)
4314 /* From RFC2133, section 6.1 */
4315 resv6 = bitset(RES_USE_INET6, _res.options);
4316 _res.options |= RES_USE_INET6;
4318 # endif /* RES_USE_INET6 */
4320 h = gethostbyname(name);
4321 # ifdef RES_USE_INET6
4323 _res.options &= ~RES_USE_INET6;
4326 /* the function is supposed to return only the requested family */
4327 if (h != NULL && h->h_addrtype != family)
4338 # endif /* HAS_GETHOSTBYNAME2 */
4341 static struct hostent *
4342 sm_getipnodebyaddr(addr, len, family, err)
4351 h = gethostbyaddr(addr, len, family);
4361 ** Stub routine -- if they don't have getipnodeby*(),
4362 ** they probably don't have the free routine either.
4367 #endif /* NETINET6 && NEEDSGETIPNODE */
4370 sm_gethostbyname(name, family)
4375 struct hostent *h = NULL;
4376 #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4))
4377 # if SOLARIS == 20300 || SOLARIS == 203
4378 static struct hostent hp;
4379 static char buf[1000];
4380 extern struct hostent *_switch_gethostbyname_r();
4383 sm_dprintf("_switch_gethostbyname_r(%s)... ", name);
4384 h = _switch_gethostbyname_r(name, &hp, buf, sizeof(buf), &h_errno);
4386 # else /* SOLARIS == 20300 || SOLARIS == 203 */
4387 extern struct hostent *__switch_gethostbyname();
4390 sm_dprintf("__switch_gethostbyname(%s)... ", name);
4391 h = __switch_gethostbyname(name);
4393 # endif /* SOLARIS == 20300 || SOLARIS == 203 */
4394 #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */
4397 # ifndef SM_IPNODEBYNAME_FLAGS
4398 /* For IPv4-mapped addresses, use: AI_DEFAULT|AI_ALL */
4399 # define SM_IPNODEBYNAME_FLAGS AI_ADDRCONFIG
4402 int flags = SM_IPNODEBYNAME_FLAGS;
4404 # endif /* NETINET6 */
4405 char *maptype[MAXMAPSTACK];
4406 short mapreturn[MAXMAPACTIONS];
4410 sm_dprintf("sm_gethostbyname(%s, %d)... ", name, family);
4413 # if ADDRCONFIG_IS_BROKEN
4414 flags &= ~AI_ADDRCONFIG;
4416 h = sm_getipnodebyname(name, family, flags, &err);
4417 SM_SET_H_ERRNO(err);
4418 # else /* NETINET6 */
4419 h = gethostbyname(name);
4420 # endif /* NETINET6 */
4426 sm_dprintf("failure\n");
4428 nmaps = switch_map_find("hosts", maptype, mapreturn);
4429 while (--nmaps >= 0)
4431 if (strcmp(maptype[nmaps], "nis") == 0 ||
4432 strcmp(maptype[nmaps], "files") == 0)
4438 /* try short name */
4439 if (strlen(name) > sizeof(hbuf) - 1)
4444 (void) sm_strlcpy(hbuf, name, sizeof(hbuf));
4445 (void) shorten_hostname(hbuf);
4447 /* if it hasn't been shortened, there's no point */
4448 if (strcmp(hbuf, name) != 0)
4451 sm_dprintf("sm_gethostbyname(%s, %d)... ",
4455 h = sm_getipnodebyname(hbuf, family, flags, &err);
4456 SM_SET_H_ERRNO(err);
4458 # else /* NETINET6 */
4459 h = gethostbyname(hbuf);
4461 # endif /* NETINET6 */
4465 #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) || (defined(sony_news) && defined(__svr4)) */
4467 /* the function is supposed to return only the requested family */
4468 if (h != NULL && h->h_addrtype != family)
4474 SM_SET_H_ERRNO(NO_DATA);
4480 sm_dprintf("failure\n");
4483 sm_dprintf("%s\n", h->h_name);
4489 struct in6_addr ia6;
4490 char buf6[INET6_ADDRSTRLEN];
4493 if (h->h_aliases != NULL)
4494 for (i = 0; h->h_aliases[i] != NULL;
4496 sm_dprintf("\talias: %s\n",
4498 for (i = 0; h->h_addr_list[i] != NULL; i++)
4504 if (h->h_addrtype == AF_INET6)
4506 memmove(&ia6, h->h_addr_list[i],
4508 addr = anynet_ntop(&ia6,
4509 buf6, sizeof(buf6));
4512 #endif /* NETINET6 */
4513 /* "else" in #if code above */
4515 memmove(&ia, h->h_addr_list[i],
4517 addr = (char *) inet_ntoa(ia);
4520 sm_dprintf("\taddr: %s\n", addr);
4530 sm_gethostbyaddr(addr, len, type)
4538 if (type == AF_INET6 &&
4539 IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *) addr))
4541 /* Avoid reverse lookup for IPv6 unspecified address */
4542 SM_SET_H_ERRNO(HOST_NOT_FOUND);
4545 #endif /* NETINET6 */
4547 #if (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204)
4548 # if SOLARIS == 20300 || SOLARIS == 203
4550 static struct hostent he;
4551 static char buf[1000];
4552 extern struct hostent *_switch_gethostbyaddr_r();
4554 hp = _switch_gethostbyaddr_r(addr, len, type, &he,
4555 buf, sizeof(buf), &h_errno);
4557 # else /* SOLARIS == 20300 || SOLARIS == 203 */
4559 extern struct hostent *__switch_gethostbyaddr();
4561 hp = __switch_gethostbyaddr(addr, len, type);
4563 # endif /* SOLARIS == 20300 || SOLARIS == 203 */
4564 #else /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */
4569 hp = sm_getipnodebyaddr(addr, len, type, &err);
4570 SM_SET_H_ERRNO(err);
4572 # else /* NETINET6 */
4573 hp = gethostbyaddr(addr, len, type);
4574 # endif /* NETINET6 */
4575 #endif /* (SOLARIS > 10000 && SOLARIS < 20400) || (defined(SOLARIS) && SOLARIS < 204) */
4579 ** SM_GETPW{NAM,UID} -- wrapper for getpwnam and getpwuid
4587 extern struct passwd *_getpwnam_shadow(const char *, const int);
4589 return _getpwnam_shadow(user, 0);
4591 return getpwnam(user);
4599 #if defined(_AIX4) && 0
4600 extern struct passwd *_getpwuid_shadow(const int, const int);
4602 return _getpwuid_shadow(uid,0);
4603 #else /* defined(_AIX4) && 0 */
4604 return getpwuid(uid);
4605 #endif /* defined(_AIX4) && 0 */
4608 ** SECUREWARE_SETUP_SECURE -- Convex SecureWare setup
4610 ** Set up the trusted computing environment for C2 level security
4611 ** under SecureWare.
4614 ** uid -- uid of the user to initialize in the TCB
4620 ** Initialized the user in the trusted computing base
4625 # include <sys/security.h>
4629 secureware_setup_secure(uid)
4634 if (getluid() != -1)
4637 if ((rc = set_secure_info(uid)) != SSI_GOOD_RETURN)
4641 case SSI_NO_PRPW_ENTRY:
4642 syserr("No protected passwd entry, uid = %d",
4647 syserr("Account has been disabled, uid = %d",
4652 syserr("Account has been retired, uid = %d",
4656 case SSI_BAD_SET_LUID:
4657 syserr("Could not set LUID, uid = %d", (int) uid);
4660 case SSI_BAD_SET_PRIVS:
4661 syserr("Could not set kernel privs, uid = %d",
4665 syserr("Unknown return code (%d) from set_secure_info(%d)",
4669 finis(false, true, EX_NOPERM);
4672 #endif /* SECUREWARE */
4674 ** ADD_HOSTNAMES -- Add a hostname to class 'w' based on IP address
4676 ** Add hostnames to class 'w' based on the IP address read from
4677 ** the network interface.
4680 ** sa -- a pointer to a SOCKADDR containing the address
4683 ** 0 if successful, -1 if host lookup fails.
4692 char hnb[MAXHOSTNAMELEN];
4694 /* lookup name with IP address */
4695 switch (sa->sa.sa_family)
4699 hp = sm_gethostbyaddr((char *) &sa->sin.sin_addr,
4700 sizeof(sa->sin.sin_addr),
4703 #endif /* NETINET */
4707 hp = sm_gethostbyaddr((char *) &sa->sin6.sin6_addr,
4708 sizeof(sa->sin6.sin6_addr),
4711 #endif /* NETINET6 */
4714 /* Give warning about unsupported family */
4716 sm_syslog(LOG_WARNING, NOQID,
4717 "Unsupported address family %d: %.100s",
4718 sa->sa.sa_family, anynet_ntoa(sa));
4724 int save_errno = errno;
4727 #if NETINET && defined(IN_LINKLOCAL)
4728 !(sa->sa.sa_family == AF_INET &&
4729 IN_LINKLOCAL(ntohl(sa->sin.sin_addr.s_addr))) &&
4732 !(sa->sa.sa_family == AF_INET6 &&
4733 IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr)) &&
4736 sm_syslog(LOG_WARNING, NOQID,
4737 "gethostbyaddr(%.100s) failed: %d",
4749 /* save its cname */
4750 if (!wordinclass((char *) hp->h_name, 'w'))
4752 setclass('w', (char *) hp->h_name);
4754 sm_dprintf("\ta.k.a.: %s\n", hp->h_name);
4756 if (sm_snprintf(hnb, sizeof(hnb), "[%s]", hp->h_name) <
4758 && !wordinclass((char *) hnb, 'w'))
4764 sm_dprintf("\ta.k.a.: %s (already in $=w)\n", hp->h_name);
4767 /* save all it aliases name */
4768 for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++)
4770 if (!wordinclass(*ha, 'w'))
4774 sm_dprintf("\ta.k.a.: %s\n", *ha);
4775 if (sm_snprintf(hnb, sizeof(hnb),
4776 "[%s]", *ha) < sizeof(hnb) &&
4777 !wordinclass((char *) hnb, 'w'))
4783 sm_dprintf("\ta.k.a.: %s (already in $=w)\n",
4793 ** LOAD_IF_NAMES -- load interface-specific names into $=w
4802 ** Loads $=w with the names of all the interfaces.
4806 # define SIOCGIFCONF_IS_BROKEN 1 /* XXX */
4809 #if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN
4813 # include <sm/time.h>
4815 # if (_AIX4 >= 40300) && !defined(_NET_IF_H)
4818 # include <net/if.h>
4819 #endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */
4824 # if NETINET6 && defined(SIOCGLIFCONF)
4828 ** Unfortunately, HP has changed all of the structures,
4829 ** making life difficult for implementors.
4832 # define lifconf if_laddrconf
4833 # define lifc_len iflc_len
4834 # define lifc_buf iflc_buf
4835 # define lifreq if_laddrreq
4836 # define lifr_addr iflr_addr
4837 # define lifr_name iflr_name
4838 # define lifr_flags iflr_flags
4839 # define ss_family sa_family
4841 # endif /* __hpux */
4848 struct lifconf lifc;
4853 s = socket(InetMode, SOCK_DGRAM, 0);
4857 /* get the list of known IP address from the kernel */
4859 i = ioctl(s, SIOCGIFNUM, (char *) &numifs);
4862 lifn.lifn_family = AF_UNSPEC;
4863 lifn.lifn_flags = 0;
4864 i = ioctl(s, SIOCGLIFNUM, (char *)&lifn);
4865 numifs = lifn.lifn_count;
4866 # endif /* SIOCGLIFNUM */
4868 # if defined(__hpux) || defined(SIOCGLIFNUM)
4871 /* can't get number of interfaces -- fall back */
4873 sm_dprintf("SIOCGLIFNUM failed: %s\n",
4874 sm_errstring(errno));
4877 else if (tTd(0, 42))
4878 sm_dprintf("system has %d interfaces\n", numifs);
4880 # endif /* defined(__hpux) || defined(SIOCGLIFNUM) */
4881 numifs = MAXINTERFACES;
4889 len = lifc.lifc_len = numifs * sizeof(struct lifreq);
4890 buf = lifc.lifc_buf = xalloc(lifc.lifc_len);
4892 lifc.lifc_family = AF_UNSPEC;
4893 lifc.lifc_flags = 0;
4895 if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0)
4898 sm_dprintf("SIOCGLIFCONF failed: %s\n",
4899 sm_errstring(errno));
4905 /* scan the list of IP address */
4907 sm_dprintf("scanning for interface specific names, lifc_len=%ld\n",
4910 for (i = 0; i < len && i >= 0; )
4913 struct lifreq *ifr = (struct lifreq *)&buf[i];
4914 SOCKADDR *sa = (SOCKADDR *) &ifr->lifr_addr;
4915 int af = ifr->lifr_addr.ss_family;
4918 struct in6_addr ia6;
4920 # ifdef SIOCGLIFFLAGS
4924 char buf6[INET6_ADDRSTRLEN];
4927 ** We must close and recreate the socket each time
4928 ** since we don't know what type of socket it is now
4929 ** (each status function may change it).
4934 s = socket(af, SOCK_DGRAM, 0);
4937 sm_free(buf); /* XXX */
4942 ** If we don't have a complete ifr structure,
4943 ** don't try to use it.
4946 if ((len - i) < sizeof(*ifr))
4949 # ifdef BSD4_4_SOCKADDR
4950 if (sa->sa.sa_len > sizeof(ifr->lifr_addr))
4951 i += sizeof(ifr->lifr_name) + sa->sa.sa_len;
4953 # endif /* BSD4_4_SOCKADDR */
4955 /* fix for IPv6 size differences */
4956 i += sizeof(ifr->ifr_name) +
4957 max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
4963 sm_dprintf("%s\n", anynet_ntoa(sa));
4965 if (af != AF_INET && af != AF_INET6)
4968 # ifdef SIOCGLIFFLAGS
4969 memset(&ifrf, '\0', sizeof(struct lifreq));
4970 (void) sm_strlcpy(ifrf.lifr_name, ifr->lifr_name,
4971 sizeof(ifrf.lifr_name));
4972 if (ioctl(s, SIOCGLIFFLAGS, (char *) &ifrf) < 0)
4975 sm_dprintf("SIOCGLIFFLAGS failed: %s\n",
4976 sm_errstring(errno));
4980 name = ifr->lifr_name;
4981 flags = ifrf.lifr_flags;
4984 sm_dprintf("\tflags: %lx\n", (unsigned long) flags);
4986 if (!bitset(IFF_UP, flags))
4988 # endif /* SIOCGLIFFLAGS */
4992 /* extract IP address from the list*/
4996 SETV6LOOPBACKADDRFOUND(*sa);
4998 /* convert into proper scoped address */
4999 if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) ||
5000 IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) &&
5001 sa->sin6.sin6_scope_id == 0)
5003 struct in6_addr *ia6p;
5005 ia6p = &sa->sin6.sin6_addr;
5006 sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] |
5007 ((unsigned int)ia6p->s6_addr[2] << 8));
5008 ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0;
5010 # endif /* __KAME__ */
5011 ia6 = sa->sin6.sin6_addr;
5012 if (IN6_IS_ADDR_UNSPECIFIED(&ia6))
5014 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
5015 message("WARNING: interface %s is UP with %s address",
5016 name, addr == NULL ? "(NULL)" : addr);
5020 /* save IP address in text from */
5021 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
5023 (void) sm_snprintf(ip_addr, sizeof(ip_addr),
5025 (int) sizeof(ip_addr) - 3,
5030 ia = sa->sin.sin_addr;
5031 if (ia.s_addr == INADDR_ANY ||
5032 ia.s_addr == INADDR_NONE)
5034 message("WARNING: interface %s is UP with %s address",
5035 name, inet_ntoa(ia));
5039 /* save IP address in text from */
5040 (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]",
5041 (int) sizeof(ip_addr) - 3, inet_ntoa(ia));
5045 if (*ip_addr == '\0')
5048 if (!wordinclass(ip_addr, 'w'))
5050 setclass('w', ip_addr);
5052 sm_dprintf("\ta.k.a.: %s\n", ip_addr);
5055 # ifdef SIOCGLIFFLAGS
5056 /* skip "loopback" interface "lo" */
5057 if (DontProbeInterfaces == DPI_SKIPLOOPBACK &&
5058 bitset(IFF_LOOPBACK, flags))
5060 # endif /* SIOCGLIFFLAGS */
5061 (void) add_hostnames(sa);
5063 sm_free(buf); /* XXX */
5065 # else /* NETINET6 && defined(SIOCGLIFCONF) */
5066 # if defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN
5072 s = socket(AF_INET, SOCK_DGRAM, 0);
5076 /* get the list of known IP address from the kernel */
5077 # if defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN
5078 if (ioctl(s, SIOCGIFNUM, (char *) &numifs) < 0)
5080 /* can't get number of interfaces -- fall back */
5082 sm_dprintf("SIOCGIFNUM failed: %s\n",
5083 sm_errstring(errno));
5086 else if (tTd(0, 42))
5087 sm_dprintf("system has %d interfaces\n", numifs);
5089 # endif /* defined(SIOCGIFNUM) && !SIOCGIFNUM_IS_BROKEN */
5090 numifs = MAXINTERFACES;
5097 ifc.ifc_len = numifs * sizeof(struct ifreq);
5098 ifc.ifc_buf = xalloc(ifc.ifc_len);
5099 if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0)
5102 sm_dprintf("SIOCGIFCONF failed: %s\n",
5103 sm_errstring(errno));
5108 /* scan the list of IP address */
5110 sm_dprintf("scanning for interface specific names, ifc_len=%d\n",
5113 for (i = 0; i < ifc.ifc_len && i >= 0; )
5116 struct ifreq *ifr = (struct ifreq *) &ifc.ifc_buf[i];
5117 SOCKADDR *sa = (SOCKADDR *) &ifr->ifr_addr;
5120 struct in6_addr ia6;
5123 # ifdef SIOCGIFFLAGS
5128 char buf6[INET6_ADDRSTRLEN];
5132 ** If we don't have a complete ifr structure,
5133 ** don't try to use it.
5136 if ((ifc.ifc_len - i) < sizeof(*ifr))
5139 # ifdef BSD4_4_SOCKADDR
5140 if (sa->sa.sa_len > sizeof(ifr->ifr_addr))
5141 i += sizeof(ifr->ifr_name) + sa->sa.sa_len;
5143 # endif /* BSD4_4_SOCKADDR */
5147 sm_dprintf("%s\n", anynet_ntoa(sa));
5149 af = ifr->ifr_addr.sa_family;
5157 # ifdef SIOCGIFFLAGS
5158 memset(&ifrf, '\0', sizeof(struct ifreq));
5159 (void) sm_strlcpy(ifrf.ifr_name, ifr->ifr_name,
5160 sizeof(ifrf.ifr_name));
5161 (void) ioctl(s, SIOCGIFFLAGS, (char *) &ifrf);
5163 sm_dprintf("\tflags: %lx\n",
5164 (unsigned long) ifrf.ifr_flags);
5165 # define IFRFREF ifrf
5166 # else /* SIOCGIFFLAGS */
5167 # define IFRFREF (*ifr)
5168 # endif /* SIOCGIFFLAGS */
5170 if (!bitset(IFF_UP, IFRFREF.ifr_flags))
5175 /* extract IP address from the list*/
5179 ia = sa->sin.sin_addr;
5180 if (ia.s_addr == INADDR_ANY ||
5181 ia.s_addr == INADDR_NONE)
5183 message("WARNING: interface %s is UP with %s address",
5184 ifr->ifr_name, inet_ntoa(ia));
5188 /* save IP address in text from */
5189 (void) sm_snprintf(ip_addr, sizeof(ip_addr), "[%.*s]",
5190 (int) sizeof(ip_addr) - 3,
5196 SETV6LOOPBACKADDRFOUND(*sa);
5198 /* convert into proper scoped address */
5199 if ((IN6_IS_ADDR_LINKLOCAL(&sa->sin6.sin6_addr) ||
5200 IN6_IS_ADDR_SITELOCAL(&sa->sin6.sin6_addr)) &&
5201 sa->sin6.sin6_scope_id == 0)
5203 struct in6_addr *ia6p;
5205 ia6p = &sa->sin6.sin6_addr;
5206 sa->sin6.sin6_scope_id = ntohs(ia6p->s6_addr[3] |
5207 ((unsigned int)ia6p->s6_addr[2] << 8));
5208 ia6p->s6_addr[2] = ia6p->s6_addr[3] = 0;
5210 # endif /* __KAME__ */
5211 ia6 = sa->sin6.sin6_addr;
5212 if (IN6_IS_ADDR_UNSPECIFIED(&ia6))
5214 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
5215 message("WARNING: interface %s is UP with %s address",
5217 addr == NULL ? "(NULL)" : addr);
5221 /* save IP address in text from */
5222 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
5224 (void) sm_snprintf(ip_addr, sizeof(ip_addr),
5226 (int) sizeof(ip_addr) - 3,
5230 # endif /* NETINET6 */
5233 if (ip_addr[0] == '\0')
5236 if (!wordinclass(ip_addr, 'w'))
5238 setclass('w', ip_addr);
5240 sm_dprintf("\ta.k.a.: %s\n", ip_addr);
5243 /* skip "loopback" interface "lo" */
5244 if (DontProbeInterfaces == DPI_SKIPLOOPBACK &&
5245 bitset(IFF_LOOPBACK, IFRFREF.ifr_flags))
5248 (void) add_hostnames(sa);
5250 sm_free(ifc.ifc_buf); /* XXX */
5253 # endif /* defined(SIOCGIFCONF) && !SIOCGIFCONF_IS_BROKEN */
5254 # endif /* NETINET6 && defined(SIOCGLIFCONF) */
5257 ** ISLOOPBACK -- is socket address in the loopback net?
5260 ** sa -- socket address.
5263 ** true -- is socket address in the loopback net?
5264 ** false -- otherwise
5272 /* XXX how to correctly extract IN_LOOPBACKNET part? */
5273 #define SM_IS_IPV4_LOOP(a) (((ntohl(a) & IN_CLASSA_NET) \
5274 >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5276 if (sa.sa.sa_family == AF_INET6 &&
5277 IN6_IS_ADDR_V4MAPPED(&sa.sin6.sin6_addr) &&
5278 SM_IS_IPV4_LOOP(((uint32_t *) (&sa.sin6.sin6_addr))[3]))
5280 if (sa.sa.sa_family == AF_INET6 &&
5281 IN6_IS_ADDR_LOOPBACK(&sa.sin6.sin6_addr))
5285 if (sa.sa.sa_family == AF_INET &&
5286 SM_IS_IPV4_LOOP(sa.sin.sin_addr.s_addr))
5293 ** GET_NUM_PROCS_ONLINE -- return the number of processors currently online
5299 ** The number of processors online.
5303 get_num_procs_online()
5308 # if defined(CTL_HW) && defined(HW_NCPU)
5314 sz = (size_t) sizeof(nproc);
5315 (void) sysctl(mib, 2, &nproc, &sz, NULL, 0);
5316 # endif /* defined(CTL_HW) && defined(HW_NCPU) */
5317 #else /* USESYSCTL */
5318 # ifdef _SC_NPROCESSORS_ONLN
5319 nproc = (int) sysconf(_SC_NPROCESSORS_ONLN);
5320 # else /* _SC_NPROCESSORS_ONLN */
5322 # include <sys/pstat.h>
5323 struct pst_dynamic psd;
5325 if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) != -1)
5326 nproc = psd.psd_proc_cnt;
5327 # endif /* __hpux */
5328 # endif /* _SC_NPROCESSORS_ONLN */
5329 #endif /* USESYSCTL */
5336 ** SM_CLOSEFROM -- close file descriptors
5339 ** lowest -- first fd to close
5340 ** highest -- last fd + 1 to close
5347 sm_closefrom(lowest, highest)
5348 int lowest, highest;
5352 #else /* HASCLOSEFROM */
5355 for (i = lowest; i < highest; i++)
5357 #endif /* HASCLOSEFROM */
5361 ** CLOSEFD_WALK -- walk fd's arranging to close them
5362 ** Callback for fdwalk()
5365 ** lowest -- first fd to arrange to be closed
5366 ** fd -- fd to arrange to be closed
5373 closefd_walk(lowest, fd)
5377 if (fd >= *(int *)lowest)
5378 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
5381 #endif /* HASFDWALK */
5383 ** SM_CLOSE_ON_EXEC -- arrange for file descriptors to be closed
5386 ** lowest -- first fd to arrange to be closed
5387 ** highest -- last fd + 1 to arrange to be closed
5394 sm_close_on_exec(lowest, highest)
5395 int lowest, highest;
5398 (void) fdwalk(closefd_walk, &lowest);
5399 #else /* HASFDWALK */
5402 for (i = lowest; i < highest; i++)
5404 if ((j = fcntl(i, F_GETFD, 0)) != -1)
5405 (void) fcntl(i, F_SETFD, j | FD_CLOEXEC);
5407 #endif /* HASFDWALK */
5410 ** SEED_RANDOM -- seed the random number generator
5424 #else /* HASSRANDOMDEV */
5428 seed = (long) CurrentPid;
5429 if (gettimeofday(&t, NULL) >= 0)
5430 seed += t.tv_sec + t.tv_usec;
5433 (void) srandom(seed);
5435 (void) srand((unsigned int) seed);
5437 #endif /* HASSRANDOMDEV */
5440 ** SM_SYSLOG -- syslog wrapper to keep messages under SYSLOG_BUFSIZE
5443 ** level -- syslog level
5444 ** id -- envelope ID or NULL (NOQUEUE)
5445 ** fmt -- format string
5446 ** arg... -- arguments as implied by fmt.
5455 sm_syslog(int level, const char *id, const char *fmt, ...)
5456 #else /* __STDC__ */
5457 sm_syslog(level, id, fmt, va_alist)
5462 #endif /* __STDC__ */
5472 extern int SyslogPrefixLen;
5478 idlen = strlen(id) + SyslogPrefixLen;
5481 bufsize = sizeof(buf0);
5487 /* print log message into buf */
5488 SM_VA_START(ap, fmt);
5489 n = sm_vsnprintf(buf, bufsize, fmt, ap);
5495 /* String too small, redo with correct size */
5502 buf = sm_malloc_x(bufsize);
5505 /* clean up buf after it has been expanded with args */
5506 newstring = str2prt(buf);
5507 if ((strlen(newstring) + idlen + 1) < SYSLOG_BUFSIZE)
5516 gettimeofday(&tv, NULL);
5517 sm_dprintf("%ld.%06ld %s\n", (long) tv.tv_sec,
5518 (long) tv.tv_usec, newstring);
5520 else if (tTd(89, 8))
5521 sm_dprintf("%s\n", newstring);
5523 syslog(level, "%s", newstring);
5531 gettimeofday(&tv, NULL);
5532 sm_dprintf("%ld.%06ld %s: %s\n", (long) tv.tv_sec,
5533 (long) tv.tv_usec, id, newstring);
5535 else if (tTd(89, 8))
5536 sm_dprintf("%s: %s\n", id, newstring);
5538 syslog(level, "%s: %s", id, newstring);
5541 /*XXX should do something more sensible */
5543 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, "%s\n",
5546 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
5547 "%s: %s\n", id, newstring);
5556 ** additional length for splitting: " ..." + 3, where 3 is magic to
5557 ** have some data for the next entry.
5563 idlen += 5; /* strlen("[999]"), see below */
5564 while (*begin != '\0' &&
5565 (strlen(begin) + idlen) > SYSLOG_BUFSIZE)
5571 /* Too many messages */
5574 end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT;
5577 /* Break on comma or space */
5578 if (*end == ',' || *end == ' ')
5580 end++; /* Include separator */
5585 /* No separator, break midstring... */
5587 end = begin + SYSLOG_BUFSIZE - idlen - SL_SPLIT;
5592 sm_dprintf("%s[%d]: %s ...\n", id, seq++, begin);
5594 syslog(level, "%s[%d]: %s ...", id, seq++, begin);
5596 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
5597 "%s[%d]: %s ...\n", id, seq++, begin);
5606 sm_dprintf("%s[%d]: log terminated, too many parts\n",
5609 syslog(level, "%s[%d]: log terminated, too many parts",
5612 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
5613 "%s[%d]: log terminated, too many parts\n", id, seq);
5616 else if (*begin != '\0')
5620 sm_dprintf("%s[%d]: %s\n", id, seq, begin);
5622 syslog(level, "%s[%d]: %s", id, seq, begin);
5624 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
5625 "%s[%d]: %s\n", id, seq, begin);
5633 ** HARD_SYSLOG -- call syslog repeatedly until it works
5635 ** Needed on HP-UX, which apparently doesn't guarantee that
5636 ** syslog succeeds during interrupt handlers.
5639 #if defined(__hpux) && !defined(HPUX11)
5641 # define MAXSYSLOGTRIES 100
5644 # define XCNST const
5645 # define CAST (const char *)
5653 hard_syslog(int pri, XCNST char *msg, ...)
5654 # else /* __STDC__ */
5655 hard_syslog(pri, msg, va_alist)
5659 # endif /* __STDC__ */
5662 char buf[SYSLOG_BUFSIZE];
5665 SM_VA_START(ap, msg);
5666 (void) sm_vsnprintf(buf, sizeof(buf), msg, ap);
5669 for (i = MAXSYSLOGTRIES; --i >= 0 && syslog(pri, CAST "%s", buf) < 0; )
5674 #endif /* defined(__hpux) && !defined(HPUX11) */
5675 #if NEEDLOCAL_HOSTNAME_LENGTH
5677 ** LOCAL_HOSTNAME_LENGTH
5679 ** This is required to get sendmail to compile against BIND 4.9.x
5682 ** Unfortunately, a Compaq Y2K patch kit provides it without
5683 ** bumping __RES in /usr/include/resolv.h so we can't automatically
5684 ** figure out whether it is needed.
5688 local_hostname_length(hostname)
5691 size_t len_host, len_domain;
5693 if (!*_res.defdname)
5695 len_host = strlen(hostname);
5696 len_domain = strlen(_res.defdname);
5697 if (len_host > len_domain &&
5698 (sm_strcasecmp(hostname + len_host - len_domain,
5699 _res.defdname) == 0) &&
5700 hostname[len_host - len_domain - 1] == '.')
5701 return len_host - len_domain - 1;
5705 #endif /* NEEDLOCAL_HOSTNAME_LENGTH */
5709 ** LINK -- clone a file
5711 ** Some OS's lacks link() and hard links. Since sendmail is using
5712 ** link() as an efficient way to clone files, this implementation
5713 ** will simply do a file copy.
5715 ** NOTE: This link() replacement is not a generic replacement as it
5716 ** does not handle all of the semantics of the real link(2).
5719 ** source -- pathname of existing file.
5720 ** target -- pathname of link (clone) to be created.
5724 ** -1 -- failure, see errno for details.
5728 link(source, target)
5734 int src = -1, dst = -1;
5740 sff = SFF_REGONLY|SFF_OPENASROOT;
5741 if (DontLockReadFiles)
5744 /* Open the original file */
5745 src = safeopen((char *)source, O_RDONLY, 0, sff);
5749 /* Obtain the size and the mode */
5750 if (fstat(src, &st) < 0)
5753 /* Create the duplicate copy */
5756 dst = safeopen((char *)target, O_CREAT|O_EXCL|O_WRONLY,
5761 /* Copy all of the bytes one buffer at a time */
5762 while ((readlen = read(src, &buf, sizeof(buf))) > 0)
5764 ssize_t left = readlen;
5768 (writelen = write(dst, p, (size_t) left)) >= 0)
5777 /* Any trouble reading? */
5778 if (readlen < 0 || writelen < 0)
5781 /* Close the input file */
5789 /* Close the output file */
5792 /* don't set dst = -1 here so we unlink the file */
5805 (void) unlink(target);
5811 #endif /* NEEDLINK */
5814 ** Compile-Time options
5817 #define SM_STR(x) #x
5818 #define SM_XSTR(x) SM_STR(x)
5820 char *CompileOptions[] =
5829 # error "DANE set but STARTTLS not defined"
5843 #if HESIOD_ALLOW_NUMERIC_LOGIN
5844 "HESIOD_ALLOW_NUMERIC_LOGIN",
5850 /* Use uncompressed IPv6 address format (no "::") by default */
5856 #if LDAP_NETWORK_TIMEOUT
5857 # if LDAPMAP && defined(LDAP_OPT_NETWORK_TIMEOUT)
5858 /* set LDAP_OPT_NETWORK_TIMEOUT if available (-c) */
5859 "LDAP_NETWORK_TIMEOUT",
5861 # ERROR: _LDAP_NETWORK_TIMEOUT requires _LDAPMAP
5879 #if MAXDAEMONS != 10
5880 "MAXDAEMONS=" SM_XSTR(MAXDAEMONS),
5882 #if defined(MSGIDLOGLEN)
5883 "MSGIDLOGLEN=" SM_XSTR(MSGIDLOGLEN),
5928 # if defined(DB_VERSION_MAJOR) && defined(DB_VERSION_MINOR)
5929 "NEWDB=" SM_XSTR(DB_VERSION_MAJOR) "." SM_XSTR(DB_VERSION_MINOR),
5935 "CDB=" SM_XSTR(CDB),
5949 #ifdef PICKY_HELO_CHECK
5965 #if SM_LDAP_ERROR_ON_MISSING_ARGS
5966 "SM_LDAP_ERROR_ON_MISSING_ARGS",
5977 #if SUID_ROOT_FILES_OK
5978 "SUID_ROOT_FILES_OK",
5980 #if SYSLOG_BUFSIZE > 1024
5981 "SYSLOG_BUFSIZE=" SM_XSTR(SYSLOG_BUFSIZE),
5990 /* elliptic curves */
5993 #if TLS_VRFY_PER_CTX
6016 ** OS compile options.
6019 char *OsCompileOptions[] =
6021 #if ADDRCONFIG_IS_BROKEN
6022 "ADDRCONFIG_IS_BROKEN",
6024 #ifdef AUTO_NETINFO_HOSTS
6025 "AUTO_NETINFO_HOSTS",
6027 #ifdef AUTO_NIS_ALIASES
6030 #if BROKEN_RES_SEARCH
6031 "BROKEN_RES_SEARCH",
6033 #ifdef BSD4_4_SOCKADDR
6039 #if DEC_OSF_BROKEN_GETPWENT
6040 "DEC_OSF_BROKEN_GETPWENT",
6045 #if FAST_PID_RECYCLE
6063 #if HASGETDTABLESIZE
6066 #if HAS_GETHOSTBYNAME2
6067 "HAS_GETHOSTBYNAME2",
6075 #if HASLDAPGETALIASBYNAME
6076 "HASLDAPGETALIASBYNAME",
6111 #if HASSETUSERCONTEXT
6112 "HASSETUSERCONTEXT",
6150 #if O_EXLOCK && HASFLOCK && !BOGUS_O_EXCL
6162 #if NEEDLOCAL_HOSTNAME_LENGTH
6163 "NEEDLOCAL_HOSTNAME_LENGTH",
6174 #ifdef NO_GETSERVBYNAME
6180 #if REQUIRES_DIR_FSYNC
6181 "REQUIRES_DIR_FSYNC",
6183 #if RLIMIT_NEEDS_SYS_TIME_H
6184 "RLIMIT_NEEDS_SYS_TIME_H",
6192 #if SFS_TYPE == SFS_4ARGS
6194 #elif SFS_TYPE == SFS_MOUNT
6196 #elif SFS_TYPE == SFS_NONE
6198 #elif SFS_TYPE == SFS_NT
6200 #elif SFS_TYPE == SFS_STATFS
6202 #elif SFS_TYPE == SFS_STATVFS
6204 #elif SFS_TYPE == SFS_USTAT
6206 #elif SFS_TYPE == SFS_VFS
6212 #if SIOCGIFCONF_IS_BROKEN
6213 "SIOCGIFCONF_IS_BROKEN",
6215 #if SIOCGIFNUM_IS_BROKEN
6216 "SIOCGIFNUM_IS_BROKEN",
6218 #if SNPRINTF_IS_BROKEN
6219 "SNPRINTF_IS_BROKEN",
6221 #if SO_REUSEADDR_IS_BROKEN
6222 "SO_REUSEADDR_IS_BROKEN",
6236 #if USE_SA_SIGACTION
6251 #if USE_OPENSSL_ENGINE
6253 ** 0: OpenSSL ENGINE?
6254 ** 1: Support Sun OpenSSL patch for SPARC T4 pkcs11
6257 # if USE_OPENSSL_ENGINE != 1
6258 "USE_OPENSSL_ENGINE=" SM_XSTR(USE_OPENSSL_ENGINE),
6260 "USE_OPENSSL_ENGINE",
6263 #if USING_NETSCAPE_LDAP
6264 "USING_NETSCAPE_LDAP",
6273 ** FFR compile options.
6276 char *FFRCompileOptions[] =
6279 /* see cf/feature/bcc.m4 */
6282 #if _FFR_ADDR_TYPE_MODES
6283 /* more info in {addr_type}, requires m4 changes! */
6284 "_FFR_ADDR_TYPE_MODES",
6286 #if _FFR_ALIAS_DETAIL
6287 /* try to handle +detail for aliases */
6288 "_FFR_ALIAS_DETAIL",
6290 #if _FFR_ALLOW_SASLINFO
6291 /* DefaultAuthInfo can be specified by user. */
6292 /* DefaultAuthInfo doesn't really work in 8.13 anymore. */
6293 "_FFR_ALLOW_SASLINFO",
6295 #if _FFR_BADRCPT_SHUTDOWN
6296 /* shut down connection (421) if there are too many bad RCPTs */
6297 "_FFR_BADRCPT_SHUTDOWN",
6299 #if _FFR_BESTMX_BETTER_TRUNCATION
6300 /* Better truncation of list of MX records for dns map. */
6301 "_FFR_BESTMX_BETTER_TRUNCATION",
6303 #if _FFR_BLANKENV_MACV
6304 /* also look up macros in BlankEnvelope */
6305 "_FFR_BLANKENV_MACV",
6307 #if _FFR_BOUNCE_QUEUE
6308 /* Separate, unprocessed queue for DSNs */
6309 /* John Gardiner Myers of Proofpoint */
6310 "_FFR_BOUNCE_QUEUE",
6312 #if _FFR_CATCH_BROKEN_MTAS
6313 /* Deal with MTAs that send a reply during the DATA phase. */
6314 "_FFR_CATCH_BROKEN_MTAS",
6317 /* Stricter checks about queue directory permissions. */
6322 ** Allow to set client specific CA values.
6323 ** CACertFile: see doc/op.*:
6324 ** "The DNs of these certificates are sent to the client
6325 ** during the TLS handshake (as part of the CertificateRequest)
6326 ** as the list of acceptable CAs.
6327 ** However, do not list too many root CAs in that file,
6328 ** otherwise the TLS handshake may fail;"
6329 ** In TLSv1.3 the certs in CACertFile are also sent by
6330 ** the client to the server and there is seemingly a
6331 ** 16KB limit (just in OpenSSL?).
6332 ** Having a separate CACertFile for the client
6333 ** helps to avoid this problem.
6338 #if _FFR_CLIENT_SIZE
6339 /* Don't try to send mail if its size exceeds SIZE= of server. */
6343 /* deliver first TA in background, then queue */
6346 #if _FFR_DIGUNIX_SAFECHOWN
6347 /* Properly set SAFECHOWN (include/sm/conf.h) for Digital UNIX */
6348 /* Problem noted by Anne Bennett of Concordia University */
6349 "_FFR_DIGUNIX_SAFECHOWN",
6351 #if _FFR_DNSMAP_ALIASABLE
6352 /* Allow dns map type to be used for aliases. */
6353 /* Don Lewis of TDK */
6354 "_FFR_DNSMAP_ALIASABLE",
6356 #if _FFR_DONTLOCKFILESFORREAD_OPTION
6357 /* Enable DontLockFilesForRead option. */
6358 "_FFR_DONTLOCKFILESFORREAD_OPTION",
6360 #if _FFR_DOTTED_USERNAMES
6361 /* Allow usernames with '.' */
6362 "_FFR_DOTTED_USERNAMES",
6366 ** Make DaemonPortOptions case sensitive.
6367 ** For some unknown reasons the code converted every option
6368 ** to uppercase (first letter only, as that's the only one that
6369 ** is actually checked). This prevented all new lower case options
6371 ** The documentation doesn't say anything about case (in)sensitivity,
6372 ** which means it should be case sensitive by default,
6373 ** but it's not a good idea to change this within a patch release,
6374 ** so let's delay this to 8.15.
6379 #if _FFR_DPRINTF_MAP
6380 /* dprintf map for logging */
6383 #if _FFR_DROP_TRUSTUSER_WARNING
6385 ** Don't issue this warning:
6386 ** "readcf: option TrustedUser may cause problems on systems
6387 ** which do not support fchown() if UseMSP is not set.
6390 "_FFR_DROP_TRUSTUSER_WARNING",
6392 #if _FFR_EIGHT_BIT_ADDR_OK
6393 /* EightBitAddrOK: allow 8-bit e-mail addresses */
6394 "_FFR_EIGHT_BIT_ADDR_OK",
6396 #if _FFR_EXPAND_HELONAME
6397 /* perform macro expansion for heloname */
6398 "_FFR_EXPAND_HELONAME",
6400 #if _FFR_EXTRA_MAP_CHECK
6401 /* perform extra checks on $( $) in R lines */
6402 "_FFR_EXTRA_MAP_CHECK",
6404 #if _FFR_GETHBN_ExFILE
6406 ** According to Motonori Nakamura some gethostbyname()
6407 ** implementations (TurboLinux?) may (temporarily) fail
6408 ** due to a lack of file descriptors. Enabling this FFR
6409 ** will check errno for EMFILE and ENFILE and in case of a match
6410 ** cause a temporary error instead of a permanent error.
6411 ** The right solution is of course to file a bug against those
6412 ** systems such that they actually set h_errno = TRY_AGAIN.
6415 "_FFR_GETHBN_ExFILE",
6418 /* FIPSMode (if supported by OpenSSL library) */
6423 ** If using -t, force not sending to argv recipients, even
6424 ** if they are mentioned in the headers.
6429 #if _FFR_FORWARD_SYSERR
6430 /* Cause a "syserr" if forward file isn't "safe". */
6431 "_FFR_FORWARD_SYSERR",
6434 /* Generate a ORCPT DSN arg if not already provided */
6437 #if _FFR_HANDLE_ISO8859_GECOS
6439 ** Allow ISO 8859 characters in GECOS field: replace them
6440 ** with ASCII "equivalent".
6443 /* Peter Eriksson of Linkopings universitet */
6444 "_FFR_HANDLE_ISO8859_GECOS",
6446 #if _FFR_HANDLE_HDR_RW_TEMPFAIL
6448 ** Temporary header rewriting problems from remotename() etc
6449 ** are not "sticky" for mci (e.g., during queue runs).
6452 "_FFR_HANDLE_HDR_RW_TEMPFAIL",
6454 #if _FFR_HPUX_NSSWITCH
6455 /* Use nsswitch on HP-UX */
6456 "_FFR_HPUX_NSSWITCH",
6458 #if _FFR_IGNORE_BOGUS_ADDR
6459 /* Ignore addresses for which prescan() failed */
6460 "_FFR_IGNORE_BOGUS_ADDR",
6462 #if _FFR_IGNORE_EXT_ON_HELO
6463 /* Ignore extensions offered in response to HELO */
6464 "_FFR_IGNORE_EXT_ON_HELO",
6467 /* Keep Bcc header */
6470 #if _FFR_LOCAL_DAEMON
6471 /* Local daemon mode (-bl) which only accepts loopback connections */
6472 "_FFR_LOCAL_DAEMON",
6475 /* log some TLS/AUTH info in from= too */
6476 "_FFR_LOG_MORE1=" SM_XSTR(_FFR_LOG_MORE1),
6479 /* log some TLS info in to= too */
6480 "_FFR_LOG_MORE2=" SM_XSTR(_FFR_LOG_MORE2),
6482 #if _FFR_LOG_MORE1 > 1 || _FFR_LOG_MORE2 > 1
6483 # if _FFR_LOG_MORE1 != _FFR_LOG_MORE2
6484 ERROR: FFR_LOG_MORE1 != FFR_LOG_MORE2
6488 /* make the "real" sender address available in {mail_from} */
6491 #if _FFR_MAXDATASIZE
6493 ** It is possible that a header is larger than MILTER_CHUNK_SIZE,
6494 ** hence this shouldn't be used as limit for milter communication.
6495 ** see also libmilter/comm.c
6496 ** Gurusamy Sarathy of ActiveState
6501 #if _FFR_MAX_FORWARD_ENTRIES
6502 /* Try to limit number of .forward entries */
6503 /* (doesn't work) */
6504 /* Randall S. Winchester of the University of Maryland */
6505 "_FFR_MAX_FORWARD_ENTRIES",
6507 #if _FFR_MAX_SLEEP_TIME
6508 /* Limit sleep(2) time in libsm/clock.c */
6509 "_FFR_MAX_SLEEP_TIME",
6511 #if _FFR_MDS_NEGOTIATE
6512 /* MaxDataSize negotiation with libmilter */
6513 "_FFR_MDS_NEGOTIATE",
6516 /* Check free memory */
6519 #if _FFR_MILTER_CHECK
6520 "_FFR_MILTER_CHECK",
6522 #if _FFR_MILTER_CONNECT_REPLYCODE
6523 /* milter: propagate replycode returned by connect commands */
6524 /* John Gardiner Myers of Proofpoint */
6525 "_FFR_MILTER_CONNECT_REPLYCODE ",
6527 #if _FFR_MILTER_CONVERT_ALL_LF_TO_CRLF
6529 ** milter_body() uses the same conversion algorithm as putbody()
6530 ** to translate the "local" df format (\n) to SMTP format (\r\n).
6531 ** However, putbody() and mime8to7() use different conversion
6533 ** If the input date does not follow the SMTP standard
6534 ** (e.g., if it has "naked \r"s), then the output from putbody()
6535 ** and mime8to7() will most likely be different.
6536 ** By turning on this FFR milter_body() will try to "imitate"
6538 ** Note: there is no (simple) way to deal with both conversions
6539 ** in a consistent manner. Moreover, as the "GiGo" principle applies,
6540 ** it's not really worth to fix it.
6543 "_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF",
6545 #if _FFR_MILTER_CHECK_REJECTIONS_TOO
6547 ** Also send RCPTs that are rejected by check_rcpt to a milter
6548 ** (if requested during option negotiation).
6551 "_FFR_MILTER_CHECK_REJECTIONS_TOO",
6553 #if _FFR_MILTER_ENHSC
6554 /* extract enhanced status code from milter replies for dsn= logging */
6555 "_FFR_MILTER_ENHSC",
6557 #if _FFR_MIME7TO8_OLD
6558 /* Old mime7to8 code, the new is broken for at least one example. */
6559 "_FFR_MIME7TO8_OLD",
6561 #if _FFR_MORE_MACROS
6562 /* allow more long macro names ("unprintable" characters). */
6566 /* allow to override "Message accepted for delivery" */
6569 #if _FFR_NODELAYDSN_ON_HOLD
6570 /* Do not issue a DELAY DSN for mailers that use the hold flag. */
6572 "_FFR_NODELAYDSN_ON_HOLD",
6575 /* Disable PIPELINING, delay client if used. */
6578 #if _FFR_LDAP_SINGLEDN
6580 ** The LDAP database map code in Sendmail 8.12.10, when
6581 ** given the -1 switch, would match only a single DN,
6582 ** but was able to return multiple attributes for that
6583 ** DN. In Sendmail 8.13 this "bug" was corrected to
6584 ** only return if exactly one attribute matched.
6586 ** Unfortunately, our configuration uses the former
6587 ** behaviour. Attached is a relatively simple patch
6588 ** to 8.13.4 which adds a -2 switch (for lack of a
6589 ** better option) which returns the single dn/multiple
6592 ** Jeffrey T. Eaton, Carnegie-Mellon University
6595 "_FFR_LDAP_SINGLEDN",
6598 /* log ntries=, from Nik Clayton of FreeBSD */
6603 /* outgoing connection control (not yet working) */
6606 # ERROR: FFR_OCC requires _SM_CONF_SHM
6610 /* "proxy" (synchronous) delivery mode */
6613 #if _FFR_QF_PARANOIA
6614 /* Check to make sure key fields were read from qf */
6617 #if _FFR_QUEUE_GROUP_SORTORDER
6618 /* Allow QueueSortOrder per queue group. */
6619 /* XXX: Still need to actually use qgrp->qg_sortorder */
6620 "_FFR_QUEUE_GROUP_SORTORDER",
6622 #if _FFR_QUEUE_MACRO
6623 /* Define {queue} macro. */
6626 #if _FFR_QUEUE_RUN_PARANOIA
6627 /* Additional checks when doing queue runs; interval of checks */
6628 "_FFR_QUEUE_RUN_PARANOIA",
6630 #if _FFR_QUEUE_SCHED_DBG
6631 /* Debug output for the queue scheduler. */
6632 "_FFR_QUEUE_SCHED_DBG",
6635 /* dynamic mailer modifications via {rcpt_flags}*/
6638 #if _FFR_RCPTTHROTDELAY
6639 /* configurable delay for BadRcptThrottle */
6640 "_FFR_RCPTTHROTDELAY",
6642 #if _FFR_REDIRECTEMPTY
6644 ** envelope <> can't be sent to mailing lists, only owner-
6645 ** send spam of this type to owner- of the list
6646 ** ---- to stop spam from going to mailing lists.
6649 "_FFR_REDIRECTEMPTY",
6651 #if _FFR_REJECT_NUL_BYTE
6652 /* reject NUL bytes in body */
6653 "_FFR_REJECT_NUL_BYTE",
6655 #if _FFR_RESET_MACRO_GLOBALS
6656 /* Allow macro 'j' to be set dynamically via rulesets. */
6657 "_FFR_RESET_MACRO_GLOBALS",
6660 /* Random shuffle for queue sorting. */
6665 ** allow -qGqueue_group -qp to work, i.e.,
6666 ** restrict a persistent queue runner to a queue group.
6672 /* session id (for logging): WIP, no logging yet! */
6678 #if _FFR_SETDEBUG_MAP
6679 "_FFR_SETDEBUG_MAP",
6685 /* Donated code (unused). */
6688 #if _FFR_SKIP_DOMAINS
6689 /* process every N'th domain instead of every N'th message */
6690 "_FFR_SKIP_DOMAINS",
6692 #if _FFR_SLEEP_USE_SELECT
6693 /* Use select(2) in libsm/clock.c to emulate sleep(2) */
6694 "_FFR_SLEEP_USE_SELECT ",
6696 #if _FFR_SM_LDAP_DBG
6697 # if LDAPMAP && defined(LBER_OPT_LOG_PRINT_FN)
6698 /* LDAP debugging */
6701 # ERROR: FFR_SM_LDAP_DBG requires _LDAPMAP and LBER_OPT_LOG_PRINT_FN
6706 ** It looks like the Compaq Tru64 5.1A now aligns argv and envp to 64
6707 ** bit alignment, so unless each piece of argv and envp is a multiple
6708 ** of 8 bytes (including terminating NULL), initsetproctitle() won't
6709 ** use any of the space beyond argv[0]. Be sure to set SPT_ALIGN_SIZE
6710 ** if you use this FFR.
6713 /* Chris Adams of HiWAAY Informations Services */
6716 #if _FFR_SS_PER_DAEMON
6717 /* SuperSafe per DaemonPortOptions: 'T' (better letter?) */
6718 "_FFR_SS_PER_DAEMON",
6721 /* enable some test code */
6725 /* Donated code (unused). */
6728 #if _FFR_TLS_ALTNAMES
6729 /* store subjectAltNames in class {cert_altnames} */
6731 "_FFR_TLS_ALTNAMES",
6733 # error "_FFR_TLS_ALTNAMES set but STARTTLS not defined"
6736 #if _FFR_TLSFB2CLEAR
6737 /* set default for TLSFallbacktoClear to true */
6741 # error "_FFR_TLSFB2CLEAR set but STARTTLS not defined"
6744 #if _FFR_TLS_USE_CERTIFICATE_CHAIN_FILE
6746 ** Use SSL_CTX_use_certificate_chain_file()
6747 ** instead of SSL_CTX_use_certificate_file()
6751 "_FFR_TLS_USE_CERTIFICATE_CHAIN_FILE",
6753 # error "_FFR_TLS_USE_CERTIFICATE_CHAIN_FILE set but STARTTLS not defined"
6758 ** If we don't own the file mark it as unsafe.
6759 ** However, allow TrustedUser to own it as well
6760 ** in case TrustedUser manipulates the queue.
6765 #if _FFR_USE_GETPWNAM_ERRNO
6767 ** See libsm/mbdb.c: only enable this on OSs
6768 ** that implement the correct (POSIX) semantics.
6769 ** This will need to become an OS-specific #if enabled
6770 ** in one of the headers files under include/sm/os/ .
6773 "_FFR_USE_GETPWNAM_ERRNO",
6775 #if _FFR_VRFY_TRUSTED_FIRST
6777 ** Sets X509_V_FLAG_TRUSTED_FIRST if -d88;.101 is used.
6778 ** X509_VERIFY_PARAM_set_flags(3)
6779 ** When X509_V_FLAG_TRUSTED_FIRST is set, construction of the
6780 ** certificate chain in X509_verify_cert(3) will search the trust
6781 ** store for issuer certificates before searching the provided
6782 ** untrusted certificates. Local issuer certificates are often more
6783 ** likely to satisfy local security requirements and lead to a locally
6784 ** trusted root. This is especially important when some certificates
6785 ** in the trust store have explicit trust settings (see "TRUST
6786 ** SETTINGS" in x509(1)).
6787 ** As of OpenSSL 1.1.0 this option is on by default.
6790 # if defined(X509_V_FLAG_TRUSTED_FIRST)
6791 "_FFR_VRFY_TRUSTED_FIRST",
6793 # error "FFR_VRFY_TRUSTED_FIRST set but X509_V_FLAG_TRUSTED_FIRST not defined"
6797 #if _FFR_USE_SEM_LOCKING
6798 /* Use semaphore locking */
6799 "_FFR_USE_SEM_LOCKING",
6801 #if _FFR_USE_SETLOGIN
6802 /* Use setlogin() */
6804 "_FFR_USE_SETLOGIN",
6807 /* X-Connect support */
6813 ** Initial/Partial/Experimental EAI (SMTPUTF8) support.
6814 ** NOTE: This is currently BROKEN as the handling of
6815 ** envelope addresses in sendmail is NOT 8-bit clean
6816 ** (in contrast to header addresses/values).
6817 ** Requires ICU include files and library depending on the OS.
6818 ** Patch from Arnt Gulbrandsen.
6822 # ERROR FFR_EAI requires _ALLOW_255
6824 # if _FFR_EIGHT_BIT_ADDR_OK
6825 # error "Cannot enable both of these FFRs: FFR_EAI FFR_EIGHT_BIT_ADDR_OK"