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