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