xref: /illumos-gate/usr/src/cmd/sendmail/src/conf.c (revision 48bbca81)
1 /*
2  * Copyright (c) 1998-2009 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
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.
7  *
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.
11  *
12  */
13 
14 /*
15  * Copyright 1999-2006 Sun Microsystems, Inc.  All rights reserved.
16  * Use is subject to license terms.
17  * Copyright (c) 2016 by Delphix. All rights reserved.
18  */
19 
20 #include <sendmail.h>
21 
22 SM_RCSID("@(#)$Id: conf.c,v 8.1153 2009/12/18 17:25:12 ca Exp $")
23 
24 #include <sm/sendmail.h>
25 #include <sendmail/pathnames.h>
26 #if NEWDB
27 # include "sm/bdb.h"
28 #endif /* NEWDB */
29 
30 #include <daemon.h>
31 #include "map.h"
32 
33 #ifdef DEC
34 # if NETINET6
35 /* for the IPv6 device lookup */
36 #  define _SOCKADDR_LEN
37 #  include <macros.h>
38 # endif /* NETINET6 */
39 #endif /* DEC */
40 
41 # include <sys/ioctl.h>
42 # include <sys/param.h>
43 
44 #include <limits.h>
45 #if NETINET || NETINET6
46 # include <arpa/inet.h>
47 #endif /* NETINET || NETINET6 */
48 #if HASULIMIT && defined(HPUX11)
49 # include <ulimit.h>
50 #endif /* HASULIMIT && defined(HPUX11) */
51 
52 static void	setupmaps __P((void));
53 static void	setupmailers __P((void));
54 static void	setupqueues __P((void));
55 static int	get_num_procs_online __P((void));
56 static int	add_hostnames __P((SOCKADDR *));
57 
58 #if NETINET6 && NEEDSGETIPNODE
59 static struct hostent *getipnodebyname __P((char *, int, int, int *));
60 static struct hostent *getipnodebyaddr __P((char *, int, int, int *));
61 #endif /* NETINET6 && NEEDSGETIPNODE */
62 
63 
64 /*
65 **  CONF.C -- Sendmail Configuration Tables.
66 **
67 **	Defines the configuration of this installation.
68 **
69 **	Configuration Variables:
70 **		HdrInfo -- a table describing well-known header fields.
71 **			Each entry has the field name and some flags,
72 **			which are described in sendmail.h.
73 **
74 **	Notes:
75 **		I have tried to put almost all the reasonable
76 **		configuration information into the configuration
77 **		file read at runtime.  My intent is that anything
78 **		here is a function of the version of UNIX you
79 **		are running, or is really static -- for example
80 **		the headers are a superset of widely used
81 **		protocols.  If you find yourself playing with
82 **		this file too much, you may be making a mistake!
83 */
84 
85 
86 /*
87 **  Header info table
88 **	Final (null) entry contains the flags used for any other field.
89 **
90 **	Not all of these are actually handled specially by sendmail
91 **	at this time.  They are included as placeholders, to let
92 **	you know that "someday" I intend to have sendmail do
93 **	something with them.
94 */
95 
96 struct hdrinfo	HdrInfo[] =
97 {
98 		/* originator fields, most to least significant */
99 	{ "resent-sender",		H_FROM|H_RESENT,	NULL	},
100 	{ "resent-from",		H_FROM|H_RESENT,	NULL	},
101 	{ "resent-reply-to",		H_FROM|H_RESENT,	NULL	},
102 	{ "sender",			H_FROM,			NULL	},
103 	{ "from",			H_FROM,			NULL	},
104 	{ "reply-to",			H_FROM,			NULL	},
105 	{ "errors-to",			H_FROM|H_ERRORSTO,	NULL	},
106 	{ "full-name",			H_ACHECK,		NULL	},
107 	{ "return-receipt-to",		H_RECEIPTTO,		NULL	},
108 	{ "delivery-receipt-to",	H_RECEIPTTO,		NULL	},
109 	{ "disposition-notification-to",	H_FROM,		NULL	},
110 
111 		/* destination fields */
112 	{ "to",				H_RCPT,			NULL	},
113 	{ "resent-to",			H_RCPT|H_RESENT,	NULL	},
114 	{ "cc",				H_RCPT,			NULL	},
115 	{ "resent-cc",			H_RCPT|H_RESENT,	NULL	},
116 	{ "bcc",			H_RCPT|H_BCC,		NULL	},
117 	{ "resent-bcc",			H_RCPT|H_BCC|H_RESENT,	NULL	},
118 	{ "apparently-to",		H_RCPT,			NULL	},
119 
120 		/* message identification and control */
121 	{ "message-id",			0,			NULL	},
122 	{ "resent-message-id",		H_RESENT,		NULL	},
123 	{ "message",			H_EOH,			NULL	},
124 	{ "text",			H_EOH,			NULL	},
125 
126 		/* date fields */
127 	{ "date",			0,			NULL	},
128 	{ "resent-date",		H_RESENT,		NULL	},
129 
130 		/* trace fields */
131 	{ "received",			H_TRACE|H_FORCE,	NULL	},
132 	{ "x400-received",		H_TRACE|H_FORCE,	NULL	},
133 	{ "via",			H_TRACE|H_FORCE,	NULL	},
134 	{ "mail-from",			H_TRACE|H_FORCE,	NULL	},
135 
136 		/* miscellaneous fields */
137 	{ "comments",			H_FORCE|H_ENCODABLE,	NULL	},
138 	{ "return-path",		H_FORCE|H_ACHECK|H_BINDLATE,	NULL	},
139 	{ "content-transfer-encoding",	H_CTE,			NULL	},
140 	{ "content-type",		H_CTYPE,		NULL	},
141 	{ "content-length",		H_ACHECK,		NULL	},
142 	{ "subject",			H_ENCODABLE,		NULL	},
143 	{ "x-authentication-warning",	H_FORCE,		NULL	},
144 
145 	{ NULL,				0,			NULL	}
146 };
147 
148 
149 
150 /*
151 **  Privacy values
152 */
153 
154 struct prival PrivacyValues[] =
155 {
156 	{ "public",		PRIV_PUBLIC		},
157 	{ "needmailhelo",	PRIV_NEEDMAILHELO	},
158 	{ "needexpnhelo",	PRIV_NEEDEXPNHELO	},
159 	{ "needvrfyhelo",	PRIV_NEEDVRFYHELO	},
160 	{ "noexpn",		PRIV_NOEXPN		},
161 	{ "novrfy",		PRIV_NOVRFY		},
162 	{ "restrictexpand",	PRIV_RESTRICTEXPAND	},
163 	{ "restrictmailq",	PRIV_RESTRICTMAILQ	},
164 	{ "restrictqrun",	PRIV_RESTRICTQRUN	},
165 	{ "noetrn",		PRIV_NOETRN		},
166 	{ "noverb",		PRIV_NOVERB		},
167 	{ "authwarnings",	PRIV_AUTHWARNINGS	},
168 	{ "noreceipts",		PRIV_NORECEIPTS		},
169 	{ "nobodyreturn",	PRIV_NOBODYRETN		},
170 	{ "goaway",		PRIV_GOAWAY		},
171 	{ "noactualrecipient",	PRIV_NOACTUALRECIPIENT	},
172 	{ NULL,			0			}
173 };
174 
175 /*
176 **  DontBlameSendmail values
177 */
178 
179 struct dbsval DontBlameSendmailValues[] =
180 {
181 	{ "safe",			DBS_SAFE			},
182 	{ "assumesafechown",		DBS_ASSUMESAFECHOWN		},
183 	{ "groupwritabledirpathsafe",	DBS_GROUPWRITABLEDIRPATHSAFE	},
184 	{ "groupwritableforwardfilesafe",
185 					DBS_GROUPWRITABLEFORWARDFILESAFE },
186 	{ "groupwritableincludefilesafe",
187 					DBS_GROUPWRITABLEINCLUDEFILESAFE },
188 	{ "groupwritablealiasfile",	DBS_GROUPWRITABLEALIASFILE	},
189 	{ "worldwritablealiasfile",	DBS_WORLDWRITABLEALIASFILE	},
190 	{ "forwardfileinunsafedirpath",	DBS_FORWARDFILEINUNSAFEDIRPATH	},
191 	{ "includefileinunsafedirpath",	DBS_INCLUDEFILEINUNSAFEDIRPATH	},
192 	{ "mapinunsafedirpath",		DBS_MAPINUNSAFEDIRPATH	},
193 	{ "linkedaliasfileinwritabledir",
194 					DBS_LINKEDALIASFILEINWRITABLEDIR },
195 	{ "linkedclassfileinwritabledir",
196 					DBS_LINKEDCLASSFILEINWRITABLEDIR },
197 	{ "linkedforwardfileinwritabledir",
198 					DBS_LINKEDFORWARDFILEINWRITABLEDIR },
199 	{ "linkedincludefileinwritabledir",
200 					DBS_LINKEDINCLUDEFILEINWRITABLEDIR },
201 	{ "linkedmapinwritabledir",	DBS_LINKEDMAPINWRITABLEDIR	},
202 	{ "linkedserviceswitchfileinwritabledir",
203 					DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR },
204 	{ "filedeliverytohardlink",	DBS_FILEDELIVERYTOHARDLINK	},
205 	{ "filedeliverytosymlink",	DBS_FILEDELIVERYTOSYMLINK	},
206 	{ "writemaptohardlink",		DBS_WRITEMAPTOHARDLINK		},
207 	{ "writemaptosymlink",		DBS_WRITEMAPTOSYMLINK		},
208 	{ "writestatstohardlink",	DBS_WRITESTATSTOHARDLINK	},
209 	{ "writestatstosymlink",	DBS_WRITESTATSTOSYMLINK		},
210 	{ "forwardfileingroupwritabledirpath",
211 					DBS_FORWARDFILEINGROUPWRITABLEDIRPATH },
212 	{ "includefileingroupwritabledirpath",
213 					DBS_INCLUDEFILEINGROUPWRITABLEDIRPATH },
214 	{ "classfileinunsafedirpath",	DBS_CLASSFILEINUNSAFEDIRPATH	},
215 	{ "errorheaderinunsafedirpath",	DBS_ERRORHEADERINUNSAFEDIRPATH	},
216 	{ "helpfileinunsafedirpath",	DBS_HELPFILEINUNSAFEDIRPATH	},
217 	{ "forwardfileinunsafedirpathsafe",
218 					DBS_FORWARDFILEINUNSAFEDIRPATHSAFE },
219 	{ "includefileinunsafedirpathsafe",
220 					DBS_INCLUDEFILEINUNSAFEDIRPATHSAFE },
221 	{ "runprograminunsafedirpath",	DBS_RUNPROGRAMINUNSAFEDIRPATH	},
222 	{ "runwritableprogram",		DBS_RUNWRITABLEPROGRAM		},
223 	{ "nonrootsafeaddr",		DBS_NONROOTSAFEADDR		},
224 	{ "truststickybit",		DBS_TRUSTSTICKYBIT		},
225 	{ "dontwarnforwardfileinunsafedirpath",
226 					DBS_DONTWARNFORWARDFILEINUNSAFEDIRPATH },
227 	{ "insufficiententropy",	DBS_INSUFFICIENTENTROPY },
228 	{ "groupreadablesasldbfile",	DBS_GROUPREADABLESASLDBFILE	},
229 	{ "groupwritablesasldbfile",	DBS_GROUPWRITABLESASLDBFILE	},
230 	{ "groupwritableforwardfile",	DBS_GROUPWRITABLEFORWARDFILE	},
231 	{ "groupwritableincludefile",	DBS_GROUPWRITABLEINCLUDEFILE	},
232 	{ "worldwritableforwardfile",	DBS_WORLDWRITABLEFORWARDFILE	},
233 	{ "worldwritableincludefile",	DBS_WORLDWRITABLEINCLUDEFILE	},
234 	{ "groupreadablekeyfile",	DBS_GROUPREADABLEKEYFILE	},
235 #if _FFR_GROUPREADABLEAUTHINFOFILE
236 	{ "groupreadableadefaultauthinfofile",
237 					DBS_GROUPREADABLEAUTHINFOFILE	},
238 #endif /* _FFR_GROUPREADABLEAUTHINFOFILE */
239 	{ NULL,				0				}
240 };
241 
242 /*
243 **  Miscellaneous stuff.
244 */
245 
246 int	DtableSize =	50;		/* max open files; reset in 4.2bsd */
247 /*
248 **  SETDEFAULTS -- set default values
249 **
250 **	Some of these must be initialized using direct code since they
251 **	depend on run-time values. So let's do all of them this way.
252 **
253 **	Parameters:
254 **		e -- the default envelope.
255 **
256 **	Returns:
257 **		none.
258 **
259 **	Side Effects:
260 **		Initializes a bunch of global variables to their
261 **		default values.
262 */
263 
264 #define MINUTES		* 60
265 #define HOURS		* 60 MINUTES
266 #define DAYS		* 24 HOURS
267 
268 #ifndef MAXRULERECURSION
269 # define MAXRULERECURSION	50	/* max ruleset recursion depth */
270 #endif /* ! MAXRULERECURSION */
271 
272 void
setdefaults(e)273 setdefaults(e)
274 	register ENVELOPE *e;
275 {
276 	int i;
277 	int numprocs;
278 	struct passwd *pw;
279 
280 	numprocs = get_num_procs_online();
281 	SpaceSub = ' ';				/* option B */
282 	QueueLA = 8 * numprocs;			/* option x */
283 	RefuseLA = 12 * numprocs;		/* option X */
284 	WkRecipFact = 30000L;			/* option y */
285 	WkClassFact = 1800L;			/* option z */
286 	WkTimeFact = 90000L;			/* option Z */
287 	QueueFactor = WkRecipFact * 20;		/* option q */
288 	QueueMode = QM_NORMAL;		/* what queue items to act upon */
289 	FileMode = (RealUid != geteuid()) ? 0644 : 0600;
290 						/* option F */
291 	QueueFileMode = (RealUid != geteuid()) ? 0644 : 0600;
292 						/* option QueueFileMode */
293 
294 	if (((pw = sm_getpwnam("mailnull")) != NULL && pw->pw_uid != 0) ||
295 	    ((pw = sm_getpwnam("sendmail")) != NULL && pw->pw_uid != 0) ||
296 	    ((pw = sm_getpwnam("daemon")) != NULL && pw->pw_uid != 0))
297 	{
298 		DefUid = pw->pw_uid;		/* option u */
299 		DefGid = pw->pw_gid;		/* option g */
300 		DefUser = newstr(pw->pw_name);
301 	}
302 	else
303 	{
304 		DefUid = 1;			/* option u */
305 		DefGid = 1;			/* option g */
306 		setdefuser();
307 	}
308 	TrustedUid = 0;
309 	if (tTd(37, 4))
310 		sm_dprintf("setdefaults: DefUser=%s, DefUid=%d, DefGid=%d\n",
311 			DefUser != NULL ? DefUser : "<1:1>",
312 			(int) DefUid, (int) DefGid);
313 	CheckpointInterval = 10;		/* option C */
314 	MaxHopCount = 25;			/* option h */
315 	set_delivery_mode(SM_FORK, e);		/* option d */
316 	e->e_errormode = EM_PRINT;		/* option e */
317 	e->e_qgrp = NOQGRP;
318 	e->e_qdir = NOQDIR;
319 	e->e_xfqgrp = NOQGRP;
320 	e->e_xfqdir = NOQDIR;
321 	e->e_ctime = curtime();
322 	SevenBitInput = false;			/* option 7 */
323 	MaxMciCache = 1;			/* option k */
324 	MciCacheTimeout = 5 MINUTES;		/* option K */
325 	LogLevel = 9;				/* option L */
326 #if MILTER
327 	MilterLogLevel = -1;
328 #endif /* MILTER */
329 	inittimeouts(NULL, false);		/* option r */
330 	PrivacyFlags = PRIV_PUBLIC;		/* option p */
331 	MeToo = true;				/* option m */
332 	SendMIMEErrors = true;			/* option f */
333 	SuperSafe = SAFE_REALLY;		/* option s */
334 	clrbitmap(DontBlameSendmail);		/* DontBlameSendmail option */
335 #if MIME8TO7
336 	MimeMode = MM_CVTMIME|MM_PASS8BIT;	/* option 8 */
337 #else /* MIME8TO7 */
338 	MimeMode = MM_PASS8BIT;
339 #endif /* MIME8TO7 */
340 	for (i = 0; i < MAXTOCLASS; i++)
341 	{
342 		TimeOuts.to_q_return[i] = 5 DAYS;	/* option T */
343 		TimeOuts.to_q_warning[i] = 0;		/* option T */
344 	}
345 	ServiceSwitchFile = "/etc/mail/service.switch";
346 	ServiceCacheMaxAge = (time_t) 10;
347 	HostsFile = _PATH_HOSTS;
348 	PidFile = newstr(_PATH_SENDMAILPID);
349 	MustQuoteChars = "@,;:\\()[].'";
350 	MciInfoTimeout = 30 MINUTES;
351 	MaxRuleRecursion = MAXRULERECURSION;
352 	MaxAliasRecursion = 10;
353 	MaxMacroRecursion = 10;
354 	ColonOkInAddr = true;
355 	DontLockReadFiles = true;
356 	DontProbeInterfaces = DPI_PROBEALL;
357 	DoubleBounceAddr = "postmaster";
358 	MaxHeadersLength = MAXHDRSLEN;
359 	MaxMimeHeaderLength = MAXLINE;
360 	MaxMimeFieldLength = MaxMimeHeaderLength / 2;
361 	MaxForwardEntries = 0;
362 	FastSplit = 1;
363 	MaxNOOPCommands = MAXNOOPCOMMANDS;
364 #if SASL
365 	AuthMechanisms = newstr(AUTH_MECHANISMS);
366 	AuthRealm = NULL;
367 	MaxSLBits = INT_MAX;
368 #endif /* SASL */
369 #if STARTTLS
370 	TLS_Srv_Opts = TLS_I_SRV;
371 #endif /* STARTTLS */
372 #ifdef HESIOD_INIT
373 	HesiodContext = NULL;
374 #endif /* HESIOD_INIT */
375 #if NETINET6
376 	/* Detect if IPv6 is available at run time */
377 	i = socket(AF_INET6, SOCK_STREAM, 0);
378 	if (i >= 0)
379 	{
380 		InetMode = AF_INET6;
381 		(void) close(i);
382 	}
383 	else
384 		InetMode = AF_INET;
385 #else /* NETINET6 */
386 	InetMode = AF_INET;
387 #endif /* NETINET6 */
388 	ControlSocketName = NULL;
389 	memset(&ConnectOnlyTo, '\0', sizeof(ConnectOnlyTo));
390 	DataFileBufferSize = 4096;
391 	XscriptFileBufferSize = 4096;
392 	for (i = 0; i < MAXRWSETS; i++)
393 		RuleSetNames[i] = NULL;
394 #if MILTER
395 	InputFilters[0] = NULL;
396 #endif /* MILTER */
397 	RejectLogInterval = 3 HOURS;
398 #if REQUIRES_DIR_FSYNC
399 	RequiresDirfsync = true;
400 #endif /* REQUIRES_DIR_FSYNC */
401 #if _FFR_RCPTTHROTDELAY
402 	BadRcptThrottleDelay = 1;
403 #endif /* _FFR_RCPTTHROTDELAY */
404 	ConnectionRateWindowSize = 60;
405 	setupmaps();
406 	setupqueues();
407 	setupmailers();
408 	setupheaders();
409 }
410 
411 
412 /*
413 **  SETDEFUSER -- set/reset DefUser using DefUid (for initgroups())
414 */
415 
416 void
setdefuser()417 setdefuser()
418 {
419 	struct passwd *defpwent;
420 	static char defuserbuf[40];
421 
422 	DefUser = defuserbuf;
423 	defpwent = sm_getpwuid(DefUid);
424 	(void) sm_strlcpy(defuserbuf,
425 			  (defpwent == NULL || defpwent->pw_name == NULL)
426 			   ? "nobody" : defpwent->pw_name,
427 			  sizeof(defuserbuf));
428 	if (tTd(37, 4))
429 		sm_dprintf("setdefuser: DefUid=%d, DefUser=%s\n",
430 			   (int) DefUid, DefUser);
431 }
432 /*
433 **  SETUPQUEUES -- initialize default queues
434 **
435 **	The mqueue QUEUE structure gets filled in after readcf() but
436 **	we need something to point to now for the mailer setup,
437 **	which use "mqueue" as default queue.
438 */
439 
440 static void
setupqueues()441 setupqueues()
442 {
443 	char buf[100];
444 
445 	MaxRunnersPerQueue = 1;
446 	(void) sm_strlcpy(buf, "mqueue, P=/var/spool/mqueue", sizeof(buf));
447 	makequeue(buf, false);
448 }
449 /*
450 **  SETUPMAILERS -- initialize default mailers
451 */
452 
453 static void
setupmailers()454 setupmailers()
455 {
456 	char buf[100];
457 
458 	(void) sm_strlcpy(buf, "prog, P=/bin/sh, F=lsouDq9, T=X-Unix/X-Unix/X-Unix, A=sh -c \201u",
459 			sizeof(buf));
460 	makemailer(buf);
461 
462 	(void) sm_strlcpy(buf, "*file*, P=[FILE], F=lsDFMPEouq9, T=X-Unix/X-Unix/X-Unix, A=FILE \201u",
463 			sizeof(buf));
464 	makemailer(buf);
465 
466 	(void) sm_strlcpy(buf, "*include*, P=/dev/null, F=su, A=INCLUDE \201u",
467 			sizeof(buf));
468 	makemailer(buf);
469 	initerrmailers();
470 }
471 /*
472 **  SETUPMAPS -- set up map classes
473 */
474 
475 #define MAPDEF(name, ext, flags, parse, open, close, lookup, store) \
476 	{ \
477 		extern bool parse __P((MAP *, char *)); \
478 		extern bool open __P((MAP *, int)); \
479 		extern void close __P((MAP *)); \
480 		extern char *lookup __P((MAP *, char *, char **, int *)); \
481 		extern void store __P((MAP *, char *, char *)); \
482 		s = stab(name, ST_MAPCLASS, ST_ENTER); \
483 		s->s_mapclass.map_cname = name; \
484 		s->s_mapclass.map_ext = ext; \
485 		s->s_mapclass.map_cflags = flags; \
486 		s->s_mapclass.map_parse = parse; \
487 		s->s_mapclass.map_open = open; \
488 		s->s_mapclass.map_close = close; \
489 		s->s_mapclass.map_lookup = lookup; \
490 		s->s_mapclass.map_store = store; \
491 	}
492 
493 static void
setupmaps()494 setupmaps()
495 {
496 	register STAB *s;
497 
498 #if NEWDB
499 # if DB_VERSION_MAJOR > 1
500 	int major_v, minor_v, patch_v;
501 
502 	(void) db_version(&major_v, &minor_v, &patch_v);
503 	if (major_v != DB_VERSION_MAJOR || minor_v != DB_VERSION_MINOR)
504 	{
505 		errno = 0;
506 		syserr("Berkeley DB version mismatch: compiled against %d.%d.%d, run-time linked against %d.%d.%d",
507 		  DB_VERSION_MAJOR, DB_VERSION_MINOR, DB_VERSION_PATCH,
508 		  major_v, minor_v, patch_v);
509 	}
510 # endif /* DB_VERSION_MAJOR > 1 */
511 
512 	MAPDEF("hash", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
513 		map_parseargs, hash_map_open, db_map_close,
514 		db_map_lookup, db_map_store);
515 
516 	MAPDEF("btree", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
517 		map_parseargs, bt_map_open, db_map_close,
518 		db_map_lookup, db_map_store);
519 #endif /* NEWDB */
520 
521 #if NDBM
522 	MAPDEF("dbm", ".dir", MCF_ALIASOK|MCF_REBUILDABLE,
523 		map_parseargs, ndbm_map_open, ndbm_map_close,
524 		ndbm_map_lookup, ndbm_map_store);
525 #endif /* NDBM */
526 
527 #if NIS
528 	MAPDEF("nis", NULL, MCF_ALIASOK,
529 		map_parseargs, nis_map_open, null_map_close,
530 		nis_map_lookup, null_map_store);
531 #endif /* NIS */
532 
533 #if NISPLUS
534 	MAPDEF("nisplus", NULL, MCF_ALIASOK,
535 		map_parseargs, nisplus_map_open, null_map_close,
536 		nisplus_map_lookup, null_map_store);
537 #endif /* NISPLUS */
538 
539 #if LDAPMAP
540 	MAPDEF("ldap", NULL, MCF_ALIASOK|MCF_NOTPERSIST,
541 		ldapmap_parseargs, ldapmap_open, ldapmap_close,
542 		ldapmap_lookup, null_map_store);
543 #endif /* LDAPMAP */
544 
545 #if PH_MAP
546 	MAPDEF("ph", NULL, MCF_NOTPERSIST,
547 		ph_map_parseargs, ph_map_open, ph_map_close,
548 		ph_map_lookup, null_map_store);
549 #endif /* PH_MAP */
550 
551 #if MAP_NSD
552 	/* IRIX 6.5 nsd support */
553 	MAPDEF("nsd", NULL, MCF_ALIASOK,
554 	       map_parseargs, null_map_open, null_map_close,
555 	       nsd_map_lookup, null_map_store);
556 #endif /* MAP_NSD */
557 
558 #if HESIOD
559 	MAPDEF("hesiod", NULL, MCF_ALIASOK|MCF_ALIASONLY,
560 		map_parseargs, hes_map_open, hes_map_close,
561 		hes_map_lookup, null_map_store);
562 #endif /* HESIOD */
563 
564 #if NETINFO
565 	MAPDEF("netinfo", NULL, MCF_ALIASOK,
566 		map_parseargs, ni_map_open, null_map_close,
567 		ni_map_lookup, null_map_store);
568 #endif /* NETINFO */
569 
570 #if 0
571 	MAPDEF("dns", NULL, 0,
572 		dns_map_init, null_map_open, null_map_close,
573 		dns_map_lookup, null_map_store);
574 #endif /* 0 */
575 
576 #if NAMED_BIND
577 # if DNSMAP
578 #  if _FFR_DNSMAP_ALIASABLE
579 	MAPDEF("dns", NULL, MCF_ALIASOK,
580 	       dns_map_parseargs, dns_map_open, null_map_close,
581 	       dns_map_lookup, null_map_store);
582 #  else /* _FFR_DNSMAP_ALIASABLE */
583 	MAPDEF("dns", NULL, 0,
584 	       dns_map_parseargs, dns_map_open, null_map_close,
585 	       dns_map_lookup, null_map_store);
586 #  endif /* _FFR_DNSMAP_ALIASABLE */
587 # endif /* DNSMAP */
588 #endif /* NAMED_BIND */
589 
590 #if NAMED_BIND
591 	/* best MX DNS lookup */
592 	MAPDEF("bestmx", NULL, MCF_OPTFILE,
593 		map_parseargs, null_map_open, null_map_close,
594 		bestmx_map_lookup, null_map_store);
595 #endif /* NAMED_BIND */
596 
597 	MAPDEF("host", NULL, 0,
598 		host_map_init, null_map_open, null_map_close,
599 		host_map_lookup, null_map_store);
600 
601 	MAPDEF("text", NULL, MCF_ALIASOK,
602 		map_parseargs, text_map_open, null_map_close,
603 		text_map_lookup, null_map_store);
604 
605 	MAPDEF("stab", NULL, MCF_ALIASOK|MCF_ALIASONLY,
606 		map_parseargs, stab_map_open, null_map_close,
607 		stab_map_lookup, stab_map_store);
608 
609 	MAPDEF("implicit", NULL, MCF_ALIASOK|MCF_ALIASONLY|MCF_REBUILDABLE,
610 		map_parseargs, impl_map_open, impl_map_close,
611 		impl_map_lookup, impl_map_store);
612 
613 	/* access to system passwd file */
614 	MAPDEF("user", NULL, MCF_OPTFILE,
615 		map_parseargs, user_map_open, null_map_close,
616 		user_map_lookup, null_map_store);
617 
618 	/* dequote map */
619 	MAPDEF("dequote", NULL, 0,
620 		dequote_init, null_map_open, null_map_close,
621 		dequote_map, null_map_store);
622 
623 #if MAP_REGEX
624 	MAPDEF("regex", NULL, 0,
625 		regex_map_init, null_map_open, null_map_close,
626 		regex_map_lookup, null_map_store);
627 #endif /* MAP_REGEX */
628 
629 #if USERDB
630 	/* user database */
631 	MAPDEF("userdb", ".db", 0,
632 		map_parseargs, null_map_open, null_map_close,
633 		udb_map_lookup, null_map_store);
634 #endif /* USERDB */
635 
636 	/* arbitrary programs */
637 	MAPDEF("program", NULL, MCF_ALIASOK,
638 		map_parseargs, null_map_open, null_map_close,
639 		prog_map_lookup, null_map_store);
640 
641 	/* sequenced maps */
642 	MAPDEF("sequence", NULL, MCF_ALIASOK,
643 		seq_map_parse, null_map_open, null_map_close,
644 		seq_map_lookup, seq_map_store);
645 
646 	/* switched interface to sequenced maps */
647 	MAPDEF("switch", NULL, MCF_ALIASOK,
648 		map_parseargs, switch_map_open, null_map_close,
649 		seq_map_lookup, seq_map_store);
650 
651 	/* null map lookup -- really for internal use only */
652 	MAPDEF("null", NULL, MCF_ALIASOK|MCF_OPTFILE,
653 		map_parseargs, null_map_open, null_map_close,
654 		null_map_lookup, null_map_store);
655 
656 	/* syslog map -- logs information to syslog */
657 	MAPDEF("syslog", NULL, 0,
658 		syslog_map_parseargs, null_map_open, null_map_close,
659 		syslog_map_lookup, null_map_store);
660 
661 	/* macro storage map -- rulesets can set macros */
662 	MAPDEF("macro", NULL, 0,
663 		dequote_init, null_map_open, null_map_close,
664 		macro_map_lookup, null_map_store);
665 
666 	/* arithmetic map -- add/subtract/compare */
667 	MAPDEF("arith", NULL, 0,
668 		dequote_init, null_map_open, null_map_close,
669 		arith_map_lookup, null_map_store);
670 
671 #if SOCKETMAP
672 	/* arbitrary daemons */
673 	MAPDEF("socket", NULL, MCF_ALIASOK,
674 		map_parseargs, socket_map_open, socket_map_close,
675 		socket_map_lookup, null_map_store);
676 #endif /* SOCKETMAP */
677 
678 #if _FFR_DPRINTF_MAP
679 	/* dprintf map -- logs information to syslog */
680 	MAPDEF("dprintf", NULL, 0,
681 		dprintf_map_parseargs, null_map_open, null_map_close,
682 		dprintf_map_lookup, null_map_store);
683 #endif /* _FFR_DPRINTF_MAP */
684 
685 	if (tTd(38, 2))
686 	{
687 		/* bogus map -- always return tempfail */
688 		MAPDEF("bogus",	NULL, MCF_ALIASOK|MCF_OPTFILE,
689 		       map_parseargs, null_map_open, null_map_close,
690 		       bogus_map_lookup, null_map_store);
691 	}
692 }
693 
694 #undef MAPDEF
695 /*
696 **  INITHOSTMAPS -- initial host-dependent maps
697 **
698 **	This should act as an interface to any local service switch
699 **	provided by the host operating system.
700 **
701 **	Parameters:
702 **		none
703 **
704 **	Returns:
705 **		none
706 **
707 **	Side Effects:
708 **		Should define maps "host" and "users" as necessary
709 **		for this OS.  If they are not defined, they will get
710 **		a default value later.  It should check to make sure
711 **		they are not defined first, since it's possible that
712 **		the config file has provided an override.
713 */
714 
715 void
inithostmaps()716 inithostmaps()
717 {
718 	register int i;
719 	int nmaps;
720 	char *maptype[MAXMAPSTACK];
721 	short mapreturn[MAXMAPACTIONS];
722 	char buf[MAXLINE];
723 
724 	/*
725 	**  Make sure we have a host map.
726 	*/
727 
728 	if (stab("host", ST_MAP, ST_FIND) == NULL)
729 	{
730 		/* user didn't initialize: set up host map */
731 		(void) sm_strlcpy(buf, "host host", sizeof(buf));
732 #if NAMED_BIND
733 		if (ConfigLevel >= 2)
734 			(void) sm_strlcat(buf, " -a. -D", sizeof(buf));
735 #endif /* NAMED_BIND */
736 		(void) makemapentry(buf);
737 	}
738 
739 	/*
740 	**  Set up default aliases maps
741 	*/
742 
743 	nmaps = switch_map_find("aliases", maptype, mapreturn);
744 	for (i = 0; i < nmaps; i++)
745 	{
746 		if (strcmp(maptype[i], "files") == 0 &&
747 		    stab("aliases.files", ST_MAP, ST_FIND) == NULL)
748 		{
749 			(void) sm_strlcpy(buf, "aliases.files null",
750 					  sizeof(buf));
751 			(void) makemapentry(buf);
752 		}
753 #if NISPLUS
754 		else if (strcmp(maptype[i], "nisplus") == 0 &&
755 			 stab("aliases.nisplus", ST_MAP, ST_FIND) == NULL)
756 		{
757 			(void) sm_strlcpy(buf, "aliases.nisplus nisplus -kalias -vexpansion mail_aliases.org_dir",
758 				sizeof(buf));
759 			(void) makemapentry(buf);
760 		}
761 #endif /* NISPLUS */
762 #if NIS
763 		else if (strcmp(maptype[i], "nis") == 0 &&
764 			 stab("aliases.nis", ST_MAP, ST_FIND) == NULL)
765 		{
766 			(void) sm_strlcpy(buf, "aliases.nis nis mail.aliases",
767 				sizeof(buf));
768 			(void) makemapentry(buf);
769 		}
770 #endif /* NIS */
771 #if NETINFO
772 		else if (strcmp(maptype[i], "netinfo") == 0 &&
773 			 stab("aliases.netinfo", ST_MAP, ST_FIND) == NULL)
774 		{
775 			(void) sm_strlcpy(buf, "aliases.netinfo netinfo -z, /aliases",
776 				sizeof(buf));
777 			(void) makemapentry(buf);
778 		}
779 #endif /* NETINFO */
780 #if HESIOD
781 		else if (strcmp(maptype[i], "hesiod") == 0 &&
782 			 stab("aliases.hesiod", ST_MAP, ST_FIND) == NULL)
783 		{
784 			(void) sm_strlcpy(buf, "aliases.hesiod hesiod aliases",
785 				sizeof(buf));
786 			(void) makemapentry(buf);
787 		}
788 #endif /* HESIOD */
789 #if LDAPMAP && defined(SUN_EXTENSIONS) && \
790     defined(SUN_SIMPLIFIED_LDAP) && HASLDAPGETALIASBYNAME
791 		else if (strcmp(maptype[i], "ldap") == 0 &&
792 		    stab("aliases.ldap", ST_MAP, ST_FIND) == NULL)
793 		{
794 			(void) sm_strlcpy(buf, "aliases.ldap ldap -b . -h localhost -k mail=%0 -v mailgroup",
795 				sizeof buf);
796 			(void) makemapentry(buf);
797 		}
798 #endif /* LDAPMAP && defined(SUN_EXTENSIONS) && ... */
799 	}
800 	if (stab("aliases", ST_MAP, ST_FIND) == NULL)
801 	{
802 		(void) sm_strlcpy(buf, "aliases switch aliases", sizeof(buf));
803 		(void) makemapentry(buf);
804 	}
805 }
806 
807 /*
808 **  SWITCH_MAP_FIND -- find the list of types associated with a map
809 **
810 **	This is the system-dependent interface to the service switch.
811 **
812 **	Parameters:
813 **		service -- the name of the service of interest.
814 **		maptype -- an out-array of strings containing the types
815 **			of access to use for this service.  There can
816 **			be at most MAXMAPSTACK types for a single service.
817 **		mapreturn -- an out-array of return information bitmaps
818 **			for the map.
819 **
820 **	Returns:
821 **		The number of map types filled in, or -1 for failure.
822 **
823 **	Side effects:
824 **		Preserves errno so nothing in the routine clobbers it.
825 */
826 
827 #if defined(SOLARIS) || (defined(sony_news) && defined(__svr4))
828 # define _USE_SUN_NSSWITCH_
829 #endif /* defined(SOLARIS) || (defined(sony_news) && defined(__svr4)) */
830 
831 #if _FFR_HPUX_NSSWITCH
832 # ifdef __hpux
833 #  define _USE_SUN_NSSWITCH_
834 # endif /* __hpux */
835 #endif /* _FFR_HPUX_NSSWITCH */
836 
837 #ifdef _USE_SUN_NSSWITCH_
838 # include <nsswitch.h>
839 #endif /* _USE_SUN_NSSWITCH_ */
840 
841 #if defined(ultrix) || (defined(__osf__) && defined(__alpha))
842 # define _USE_DEC_SVC_CONF_
843 #endif /* defined(ultrix) || (defined(__osf__) && defined(__alpha)) */
844 
845 #ifdef _USE_DEC_SVC_CONF_
846 # include <sys/svcinfo.h>
847 #endif /* _USE_DEC_SVC_CONF_ */
848 
849 int
switch_map_find(service,maptype,mapreturn)850 switch_map_find(service, maptype, mapreturn)
851 	char *service;
852 	char *maptype[MAXMAPSTACK];
853 	short mapreturn[MAXMAPACTIONS];
854 {
855 	int svcno = 0;
856 	int save_errno = errno;
857 
858 #ifdef _USE_SUN_NSSWITCH_
859 	struct __nsw_switchconfig *nsw_conf;
860 	enum __nsw_parse_err pserr;
861 	struct __nsw_lookup *lk;
862 	static struct __nsw_lookup lkp0 =
863 		{ "files", {1, 0, 0, 0}, NULL, NULL };
864 	static struct __nsw_switchconfig lkp_default =
865 		{ 0, "sendmail", 3, &lkp0 };
866 
867 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
868 		mapreturn[svcno] = 0;
869 
870 	if ((nsw_conf = __nsw_getconfig(service, &pserr)) == NULL)
871 		lk = lkp_default.lookups;
872 	else
873 		lk = nsw_conf->lookups;
874 	svcno = 0;
875 	while (lk != NULL && svcno < MAXMAPSTACK)
876 	{
877 		maptype[svcno] = lk->service_name;
878 		if (lk->actions[__NSW_NOTFOUND] == __NSW_RETURN)
879 			mapreturn[MA_NOTFOUND] |= 1 << svcno;
880 		if (lk->actions[__NSW_TRYAGAIN] == __NSW_RETURN)
881 			mapreturn[MA_TRYAGAIN] |= 1 << svcno;
882 		if (lk->actions[__NSW_UNAVAIL] == __NSW_RETURN)
883 			mapreturn[MA_TRYAGAIN] |= 1 << svcno;
884 		svcno++;
885 		lk = lk->next;
886 	}
887 	errno = save_errno;
888 	return svcno;
889 #endif /* _USE_SUN_NSSWITCH_ */
890 
891 #ifdef _USE_DEC_SVC_CONF_
892 	struct svcinfo *svcinfo;
893 	int svc;
894 
895 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
896 		mapreturn[svcno] = 0;
897 
898 	svcinfo = getsvc();
899 	if (svcinfo == NULL)
900 		goto punt;
901 	if (strcmp(service, "hosts") == 0)
902 		svc = SVC_HOSTS;
903 	else if (strcmp(service, "aliases") == 0)
904 		svc = SVC_ALIASES;
905 	else if (strcmp(service, "passwd") == 0)
906 		svc = SVC_PASSWD;
907 	else
908 	{
909 		errno = save_errno;
910 		return -1;
911 	}
912 	for (svcno = 0; svcno < SVC_PATHSIZE && svcno < MAXMAPSTACK; svcno++)
913 	{
914 		switch (svcinfo->svcpath[svc][svcno])
915 		{
916 		  case SVC_LOCAL:
917 			maptype[svcno] = "files";
918 			break;
919 
920 		  case SVC_YP:
921 			maptype[svcno] = "nis";
922 			break;
923 
924 		  case SVC_BIND:
925 			maptype[svcno] = "dns";
926 			break;
927 
928 # ifdef SVC_HESIOD
929 		  case SVC_HESIOD:
930 			maptype[svcno] = "hesiod";
931 			break;
932 # endif /* SVC_HESIOD */
933 
934 		  case SVC_LAST:
935 			errno = save_errno;
936 			return svcno;
937 		}
938 	}
939 	errno = save_errno;
940 	return svcno;
941 #endif /* _USE_DEC_SVC_CONF_ */
942 
943 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
944 	/*
945 	**  Fall-back mechanism.
946 	*/
947 
948 	STAB *st;
949 	static time_t servicecachetime;	/* time service switch was cached */
950 	time_t now = curtime();
951 
952 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
953 		mapreturn[svcno] = 0;
954 
955 	if ((now - servicecachetime) > (time_t) ServiceCacheMaxAge)
956 	{
957 		/* (re)read service switch */
958 		register SM_FILE_T *fp;
959 		long sff = SFF_REGONLY|SFF_OPENASROOT|SFF_NOLOCK;
960 
961 		if (!bitnset(DBS_LINKEDSERVICESWITCHFILEINWRITABLEDIR,
962 			    DontBlameSendmail))
963 			sff |= SFF_NOWLINK;
964 
965 		if (ConfigFileRead)
966 			servicecachetime = now;
967 		fp = safefopen(ServiceSwitchFile, O_RDONLY, 0, sff);
968 		if (fp != NULL)
969 		{
970 			char buf[MAXLINE];
971 
972 			while (sm_io_fgets(fp, SM_TIME_DEFAULT, buf,
973 					   sizeof(buf)) != NULL)
974 			{
975 				register char *p;
976 
977 				p = strpbrk(buf, "#\n");
978 				if (p != NULL)
979 					*p = '\0';
980 #ifndef SM_NSSWITCH_DELIMS
981 # define SM_NSSWITCH_DELIMS	" \t"
982 #endif /* SM_NSSWITCH_DELIMS */
983 				p = strpbrk(buf, SM_NSSWITCH_DELIMS);
984 				if (p != NULL)
985 					*p++ = '\0';
986 				if (buf[0] == '\0')
987 					continue;
988 				if (p == NULL)
989 				{
990 					sm_syslog(LOG_ERR, NOQID,
991 						  "Bad line on %.100s: %.100s",
992 						  ServiceSwitchFile,
993 						  buf);
994 					continue;
995 				}
996 				while (isascii(*p) && isspace(*p))
997 					p++;
998 				if (*p == '\0')
999 					continue;
1000 
1001 				/*
1002 				**  Find/allocate space for this service entry.
1003 				**	Space for all of the service strings
1004 				**	are allocated at once.  This means
1005 				**	that we only have to free the first
1006 				**	one to free all of them.
1007 				*/
1008 
1009 				st = stab(buf, ST_SERVICE, ST_ENTER);
1010 				if (st->s_service[0] != NULL)
1011 					sm_free((void *) st->s_service[0]); /* XXX */
1012 				p = newstr(p);
1013 				for (svcno = 0; svcno < MAXMAPSTACK; )
1014 				{
1015 					if (*p == '\0')
1016 						break;
1017 					st->s_service[svcno++] = p;
1018 					p = strpbrk(p, " \t");
1019 					if (p == NULL)
1020 						break;
1021 					*p++ = '\0';
1022 					while (isascii(*p) && isspace(*p))
1023 						p++;
1024 				}
1025 				if (svcno < MAXMAPSTACK)
1026 					st->s_service[svcno] = NULL;
1027 			}
1028 			(void) sm_io_close(fp, SM_TIME_DEFAULT);
1029 		}
1030 	}
1031 
1032 	/* look up entry in cache */
1033 	st = stab(service, ST_SERVICE, ST_FIND);
1034 	if (st != NULL && st->s_service[0] != NULL)
1035 	{
1036 		/* extract data */
1037 		svcno = 0;
1038 		while (svcno < MAXMAPSTACK)
1039 		{
1040 			maptype[svcno] = st->s_service[svcno];
1041 			if (maptype[svcno++] == NULL)
1042 				break;
1043 		}
1044 		errno = save_errno;
1045 		return --svcno;
1046 	}
1047 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1048 
1049 #if !defined(_USE_SUN_NSSWITCH_)
1050 	/* if the service file doesn't work, use an absolute fallback */
1051 # ifdef _USE_DEC_SVC_CONF_
1052   punt:
1053 # endif /* _USE_DEC_SVC_CONF_ */
1054 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
1055 		mapreturn[svcno] = 0;
1056 	svcno = 0;
1057 	if (strcmp(service, "aliases") == 0)
1058 	{
1059 		maptype[svcno++] = "files";
1060 # if defined(AUTO_NETINFO_ALIASES) && defined (NETINFO)
1061 		maptype[svcno++] = "netinfo";
1062 # endif /* defined(AUTO_NETINFO_ALIASES) && defined (NETINFO) */
1063 # ifdef AUTO_NIS_ALIASES
1064 #  if NISPLUS
1065 		maptype[svcno++] = "nisplus";
1066 #  endif /* NISPLUS */
1067 #  if NIS
1068 		maptype[svcno++] = "nis";
1069 #  endif /* NIS */
1070 # endif /* AUTO_NIS_ALIASES */
1071 		errno = save_errno;
1072 		return svcno;
1073 	}
1074 	if (strcmp(service, "hosts") == 0)
1075 	{
1076 # if NAMED_BIND
1077 		maptype[svcno++] = "dns";
1078 # else /* NAMED_BIND */
1079 #  if defined(sun) && !defined(BSD)
1080 		/* SunOS */
1081 		maptype[svcno++] = "nis";
1082 #  endif /* defined(sun) && !defined(BSD) */
1083 # endif /* NAMED_BIND */
1084 # if defined(AUTO_NETINFO_HOSTS) && defined (NETINFO)
1085 		maptype[svcno++] = "netinfo";
1086 # endif /* defined(AUTO_NETINFO_HOSTS) && defined (NETINFO) */
1087 		maptype[svcno++] = "files";
1088 		errno = save_errno;
1089 		return svcno;
1090 	}
1091 	errno = save_errno;
1092 	return -1;
1093 #endif /* !defined(_USE_SUN_NSSWITCH_) */
1094 }
1095 /*
1096 **  USERNAME -- return the user id of the logged in user.
1097 **
1098 **	Parameters:
1099 **		none.
1100 **
1101 **	Returns:
1102 **		The login name of the logged in user.
1103 **
1104 **	Side Effects:
1105 **		none.
1106 **
1107 **	Notes:
1108 **		The return value is statically allocated.
1109 */
1110 
1111 char *
username()1112 username()
1113 {
1114 	static char *myname = NULL;
1115 	extern char *getlogin();
1116 	register struct passwd *pw;
1117 
1118 	/* cache the result */
1119 	if (myname == NULL)
1120 	{
1121 		myname = getlogin();
1122 		if (myname == NULL || myname[0] == '\0')
1123 		{
1124 			pw = sm_getpwuid(RealUid);
1125 			if (pw != NULL)
1126 				myname = pw->pw_name;
1127 		}
1128 		else
1129 		{
1130 			uid_t uid = RealUid;
1131 
1132 			if ((pw = sm_getpwnam(myname)) == NULL ||
1133 			      (uid != 0 && uid != pw->pw_uid))
1134 			{
1135 				pw = sm_getpwuid(uid);
1136 				if (pw != NULL)
1137 					myname = pw->pw_name;
1138 			}
1139 		}
1140 		if (myname == NULL || myname[0] == '\0')
1141 		{
1142 			syserr("554 5.3.0 Who are you?");
1143 			myname = "postmaster";
1144 		}
1145 		else if (strpbrk(myname, ",;:/|\"\\") != NULL)
1146 			myname = addquotes(myname, NULL);
1147 		else
1148 			myname = sm_pstrdup_x(myname);
1149 	}
1150 	return myname;
1151 }
1152 /*
1153 **  TTYPATH -- Get the path of the user's tty
1154 **
1155 **	Returns the pathname of the user's tty.  Returns NULL if
1156 **	the user is not logged in or if they have write permission
1157 **	denied.
1158 **
1159 **	Parameters:
1160 **		none
1161 **
1162 **	Returns:
1163 **		pathname of the user's tty.
1164 **		NULL if not logged in or write permission denied.
1165 **
1166 **	Side Effects:
1167 **		none.
1168 **
1169 **	WARNING:
1170 **		Return value is in a local buffer.
1171 **
1172 **	Called By:
1173 **		savemail
1174 */
1175 
1176 char *
ttypath()1177 ttypath()
1178 {
1179 	struct stat stbuf;
1180 	register char *pathn;
1181 	extern char *ttyname();
1182 	extern char *getlogin();
1183 
1184 	/* compute the pathname of the controlling tty */
1185 	if ((pathn = ttyname(2)) == NULL && (pathn = ttyname(1)) == NULL &&
1186 	    (pathn = ttyname(0)) == NULL)
1187 	{
1188 		errno = 0;
1189 		return NULL;
1190 	}
1191 
1192 	/* see if we have write permission */
1193 	if (stat(pathn, &stbuf) < 0 || !bitset(S_IWOTH, stbuf.st_mode))
1194 	{
1195 		errno = 0;
1196 		return NULL;
1197 	}
1198 
1199 	/* see if the user is logged in */
1200 	if (getlogin() == NULL)
1201 		return NULL;
1202 
1203 	/* looks good */
1204 	return pathn;
1205 }
1206 /*
1207 **  CHECKCOMPAT -- check for From and To person compatible.
1208 **
1209 **	This routine can be supplied on a per-installation basis
1210 **	to determine whether a person is allowed to send a message.
1211 **	This allows restriction of certain types of internet
1212 **	forwarding or registration of users.
1213 **
1214 **	If the hosts are found to be incompatible, an error
1215 **	message should be given using "usrerr" and an EX_ code
1216 **	should be returned.  You can also set to->q_status to
1217 **	a DSN-style status code.
1218 **
1219 **	EF_NO_BODY_RETN can be set in e->e_flags to suppress the
1220 **	body during the return-to-sender function; this should be done
1221 **	on huge messages.  This bit may already be set by the ESMTP
1222 **	protocol.
1223 **
1224 **	Parameters:
1225 **		to -- the person being sent to.
1226 **
1227 **	Returns:
1228 **		an exit status
1229 **
1230 **	Side Effects:
1231 **		none (unless you include the usrerr stuff)
1232 */
1233 
1234 int
checkcompat(to,e)1235 checkcompat(to, e)
1236 	register ADDRESS *to;
1237 	register ENVELOPE *e;
1238 {
1239 	if (tTd(49, 1))
1240 		sm_dprintf("checkcompat(to=%s, from=%s)\n",
1241 			to->q_paddr, e->e_from.q_paddr);
1242 
1243 #ifdef EXAMPLE_CODE
1244 	/* this code is intended as an example only */
1245 	register STAB *s;
1246 
1247 	s = stab("arpa", ST_MAILER, ST_FIND);
1248 	if (s != NULL && strcmp(e->e_from.q_mailer->m_name, "local") != 0 &&
1249 	    to->q_mailer == s->s_mailer)
1250 	{
1251 		usrerr("553 No ARPA mail through this machine: see your system administration");
1252 		/* e->e_flags |= EF_NO_BODY_RETN; to suppress body on return */
1253 		to->q_status = "5.7.1";
1254 		return EX_UNAVAILABLE;
1255 	}
1256 #endif /* EXAMPLE_CODE */
1257 	return EX_OK;
1258 }
1259 
1260 #ifdef SUN_EXTENSIONS
1261 static void
init_md_sun()1262 init_md_sun()
1263 {
1264 	struct stat sbuf;
1265 
1266 	/* Check for large file descriptor */
1267 	if (fstat(fileno(stdin), &sbuf) < 0)
1268 	{
1269 		if (errno == EOVERFLOW)
1270 		{
1271 			perror("stdin");
1272 			exit(EX_NOINPUT);
1273 		}
1274 	}
1275 }
1276 #endif /* SUN_EXTENSIONS */
1277 
1278 /*
1279 **  INIT_MD -- do machine dependent initializations
1280 **
1281 **	Systems that have global modes that should be set should do
1282 **	them here rather than in main.
1283 */
1284 
1285 #ifdef _AUX_SOURCE
1286 # include <compat.h>
1287 #endif /* _AUX_SOURCE */
1288 
1289 #if SHARE_V1
1290 # include <shares.h>
1291 #endif /* SHARE_V1 */
1292 
1293 void
init_md(argc,argv)1294 init_md(argc, argv)
1295 	int argc;
1296 	char **argv;
1297 {
1298 #ifdef _AUX_SOURCE
1299 	setcompat(getcompat() | COMPAT_BSDPROT);
1300 #endif /* _AUX_SOURCE */
1301 
1302 #ifdef SUN_EXTENSIONS
1303 	init_md_sun();
1304 #endif /* SUN_EXTENSIONS */
1305 
1306 #if _CONVEX_SOURCE
1307 	/* keep gethostby*() from stripping the local domain name */
1308 	set_domain_trim_off();
1309 #endif /* _CONVEX_SOURCE */
1310 #if defined(__QNX__) && !defined(__QNXNTO__)
1311 	/*
1312 	**  Due to QNX's network distributed nature, you can target a tcpip
1313 	**  stack on a different node in the qnx network; this patch lets
1314 	**  this feature work.  The __sock_locate() must be done before the
1315 	**  environment is clear.
1316 	*/
1317 	__sock_locate();
1318 #endif /* __QNX__ */
1319 #if SECUREWARE || defined(_SCO_unix_)
1320 	set_auth_parameters(argc, argv);
1321 
1322 # ifdef _SCO_unix_
1323 	/*
1324 	**  This is required for highest security levels (the kernel
1325 	**  won't let it call set*uid() or run setuid binaries without
1326 	**  it).  It may be necessary on other SECUREWARE systems.
1327 	*/
1328 
1329 	if (getluid() == -1)
1330 		setluid(0);
1331 # endif /* _SCO_unix_ */
1332 #endif /* SECUREWARE || defined(_SCO_unix_) */
1333 
1334 
1335 #ifdef VENDOR_DEFAULT
1336 	VendorCode = VENDOR_DEFAULT;
1337 #else /* VENDOR_DEFAULT */
1338 	VendorCode = VENDOR_BERKELEY;
1339 #endif /* VENDOR_DEFAULT */
1340 }
1341 /*
1342 **  INIT_VENDOR_MACROS -- vendor-dependent macro initializations
1343 **
1344 **	Called once, on startup.
1345 **
1346 **	Parameters:
1347 **		e -- the global envelope.
1348 **
1349 **	Returns:
1350 **		none.
1351 **
1352 **	Side Effects:
1353 **		vendor-dependent.
1354 */
1355 
1356 void
init_vendor_macros(e)1357 init_vendor_macros(e)
1358 	register ENVELOPE *e;
1359 {
1360 }
1361 /*
1362 **  GETLA -- get the current load average
1363 **
1364 **	This code stolen from la.c.
1365 **
1366 **	Parameters:
1367 **		none.
1368 **
1369 **	Returns:
1370 **		The current load average as an integer.
1371 **
1372 **	Side Effects:
1373 **		none.
1374 */
1375 
1376 /* try to guess what style of load average we have */
1377 #define LA_ZERO		1	/* always return load average as zero */
1378 #define LA_INT		2	/* read kmem for avenrun; interpret as long */
1379 #define LA_FLOAT	3	/* read kmem for avenrun; interpret as float */
1380 #define LA_SUBR		4	/* call getloadavg */
1381 #define LA_MACH		5	/* MACH load averages (as on NeXT boxes) */
1382 #define LA_SHORT	6	/* read kmem for avenrun; interpret as short */
1383 #define LA_PROCSTR	7	/* read string ("1.17") from /proc/loadavg */
1384 #define LA_READKSYM	8	/* SVR4: use MIOC_READKSYM ioctl call */
1385 #define LA_DGUX		9	/* special DGUX implementation */
1386 #define LA_HPUX		10	/* special HPUX implementation */
1387 #define LA_IRIX6	11	/* special IRIX 6.2 implementation */
1388 #define LA_KSTAT	12	/* special Solaris kstat(3k) implementation */
1389 #define LA_DEVSHORT	13	/* read short from a device */
1390 #define LA_ALPHAOSF	14	/* Digital UNIX (OSF/1 on Alpha) table() call */
1391 #define LA_PSET		15	/* Solaris per-processor-set load average */
1392 #define LA_LONGLONG	17 /* read kmem for avenrun; interpret as long long */
1393 
1394 /* do guesses based on general OS type */
1395 #ifndef LA_TYPE
1396 # define LA_TYPE	LA_ZERO
1397 #endif /* ! LA_TYPE */
1398 
1399 #ifndef FSHIFT
1400 # if defined(unixpc)
1401 #  define FSHIFT	5
1402 # endif /* defined(unixpc) */
1403 
1404 # if defined(__alpha) || defined(IRIX)
1405 #  define FSHIFT	10
1406 # endif /* defined(__alpha) || defined(IRIX) */
1407 
1408 #endif /* ! FSHIFT */
1409 
1410 #ifndef FSHIFT
1411 # define FSHIFT		8
1412 #endif /* ! FSHIFT */
1413 
1414 #ifndef FSCALE
1415 # define FSCALE		(1 << FSHIFT)
1416 #endif /* ! FSCALE */
1417 
1418 #ifndef LA_AVENRUN
1419 # ifdef SYSTEM5
1420 #  define LA_AVENRUN	"avenrun"
1421 # else /* SYSTEM5 */
1422 #  define LA_AVENRUN	"_avenrun"
1423 # endif /* SYSTEM5 */
1424 #endif /* ! LA_AVENRUN */
1425 
1426 /* _PATH_KMEM should be defined in <paths.h> */
1427 #ifndef _PATH_KMEM
1428 # define _PATH_KMEM	"/dev/kmem"
1429 #endif /* ! _PATH_KMEM */
1430 
1431 #if (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG)
1432 
1433 # include <nlist.h>
1434 
1435 /* _PATH_UNIX should be defined in <paths.h> */
1436 # ifndef _PATH_UNIX
1437 #  if defined(SYSTEM5)
1438 #   define _PATH_UNIX	"/unix"
1439 #  else /* defined(SYSTEM5) */
1440 #   define _PATH_UNIX	"/vmunix"
1441 #  endif /* defined(SYSTEM5) */
1442 # endif /* ! _PATH_UNIX */
1443 
1444 # ifdef _AUX_SOURCE
1445 struct nlist	Nl[2];
1446 # else /* _AUX_SOURCE */
1447 struct nlist	Nl[] =
1448 {
1449 	{ LA_AVENRUN },
1450 	{ 0 },
1451 };
1452 # endif /* _AUX_SOURCE */
1453 # define X_AVENRUN	0
1454 
1455 int
getla()1456 getla()
1457 {
1458 	int j;
1459 	static int kmem = -1;
1460 # if LA_TYPE == LA_INT
1461 	long avenrun[3];
1462 # else /* LA_TYPE == LA_INT */
1463 #  if LA_TYPE == LA_SHORT
1464 	short avenrun[3];
1465 #  else
1466 #   if LA_TYPE == LA_LONGLONG
1467 	long long avenrun[3];
1468 #   else /* LA_TYPE == LA_LONGLONG */
1469 	double avenrun[3];
1470 #   endif /* LA_TYPE == LA_LONGLONG */
1471 #  endif /* LA_TYPE == LA_SHORT */
1472 # endif /* LA_TYPE == LA_INT */
1473 	extern off_t lseek();
1474 
1475 	if (kmem < 0)
1476 	{
1477 # ifdef _AUX_SOURCE
1478 		(void) sm_strlcpy(Nl[X_AVENRUN].n_name, LA_AVENRUN,
1479 			       sizeof(Nl[X_AVENRUN].n_name));
1480 		Nl[1].n_name[0] = '\0';
1481 # endif /* _AUX_SOURCE */
1482 
1483 # if defined(_AIX3) || defined(_AIX4)
1484 		if (knlist(Nl, 1, sizeof(Nl[0])) < 0)
1485 # else /* defined(_AIX3) || defined(_AIX4) */
1486 		if (nlist(_PATH_UNIX, Nl) < 0)
1487 # endif /* defined(_AIX3) || defined(_AIX4) */
1488 		{
1489 			if (tTd(3, 1))
1490 				sm_dprintf("getla: nlist(%s): %s\n", _PATH_UNIX,
1491 					   sm_errstring(errno));
1492 			return -1;
1493 		}
1494 		if (Nl[X_AVENRUN].n_value == 0)
1495 		{
1496 			if (tTd(3, 1))
1497 				sm_dprintf("getla: nlist(%s, %s) ==> 0\n",
1498 					_PATH_UNIX, LA_AVENRUN);
1499 			return -1;
1500 		}
1501 # ifdef NAMELISTMASK
1502 		Nl[X_AVENRUN].n_value &= NAMELISTMASK;
1503 # endif /* NAMELISTMASK */
1504 
1505 		kmem = open(_PATH_KMEM, 0, 0);
1506 		if (kmem < 0)
1507 		{
1508 			if (tTd(3, 1))
1509 				sm_dprintf("getla: open(/dev/kmem): %s\n",
1510 					   sm_errstring(errno));
1511 			return -1;
1512 		}
1513 		if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1514 		    fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1515 		{
1516 			if (tTd(3, 1))
1517 				sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1518 					   sm_errstring(errno));
1519 			(void) close(kmem);
1520 			kmem = -1;
1521 			return -1;
1522 		}
1523 	}
1524 	if (tTd(3, 20))
1525 		sm_dprintf("getla: symbol address = %#lx\n",
1526 			(unsigned long) Nl[X_AVENRUN].n_value);
1527 	if (lseek(kmem, (off_t) Nl[X_AVENRUN].n_value, SEEK_SET) == -1 ||
1528 	    read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun))
1529 	{
1530 		/* thank you Ian */
1531 		if (tTd(3, 1))
1532 			sm_dprintf("getla: lseek or read: %s\n",
1533 				   sm_errstring(errno));
1534 		return -1;
1535 	}
1536 # if (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG)
1537 	if (tTd(3, 5))
1538 	{
1539 #  if LA_TYPE == LA_SHORT
1540 		sm_dprintf("getla: avenrun = %d", avenrun[0]);
1541 		if (tTd(3, 15))
1542 			sm_dprintf(", %d, %d", avenrun[1], avenrun[2]);
1543 #  else /* LA_TYPE == LA_SHORT */
1544 #   if LA_TYPE == LA_LONGLONG
1545 		sm_dprintf("getla: avenrun = %lld", avenrun[0]);
1546 		if (tTd(3, 15))
1547 			sm_dprintf(", %lld, %lld", avenrun[1], avenrun[2]);
1548 #   else /* LA_TYPE == LA_LONGLONG */
1549 		sm_dprintf("getla: avenrun = %ld", avenrun[0]);
1550 		if (tTd(3, 15))
1551 			sm_dprintf(", %ld, %ld", avenrun[1], avenrun[2]);
1552 #   endif /* LA_TYPE == LA_LONGLONG */
1553 #  endif /* LA_TYPE == LA_SHORT */
1554 		sm_dprintf("\n");
1555 	}
1556 	if (tTd(3, 1))
1557 		sm_dprintf("getla: %d\n",
1558 			(int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1559 	return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1560 # else /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1561 	if (tTd(3, 5))
1562 	{
1563 		sm_dprintf("getla: avenrun = %g", avenrun[0]);
1564 		if (tTd(3, 15))
1565 			sm_dprintf(", %g, %g", avenrun[1], avenrun[2]);
1566 		sm_dprintf("\n");
1567 	}
1568 	if (tTd(3, 1))
1569 		sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
1570 	return ((int) (avenrun[0] + 0.5));
1571 # endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1572 }
1573 
1574 #endif /* (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT) || (LA_TYPE == LA_LONGLONG) */
1575 
1576 #if LA_TYPE == LA_READKSYM
1577 
1578 # include <sys/ksym.h>
1579 
1580 int
getla()1581 getla()
1582 {
1583 	int j;
1584 	static int kmem = -1;
1585 	long avenrun[3];
1586 	struct mioc_rksym mirk;
1587 
1588 	if (kmem < 0)
1589 	{
1590 		kmem = open("/dev/kmem", 0, 0);
1591 		if (kmem < 0)
1592 		{
1593 			if (tTd(3, 1))
1594 				sm_dprintf("getla: open(/dev/kmem): %s\n",
1595 					   sm_errstring(errno));
1596 			return -1;
1597 		}
1598 		if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1599 		    fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1600 		{
1601 			if (tTd(3, 1))
1602 				sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1603 					   sm_errstring(errno));
1604 			(void) close(kmem);
1605 			kmem = -1;
1606 			return -1;
1607 		}
1608 	}
1609 	mirk.mirk_symname = LA_AVENRUN;
1610 	mirk.mirk_buf = avenrun;
1611 	mirk.mirk_buflen = sizeof(avenrun);
1612 	if (ioctl(kmem, MIOC_READKSYM, &mirk) < 0)
1613 	{
1614 		if (tTd(3, 1))
1615 			sm_dprintf("getla: ioctl(MIOC_READKSYM) failed: %s\n",
1616 				   sm_errstring(errno));
1617 		return -1;
1618 	}
1619 	if (tTd(3, 5))
1620 	{
1621 		sm_dprintf("getla: avenrun = %d", avenrun[0]);
1622 		if (tTd(3, 15))
1623 			sm_dprintf(", %d, %d", avenrun[1], avenrun[2]);
1624 		sm_dprintf("\n");
1625 	}
1626 	if (tTd(3, 1))
1627 		sm_dprintf("getla: %d\n",
1628 			(int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1629 	return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1630 }
1631 
1632 #endif /* LA_TYPE == LA_READKSYM */
1633 
1634 #if LA_TYPE == LA_DGUX
1635 
1636 # include <sys/dg_sys_info.h>
1637 
1638 int
getla()1639 getla()
1640 {
1641 	struct dg_sys_info_load_info load_info;
1642 
1643 	dg_sys_info((long *)&load_info,
1644 		DG_SYS_INFO_LOAD_INFO_TYPE, DG_SYS_INFO_LOAD_VERSION_0);
1645 
1646 	if (tTd(3, 1))
1647 		sm_dprintf("getla: %d\n", (int) (load_info.one_minute + 0.5));
1648 
1649 	return ((int) (load_info.one_minute + 0.5));
1650 }
1651 
1652 #endif /* LA_TYPE == LA_DGUX */
1653 
1654 #if LA_TYPE == LA_HPUX
1655 
1656 /* forward declarations to keep gcc from complaining */
1657 struct pst_dynamic;
1658 struct pst_status;
1659 struct pst_static;
1660 struct pst_vminfo;
1661 struct pst_diskinfo;
1662 struct pst_processor;
1663 struct pst_lv;
1664 struct pst_swapinfo;
1665 
1666 # include <sys/param.h>
1667 # include <sys/pstat.h>
1668 
1669 int
getla()1670 getla()
1671 {
1672 	struct pst_dynamic pstd;
1673 
1674 	if (pstat_getdynamic(&pstd, sizeof(struct pst_dynamic),
1675 			     (size_t) 1, 0) == -1)
1676 		return 0;
1677 
1678 	if (tTd(3, 1))
1679 		sm_dprintf("getla: %d\n", (int) (pstd.psd_avg_1_min + 0.5));
1680 
1681 	return (int) (pstd.psd_avg_1_min + 0.5);
1682 }
1683 
1684 #endif /* LA_TYPE == LA_HPUX */
1685 
1686 #if LA_TYPE == LA_SUBR
1687 
1688 int
getla()1689 getla()
1690 {
1691 	double avenrun[3];
1692 
1693 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0)
1694 	{
1695 		if (tTd(3, 1))
1696 			sm_dprintf("getla: getloadavg failed: %s",
1697 				   sm_errstring(errno));
1698 		return -1;
1699 	}
1700 	if (tTd(3, 1))
1701 		sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
1702 	return ((int) (avenrun[0] + 0.5));
1703 }
1704 
1705 #endif /* LA_TYPE == LA_SUBR */
1706 
1707 #if LA_TYPE == LA_MACH
1708 
1709 /*
1710 **  This has been tested on NEXTSTEP release 2.1/3.X.
1711 */
1712 
1713 # if defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0
1714 #  include <mach/mach.h>
1715 # else /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */
1716 #  include <mach.h>
1717 # endif /* defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0 */
1718 
1719 int
getla()1720 getla()
1721 {
1722 	processor_set_t default_set;
1723 	kern_return_t error;
1724 	unsigned int info_count;
1725 	struct processor_set_basic_info info;
1726 	host_t host;
1727 
1728 	error = processor_set_default(host_self(), &default_set);
1729 	if (error != KERN_SUCCESS)
1730 	{
1731 		if (tTd(3, 1))
1732 			sm_dprintf("getla: processor_set_default failed: %s",
1733 				   sm_errstring(errno));
1734 		return -1;
1735 	}
1736 	info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
1737 	if (processor_set_info(default_set, PROCESSOR_SET_BASIC_INFO,
1738 			       &host, (processor_set_info_t)&info,
1739 			       &info_count) != KERN_SUCCESS)
1740 	{
1741 		if (tTd(3, 1))
1742 			sm_dprintf("getla: processor_set_info failed: %s",
1743 				   sm_errstring(errno));
1744 		return -1;
1745 	}
1746 	if (tTd(3, 1))
1747 		sm_dprintf("getla: %d\n",
1748 			(int) ((info.load_average + (LOAD_SCALE / 2)) /
1749 			       LOAD_SCALE));
1750 	return (int) (info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE;
1751 }
1752 
1753 #endif /* LA_TYPE == LA_MACH */
1754 
1755 #if LA_TYPE == LA_PROCSTR
1756 # if SM_CONF_BROKEN_STRTOD
1757 	ERROR: This OS has most likely a broken strtod() implemenentation.
1758 	ERROR: The function is required for getla().
1759 	ERROR: Check the compilation options _LA_PROCSTR and
_SM_CONF_BROKEN_STRTOD(without the leading _)1760 	ERROR: _SM_CONF_BROKEN_STRTOD (without the leading _).
1761 # endif /* SM_CONF_BROKEN_STRTOD */
1762 
1763 /*
1764 **  Read /proc/loadavg for the load average.  This is assumed to be
1765 **  in a format like "0.15 0.12 0.06".
1766 **
1767 **	Initially intended for Linux.  This has been in the kernel
1768 **	since at least 0.99.15.
1769 */
1770 
1771 # ifndef _PATH_LOADAVG
1772 #  define _PATH_LOADAVG	"/proc/loadavg"
1773 # endif /* ! _PATH_LOADAVG */
1774 
1775 int
1776 getla()
1777 {
1778 	double avenrun;
1779 	register int result;
1780 	SM_FILE_T *fp;
1781 
1782 	fp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_LOADAVG, SM_IO_RDONLY,
1783 			NULL);
1784 	if (fp == NULL)
1785 	{
1786 		if (tTd(3, 1))
1787 			sm_dprintf("getla: sm_io_open(%s): %s\n",
1788 				   _PATH_LOADAVG, sm_errstring(errno));
1789 		return -1;
1790 	}
1791 	result = sm_io_fscanf(fp, SM_TIME_DEFAULT, "%lf", &avenrun);
1792 	(void) sm_io_close(fp, SM_TIME_DEFAULT);
1793 	if (result != 1)
1794 	{
1795 		if (tTd(3, 1))
1796 			sm_dprintf("getla: sm_io_fscanf() = %d: %s\n",
1797 				   result, sm_errstring(errno));
1798 		return -1;
1799 	}
1800 
1801 	if (tTd(3, 1))
1802 		sm_dprintf("getla(): %.2f\n", avenrun);
1803 
1804 	return ((int) (avenrun + 0.5));
1805 }
1806 
1807 #endif /* LA_TYPE == LA_PROCSTR */
1808 
1809 #if LA_TYPE == LA_IRIX6
1810 
1811 # include <sys/sysmp.h>
1812 
1813 # ifdef _UNICOSMP
1814 #  define CAST_SYSMP(x)	(x)
1815 # else /* _UNICOSMP */
1816 #  define CAST_SYSMP(x)	((x) & 0x7fffffff)
1817 # endif /* _UNICOSMP */
1818 
1819 int
getla(void)1820 getla(void)
1821 {
1822 	int j;
1823 	static int kmem = -1;
1824 	int avenrun[3];
1825 
1826 	if (kmem < 0)
1827 	{
1828 		kmem = open(_PATH_KMEM, 0, 0);
1829 		if (kmem < 0)
1830 		{
1831 			if (tTd(3, 1))
1832 				sm_dprintf("getla: open(%s): %s\n", _PATH_KMEM,
1833 					   sm_errstring(errno));
1834 			return -1;
1835 		}
1836 		if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
1837 		    fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
1838 		{
1839 			if (tTd(3, 1))
1840 				sm_dprintf("getla: fcntl(/dev/kmem, FD_CLOEXEC): %s\n",
1841 					   sm_errstring(errno));
1842 			(void) close(kmem);
1843 			kmem = -1;
1844 			return -1;
1845 		}
1846 	}
1847 
1848 	if (lseek(kmem, CAST_SYSMP(sysmp(MP_KERNADDR, MPKA_AVENRUN)), SEEK_SET)
1849 		== -1 ||
1850 	    read(kmem, (char *) avenrun, sizeof(avenrun)) != sizeof(avenrun))
1851 	{
1852 		if (tTd(3, 1))
1853 			sm_dprintf("getla: lseek or read: %s\n",
1854 				   sm_errstring(errno));
1855 		return -1;
1856 	}
1857 	if (tTd(3, 5))
1858 	{
1859 		sm_dprintf("getla: avenrun = %ld", (long int) avenrun[0]);
1860 		if (tTd(3, 15))
1861 			sm_dprintf(", %ld, %ld",
1862 				(long int) avenrun[1], (long int) avenrun[2]);
1863 		sm_dprintf("\n");
1864 	}
1865 
1866 	if (tTd(3, 1))
1867 		sm_dprintf("getla: %d\n",
1868 			(int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1869 	return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1870 
1871 }
1872 #endif /* LA_TYPE == LA_IRIX6 */
1873 
1874 #if LA_TYPE == LA_KSTAT
1875 
1876 # include <kstat.h>
1877 
1878 int
getla()1879 getla()
1880 {
1881 	static kstat_ctl_t *kc = NULL;
1882 	static kstat_t *ksp = NULL;
1883 	kstat_named_t *ksn;
1884 	int la;
1885 
1886 	if (kc == NULL)		/* if not initialized before */
1887 		kc = kstat_open();
1888 	if (kc == NULL)
1889 	{
1890 		if (tTd(3, 1))
1891 			sm_dprintf("getla: kstat_open(): %s\n",
1892 				   sm_errstring(errno));
1893 		return -1;
1894 	}
1895 	if (ksp == NULL)
1896 		ksp = kstat_lookup(kc, "unix", 0, "system_misc");
1897 	if (ksp == NULL)
1898 	{
1899 		if (tTd(3, 1))
1900 			sm_dprintf("getla: kstat_lookup(): %s\n",
1901 				   sm_errstring(errno));
1902 		return -1;
1903 	}
1904 	if (kstat_read(kc, ksp, NULL) < 0)
1905 	{
1906 		if (tTd(3, 1))
1907 			sm_dprintf("getla: kstat_read(): %s\n",
1908 				   sm_errstring(errno));
1909 		return -1;
1910 	}
1911 	ksn = (kstat_named_t *) kstat_data_lookup(ksp, "avenrun_1min");
1912 	la = ((double) ksn->value.ul + FSCALE/2) / FSCALE;
1913 	/* kstat_close(kc); /o do not close for fast access */
1914 	return la;
1915 }
1916 
1917 #endif /* LA_TYPE == LA_KSTAT */
1918 
1919 #if LA_TYPE == LA_DEVSHORT
1920 
1921 /*
1922 **  Read /dev/table/avenrun for the load average.  This should contain
1923 **  three shorts for the 1, 5, and 15 minute loads.  We only read the
1924 **  first, since that's all we care about.
1925 **
1926 **	Intended for SCO OpenServer 5.
1927 */
1928 
1929 # ifndef _PATH_AVENRUN
1930 #  define _PATH_AVENRUN	"/dev/table/avenrun"
1931 # endif /* ! _PATH_AVENRUN */
1932 
1933 int
getla()1934 getla()
1935 {
1936 	static int afd = -1;
1937 	short avenrun;
1938 	int loadav;
1939 	int r;
1940 
1941 	errno = EBADF;
1942 
1943 	if (afd == -1 || lseek(afd, 0L, SEEK_SET) == -1)
1944 	{
1945 		if (errno != EBADF)
1946 			return -1;
1947 		afd = open(_PATH_AVENRUN, O_RDONLY|O_SYNC);
1948 		if (afd < 0)
1949 		{
1950 			sm_syslog(LOG_ERR, NOQID,
1951 				"can't open %s: %s",
1952 				_PATH_AVENRUN, sm_errstring(errno));
1953 			return -1;
1954 		}
1955 	}
1956 
1957 	r = read(afd, &avenrun, sizeof(avenrun));
1958 	if (r != sizeof(avenrun))
1959 	{
1960 		sm_syslog(LOG_ERR, NOQID,
1961 			"can't read %s: %s", _PATH_AVENRUN,
1962 			r == -1 ? sm_errstring(errno) : "short read");
1963 		return -1;
1964 	}
1965 
1966 	if (tTd(3, 5))
1967 		sm_dprintf("getla: avenrun = %d\n", avenrun);
1968 	loadav = (int) (avenrun + FSCALE/2) >> FSHIFT;
1969 	if (tTd(3, 1))
1970 		sm_dprintf("getla: %d\n", loadav);
1971 	return loadav;
1972 }
1973 
1974 #endif /* LA_TYPE == LA_DEVSHORT */
1975 
1976 #if LA_TYPE == LA_ALPHAOSF
1977 struct rtentry;
1978 struct mbuf;
1979 # include <sys/table.h>
1980 
1981 int
getla()1982 getla()
1983 {
1984 	int ave = 0;
1985 	struct tbl_loadavg tab;
1986 
1987 	if (table(TBL_LOADAVG, 0, &tab, 1, sizeof(tab)) == -1)
1988 	{
1989 		if (tTd(3, 1))
1990 			sm_dprintf("getla: table %s\n", sm_errstring(errno));
1991 		return -1;
1992 	}
1993 
1994 	if (tTd(3, 1))
1995 		sm_dprintf("getla: scale = %d\n", tab.tl_lscale);
1996 
1997 	if (tab.tl_lscale)
1998 		ave = ((tab.tl_avenrun.l[2] + (tab.tl_lscale/2)) /
1999 		       tab.tl_lscale);
2000 	else
2001 		ave = (int) (tab.tl_avenrun.d[2] + 0.5);
2002 
2003 	if (tTd(3, 1))
2004 		sm_dprintf("getla: %d\n", ave);
2005 
2006 	return ave;
2007 }
2008 
2009 #endif /* LA_TYPE == LA_ALPHAOSF */
2010 
2011 #if LA_TYPE == LA_PSET
2012 
2013 int
getla()2014 getla()
2015 {
2016 	double avenrun[3];
2017 
2018 	if (pset_getloadavg(PS_MYID, avenrun,
2019 			    sizeof(avenrun) / sizeof(avenrun[0])) < 0)
2020 	{
2021 		if (tTd(3, 1))
2022 			sm_dprintf("getla: pset_getloadavg failed: %s",
2023 				   sm_errstring(errno));
2024 		return -1;
2025 	}
2026 	if (tTd(3, 1))
2027 		sm_dprintf("getla: %d\n", (int) (avenrun[0] +0.5));
2028 	return ((int) (avenrun[0] + 0.5));
2029 }
2030 
2031 #endif /* LA_TYPE == LA_PSET */
2032 
2033 #if LA_TYPE == LA_ZERO
2034 
2035 int
getla()2036 getla()
2037 {
2038 	if (tTd(3, 1))
2039 		sm_dprintf("getla: ZERO\n");
2040 	return 0;
2041 }
2042 
2043 #endif /* LA_TYPE == LA_ZERO */
2044 
2045 /*
2046  * Copyright 1989 Massachusetts Institute of Technology
2047  *
2048  * Permission to use, copy, modify, distribute, and sell this software and its
2049  * documentation for any purpose is hereby granted without fee, provided that
2050  * the above copyright notice appear in all copies and that both that
2051  * copyright notice and this permission notice appear in supporting
2052  * documentation, and that the name of M.I.T. not be used in advertising or
2053  * publicity pertaining to distribution of the software without specific,
2054  * written prior permission.  M.I.T. makes no representations about the
2055  * suitability of this software for any purpose.  It is provided "as is"
2056  * without express or implied warranty.
2057  *
2058  * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
2059  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T.
2060  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2061  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
2062  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2063  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2064  *
2065  * Authors:  Many and varied...
2066  */
2067 
2068 /* Non Apollo stuff removed by Don Lewis 11/15/93 */
2069 #ifndef lint
2070 SM_UNUSED(static char  rcsid[]) = "@(#)$OrigId: getloadavg.c,v 1.16 1991/06/21 12:51:15 paul Exp $";
2071 #endif /* ! lint */
2072 
2073 #ifdef apollo
2074 # undef volatile
2075 # include <apollo/base.h>
2076 
2077 /* ARGSUSED */
getloadavg(call_data)2078 int getloadavg( call_data )
2079 	caddr_t call_data;	/* pointer to (double) return value */
2080 {
2081 	double *avenrun = (double *) call_data;
2082 	int i;
2083 	status_$t      st;
2084 	long loadav[3];
2085 
2086 	proc1_$get_loadav(loadav, &st);
2087 	*avenrun = loadav[0] / (double) (1 << 16);
2088 	return 0;
2089 }
2090 #endif /* apollo */
2091 /*
2092 **  SM_GETLA -- get the current load average
2093 **
2094 **	Parameters:
2095 **		none
2096 **
2097 **	Returns:
2098 **		none
2099 **
2100 **	Side Effects:
2101 **		Set CurrentLA to the current load average.
2102 **		Set {load_avg} in GlobalMacros to the current load average.
2103 */
2104 
2105 void
sm_getla()2106 sm_getla()
2107 {
2108 	char labuf[8];
2109 
2110 	CurrentLA = getla();
2111 	(void) sm_snprintf(labuf, sizeof(labuf), "%d", CurrentLA);
2112 	macdefine(&GlobalMacros, A_TEMP, macid("{load_avg}"), labuf);
2113 }
2114 /*
2115 **  SHOULDQUEUE -- should this message be queued or sent?
2116 **
2117 **	Compares the message cost to the load average to decide.
2118 **
2119 **	Note: Do NOT change this API! It is documented in op.me
2120 **		and theoretically the user can change this function...
2121 **
2122 **	Parameters:
2123 **		pri -- the priority of the message in question.
2124 **		ct -- the message creation time (unused, but see above).
2125 **
2126 **	Returns:
2127 **		true -- if this message should be queued up for the
2128 **			time being.
2129 **		false -- if the load is low enough to send this message.
2130 **
2131 **	Side Effects:
2132 **		none.
2133 */
2134 
2135 /* ARGSUSED1 */
2136 bool
shouldqueue(pri,ct)2137 shouldqueue(pri, ct)
2138 	long pri;
2139 	time_t ct;
2140 {
2141 	bool rval;
2142 #if _FFR_MEMSTAT
2143 	long memfree;
2144 #endif /* _FFR_MEMSTAT */
2145 
2146 	if (tTd(3, 30))
2147 		sm_dprintf("shouldqueue: CurrentLA=%d, pri=%ld: ",
2148 			CurrentLA, pri);
2149 
2150 #if _FFR_MEMSTAT
2151 	if (QueueLowMem > 0 &&
2152 	    sm_memstat_get(MemoryResource, &memfree) >= 0 &&
2153 	    memfree < QueueLowMem)
2154 	{
2155 		if (tTd(3, 30))
2156 			sm_dprintf("true (memfree=%ld < QueueLowMem=%ld)\n",
2157 				memfree, QueueLowMem);
2158 		return true;
2159 	}
2160 #endif /* _FFR_MEMSTAT */
2161 	if (CurrentLA < QueueLA)
2162 	{
2163 		if (tTd(3, 30))
2164 			sm_dprintf("false (CurrentLA < QueueLA)\n");
2165 		return false;
2166 	}
2167 	rval = pri > (QueueFactor / (CurrentLA - QueueLA + 1));
2168 	if (tTd(3, 30))
2169 		sm_dprintf("%s (by calculation)\n", rval ? "true" : "false");
2170 	return rval;
2171 }
2172 
2173 /*
2174 **  REFUSECONNECTIONS -- decide if connections should be refused
2175 **
2176 **	Parameters:
2177 **		e -- the current envelope.
2178 **		dn -- number of daemon.
2179 **		active -- was this daemon actually active?
2180 **
2181 **	Returns:
2182 **		true if incoming SMTP connections should be refused
2183 **			(for now).
2184 **		false if we should accept new work.
2185 **
2186 **	Side Effects:
2187 **		Sets process title when it is rejecting connections.
2188 */
2189 
2190 bool
refuseconnections(e,dn,active)2191 refuseconnections(e, dn, active)
2192 	ENVELOPE *e;
2193 	int dn;
2194 	bool active;
2195 {
2196 	static time_t lastconn[MAXDAEMONS];
2197 	static int conncnt[MAXDAEMONS];
2198 	static time_t firstrejtime[MAXDAEMONS];
2199 	static time_t nextlogtime[MAXDAEMONS];
2200 	int limit;
2201 #if _FFR_MEMSTAT
2202 	long memfree;
2203 #endif /* _FFR_MEMSTAT */
2204 
2205 #if XLA
2206 	if (!xla_smtp_ok())
2207 		return true;
2208 #endif /* XLA */
2209 
2210 	SM_ASSERT(dn >= 0);
2211 	SM_ASSERT(dn < MAXDAEMONS);
2212 	if (ConnRateThrottle > 0)
2213 	{
2214 		time_t now;
2215 
2216 		now = curtime();
2217 		if (active)
2218 		{
2219 			if (now != lastconn[dn])
2220 			{
2221 				lastconn[dn] = now;
2222 				conncnt[dn] = 1;
2223 			}
2224 			else if (conncnt[dn]++ > ConnRateThrottle)
2225 			{
2226 #define D_MSG_CRT "deferring connections on daemon %s: %d per second"
2227 				/* sleep to flatten out connection load */
2228 				sm_setproctitle(true, e, D_MSG_CRT,
2229 						Daemons[dn].d_name,
2230 						ConnRateThrottle);
2231 				if (LogLevel > 8)
2232 					sm_syslog(LOG_INFO, NOQID, D_MSG_CRT,
2233 						  Daemons[dn].d_name,
2234 						  ConnRateThrottle);
2235 				(void) sleep(1);
2236 			}
2237 		}
2238 		else if (now != lastconn[dn])
2239 			conncnt[dn] = 0;
2240 	}
2241 
2242 
2243 #if _FFR_MEMSTAT
2244 	if (RefuseLowMem > 0 &&
2245 	    sm_memstat_get(MemoryResource, &memfree) >= 0 &&
2246 	    memfree < RefuseLowMem)
2247 	{
2248 # define R_MSG_LM "rejecting connections on daemon %s: free memory: %ld"
2249 		sm_setproctitle(true, e, R_MSG_LM, Daemons[dn].d_name, memfree);
2250 		if (LogLevel > 8)
2251 			sm_syslog(LOG_NOTICE, NOQID, R_MSG_LM,
2252 				Daemons[dn].d_name, memfree);
2253 		return true;
2254 	}
2255 #endif /* _FFR_MEMSTAT */
2256 	sm_getla();
2257 	limit = (Daemons[dn].d_refuseLA != DPO_NOTSET) ?
2258 		Daemons[dn].d_refuseLA : RefuseLA;
2259 	if (limit > 0 && CurrentLA >= limit)
2260 	{
2261 		time_t now;
2262 
2263 # define R_MSG_LA "rejecting connections on daemon %s: load average: %d"
2264 # define R2_MSG_LA "have been rejecting connections on daemon %s for %s"
2265 		sm_setproctitle(true, e, R_MSG_LA, Daemons[dn].d_name,
2266 				CurrentLA);
2267 		if (LogLevel > 8)
2268 			sm_syslog(LOG_NOTICE, NOQID, R_MSG_LA,
2269 				Daemons[dn].d_name, CurrentLA);
2270 		now = curtime();
2271 		if (firstrejtime[dn] == 0)
2272 		{
2273 			firstrejtime[dn] = now;
2274 			nextlogtime[dn] = now + RejectLogInterval;
2275 		}
2276 		else if (nextlogtime[dn] < now)
2277 		{
2278 			sm_syslog(LOG_ERR, NOQID, R2_MSG_LA, Daemons[dn].d_name,
2279 				  pintvl(now - firstrejtime[dn], true));
2280 			nextlogtime[dn] = now + RejectLogInterval;
2281 		}
2282 		return true;
2283 	}
2284 	else
2285 		firstrejtime[dn] = 0;
2286 
2287 	limit = (Daemons[dn].d_delayLA != DPO_NOTSET) ?
2288 		Daemons[dn].d_delayLA : DelayLA;
2289 	if (limit > 0 && CurrentLA >= limit)
2290 	{
2291 		time_t now;
2292 		static time_t log_delay = (time_t) 0;
2293 
2294 # define MIN_DELAY_LOG	90	/* wait before logging this again */
2295 # define D_MSG_LA "delaying connections on daemon %s: load average=%d >= %d"
2296 		/* sleep to flatten out connection load */
2297 		sm_setproctitle(true, e, D_MSG_LA, Daemons[dn].d_name,
2298 			        CurrentLA, limit);
2299 		if (LogLevel > 8 && (now = curtime()) > log_delay)
2300 		{
2301 			sm_syslog(LOG_INFO, NOQID, D_MSG_LA,
2302 				  Daemons[dn].d_name, CurrentLA, limit);
2303 			log_delay = now + MIN_DELAY_LOG;
2304 		}
2305 		(void) sleep(1);
2306 	}
2307 
2308 	limit = (Daemons[dn].d_maxchildren != DPO_NOTSET) ?
2309 		Daemons[dn].d_maxchildren : MaxChildren;
2310 	if (limit > 0 && CurChildren >= limit)
2311 	{
2312 		proc_list_probe();
2313 		if (CurChildren >= limit)
2314 		{
2315 #define R_MSG_CHILD "rejecting connections on daemon %s: %d children, max %d"
2316 			sm_setproctitle(true, e, R_MSG_CHILD,
2317 					Daemons[dn].d_name, CurChildren,
2318 					limit);
2319 			if (LogLevel > 8)
2320 				sm_syslog(LOG_INFO, NOQID, R_MSG_CHILD,
2321 					Daemons[dn].d_name, CurChildren,
2322 					limit);
2323 			return true;
2324 		}
2325 	}
2326 	return false;
2327 }
2328 
2329 /*
2330 **  SETPROCTITLE -- set process title for ps
2331 **
2332 **	Parameters:
2333 **		fmt -- a printf style format string.
2334 **		a, b, c -- possible parameters to fmt.
2335 **
2336 **	Returns:
2337 **		none.
2338 **
2339 **	Side Effects:
2340 **		Clobbers argv of our main procedure so ps(1) will
2341 **		display the title.
2342 */
2343 
2344 #define SPT_NONE	0	/* don't use it at all */
2345 #define SPT_REUSEARGV	1	/* cover argv with title information */
2346 #define SPT_BUILTIN	2	/* use libc builtin */
2347 #define SPT_PSTAT	3	/* use pstat(PSTAT_SETCMD, ...) */
2348 #define SPT_PSSTRINGS	4	/* use PS_STRINGS->... */
2349 #define SPT_SYSMIPS	5	/* use sysmips() supported by NEWS-OS 6 */
2350 #define SPT_SCO		6	/* write kernel u. area */
2351 #define SPT_CHANGEARGV	7	/* write our own strings into argv[] */
2352 
2353 #ifndef SPT_TYPE
2354 # define SPT_TYPE	SPT_REUSEARGV
2355 #endif /* ! SPT_TYPE */
2356 
2357 
2358 #if SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN
2359 
2360 # if SPT_TYPE == SPT_PSTAT
2361 #  include <sys/pstat.h>
2362 # endif /* SPT_TYPE == SPT_PSTAT */
2363 # if SPT_TYPE == SPT_PSSTRINGS
2364 #  include <machine/vmparam.h>
2365 #  include <sys/exec.h>
2366 #  ifndef PS_STRINGS	/* hmmmm....  apparently not available after all */
2367 #   undef SPT_TYPE
2368 #   define SPT_TYPE	SPT_REUSEARGV
2369 #  else /* ! PS_STRINGS */
2370 #   ifndef NKPDE			/* FreeBSD 2.0 */
2371 #    define NKPDE 63
2372 typedef unsigned int	*pt_entry_t;
2373 #   endif /* ! NKPDE */
2374 #  endif /* ! PS_STRINGS */
2375 # endif /* SPT_TYPE == SPT_PSSTRINGS */
2376 
2377 # if SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV
2378 #  define SETPROC_STATIC	static
2379 # else /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */
2380 #  define SETPROC_STATIC
2381 # endif /* SPT_TYPE == SPT_PSSTRINGS || SPT_TYPE == SPT_CHANGEARGV */
2382 
2383 # if SPT_TYPE == SPT_SYSMIPS
2384 #  include <sys/sysmips.h>
2385 #  include <sys/sysnews.h>
2386 # endif /* SPT_TYPE == SPT_SYSMIPS */
2387 
2388 # if SPT_TYPE == SPT_SCO
2389 #  include <sys/immu.h>
2390 #  include <sys/dir.h>
2391 #  include <sys/user.h>
2392 #  include <sys/fs/s5param.h>
2393 #  if PSARGSZ > MAXLINE
2394 #   define SPT_BUFSIZE	PSARGSZ
2395 #  endif /* PSARGSZ > MAXLINE */
2396 # endif /* SPT_TYPE == SPT_SCO */
2397 
2398 # ifndef SPT_PADCHAR
2399 #  define SPT_PADCHAR	' '
2400 # endif /* ! SPT_PADCHAR */
2401 
2402 #endif /* SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN */
2403 
2404 #ifndef SPT_BUFSIZE
2405 # define SPT_BUFSIZE	MAXLINE
2406 #endif /* ! SPT_BUFSIZE */
2407 
2408 #if _FFR_SPT_ALIGN
2409 
2410 /*
2411 **  It looks like the Compaq Tru64 5.1A now aligns argv and envp to
2412 **  64 bit alignment, so unless each piece of argv and envp is a multiple
2413 **  of 8 bytes (including terminating NULL), initsetproctitle() won't use
2414 **  any of the space beyond argv[0].  Be sure to set SPT_ALIGN_SIZE if
2415 **  you use this FFR.
2416 */
2417 
2418 # ifdef SPT_ALIGN_SIZE
2419 #  define SPT_ALIGN(x, align)	(((((x) + SPT_ALIGN_SIZE) >> (align)) << (align)) - 1)
2420 # else /* SPT_ALIGN_SIZE */
2421 #  define SPT_ALIGN(x, align)	(x)
2422 # endif /* SPT_ALIGN_SIZE */
2423 #else /* _FFR_SPT_ALIGN */
2424 # define SPT_ALIGN(x, align)	(x)
2425 #endif /* _FFR_SPT_ALIGN */
2426 
2427 /*
2428 **  Pointers for setproctitle.
2429 **	This allows "ps" listings to give more useful information.
2430 */
2431 
2432 static char	**Argv = NULL;		/* pointer to argument vector */
2433 static char	*LastArgv = NULL;	/* end of argv */
2434 #if SPT_TYPE != SPT_BUILTIN
2435 static void	setproctitle __P((const char *, ...));
2436 #endif /* SPT_TYPE != SPT_BUILTIN */
2437 
2438 void
initsetproctitle(argc,argv,envp)2439 initsetproctitle(argc, argv, envp)
2440 	int argc;
2441 	char **argv;
2442 	char **envp;
2443 {
2444 	register int i;
2445 	int align;
2446 	extern char **environ;
2447 
2448 	/*
2449 	**  Move the environment so setproctitle can use the space at
2450 	**  the top of memory.
2451 	*/
2452 
2453 	if (envp != NULL)
2454 	{
2455 		for (i = 0; envp[i] != NULL; i++)
2456 			continue;
2457 		environ = (char **) xalloc(sizeof(char *) * (i + 1));
2458 		for (i = 0; envp[i] != NULL; i++)
2459 			environ[i] = newstr(envp[i]);
2460 		environ[i] = NULL;
2461 	}
2462 
2463 	/*
2464 	**  Save start and extent of argv for setproctitle.
2465 	*/
2466 
2467 	Argv = argv;
2468 
2469 	/*
2470 	**  Determine how much space we can use for setproctitle.
2471 	**  Use all contiguous argv and envp pointers starting at argv[0]
2472 	*/
2473 
2474 	align = -1;
2475 # if _FFR_SPT_ALIGN
2476 #  ifdef SPT_ALIGN_SIZE
2477 	for (i = SPT_ALIGN_SIZE; i > 0; i >>= 1)
2478 		align++;
2479 #  endif /* SPT_ALIGN_SIZE */
2480 # endif /* _FFR_SPT_ALIGN */
2481 
2482 	for (i = 0; i < argc; i++)
2483 	{
2484 		if (i == 0 || LastArgv + 1 == argv[i])
2485 			LastArgv = argv[i] + SPT_ALIGN(strlen(argv[i]), align);
2486 	}
2487 	for (i = 0; LastArgv != NULL && envp != NULL && envp[i] != NULL; i++)
2488 	{
2489 		if (LastArgv + 1 == envp[i])
2490 			LastArgv = envp[i] + SPT_ALIGN(strlen(envp[i]), align);
2491 	}
2492 }
2493 
2494 #if SPT_TYPE != SPT_BUILTIN
2495 
2496 /*VARARGS1*/
2497 static void
2498 # ifdef __STDC__
setproctitle(const char * fmt,...)2499 setproctitle(const char *fmt, ...)
2500 # else /* __STDC__ */
2501 setproctitle(fmt, va_alist)
2502 	const char *fmt;
2503 	va_dcl
2504 # endif /* __STDC__ */
2505 {
2506 # if SPT_TYPE != SPT_NONE
2507 	register int i;
2508 	register char *p;
2509 	SETPROC_STATIC char buf[SPT_BUFSIZE];
2510 	SM_VA_LOCAL_DECL
2511 #  if SPT_TYPE == SPT_PSTAT
2512 	union pstun pst;
2513 #  endif /* SPT_TYPE == SPT_PSTAT */
2514 #  if SPT_TYPE == SPT_SCO
2515 	int j;
2516 	off_t seek_off;
2517 	static int kmem = -1;
2518 	static pid_t kmempid = -1;
2519 	struct user u;
2520 #  endif /* SPT_TYPE == SPT_SCO */
2521 
2522 	p = buf;
2523 
2524 	/* print sendmail: heading for grep */
2525 	(void) sm_strlcpy(p, "sendmail: ", SPACELEFT(buf, p));
2526 	p += strlen(p);
2527 
2528 	/* print the argument string */
2529 	SM_VA_START(ap, fmt);
2530 	(void) sm_vsnprintf(p, SPACELEFT(buf, p), fmt, ap);
2531 	SM_VA_END(ap);
2532 
2533 	i = (int) strlen(buf);
2534 	if (i < 0)
2535 		return;
2536 
2537 #  if SPT_TYPE == SPT_PSTAT
2538 	pst.pst_command = buf;
2539 	pstat(PSTAT_SETCMD, pst, i, 0, 0);
2540 #  endif /* SPT_TYPE == SPT_PSTAT */
2541 #  if SPT_TYPE == SPT_PSSTRINGS
2542 	PS_STRINGS->ps_nargvstr = 1;
2543 	PS_STRINGS->ps_argvstr = buf;
2544 #  endif /* SPT_TYPE == SPT_PSSTRINGS */
2545 #  if SPT_TYPE == SPT_SYSMIPS
2546 	sysmips(SONY_SYSNEWS, NEWS_SETPSARGS, buf);
2547 #  endif /* SPT_TYPE == SPT_SYSMIPS */
2548 #  if SPT_TYPE == SPT_SCO
2549 	if (kmem < 0 || kmempid != CurrentPid)
2550 	{
2551 		if (kmem >= 0)
2552 			(void) close(kmem);
2553 		kmem = open(_PATH_KMEM, O_RDWR, 0);
2554 		if (kmem < 0)
2555 			return;
2556 		if ((j = fcntl(kmem, F_GETFD, 0)) < 0 ||
2557 		    fcntl(kmem, F_SETFD, j | FD_CLOEXEC) < 0)
2558 		{
2559 			(void) close(kmem);
2560 			kmem = -1;
2561 			return;
2562 		}
2563 		kmempid = CurrentPid;
2564 	}
2565 	buf[PSARGSZ - 1] = '\0';
2566 	seek_off = UVUBLK + (off_t) u.u_psargs - (off_t) &u;
2567 	if (lseek(kmem, (off_t) seek_off, SEEK_SET) == seek_off)
2568 		(void) write(kmem, buf, PSARGSZ);
2569 #  endif /* SPT_TYPE == SPT_SCO */
2570 #  if SPT_TYPE == SPT_REUSEARGV
2571 	if (LastArgv == NULL)
2572 		return;
2573 
2574 	if (i > LastArgv - Argv[0] - 2)
2575 	{
2576 		i = LastArgv - Argv[0] - 2;
2577 		buf[i] = '\0';
2578 	}
2579 	(void) sm_strlcpy(Argv[0], buf, i + 1);
2580 	p = &Argv[0][i];
2581 	while (p < LastArgv)
2582 		*p++ = SPT_PADCHAR;
2583 	Argv[1] = NULL;
2584 #  endif /* SPT_TYPE == SPT_REUSEARGV */
2585 #  if SPT_TYPE == SPT_CHANGEARGV
2586 	Argv[0] = buf;
2587 	Argv[1] = 0;
2588 #  endif /* SPT_TYPE == SPT_CHANGEARGV */
2589 # endif /* SPT_TYPE != SPT_NONE */
2590 }
2591 
2592 #endif /* SPT_TYPE != SPT_BUILTIN */
2593 /*
2594 **  SM_SETPROCTITLE -- set process task and set process title for ps
2595 **
2596 **	Possibly set process status and call setproctitle() to
2597 **	change the ps display.
2598 **
2599 **	Parameters:
2600 **		status -- whether or not to store as process status
2601 **		e -- the current envelope.
2602 **		fmt -- a printf style format string.
2603 **		a, b, c -- possible parameters to fmt.
2604 **
2605 **	Returns:
2606 **		none.
2607 */
2608 
2609 /*VARARGS2*/
2610 void
2611 #ifdef __STDC__
sm_setproctitle(bool status,ENVELOPE * e,const char * fmt,...)2612 sm_setproctitle(bool status, ENVELOPE *e, const char *fmt, ...)
2613 #else /* __STDC__ */
2614 sm_setproctitle(status, e, fmt, va_alist)
2615 	bool status;
2616 	ENVELOPE *e;
2617 	const char *fmt;
2618 	va_dcl
2619 #endif /* __STDC__ */
2620 {
2621 	char buf[SPT_BUFSIZE];
2622 	SM_VA_LOCAL_DECL
2623 
2624 	/* print the argument string */
2625 	SM_VA_START(ap, fmt);
2626 	(void) sm_vsnprintf(buf, sizeof(buf), fmt, ap);
2627 	SM_VA_END(ap);
2628 
2629 	if (status)
2630 		proc_list_set(CurrentPid, buf);
2631 
2632 	if (ProcTitlePrefix != NULL)
2633 	{
2634 		char prefix[SPT_BUFSIZE];
2635 
2636 		expand(ProcTitlePrefix, prefix, sizeof(prefix), e);
2637 		setproctitle("%s: %s", prefix, buf);
2638 	}
2639 	else
2640 		setproctitle("%s", buf);
2641 }
2642 /*
2643 **  WAITFOR -- wait for a particular process id.
2644 **
2645 **	Parameters:
2646 **		pid -- process id to wait for.
2647 **
2648 **	Returns:
2649 **		status of pid.
2650 **		-1 if pid never shows up.
2651 **
2652 **	Side Effects:
2653 **		none.
2654 */
2655 
2656 int
waitfor(pid)2657 waitfor(pid)
2658 	pid_t pid;
2659 {
2660 	int st;
2661 	pid_t i;
2662 
2663 	do
2664 	{
2665 		errno = 0;
2666 		i = sm_wait(&st);
2667 		if (i > 0)
2668 			proc_list_drop(i, st, NULL);
2669 	} while ((i >= 0 || errno == EINTR) && i != pid);
2670 	if (i < 0)
2671 		return -1;
2672 	return st;
2673 }
2674 /*
2675 **  SM_WAIT -- wait
2676 **
2677 **	Parameters:
2678 **		status -- pointer to status (return value)
2679 **
2680 **	Returns:
2681 **		pid
2682 */
2683 
2684 pid_t
sm_wait(status)2685 sm_wait(status)
2686 	int *status;
2687 {
2688 # ifdef WAITUNION
2689 	union wait st;
2690 # else /* WAITUNION */
2691 	auto int st;
2692 # endif /* WAITUNION */
2693 	pid_t i;
2694 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2695 	int savesig;
2696 # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */
2697 
2698 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2699 	savesig = sm_releasesignal(SIGCHLD);
2700 # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */
2701 	i = wait(&st);
2702 # if defined(ISC_UNIX) || defined(_SCO_unix_)
2703 	if (savesig > 0)
2704 		sm_blocksignal(SIGCHLD);
2705 # endif /* defined(ISC_UNIX) || defined(_SCO_unix_) */
2706 # ifdef WAITUNION
2707 	*status = st.w_status;
2708 # else /* WAITUNION */
2709 	*status = st;
2710 # endif /* WAITUNION */
2711 	return i;
2712 }
2713 /*
2714 **  REAPCHILD -- pick up the body of my child, lest it become a zombie
2715 **
2716 **	Parameters:
2717 **		sig -- the signal that got us here (unused).
2718 **
2719 **	Returns:
2720 **		none.
2721 **
2722 **	Side Effects:
2723 **		Picks up extant zombies.
2724 **		Control socket exits may restart/shutdown daemon.
2725 **
2726 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2727 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2728 **		DOING.
2729 */
2730 
2731 /* ARGSUSED0 */
2732 SIGFUNC_DECL
reapchild(sig)2733 reapchild(sig)
2734 	int sig;
2735 {
2736 	int save_errno = errno;
2737 	int st;
2738 	pid_t pid;
2739 # if HASWAITPID
2740 	auto int status;
2741 	int count;
2742 
2743 	count = 0;
2744 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2745 	{
2746 		st = status;
2747 		if (count++ > 1000)
2748 			break;
2749 # else /* HASWAITPID */
2750 #  ifdef WNOHANG
2751 	union wait status;
2752 
2753 	while ((pid = wait3(&status, WNOHANG, (struct rusage *) NULL)) > 0)
2754 	{
2755 		st = status.w_status;
2756 #  else /* WNOHANG */
2757 	auto int status;
2758 
2759 	/*
2760 	**  Catch one zombie -- we will be re-invoked (we hope) if there
2761 	**  are more.  Unreliable signals probably break this, but this
2762 	**  is the "old system" situation -- waitpid or wait3 are to be
2763 	**  strongly preferred.
2764 	*/
2765 
2766 	if ((pid = wait(&status)) > 0)
2767 	{
2768 		st = status;
2769 #  endif /* WNOHANG */
2770 # endif /* HASWAITPID */
2771 		/* Drop PID and check if it was a control socket child */
2772 		proc_list_drop(pid, st, NULL);
2773 	}
2774 	FIX_SYSV_SIGNAL(sig, reapchild);
2775 	errno = save_errno;
2776 	return SIGFUNC_RETURN;
2777 }
2778 /*
2779 **  GETDTABLESIZE -- return number of file descriptors
2780 **
2781 **	Only on non-BSD systems
2782 **
2783 **	Parameters:
2784 **		none
2785 **
2786 **	Returns:
2787 **		size of file descriptor table
2788 **
2789 **	Side Effects:
2790 **		none
2791 */
2792 
2793 #ifdef SOLARIS
2794 # include <sys/resource.h>
2795 #endif /* SOLARIS */
2796 
2797 int
getdtsize()2798 getdtsize()
2799 {
2800 # ifdef RLIMIT_NOFILE
2801 	struct rlimit rl;
2802 
2803 	if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
2804 		return rl.rlim_cur;
2805 # endif /* RLIMIT_NOFILE */
2806 
2807 # if HASGETDTABLESIZE
2808 	return getdtablesize();
2809 # else /* HASGETDTABLESIZE */
2810 #  ifdef _SC_OPEN_MAX
2811 	return sysconf(_SC_OPEN_MAX);
2812 #  else /* _SC_OPEN_MAX */
2813 	return NOFILE;
2814 #  endif /* _SC_OPEN_MAX */
2815 # endif /* HASGETDTABLESIZE */
2816 }
2817 /*
2818 **  UNAME -- get the UUCP name of this system.
2819 */
2820 
2821 #if !HASUNAME
2822 
2823 int
uname(name)2824 uname(name)
2825 	struct utsname *name;
2826 {
2827 	SM_FILE_T *file;
2828 	char *n;
2829 
2830 	name->nodename[0] = '\0';
2831 
2832 	/* try /etc/whoami -- one line with the node name */
2833 	if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, "/etc/whoami",
2834 			       SM_IO_RDONLY, NULL)) != NULL)
2835 	{
2836 		(void) sm_io_fgets(file, SM_TIME_DEFAULT, name->nodename,
2837 				   NODE_LENGTH + 1);
2838 		(void) sm_io_close(file, SM_TIME_DEFAULT);
2839 		n = strchr(name->nodename, '\n');
2840 		if (n != NULL)
2841 			*n = '\0';
2842 		if (name->nodename[0] != '\0')
2843 			return 0;
2844 	}
2845 
2846 	/* try /usr/include/whoami.h -- has a #define somewhere */
2847 	if ((file = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
2848 			       "/usr/include/whoami.h", SM_IO_RDONLY, NULL))
2849 	    != NULL)
2850 	{
2851 		char buf[MAXLINE];
2852 
2853 		while (sm_io_fgets(file, SM_TIME_DEFAULT,
2854 				   buf, sizeof(buf)) != NULL)
2855 		{
2856 			if (sm_io_sscanf(buf, "#define sysname \"%*[^\"]\"",
2857 					NODE_LENGTH, name->nodename) > 0)
2858 				break;
2859 		}
2860 		(void) sm_io_close(file, SM_TIME_DEFAULT);
2861 		if (name->nodename[0] != '\0')
2862 			return 0;
2863 	}
2864 
2865 	return -1;
2866 }
2867 #endif /* !HASUNAME */
2868 /*
2869 **  INITGROUPS -- initialize groups
2870 **
2871 **	Stub implementation for System V style systems
2872 */
2873 
2874 #if !HASINITGROUPS
2875 
initgroups(name,basegid)2876 initgroups(name, basegid)
2877 	char *name;
2878 	int basegid;
2879 {
2880 	return 0;
2881 }
2882 
2883 #endif /* !HASINITGROUPS */
2884 /*
2885 **  SETGROUPS -- set group list
2886 **
2887 **	Stub implementation for systems that don't have group lists
2888 */
2889 
2890 #ifndef NGROUPS_MAX
2891 
2892 int
setgroups(ngroups,grouplist)2893 setgroups(ngroups, grouplist)
2894 	int ngroups;
2895 	GIDSET_T grouplist[];
2896 {
2897 	return 0;
2898 }
2899 
2900 #endif /* ! NGROUPS_MAX */
2901 /*
2902 **  SETSID -- set session id (for non-POSIX systems)
2903 */
2904 
2905 #if !HASSETSID
2906 
2907 pid_t
setsid(void)2908 setsid __P ((void))
2909 {
2910 #  ifdef TIOCNOTTY
2911 	int fd;
2912 
2913 	fd = open("/dev/tty", O_RDWR, 0);
2914 	if (fd >= 0)
2915 	{
2916 		(void) ioctl(fd, TIOCNOTTY, (char *) 0);
2917 		(void) close(fd);
2918 	}
2919 #  endif /* TIOCNOTTY */
2920 #  ifdef SYS5SETPGRP
2921 	return setpgrp();
2922 #  else /* SYS5SETPGRP */
2923 	return setpgid(0, CurrentPid);
2924 #  endif /* SYS5SETPGRP */
2925 }
2926 
2927 #endif /* !HASSETSID */
2928 /*
2929 **  FSYNC -- dummy fsync
2930 */
2931 
2932 #if NEEDFSYNC
2933 
fsync(fd)2934 fsync(fd)
2935 	int fd;
2936 {
2937 # ifdef O_SYNC
2938 	return fcntl(fd, F_SETFL, O_SYNC);
2939 # else /* O_SYNC */
2940 	/* nothing we can do */
2941 	return 0;
2942 # endif /* O_SYNC */
2943 }
2944 
2945 #endif /* NEEDFSYNC */
2946 /*
2947 **  DGUX_INET_ADDR -- inet_addr for DG/UX
2948 **
2949 **	Data General DG/UX version of inet_addr returns a struct in_addr
2950 **	instead of a long.  This patches things.  Only needed on versions
2951 **	prior to 5.4.3.
2952 */
2953 
2954 #ifdef DGUX_5_4_2
2955 
2956 # undef inet_addr
2957 
2958 long
dgux_inet_addr(host)2959 dgux_inet_addr(host)
2960 	char *host;
2961 {
2962 	struct in_addr haddr;
2963 
2964 	haddr = inet_addr(host);
2965 	return haddr.s_addr;
2966 }
2967 
2968 #endif /* DGUX_5_4_2 */
2969 /*
2970 **  GETOPT -- for old systems or systems with bogus implementations
2971 */
2972 
2973 #if !SM_CONF_GETOPT
2974 
2975 /*
2976  * Copyright (c) 1985 Regents of the University of California.
2977  * All rights reserved.  The Berkeley software License Agreement
2978  * specifies the terms and conditions for redistribution.
2979  */
2980 
2981 
2982 /*
2983 **  this version hacked to add `atend' flag to allow state machine
2984 **  to reset if invoked by the program to scan args for a 2nd time
2985 */
2986 
2987 # if defined(LIBC_SCCS) && !defined(lint)
2988 static char sccsid[] = "@(#)getopt.c	4.3 (Berkeley) 3/9/86";
2989 # endif /* defined(LIBC_SCCS) && !defined(lint) */
2990 
2991 /*
2992 **  get option letter from argument vector
2993 */
2994 # ifdef _CONVEX_SOURCE
2995 extern int	optind, opterr, optopt;
2996 extern char	*optarg;
2997 # else /* _CONVEX_SOURCE */
2998 int	opterr = 1;		/* if error message should be printed */
2999 int	optind = 1;		/* index into parent argv vector */
3000 int	optopt = 0;		/* character checked for validity */
3001 char	*optarg = NULL;		/* argument associated with option */
3002 # endif /* _CONVEX_SOURCE */
3003 
3004 # define BADCH	(int)'?'
3005 # define EMSG	""
3006 # define tell(s)	if (opterr) \
3007 			{sm_io_fputs(smioerr, SM_TIME_DEFAULT, *nargv); \
3008 			(void) sm_io_fputs(smioerr, SM_TIME_DEFAULT, s); \
3009 			(void) sm_io_putc(smioerr, SM_TIME_DEFAULT, optopt); \
3010 			(void) sm_io_putc(smioerr, SM_TIME_DEFAULT, '\n'); \
3011 			return BADCH;}
3012 
3013 int
getopt(nargc,nargv,ostr)3014 getopt(nargc,nargv,ostr)
3015 	int		nargc;
3016 	char *const	*nargv;
3017 	const char	*ostr;
3018 {
3019 	static char	*place = EMSG;	/* option letter processing */
3020 	static char	atend = 0;
3021 	register char	*oli = NULL;	/* option letter list index */
3022 
3023 	if (atend) {
3024 		atend = 0;
3025 		place = EMSG;
3026 	}
3027 	if(!*place) {			/* update scanning pointer */
3028 		if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) {
3029 			atend++;
3030 			return -1;
3031 		}
3032 		if (*place == '-') {	/* found "--" */
3033 			++optind;
3034 			atend++;
3035 			return -1;
3036 		}
3037 	}				/* option letter okay? */
3038 	if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) {
3039 		if (!*place) ++optind;
3040 		tell(": illegal option -- ");
3041 	}
3042 	if (oli && *++oli != ':') {		/* don't need argument */
3043 		optarg = NULL;
3044 		if (!*place) ++optind;
3045 	}
3046 	else {				/* need an argument */
3047 		if (*place) optarg = place;	/* no white space */
3048 		else if (nargc <= ++optind) {	/* no arg */
3049 			place = EMSG;
3050 			tell(": option requires an argument -- ");
3051 		}
3052 		else optarg = nargv[optind];	/* white space */
3053 		place = EMSG;
3054 		++optind;
3055 	}
3056 	return optopt;			/* dump back option letter */
3057 }
3058 
3059 #endif /* !SM_CONF_GETOPT */
3060 /*
3061 **  USERSHELLOK -- tell if a user's shell is ok for unrestricted use
3062 **
3063 **	Parameters:
3064 **		user -- the name of the user we are checking.
3065 **		shell -- the user's shell from /etc/passwd
3066 **
3067 **	Returns:
3068 **		true -- if it is ok to use this for unrestricted access.
3069 **		false -- if the shell is restricted.
3070 */
3071 
3072 #if !HASGETUSERSHELL
3073 
3074 # ifndef _PATH_SHELLS
3075 #  define _PATH_SHELLS	"/etc/shells"
3076 # endif /* ! _PATH_SHELLS */
3077 
3078 # if defined(_AIX3) || defined(_AIX4)
3079 #  include <userconf.h>
3080 #  if _AIX4 >= 40200
3081 #   include <userpw.h>
3082 #  endif /* _AIX4 >= 40200 */
3083 #  include <usersec.h>
3084 # endif /* defined(_AIX3) || defined(_AIX4) */
3085 
3086 static char	*DefaultUserShells[] =
3087 {
3088 	"/bin/sh",		/* standard shell */
3089 # ifdef MPE
3090 	"/SYS/PUB/CI",
3091 # else /* MPE */
3092 	"/usr/bin/sh",
3093 	"/bin/csh",		/* C shell */
3094 	"/usr/bin/csh",
3095 # endif /* MPE */
3096 # ifdef __hpux
3097 #  ifdef V4FS
3098 	"/usr/bin/rsh",		/* restricted Bourne shell */
3099 	"/usr/bin/ksh",		/* Korn shell */
3100 	"/usr/bin/rksh",	/* restricted Korn shell */
3101 	"/usr/bin/pam",
3102 	"/usr/bin/keysh",	/* key shell (extended Korn shell) */
3103 	"/usr/bin/posix/sh",
3104 #  else /* V4FS */
3105 	"/bin/rsh",		/* restricted Bourne shell */
3106 	"/bin/ksh",		/* Korn shell */
3107 	"/bin/rksh",		/* restricted Korn shell */
3108 	"/bin/pam",
3109 	"/usr/bin/keysh",	/* key shell (extended Korn shell) */
3110 	"/bin/posix/sh",
3111 	"/sbin/sh",
3112 #  endif /* V4FS */
3113 # endif /* __hpux */
3114 # if defined(_AIX3) || defined(_AIX4)
3115 	"/bin/ksh",		/* Korn shell */
3116 	"/usr/bin/ksh",
3117 	"/bin/tsh",		/* trusted shell */
3118 	"/usr/bin/tsh",
3119 	"/bin/bsh",		/* Bourne shell */
3120 	"/usr/bin/bsh",
3121 # endif /* defined(_AIX3) || defined(_AIX4) */
3122 # if defined(__svr4__) || defined(__svr5__)
3123 	"/bin/ksh",		/* Korn shell */
3124 	"/usr/bin/ksh",
3125 # endif /* defined(__svr4__) || defined(__svr5__) */
3126 # ifdef sgi
3127 	"/sbin/sh",		/* SGI's shells really live in /sbin */
3128 	"/usr/bin/sh",
3129 	"/sbin/bsh",		/* classic Bourne shell */
3130 	"/bin/bsh",
3131 	"/usr/bin/bsh",
3132 	"/sbin/csh",		/* standard csh */
3133 	"/bin/csh",
3134 	"/usr/bin/csh",
3135 	"/sbin/jsh",		/* classic Bourne shell w/ job control*/
3136 	"/bin/jsh",
3137 	"/usr/bin/jsh",
3138 	"/bin/ksh",		/* Korn shell */
3139 	"/sbin/ksh",
3140 	"/usr/bin/ksh",
3141 	"/sbin/tcsh",		/* Extended csh */
3142 	"/bin/tcsh",
3143 	"/usr/bin/tcsh",
3144 # endif /* sgi */
3145 	NULL
3146 };
3147 
3148 #endif /* !HASGETUSERSHELL */
3149 
3150 #define WILDCARD_SHELL	"/SENDMAIL/ANY/SHELL/"
3151 
3152 bool
usershellok(user,shell)3153 usershellok(user, shell)
3154 	char *user;
3155 	char *shell;
3156 {
3157 # if HASGETUSERSHELL
3158 	register char *p;
3159 	extern char *getusershell();
3160 
3161 	if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') ||
3162 	    ConfigLevel <= 1)
3163 		return true;
3164 
3165 	setusershell();
3166 	while ((p = getusershell()) != NULL)
3167 		if (strcmp(p, shell) == 0 || strcmp(p, WILDCARD_SHELL) == 0)
3168 			break;
3169 	endusershell();
3170 	return p != NULL;
3171 # else /* HASGETUSERSHELL */
3172 #  if USEGETCONFATTR
3173 	auto char *v;
3174 #  endif /* USEGETCONFATTR */
3175 	register SM_FILE_T *shellf;
3176 	char buf[MAXLINE];
3177 
3178 	if (shell == NULL || shell[0] == '\0' || wordinclass(user, 't') ||
3179 	    ConfigLevel <= 1)
3180 		return true;
3181 
3182 #  if USEGETCONFATTR
3183 	/*
3184 	**  Naturally IBM has a "better" idea.....
3185 	**
3186 	**	What a crock.  This interface isn't documented, it is
3187 	**	considered part of the security library (-ls), and it
3188 	**	only works if you are running as root (since the list
3189 	**	of valid shells is obviously a source of great concern).
3190 	**	I recommend that you do NOT define USEGETCONFATTR,
3191 	**	especially since you are going to have to set up an
3192 	**	/etc/shells anyhow to handle the cases where getconfattr
3193 	**	fails.
3194 	*/
3195 
3196 	if (getconfattr(SC_SYS_LOGIN, SC_SHELLS, &v, SEC_LIST) == 0 && v != NULL)
3197 	{
3198 		while (*v != '\0')
3199 		{
3200 			if (strcmp(v, shell) == 0 || strcmp(v, WILDCARD_SHELL) == 0)
3201 				return true;
3202 			v += strlen(v) + 1;
3203 		}
3204 		return false;
3205 	}
3206 #  endif /* USEGETCONFATTR */
3207 
3208 	shellf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, _PATH_SHELLS,
3209 			    SM_IO_RDONLY, NULL);
3210 	if (shellf == NULL)
3211 	{
3212 		/* no /etc/shells; see if it is one of the std shells */
3213 		char **d;
3214 
3215 		if (errno != ENOENT && LogLevel > 3)
3216 			sm_syslog(LOG_ERR, NOQID,
3217 				  "usershellok: cannot open %s: %s",
3218 				  _PATH_SHELLS, sm_errstring(errno));
3219 
3220 		for (d = DefaultUserShells; *d != NULL; d++)
3221 		{
3222 			if (strcmp(shell, *d) == 0)
3223 				return true;
3224 		}
3225 		return false;
3226 	}
3227 
3228 	while (sm_io_fgets(shellf, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL)
3229 	{
3230 		register char *p, *q;
3231 
3232 		p = buf;
3233 		while (*p != '\0' && *p != '#' && *p != '/')
3234 			p++;
3235 		if (*p == '#' || *p == '\0')
3236 			continue;
3237 		q = p;
3238 		while (*p != '\0' && *p != '#' && !(isascii(*p) && isspace(*p)))
3239 			p++;
3240 		*p = '\0';
3241 		if (strcmp(shell, q) == 0 || strcmp(WILDCARD_SHELL, q) == 0)
3242 		{
3243 			(void) sm_io_close(shellf, SM_TIME_DEFAULT);
3244 			return true;
3245 		}
3246 	}
3247 	(void) sm_io_close(shellf, SM_TIME_DEFAULT);
3248 	return false;
3249 # endif /* HASGETUSERSHELL */
3250 }
3251 /*
3252 **  FREEDISKSPACE -- see how much free space is on the queue filesystem
3253 **
3254 **	Only implemented if you have statfs.
3255 **
3256 **	Parameters:
3257 **		dir -- the directory in question.
3258 **		bsize -- a variable into which the filesystem
3259 **			block size is stored.
3260 **
3261 **	Returns:
3262 **		The number of blocks free on the queue filesystem.
3263 **		-1 if the statfs call fails.
3264 **
3265 **	Side effects:
3266 **		Puts the filesystem block size into bsize.
3267 */
3268 
3269 /* statfs types */
3270 # define SFS_NONE	0	/* no statfs implementation */
3271 # define SFS_USTAT	1	/* use ustat */
3272 # define SFS_4ARGS	2	/* use four-argument statfs call */
3273 # define SFS_VFS	3	/* use <sys/vfs.h> implementation */
3274 # define SFS_MOUNT	4	/* use <sys/mount.h> implementation */
3275 # define SFS_STATFS	5	/* use <sys/statfs.h> implementation */
3276 # define SFS_STATVFS	6	/* use <sys/statvfs.h> implementation */
3277 
3278 # ifndef SFS_TYPE
3279 #  define SFS_TYPE	SFS_NONE
3280 # endif /* ! SFS_TYPE */
3281 
3282 # if SFS_TYPE == SFS_USTAT
3283 #  include <ustat.h>
3284 # endif /* SFS_TYPE == SFS_USTAT */
3285 # if SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS
3286 #  include <sys/statfs.h>
3287 # endif /* SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS */
3288 # if SFS_TYPE == SFS_VFS
3289 #  include <sys/vfs.h>
3290 # endif /* SFS_TYPE == SFS_VFS */
3291 # if SFS_TYPE == SFS_MOUNT
3292 #  include <sys/mount.h>
3293 # endif /* SFS_TYPE == SFS_MOUNT */
3294 # if SFS_TYPE == SFS_STATVFS
3295 #  include <sys/statvfs.h>
3296 # endif /* SFS_TYPE == SFS_STATVFS */
3297 
3298 long
freediskspace(dir,bsize)3299 freediskspace(dir, bsize)
3300 	const char *dir;
3301 	long *bsize;
3302 {
3303 # if SFS_TYPE == SFS_NONE
3304 	if (bsize != NULL)
3305 		*bsize = 4096L;
3306 
3307 	/* assume free space is plentiful */
3308 	return (long) LONG_MAX;
3309 # else /* SFS_TYPE == SFS_NONE */
3310 #  if SFS_TYPE == SFS_USTAT
3311 	struct ustat fs;
3312 	struct stat statbuf;
3313 #   define FSBLOCKSIZE	DEV_BSIZE
3314 #   define SFS_BAVAIL	f_tfree
3315 #  else /* SFS_TYPE == SFS_USTAT */
3316 #   if defined(ultrix)
3317 	struct fs_data fs;
3318 #    define SFS_BAVAIL	fd_bfreen
3319 #    define FSBLOCKSIZE	1024L
3320 #   else /* defined(ultrix) */
3321 #    if SFS_TYPE == SFS_STATVFS
3322 	struct statvfs fs;
3323 #     define FSBLOCKSIZE	fs.f_frsize
3324 #    else /* SFS_TYPE == SFS_STATVFS */
3325 	struct statfs fs;
3326 #     define FSBLOCKSIZE	fs.f_bsize
3327 #    endif /* SFS_TYPE == SFS_STATVFS */
3328 #   endif /* defined(ultrix) */
3329 #  endif /* SFS_TYPE == SFS_USTAT */
3330 #  ifndef SFS_BAVAIL
3331 #   define SFS_BAVAIL f_bavail
3332 #  endif /* ! SFS_BAVAIL */
3333 
3334 #  if SFS_TYPE == SFS_USTAT
3335 	if (stat(dir, &statbuf) == 0 && ustat(statbuf.st_dev, &fs) == 0)
3336 #  else /* SFS_TYPE == SFS_USTAT */
3337 #   if SFS_TYPE == SFS_4ARGS
3338 	if (statfs(dir, &fs, sizeof(fs), 0) == 0)
3339 #   else /* SFS_TYPE == SFS_4ARGS */
3340 #    if SFS_TYPE == SFS_STATVFS
3341 	if (statvfs(dir, &fs) == 0)
3342 #    else /* SFS_TYPE == SFS_STATVFS */
3343 #     if defined(ultrix)
3344 	if (statfs(dir, &fs) > 0)
3345 #     else /* defined(ultrix) */
3346 	if (statfs(dir, &fs) == 0)
3347 #     endif /* defined(ultrix) */
3348 #    endif /* SFS_TYPE == SFS_STATVFS */
3349 #   endif /* SFS_TYPE == SFS_4ARGS */
3350 #  endif /* SFS_TYPE == SFS_USTAT */
3351 	{
3352 		if (bsize != NULL)
3353 			*bsize = FSBLOCKSIZE;
3354 		if (fs.SFS_BAVAIL <= 0)
3355 			return 0;
3356 		else if (fs.SFS_BAVAIL > LONG_MAX)
3357 			return (long) LONG_MAX;
3358 		else
3359 			return (long) fs.SFS_BAVAIL;
3360 	}
3361 	return -1;
3362 # endif /* SFS_TYPE == SFS_NONE */
3363 }
3364 /*
3365 **  ENOUGHDISKSPACE -- is there enough free space on the queue file systems?
3366 **
3367 **	Parameters:
3368 **		msize -- the size to check against.  If zero, we don't yet
3369 **		know how big the message will be, so just check for
3370 **		a "reasonable" amount.
3371 **		e -- envelope, or NULL -- controls logging
3372 **
3373 **	Returns:
3374 **		true if in every queue group there is at least one
3375 **		queue directory whose file system contains enough free space.
3376 **		false otherwise.
3377 **
3378 **	Side Effects:
3379 **		If there is not enough disk space and e != NULL
3380 **		then sm_syslog is called.
3381 */
3382 
3383 bool
enoughdiskspace(msize,e)3384 enoughdiskspace(msize, e)
3385 	long msize;
3386 	ENVELOPE *e;
3387 {
3388 	int i;
3389 
3390 #if _FFR_TESTS
3391 	if (tTd(4, 101))
3392 		return false;
3393 #endif /* _FFR_TESTS */
3394 	if (MinBlocksFree <= 0 && msize <= 0)
3395 	{
3396 		if (tTd(4, 80))
3397 			sm_dprintf("enoughdiskspace: no threshold\n");
3398 		return true;
3399 	}
3400 
3401 	filesys_update();
3402 	for (i = 0; i < NumQueue; ++i)
3403 	{
3404 		if (pickqdir(Queue[i], msize, e) < 0)
3405 			return false;
3406 	}
3407 	return true;
3408 }
3409 /*
3410 **  TRANSIENTERROR -- tell if an error code indicates a transient failure
3411 **
3412 **	This looks at an errno value and tells if this is likely to
3413 **	go away if retried later.
3414 **
3415 **	Parameters:
3416 **		err -- the errno code to classify.
3417 **
3418 **	Returns:
3419 **		true if this is probably transient.
3420 **		false otherwise.
3421 */
3422 
3423 bool
transienterror(err)3424 transienterror(err)
3425 	int err;
3426 {
3427 	switch (err)
3428 	{
3429 	  case EIO:			/* I/O error */
3430 	  case ENXIO:			/* Device not configured */
3431 	  case EAGAIN:			/* Resource temporarily unavailable */
3432 	  case ENOMEM:			/* Cannot allocate memory */
3433 	  case ENODEV:			/* Operation not supported by device */
3434 	  case ENFILE:			/* Too many open files in system */
3435 	  case EMFILE:			/* Too many open files */
3436 	  case ENOSPC:			/* No space left on device */
3437 	  case ETIMEDOUT:		/* Connection timed out */
3438 #ifdef ESTALE
3439 	  case ESTALE:			/* Stale NFS file handle */
3440 #endif /* ESTALE */
3441 #ifdef ENETDOWN
3442 	  case ENETDOWN:		/* Network is down */
3443 #endif /* ENETDOWN */
3444 #ifdef ENETUNREACH
3445 	  case ENETUNREACH:		/* Network is unreachable */
3446 #endif /* ENETUNREACH */
3447 #ifdef ENETRESET
3448 	  case ENETRESET:		/* Network dropped connection on reset */
3449 #endif /* ENETRESET */
3450 #ifdef ECONNABORTED
3451 	  case ECONNABORTED:		/* Software caused connection abort */
3452 #endif /* ECONNABORTED */
3453 #ifdef ECONNRESET
3454 	  case ECONNRESET:		/* Connection reset by peer */
3455 #endif /* ECONNRESET */
3456 #ifdef ENOBUFS
3457 	  case ENOBUFS:			/* No buffer space available */
3458 #endif /* ENOBUFS */
3459 #ifdef ESHUTDOWN
3460 	  case ESHUTDOWN:		/* Can't send after socket shutdown */
3461 #endif /* ESHUTDOWN */
3462 #ifdef ECONNREFUSED
3463 	  case ECONNREFUSED:		/* Connection refused */
3464 #endif /* ECONNREFUSED */
3465 #ifdef EHOSTDOWN
3466 	  case EHOSTDOWN:		/* Host is down */
3467 #endif /* EHOSTDOWN */
3468 #ifdef EHOSTUNREACH
3469 	  case EHOSTUNREACH:		/* No route to host */
3470 #endif /* EHOSTUNREACH */
3471 #ifdef EDQUOT
3472 	  case EDQUOT:			/* Disc quota exceeded */
3473 #endif /* EDQUOT */
3474 #ifdef EPROCLIM
3475 	  case EPROCLIM:		/* Too many processes */
3476 #endif /* EPROCLIM */
3477 #ifdef EUSERS
3478 	  case EUSERS:			/* Too many users */
3479 #endif /* EUSERS */
3480 #ifdef EDEADLK
3481 	  case EDEADLK:			/* Resource deadlock avoided */
3482 #endif /* EDEADLK */
3483 #ifdef EISCONN
3484 	  case EISCONN:			/* Socket already connected */
3485 #endif /* EISCONN */
3486 #ifdef EINPROGRESS
3487 	  case EINPROGRESS:		/* Operation now in progress */
3488 #endif /* EINPROGRESS */
3489 #ifdef EALREADY
3490 	  case EALREADY:		/* Operation already in progress */
3491 #endif /* EALREADY */
3492 #ifdef EADDRINUSE
3493 	  case EADDRINUSE:		/* Address already in use */
3494 #endif /* EADDRINUSE */
3495 #ifdef EADDRNOTAVAIL
3496 	  case EADDRNOTAVAIL:		/* Can't assign requested address */
3497 #endif /* EADDRNOTAVAIL */
3498 #ifdef ETXTBSY
3499 	  case ETXTBSY:			/* (Apollo) file locked */
3500 #endif /* ETXTBSY */
3501 #if defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR))
3502 	  case ENOSR:			/* Out of streams resources */
3503 #endif /* defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR)) */
3504 #ifdef ENOLCK
3505 	  case ENOLCK:			/* No locks available */
3506 #endif /* ENOLCK */
3507 	  case E_SM_OPENTIMEOUT:	/* PSEUDO: open timed out */
3508 		return true;
3509 	}
3510 
3511 	/* nope, must be permanent */
3512 	return false;
3513 }
3514 /*
3515 **  LOCKFILE -- lock a file using flock or (shudder) fcntl locking
3516 **
3517 **	Parameters:
3518 **		fd -- the file descriptor of the file.
3519 **		filename -- the file name (for error messages).
3520 **		ext -- the filename extension.
3521 **		type -- type of the lock.  Bits can be:
3522 **			LOCK_EX -- exclusive lock.
3523 **			LOCK_NB -- non-blocking.
3524 **			LOCK_UN -- unlock.
3525 **
3526 **	Returns:
3527 **		true if the lock was acquired.
3528 **		false otherwise.
3529 */
3530 
3531 bool
lockfile(fd,filename,ext,type)3532 lockfile(fd, filename, ext, type)
3533 	int fd;
3534 	char *filename;
3535 	char *ext;
3536 	int type;
3537 {
3538 	int i;
3539 	int save_errno;
3540 # if !HASFLOCK
3541 	int action;
3542 	struct flock lfd;
3543 
3544 	if (ext == NULL)
3545 		ext = "";
3546 
3547 	memset(&lfd, '\0', sizeof(lfd));
3548 	if (bitset(LOCK_UN, type))
3549 		lfd.l_type = F_UNLCK;
3550 	else if (bitset(LOCK_EX, type))
3551 		lfd.l_type = F_WRLCK;
3552 	else
3553 		lfd.l_type = F_RDLCK;
3554 
3555 	if (bitset(LOCK_NB, type))
3556 		action = F_SETLK;
3557 	else
3558 		action = F_SETLKW;
3559 
3560 	if (tTd(55, 60))
3561 		sm_dprintf("lockfile(%s%s, action=%d, type=%d): ",
3562 			filename, ext, action, lfd.l_type);
3563 
3564 	while ((i = fcntl(fd, action, &lfd)) < 0 && errno == EINTR)
3565 		continue;
3566 	if (i >= 0)
3567 	{
3568 		if (tTd(55, 60))
3569 			sm_dprintf("SUCCESS\n");
3570 		return true;
3571 	}
3572 	save_errno = errno;
3573 
3574 	if (tTd(55, 60))
3575 		sm_dprintf("(%s) ", sm_errstring(save_errno));
3576 
3577 	/*
3578 	**  On SunOS, if you are testing using -oQ/tmp/mqueue or
3579 	**  -oA/tmp/aliases or anything like that, and /tmp is mounted
3580 	**  as type "tmp" (that is, served from swap space), the
3581 	**  previous fcntl will fail with "Invalid argument" errors.
3582 	**  Since this is fairly common during testing, we will assume
3583 	**  that this indicates that the lock is successfully grabbed.
3584 	*/
3585 
3586 	if (save_errno == EINVAL)
3587 	{
3588 		if (tTd(55, 60))
3589 			sm_dprintf("SUCCESS\n");
3590 		return true;
3591 	}
3592 
3593 	if (!bitset(LOCK_NB, type) ||
3594 	    (save_errno != EACCES && save_errno != EAGAIN))
3595 	{
3596 		int omode = fcntl(fd, F_GETFL, 0);
3597 		uid_t euid = geteuid();
3598 
3599 		errno = save_errno;
3600 		syserr("cannot lockf(%s%s, fd=%d, type=%o, omode=%o, euid=%d)",
3601 		       filename, ext, fd, type, omode, euid);
3602 		dumpfd(fd, true, true);
3603 	}
3604 # else /* !HASFLOCK */
3605 	if (ext == NULL)
3606 		ext = "";
3607 
3608 	if (tTd(55, 60))
3609 		sm_dprintf("lockfile(%s%s, type=%o): ", filename, ext, type);
3610 
3611 	while ((i = flock(fd, type)) < 0 && errno == EINTR)
3612 		continue;
3613 	if (i >= 0)
3614 	{
3615 		if (tTd(55, 60))
3616 			sm_dprintf("SUCCESS\n");
3617 		return true;
3618 	}
3619 	save_errno = errno;
3620 
3621 	if (tTd(55, 60))
3622 		sm_dprintf("(%s) ", sm_errstring(save_errno));
3623 
3624 	if (!bitset(LOCK_NB, type) || save_errno != EWOULDBLOCK)
3625 	{
3626 		int omode = fcntl(fd, F_GETFL, 0);
3627 		uid_t euid = geteuid();
3628 
3629 		errno = save_errno;
3630 		syserr("cannot flock(%s%s, fd=%d, type=%o, omode=%o, euid=%d)",
3631 			filename, ext, fd, type, omode, euid);
3632 		dumpfd(fd, true, true);
3633 	}
3634 # endif /* !HASFLOCK */
3635 	if (tTd(55, 60))
3636 		sm_dprintf("FAIL\n");
3637 	errno = save_errno;
3638 	return false;
3639 }
3640 /*
3641 **  CHOWNSAFE -- tell if chown is "safe" (executable only by root)
3642 **
3643 **	Unfortunately, given that we can't predict other systems on which
3644 **	a remote mounted (NFS) filesystem will be mounted, the answer is
3645 **	almost always that this is unsafe.
3646 **
3647 **	Note also that many operating systems have non-compliant
3648 **	implementations of the _POSIX_CHOWN_RESTRICTED variable and the
3649 **	fpathconf() routine.  According to IEEE 1003.1-1990, if
3650 **	_POSIX_CHOWN_RESTRICTED is defined and not equal to -1, then
3651 **	no non-root process can give away the file.  However, vendors
3652 **	don't take NFS into account, so a comfortable value of
3653 **	_POSIX_CHOWN_RESTRICTED tells us nothing.
3654 **
3655 **	Also, some systems (e.g., IRIX 6.2) return 1 from fpathconf()
3656 **	even on files where chown is not restricted.  Many systems get
3657 **	this wrong on NFS-based filesystems (that is, they say that chown
3658 **	is restricted [safe] on NFS filesystems where it may not be, since
3659 **	other systems can access the same filesystem and do file giveaway;
3660 **	only the NFS server knows for sure!)  Hence, it is important to
3661 **	get the value of SAFENFSPATHCONF correct -- it should be defined
3662 **	_only_ after testing (see test/t_pathconf.c) a system on an unsafe
3663 **	NFS-based filesystem to ensure that you can get meaningful results.
3664 **	If in doubt, assume unsafe!
3665 **
3666 **	You may also need to tweak IS_SAFE_CHOWN -- it should be a
3667 **	condition indicating whether the return from pathconf indicates
3668 **	that chown is safe (typically either > 0 or >= 0 -- there isn't
3669 **	even any agreement about whether a zero return means that a file
3670 **	is or is not safe).  It defaults to "> 0".
3671 **
3672 **	If the parent directory is safe (writable only by owner back
3673 **	to the root) then we can relax slightly and trust fpathconf
3674 **	in more circumstances.  This is really a crock -- if this is an
3675 **	NFS mounted filesystem then we really know nothing about the
3676 **	underlying implementation.  However, most systems pessimize and
3677 **	return an error (EINVAL or EOPNOTSUPP) on NFS filesystems, which
3678 **	we interpret as unsafe, as we should.  Thus, this heuristic gets
3679 **	us into a possible problem only on systems that have a broken
3680 **	pathconf implementation and which are also poorly configured
3681 **	(have :include: files in group- or world-writable directories).
3682 **
3683 **	Parameters:
3684 **		fd -- the file descriptor to check.
3685 **		safedir -- set if the parent directory is safe.
3686 **
3687 **	Returns:
3688 **		true -- if the chown(2) operation is "safe" -- that is,
3689 **			only root can chown the file to an arbitrary user.
3690 **		false -- if an arbitrary user can give away a file.
3691 */
3692 
3693 #ifndef IS_SAFE_CHOWN
3694 # define IS_SAFE_CHOWN	> 0
3695 #endif /* ! IS_SAFE_CHOWN */
3696 
3697 bool
chownsafe(fd,safedir)3698 chownsafe(fd, safedir)
3699 	int fd;
3700 	bool safedir;
3701 {
3702 # if (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && \
3703     (defined(_PC_CHOWN_RESTRICTED) || defined(_GNU_TYPES_H))
3704 	int rval;
3705 
3706 	/* give the system administrator a chance to override */
3707 	if (bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail))
3708 		return true;
3709 
3710 	/*
3711 	**  Some systems (e.g., SunOS) seem to have the call and the
3712 	**  #define _PC_CHOWN_RESTRICTED, but don't actually implement
3713 	**  the call.  This heuristic checks for that.
3714 	*/
3715 
3716 	errno = 0;
3717 	rval = fpathconf(fd, _PC_CHOWN_RESTRICTED);
3718 #  if SAFENFSPATHCONF
3719 	return errno == 0 && rval IS_SAFE_CHOWN;
3720 #  else /* SAFENFSPATHCONF */
3721 	return safedir && errno == 0 && rval IS_SAFE_CHOWN;
3722 #  endif /* SAFENFSPATHCONF */
3723 # else /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */
3724 	return bitnset(DBS_ASSUMESAFECHOWN, DontBlameSendmail);
3725 # endif /* (!defined(_POSIX_CHOWN_RESTRICTED) || _POSIX_CHOWN_RESTRICTED != -1) && ... */
3726 }
3727 /*
3728 **  RESETLIMITS -- reset system controlled resource limits
3729 **
3730 **	This is to avoid denial-of-service attacks
3731 **
3732 **	Parameters:
3733 **		none
3734 **
3735 **	Returns:
3736 **		none
3737 */
3738 
3739 #if HASSETRLIMIT
3740 # ifdef RLIMIT_NEEDS_SYS_TIME_H
3741 #  include <sm/time.h>
3742 # endif /* RLIMIT_NEEDS_SYS_TIME_H */
3743 # include <sys/resource.h>
3744 #endif /* HASSETRLIMIT */
3745 
3746 void
resetlimits()3747 resetlimits()
3748 {
3749 #if HASSETRLIMIT
3750 	struct rlimit lim;
3751 
3752 	lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
3753 	(void) setrlimit(RLIMIT_CPU, &lim);
3754 	(void) setrlimit(RLIMIT_FSIZE, &lim);
3755 # ifdef RLIMIT_NOFILE
3756 	lim.rlim_cur = lim.rlim_max = FD_SETSIZE;
3757 	(void) setrlimit(RLIMIT_NOFILE, &lim);
3758 # endif /* RLIMIT_NOFILE */
3759 #else /* HASSETRLIMIT */
3760 # if HASULIMIT
3761 	(void) ulimit(2, 0x3fffff);
3762 	(void) ulimit(4, FD_SETSIZE);
3763 # endif /* HASULIMIT */
3764 #endif /* HASSETRLIMIT */
3765 	errno = 0;
3766 }
3767 /*
3768 **  SETVENDOR -- process vendor code from V configuration line
3769 **
3770 **	Parameters:
3771 **		vendor -- string representation of vendor.
3772 **
3773 **	Returns:
3774 **		true -- if ok.
3775 **		false -- if vendor code could not be processed.
3776 **
3777 **	Side Effects:
3778 **		It is reasonable to set mode flags here to tweak
3779 **		processing in other parts of the code if necessary.
3780 **		For example, if you are a vendor that uses $%y to
3781 **		indicate YP lookups, you could enable that here.
3782 */
3783 
3784 bool
setvendor(vendor)3785 setvendor(vendor)
3786 	char *vendor;
3787 {
3788 	if (sm_strcasecmp(vendor, "Berkeley") == 0)
3789 	{
3790 		VendorCode = VENDOR_BERKELEY;
3791 		return true;
3792 	}
3793 
3794 	/* add vendor extensions here */
3795 
3796 #ifdef SUN_EXTENSIONS
3797 	if (sm_strcasecmp(vendor, "Sun") == 0)
3798 	{
3799 		VendorCode = VENDOR_SUN;
3800 		return true;
3801 	}
3802 #endif /* SUN_EXTENSIONS */
3803 #ifdef DEC
3804 	if (sm_strcasecmp(vendor, "Digital") == 0)
3805 	{
3806 		VendorCode = VENDOR_DEC;
3807 		return true;
3808 	}
3809 #endif /* DEC */
3810 
3811 #if defined(VENDOR_NAME) && defined(VENDOR_CODE)
3812 	if (sm_strcasecmp(vendor, VENDOR_NAME) == 0)
3813 	{
3814 		VendorCode = VENDOR_CODE;
3815 		return true;
3816 	}
3817 #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */
3818 
3819 	return false;
3820 }
3821 /*
3822 **  GETVENDOR -- return vendor name based on vendor code
3823 **
3824 **	Parameters:
3825 **		vendorcode -- numeric representation of vendor.
3826 **
3827 **	Returns:
3828 **		string containing vendor name.
3829 */
3830 
3831 char *
getvendor(vendorcode)3832 getvendor(vendorcode)
3833 	int vendorcode;
3834 {
3835 #if defined(VENDOR_NAME) && defined(VENDOR_CODE)
3836 	/*
3837 	**  Can't have the same switch case twice so need to
3838 	**  handle VENDOR_CODE outside of switch.  It might
3839 	**  match one of the existing VENDOR_* codes.
3840 	*/
3841 
3842 	if (vendorcode == VENDOR_CODE)
3843 		return VENDOR_NAME;
3844 #endif /* defined(VENDOR_NAME) && defined(VENDOR_CODE) */
3845 
3846 	switch (vendorcode)
3847 	{
3848 	  case VENDOR_BERKELEY:
3849 		return "Berkeley";
3850 
3851 	  case VENDOR_SUN:
3852 		return "Sun";
3853 
3854 	  case VENDOR_HP:
3855 		return "HP";
3856 
3857 	  case VENDOR_IBM:
3858 		return "IBM";
3859 
3860 	  case VENDOR_SENDMAIL:
3861 		return "Sendmail";
3862 
3863 	  default:
3864 		return "Unknown";
3865 	}
3866 }
3867 /*
3868 **  VENDOR_PRE_DEFAULTS, VENDOR_POST_DEFAULTS -- set vendor-specific defaults
3869 **
3870 **	Vendor_pre_defaults is called before reading the configuration
3871 **	file; vendor_post_defaults is called immediately after.
3872 **
3873 **	Parameters:
3874 **		e -- the global environment to initialize.
3875 **
3876 **	Returns:
3877 **		none.
3878 */
3879 
3880 #if SHARE_V1
3881 int	DefShareUid;	/* default share uid to run as -- unused??? */
3882 #endif /* SHARE_V1 */
3883 
3884 void
vendor_pre_defaults(e)3885 vendor_pre_defaults(e)
3886 	ENVELOPE *e;
3887 {
3888 #if SHARE_V1
3889 	/* OTHERUID is defined in shares.h, do not be alarmed */
3890 	DefShareUid = OTHERUID;
3891 #endif /* SHARE_V1 */
3892 #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES)
3893 	sun_pre_defaults(e);
3894 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */
3895 #ifdef apollo
3896 	/*
3897 	**  stupid domain/os can't even open
3898 	**  /etc/mail/sendmail.cf without this
3899 	*/
3900 
3901 	sm_setuserenv("ISP", NULL);
3902 	sm_setuserenv("SYSTYPE", NULL);
3903 #endif /* apollo */
3904 }
3905 
3906 
3907 void
vendor_post_defaults(e)3908 vendor_post_defaults(e)
3909 	ENVELOPE *e;
3910 {
3911 #ifdef __QNX__
3912 	/* Makes sure the SOCK environment variable remains */
3913 	sm_setuserenv("SOCK", NULL);
3914 #endif /* __QNX__ */
3915 #if defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES)
3916 	sun_post_defaults(e);
3917 #endif /* defined(SUN_EXTENSIONS) && defined(SUN_DEFAULT_VALUES) */
3918 }
3919 /*
3920 **  VENDOR_DAEMON_SETUP -- special vendor setup needed for daemon mode
3921 */
3922 
3923 void
vendor_daemon_setup(e)3924 vendor_daemon_setup(e)
3925 	ENVELOPE *e;
3926 {
3927 #if HASSETLOGIN
3928 	(void) setlogin(RunAsUserName);
3929 #endif /* HASSETLOGIN */
3930 #if SECUREWARE
3931 	if (getluid() != -1)
3932 	{
3933 		usrerr("Daemon cannot have LUID");
3934 		finis(false, true, EX_USAGE);
3935 	}
3936 #endif /* SECUREWARE */
3937 }
3938 /*
3939 **  VENDOR_SET_UID -- do setup for setting a user id
3940 **
3941 **	This is called when we are still root.
3942 **
3943 **	Parameters:
3944 **		uid -- the uid we are about to become.
3945 **
3946 **	Returns:
3947 **		none.
3948 */
3949 
3950 void
vendor_set_uid(uid)3951 vendor_set_uid(uid)
3952 	UID_T uid;
3953 {
3954 	/*
3955 	**  We need to setup the share groups (lnodes)
3956 	**  and add auditing information (luid's)
3957 	**  before we loose our ``root''ness.
3958 	*/
3959 #if SHARE_V1
3960 	if (setupshares(uid, syserr) != 0)
3961 		syserr("Unable to set up shares");
3962 #endif /* SHARE_V1 */
3963 #if SECUREWARE
3964 	(void) setup_secure(uid);
3965 #endif /* SECUREWARE */
3966 }
3967 /*
3968 **  VALIDATE_CONNECTION -- check connection for rationality
3969 **
3970 **	If the connection is rejected, this routine should log an
3971 **	appropriate message -- but should never issue any SMTP protocol.
3972 **
3973 **	Parameters:
3974 **		sap -- a pointer to a SOCKADDR naming the peer.
3975 **		hostname -- the name corresponding to sap.
3976 **		e -- the current envelope.
3977 **
3978 **	Returns:
3979 **		error message from rejection.
3980 **		NULL if not rejected.
3981 */
3982 
3983 #if TCPWRAPPERS
3984 # include <tcpd.h>
3985 
3986 /* tcpwrappers does no logging, but you still have to declare these -- ugh */
3987 int	allow_severity	= LOG_INFO;
3988 int	deny_severity	= LOG_NOTICE;
3989 #endif /* TCPWRAPPERS */
3990 
3991 char *
validate_connection(sap,hostname,e)3992 validate_connection(sap, hostname, e)
3993 	SOCKADDR *sap;
3994 	char *hostname;
3995 	ENVELOPE *e;
3996 {
3997 #if TCPWRAPPERS
3998 	char *host;
3999 	char *addr;
4000 	extern int hosts_ctl();
4001 #endif /* TCPWRAPPERS */
4002 
4003 	if (tTd(48, 3))
4004 		sm_dprintf("validate_connection(%s, %s)\n",
4005 			hostname, anynet_ntoa(sap));
4006 
4007 	connection_rate_check(sap, e);
4008 	if (rscheck("check_relay", hostname, anynet_ntoa(sap),
4009 		    e, RSF_RMCOMM|RSF_COUNT, 3, NULL, NOQID, NULL) != EX_OK)
4010 	{
4011 		static char reject[BUFSIZ*2];
4012 		extern char MsgBuf[];
4013 
4014 		if (tTd(48, 4))
4015 			sm_dprintf("  ... validate_connection: BAD (rscheck)\n");
4016 
4017 		if (strlen(MsgBuf) >= 3)
4018 			(void) sm_strlcpy(reject, MsgBuf, sizeof(reject));
4019 		else
4020 			(void) sm_strlcpy(reject, "Access denied", sizeof(reject));
4021 
4022 		return reject;
4023 	}
4024 
4025 #if TCPWRAPPERS
4026 	if (hostname[0] == '[' && hostname[strlen(hostname) - 1] == ']')
4027 		host = "unknown";
4028 	else
4029 		host = hostname;
4030 	addr = anynet_ntoa(sap);
4031 
4032 # if NETINET6
4033 	/* TCP/Wrappers don't want the IPv6: protocol label */
4034 	if (addr != NULL && sm_strncasecmp(addr, "IPv6:", 5) == 0)
4035 		addr += 5;
4036 # endif /* NETINET6 */
4037 
4038 	if (!hosts_ctl("sendmail", host, addr, STRING_UNKNOWN))
4039 	{
4040 		if (tTd(48, 4))
4041 			sm_dprintf("  ... validate_connection: BAD (tcpwrappers)\n");
4042 		if (LogLevel > 3)
4043 			sm_syslog(LOG_NOTICE, e->e_id,
4044 				  "tcpwrappers (%s, %s) rejection",
4045 				  host, addr);
4046 		return "Access denied";
4047 	}
4048 #endif /* TCPWRAPPERS */
4049 	if (tTd(48, 4))
4050 		sm_dprintf("  ... validate_connection: OK\n");
4051 	return NULL;
4052 }
4053 
4054 /*
4055 **  STRTOL -- convert string to long integer
4056 **
4057 **	For systems that don't have it in the C library.
4058 **
4059 **	This is taken verbatim from the 4.4-Lite C library.
4060 */
4061 
4062 #if NEEDSTRTOL
4063 
4064 # if defined(LIBC_SCCS) && !defined(lint)
4065 static char sccsid[] = "@(#)strtol.c	8.1 (Berkeley) 6/4/93";
4066 # endif /* defined(LIBC_SCCS) && !defined(lint) */
4067 
4068 /*
4069 **  Convert a string to a long integer.
4070 **
4071 **  Ignores `locale' stuff.  Assumes that the upper and lower case
4072 **  alphabets and digits are each contiguous.
4073 */
4074 
4075 long
strtol(nptr,endptr,base)4076 strtol(nptr, endptr, base)
4077 	const char *nptr;
4078 	char **endptr;
4079 	register int base;
4080 {
4081 	register const char *s = nptr;
4082 	register unsigned long acc;
4083 	register int c;
4084 	register unsigned long cutoff;
4085 	register int neg = 0, any, cutlim;
4086 
4087 	/*
4088 	**  Skip white space and pick up leading +/- sign if any.
4089 	**  If base is 0, allow 0x for hex and 0 for octal, else
4090 	**  assume decimal; if base is already 16, allow 0x.
4091 	*/
4092 	do {
4093 		c = *s++;
4094 	} while (isascii(c) && isspace(c));
4095 	if (c == '-') {
4096 		neg = 1;
4097 		c = *s++;
4098 	} else if (c == '+')
4099 		c = *s++;
4100 	if ((base == 0 || base == 16) &&
4101 	    c == '0' && (*s == 'x' || *s == 'X')) {
4102 		c = s[1];
4103 		s += 2;
4104 		base = 16;
4105 	}
4106 	if (base == 0)
4107 		base = c == '0' ? 8 : 10;
4108 
4109 	/*
4110 	**  Compute the cutoff value between legal numbers and illegal
4111 	**  numbers.  That is the largest legal value, divided by the
4112 	**  base.  An input number that is greater than this value, if
4113 	**  followed by a legal input character, is too big.  One that
4114 	**  is equal to this value may be valid or not; the limit
4115 	**  between valid and invalid numbers is then based on the last
4116 	**  digit.  For instance, if the range for longs is
4117 	**  [-2147483648..2147483647] and the input base is 10,
4118 	**  cutoff will be set to 214748364 and cutlim to either
4119 	**  7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
4120 	**  a value > 214748364, or equal but the next digit is > 7 (or 8),
4121 	**  the number is too big, and we will return a range error.
4122 	**
4123 	**  Set any if any `digits' consumed; make it negative to indicate
4124 	**  overflow.
4125 	*/
4126 	cutoff = neg ? -(unsigned long) LONG_MIN : LONG_MAX;
4127 	cutlim = cutoff % (unsigned long) base;
4128 	cutoff /= (unsigned long) base;
4129 	for (acc = 0, any = 0;; c = *s++) {
4130 		if (isascii(c) && isdigit(c))
4131 			c -= '0';
4132 		else if (isascii(c) && isalpha(c))
4133 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4134 		else
4135 			break;
4136 		if (c >= base)
4137 			break;
4138 		if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
4139 			any = -1;
4140 		else {
4141 			any = 1;
4142 			acc *= base;
4143 			acc += c;
4144 		}
4145 	}
4146 	if (any < 0) {
4147 		acc = neg ? LONG_MIN :