xref: /original-bsd/usr.sbin/sendmail/src/conf.c (revision dbfb0019)
1 /*
2  * Copyright (c) 1983, 1995 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #ifndef lint
10 static char sccsid[] = "@(#)conf.c	8.179 (Berkeley) 05/28/95";
11 #endif /* not lint */
12 
13 # include "sendmail.h"
14 # include "pathnames.h"
15 # include <sys/ioctl.h>
16 # include <sys/param.h>
17 
18 /*
19 **  CONF.C -- Sendmail Configuration Tables.
20 **
21 **	Defines the configuration of this installation.
22 **
23 **	Configuration Variables:
24 **		HdrInfo -- a table describing well-known header fields.
25 **			Each entry has the field name and some flags,
26 **			which are described in sendmail.h.
27 **
28 **	Notes:
29 **		I have tried to put almost all the reasonable
30 **		configuration information into the configuration
31 **		file read at runtime.  My intent is that anything
32 **		here is a function of the version of UNIX you
33 **		are running, or is really static -- for example
34 **		the headers are a superset of widely used
35 **		protocols.  If you find yourself playing with
36 **		this file too much, you may be making a mistake!
37 */
38 
39 
40 
41 
42 /*
43 **  Header info table
44 **	Final (null) entry contains the flags used for any other field.
45 **
46 **	Not all of these are actually handled specially by sendmail
47 **	at this time.  They are included as placeholders, to let
48 **	you know that "someday" I intend to have sendmail do
49 **	something with them.
50 */
51 
52 struct hdrinfo	HdrInfo[] =
53 {
54 		/* originator fields, most to least significant  */
55 	"resent-sender",		H_FROM|H_RESENT,
56 	"resent-from",			H_FROM|H_RESENT,
57 	"resent-reply-to",		H_FROM|H_RESENT,
58 	"sender",			H_FROM,
59 	"from",				H_FROM,
60 	"reply-to",			H_FROM,
61 	"full-name",			H_ACHECK,
62 	"return-receipt-to",		H_FROM|H_RECEIPTTO,
63 	"errors-to",			H_FROM|H_ERRORSTO,
64 
65 		/* destination fields */
66 	"to",				H_RCPT,
67 	"resent-to",			H_RCPT|H_RESENT,
68 	"cc",				H_RCPT,
69 	"resent-cc",			H_RCPT|H_RESENT,
70 	"bcc",				H_RCPT|H_STRIPVAL,
71 	"resent-bcc",			H_RCPT|H_STRIPVAL|H_RESENT,
72 	"apparently-to",		H_RCPT,
73 
74 		/* message identification and control */
75 	"message-id",			0,
76 	"resent-message-id",		H_RESENT,
77 	"message",			H_EOH,
78 	"text",				H_EOH,
79 
80 		/* date fields */
81 	"date",				0,
82 	"resent-date",			H_RESENT,
83 
84 		/* trace fields */
85 	"received",			H_TRACE|H_FORCE,
86 	"x400-received",		H_TRACE|H_FORCE,
87 	"via",				H_TRACE|H_FORCE,
88 	"mail-from",			H_TRACE|H_FORCE,
89 
90 		/* miscellaneous fields */
91 	"comments",			H_FORCE,
92 	"return-path",			H_FORCE|H_ACHECK,
93 	"content-transfer-encoding",	H_CTE,
94 	"content-type",			H_CTYPE,
95 	"content-length",		H_ACHECK,
96 
97 	NULL,			0,
98 };
99 
100 
101 
102 /*
103 **  Location of system files/databases/etc.
104 */
105 
106 char	*PidFile =	_PATH_SENDMAILPID;	/* stores daemon proc id */
107 
108 
109 
110 /*
111 **  Privacy values
112 */
113 
114 struct prival PrivacyValues[] =
115 {
116 	"public",		PRIV_PUBLIC,
117 	"needmailhelo",		PRIV_NEEDMAILHELO,
118 	"needexpnhelo",		PRIV_NEEDEXPNHELO,
119 	"needvrfyhelo",		PRIV_NEEDVRFYHELO,
120 	"noexpn",		PRIV_NOEXPN,
121 	"novrfy",		PRIV_NOVRFY,
122 	"restrictmailq",	PRIV_RESTRICTMAILQ,
123 	"restrictqrun",		PRIV_RESTRICTQRUN,
124 	"authwarnings",		PRIV_AUTHWARNINGS,
125 	"noreceipts",		PRIV_NORECEIPTS,
126 	"goaway",		PRIV_GOAWAY,
127 	NULL,			0,
128 };
129 
130 
131 
132 /*
133 **  Miscellaneous stuff.
134 */
135 
136 int	DtableSize =	50;		/* max open files; reset in 4.2bsd */
137 /*
138 **  SETDEFAULTS -- set default values
139 **
140 **	Because of the way freezing is done, these must be initialized
141 **	using direct code.
142 **
143 **	Parameters:
144 **		e -- the default envelope.
145 **
146 **	Returns:
147 **		none.
148 **
149 **	Side Effects:
150 **		Initializes a bunch of global variables to their
151 **		default values.
152 */
153 
154 #define DAYS		* 24 * 60 * 60
155 
156 void
157 setdefaults(e)
158 	register ENVELOPE *e;
159 {
160 	int i;
161 	extern void inittimeouts();
162 	extern void setdefuser();
163 	extern void setupmaps();
164 	extern void setupmailers();
165 
166 	SpaceSub = ' ';				/* option B */
167 	QueueLA = 8;				/* option x */
168 	RefuseLA = 12;				/* option X */
169 	WkRecipFact = 30000L;			/* option y */
170 	WkClassFact = 1800L;			/* option z */
171 	WkTimeFact = 90000L;			/* option Z */
172 	QueueFactor = WkRecipFact * 20;		/* option q */
173 	FileMode = (RealUid != geteuid()) ? 0644 : 0600;
174 						/* option F */
175 	DefUid = 1;				/* option u */
176 	DefGid = 1;				/* option g */
177 	CheckpointInterval = 10;		/* option C */
178 	MaxHopCount = 25;			/* option h */
179 	e->e_sendmode = SM_FORK;		/* option d */
180 	e->e_errormode = EM_PRINT;		/* option e */
181 	SevenBitInput = FALSE;			/* option 7 */
182 	MaxMciCache = 1;			/* option k */
183 	MciCacheTimeout = 300;			/* option K */
184 	LogLevel = 9;				/* option L */
185 	inittimeouts(NULL);			/* option r */
186 	PrivacyFlags = 0;			/* option p */
187 #if MIME8TO7
188 	MimeMode = MM_CVTMIME|MM_PASS8BIT;	/* option 8 */
189 #else
190 	MimeMode = MM_PASS8BIT;
191 #endif
192 	for (i = 0; i < MAXTOCLASS; i++)
193 	{
194 		TimeOuts.to_q_return[i] = 5 DAYS;	/* option T */
195 		TimeOuts.to_q_warning[i] = 0;		/* option T */
196 	}
197 	ServiceSwitchFile = "/etc/service.switch";
198 	HostsFile = _PATH_HOSTS;
199 	setdefuser();
200 	setupmaps();
201 	setupmailers();
202 }
203 
204 
205 /*
206 **  SETDEFUSER -- set/reset DefUser using DefUid (for initgroups())
207 */
208 
209 void
210 setdefuser()
211 {
212 	struct passwd *defpwent;
213 	static char defuserbuf[40];
214 
215 	DefUser = defuserbuf;
216 	if ((defpwent = sm_getpwuid(DefUid)) != NULL)
217 		strcpy(defuserbuf, defpwent->pw_name);
218 	else
219 		strcpy(defuserbuf, "nobody");
220 }
221 /*
222 **  HOST_MAP_INIT -- initialize host class structures
223 */
224 
225 bool	host_map_init __P((MAP *map, char *args));
226 
227 bool
228 host_map_init(map, args)
229 	MAP *map;
230 	char *args;
231 {
232 	register char *p = args;
233 
234 	for (;;)
235 	{
236 		while (isascii(*p) && isspace(*p))
237 			p++;
238 		if (*p != '-')
239 			break;
240 		switch (*++p)
241 		{
242 		  case 'a':
243 			map->map_app = ++p;
244 			break;
245 		}
246 		while (*p != '\0' && !(isascii(*p) && isspace(*p)))
247 			p++;
248 		if (*p != '\0')
249 			*p++ = '\0';
250 	}
251 	if (map->map_app != NULL)
252 		map->map_app = newstr(map->map_app);
253 	return TRUE;
254 }
255 /*
256 **  SETUPMAILERS -- initialize default mailers
257 */
258 
259 void
260 setupmailers()
261 {
262 	char buf[100];
263 	extern void makemailer();
264 
265 	strcpy(buf, "prog, P=/bin/sh, F=lsoD, T=DNS/RFC822/X-Unix, A=sh -c $u");
266 	makemailer(buf);
267 
268 	strcpy(buf, "*file*, P=[FILE], F=lsDFMPEou, T=DNS/RFC822/X-Unix, A=FILE");
269 	makemailer(buf);
270 
271 	strcpy(buf, "*include*, P=/dev/null, F=su, A=INCLUDE");
272 	makemailer(buf);
273 }
274 /*
275 **  SETUPMAPS -- set up map classes
276 */
277 
278 #define MAPDEF(name, ext, flags, parse, open, close, lookup, store) \
279 	{ \
280 		extern bool parse __P((MAP *, char *)); \
281 		extern bool open __P((MAP *, int)); \
282 		extern void close __P((MAP *)); \
283 		extern char *lookup __P((MAP *, char *, char **, int *)); \
284 		extern void store __P((MAP *, char *, char *)); \
285 		s = stab(name, ST_MAPCLASS, ST_ENTER); \
286 		s->s_mapclass.map_cname = name; \
287 		s->s_mapclass.map_ext = ext; \
288 		s->s_mapclass.map_cflags = flags; \
289 		s->s_mapclass.map_parse = parse; \
290 		s->s_mapclass.map_open = open; \
291 		s->s_mapclass.map_close = close; \
292 		s->s_mapclass.map_lookup = lookup; \
293 		s->s_mapclass.map_store = store; \
294 	}
295 
296 void
297 setupmaps()
298 {
299 	register STAB *s;
300 
301 #ifdef NEWDB
302 	MAPDEF("hash", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
303 		map_parseargs, hash_map_open, db_map_close,
304 		db_map_lookup, db_map_store);
305 
306 	MAPDEF("btree", ".db", MCF_ALIASOK|MCF_REBUILDABLE,
307 		map_parseargs, bt_map_open, db_map_close,
308 		db_map_lookup, db_map_store);
309 #endif
310 
311 #ifdef NDBM
312 	MAPDEF("dbm", ".dir", MCF_ALIASOK|MCF_REBUILDABLE,
313 		map_parseargs, ndbm_map_open, ndbm_map_close,
314 		ndbm_map_lookup, ndbm_map_store);
315 #endif
316 
317 #ifdef NIS
318 	MAPDEF("nis", NULL, MCF_ALIASOK,
319 		map_parseargs, nis_map_open, null_map_close,
320 		nis_map_lookup, null_map_store);
321 #endif
322 
323 #ifdef NISPLUS
324 	MAPDEF("nisplus", NULL, MCF_ALIASOK,
325 		map_parseargs, nisplus_map_open, null_map_close,
326 		nisplus_map_lookup, null_map_store);
327 #endif
328 
329 #ifdef HESIOD
330 	MAPDEF("hesiod", NULL, MCF_ALIASOK|MCF_ALIASONLY,
331 		map_parseargs, null_map_open, null_map_close,
332 		hes_map_lookup, null_map_store);
333 #endif
334 
335 #ifdef NETINFO
336 	MAPDEF("netinfo", NULL, MCF_ALIASOK,
337 		map_parseargs, ni_map_open, null_map_close,
338 		ni_map_lookup, null_map_store);
339 #endif
340 
341 #if 0
342 	MAPDEF("dns", NULL, 0,
343 		dns_map_init, null_map_open, null_map_close,
344 		dns_map_lookup, null_map_store);
345 #endif
346 
347 #if NAMED_BIND
348 	/* best MX DNS lookup */
349 	MAPDEF("bestmx", NULL, MCF_OPTFILE,
350 		map_parseargs, null_map_open, null_map_close,
351 		bestmx_map_lookup, null_map_store);
352 #endif
353 
354 	MAPDEF("host", NULL, 0,
355 		host_map_init, null_map_open, null_map_close,
356 		host_map_lookup, null_map_store);
357 
358 	MAPDEF("text", NULL, MCF_ALIASOK,
359 		map_parseargs, text_map_open, null_map_close,
360 		text_map_lookup, null_map_store);
361 
362 	MAPDEF("stab", NULL, MCF_ALIASOK|MCF_ALIASONLY,
363 		map_parseargs, stab_map_open, null_map_close,
364 		stab_map_lookup, stab_map_store);
365 
366 	MAPDEF("implicit", NULL, MCF_ALIASOK|MCF_ALIASONLY|MCF_REBUILDABLE,
367 		map_parseargs, impl_map_open, impl_map_close,
368 		impl_map_lookup, impl_map_store);
369 
370 	/* access to system passwd file */
371 	MAPDEF("user", NULL, MCF_OPTFILE,
372 		map_parseargs, user_map_open, null_map_close,
373 		user_map_lookup, null_map_store);
374 
375 	/* dequote map */
376 	MAPDEF("dequote", NULL, 0,
377 		dequote_init, null_map_open, null_map_close,
378 		dequote_map, null_map_store);
379 
380 #if USERDB
381 	/* user database */
382 	MAPDEF("userdb", ".db", 0,
383 		map_parseargs, null_map_open, null_map_close,
384 		udb_map_lookup, null_map_store);
385 #endif
386 
387 	/* arbitrary programs */
388 	MAPDEF("program", NULL, MCF_ALIASOK,
389 		map_parseargs, null_map_open, null_map_close,
390 		prog_map_lookup, null_map_store);
391 
392 	/* sequenced maps */
393 	MAPDEF("sequence", NULL, MCF_ALIASOK,
394 		seq_map_parse, null_map_open, null_map_close,
395 		seq_map_lookup, seq_map_store);
396 
397 	/* switched interface to sequenced maps */
398 	MAPDEF("switch", NULL, MCF_ALIASOK,
399 		map_parseargs, switch_map_open, null_map_close,
400 		seq_map_lookup, seq_map_store);
401 }
402 
403 #undef MAPDEF
404 /*
405 **  INITHOSTMAPS -- initial host-dependent maps
406 **
407 **	This should act as an interface to any local service switch
408 **	provided by the host operating system.
409 **
410 **	Parameters:
411 **		none
412 **
413 **	Returns:
414 **		none
415 **
416 **	Side Effects:
417 **		Should define maps "host" and "users" as necessary
418 **		for this OS.  If they are not defined, they will get
419 **		a default value later.  It should check to make sure
420 **		they are not defined first, since it's possible that
421 **		the config file has provided an override.
422 */
423 
424 void
425 inithostmaps()
426 {
427 	register int i;
428 	int nmaps;
429 	char *maptype[MAXMAPSTACK];
430 	short mapreturn[MAXMAPACTIONS];
431 	char buf[MAXLINE];
432 
433 	/*
434 	**  Set up default hosts maps.
435 	*/
436 
437 #if 0
438 	nmaps = switch_map_find("hosts", maptype, mapreturn);
439 	for (i = 0; i < nmaps; i++)
440 	{
441 		if (strcmp(maptype[i], "files") == 0 &&
442 		    stab("hosts.files", ST_MAP, ST_FIND) == NULL)
443 		{
444 			strcpy(buf, "hosts.files text -k 0 -v 1 /etc/hosts");
445 			makemapentry(buf);
446 		}
447 #if NAMED_BIND
448 		else if (strcmp(maptype[i], "dns") == 0 &&
449 		    stab("hosts.dns", ST_MAP, ST_FIND) == NULL)
450 		{
451 			strcpy(buf, "hosts.dns dns A");
452 			makemapentry(buf);
453 		}
454 #endif
455 #ifdef NISPLUS
456 		else if (strcmp(maptype[i], "nisplus") == 0 &&
457 		    stab("hosts.nisplus", ST_MAP, ST_FIND) == NULL)
458 		{
459 			strcpy(buf, "hosts.nisplus nisplus -k name -v address -d hosts.org_dir");
460 			makemapentry(buf);
461 		}
462 #endif
463 #ifdef NIS
464 		else if (strcmp(maptype[i], "nis") == 0 &&
465 		    stab("hosts.nis", ST_MAP, ST_FIND) == NULL)
466 		{
467 			strcpy(buf, "hosts.nis nis -d -k 0 -v 1 hosts.byname");
468 			makemapentry(buf);
469 		}
470 #endif
471 	}
472 #endif
473 
474 	/*
475 	**  Make sure we have a host map.
476 	*/
477 
478 	if (stab("host", ST_MAP, ST_FIND) == NULL)
479 	{
480 		/* user didn't initialize: set up host map */
481 		strcpy(buf, "host host");
482 #if NAMED_BIND
483 		if (ConfigLevel >= 2)
484 			strcat(buf, " -a.");
485 #endif
486 		makemapentry(buf);
487 	}
488 
489 	/*
490 	**  Set up default aliases maps
491 	*/
492 
493 	nmaps = switch_map_find("aliases", maptype, mapreturn);
494 	for (i = 0; i < nmaps; i++)
495 	{
496 		if (strcmp(maptype[i], "files") == 0 &&
497 		    stab("aliases.files", ST_MAP, ST_FIND) == NULL)
498 		{
499 			strcpy(buf, "aliases.files implicit /etc/aliases");
500 			makemapentry(buf);
501 		}
502 #ifdef NISPLUS
503 		else if (strcmp(maptype[i], "nisplus") == 0 &&
504 		    stab("aliases.nisplus", ST_MAP, ST_FIND) == NULL)
505 		{
506 			strcpy(buf, "aliases.nisplus nisplus -kalias -vexpansion -d mail_aliases.org_dir");
507 			makemapentry(buf);
508 		}
509 #endif
510 #ifdef NIS
511 		else if (strcmp(maptype[i], "nis") == 0 &&
512 		    stab("aliases.nis", ST_MAP, ST_FIND) == NULL)
513 		{
514 			strcpy(buf, "aliases.nis nis -d mail.aliases");
515 			makemapentry(buf);
516 		}
517 #endif
518 	}
519 	if (stab("aliases", ST_MAP, ST_FIND) == NULL)
520 	{
521 		strcpy(buf, "aliases switch aliases");
522 		makemapentry(buf);
523 	}
524 	strcpy(buf, "switch:aliases");
525 	setalias(buf);
526 
527 #if 0		/* "user" map class is a better choice */
528 	/*
529 	**  Set up default users maps.
530 	*/
531 
532 	nmaps = switch_map_find("passwd", maptype, mapreturn);
533 	for (i = 0; i < nmaps; i++)
534 	{
535 		if (strcmp(maptype[i], "files") == 0 &&
536 		    stab("users.files", ST_MAP, ST_FIND) == NULL)
537 		{
538 			strcpy(buf, "users.files text -m -z: -k0 -v6 /etc/passwd");
539 			makemapentry(buf);
540 		}
541 #ifdef NISPLUS
542 		else if (strcmp(maptype[i], "nisplus") == 0 &&
543 		    stab("users.nisplus", ST_MAP, ST_FIND) == NULL)
544 		{
545 			strcpy(buf, "users.nisplus nisplus -m -kname -vhome -d passwd.org_dir");
546 			makemapentry(buf);
547 		}
548 #endif
549 #ifdef NIS
550 		else if (strcmp(maptype[i], "nis") == 0 &&
551 		    stab("users.nis", ST_MAP, ST_FIND) == NULL)
552 		{
553 			strcpy(buf, "users.nis nis -m -d passwd.byname");
554 			makemapentry(buf);
555 		}
556 #endif
557 #ifdef HESIOD
558 		else if (strcmp(maptype[i], "hesiod") == 0) &&
559 		    stab("users.hesiod", ST_MAP, ST_FIND) == NULL)
560 		{
561 			strcpy(buf, "users.hesiod hesiod");
562 			makemapentry(buf);
563 		}
564 #endif
565 	}
566 	if (stab("users", ST_MAP, ST_FIND) == NULL)
567 	{
568 		strcpy(buf, "users switch -m passwd");
569 		makemapentry(buf);
570 	}
571 #endif
572 }
573 /*
574 **  SWITCH_MAP_FIND -- find the list of types associated with a map
575 **
576 **	This is the system-dependent interface to the service switch.
577 **
578 **	Parameters:
579 **		service -- the name of the service of interest.
580 **		maptype -- an out-array of strings containing the types
581 **			of access to use for this service.  There can
582 **			be at most MAXMAPSTACK types for a single service.
583 **		mapreturn -- an out-array of return information bitmaps
584 **			for the map.
585 **
586 **	Returns:
587 **		The number of map types filled in, or -1 for failure.
588 */
589 
590 #ifdef SOLARIS
591 # include <nsswitch.h>
592 #endif
593 
594 #if defined(ultrix) || defined(__osf__)
595 # include <sys/svcinfo.h>
596 #endif
597 
598 int
599 switch_map_find(service, maptype, mapreturn)
600 	char *service;
601 	char *maptype[MAXMAPSTACK];
602 	short mapreturn[MAXMAPACTIONS];
603 {
604 	register FILE *fp;
605 	int svcno;
606 	static char buf[MAXLINE];
607 
608 #ifdef SOLARIS
609 	struct __nsw_switchconfig *nsw_conf;
610 	enum __nsw_parse_err pserr;
611 	struct __nsw_lookup *lk;
612 	int nsw_rc;
613 	static struct __nsw_lookup lkp0 =
614 		{ "files", {1, 0, 0, 0}, NULL, NULL };
615 	static struct __nsw_switchconfig lkp_default =
616 		{ 0, "sendmail", 3, &lkp0 };
617 
618 	if ((nsw_conf = __nsw_getconfig(service, &pserr)) == NULL)
619 		lk = lkp_default.lookups;
620 	else
621 		lk = nsw_conf->lookups;
622 	svcno = 0;
623 	while (lk != NULL)
624 	{
625 		maptype[svcno] = lk->service_name;
626 		if (lk->actions[__NSW_NOTFOUND] == __NSW_RETURN)
627 			mapreturn[MA_NOTFOUND] |= 1 << svcno;
628 		if (lk->actions[__NSW_TRYAGAIN] == __NSW_RETURN)
629 			mapreturn[MA_TRYAGAIN] |= 1 << svcno;
630 		if (lk->actions[__NSW_UNAVAIL] == __NSW_RETURN)
631 			mapreturn[MA_TRYAGAIN] |= 1 << svcno;
632 		svcno++;
633 		lk = lk->next;
634 	}
635 	return svcno;
636 #endif
637 
638 #if defined(ultrix) || defined(__osf__)
639 	struct svcinfo *svcinfo;
640 	int svc;
641 
642 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
643 		mapreturn[svcno] = 0;
644 
645 	svcinfo = getsvc();
646 	if (svcinfo == NULL)
647 		goto punt;
648 	if (strcmp(service, "hosts") == 0)
649 		svc = SVC_HOSTS;
650 	else if (strcmp(service, "aliases") == 0)
651 		svc = SVC_ALIASES;
652 	else if (strcmp(service, "passwd") == 0)
653 		svc = SVC_PASSWD;
654 	else
655 		return -1;
656 	for (svcno = 0; svcno < SVC_PATHSIZE; svcno++)
657 	{
658 		switch (svcinfo->svcpath[svc][svcno])
659 		{
660 		  case SVC_LOCAL:
661 			maptype[svcno] = "files";
662 			break;
663 
664 		  case SVC_YP:
665 			maptype[svcno] = "nis";
666 			break;
667 
668 		  case SVC_BIND:
669 			maptype[svcno] = "dns";
670 			break;
671 
672 #ifdef SVC_HESIOD
673 		  case SVC_HESIOD:
674 			maptype[svcno] = "hesiod";
675 			break;
676 #endif
677 
678 		  case SVC_LAST:
679 			return svcno;
680 		}
681 	}
682 	return svcno;
683 #endif
684 
685 #if !defined(SOLARIS) && !defined(ultrix) && !defined(__osf__)
686 	/*
687 	**  Fall-back mechanism.
688 	*/
689 
690 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
691 		mapreturn[svcno] = 0;
692 
693 	svcno = 0;
694 	fp = fopen(ServiceSwitchFile, "r");
695 	if (fp != NULL)
696 	{
697 		while (fgets(buf, sizeof buf, fp) != NULL)
698 		{
699 			register char *p;
700 
701 			p = strpbrk(buf, "#\n");
702 			if (p != NULL)
703 				*p = '\0';
704 			p = strpbrk(buf, " \t");
705 			if (p != NULL)
706 				*p++ = '\0';
707 			if (strcmp(buf, service) != 0)
708 				continue;
709 
710 			/* got the right service -- extract data */
711 			do
712 			{
713 				while (isspace(*p))
714 					p++;
715 				if (*p == '\0')
716 					break;
717 				maptype[svcno++] = p;
718 				p = strpbrk(p, " \t");
719 				if (p != NULL)
720 					*p++ = '\0';
721 			} while (p != NULL);
722 			break;
723 		}
724 		fclose(fp);
725 		return svcno;
726 	}
727 #endif
728 
729 	/* if the service file doesn't work, use an absolute fallback */
730   punt:
731 	for (svcno = 0; svcno < MAXMAPACTIONS; svcno++)
732 		mapreturn[svcno] = 0;
733 	svcno = 0;
734 	if (strcmp(service, "aliases") == 0)
735 	{
736 		maptype[svcno++] = "files";
737 #ifdef AUTO_NIS_ALIASES
738 # ifdef NISPLUS
739 		maptype[svcno++] = "nisplus";
740 # endif
741 # ifdef NIS
742 		maptype[svcno++] = "nis";
743 # endif
744 #endif
745 		return svcno;
746 	}
747 	if (strcmp(service, "hosts") == 0)
748 	{
749 # if NAMED_BIND
750 		maptype[svcno++] = "dns";
751 # else
752 #  if defined(sun) && !defined(BSD) && !defined(SOLARIS)
753 		/* SunOS */
754 		maptype[svcno++] = "nis";
755 #  endif
756 # endif
757 		maptype[svcno++] = "files";
758 		return svcno;
759 	}
760 	return -1;
761 }
762 /*
763 **  USERNAME -- return the user id of the logged in user.
764 **
765 **	Parameters:
766 **		none.
767 **
768 **	Returns:
769 **		The login name of the logged in user.
770 **
771 **	Side Effects:
772 **		none.
773 **
774 **	Notes:
775 **		The return value is statically allocated.
776 */
777 
778 char *
779 username()
780 {
781 	static char *myname = NULL;
782 	extern char *getlogin();
783 	register struct passwd *pw;
784 
785 	/* cache the result */
786 	if (myname == NULL)
787 	{
788 		myname = getlogin();
789 		if (myname == NULL || myname[0] == '\0')
790 		{
791 			pw = sm_getpwuid(RealUid);
792 			if (pw != NULL)
793 				myname = newstr(pw->pw_name);
794 		}
795 		else
796 		{
797 			uid_t uid = RealUid;
798 
799 			myname = newstr(myname);
800 			if ((pw = sm_getpwnam(myname)) == NULL ||
801 			      (uid != 0 && uid != pw->pw_uid))
802 			{
803 				pw = sm_getpwuid(uid);
804 				if (pw != NULL)
805 					myname = newstr(pw->pw_name);
806 			}
807 		}
808 		if (myname == NULL || myname[0] == '\0')
809 		{
810 			syserr("554 Who are you?");
811 			myname = "postmaster";
812 		}
813 	}
814 
815 	return (myname);
816 }
817 /*
818 **  TTYPATH -- Get the path of the user's tty
819 **
820 **	Returns the pathname of the user's tty.  Returns NULL if
821 **	the user is not logged in or if s/he has write permission
822 **	denied.
823 **
824 **	Parameters:
825 **		none
826 **
827 **	Returns:
828 **		pathname of the user's tty.
829 **		NULL if not logged in or write permission denied.
830 **
831 **	Side Effects:
832 **		none.
833 **
834 **	WARNING:
835 **		Return value is in a local buffer.
836 **
837 **	Called By:
838 **		savemail
839 */
840 
841 char *
842 ttypath()
843 {
844 	struct stat stbuf;
845 	register char *pathn;
846 	extern char *ttyname();
847 	extern char *getlogin();
848 
849 	/* compute the pathname of the controlling tty */
850 	if ((pathn = ttyname(2)) == NULL && (pathn = ttyname(1)) == NULL &&
851 	    (pathn = ttyname(0)) == NULL)
852 	{
853 		errno = 0;
854 		return (NULL);
855 	}
856 
857 	/* see if we have write permission */
858 	if (stat(pathn, &stbuf) < 0 || !bitset(02, stbuf.st_mode))
859 	{
860 		errno = 0;
861 		return (NULL);
862 	}
863 
864 	/* see if the user is logged in */
865 	if (getlogin() == NULL)
866 		return (NULL);
867 
868 	/* looks good */
869 	return (pathn);
870 }
871 /*
872 **  CHECKCOMPAT -- check for From and To person compatible.
873 **
874 **	This routine can be supplied on a per-installation basis
875 **	to determine whether a person is allowed to send a message.
876 **	This allows restriction of certain types of internet
877 **	forwarding or registration of users.
878 **
879 **	If the hosts are found to be incompatible, an error
880 **	message should be given using "usrerr" and an EX_ code
881 **	should be returned.  You can also set to->q_status to
882 **	a DSN-style status code.
883 **
884 **	EF_NO_BODY_RETN can be set in e->e_flags to suppress the
885 **	body during the return-to-sender function; this should be done
886 **	on huge messages.  This bit may already be set by the ESMTP
887 **	protocol.
888 **
889 **	Parameters:
890 **		to -- the person being sent to.
891 **
892 **	Returns:
893 **		an exit status
894 **
895 **	Side Effects:
896 **		none (unless you include the usrerr stuff)
897 */
898 
899 int
900 checkcompat(to, e)
901 	register ADDRESS *to;
902 	register ENVELOPE *e;
903 {
904 # ifdef lint
905 	if (to == NULL)
906 		to++;
907 # endif /* lint */
908 
909 	if (tTd(49, 1))
910 		printf("checkcompat(to=%s, from=%s)\n",
911 			to->q_paddr, e->e_from.q_paddr);
912 
913 # ifdef EXAMPLE_CODE
914 	/* this code is intended as an example only */
915 	register STAB *s;
916 
917 	s = stab("arpa", ST_MAILER, ST_FIND);
918 	if (s != NULL && strcmp(e->e_from.q_mailer->m_name, "local") != 0 &&
919 	    to->q_mailer == s->s_mailer)
920 	{
921 		usrerr("553 No ARPA mail through this machine: see your system administration");
922 		/* e->e_flags |= EF_NO_BODY_RETN; to supress body on return */
923 		to->q_status = "5.7.1";
924 		return (EX_UNAVAILABLE);
925 	}
926 # endif /* EXAMPLE_CODE */
927 	return (EX_OK);
928 }
929 /*
930 **  SETSIGNAL -- set a signal handler
931 **
932 **	This is essentially old BSD "signal(3)".
933 */
934 
935 sigfunc_t
936 setsignal(sig, handler)
937 	int sig;
938 	sigfunc_t handler;
939 {
940 #if defined(SYS5SIGNALS) || defined(BSD4_3) || defined(_AUX_SOURCE)
941 	return signal(sig, handler);
942 #else
943 	struct sigaction n, o;
944 
945 	bzero(&n, sizeof n);
946 	n.sa_handler = handler;
947 # ifdef SA_RESTART
948 	n.sa_flags = SA_RESTART;
949 # endif
950 	if (sigaction(sig, &n, &o) < 0)
951 		return SIG_ERR;
952 	return o.sa_handler;
953 #endif
954 }
955 /*
956 **  HOLDSIGS -- arrange to hold all signals
957 **
958 **	Parameters:
959 **		none.
960 **
961 **	Returns:
962 **		none.
963 **
964 **	Side Effects:
965 **		Arranges that signals are held.
966 */
967 
968 void
969 holdsigs()
970 {
971 }
972 /*
973 **  RLSESIGS -- arrange to release all signals
974 **
975 **	This undoes the effect of holdsigs.
976 **
977 **	Parameters:
978 **		none.
979 **
980 **	Returns:
981 **		none.
982 **
983 **	Side Effects:
984 **		Arranges that signals are released.
985 */
986 
987 void
988 rlsesigs()
989 {
990 }
991 /*
992 **  INIT_MD -- do machine dependent initializations
993 **
994 **	Systems that have global modes that should be set should do
995 **	them here rather than in main.
996 */
997 
998 #ifdef _AUX_SOURCE
999 # include	<compat.h>
1000 #endif
1001 
1002 void
1003 init_md(argc, argv)
1004 	int argc;
1005 	char **argv;
1006 {
1007 #ifdef _AUX_SOURCE
1008 	setcompat(getcompat() | COMPAT_BSDPROT);
1009 #endif
1010 
1011 #ifdef VENDOR_DEFAULT
1012 	VendorCode = VENDOR_DEFAULT;
1013 #else
1014 	VendorCode = VENDOR_BERKELEY;
1015 #endif
1016 }
1017 /*
1018 **  INIT_VENDOR_MACROS -- vendor-dependent macro initializations
1019 **
1020 **	Called once, on startup.
1021 **
1022 **	Parameters:
1023 **		e -- the global envelope.
1024 **
1025 **	Returns:
1026 **		none.
1027 **
1028 **	Side Effects:
1029 **		vendor-dependent.
1030 */
1031 
1032 void
1033 init_vendor_macros(e)
1034 	register ENVELOPE *e;
1035 {
1036 }
1037 /*
1038 **  GETLA -- get the current load average
1039 **
1040 **	This code stolen from la.c.
1041 **
1042 **	Parameters:
1043 **		none.
1044 **
1045 **	Returns:
1046 **		The current load average as an integer.
1047 **
1048 **	Side Effects:
1049 **		none.
1050 */
1051 
1052 /* try to guess what style of load average we have */
1053 #define LA_ZERO		1	/* always return load average as zero */
1054 #define LA_INT		2	/* read kmem for avenrun; interpret as long */
1055 #define LA_FLOAT	3	/* read kmem for avenrun; interpret as float */
1056 #define LA_SUBR		4	/* call getloadavg */
1057 #define LA_MACH		5	/* MACH load averages (as on NeXT boxes) */
1058 #define LA_SHORT	6	/* read kmem for avenrun; interpret as short */
1059 #define LA_PROCSTR	7	/* read string ("1.17") from /proc/loadavg */
1060 #define LA_READKSYM	8	/* SVR4: use MIOC_READKSYM ioctl call */
1061 #define LA_DGUX		9	/* special DGUX implementation */
1062 #define LA_HPUX		10	/* special HPUX implementation */
1063 
1064 /* do guesses based on general OS type */
1065 #ifndef LA_TYPE
1066 # define LA_TYPE	LA_ZERO
1067 #endif
1068 
1069 #ifndef FSHIFT
1070 # if defined(unixpc)
1071 #  define FSHIFT	5
1072 # endif
1073 
1074 # if defined(__alpha) || defined(IRIX)
1075 #  define FSHIFT	10
1076 # endif
1077 
1078 # if defined(_AIX3)
1079 #  define FSHIFT	16
1080 # endif
1081 #endif
1082 
1083 #ifndef FSHIFT
1084 # define FSHIFT		8
1085 #endif
1086 
1087 #ifndef FSCALE
1088 # define FSCALE		(1 << FSHIFT)
1089 #endif
1090 
1091 #ifndef LA_AVENRUN
1092 # ifdef SYSTEM5
1093 #  define LA_AVENRUN	"avenrun"
1094 # else
1095 #  define LA_AVENRUN	"_avenrun"
1096 # endif
1097 #endif
1098 
1099 #if (LA_TYPE == LA_INT) || (LA_TYPE == LA_FLOAT) || (LA_TYPE == LA_SHORT)
1100 
1101 #include <nlist.h>
1102 
1103 #ifdef IRIX64
1104 # define nlist		nlist64
1105 #endif
1106 
1107 /* _PATH_UNIX should be defined in <paths.h> */
1108 #ifndef _PATH_UNIX
1109 # if defined(SYSTEM5)
1110 #  define _PATH_UNIX	"/unix"
1111 # else
1112 #  define _PATH_UNIX	"/vmunix"
1113 # endif
1114 #endif
1115 
1116 struct nlist	Nl[] =
1117 {
1118 	{ LA_AVENRUN },
1119 #define	X_AVENRUN	0
1120 	{ 0 },
1121 };
1122 
1123 getla()
1124 {
1125 	static int kmem = -1;
1126 #if LA_TYPE == LA_INT
1127 	long avenrun[3];
1128 #else
1129 # if LA_TYPE == LA_SHORT
1130 	short avenrun[3];
1131 # else
1132 	double avenrun[3];
1133 # endif
1134 #endif
1135 	extern int errno;
1136 	extern off_t lseek();
1137 
1138 	if (kmem < 0)
1139 	{
1140 		kmem = open("/dev/kmem", 0, 0);
1141 		if (kmem < 0)
1142 		{
1143 			if (tTd(3, 1))
1144 				printf("getla: open(/dev/kmem): %s\n",
1145 					errstring(errno));
1146 			return (-1);
1147 		}
1148 		(void) fcntl(kmem, F_SETFD, 1);
1149 
1150 #ifdef _AIX3
1151 		if (knlist(Nl, 1, sizeof Nl[0]) < 0)
1152 #else
1153 		if (nlist(_PATH_UNIX, Nl) < 0)
1154 #endif
1155 		{
1156 			if (tTd(3, 1))
1157 				printf("getla: nlist(%s): %s\n", _PATH_UNIX,
1158 					errstring(errno));
1159 			return (-1);
1160 		}
1161 		if (Nl[X_AVENRUN].n_value == 0)
1162 		{
1163 			if (tTd(3, 1))
1164 				printf("getla: nlist(%s, %s) ==> 0\n",
1165 					_PATH_UNIX, LA_AVENRUN);
1166 			return (-1);
1167 		}
1168 #ifdef NAMELISTMASK
1169 		Nl[X_AVENRUN].n_value &= NAMELISTMASK;
1170 #endif
1171 	}
1172 	if (tTd(3, 20))
1173 		printf("getla: symbol address = %#x\n", Nl[X_AVENRUN].n_value);
1174 	if (lseek(kmem, (off_t) Nl[X_AVENRUN].n_value, SEEK_SET) == -1 ||
1175 	    read(kmem, (char *) avenrun, sizeof(avenrun)) < sizeof(avenrun))
1176 	{
1177 		/* thank you Ian */
1178 		if (tTd(3, 1))
1179 			printf("getla: lseek or read: %s\n", errstring(errno));
1180 		return (-1);
1181 	}
1182 # if (LA_TYPE == LA_INT) || (LA_TYPE == LA_SHORT)
1183 	if (tTd(3, 5))
1184 	{
1185 		printf("getla: avenrun = %d", avenrun[0]);
1186 		if (tTd(3, 15))
1187 			printf(", %d, %d", avenrun[1], avenrun[2]);
1188 		printf("\n");
1189 	}
1190 	if (tTd(3, 1))
1191 		printf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1192 	return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1193 # else /* LA_TYPE == LA_FLOAT */
1194 	if (tTd(3, 5))
1195 	{
1196 		printf("getla: avenrun = %g", avenrun[0]);
1197 		if (tTd(3, 15))
1198 			printf(", %g, %g", avenrun[1], avenrun[2]);
1199 		printf("\n");
1200 	}
1201 	if (tTd(3, 1))
1202 		printf("getla: %d\n", (int) (avenrun[0] +0.5));
1203 	return ((int) (avenrun[0] + 0.5));
1204 # endif
1205 }
1206 
1207 #endif /* LA_TYPE == LA_INT or LA_SHORT or LA_FLOAT */
1208 
1209 #if LA_TYPE == LA_READKSYM
1210 
1211 # include <sys/ksym.h>
1212 
1213 getla()
1214 {
1215 	static int kmem = -1;
1216 	long avenrun[3];
1217 	extern int errno;
1218 	struct mioc_rksym mirk;
1219 
1220 	if (kmem < 0)
1221 	{
1222 		kmem = open("/dev/kmem", 0, 0);
1223 		if (kmem < 0)
1224 		{
1225 			if (tTd(3, 1))
1226 				printf("getla: open(/dev/kmem): %s\n",
1227 					errstring(errno));
1228 			return (-1);
1229 		}
1230 		(void) fcntl(kmem, F_SETFD, 1);
1231 	}
1232 	mirk.mirk_symname = LA_AVENRUN;
1233 	mirk.mirk_buf = avenrun;
1234 	mirk.mirk_buflen = sizeof(avenrun);
1235 	if (ioctl(kmem, MIOC_READKSYM, &mirk) < 0)
1236 	{
1237 		if (tTd(3, 1))
1238 			printf("getla: ioctl(MIOC_READKSYM) failed: %s\n",
1239 				errstring(errno));
1240 		return -1;
1241 	}
1242 	if (tTd(3, 5))
1243 	{
1244 		printf("getla: avenrun = %d", avenrun[0]);
1245 		if (tTd(3, 15))
1246 			printf(", %d, %d", avenrun[1], avenrun[2]);
1247 		printf("\n");
1248 	}
1249 	if (tTd(3, 1))
1250 		printf("getla: %d\n", (int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1251 	return ((int) (avenrun[0] + FSCALE/2) >> FSHIFT);
1252 }
1253 
1254 #endif /* LA_TYPE == LA_READKSYM */
1255 
1256 #if LA_TYPE == LA_DGUX
1257 
1258 # include <sys/dg_sys_info.h>
1259 
1260 int
1261 getla()
1262 {
1263 	struct dg_sys_info_load_info load_info;
1264 
1265 	dg_sys_info((long *)&load_info,
1266 		DG_SYS_INFO_LOAD_INFO_TYPE, DG_SYS_INFO_LOAD_VERSION_0);
1267 
1268         if (tTd(3, 1))
1269                 printf("getla: %d\n", (int) (load_info.one_minute + 0.5));
1270 
1271 	return((int) (load_info.one_minute + 0.5));
1272 }
1273 
1274 #endif /* LA_TYPE == LA_DGUX */
1275 
1276 #if LA_TYPE == LA_HPUX
1277 
1278 /* forward declarations to keep gcc from complaining */
1279 struct pst_dynamic;
1280 struct pst_status;
1281 struct pst_static;
1282 struct pst_vminfo;
1283 struct pst_diskinfo;
1284 struct pst_processor;
1285 struct pst_lv;
1286 struct pst_swapinfo;
1287 
1288 # include <sys/param.h>
1289 # include <sys/pstat.h>
1290 
1291 int
1292 getla()
1293 {
1294 	struct pst_dynamic pstd;
1295 
1296 	if (pstat_getdynamic(&pstd, sizeof(struct pst_dynamic),
1297 			     (size_t) 1, 0) == -1)
1298 		return 0;
1299 
1300         if (tTd(3, 1))
1301                 printf("getla: %d\n", (int) (pstd.psd_avg_1_min + 0.5));
1302 
1303 	return (int) (pstd.psd_avg_1_min + 0.5);
1304 }
1305 
1306 #endif /* LA_TYPE == LA_HPUX */
1307 
1308 #if LA_TYPE == LA_SUBR
1309 
1310 int
1311 getla()
1312 {
1313 	double avenrun[3];
1314 
1315 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) < 0)
1316 	{
1317 		if (tTd(3, 1))
1318 			perror("getla: getloadavg failed:");
1319 		return (-1);
1320 	}
1321 	if (tTd(3, 1))
1322 		printf("getla: %d\n", (int) (avenrun[0] +0.5));
1323 	return ((int) (avenrun[0] + 0.5));
1324 }
1325 
1326 #endif /* LA_TYPE == LA_SUBR */
1327 
1328 #if LA_TYPE == LA_MACH
1329 
1330 /*
1331 **  This has been tested on NEXTSTEP release 2.1/3.X.
1332 */
1333 
1334 #if defined(NX_CURRENT_COMPILER_RELEASE) && NX_CURRENT_COMPILER_RELEASE > NX_COMPILER_RELEASE_3_0
1335 # include <mach/mach.h>
1336 #else
1337 # include <mach.h>
1338 #endif
1339 
1340 getla()
1341 {
1342 	processor_set_t default_set;
1343 	kern_return_t error;
1344 	unsigned int info_count;
1345 	struct processor_set_basic_info info;
1346 	host_t host;
1347 
1348 	error = processor_set_default(host_self(), &default_set);
1349 	if (error != KERN_SUCCESS)
1350 		return -1;
1351 	info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
1352 	if (processor_set_info(default_set, PROCESSOR_SET_BASIC_INFO,
1353 			       &host, (processor_set_info_t)&info,
1354 			       &info_count) != KERN_SUCCESS)
1355 	{
1356 		return -1;
1357 	}
1358 	return (int) (info.load_average + (LOAD_SCALE / 2)) / LOAD_SCALE;
1359 }
1360 
1361 #endif /* LA_TYPE == LA_MACH */
1362 
1363 #if LA_TYPE == LA_PROCSTR
1364 
1365 /*
1366 **  Read /proc/loadavg for the load average.  This is assumed to be
1367 **  in a format like "0.15 0.12 0.06".
1368 **
1369 **	Initially intended for Linux.  This has been in the kernel
1370 **	since at least 0.99.15.
1371 */
1372 
1373 # ifndef _PATH_LOADAVG
1374 #  define _PATH_LOADAVG	"/proc/loadavg"
1375 # endif
1376 
1377 int
1378 getla()
1379 {
1380 	double avenrun;
1381 	register int result;
1382 	FILE *fp;
1383 
1384 	fp = fopen(_PATH_LOADAVG, "r");
1385 	if (fp == NULL)
1386 	{
1387 		if (tTd(3, 1))
1388 			printf("getla: fopen(%s): %s\n",
1389 				_PATH_LOADAVG, errstring(errno));
1390 		return -1;
1391 	}
1392 	result = fscanf(fp, "%lf", &avenrun);
1393 	fclose(fp);
1394 	if (result != 1)
1395 	{
1396 		if (tTd(3, 1))
1397 			printf("getla: fscanf() = %d: %s\n",
1398 				result, errstring(errno));
1399 		return -1;
1400 	}
1401 
1402 	if (tTd(3, 1))
1403 		printf("getla(): %.2f\n", avenrun);
1404 
1405 	return ((int) (avenrun + 0.5));
1406 }
1407 
1408 #endif /* LA_TYPE == LA_PROCSTR */
1409 
1410 #if LA_TYPE == LA_ZERO
1411 
1412 getla()
1413 {
1414 	if (tTd(3, 1))
1415 		printf("getla: ZERO\n");
1416 	return (0);
1417 }
1418 
1419 #endif /* LA_TYPE == LA_ZERO */
1420 
1421 
1422 /*
1423  * Copyright 1989 Massachusetts Institute of Technology
1424  *
1425  * Permission to use, copy, modify, distribute, and sell this software and its
1426  * documentation for any purpose is hereby granted without fee, provided that
1427  * the above copyright notice appear in all copies and that both that
1428  * copyright notice and this permission notice appear in supporting
1429  * documentation, and that the name of M.I.T. not be used in advertising or
1430  * publicity pertaining to distribution of the software without specific,
1431  * written prior permission.  M.I.T. makes no representations about the
1432  * suitability of this software for any purpose.  It is provided "as is"
1433  * without express or implied warranty.
1434  *
1435  * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
1436  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T.
1437  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1438  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
1439  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1440  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1441  *
1442  * Authors:  Many and varied...
1443  */
1444 
1445 /* Non Apollo stuff removed by Don Lewis 11/15/93 */
1446 #ifndef lint
1447 static char  rcsid[] = "@(#)$Id: getloadavg.c,v 1.16 1991/06/21 12:51:15 paul Exp $";
1448 #endif /* !lint */
1449 
1450 #ifdef apollo
1451 # undef volatile
1452 #    include <apollo/base.h>
1453 
1454 /* ARGSUSED */
1455 int getloadavg( call_data )
1456      caddr_t	call_data;	/* pointer to (double) return value */
1457 {
1458      double *avenrun = (double *) call_data;
1459      int i;
1460      status_$t      st;
1461      long loadav[3];
1462      proc1_$get_loadav(loadav, &st);
1463      *avenrun = loadav[0] / (double) (1 << 16);
1464      return(0);
1465 }
1466 #   endif /* apollo */
1467 /*
1468 **  SHOULDQUEUE -- should this message be queued or sent?
1469 **
1470 **	Compares the message cost to the load average to decide.
1471 **
1472 **	Parameters:
1473 **		pri -- the priority of the message in question.
1474 **		ctime -- the message creation time.
1475 **
1476 **	Returns:
1477 **		TRUE -- if this message should be queued up for the
1478 **			time being.
1479 **		FALSE -- if the load is low enough to send this message.
1480 **
1481 **	Side Effects:
1482 **		none.
1483 */
1484 
1485 bool
1486 shouldqueue(pri, ctime)
1487 	long pri;
1488 	time_t ctime;
1489 {
1490 	bool rval;
1491 
1492 	if (tTd(3, 30))
1493 		printf("shouldqueue: CurrentLA=%d, pri=%d: ", CurrentLA, pri);
1494 	if (CurrentLA < QueueLA)
1495 	{
1496 		if (tTd(3, 30))
1497 			printf("FALSE (CurrentLA < QueueLA)\n");
1498 		return (FALSE);
1499 	}
1500 	if (CurrentLA >= RefuseLA)
1501 	{
1502 		if (tTd(3, 30))
1503 			printf("TRUE (CurrentLA >= RefuseLA)\n");
1504 		return (TRUE);
1505 	}
1506 	rval = pri > (QueueFactor / (CurrentLA - QueueLA + 1));
1507 	if (tTd(3, 30))
1508 		printf("%s (by calculation)\n", rval ? "TRUE" : "FALSE");
1509 	return rval;
1510 }
1511 /*
1512 **  REFUSECONNECTIONS -- decide if connections should be refused
1513 **
1514 **	Parameters:
1515 **		none.
1516 **
1517 **	Returns:
1518 **		TRUE if incoming SMTP connections should be refused
1519 **			(for now).
1520 **		FALSE if we should accept new work.
1521 **
1522 **	Side Effects:
1523 **		none.
1524 */
1525 
1526 bool
1527 refuseconnections()
1528 {
1529 	extern bool enoughspace();
1530 
1531 #ifdef XLA
1532 	if (!xla_smtp_ok())
1533 		return TRUE;
1534 #endif
1535 
1536 	/* this is probably too simplistic */
1537 	return CurrentLA >= RefuseLA || !enoughspace(MinBlocksFree + 1);
1538 }
1539 /*
1540 **  SETPROCTITLE -- set process title for ps
1541 **
1542 **	Parameters:
1543 **		fmt -- a printf style format string.
1544 **		a, b, c -- possible parameters to fmt.
1545 **
1546 **	Returns:
1547 **		none.
1548 **
1549 **	Side Effects:
1550 **		Clobbers argv of our main procedure so ps(1) will
1551 **		display the title.
1552 */
1553 
1554 #define SPT_NONE	0	/* don't use it at all */
1555 #define SPT_REUSEARGV	1	/* cover argv with title information */
1556 #define SPT_BUILTIN	2	/* use libc builtin */
1557 #define SPT_PSTAT	3	/* use pstat(PSTAT_SETCMD, ...) */
1558 #define SPT_PSSTRINGS	4	/* use PS_STRINGS->... */
1559 #define SPT_SYSMIPS	5	/* use sysmips() supported by NEWS-OS 6 */
1560 
1561 #ifndef SPT_TYPE
1562 # define SPT_TYPE	SPT_REUSEARGV
1563 #endif
1564 
1565 #if SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN
1566 
1567 # if SPT_TYPE == SPT_PSTAT
1568 #  include <sys/pstat.h>
1569 # endif
1570 # if SPT_TYPE == SPT_PSSTRINGS
1571 #  include <machine/vmparam.h>
1572 #  include <sys/exec.h>
1573 #  ifndef PS_STRINGS	/* hmmmm....  apparently not available after all */
1574 #   undef SPT_TYPE
1575 #   define SPT_TYPE	SPT_REUSEARGV
1576 #  else
1577 #   ifndef NKPDE			/* FreeBSD 2.0 */
1578 #    define NKPDE 63
1579 typedef unsigned int	*pt_entry_t;
1580 #   endif
1581 #  endif
1582 # endif
1583 
1584 # if SPT_TYPE == SPT_PSSTRINGS
1585 #  define SETPROC_STATIC	static
1586 # else
1587 #  define SETPROC_STATIC
1588 # endif
1589 
1590 # if SPT_TYPE == SPT_SYSMIPS
1591 #  include <sys/sysmips.h>
1592 #  include <sys/sysnews.h>
1593 # endif
1594 
1595 # ifndef SPT_PADCHAR
1596 #  define SPT_PADCHAR	' '
1597 # endif
1598 
1599 #endif /* SPT_TYPE != SPT_NONE && SPT_TYPE != SPT_BUILTIN */
1600 
1601 #if SPT_TYPE != SPT_BUILTIN
1602 
1603 /*VARARGS1*/
1604 void
1605 # ifdef __STDC__
1606 setproctitle(char *fmt, ...)
1607 # else
1608 setproctitle(fmt, va_alist)
1609 	char *fmt;
1610 	va_dcl
1611 # endif
1612 {
1613 # if SPT_TYPE != SPT_NONE
1614 	register char *p;
1615 	register int i;
1616 	SETPROC_STATIC char buf[MAXLINE];
1617 	VA_LOCAL_DECL
1618 #  if SPT_TYPE == SPT_PSTAT
1619 	union pstun pst;
1620 #  endif
1621 #  if SPT_TYPE == SPT_REUSEARGV
1622 	extern char **Argv;
1623 	extern char *LastArgv;
1624 #  endif
1625 
1626 	p = buf;
1627 
1628 	/* print sendmail: heading for grep */
1629 	(void) strcpy(p, "sendmail: ");
1630 	p += strlen(p);
1631 
1632 	/* print the argument string */
1633 	VA_START(fmt);
1634 	(void) vsprintf(p, fmt, ap);
1635 	VA_END;
1636 
1637 	i = strlen(buf);
1638 
1639 #  if SPT_TYPE == SPT_PSTAT
1640 	pst.pst_command = buf;
1641 	pstat(PSTAT_SETCMD, pst, i, 0, 0);
1642 #  endif
1643 #  if SPT_TYPE == SPT_PSSTRINGS
1644 	PS_STRINGS->ps_nargvstr = 1;
1645 	PS_STRINGS->ps_argvstr = buf;
1646 #  endif
1647 #  if SPT_TYPE == SPT_SYSMIPS
1648 	sysmips(SONY_SYSNEWS, NEWS_SETPSARGS, buf);
1649 #  endif
1650 #  if SPT_TYPE == SPT_REUSEARGV
1651 	if (i > LastArgv - Argv[0] - 2)
1652 	{
1653 		i = LastArgv - Argv[0] - 2;
1654 		buf[i] = '\0';
1655 	}
1656 	(void) strcpy(Argv[0], buf);
1657 	p = &Argv[0][i];
1658 	while (p < LastArgv)
1659 		*p++ = SPT_PADCHAR;
1660 	Argv[1] = NULL;
1661 #  endif
1662 # endif /* SPT_TYPE != SPT_NONE */
1663 }
1664 
1665 #endif /* SPT_TYPE != SPT_BUILTIN */
1666 /*
1667 **  REAPCHILD -- pick up the body of my child, lest it become a zombie
1668 **
1669 **	Parameters:
1670 **		sig -- the signal that got us here (unused).
1671 **
1672 **	Returns:
1673 **		none.
1674 **
1675 **	Side Effects:
1676 **		Picks up extant zombies.
1677 */
1678 
1679 void
1680 reapchild(sig)
1681 	int sig;
1682 {
1683 	int olderrno = errno;
1684 # ifdef HASWAITPID
1685 	auto int status;
1686 	int count;
1687 	int pid;
1688 
1689 	count = 0;
1690 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1691 	{
1692 		if (count++ > 1000)
1693 		{
1694 #ifdef LOG
1695 			syslog(LOG_ALERT, "reapchild: waitpid loop: pid=%d, status=%x",
1696 				pid, status);
1697 #endif
1698 			break;
1699 		}
1700 	}
1701 # else
1702 # ifdef WNOHANG
1703 	union wait status;
1704 
1705 	while (wait3(&status, WNOHANG, (struct rusage *) NULL) > 0)
1706 		continue;
1707 # else /* WNOHANG */
1708 	auto int status;
1709 
1710 	while (wait(&status) > 0)
1711 		continue;
1712 # endif /* WNOHANG */
1713 # endif
1714 # ifdef SYS5SIGNALS
1715 	(void) setsignal(SIGCHLD, reapchild);
1716 # endif
1717 	errno = olderrno;
1718 }
1719 /*
1720 **  PUTENV -- emulation of putenv() in terms of setenv()
1721 **
1722 **	Not needed on Posix-compliant systems.
1723 **	This doesn't have full Posix semantics, but it's good enough
1724 **		for sendmail.
1725 **
1726 **	Parameter:
1727 **		env -- the environment to put.
1728 **
1729 **	Returns:
1730 **		none.
1731 */
1732 
1733 #ifdef NEEDPUTENV
1734 
1735 # if NEEDPUTENV == 2		/* no setenv(3) call available */
1736 
1737 int
1738 putenv(str)
1739 	char *str;
1740 {
1741 	char **current;
1742 	int matchlen, envlen=0;
1743 	char *tmp;
1744 	char **newenv;
1745 	static int first=1;
1746 	extern char **environ;
1747 
1748 	/*
1749 	 * find out how much of str to match when searching
1750 	 * for a string to replace.
1751 	 */
1752 	if ((tmp = index(str, '=')) == NULL || tmp == str)
1753 		matchlen = strlen(str);
1754 	else
1755 		matchlen = (int) (tmp - str);
1756 	++matchlen;
1757 
1758 	/*
1759 	 * Search for an existing string in the environment and find the
1760 	 * length of environ.  If found, replace and exit.
1761 	 */
1762 	for (current=environ; *current; current++) {
1763 		++envlen;
1764 
1765 		if (strncmp(str, *current, matchlen) == 0) {
1766 			/* found it, now insert the new version */
1767 			*current = (char *)str;
1768 			return(0);
1769 		}
1770 	}
1771 
1772 	/*
1773 	 * There wasn't already a slot so add space for a new slot.
1774 	 * If this is our first time through, use malloc(), else realloc().
1775 	 */
1776 	if (first) {
1777 		newenv = (char **) malloc(sizeof(char *) * (envlen + 2));
1778 		if (newenv == NULL)
1779 			return(-1);
1780 
1781 		first=0;
1782 		(void) memcpy(newenv, environ, sizeof(char *) * envlen);
1783 	} else {
1784 		newenv = (char **) realloc((char *)environ, sizeof(char *) * (envlen + 2));
1785 		if (newenv == NULL)
1786 			return(-1);
1787 	}
1788 
1789 	/* actually add in the new entry */
1790 	environ = newenv;
1791 	environ[envlen] = (char *)str;
1792 	environ[envlen+1] = NULL;
1793 
1794 	return(0);
1795 }
1796 
1797 #else			/* implement putenv() in terms of setenv() */
1798 
1799 int
1800 putenv(env)
1801 	char *env;
1802 {
1803 	char *p;
1804 	int l;
1805 	char nbuf[100];
1806 
1807 	p = strchr(env, '=');
1808 	if (p == NULL)
1809 		return 0;
1810 	l = p - env;
1811 	if (l > sizeof nbuf - 1)
1812 		l = sizeof nbuf - 1;
1813 	bcopy(env, nbuf, l);
1814 	nbuf[l] = '\0';
1815 	return setenv(nbuf, ++p, 1);
1816 }
1817 
1818 # endif
1819 #endif
1820 /*
1821 **  UNSETENV -- remove a variable from the environment
1822 **
1823 **	Not needed on newer systems.
1824 **
1825 **	Parameters:
1826 **		name -- the string name of the environment variable to be
1827 **			deleted from the current environment.
1828 **
1829 **	Returns:
1830 **		none.
1831 **
1832 **	Globals:
1833 **		environ -- a pointer to the current environment.
1834 **
1835 **	Side Effects:
1836 **		Modifies environ.
1837 */
1838 
1839 #ifndef HASUNSETENV
1840 
1841 void
1842 unsetenv(name)
1843 	char *name;
1844 {
1845 	extern char **environ;
1846 	register char **pp;
1847 	int len = strlen(name);
1848 
1849 	for (pp = environ; *pp != NULL; pp++)
1850 	{
1851 		if (strncmp(name, *pp, len) == 0 &&
1852 		    ((*pp)[len] == '=' || (*pp)[len] == '\0'))
1853 			break;
1854 	}
1855 
1856 	for (; *pp != NULL; pp++)
1857 		*pp = pp[1];
1858 }
1859 
1860 #endif
1861 /*
1862 **  GETDTABLESIZE -- return number of file descriptors
1863 **
1864 **	Only on non-BSD systems
1865 **
1866 **	Parameters:
1867 **		none
1868 **
1869 **	Returns:
1870 **		size of file descriptor table
1871 **
1872 **	Side Effects:
1873 **		none
1874 */
1875 
1876 #ifdef SOLARIS
1877 # include <sys/resource.h>
1878 #endif
1879 
1880 int
1881 getdtsize()
1882 {
1883 #ifdef RLIMIT_NOFILE
1884 	struct rlimit rl;
1885 
1886 	if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
1887 		return rl.rlim_cur;
1888 #endif
1889 
1890 # ifdef HASGETDTABLESIZE
1891 	return getdtablesize();
1892 # else
1893 #  ifdef _SC_OPEN_MAX
1894 	return sysconf(_SC_OPEN_MAX);
1895 #  else
1896 	return NOFILE;
1897 #  endif
1898 # endif
1899 }
1900 /*
1901 **  UNAME -- get the UUCP name of this system.
1902 */
1903 
1904 #ifndef HASUNAME
1905 
1906 int
1907 uname(name)
1908 	struct utsname *name;
1909 {
1910 	FILE *file;
1911 	char *n;
1912 
1913 	name->nodename[0] = '\0';
1914 
1915 	/* try /etc/whoami -- one line with the node name */
1916 	if ((file = fopen("/etc/whoami", "r")) != NULL)
1917 	{
1918 		(void) fgets(name->nodename, NODE_LENGTH + 1, file);
1919 		(void) fclose(file);
1920 		n = strchr(name->nodename, '\n');
1921 		if (n != NULL)
1922 			*n = '\0';
1923 		if (name->nodename[0] != '\0')
1924 			return (0);
1925 	}
1926 
1927 	/* try /usr/include/whoami.h -- has a #define somewhere */
1928 	if ((file = fopen("/usr/include/whoami.h", "r")) != NULL)
1929 	{
1930 		char buf[MAXLINE];
1931 
1932 		while (fgets(buf, MAXLINE, file) != NULL)
1933 			if (sscanf(buf, "#define sysname \"%*[^\"]\"",
1934 					NODE_LENGTH, name->nodename) > 0)
1935 				break;
1936 		(void) fclose(file);
1937 		if (name->nodename[0] != '\0')
1938 			return (0);
1939 	}
1940 
1941 #ifdef TRUST_POPEN
1942 	/*
1943 	**  Popen is known to have security holes.
1944 	*/
1945 
1946 	/* try uuname -l to return local name */
1947 	if ((file = popen("uuname -l", "r")) != NULL)
1948 	{
1949 		(void) fgets(name, NODE_LENGTH + 1, file);
1950 		(void) pclose(file);
1951 		n = strchr(name, '\n');
1952 		if (n != NULL)
1953 			*n = '\0';
1954 		if (name->nodename[0] != '\0')
1955 			return (0);
1956 	}
1957 #endif
1958 
1959 	return (-1);
1960 }
1961 #endif /* HASUNAME */
1962 /*
1963 **  INITGROUPS -- initialize groups
1964 **
1965 **	Stub implementation for System V style systems
1966 */
1967 
1968 #ifndef HASINITGROUPS
1969 
1970 initgroups(name, basegid)
1971 	char *name;
1972 	int basegid;
1973 {
1974 	return 0;
1975 }
1976 
1977 #endif
1978 /*
1979 **  SETSID -- set session id (for non-POSIX systems)
1980 */
1981 
1982 #ifndef HASSETSID
1983 
1984 pid_t
1985 setsid __P ((void))
1986 {
1987 #ifdef TIOCNOTTY
1988 	int fd;
1989 
1990 	fd = open("/dev/tty", O_RDWR, 0);
1991 	if (fd >= 0)
1992 	{
1993 		(void) ioctl(fd, (int) TIOCNOTTY, (char *) 0);
1994 		(void) close(fd);
1995 	}
1996 #endif /* TIOCNOTTY */
1997 # ifdef SYS5SETPGRP
1998 	return setpgrp();
1999 # else
2000 	return setpgid(0, getpid());
2001 # endif
2002 }
2003 
2004 #endif
2005 /*
2006 **  FSYNC -- dummy fsync
2007 */
2008 
2009 #ifdef NEEDFSYNC
2010 
2011 fsync(fd)
2012 	int fd;
2013 {
2014 # ifdef O_SYNC
2015 	return fcntl(fd, F_SETFL, O_SYNC);
2016 # else
2017 	/* nothing we can do */
2018 	return 0;
2019 # endif
2020 }
2021 
2022 #endif
2023 /*
2024 **  DGUX_INET_ADDR -- inet_addr for DG/UX
2025 **
2026 **	Data General DG/UX version of inet_addr returns a struct in_addr
2027 **	instead of a long.  This patches things.  Only needed on versions
2028 **	prior to 5.4.3.
2029 */
2030 
2031 #ifdef DGUX_5_4_2
2032 
2033 #undef inet_addr
2034 
2035 long
2036 dgux_inet_addr(host)
2037 	char *host;
2038 {
2039 	struct in_addr haddr;
2040 
2041 	haddr = inet_addr(host);
2042 	return haddr.s_addr;
2043 }
2044 
2045 #endif
2046 /*
2047 **  GETOPT -- for old systems or systems with bogus implementations
2048 */
2049 
2050 #ifdef NEEDGETOPT
2051 
2052 /*
2053  * Copyright (c) 1985 Regents of the University of California.
2054  * All rights reserved.  The Berkeley software License Agreement
2055  * specifies the terms and conditions for redistribution.
2056  */
2057 
2058 
2059 /*
2060 ** this version hacked to add `atend' flag to allow state machine
2061 ** to reset if invoked by the program to scan args for a 2nd time
2062 */
2063 
2064 #if defined(LIBC_SCCS) && !defined(lint)
2065 static char sccsid[] = "@(#)getopt.c	4.3 (Berkeley) 3/9/86";
2066 #endif /* LIBC_SCCS and not lint */
2067 
2068 #include <stdio.h>
2069 
2070 /*
2071  * get option letter from argument vector
2072  */
2073 #ifdef _CONVEX_SOURCE
2074 extern int	optind, opterr, optopt;
2075 extern char	*optarg;
2076 #else
2077 int	opterr = 1;		/* if error message should be printed */
2078 int	optind = 1;		/* index into parent argv vector */
2079 int	optopt = 0;		/* character checked for validity */
2080 char	*optarg = NULL;		/* argument associated with option */
2081 #endif
2082 
2083 #define BADCH	(int)'?'
2084 #define EMSG	""
2085 #define tell(s)	if (opterr) {fputs(*nargv,stderr);fputs(s,stderr); \
2086 		fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);}
2087 
2088 getopt(nargc,nargv,ostr)
2089 	int		nargc;
2090 	char *const	*nargv;
2091 	const char	*ostr;
2092 {
2093 	static char	*place = EMSG;	/* option letter processing */
2094 	static char	atend = 0;
2095 	register char	*oli;		/* option letter list index */
2096 
2097 	if (atend) {
2098 		atend = 0;
2099 		place = EMSG;
2100 	}
2101 	if(!*place) {			/* update scanning pointer */
2102 		if (optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) {
2103 			atend++;
2104 			return(EOF);
2105 		}
2106 		if (*place == '-') {	/* found "--" */
2107 			++optind;
2108 			atend++;
2109 			return(EOF);
2110 		}
2111 	}				/* option letter okay? */
2112 	if ((optopt = (int)*place++) == (int)':' || !(oli = strchr(ostr,optopt))) {
2113 		if (!*place) ++optind;
2114 		tell(": illegal option -- ");
2115 	}
2116 	if (*++oli != ':') {		/* don't need argument */
2117 		optarg = NULL;
2118 		if (!*place) ++optind;
2119 	}
2120 	else {				/* need an argument */
2121 		if (*place) optarg = place;	/* no white space */
2122 		else if (nargc <= ++optind) {	/* no arg */
2123 			place = EMSG;
2124 			tell(": option requires an argument -- ");
2125 		}
2126 	 	else optarg = nargv[optind];	/* white space */
2127 		place = EMSG;
2128 		++optind;
2129 	}
2130 	return(optopt);			/* dump back option letter */
2131 }
2132 
2133 #endif
2134 /*
2135 **  VFPRINTF, VSPRINTF -- for old 4.3 BSD systems missing a real version
2136 */
2137 
2138 #ifdef NEEDVPRINTF
2139 
2140 #define MAXARG	16
2141 
2142 vfprintf(fp, fmt, ap)
2143 	FILE *	fp;
2144 	char *	fmt;
2145 	char **	ap;
2146 {
2147 	char *	bp[MAXARG];
2148 	int	i = 0;
2149 
2150 	while (*ap && i < MAXARG)
2151 		bp[i++] = *ap++;
2152 	fprintf(fp, fmt, bp[0], bp[1], bp[2], bp[3],
2153 			 bp[4], bp[5], bp[6], bp[7],
2154 			 bp[8], bp[9], bp[10], bp[11],
2155 			 bp[12], bp[13], bp[14], bp[15]);
2156 }
2157 
2158 vsprintf(s, fmt, ap)
2159 	char *	s;
2160 	char *	fmt;
2161 	char **	ap;
2162 {
2163 	char *	bp[MAXARG];
2164 	int	i = 0;
2165 
2166 	while (*ap && i < MAXARG)
2167 		bp[i++] = *ap++;
2168 	sprintf(s, fmt, bp[0], bp[1], bp[2], bp[3],
2169 			bp[4], bp[5], bp[6], bp[7],
2170 			bp[8], bp[9], bp[10], bp[11],
2171 			bp[12], bp[13], bp[14], bp[15]);
2172 }
2173 
2174 #endif
2175 /*
2176 **  USERSHELLOK -- tell if a user's shell is ok for unrestricted use
2177 **
2178 **	Parameters:
2179 **		shell -- the user's shell from /etc/passwd
2180 **
2181 **	Returns:
2182 **		TRUE -- if it is ok to use this for unrestricted access.
2183 **		FALSE -- if the shell is restricted.
2184 */
2185 
2186 #if !HASGETUSERSHELL
2187 
2188 # ifndef _PATH_SHELLS
2189 #  define _PATH_SHELLS	"/etc/shells"
2190 # endif
2191 
2192 char	*DefaultUserShells[] =
2193 {
2194 	"/bin/sh",		/* standard shell */
2195 	"/usr/bin/sh",
2196 	"/bin/csh",		/* C shell */
2197 	"/usr/bin/csh",
2198 #ifdef __hpux
2199 # ifdef V4FS
2200 	"/usr/bin/rsh",		/* restricted Bourne shell */
2201 	"/usr/bin/ksh",		/* Korn shell */
2202 	"/usr/bin/rksh",	/* restricted Korn shell */
2203 	"/usr/bin/pam",
2204 	"/usr/bin/keysh",	/* key shell (extended Korn shell) */
2205 	"/usr/bin/posix/sh",
2206 # else
2207 	"/bin/rsh",		/* restricted Bourne shell */
2208 	"/bin/ksh",		/* Korn shell */
2209 	"/bin/rksh",		/* restricted Korn shell */
2210 	"/bin/pam",
2211 	"/usr/bin/keysh",	/* key shell (extended Korn shell) */
2212 	"/bin/posix/sh",
2213 # endif
2214 #endif
2215 #ifdef _AIX3
2216 	"/bin/ksh",		/* Korn shell */
2217 	"/usr/bin/ksh",
2218 	"/bin/tsh",		/* trusted shell */
2219 	"/usr/bin/tsh",
2220 	"/bin/bsh",		/* Bourne shell */
2221 	"/usr/bin/bsh",
2222 #endif
2223 	NULL
2224 };
2225 
2226 #endif
2227 
2228 #define WILDCARD_SHELL	"/SENDMAIL/ANY/SHELL/"
2229 
2230 bool
2231 usershellok(shell)
2232 	char *shell;
2233 {
2234 #if HASGETUSERSHELL
2235 	register char *p;
2236 	extern char *getusershell();
2237 
2238 	if (shell == NULL || shell[0] == '\0' || ConfigLevel <= 1)
2239 		return TRUE;
2240 
2241 	setusershell();
2242 	while ((p = getusershell()) != NULL)
2243 		if (strcmp(p, shell) == 0 || strcmp(p, WILDCARD_SHELL) == 0)
2244 			break;
2245 	endusershell();
2246 	return p != NULL;
2247 #else
2248 	register FILE *shellf;
2249 	char buf[MAXLINE];
2250 
2251 	if (shell == NULL || shell[0] == '\0')
2252 		return TRUE;
2253 
2254 	shellf = fopen(_PATH_SHELLS, "r");
2255 	if (shellf == NULL)
2256 	{
2257 		/* no /etc/shells; see if it is one of the std shells */
2258 		char **d;
2259 
2260 		for (d = DefaultUserShells; *d != NULL; d++)
2261 		{
2262 			if (strcmp(shell, *d) == 0)
2263 				return TRUE;
2264 		}
2265 		return FALSE;
2266 	}
2267 
2268 	while (fgets(buf, sizeof buf, shellf) != NULL)
2269 	{
2270 		register char *p, *q;
2271 
2272 		p = buf;
2273 		while (*p != '\0' && *p != '#' && *p != '/')
2274 			p++;
2275 		if (*p == '#' || *p == '\0')
2276 			continue;
2277 		q = p;
2278 		while (*p != '\0' && *p != '#' && !isspace(*p))
2279 			p++;
2280 		*p = '\0';
2281 		if (strcmp(shell, q) == 0 || strcmp(WILDCARD_SHELL, q) == 0)
2282 		{
2283 			fclose(shellf);
2284 			return TRUE;
2285 		}
2286 	}
2287 	fclose(shellf);
2288 	return FALSE;
2289 #endif
2290 }
2291 /*
2292 **  FREESPACE -- see how much free space is on the queue filesystem
2293 **
2294 **	Only implemented if you have statfs.
2295 **
2296 **	Parameters:
2297 **		dir -- the directory in question.
2298 **		bsize -- a variable into which the filesystem
2299 **			block size is stored.
2300 **
2301 **	Returns:
2302 **		The number of bytes free on the queue filesystem.
2303 **		-1 if the statfs call fails.
2304 **
2305 **	Side effects:
2306 **		Puts the filesystem block size into bsize.
2307 */
2308 
2309 /* statfs types */
2310 #define SFS_NONE	0	/* no statfs implementation */
2311 #define SFS_USTAT	1	/* use ustat */
2312 #define SFS_4ARGS	2	/* use four-argument statfs call */
2313 #define SFS_VFS		3	/* use <sys/vfs.h> implementation */
2314 #define SFS_MOUNT	4	/* use <sys/mount.h> implementation */
2315 #define SFS_STATFS	5	/* use <sys/statfs.h> implementation */
2316 #define SFS_STATVFS	6	/* use <sys/statvfs.h> implementation */
2317 
2318 #ifndef SFS_TYPE
2319 # define SFS_TYPE	SFS_NONE
2320 #endif
2321 
2322 #if SFS_TYPE == SFS_USTAT
2323 # include <ustat.h>
2324 #endif
2325 #if SFS_TYPE == SFS_4ARGS || SFS_TYPE == SFS_STATFS
2326 # include <sys/statfs.h>
2327 #endif
2328 #if SFS_TYPE == SFS_VFS
2329 # include <sys/vfs.h>
2330 #endif
2331 #if SFS_TYPE == SFS_MOUNT
2332 # include <sys/mount.h>
2333 #endif
2334 #if SFS_TYPE == SFS_STATVFS
2335 # include <sys/statvfs.h>
2336 #endif
2337 
2338 long
2339 freespace(dir, bsize)
2340 	char *dir;
2341 	long *bsize;
2342 {
2343 #if SFS_TYPE != SFS_NONE
2344 # if SFS_TYPE == SFS_USTAT
2345 	struct ustat fs;
2346 	struct stat statbuf;
2347 #  define FSBLOCKSIZE	DEV_BSIZE
2348 #  define SFS_BAVAIL	f_tfree
2349 # else
2350 #  if defined(ultrix)
2351 	struct fs_data fs;
2352 #   define SFS_BAVAIL	fd_bfreen
2353 #   define FSBLOCKSIZE	1024L
2354 #  else
2355 #   if SFS_TYPE == SFS_STATVFS
2356 	struct statvfs fs;
2357 #    define FSBLOCKSIZE	fs.f_frsize
2358 #   else
2359 	struct statfs fs;
2360 #    define FSBLOCKSIZE	fs.f_bsize
2361 #   endif
2362 #  endif
2363 # endif
2364 # ifndef SFS_BAVAIL
2365 #  define SFS_BAVAIL f_bavail
2366 # endif
2367 
2368 # if SFS_TYPE == SFS_USTAT
2369 	if (stat(dir, &statbuf) == 0 && ustat(statbuf.st_dev, &fs) == 0)
2370 # else
2371 #  if SFS_TYPE == SFS_4ARGS
2372 	if (statfs(dir, &fs, sizeof fs, 0) == 0)
2373 #  else
2374 #   if SFS_TYPE == SFS_STATVFS
2375 	if (statvfs(dir, &fs) == 0)
2376 #   else
2377 #    if defined(ultrix)
2378 	if (statfs(dir, &fs) > 0)
2379 #    else
2380 	if (statfs(dir, &fs) == 0)
2381 #    endif
2382 #   endif
2383 #  endif
2384 # endif
2385 	{
2386 		if (bsize != NULL)
2387 			*bsize = FSBLOCKSIZE;
2388 		return (fs.SFS_BAVAIL);
2389 	}
2390 #endif
2391 	return (-1);
2392 }
2393 /*
2394 **  ENOUGHSPACE -- check to see if there is enough free space on the queue fs
2395 **
2396 **	Only implemented if you have statfs.
2397 **
2398 **	Parameters:
2399 **		msize -- the size to check against.  If zero, we don't yet
2400 **		know how big the message will be, so just check for
2401 **		a "reasonable" amount.
2402 **
2403 **	Returns:
2404 **		TRUE if there is enough space.
2405 **		FALSE otherwise.
2406 */
2407 
2408 bool
2409 enoughspace(msize)
2410 	long msize;
2411 {
2412 	long bfree, bsize;
2413 
2414 	if (MinBlocksFree <= 0 && msize <= 0)
2415 	{
2416 		if (tTd(4, 80))
2417 			printf("enoughspace: no threshold\n");
2418 		return TRUE;
2419 	}
2420 
2421 	if ((bfree = freespace(QueueDir, &bsize)) >= 0)
2422 	{
2423 		if (tTd(4, 80))
2424 			printf("enoughspace: bavail=%ld, need=%ld\n",
2425 				bfree, msize);
2426 
2427 		/* convert msize to block count */
2428 		msize = msize / bsize + 1;
2429 		if (MinBlocksFree >= 0)
2430 			msize += MinBlocksFree;
2431 
2432 		if (bfree < msize)
2433 		{
2434 #ifdef LOG
2435 			if (LogLevel > 0)
2436 				syslog(LOG_ALERT,
2437 					"%s: low on space (have %ld, %s needs %ld in %s)",
2438 					CurEnv->e_id == NULL ? "[NOQUEUE]" : CurEnv->e_id,
2439 					bfree,
2440 					CurHostName == NULL ? "SMTP-DAEMON" : CurHostName,
2441 					msize, QueueDir);
2442 #endif
2443 			return FALSE;
2444 		}
2445 	}
2446 	else if (tTd(4, 80))
2447 		printf("enoughspace failure: min=%ld, need=%ld: %s\n",
2448 			MinBlocksFree, msize, errstring(errno));
2449 	return TRUE;
2450 }
2451 /*
2452 **  TRANSIENTERROR -- tell if an error code indicates a transient failure
2453 **
2454 **	This looks at an errno value and tells if this is likely to
2455 **	go away if retried later.
2456 **
2457 **	Parameters:
2458 **		err -- the errno code to classify.
2459 **
2460 **	Returns:
2461 **		TRUE if this is probably transient.
2462 **		FALSE otherwise.
2463 */
2464 
2465 bool
2466 transienterror(err)
2467 	int err;
2468 {
2469 	switch (err)
2470 	{
2471 	  case EIO:			/* I/O error */
2472 	  case ENXIO:			/* Device not configured */
2473 	  case EAGAIN:			/* Resource temporarily unavailable */
2474 	  case ENOMEM:			/* Cannot allocate memory */
2475 	  case ENODEV:			/* Operation not supported by device */
2476 	  case ENFILE:			/* Too many open files in system */
2477 	  case EMFILE:			/* Too many open files */
2478 	  case ENOSPC:			/* No space left on device */
2479 #ifdef ETIMEDOUT
2480 	  case ETIMEDOUT:		/* Connection timed out */
2481 #endif
2482 #ifdef ESTALE
2483 	  case ESTALE:			/* Stale NFS file handle */
2484 #endif
2485 #ifdef ENETDOWN
2486 	  case ENETDOWN:		/* Network is down */
2487 #endif
2488 #ifdef ENETUNREACH
2489 	  case ENETUNREACH:		/* Network is unreachable */
2490 #endif
2491 #ifdef ENETRESET
2492 	  case ENETRESET:		/* Network dropped connection on reset */
2493 #endif
2494 #ifdef ECONNABORTED
2495 	  case ECONNABORTED:		/* Software caused connection abort */
2496 #endif
2497 #ifdef ECONNRESET
2498 	  case ECONNRESET:		/* Connection reset by peer */
2499 #endif
2500 #ifdef ENOBUFS
2501 	  case ENOBUFS:			/* No buffer space available */
2502 #endif
2503 #ifdef ESHUTDOWN
2504 	  case ESHUTDOWN:		/* Can't send after socket shutdown */
2505 #endif
2506 #ifdef ECONNREFUSED
2507 	  case ECONNREFUSED:		/* Connection refused */
2508 #endif
2509 #ifdef EHOSTDOWN
2510 	  case EHOSTDOWN:		/* Host is down */
2511 #endif
2512 #ifdef EHOSTUNREACH
2513 	  case EHOSTUNREACH:		/* No route to host */
2514 #endif
2515 #ifdef EDQUOT
2516 	  case EDQUOT:			/* Disc quota exceeded */
2517 #endif
2518 #ifdef EPROCLIM
2519 	  case EPROCLIM:		/* Too many processes */
2520 #endif
2521 #ifdef EUSERS
2522 	  case EUSERS:			/* Too many users */
2523 #endif
2524 #ifdef EDEADLK
2525 	  case EDEADLK:			/* Resource deadlock avoided */
2526 #endif
2527 #ifdef EISCONN
2528 	  case EISCONN:			/* Socket already connected */
2529 #endif
2530 #ifdef EINPROGRESS
2531 	  case EINPROGRESS:		/* Operation now in progress */
2532 #endif
2533 #ifdef EALREADY
2534 	  case EALREADY:		/* Operation already in progress */
2535 #endif
2536 #ifdef EADDRINUSE
2537 	  case EADDRINUSE:		/* Address already in use */
2538 #endif
2539 #ifdef EADDRNOTAVAIL
2540 	  case EADDRNOTAVAIL:		/* Can't assign requested address */
2541 #endif
2542 #ifdef ETXTBSY
2543 	  case ETXTBSY:			/* (Apollo) file locked */
2544 #endif
2545 #if defined(ENOSR) && (!defined(ENOBUFS) || (ENOBUFS != ENOSR))
2546 	  case ENOSR:			/* Out of streams resources */
2547 #endif
2548 		return TRUE;
2549 	}
2550 
2551 	/* nope, must be permanent */
2552 	return FALSE;
2553 }
2554 /*
2555 **  LOCKFILE -- lock a file using flock or (shudder) fcntl locking
2556 **
2557 **	Parameters:
2558 **		fd -- the file descriptor of the file.
2559 **		filename -- the file name (for error messages).
2560 **		ext -- the filename extension.
2561 **		type -- type of the lock.  Bits can be:
2562 **			LOCK_EX -- exclusive lock.
2563 **			LOCK_NB -- non-blocking.
2564 **
2565 **	Returns:
2566 **		TRUE if the lock was acquired.
2567 **		FALSE otherwise.
2568 */
2569 
2570 bool
2571 lockfile(fd, filename, ext, type)
2572 	int fd;
2573 	char *filename;
2574 	char *ext;
2575 	int type;
2576 {
2577 # if !HASFLOCK
2578 	int action;
2579 	struct flock lfd;
2580 
2581 	if (ext == NULL)
2582 		ext = "";
2583 
2584 	bzero(&lfd, sizeof lfd);
2585 	if (bitset(LOCK_UN, type))
2586 		lfd.l_type = F_UNLCK;
2587 	else if (bitset(LOCK_EX, type))
2588 		lfd.l_type = F_WRLCK;
2589 	else
2590 		lfd.l_type = F_RDLCK;
2591 
2592 	if (bitset(LOCK_NB, type))
2593 		action = F_SETLK;
2594 	else
2595 		action = F_SETLKW;
2596 
2597 	if (tTd(55, 60))
2598 		printf("lockfile(%s%s, action=%d, type=%d): ",
2599 			filename, ext, action, lfd.l_type);
2600 
2601 	if (fcntl(fd, action, &lfd) >= 0)
2602 	{
2603 		if (tTd(55, 60))
2604 			printf("SUCCESS\n");
2605 		return TRUE;
2606 	}
2607 
2608 	if (tTd(55, 60))
2609 		printf("(%s) ", errstring(errno));
2610 
2611 	/*
2612 	**  On SunOS, if you are testing using -oQ/tmp/mqueue or
2613 	**  -oA/tmp/aliases or anything like that, and /tmp is mounted
2614 	**  as type "tmp" (that is, served from swap space), the
2615 	**  previous fcntl will fail with "Invalid argument" errors.
2616 	**  Since this is fairly common during testing, we will assume
2617 	**  that this indicates that the lock is successfully grabbed.
2618 	*/
2619 
2620 	if (errno == EINVAL)
2621 	{
2622 		if (tTd(55, 60))
2623 			printf("SUCCESS\n");
2624 		return TRUE;
2625 	}
2626 
2627 	if (!bitset(LOCK_NB, type) || (errno != EACCES && errno != EAGAIN))
2628 	{
2629 		int omode = -1;
2630 #  ifdef F_GETFL
2631 		int oerrno = errno;
2632 
2633 		(void) fcntl(fd, F_GETFL, &omode);
2634 		errno = oerrno;
2635 #  endif
2636 		syserr("cannot lockf(%s%s, fd=%d, type=%o, omode=%o, euid=%d)",
2637 			filename, ext, fd, type, omode, geteuid());
2638 	}
2639 # else
2640 	if (ext == NULL)
2641 		ext = "";
2642 
2643 	if (tTd(55, 60))
2644 		printf("lockfile(%s%s, type=%o): ", filename, ext, type);
2645 
2646 	if (flock(fd, type) >= 0)
2647 	{
2648 		if (tTd(55, 60))
2649 			printf("SUCCESS\n");
2650 		return TRUE;
2651 	}
2652 
2653 	if (tTd(55, 60))
2654 		printf("(%s) ", errstring(errno));
2655 
2656 	if (!bitset(LOCK_NB, type) || errno != EWOULDBLOCK)
2657 	{
2658 		int omode = -1;
2659 #  ifdef F_GETFL
2660 		int oerrno = errno;
2661 
2662 		(void) fcntl(fd, F_GETFL, &omode);
2663 		errno = oerrno;
2664 #  endif
2665 		syserr("cannot flock(%s%s, fd=%d, type=%o, omode=%o, euid=%d)",
2666 			filename, ext, fd, type, omode, geteuid());
2667 	}
2668 # endif
2669 	if (tTd(55, 60))
2670 		printf("FAIL\n");
2671 	return FALSE;
2672 }
2673 /*
2674 **  CHOWNSAFE -- tell if chown is "safe" (executable only by root)
2675 **
2676 **	Parameters:
2677 **		fd -- the file descriptor to check.
2678 **
2679 **	Returns:
2680 **		TRUE -- if only root can chown the file to an arbitrary
2681 **			user.
2682 **		FALSE -- if an arbitrary user can give away a file.
2683 */
2684 
2685 bool
2686 chownsafe(fd)
2687 	int fd;
2688 {
2689 #ifdef __hpux
2690 	char *s;
2691 	int tfd;
2692 	uid_t o_uid, o_euid;
2693 	gid_t o_gid, o_egid;
2694 	bool rval;
2695 	struct stat stbuf;
2696 
2697 	o_uid = getuid();
2698 	o_euid = geteuid();
2699 	o_gid = getgid();
2700 	o_egid = getegid();
2701 	fstat(fd, &stbuf);
2702 	setresuid(stbuf.st_uid, stbuf.st_uid, -1);
2703 	setresgid(stbuf.st_gid, stbuf.st_gid, -1);
2704 	s = tmpnam(NULL);
2705 	tfd = open(s, O_RDONLY|O_CREAT, 0600);
2706 	rval = fchown(tfd, DefUid, DefGid) != 0;
2707 	close(tfd);
2708 	unlink(s);
2709 	setresuid(o_uid, o_euid, -1);
2710 	setresgid(o_gid, o_egid, -1);
2711 	return rval;
2712 #else
2713 # ifdef _POSIX_CHOWN_RESTRICTED
2714 #  if _POSIX_CHOWN_RESTRICTED == -1
2715 	return FALSE;
2716 #  else
2717 	return TRUE;
2718 #  endif
2719 # else
2720 #  ifdef _PC_CHOWN_RESTRICTED
2721 	int rval;
2722 
2723 	/*
2724 	**  Some systems (e.g., SunOS) seem to have the call and the
2725 	**  #define _PC_CHOWN_RESTRICTED, but don't actually implement
2726 	**  the call.  This heuristic checks for that.
2727 	*/
2728 
2729 	errno = 0;
2730 	rval = fpathconf(fd, _PC_CHOWN_RESTRICTED);
2731 	if (errno == 0)
2732 		return rval > 0;
2733 #  endif
2734 #  ifdef BSD
2735 	return TRUE;
2736 #  else
2737 	return FALSE;
2738 #  endif
2739 # endif
2740 #endif
2741 }
2742 /*
2743 **  RESETLIMITS -- reset system controlled resource limits
2744 **
2745 **	This is to avoid denial-of-service attacks
2746 **
2747 **	Parameters:
2748 **		none
2749 **
2750 **	Returns:
2751 **		none
2752 */
2753 
2754 #if HASSETRLIMIT
2755 # include <sys/resource.h>
2756 #endif
2757 
2758 void
2759 resetlimits()
2760 {
2761 #if HASSETRLIMIT
2762 	struct rlimit lim;
2763 
2764 	lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
2765 	(void) setrlimit(RLIMIT_CPU, &lim);
2766 	(void) setrlimit(RLIMIT_FSIZE, &lim);
2767 #else
2768 # if HASULIMIT
2769 	(void) ulimit(2, 0x3fffff);
2770 # endif
2771 #endif
2772 }
2773 /*
2774 **  GETCFNAME -- return the name of the .cf file.
2775 **
2776 **	Some systems (e.g., NeXT) determine this dynamically.
2777 */
2778 
2779 char *
2780 getcfname()
2781 {
2782 #ifdef TRY_VERSIONED_CF_NAME
2783 	int i;
2784 	static char cbuf[200];
2785 #endif
2786 
2787 	if (ConfFile != NULL)
2788 		return ConfFile;
2789 #ifdef NETINFO
2790 	{
2791 		extern char *ni_propval();
2792 		char *cflocation;
2793 
2794 		cflocation = ni_propval("/locations", NULL, "sendmail",
2795 					"sendmail.cf", '\0');
2796 		if (cflocation != NULL)
2797 			return cflocation;
2798 	}
2799 #endif
2800 
2801 #ifdef TRY_VERSIONED_CF_NAME
2802 	/*
2803 	**  Try sendmail.8.6.12.cf, then sendmail.8.6.cf, then
2804 	**  sendmail.8.cf, and finally sendmail.cf.
2805 	**
2806 	**	I suppose it should really try a search path here --
2807 	**	e.g., /etc/sendmail.cf, /etc/mail/sendmail.cf,
2808 	**	/usr/lib/sendmail.cf, and so forth.
2809 	*/
2810 
2811 	strcpy(cbuf, _PATH_SENDMAILCF);
2812 	i = strlen(cbuf);
2813 	if (strcmp(&cbuf[i - 3], ".cf") == 0)
2814 	{
2815 		char *p;
2816 		extern char Version[];
2817 
2818 		strcpy(&cbuf[i - 2], Version);
2819 		p = strchr(&cbuf[i - 2], '/');
2820 		if (p != NULL)
2821 			*p = '\0';
2822 		p = &cbuf[strlen(cbuf)];
2823 		do
2824 		{
2825 			int fd;
2826 
2827 			strcpy(p, ".cf");
2828 			if ((fd = open(cbuf, O_RDONLY, 0)) >= 0)
2829 			{
2830 				close(fd);
2831 				return cbuf;
2832 			}
2833 			*p = '\0';
2834 		} while ((p = strrchr(&cbuf[i - 2], '.')) != NULL);
2835 	}
2836 #endif
2837 	return _PATH_SENDMAILCF;
2838 }
2839 /*
2840 **  SETVENDOR -- process vendor code from V configuration line
2841 **
2842 **	Parameters:
2843 **		vendor -- string representation of vendor.
2844 **
2845 **	Returns:
2846 **		TRUE -- if ok.
2847 **		FALSE -- if vendor code could not be processed.
2848 **
2849 **	Side Effects:
2850 **		It is reasonable to set mode flags here to tweak
2851 **		processing in other parts of the code if necessary.
2852 **		For example, if you are a vendor that uses $%y to
2853 **		indicate YP lookups, you could enable that here.
2854 */
2855 
2856 bool
2857 setvendor(vendor)
2858 	char *vendor;
2859 {
2860 	if (strcasecmp(vendor, "Berkeley") == 0)
2861 	{
2862 		VendorCode = VENDOR_BERKELEY;
2863 		return TRUE;
2864 	}
2865 
2866 	/* add vendor extensions here */
2867 
2868 #ifdef SUN_EXTENSIONS
2869 	if (strcasecmp(vendor, "Sun") == 0)
2870 	{
2871 		VendorCode = VENDOR_SUN;
2872 		return TRUE;
2873 	}
2874 #endif
2875 
2876 	return FALSE;
2877 }
2878 /*
2879 **  VENDOR_PRE_DEFAULTS, VENDOR_POST_DEFAULTS -- set vendor-specific defaults
2880 **
2881 **	Vendor_pre_defaults is called before reading the configuration
2882 **	file; vendor_post_defaults is called immediately after.
2883 **
2884 **	Parameters:
2885 **		e -- the global environment to initialize.
2886 **
2887 **	Returns:
2888 **		none.
2889 */
2890 
2891 void
2892 vendor_pre_defaults(e)
2893 	ENVELOPE *e;
2894 {
2895 }
2896 
2897 
2898 void
2899 vendor_post_defaults(e)
2900 	ENVELOPE *e;
2901 {
2902 }
2903 /*
2904 **  STRTOL -- convert string to long integer
2905 **
2906 **	For systems that don't have it in the C library.
2907 **
2908 **	This is taken verbatim from the 4.4-Lite C library.
2909 */
2910 
2911 #ifdef NEEDSTRTOL
2912 
2913 #if defined(LIBC_SCCS) && !defined(lint)
2914 static char sccsid[] = "@(#)strtol.c	8.1 (Berkeley) 6/4/93";
2915 #endif /* LIBC_SCCS and not lint */
2916 
2917 #include <limits.h>
2918 
2919 /*
2920  * Convert a string to a long integer.
2921  *
2922  * Ignores `locale' stuff.  Assumes that the upper and lower case
2923  * alphabets and digits are each contiguous.
2924  */
2925 
2926 long
2927 strtol(nptr, endptr, base)
2928 	const char *nptr;
2929 	char **endptr;
2930 	register int base;
2931 {
2932 	register const char *s = nptr;
2933 	register unsigned long acc;
2934 	register int c;
2935 	register unsigned long cutoff;
2936 	register int neg = 0, any, cutlim;
2937 
2938 	/*
2939 	 * Skip white space and pick up leading +/- sign if any.
2940 	 * If base is 0, allow 0x for hex and 0 for octal, else
2941 	 * assume decimal; if base is already 16, allow 0x.
2942 	 */
2943 	do {
2944 		c = *s++;
2945 	} while (isspace(c));
2946 	if (c == '-') {
2947 		neg = 1;
2948 		c = *s++;
2949 	} else if (c == '+')
2950 		c = *s++;
2951 	if ((base == 0 || base == 16) &&
2952 	    c == '0' && (*s == 'x' || *s == 'X')) {
2953 		c = s[1];
2954 		s += 2;
2955 		base = 16;
2956 	}
2957 	if (base == 0)
2958 		base = c == '0' ? 8 : 10;
2959 
2960 	/*
2961 	 * Compute the cutoff value between legal numbers and illegal
2962 	 * numbers.  That is the largest legal value, divided by the
2963 	 * base.  An input number that is greater than this value, if
2964 	 * followed by a legal input character, is too big.  One that
2965 	 * is equal to this value may be valid or not; the limit
2966 	 * between valid and invalid numbers is then based on the last
2967 	 * digit.  For instance, if the range for longs is
2968 	 * [-2147483648..2147483647] and the input base is 10,
2969 	 * cutoff will be set to 214748364 and cutlim to either
2970 	 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
2971 	 * a value > 214748364, or equal but the next digit is > 7 (or 8),
2972 	 * the number is too big, and we will return a range error.
2973 	 *
2974 	 * Set any if any `digits' consumed; make it negative to indicate
2975 	 * overflow.
2976 	 */
2977 	cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
2978 	cutlim = cutoff % (unsigned long)base;
2979 	cutoff /= (unsigned long)base;
2980 	for (acc = 0, any = 0;; c = *s++) {
2981 		if (isdigit(c))
2982 			c -= '0';
2983 		else if (isalpha(c))
2984 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
2985 		else
2986 			break;
2987 		if (c >= base)
2988 			break;
2989 		if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
2990 			any = -1;
2991 		else {
2992 			any = 1;
2993 			acc *= base;
2994 			acc += c;
2995 		}
2996 	}
2997 	if (any < 0) {
2998 		acc = neg ? LONG_MIN : LONG_MAX;
2999 		errno = ERANGE;
3000 	} else if (neg)
3001 		acc = -acc;
3002 	if (endptr != 0)
3003 		*endptr = (char *)(any ? s - 1 : nptr);
3004 	return (acc);
3005 }
3006 
3007 #endif
3008 /*
3009 **  STRSTR -- find first substring in string
3010 **
3011 **	Parameters:
3012 **		big -- the big (full) string.
3013 **		little -- the little (sub) string.
3014 **
3015 **	Returns:
3016 **		A pointer to the first instance of little in big.
3017 **		big if little is the null string.
3018 **		NULL if little is not contained in big.
3019 */
3020 
3021 #ifdef NEEDSTRSTR
3022 
3023 char *
3024 strstr(big, little)
3025 	char *big;
3026 	char *little;
3027 {
3028 	register char *p = big;
3029 	int l;
3030 
3031 	if (*little == '\0')
3032 		return big;
3033 	l = strlen(little);
3034 
3035 	while ((p = strchr(p, *little)) != NULL)
3036 	{
3037 		if (strncmp(p, little, l) == 0)
3038 			return p;
3039 		p++;
3040 	}
3041 	return NULL;
3042 }
3043 
3044 #endif
3045 /*
3046 **  SM_GETHOSTBY{NAME,ADDR} -- compatibility routines for gethostbyXXX
3047 **
3048 **	Some operating systems have wierd problems with the gethostbyXXX
3049 **	routines.  For example, Solaris versions at least through 2.3
3050 **	don't properly deliver a canonical h_name field.  This tries to
3051 **	work around these problems.
3052 */
3053 
3054 struct hostent *
3055 sm_gethostbyname(name)
3056 	char *name;
3057 {
3058 #if defined(SOLARIS) && SOLARIS < 204 || defined(sony_news) && defined(__svr4)
3059 	extern int h_errno;
3060 
3061 # if SOLARIS == 203
3062 	static struct hostent hp;
3063 	static char buf[1000];
3064 	extern struct hostent *_switch_gethostbyname_r();
3065 
3066 	return _switch_gethostbyname_r(name, &hp, buf, sizeof(buf), &h_errno);
3067 # else
3068 	extern struct hostent *__switch_gethostbyname();
3069 
3070 	return __switch_gethostbyname(name);
3071 # endif
3072 #else
3073 	struct hostent *h;
3074 	int nmaps;
3075 	char *maptype[MAXMAPSTACK];
3076 	short mapreturn[MAXMAPACTIONS];
3077 	char hbuf[MAXNAME];
3078 
3079 	h = gethostbyname(name);
3080 # if defined(NIS)
3081 	if (h != NULL)
3082 		return h;
3083 	nmaps = switch_map_find("hosts", maptype, mapreturn);
3084 	while (--nmaps >= 0)
3085 		if (strcmp(maptype[nmaps], "nis") == 0)
3086 			break;
3087 	if (nmaps >= 0)
3088 	{
3089 		/* try short name */
3090 		if (strlen(name) > sizeof hbuf - 1)
3091 			return NULL;
3092 		strcpy(hbuf, name);
3093 		shorten_hostname(hbuf);
3094 
3095 		/* if it hasn't been shortened, there's no point */
3096 		if (strcmp(hbuf, name) != 0)
3097 			return gethostbyname(hbuf);
3098 	}
3099 # endif
3100 	return h;
3101 #endif
3102 }
3103 
3104 struct hostent *
3105 sm_gethostbyaddr(addr, len, type)
3106 	char *addr;
3107 	int len;
3108 	int type;
3109 {
3110 #if defined(SOLARIS) && SOLARIS < 204
3111 	extern int h_errno;
3112 
3113 # if SOLARIS == 203
3114 	static struct hostent hp;
3115 	static char buf[1000];
3116 	extern struct hostent *_switch_gethostbyaddr_r();
3117 
3118 	return _switch_gethostbyaddr_r(addr, len, type, &hp, buf, sizeof(buf), &h_errno);
3119 # else
3120 	extern struct hostent *__switch_gethostbyaddr();
3121 
3122 	return __switch_gethostbyaddr(addr, len, type);
3123 # endif
3124 #else
3125 	return gethostbyaddr(addr, len, type);
3126 #endif
3127 }
3128 /*
3129 **  SM_GETPW{NAM,UID} -- wrapper for getpwnam and getpwuid
3130 */
3131 
3132 struct passwd *
3133 sm_getpwnam(user)
3134 	char *user;
3135 {
3136 	return getpwnam(user);
3137 }
3138 
3139 struct passwd *
3140 sm_getpwuid(uid)
3141 	uid_t uid;
3142 {
3143 	return getpwuid(uid);
3144 }
3145 /*
3146 **  LOAD_IF_NAMES -- load interface-specific names into $=w
3147 **
3148 **	Parameters:
3149 **		none.
3150 **
3151 **	Returns:
3152 **		none.
3153 **
3154 **	Side Effects:
3155 **		Loads $=w with the names of all the interfaces.
3156 */
3157 
3158 #ifdef SIOCGIFCONF
3159 struct rtentry;
3160 struct mbuf;
3161 # include <arpa/inet.h>
3162 # include <sys/time.h>
3163 # include <net/if.h>
3164 #endif
3165 
3166 void
3167 load_if_names()
3168 {
3169 #ifdef SIOCGIFCONF
3170 	int s;
3171 	int i;
3172         struct ifconf ifc;
3173 	char interfacebuf[1024];
3174 
3175 	s = socket(AF_INET, SOCK_DGRAM, 0);
3176 	if (s == -1)
3177 		return;
3178 
3179 	/* get the list of known IP address from the kernel */
3180         ifc.ifc_buf = interfacebuf;
3181         ifc.ifc_len = sizeof interfacebuf;
3182 	if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0)
3183 	{
3184 		if (tTd(0, 4))
3185 			printf("SIOGIFCONF failed: %s\n", errstring(errno));
3186 		close(s);
3187 		return;
3188 	}
3189 	close(s);
3190 
3191 	/* scan the list of IP address */
3192 	if (tTd(0, 4))
3193 		printf("scanning for interface specific names, ifc_len=%d\n",
3194 			ifc.ifc_len);
3195 
3196 	for (i = 0; i < ifc.ifc_len; )
3197 	{
3198 		struct ifreq *ifr = (struct ifreq *) &ifc.ifc_buf[i];
3199 		struct sockaddr *sa = &ifr->ifr_addr;
3200 		struct in_addr ia;
3201 		struct hostent *hp;
3202 		char ip_addr[256];
3203 		extern char *inet_ntoa();
3204 		extern struct hostent *gethostbyaddr();
3205 
3206 #ifdef BSD4_4_SOCKADDR
3207 		if (sa->sa_len > sizeof ifr->ifr_addr)
3208 			i += sizeof ifr->ifr_name + sa->sa_len;
3209 		else
3210 #endif
3211 			i += sizeof *ifr;
3212 
3213 		if (tTd(0, 20))
3214 			printf("%s\n", anynet_ntoa((SOCKADDR *) sa));
3215 
3216 		if (ifr->ifr_addr.sa_family != AF_INET)
3217 			continue;
3218 
3219 		/* extract IP address from the list*/
3220 		ia = (((struct sockaddr_in *) sa)->sin_addr);
3221 
3222 		/* save IP address in text from */
3223 		(void) sprintf(ip_addr, "[%s]",
3224 			inet_ntoa(((struct sockaddr_in *) sa)->sin_addr));
3225 		if (!wordinclass(ip_addr, 'w'))
3226 		{
3227 			setclass('w', ip_addr);
3228 			if (tTd(0, 4))
3229 				printf("\ta.k.a.: %s\n", ip_addr);
3230 		}
3231 
3232 		/* skip "loopback" interface "lo" */
3233 		if (strcmp("lo0", ifr->ifr_name) == 0)
3234 			continue;
3235 
3236 		/* lookup name with IP address */
3237 		hp = sm_gethostbyaddr((char *) &ia, sizeof(ia), AF_INET);
3238 		if (hp == NULL)
3239 		{
3240 			syslog(LOG_CRIT, "gethostbyaddr() failed for %s\n",
3241 				inet_ntoa(ia));
3242 			continue;
3243 		}
3244 
3245 		/* save its cname */
3246 		if (!wordinclass(hp->h_name, 'w'))
3247 		{
3248 			setclass('w', hp->h_name);
3249 			if (tTd(0, 4))
3250 				printf("\ta.k.a.: %s\n", hp->h_name);
3251 		}
3252 
3253 		/* save all it aliases name */
3254 		while (*hp->h_aliases)
3255 		{
3256 			if (!wordinclass(*hp->h_aliases, 'w'))
3257 			{
3258 				setclass('w', *hp->h_aliases);
3259 				if (tTd(0, 4))
3260 				printf("\ta.k.a.: %s\n", *hp->h_aliases);
3261 			}
3262 			hp->h_aliases++;
3263 		}
3264 	}
3265 #endif
3266 }
3267 /*
3268 **  NI_PROPVAL -- netinfo property value lookup routine
3269 **
3270 **	Parameters:
3271 **		keydir -- the Netinfo directory name in which to search
3272 **			for the key.
3273 **		keyprop -- the name of the property in which to find the
3274 **			property we are interested.  Defaults to "name".
3275 **		keyval -- the value for which we are really searching.
3276 **		valprop -- the property name for the value in which we
3277 **			are interested.
3278 **		sepchar -- if non-nil, this can be multiple-valued, and
3279 **			we should return a string separated by this
3280 **			character.
3281 **
3282 **	Returns:
3283 **		NULL -- if:
3284 **			1. the directory is not found
3285 **			2. the property name is not found
3286 **			3. the property contains multiple values
3287 **			4. some error occured
3288 **		else -- the location of the config file.
3289 **
3290 **	Example:
3291 **		To search for an alias value, use:
3292 **		  ni_propval("/aliases", "name", aliasname, "members", ',')
3293 **
3294 **	Notes:
3295 **      	Caller should free the return value of ni_proval
3296 */
3297 
3298 #ifdef NETINFO
3299 
3300 # include <netinfo/ni.h>
3301 
3302 # define LOCAL_NETINFO_DOMAIN    "."
3303 # define PARENT_NETINFO_DOMAIN   ".."
3304 # define MAX_NI_LEVELS           256
3305 
3306 char *
3307 ni_propval(keydir, keyprop, keyval, valprop, sepchar)
3308 	char *keydir;
3309 	char *keyprop;
3310 	char *keyval;
3311 	char *valprop;
3312 	char sepchar;
3313 {
3314 	char *propval = NULL;
3315 	int i;
3316 	int j, alen;
3317 	void *ni = NULL;
3318 	void *lastni = NULL;
3319 	ni_status nis;
3320 	ni_id nid;
3321 	ni_namelist ninl;
3322 	register char *p;
3323 	char keybuf[1024];
3324 
3325 	/*
3326 	**  Create the full key from the two parts.
3327 	**
3328 	**	Note that directory can end with, e.g., "name=" to specify
3329 	**	an alternate search property.
3330 	*/
3331 
3332 	i = strlen(keydir) + strlen(keyval) + 2;
3333 	if (keyprop != NULL)
3334 		i += strlen(keyprop) + 1;
3335 	if (i > sizeof keybuf)
3336 		return NULL;
3337 	strcpy(keybuf, keydir);
3338 	strcat(keybuf, "/");
3339 	if (keyprop != NULL)
3340 	{
3341 		strcat(keybuf, keyprop);
3342 		strcat(keybuf, "=");
3343 	}
3344 	strcat(keybuf, keyval);
3345 
3346 	/*
3347 	**  If the passed directory and property name are found
3348 	**  in one of netinfo domains we need to search (starting
3349 	**  from the local domain moving all the way back to the
3350 	**  root domain) set propval to the property's value
3351 	**  and return it.
3352 	*/
3353 
3354 	for (i = 0; i < MAX_NI_LEVELS; ++i)
3355 	{
3356 		if (i == 0)
3357 		{
3358 			nis = ni_open(NULL, LOCAL_NETINFO_DOMAIN, &ni);
3359 		}
3360 		else
3361 		{
3362 			if (lastni != NULL)
3363 				ni_free(lastni);
3364 			lastni = ni;
3365 			nis = ni_open(lastni, PARENT_NETINFO_DOMAIN, &ni);
3366 		}
3367 
3368 		/*
3369 		**  Don't bother if we didn't get a handle on a
3370 		**  proper domain.  This is not necessarily an error.
3371 		**  We would get a positive ni_status if, for instance
3372 		**  we never found the directory or property and tried
3373 		**  to open the parent of the root domain!
3374 		*/
3375 
3376 		if (nis != 0)
3377 			break;
3378 
3379 		/*
3380 		**  Find the path to the server information.
3381 		*/
3382 
3383 		if (ni_pathsearch(ni, &nid, keybuf) != 0)
3384 			continue;
3385 
3386 		/*
3387 		**  Find associated value information.
3388 		*/
3389 
3390 		if (ni_lookupprop(ni, &nid, valprop, &ninl) != 0)
3391 			continue;
3392 
3393 		/*
3394 		**  See if we have an acceptable number of values.
3395 		*/
3396 
3397 		if (ninl.ni_namelist_len <= 0)
3398 			continue;
3399 
3400 		if (sepchar == '\0' && ninl.ni_namelist_len > 1)
3401 		{
3402 			ni_namelist_free(&ninl);
3403 			continue;
3404 		}
3405 
3406 		/*
3407 		**  Calculate number of bytes needed and build result
3408 		*/
3409 
3410 		alen = 1;
3411 		for (j = 0; j < ninl.ni_namelist_len; j++)
3412 			alen += strlen(ninl.ni_namelist_val[j]) + 1;
3413 		propval = p = xalloc(alen);
3414 		for (j = 0; j < ninl.ni_namelist_len; j++)
3415 		{
3416 			strcpy(p, ninl.ni_namelist_val[j]);
3417 			p += strlen(p);
3418 			*p++ = sepchar;
3419 		}
3420 		*--p = '\0';
3421 
3422 		ni_namelist_free(&ninl);
3423 	}
3424 
3425 	/*
3426 	**  Clean up.
3427 	*/
3428 
3429 	if (ni != NULL)
3430 		ni_free(ni);
3431 	if (lastni != NULL && ni != lastni)
3432 		ni_free(lastni);
3433 
3434 	return propval;
3435 }
3436 
3437 #endif /* NETINFO */
3438 /*
3439 **  HARD_SYSLOG -- call syslog repeatedly until it works
3440 **
3441 **	Needed on HP-UX, which apparently doesn't guarantee that
3442 **	syslog succeeds during interrupt handlers.
3443 */
3444 
3445 #ifdef __hpux
3446 
3447 # define MAXSYSLOGTRIES	100
3448 # undef syslog
3449 
3450 void
3451 # ifdef __STDC__
3452 hard_syslog(int pri, char *msg, ...)
3453 # else
3454 hard_syslog(pri, msg, va_alist)
3455 	int pri;
3456 	char *msg;
3457 	va_dcl
3458 # endif
3459 {
3460 	int i;
3461 	char buf[SYSLOG_BUFSIZE * 2];
3462 	VA_LOCAL_DECL;
3463 
3464 	VA_START(msg);
3465 	vsprintf(buf, msg, ap);
3466 	VA_END;
3467 
3468 	for (i = MAXSYSLOGTRIES; --i >= 0 && syslog(pri, "%s", buf) < 0; )
3469 		continue;
3470 }
3471 
3472 #endif
3473 /*
3474 **  LOCAL_HOSTNAME_LENGTH
3475 **
3476 **	This is required to get sendmail to compile against BIND 4.9.x
3477 **	on Ultrix.
3478 */
3479 
3480 #if defined(ultrix) && NAMED_BIND
3481 
3482 # include <resolv.h>
3483 # if __RES >= 19931104
3484 
3485 int
3486 local_hostname_length(hostname)
3487 	char *hostname;
3488 {
3489 	int len_host, len_domain;
3490 
3491 	if (!*_res.defdname)
3492 		res_init();
3493 	len_host = strlen(hostname);
3494 	len_domain = strlen(_res.defdname);
3495 	if (len_host > len_domain &&
3496 	    (strcasecmp(hostname + len_host - len_domain,_res.defdname) == 0) &&
3497 	    hostname[len_host - len_domain - 1] == '.')
3498 		return len_host - len_domain - 1;
3499 	else
3500 		return 0;
3501 }
3502 
3503 # endif
3504 #endif
3505 /*
3506 **  Compile-Time options
3507 */
3508 
3509 char	*CompileOptions[] =
3510 {
3511 #if HESIOD
3512 	"HESIOD",
3513 #endif
3514 #if LOG
3515 	"LOG",
3516 #endif
3517 #if MATCHGECOS
3518 	"MATCHGECOS",
3519 #endif
3520 #if NAMED_BIND
3521 	"NAMED_BIND",
3522 #endif
3523 #if NDBM
3524 	"NDBM",
3525 #endif
3526 #if NETINET
3527 	"NETINET",
3528 #endif
3529 #if NETINFO
3530 	"NETINFO",
3531 #endif
3532 #if NETISO
3533 	"NETISO",
3534 #endif
3535 #if NETNS
3536 	"NETNS",
3537 #endif
3538 #if NETUNIX
3539 	"NETUNIX",
3540 #endif
3541 #if NETX25
3542 	"NETX25",
3543 #endif
3544 #if NEWDB
3545 	"NEWDB",
3546 #endif
3547 #if NIS
3548 	"NIS",
3549 #endif
3550 #if NISPLUS
3551 	"NISPLUS",
3552 #endif
3553 #if SCANF
3554 	"SCANF",
3555 #endif
3556 #if SUID_ROOT_FILES_OK
3557 	"SUID_ROOT_FILES_OK",
3558 #endif
3559 #if USERDB
3560 	"USERDB",
3561 #endif
3562 #if XDEBUG
3563 	"XDEBUG",
3564 #endif
3565 #if XLA
3566 	"XLA",
3567 #endif
3568 	NULL
3569 };
3570