nsdispatch.c revision 1.23 1 /* $NetBSD: nsdispatch.c,v 1.23 2004/08/02 00:19:34 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 1997, 1998, 1999, 2004 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn; and by Jason R. Thorpe.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*-
40 * Copyright (c) 2003 Networks Associates Technology, Inc.
41 * All rights reserved.
42 *
43 * Portions of this software were developed for the FreeBSD Project by
44 * Jacques A. Vidrine, Safeport Network Services, and Network
45 * Associates Laboratories, the Security Research Division of Network
46 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
47 * ("CBOSS"), as part of the DARPA CHATS research program.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
51 * are met:
52 * 1. Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * 2. Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in the
56 * documentation and/or other materials provided with the distribution.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 */
70
71 #include <sys/cdefs.h>
72 #if defined(LIBC_SCCS) && !defined(lint)
73 __RCSID("$NetBSD: nsdispatch.c,v 1.23 2004/08/02 00:19:34 thorpej Exp $");
74 #endif /* LIBC_SCCS and not lint */
75
76 #include "namespace.h"
77
78 #include <sys/types.h>
79 #include <sys/param.h>
80 #include <sys/stat.h>
81 #include <sys/queue.h>
82
83 #include <assert.h>
84 #ifdef __ELF__
85 #include <dlfcn.h>
86 #endif /* __ELF__ */
87 #include <err.h>
88 #include <fcntl.h>
89 #define _NS_PRIVATE
90 #include <nsswitch.h>
91 #include <stdarg.h>
92 #include <stdio.h>
93 #include <stdlib.h>
94 #include <string.h>
95 #include <unistd.h>
96
97 #include "reentrant.h"
98
99 extern FILE *_nsyyin;
100 extern int _nsyyparse(void);
101
102
103 #ifdef __weak_alias
104 __weak_alias(nsdispatch,_nsdispatch)
105 #endif
106
107
108 /*
109 * default sourcelist: `files'
110 */
111 const ns_src __nsdefaultsrc[] = {
112 { NSSRC_FILES, NS_SUCCESS },
113 { 0 },
114 };
115
116 /* Database, source mappings. */
117 static u_int _nsmapsize;
118 static ns_dbt *_nsmap;
119
120 /* Nsswitch modules. */
121 static u_int _nsmodsize;
122 static ns_mod *_nsmod;
123
124 /* Placeholder for built-in modules' dlopen() handles. */
125 static void *_nsbuiltin = &_nsbuiltin;
126
127 #ifdef _REENTRANT
128 /*
129 * Global nsswitch data structures are mostly read-only, but we update them
130 * when we read or re-read nsswitch.conf.
131 */
132 static rwlock_t _nslock = RWLOCK_INITIALIZER;
133
134 /*
135 * List of threads currently in nsdispatch(). We use this to detect
136 * recursive calls and avoid reloading configuration in such cases,
137 * which could cause deadlock.
138 */
139 struct _ns_drec {
140 LIST_ENTRY(_ns_drec) list;
141 thr_t thr;
142 };
143 static LIST_HEAD(, _ns_drec) _ns_drec = LIST_HEAD_INITIALIZER(&_ns_drec);
144 static mutex_t _ns_drec_lock = MUTEX_INITIALIZER;
145 #endif /* _REENTRANT */
146
147
148 /*
149 * Runtime determination of whether we are dynamically linked or not.
150 */
151 #ifdef __ELF__
152 extern int _DYNAMIC __attribute__((__weak__));
153 #define is_dynamic() (&_DYNAMIC != NULL)
154 #else
155 #define is_dynamic() (0) /* don't bother - switch to ELF! */
156 #endif /* __ELF__ */
157
158
159 /*
160 * size of dynamic array chunk for _nsmap and _nsmap[x].srclist (and other
161 * growing arrays).
162 */
163 #define NSELEMSPERCHUNK 8
164
165 /*
166 * Dynamically growable arrays are used for lists of databases, sources,
167 * and modules. The following "vector" API is used to isolate the
168 * common operations.
169 */
170 typedef void (*_nsvect_free_elem)(void *);
171
172 static void *
173 _nsvect_append(const void *elem, void *vec, u_int *count, size_t esize)
174 {
175 void *p;
176
177 if ((*count % NSELEMSPERCHUNK) == 0) {
178 p = realloc(vec, (*count + NSELEMSPERCHUNK) * esize);
179 if (p == NULL)
180 return (NULL);
181 vec = p;
182 }
183 memmove((void *)(((uintptr_t)vec) + (*count * esize)), elem, esize);
184 (*count)++;
185 return (vec);
186 }
187
188 static void *
189 _nsvect_elem(u_int i, void *vec, u_int count, size_t esize)
190 {
191
192 if (i < count)
193 return ((void *)((uintptr_t)vec + (i * esize)));
194 else
195 return (NULL);
196 }
197
198 static void
199 _nsvect_free(void *vec, u_int *count, size_t esize, _nsvect_free_elem free_elem)
200 {
201 void *elem;
202 u_int i;
203
204 for (i = 0; i < *count; i++) {
205 elem = _nsvect_elem(i, vec, *count, esize);
206 if (elem != NULL)
207 (*free_elem)(elem);
208 }
209 if (vec != NULL)
210 free(vec);
211 *count = 0;
212 }
213 #define _NSVECT_FREE(v, c, s, f) \
214 do { \
215 _nsvect_free((v), (c), (s), (f)); \
216 (v) = NULL; \
217 } while (/*CONSTCOND*/0)
218
219 static int
220 _nsdbtcmp(const void *a, const void *b)
221 {
222
223 return (strcasecmp(((const ns_dbt *)a)->name,
224 ((const ns_dbt *)b)->name));
225 }
226
227 static int
228 _nsmodcmp(const void *a, const void *b)
229 {
230
231 return (strcasecmp(((const ns_mod *)a)->name,
232 ((const ns_mod *)b)->name));
233 }
234
235 static int
236 _nsmtabcmp(const void *a, const void *b)
237 {
238 int cmp;
239
240 cmp = strcmp(((const ns_mtab *)a)->name,
241 ((const ns_mtab *)b)->name);
242 if (cmp)
243 return (cmp);
244
245 return (strcasecmp(((const ns_mtab *)a)->database,
246 ((const ns_mtab *)b)->database));
247 }
248
249 static void
250 _nsmodfree(ns_mod *mod)
251 {
252
253 /*LINTED const cast*/
254 free((void *)mod->name);
255 if (mod->handle == NULL)
256 return;
257 if (mod->unregister != NULL)
258 (*mod->unregister)(mod->mtab, mod->mtabsize);
259 #ifdef __ELF__
260 if (mod->handle != _nsbuiltin)
261 (void) dlclose(mod->handle);
262 #endif /* __ELF__ */
263 }
264
265 /*
266 * Load a built-in or dyanamically linked module. If the `reg_fn'
267 * argument is non-NULL, assume a built-in module and use `reg_fn'
268 * to register it. Otherwise, search for a dynamic nsswitch module.
269 */
270 static int
271 _nsloadmod(const char *source, nss_module_register_fn reg_fn)
272 {
273 char buf[PATH_MAX];
274 ns_mod mod, *new;
275
276 memset(&mod, 0, sizeof(mod));
277 mod.name = strdup(source);
278 if (mod.name == NULL)
279 return (-1);
280
281 if (reg_fn != NULL) {
282 /*
283 * The placeholder is required, as a NULL handle
284 * represents an invalid module.
285 */
286 mod.handle = _nsbuiltin;
287 } else if (!is_dynamic()) {
288 goto out;
289 } else {
290 #ifdef __ELF__
291 if (snprintf(buf, sizeof(buf), "nss_%s.so.%d", mod.name,
292 NSS_MODULE_INTERFACE_VERSION) >= (int)sizeof(buf))
293 goto out;
294 mod.handle = dlopen(buf, RTLD_LOCAL | RTLD_LAZY);
295 if (mod.handle == NULL) {
296 #ifdef _NSS_DEBUG
297 /*
298 * This gets pretty annoying, since the built-in
299 * sources are not yet modules.
300 */
301 /* XXX log some error? */
302 #endif
303 goto out;
304 }
305 reg_fn = (nss_module_register_fn) dlsym(mod.handle,
306 "nss_module_register");
307 if (reg_fn == NULL) {
308 (void) dlclose(mod.handle);
309 mod.handle = NULL;
310 /* XXX log some error? */
311 goto out;
312 }
313 #else /* ! __ELF__ */
314 mod.handle = NULL;
315 #endif /* __ELF__ */
316 }
317 mod.mtab = (*reg_fn)(mod.name, &mod.mtabsize, &mod.unregister);
318 if (mod.mtab == NULL || mod.mtabsize == 0) {
319 #ifdef __ELF__
320 if (mod.handle != _nsbuiltin)
321 (void) dlclose(mod.handle);
322 #endif /* __ELF__ */
323 mod.handle = NULL;
324 /* XXX log some error? */
325 goto out;
326 }
327 if (mod.mtabsize > 1)
328 qsort(mod.mtab, mod.mtabsize, sizeof(mod.mtab[0]),
329 _nsmtabcmp);
330 out:
331 new = _nsvect_append(&mod, _nsmod, &_nsmodsize, sizeof(*_nsmod));
332 if (new == NULL) {
333 _nsmodfree(&mod);
334 return (-1);
335 }
336 _nsmod = new;
337 /* _nsmodsize already incremented */
338
339 qsort(_nsmod, _nsmodsize, sizeof(*_nsmod), _nsmodcmp);
340 return (0);
341 }
342
343 static void
344 _nsloadbuiltin(void)
345 {
346
347 /* Do nothing, for now. */
348 }
349
350 int
351 _nsdbtaddsrc(ns_dbt *dbt, const ns_src *src)
352 {
353 void *new;
354 const ns_mod *mod;
355 ns_mod modkey;
356
357 _DIAGASSERT(dbt != NULL);
358 _DIAGASSERT(src != NULL);
359
360 new = _nsvect_append(src, dbt->srclist, &dbt->srclistsize,
361 sizeof(*src));
362 if (new == NULL)
363 return (-1);
364 dbt->srclist = new;
365 /* dbt->srclistsize already incremented */
366
367 modkey.name = src->name;
368 mod = bsearch(&modkey, _nsmod, _nsmodsize, sizeof(*_nsmod),
369 _nsmodcmp);
370 if (mod == NULL)
371 return (_nsloadmod(src->name, NULL));
372
373 return (0);
374 }
375
376 void
377 _nsdbtdump(const ns_dbt *dbt)
378 {
379 int i;
380
381 _DIAGASSERT(dbt != NULL);
382
383 printf("%s (%d source%s):", dbt->name, dbt->srclistsize,
384 dbt->srclistsize == 1 ? "" : "s");
385 for (i = 0; i < dbt->srclistsize; i++) {
386 printf(" %s", dbt->srclist[i].name);
387 if (!(dbt->srclist[i].flags &
388 (NS_UNAVAIL|NS_NOTFOUND|NS_TRYAGAIN)) &&
389 (dbt->srclist[i].flags & NS_SUCCESS))
390 continue;
391 printf(" [");
392 if (!(dbt->srclist[i].flags & NS_SUCCESS))
393 printf(" SUCCESS=continue");
394 if (dbt->srclist[i].flags & NS_UNAVAIL)
395 printf(" UNAVAIL=return");
396 if (dbt->srclist[i].flags & NS_NOTFOUND)
397 printf(" NOTFOUND=return");
398 if (dbt->srclist[i].flags & NS_TRYAGAIN)
399 printf(" TRYAGAIN=return");
400 printf(" ]");
401 }
402 printf("\n");
403 }
404
405 static void
406 _nssrclist_free(ns_src **src, u_int srclistsize)
407 {
408 u_int i;
409
410 for (i = 0; i < srclistsize; i++) {
411 if ((*src)[i].name != NULL) {
412 /*LINTED const cast*/
413 free((void *)(*src)[i].name);
414 }
415 }
416 free(*src);
417 *src = NULL;
418 }
419
420 static void
421 _nsdbtfree(ns_dbt *dbt)
422 {
423
424 _nssrclist_free(&dbt->srclist, dbt->srclistsize);
425 if (dbt->name != NULL) {
426 /*LINTED const cast*/
427 free((void *)dbt->name);
428 }
429 }
430
431 int
432 _nsdbtput(const ns_dbt *dbt)
433 {
434 ns_dbt *p;
435 void *new;
436 u_int i;
437
438 _DIAGASSERT(dbt != NULL);
439
440 for (i = 0; i < _nsmapsize; i++) {
441 p = _nsvect_elem(i, _nsmap, _nsmapsize, sizeof(*_nsmap));
442 if (strcasecmp(dbt->name, p->name) == 0) {
443 /* overwrite existing entry */
444 if (p->srclist != NULL)
445 _nssrclist_free(&p->srclist, p->srclistsize);
446 memmove(p, dbt, sizeof(*dbt));
447 return (0);
448 }
449 }
450 new = _nsvect_append(dbt, _nsmap, &_nsmapsize, sizeof(*_nsmap));
451 if (new == NULL)
452 return (-1);
453 _nsmap = new;
454 /* _nsmapsize already incremented */
455
456 return (0);
457 }
458
459 /*
460 * This function is called each time nsdispatch() is called. If this
461 * is the first call, or if the configuration has changed, (re-)prepare
462 * the global data used by NSS.
463 */
464 static int
465 _nsconfigure(void)
466 {
467 #ifdef _REENTRANT
468 static mutex_t _nsconflock = MUTEX_INITIALIZER;
469 #endif
470 static time_t _nsconfmod;
471 struct stat statbuf;
472
473 mutex_lock(&_nsconflock);
474
475 if (stat(_PATH_NS_CONF, &statbuf) == -1) {
476 /*
477 * No nsswitch.conf; just use whatever configuration we
478 * currently have, or fall back on the defaults specified
479 * by the caller.
480 */
481 mutex_unlock(&_nsconflock);
482 return (0);
483 }
484
485 if (statbuf.st_mtime <= _nsconfmod) {
486 /* Internal state is up-to-date with nsswitch.conf. */
487 mutex_unlock(&_nsconflock);
488 return (0);
489 }
490
491 /*
492 * Ok, we've decided we need to update the nsswitch configuration
493 * structures. Acquire a write-lock on _nslock while continuing
494 * to hold _nsconflock. Acquiring a write-lock blocks while
495 * waiting for other threads already holding a read-lock to clear.
496 * We hold _nsconflock for the duration, and update the time stamp
497 * at the end of the update operation, at which time we release
498 * both locks.
499 */
500 rwlock_wrlock(&_nslock);
501
502 _nsyyin = fopen(_PATH_NS_CONF, "r");
503 if (_nsyyin == NULL) {
504 /*
505 * Unable to open nsswitch.conf; behave as though the
506 * stat() above failed. Even though we have already
507 * updated _nsconfmod, if the file reappears, the
508 * mtime will change.
509 */
510 goto out;
511 }
512
513 _NSVECT_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap),
514 (_nsvect_free_elem) _nsdbtfree);
515 _NSVECT_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod),
516 (_nsvect_free_elem) _nsmodfree);
517
518 _nsloadbuiltin();
519
520 _nsyyparse();
521 (void) fclose(_nsyyin);
522 if (_nsmapsize != 0)
523 qsort(_nsmap, _nsmapsize, sizeof(*_nsmap), _nsdbtcmp);
524
525 _nsconfmod = statbuf.st_mtime;
526
527 out:
528 rwlock_unlock(&_nslock);
529 mutex_unlock(&_nsconflock);
530 return (0);
531 }
532
533 static nss_method
534 _nsmethod(const char *source, const char *database, const char *method,
535 const ns_dtab disp_tab[], void **cb_data)
536 {
537 int curdisp;
538 ns_mod *mod, modkey;
539 ns_mtab *mtab, mtabkey;
540
541 if (disp_tab != NULL) {
542 for (curdisp = 0; disp_tab[curdisp].src != NULL; curdisp++) {
543 if (strcasecmp(source, disp_tab[curdisp].src) == 0) {
544 *cb_data = disp_tab[curdisp].cb_data;
545 return (disp_tab[curdisp].callback);
546 }
547 }
548 }
549
550 modkey.name = source;
551 mod = bsearch(&modkey, _nsmod, _nsmodsize, sizeof(*_nsmod),
552 _nsmodcmp);
553 if (mod != NULL && mod->handle != NULL) {
554 mtabkey.database = database;
555 mtabkey.name = method;
556 mtab = bsearch(&mtabkey, mod->mtab, mod->mtabsize,
557 sizeof(mod->mtab[0]), _nsmtabcmp);
558 if (mtab != NULL) {
559 *cb_data = mtab->mdata;
560 return (mtab->method);
561 }
562 }
563
564 *cb_data = NULL;
565 return (NULL);
566 }
567
568 int
569 /*ARGSUSED*/
570 nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database,
571 const char *method, const ns_src defaults[], ...)
572 {
573 static int _nsdispatching;
574 #ifdef _REENTRANT
575 struct _ns_drec drec, *ldrec;
576 #endif
577 va_list ap;
578 int i, result;
579 ns_dbt key;
580 const ns_dbt *dbt;
581 const ns_src *srclist;
582 int srclistsize;
583 nss_method cb;
584 void *cb_data;
585
586 _DIAGASSERT(database != NULL);
587 _DIAGASSERT(method != NULL);
588 if (database == NULL || method == NULL)
589 return (NS_UNAVAIL);
590
591 /*
592 * In both the threaded and non-threaded cases, avoid reloading
593 * the configuration if the current thread is already running
594 * nsdispatch() (i.e. recursive call).
595 *
596 * In the non-threaded case, this avoids changing the data structures
597 * while we're using them.
598 *
599 * In the threaded case, this avoids trying to take a write lock
600 * while the current thread holds a read lock (which would result
601 * in deadlock).
602 */
603 #ifdef _REENTRANT
604 if (__isthreaded) {
605 drec.thr = thr_self();
606 mutex_lock(&_ns_drec_lock);
607 LIST_FOREACH(ldrec, &_ns_drec, list) {
608 if (ldrec->thr == drec.thr)
609 break;
610 }
611 LIST_INSERT_HEAD(&_ns_drec, &drec, list);
612 mutex_unlock(&_ns_drec_lock);
613 if (ldrec == NULL && _nsconfigure()) {
614 mutex_lock(&_ns_drec_lock);
615 LIST_REMOVE(&drec, list);
616 mutex_unlock(&_ns_drec_lock);
617 return (NS_UNAVAIL);
618 }
619 } else {
620 if (_nsdispatching == 0 && _nsconfigure())
621 return (NS_UNAVAIL);
622 _nsdispatching = 1;
623 }
624 #else
625 if (_nsdispatching == 0 && _nsconfigure())
626 return (NS_UNAVAIL);
627 _nsdispatching = 1;
628 #endif /* _REENTRANT */
629
630 rwlock_rdlock(&_nslock);
631
632 key.name = database;
633 dbt = bsearch(&key, _nsmap, _nsmapsize, sizeof(*_nsmap), _nsdbtcmp);
634 if (dbt != NULL) {
635 srclist = dbt->srclist;
636 srclistsize = dbt->srclistsize;
637 } else {
638 srclist = defaults;
639 srclistsize = 0;
640 while (srclist[srclistsize].name != NULL)
641 srclistsize++;
642 }
643 result = 0;
644
645 for (i = 0; i < srclistsize; i++) {
646 cb = _nsmethod(srclist[i].name, database, method,
647 disp_tab, &cb_data);
648 result = 0;
649 if (cb != NULL) {
650 va_start(ap, defaults);
651 result = (*cb)(retval, cb_data, ap);
652 va_end(ap);
653 if (result & srclist[i].flags)
654 break;
655 }
656 }
657
658 rwlock_unlock(&_nslock);
659
660 #ifdef _REENTRANT
661 if (__isthreaded) {
662 mutex_lock(&_ns_drec_lock);
663 LIST_REMOVE(&drec, list);
664 mutex_unlock(&_ns_drec_lock);
665 } else
666 _nsdispatching = 0;
667 #else
668 _nsdispatching = 0;
669 #endif /* _REENTRANT */
670
671 return (result ? result : NS_NOTFOUND);
672 }
673