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