nss_db: Quash read implicit declaration warning
[platform/upstream/glibc.git] / nss / nsswitch.c
1 /* Copyright (C) 1996-1999,2001-2007,2009,2010 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, write to the Free
17    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18    02111-1307 USA.  */
19
20 #include <ctype.h>
21 #include <dlfcn.h>
22 #include <errno.h>
23 #include <netdb.h>
24 #include <bits/libc-lock.h>
25 #include <search.h>
26 #include <stdio.h>
27 #include <stdio_ext.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <aliases.h>
32 #include <grp.h>
33 #include <netinet/ether.h>
34 #include <pwd.h>
35 #include <shadow.h>
36
37 #if !defined DO_STATIC_NSS || defined SHARED
38 # include <gnu/lib-names.h>
39 #endif
40
41 #include "nsswitch.h"
42 #include "../nscd/nscd_proto.h"
43
44 /* Prototypes for the local functions.  */
45 static name_database *nss_parse_file (const char *fname) internal_function;
46 static name_database_entry *nss_getline (char *line) internal_function;
47 static service_user *nss_parse_service_list (const char *line)
48      internal_function;
49 static service_library *nss_new_service (name_database *database,
50                                          const char *name) internal_function;
51
52
53 /* Declare external database variables.  */
54 #define DEFINE_DATABASE(name)                                                 \
55   extern service_user *__nss_##name##_database attribute_hidden;              \
56   weak_extern (__nss_##name##_database)
57 #include "databases.def"
58 #undef DEFINE_DATABASE
59
60 /* Structure to map database name to variable.  */
61 static const struct
62 {
63   const char name[10];
64   service_user **dbp;
65 } databases[] =
66 {
67 #define DEFINE_DATABASE(name)                                                 \
68   { #name, &__nss_##name##_database },
69 #include "databases.def"
70 #undef DEFINE_DATABASE
71 };
72 #define ndatabases (sizeof (databases) / sizeof (databases[0]))
73
74 /* Flags whether custom rules for database is set.  */
75 bool __nss_database_custom[NSS_DBSIDX_max];
76
77
78 __libc_lock_define_initialized (static, lock)
79
80 #if !defined DO_STATIC_NSS || defined SHARED
81 /* String with revision number of the shared object files.  */
82 static const char *const __nss_shlib_revision = LIBNSS_FILES_SO + 15;
83 #endif
84
85 /* The root of the whole data base.  */
86 static name_database *service_table;
87
88
89 /* -1 == database not found
90     0 == database entry pointer stored */
91 int
92 __nss_database_lookup (const char *database, const char *alternate_name,
93                        const char *defconfig, service_user **ni)
94 {
95   /* Prevent multiple threads to change the service table.  */
96   __libc_lock_lock (lock);
97
98   /* Reconsider database variable in case some other thread called
99      `__nss_configure_lookup' while we waited for the lock.  */
100   if (*ni != NULL)
101     {
102       __libc_lock_unlock (lock);
103       return 0;
104     }
105
106   /* Are we initialized yet?  */
107   if (service_table == NULL)
108     /* Read config file.  */
109     service_table = nss_parse_file (_PATH_NSSWITCH_CONF);
110
111   /* Test whether configuration data is available.  */
112   if (service_table != NULL)
113     {
114       /* Return first `service_user' entry for DATABASE.  */
115       name_database_entry *entry;
116
117       /* XXX Could use some faster mechanism here.  But each database is
118          only requested once and so this might not be critical.  */
119       for (entry = service_table->entry; entry != NULL; entry = entry->next)
120         if (strcmp (database, entry->name) == 0)
121           *ni = entry->service;
122
123       if (*ni == NULL && alternate_name != NULL)
124         /* We haven't found an entry so far.  Try to find it with the
125            alternative name.  */
126         for (entry = service_table->entry; entry != NULL; entry = entry->next)
127           if (strcmp (alternate_name, entry->name) == 0)
128             *ni = entry->service;
129     }
130
131   /* No configuration data is available, either because nsswitch.conf
132      doesn't exist or because it doesn't has a line for this database.
133
134      DEFCONFIG specifies the default service list for this database,
135      or null to use the most common default.  */
136   if (*ni == NULL)
137     *ni = nss_parse_service_list (defconfig
138                                   ?: "nis [NOTFOUND=return] files");
139
140   __libc_lock_unlock (lock);
141
142   return 0;
143 }
144 libc_hidden_def (__nss_database_lookup)
145
146
147 /* -1 == not found
148     0 == function found
149     1 == finished */
150 int
151 __nss_lookup (service_user **ni, const char *fct_name, const char *fct2_name,
152               void **fctp)
153 {
154   *fctp = __nss_lookup_function (*ni, fct_name);
155   if (*fctp == NULL && fct2_name != NULL)
156     *fctp = __nss_lookup_function (*ni, fct2_name);
157
158   while (*fctp == NULL
159          && nss_next_action (*ni, NSS_STATUS_UNAVAIL) == NSS_ACTION_CONTINUE
160          && (*ni)->next != NULL)
161     {
162       *ni = (*ni)->next;
163
164       *fctp = __nss_lookup_function (*ni, fct_name);
165       if (*fctp == NULL && fct2_name != NULL)
166         *fctp = __nss_lookup_function (*ni, fct2_name);
167     }
168
169   return *fctp != NULL ? 0 : (*ni)->next == NULL ? 1 : -1;
170 }
171
172
173 /* -1 == not found
174     0 == adjusted for next function
175     1 == finished */
176 int
177 __nss_next2 (service_user **ni, const char *fct_name, const char *fct2_name,
178              void **fctp, int status, int all_values)
179 {
180   if (all_values)
181     {
182       if (nss_next_action (*ni, NSS_STATUS_TRYAGAIN) == NSS_ACTION_RETURN
183           && nss_next_action (*ni, NSS_STATUS_UNAVAIL) == NSS_ACTION_RETURN
184           && nss_next_action (*ni, NSS_STATUS_NOTFOUND) == NSS_ACTION_RETURN
185           && nss_next_action (*ni, NSS_STATUS_SUCCESS) == NSS_ACTION_RETURN)
186         return 1;
187     }
188   else
189     {
190       /* This is really only for debugging.  */
191       if (__builtin_expect (NSS_STATUS_TRYAGAIN > status
192                             || status > NSS_STATUS_RETURN, 0))
193          __libc_fatal ("illegal status in __nss_next");
194
195        if (nss_next_action (*ni, status) == NSS_ACTION_RETURN)
196          return 1;
197     }
198
199   if ((*ni)->next == NULL)
200     return -1;
201
202   do
203     {
204       *ni = (*ni)->next;
205
206       *fctp = __nss_lookup_function (*ni, fct_name);
207       if (*fctp == NULL && fct2_name != NULL)
208         *fctp = __nss_lookup_function (*ni, fct2_name);
209     }
210   while (*fctp == NULL
211          && nss_next_action (*ni, NSS_STATUS_UNAVAIL) == NSS_ACTION_CONTINUE
212          && (*ni)->next != NULL);
213
214   return *fctp != NULL ? 0 : -1;
215 }
216 libc_hidden_def (__nss_next2)
217
218
219 int
220 attribute_compat_text_section
221 __nss_next (service_user **ni, const char *fct_name, void **fctp, int status,
222             int all_values)
223 {
224   return __nss_next2 (ni, fct_name, NULL, fctp, status, all_values);
225 }
226
227
228 int
229 __nss_configure_lookup (const char *dbname, const char *service_line)
230 {
231   service_user *new_db;
232   size_t cnt;
233
234   for (cnt = 0; cnt < ndatabases; ++cnt)
235     {
236       int cmp = strcmp (dbname, databases[cnt].name);
237       if (cmp == 0)
238         break;
239       if (cmp < 0)
240         {
241           __set_errno (EINVAL);
242           return -1;
243         }
244     }
245
246   if (cnt == ndatabases)
247     {
248       __set_errno (EINVAL);
249       return -1;
250     }
251
252   /* Test whether it is really used.  */
253   if (databases[cnt].dbp == NULL)
254     /* Nothing to do, but we could do.  */
255     return 0;
256
257   /* Try to generate new data.  */
258   new_db = nss_parse_service_list (service_line);
259   if (new_db == NULL)
260     {
261       /* Illegal service specification.  */
262       __set_errno (EINVAL);
263       return -1;
264     }
265
266   /* Prevent multiple threads to change the service table.  */
267   __libc_lock_lock (lock);
268
269   /* Install new rules.  */
270   *databases[cnt].dbp = new_db;
271   __nss_database_custom[cnt] = true;
272
273   __libc_lock_unlock (lock);
274
275   return 0;
276 }
277
278
279 /* Comparison function for searching NI->known tree.  */
280 static int
281 known_compare (const void *p1, const void *p2)
282 {
283   return p1 == p2 ? 0 : strcmp (*(const char *const *) p1,
284                                 *(const char *const *) p2);
285 }
286
287
288 void *
289 __nss_lookup_function (service_user *ni, const char *fct_name)
290 {
291   void **found, *result;
292
293   /* We now modify global data.  Protect it.  */
294   __libc_lock_lock (lock);
295
296   /* Search the tree of functions previously requested.  Data in the
297      tree are `known_function' structures, whose first member is a
298      `const char *', the lookup key.  The search returns a pointer to
299      the tree node structure; the first member of the is a pointer to
300      our structure (i.e. what will be a `known_function'); since the
301      first member of that is the lookup key string, &FCT_NAME is close
302      enough to a pointer to our structure to use as a lookup key that
303      will be passed to `known_compare' (above).  */
304
305   found = __tsearch (&fct_name, &ni->known, &known_compare);
306   if (*found != &fct_name)
307     {
308       /* The search found an existing structure in the tree.  */
309       result = ((known_function *) *found)->fct_ptr;
310       PTR_DEMANGLE (result);
311     }
312   else
313     {
314       /* This name was not known before.  Now we have a node in the tree
315          (in the proper sorted position for FCT_NAME) that points to
316          &FCT_NAME instead of any real `known_function' structure.
317          Allocate a new structure and fill it in.  */
318
319       known_function *known = malloc (sizeof *known);
320       if (! known)
321         {
322         remove_from_tree:
323           /* Oops.  We can't instantiate this node properly.
324              Remove it from the tree.  */
325           __tdelete (&fct_name, &ni->known, &known_compare);
326           result = NULL;
327         }
328       else
329         {
330           /* Point the tree node at this new structure.  */
331           *found = known;
332           known->fct_name = fct_name;
333
334           if (ni->library == NULL)
335             {
336               /* This service has not yet been used.  Fetch the service
337                  library for it, creating a new one if need be.  If there
338                  is no service table from the file, this static variable
339                  holds the head of the service_library list made from the
340                  default configuration.  */
341               static name_database default_table;
342               ni->library = nss_new_service (service_table ?: &default_table,
343                                              ni->name);
344               if (ni->library == NULL)
345                 {
346                   /* This only happens when out of memory.  */
347                   free (known);
348                   goto remove_from_tree;
349                 }
350             }
351
352 #if !defined DO_STATIC_NSS || defined SHARED
353           if (ni->library->lib_handle == NULL)
354             {
355               /* Load the shared library.  */
356               size_t shlen = (7 + strlen (ni->library->name) + 3
357                               + strlen (__nss_shlib_revision) + 1);
358               int saved_errno = errno;
359               char shlib_name[shlen];
360
361               /* Construct shared object name.  */
362               __stpcpy (__stpcpy (__stpcpy (__stpcpy (shlib_name,
363                                                       "libnss_"),
364                                             ni->library->name),
365                                   ".so"),
366                         __nss_shlib_revision);
367
368               ni->library->lib_handle = __libc_dlopen (shlib_name);
369               if (ni->library->lib_handle == NULL)
370                 {
371                   /* Failed to load the library.  */
372                   ni->library->lib_handle = (void *) -1l;
373                   __set_errno (saved_errno);
374                 }
375             }
376
377           if (ni->library->lib_handle == (void *) -1l)
378             /* Library not found => function not found.  */
379             result = NULL;
380           else
381             {
382               /* Get the desired function.  */
383               size_t namlen = (5 + strlen (ni->library->name) + 1
384                                + strlen (fct_name) + 1);
385               char name[namlen];
386
387               /* Construct the function name.  */
388               __stpcpy (__stpcpy (__stpcpy (__stpcpy (name, "_nss_"),
389                                             ni->library->name),
390                                   "_"),
391                         fct_name);
392
393               /* Look up the symbol.  */
394               result = __libc_dlsym (ni->library->lib_handle, name);
395             }
396 #else
397           /* We can't get function address dynamically in static linking. */
398           {
399 # define DEFINE_ENT(h,nm)                                                     \
400             { #h"_get"#nm"ent_r", _nss_##h##_get##nm##ent_r },                \
401             { #h"_end"#nm"ent", _nss_##h##_end##nm##ent },                    \
402             { #h"_set"#nm"ent", _nss_##h##_set##nm##ent },
403 # define DEFINE_GET(h,nm)                                                     \
404             { #h"_get"#nm"_r", _nss_##h##_get##nm##_r },
405 # define DEFINE_GETBY(h,nm,ky)                                                \
406             { #h"_get"#nm"by"#ky"_r", _nss_##h##_get##nm##by##ky##_r },
407             static struct fct_tbl { const char *fname; void *fp; } *tp, tbl[] =
408               {
409 # include "function.def"
410                 { NULL, NULL }
411               };
412             size_t namlen = (5 + strlen (ni->library->name) + 1
413                              + strlen (fct_name) + 1);
414             char name[namlen];
415
416             /* Construct the function name.  */
417             __stpcpy (__stpcpy (__stpcpy (name, ni->library->name),
418                                 "_"),
419                       fct_name);
420
421             result = NULL;
422             for (tp = &tbl[0]; tp->fname; tp++)
423               if (strcmp (tp->fname, name) == 0)
424                 {
425                   result = tp->fp;
426                   break;
427                 }
428           }
429 #endif
430
431           /* Remember function pointer for later calls.  Even if null, we
432              record it so a second try needn't search the library again.  */
433           known->fct_ptr = result;
434           PTR_MANGLE (known->fct_ptr);
435         }
436     }
437
438   /* Remove the lock.  */
439   __libc_lock_unlock (lock);
440
441   return result;
442 }
443 libc_hidden_def (__nss_lookup_function)
444
445
446 static name_database *
447 internal_function
448 nss_parse_file (const char *fname)
449 {
450   FILE *fp;
451   name_database *result;
452   name_database_entry *last;
453   char *line;
454   size_t len;
455
456   /* Open the configuration file.  */
457   fp = fopen (fname, "rc");
458   if (fp == NULL)
459     return NULL;
460
461   /* No threads use this stream.  */
462   __fsetlocking (fp, FSETLOCKING_BYCALLER);
463
464   result = (name_database *) malloc (sizeof (name_database));
465   if (result == NULL)
466     return NULL;
467
468   result->entry = NULL;
469   result->library = NULL;
470   last = NULL;
471   line = NULL;
472   len = 0;
473   do
474     {
475       name_database_entry *this;
476       ssize_t n;
477
478       n = __getline (&line, &len, fp);
479       if (n < 0)
480         break;
481       if (line[n - 1] == '\n')
482         line[n - 1] = '\0';
483
484       /* Because the file format does not know any form of quoting we
485          can search forward for the next '#' character and if found
486          make it terminating the line.  */
487       *__strchrnul (line, '#') = '\0';
488
489       /* If the line is blank it is ignored.  */
490       if (line[0] == '\0')
491         continue;
492
493       /* Each line completely specifies the actions for a database.  */
494       this = nss_getline (line);
495       if (this != NULL)
496         {
497           if (last != NULL)
498             last->next = this;
499           else
500             result->entry = this;
501
502           last = this;
503         }
504     }
505   while (!feof_unlocked (fp));
506
507   /* Free the buffer.  */
508   free (line);
509   /* Close configuration file.  */
510   fclose (fp);
511
512   return result;
513 }
514
515
516 /* Read the source names:
517         `( <source> ( "[" "!"? (<status> "=" <action> )+ "]" )? )*'
518    */
519 static service_user *
520 internal_function
521 nss_parse_service_list (const char *line)
522 {
523   service_user *result = NULL, **nextp = &result;
524
525   while (1)
526     {
527       service_user *new_service;
528       const char *name;
529
530       while (isspace (line[0]))
531         ++line;
532       if (line[0] == '\0')
533         /* No source specified.  */
534         return result;
535
536       /* Read <source> identifier.  */
537       name = line;
538       while (line[0] != '\0' && !isspace (line[0]) && line[0] != '[')
539         ++line;
540       if (name == line)
541         return result;
542
543
544       new_service = (service_user *) malloc (sizeof (service_user)
545                                              + (line - name + 1));
546       if (new_service == NULL)
547         return result;
548
549       *((char *) __mempcpy (new_service->name, name, line - name)) = '\0';
550
551       /* Set default actions.  */
552       new_service->actions[2 + NSS_STATUS_TRYAGAIN] = NSS_ACTION_CONTINUE;
553       new_service->actions[2 + NSS_STATUS_UNAVAIL] = NSS_ACTION_CONTINUE;
554       new_service->actions[2 + NSS_STATUS_NOTFOUND] = NSS_ACTION_CONTINUE;
555       new_service->actions[2 + NSS_STATUS_SUCCESS] = NSS_ACTION_RETURN;
556       new_service->actions[2 + NSS_STATUS_RETURN] = NSS_ACTION_RETURN;
557       new_service->library = NULL;
558       new_service->known = NULL;
559       new_service->next = NULL;
560
561       while (isspace (line[0]))
562         ++line;
563
564       if (line[0] == '[')
565         {
566           /* Read criterions.  */
567           do
568             ++line;
569           while (line[0] != '\0' && isspace (line[0]));
570
571           do
572             {
573               int not;
574               enum nss_status status;
575               lookup_actions action;
576
577               /* Grok ! before name to mean all statii but that one.  */
578               not = line[0] == '!';
579               if (not)
580                 ++line;
581
582               /* Read status name.  */
583               name = line;
584               while (line[0] != '\0' && !isspace (line[0]) && line[0] != '='
585                      && line[0] != ']')
586                 ++line;
587
588               /* Compare with known statii.  */
589               if (line - name == 7)
590                 {
591                   if (__strncasecmp (name, "SUCCESS", 7) == 0)
592                     status = NSS_STATUS_SUCCESS;
593                   else if (__strncasecmp (name, "UNAVAIL", 7) == 0)
594                     status = NSS_STATUS_UNAVAIL;
595                   else
596                     return result;
597                 }
598               else if (line - name == 8)
599                 {
600                   if (__strncasecmp (name, "NOTFOUND", 8) == 0)
601                     status = NSS_STATUS_NOTFOUND;
602                   else if (__strncasecmp (name, "TRYAGAIN", 8) == 0)
603                     status = NSS_STATUS_TRYAGAIN;
604                   else
605                     return result;
606                 }
607               else
608                 return result;
609
610               while (isspace (line[0]))
611                 ++line;
612               if (line[0] != '=')
613                 return result;
614               do
615                 ++line;
616               while (isspace (line[0]));
617
618               name = line;
619               while (line[0] != '\0' && !isspace (line[0]) && line[0] != '='
620                      && line[0] != ']')
621                 ++line;
622
623               if (line - name == 6 && __strncasecmp (name, "RETURN", 6) == 0)
624                 action = NSS_ACTION_RETURN;
625               else if (line - name == 8
626                        && __strncasecmp (name, "CONTINUE", 8) == 0)
627                 action = NSS_ACTION_CONTINUE;
628               else
629                 return result;
630
631               if (not)
632                 {
633                   /* Save the current action setting for this status,
634                      set them all to the given action, and reset this one.  */
635                   const lookup_actions save = new_service->actions[2 + status];
636                   new_service->actions[2 + NSS_STATUS_TRYAGAIN] = action;
637                   new_service->actions[2 + NSS_STATUS_UNAVAIL] = action;
638                   new_service->actions[2 + NSS_STATUS_NOTFOUND] = action;
639                   new_service->actions[2 + NSS_STATUS_SUCCESS] = action;
640                   new_service->actions[2 + status] = save;
641                 }
642               else
643                 new_service->actions[2 + status] = action;
644
645               /* Skip white spaces.  */
646               while (isspace (line[0]))
647                 ++line;
648             }
649           while (line[0] != ']');
650
651           /* Skip the ']'.  */
652           ++line;
653         }
654
655       *nextp = new_service;
656       nextp = &new_service->next;
657     }
658 }
659
660 static name_database_entry *
661 internal_function
662 nss_getline (char *line)
663 {
664   const char *name;
665   name_database_entry *result;
666   size_t len;
667
668   /* Ignore leading white spaces.  ATTENTION: this is different from
669      what is implemented in Solaris.  The Solaris man page says a line
670      beginning with a white space character is ignored.  We regard
671      this as just another misfeature in Solaris.  */
672   while (isspace (line[0]))
673     ++line;
674
675   /* Recognize `<database> ":"'.  */
676   name = line;
677   while (line[0] != '\0' && !isspace (line[0]) && line[0] != ':')
678     ++line;
679   if (line[0] == '\0' || name == line)
680     /* Syntax error.  */
681     return NULL;
682   *line++ = '\0';
683
684   len = strlen (name) + 1;
685
686   result = (name_database_entry *) malloc (sizeof (name_database_entry) + len);
687   if (result == NULL)
688     return NULL;
689
690   /* Save the database name.  */
691   memcpy (result->name, name, len);
692
693   /* Parse the list of services.  */
694   result->service = nss_parse_service_list (line);
695
696   result->next = NULL;
697   return result;
698 }
699
700
701 static service_library *
702 internal_function
703 nss_new_service (name_database *database, const char *name)
704 {
705   service_library **currentp = &database->library;
706
707   while (*currentp != NULL)
708     {
709       if (strcmp ((*currentp)->name, name) == 0)
710         return *currentp;
711       currentp = &(*currentp)->next;
712     }
713
714   /* We have to add the new service.  */
715   *currentp = (service_library *) malloc (sizeof (service_library));
716   if (*currentp == NULL)
717     return NULL;
718
719   (*currentp)->name = name;
720   (*currentp)->lib_handle = NULL;
721   (*currentp)->next = NULL;
722
723   return *currentp;
724 }
725
726
727 /* Called by nscd and nscd alone.  */
728 void
729 __nss_disable_nscd (void)
730 {
731   /* Disable all uses of NSCD.  */
732   __nss_not_use_nscd_passwd = -1;
733   __nss_not_use_nscd_group = -1;
734   __nss_not_use_nscd_hosts = -1;
735   __nss_not_use_nscd_services = -1;
736 }
737
738
739 /* Free all resources if necessary.  */
740 libc_freeres_fn (free_mem)
741 {
742   name_database *top = service_table;
743   name_database_entry *entry;
744   service_library *library;
745
746   if (top == NULL)
747     /* Maybe we have not read the nsswitch.conf file.  */
748     return;
749
750   /* Don't disturb ongoing other threads (if there are any).  */
751   service_table = NULL;
752
753   entry = top->entry;
754   while (entry != NULL)
755     {
756       name_database_entry *olde = entry;
757       service_user *service = entry->service;
758
759       while (service != NULL)
760         {
761           service_user *olds = service;
762
763           if (service->known != NULL)
764             __tdestroy (service->known, free);
765
766           service = service->next;
767           free (olds);
768         }
769
770       entry = entry->next;
771       free (olde);
772     }
773
774   library = top->library;
775   while (library != NULL)
776     {
777       service_library *oldl = library;
778
779       if (library->lib_handle && library->lib_handle != (void *) -1l)
780         __libc_dlclose (library->lib_handle);
781
782       library = library->next;
783       free (oldl);
784     }
785
786   free (top);
787 }