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