xref: /dragonfly/lib/libc/gen/getnetgrent.c (revision 0db87cb7)
1 /*
2  * Copyright (c) 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)getnetgrent.c	8.2 (Berkeley) 4/27/95
33  * $FreeBSD: src/lib/libc/gen/getnetgrent.c,v 1.35 2007/01/09 00:27:54 imp Exp $
34  * $DragonFly: src/lib/libc/gen/getnetgrent.c,v 1.5 2005/04/25 19:03:46 joerg Exp $
35  */
36 
37 #include <ctype.h>
38 #include <netdb.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #ifdef YP
45 /*
46  * Notes:
47  * We want to be able to use NIS netgroups properly while retaining
48  * the ability to use a local /etc/netgroup file. Unfortunately, you
49  * can't really do both at the same time - at least, not efficiently.
50  * NetBSD deals with this problem by creating a netgroup database
51  * using Berkeley DB (just like the password database) that allows
52  * for lookups using netgroup, netgroup.byuser or netgroup.byhost
53  * searches. This is a neat idea, but I don't have time to implement
54  * something like that now. (I think ultimately it would be nice
55  * if we DB-fied the group and netgroup stuff all in one shot, but
56  * for now I'm satisfied just to have something that works well
57  * without requiring massive code changes.)
58  *
59  * Therefore, to still permit the use of the local file and maintain
60  * optimum NIS performance, we allow for the following conditions:
61  *
62  * - If /etc/netgroup does not exist and NIS is turned on, we use
63  *   NIS netgroups only.
64  *
65  * - If /etc/netgroup exists but is empty, we use NIS netgroups
66  *   only.
67  *
68  * - If /etc/netgroup exists and contains _only_ a '+', we use
69  *   NIS netgroups only.
70  *
71  * - If /etc/netgroup exists, contains locally defined netgroups
72  *   and a '+', we use a mixture of NIS and the local entries.
73  *   This method should return the same NIS data as just using
74  *   NIS alone, but it will be slower if the NIS netgroup database
75  *   is large (innetgr() in particular will suffer since extra
76  *   processing has to be done in order to determine memberships
77  *   using just the raw netgroup data).
78  *
79  * - If /etc/netgroup exists and contains only locally defined
80  *   netgroup entries, we use just those local entries and ignore
81  *   NIS (this is the original, pre-NIS behavior).
82  */
83 
84 #include <rpc/rpc.h>
85 #include <rpcsvc/yp_prot.h>
86 #include <rpcsvc/ypclnt.h>
87 #include <sys/types.h>
88 #include <sys/stat.h>
89 #include <sys/param.h>
90 #include <sys/errno.h>
91 static char *_netgr_yp_domain;
92 int _use_only_yp;
93 static int _netgr_yp_enabled;
94 static int _yp_innetgr;
95 #endif
96 
97 #ifndef _PATH_NETGROUP
98 #define _PATH_NETGROUP "/etc/netgroup"
99 #endif
100 
101 /*
102  * Static Variables and functions used by setnetgrent(), getnetgrent() and
103  * endnetgrent().
104  * There are two linked lists:
105  * - linelist is just used by setnetgrent() to parse the net group file via.
106  *   parse_netgrp()
107  * - netgrp is the list of entries for the current netgroup
108  */
109 struct linelist {
110 	struct linelist	*l_next;	/* Chain ptr. */
111 	int		l_parsed;	/* Flag for cycles */
112 	char		*l_groupname;	/* Name of netgroup */
113 	char		*l_line;	/* Netgroup entrie(s) to be parsed */
114 };
115 
116 struct netgrp {
117 	struct netgrp	*ng_next;	/* Chain ptr */
118 	char		*ng_str[3];	/* Field pointers, see below */
119 };
120 #define NG_HOST		0	/* Host name */
121 #define NG_USER		1	/* User name */
122 #define NG_DOM		2	/* and Domain name */
123 
124 static struct linelist	*linehead = NULL;
125 static struct netgrp	*nextgrp = NULL;
126 static struct {
127 	struct netgrp	*gr;
128 	char		*grname;
129 } grouphead = {
130 	NULL,
131 	NULL,
132 };
133 static FILE *netf = NULL;
134 
135 static int parse_netgrp(const char *);
136 static struct linelist *read_for_group(const char *);
137 
138 #define	LINSIZ	1024	/* Length of netgroup file line */
139 
140 /*
141  * setnetgrent()
142  * Parse the netgroup file looking for the netgroup and build the list
143  * of netgrp structures. Let parse_netgrp() and read_for_group() do
144  * most of the work.
145  */
146 void
147 setnetgrent(const char *group)
148 {
149 #ifdef YP
150 	struct stat _yp_statp;
151 	char _yp_plus;
152 #endif
153 
154 	/* Sanity check */
155 
156 	if (group == NULL || !strlen(group))
157 		return;
158 
159 	if (grouphead.gr == NULL ||
160 		strcmp(group, grouphead.grname)) {
161 		endnetgrent();
162 #ifdef YP
163 		/* Presumed guilty until proven innocent. */
164 		_use_only_yp = 0;
165 		/*
166 		 * If /etc/netgroup doesn't exist or is empty,
167 		 * use NIS exclusively.
168 		 */
169 		if (((stat(_PATH_NETGROUP, &_yp_statp) < 0) &&
170 			errno == ENOENT) || _yp_statp.st_size == 0)
171 			_use_only_yp = _netgr_yp_enabled = 1;
172 		if ((netf = fopen(_PATH_NETGROUP,"r")) != NULL ||_use_only_yp){
173 		/*
174 		 * Icky: grab the first character of the netgroup file
175 		 * and turn on NIS if it's a '+'. rewind the stream
176 		 * afterwards so we don't goof up read_for_group() later.
177 		 */
178 			if (netf) {
179 				fscanf(netf, "%c", &_yp_plus);
180 				rewind(netf);
181 				if (_yp_plus == '+')
182 					_use_only_yp = _netgr_yp_enabled = 1;
183 			}
184 		/*
185 		 * If we were called specifically for an innetgr()
186 		 * lookup and we're in NIS-only mode, short-circuit
187 		 * parse_netgroup() and cut directly to the chase.
188 		 */
189 			if (_use_only_yp && _yp_innetgr) {
190 				/* dohw! */
191 				if (netf != NULL)
192 					fclose(netf);
193 				return;
194 			}
195 #else
196 		if (netf = fopen(_PATH_NETGROUP, "r")) {
197 #endif
198 			if (parse_netgrp(group))
199 				endnetgrent();
200 			else {
201 				grouphead.grname = (char *)
202 					malloc(strlen(group) + 1);
203 				strcpy(grouphead.grname, group);
204 			}
205 			if (netf)
206 				fclose(netf);
207 		}
208 	}
209 	nextgrp = grouphead.gr;
210 }
211 
212 /*
213  * Get the next netgroup off the list.
214  */
215 int
216 getnetgrent(char **hostp, char **userp, char **domp)
217 {
218 #ifdef YP
219 	_yp_innetgr = 0;
220 #endif
221 
222 	if (nextgrp) {
223 		*hostp = nextgrp->ng_str[NG_HOST];
224 		*userp = nextgrp->ng_str[NG_USER];
225 		*domp = nextgrp->ng_str[NG_DOM];
226 		nextgrp = nextgrp->ng_next;
227 		return (1);
228 	}
229 	return (0);
230 }
231 
232 /*
233  * endnetgrent() - cleanup
234  */
235 void
236 endnetgrent(void)
237 {
238 	struct linelist *lp, *olp;
239 	struct netgrp *gp, *ogp;
240 
241 	lp = linehead;
242 	while (lp) {
243 		olp = lp;
244 		lp = lp->l_next;
245 		free(olp->l_groupname);
246 		free(olp->l_line);
247 		free((char *)olp);
248 	}
249 	linehead = NULL;
250 	if (grouphead.grname) {
251 		free(grouphead.grname);
252 		grouphead.grname = NULL;
253 	}
254 	gp = grouphead.gr;
255 	while (gp) {
256 		ogp = gp;
257 		gp = gp->ng_next;
258 		if (ogp->ng_str[NG_HOST])
259 			free(ogp->ng_str[NG_HOST]);
260 		if (ogp->ng_str[NG_USER])
261 			free(ogp->ng_str[NG_USER]);
262 		if (ogp->ng_str[NG_DOM])
263 			free(ogp->ng_str[NG_DOM]);
264 		free((char *)ogp);
265 	}
266 	grouphead.gr = NULL;
267 	nextgrp = NULL;
268 #ifdef YP
269 	_netgr_yp_enabled = 0;
270 #endif
271 }
272 
273 #ifdef YP
274 static int
275 _listmatch(const char *list, const char *group, int len)
276 {
277 	const char *ptr = list;
278 	const char *cptr;
279 	int glen = strlen(group);
280 
281 	/* skip possible leading whitespace */
282 	while(isspace((unsigned char)*ptr))
283 		ptr++;
284 
285 	while (ptr < list + len) {
286 		cptr = ptr;
287 		while(*ptr != ','  && *ptr != '\0' && !isspace((unsigned char)*ptr))
288 			ptr++;
289 		if (strncmp(cptr, group, glen) == 0 && glen == (ptr - cptr))
290 			return(1);
291 		while(*ptr == ','  || isspace((unsigned char)*ptr))
292 			ptr++;
293 	}
294 
295 	return(0);
296 }
297 
298 static int
299 _revnetgr_lookup(char *lookupdom, char *map, const char *str,
300 		 const char *dom, const char *group)
301 {
302 	int y, rv, rot;
303 	char key[MAXHOSTNAMELEN];
304 	char *result;
305 	int resultlen;
306 
307 	for (rot = 0; ; rot++) {
308 		switch (rot) {
309 			case(0): snprintf(key, MAXHOSTNAMELEN, "%s.%s",
310 					  str, dom?dom:lookupdom);
311 				 break;
312 			case(1): snprintf(key, MAXHOSTNAMELEN, "%s.*",
313 					  str);
314 				 break;
315 			case(2): snprintf(key, MAXHOSTNAMELEN, "*.%s",
316 					  dom?dom:lookupdom);
317 				 break;
318 			case(3): snprintf(key, MAXHOSTNAMELEN, "*.*");
319 				 break;
320 			default: return(0);
321 		}
322 		y = yp_match(lookupdom, map, key, strlen(key), &result,
323 			     &resultlen);
324 		if (y == 0) {
325 			rv = _listmatch(result, group, resultlen);
326 			free(result);
327 			if (rv) return(1);
328 		} else if (y != YPERR_KEY) {
329 			/*
330 			 * If we get an error other than 'no
331 			 * such key in map' then something is
332 			 * wrong and we should stop the search.
333 			 */
334 			return(-1);
335 		}
336 	}
337 }
338 #endif
339 
340 /*
341  * Search for a match in a netgroup.
342  */
343 int
344 innetgr(const char *group, const char *host, const char *user, const char *dom)
345 {
346 	char *hst, *usr, *dm;
347 	/* Sanity check */
348 
349 	if (group == NULL || !strlen(group))
350 		return (0);
351 
352 #ifdef YP
353 	_yp_innetgr = 1;
354 #endif
355 	setnetgrent(group);
356 #ifdef YP
357 	_yp_innetgr = 0;
358 	/*
359 	 * If we're in NIS-only mode, do the search using
360 	 * NIS 'reverse netgroup' lookups.
361 	 *
362 	 * What happens with 'reverse netgroup' lookups:
363 	 *
364 	 * 1) try 'reverse netgroup' lookup
365 	 *    1.a) if host is specified and user is null:
366 	 *         look in netgroup.byhost
367 	 *         (try host.domain, host.*, *.domain or *.*)
368 	 *         if found, return yes
369 	 *    1.b) if user is specified and host is null:
370 	 *         look in netgroup.byuser
371 	 *         (try host.domain, host.*, *.domain or *.*)
372 	 *         if found, return yes
373 	 *    1.c) if both host and user are specified,
374 	 *         don't do 'reverse netgroup' lookup.  It won't work.
375 	 *    1.d) if neither host ane user are specified (why?!?)
376 	 *         don't do 'reverse netgroup' lookup either.
377 	 * 2) if domain is specified and 'reverse lookup' is done:
378 	 *    'reverse lookup' was authoritative.  bye bye.
379 	 * 3) otherwise, too bad, try it the slow way.
380 	 */
381 	if (_use_only_yp && (host == NULL) != (user == NULL)) {
382 		int ret;
383 		if(yp_get_default_domain(&_netgr_yp_domain))
384 			return(0);
385 		ret = _revnetgr_lookup(_netgr_yp_domain,
386 				      host?"netgroup.byhost":"netgroup.byuser",
387 				      host?host:user, dom, group);
388 		if (ret == 1)
389 			return(1);
390 		else if (ret == 0 && dom != NULL)
391 			return(0);
392 	}
393 
394 	setnetgrent(group);
395 #endif /* YP */
396 
397 	while (getnetgrent(&hst, &usr, &dm))
398 		if ((host == NULL || hst == NULL || !strcmp(host, hst)) &&
399 		    (user == NULL || usr == NULL || !strcmp(user, usr)) &&
400 		    ( dom == NULL ||  dm == NULL || !strcmp(dom, dm))) {
401 			endnetgrent();
402 			return (1);
403 		}
404 	endnetgrent();
405 	return (0);
406 }
407 
408 /*
409  * Parse the netgroup file setting up the linked lists.
410  */
411 static int
412 parse_netgrp(const char *group)
413 {
414 	char *spos, *epos;
415 	int len, strpos;
416 #ifdef DEBUG
417 	int fields;
418 #endif
419 	char *pos, *gpos;
420 	struct netgrp *grp;
421 	struct linelist *lp = linehead;
422 
423 	/*
424 	 * First, see if the line has already been read in.
425 	 */
426 	while (lp) {
427 		if (!strcmp(group, lp->l_groupname))
428 			break;
429 		lp = lp->l_next;
430 	}
431 	if (lp == NULL &&
432 	    (lp = read_for_group(group)) == NULL)
433 		return (1);
434 	if (lp->l_parsed) {
435 #ifdef DEBUG
436 		/*
437 		 * This error message is largely superflous since the
438 		 * code handles the error condition successfully, and
439 		 * spewing it out from inside libc can actually hose
440 		 * certain programs.
441 		 */
442 		fprintf(stderr, "Cycle in netgroup %s\n", lp->l_groupname);
443 #endif
444 		return (1);
445 	} else
446 		lp->l_parsed = 1;
447 	pos = lp->l_line;
448 	/* Watch for null pointer dereferences, dammit! */
449 	while (pos != NULL && *pos != '\0') {
450 		if (*pos == '(') {
451 			grp = (struct netgrp *)malloc(sizeof (struct netgrp));
452 			bzero((char *)grp, sizeof (struct netgrp));
453 			grp->ng_next = grouphead.gr;
454 			grouphead.gr = grp;
455 			pos++;
456 			gpos = strsep(&pos, ")");
457 #ifdef DEBUG
458 			fields = 0;
459 #endif
460 			for (strpos = 0; strpos < 3; strpos++) {
461 				if ((spos = strsep(&gpos, ","))) {
462 #ifdef DEBUG
463 					fields++;
464 #endif
465 					while (*spos == ' ' || *spos == '\t')
466 						spos++;
467 					if ((epos = strpbrk(spos, " \t"))) {
468 						*epos = '\0';
469 						len = epos - spos;
470 					} else
471 						len = strlen(spos);
472 					if (len > 0) {
473 						grp->ng_str[strpos] =  (char *)
474 							malloc(len + 1);
475 						bcopy(spos, grp->ng_str[strpos],
476 							len + 1);
477 					}
478 				} else {
479 					/*
480 					 * All other systems I've tested
481 					 * return NULL for empty netgroup
482 					 * fields. It's up to user programs
483 					 * to handle the NULLs appropriately.
484 					 */
485 					grp->ng_str[strpos] = NULL;
486 				}
487 			}
488 #ifdef DEBUG
489 			/*
490 			 * Note: on other platforms, malformed netgroup
491 			 * entries are not normally flagged. While we
492 			 * can catch bad entries and report them, we should
493 			 * stay silent by default for compatibility's sake.
494 			 */
495 			if (fields < 3)
496 					fprintf(stderr, "Bad entry (%s%s%s%s%s) in netgroup \"%s\"\n",
497 						grp->ng_str[NG_HOST] == NULL ? "" : grp->ng_str[NG_HOST],
498 						grp->ng_str[NG_USER] == NULL ? "" : ",",
499 						grp->ng_str[NG_USER] == NULL ? "" : grp->ng_str[NG_USER],
500 						grp->ng_str[NG_DOM] == NULL ? "" : ",",
501 						grp->ng_str[NG_DOM] == NULL ? "" : grp->ng_str[NG_DOM],
502 						lp->l_groupname);
503 #endif
504 		} else {
505 			spos = strsep(&pos, ", \t");
506 			if (parse_netgrp(spos))
507 				continue;
508 		}
509 		if (pos == NULL)
510 			break;
511 		while (*pos == ' ' || *pos == ',' || *pos == '\t')
512 			pos++;
513 	}
514 	return (0);
515 }
516 
517 /*
518  * Read the netgroup file and save lines until the line for the netgroup
519  * is found. Return 1 if eof is encountered.
520  */
521 static struct linelist *
522 read_for_group(const char *group)
523 {
524 	char *pos, *spos, *linep = NULL, *olinep = NULL;
525 	int len, olen;
526 	int cont;
527 	struct linelist *lp;
528 	char line[LINSIZ + 2];
529 #ifdef YP
530 	char *result;
531 	int resultlen;
532 
533 	while (_netgr_yp_enabled || fgets(line, LINSIZ, netf) != NULL) {
534 		if (_netgr_yp_enabled) {
535 			if(!_netgr_yp_domain)
536 				if(yp_get_default_domain(&_netgr_yp_domain))
537 					continue;
538 			if (yp_match(_netgr_yp_domain, "netgroup", group,
539 					strlen(group), &result, &resultlen)) {
540 				free(result);
541 				if (_use_only_yp)
542 					return (NULL);
543 				else {
544 					_netgr_yp_enabled = 0;
545 					continue;
546 				}
547 			}
548 			snprintf(line, LINSIZ, "%s %s", group, result);
549 			free(result);
550 		}
551 #else
552 	while (fgets(line, LINSIZ, netf) != NULL) {
553 #endif
554 		pos = (char *)&line;
555 #ifdef YP
556 		if (*pos == '+') {
557 			_netgr_yp_enabled = 1;
558 			continue;
559 		}
560 #endif
561 		if (*pos == '#')
562 			continue;
563 		while (*pos == ' ' || *pos == '\t')
564 			pos++;
565 		spos = pos;
566 		while (*pos != ' ' && *pos != '\t' && *pos != '\n' &&
567 			*pos != '\0')
568 			pos++;
569 		len = pos - spos;
570 		while (*pos == ' ' || *pos == '\t')
571 			pos++;
572 		if (*pos != '\n' && *pos != '\0') {
573 			lp = (struct linelist *)malloc(sizeof (*lp));
574 			lp->l_parsed = 0;
575 			lp->l_groupname = (char *)malloc(len + 1);
576 			bcopy(spos, lp->l_groupname, len);
577 			*(lp->l_groupname + len) = '\0';
578 			len = strlen(pos);
579 			olen = 0;
580 
581 			/*
582 			 * Loop around handling line continuations.
583 			 */
584 			do {
585 				if (*(pos + len - 1) == '\n')
586 					len--;
587 				if (*(pos + len - 1) == '\\') {
588 					len--;
589 					cont = 1;
590 				} else
591 					cont = 0;
592 				if (len > 0) {
593 					linep = (char *)malloc(olen + len + 1);
594 					if (olen > 0) {
595 						bcopy(olinep, linep, olen);
596 						free(olinep);
597 					}
598 					bcopy(pos, linep + olen, len);
599 					olen += len;
600 					*(linep + olen) = '\0';
601 					olinep = linep;
602 				}
603 				if (cont) {
604 					if (fgets(line, LINSIZ, netf)) {
605 						pos = line;
606 						len = strlen(pos);
607 					} else
608 						cont = 0;
609 				}
610 			} while (cont);
611 			lp->l_line = linep;
612 			lp->l_next = linehead;
613 			linehead = lp;
614 
615 			/*
616 			 * If this is the one we wanted, we are done.
617 			 */
618 			if (!strcmp(lp->l_groupname, group))
619 				return (lp);
620 		}
621 	}
622 #ifdef YP
623 	/*
624 	 * Yucky. The recursive nature of this whole mess might require
625 	 * us to make more than one pass through the netgroup file.
626 	 * This might be best left outside the #ifdef YP, but YP is
627 	 * defined by default anyway, so I'll leave it like this
628 	 * until I know better.
629 	 */
630 	rewind(netf);
631 #endif
632 	return (NULL);
633 }
634