xref: /freebsd/lib/libc/net/nsdispatch.c (revision 4f29da19bd44f0e99f021510460a81bf754c21d2)
1 /*	$NetBSD: nsdispatch.c,v 1.9 1999/01/25 00:16:17 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997, 1998, 1999 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.
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  * Copyright (c) 2003 Networks Associates Technology, Inc.
40  * All rights reserved.
41  *
42  * Portions of this software were developed for the FreeBSD Project by
43  * Jacques A. Vidrine, Safeport Network Services, and Network
44  * Associates Laboratories, the Security Research Division of Network
45  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
46  * ("CBOSS"), as part of the DARPA CHATS research program.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
51  * 1. Redistributions of source code must retain the above copyright
52  *    notice, this list of conditions and the following disclaimer.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  *
57  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
61  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67  * SUCH DAMAGE.
68  *
69  */
70 #include <sys/cdefs.h>
71 __FBSDID("$FreeBSD$");
72 
73 #include "namespace.h"
74 #include <sys/param.h>
75 #include <sys/stat.h>
76 
77 #include <dlfcn.h>
78 #include <errno.h>
79 #include <fcntl.h>
80 #define _NS_PRIVATE
81 #include <nsswitch.h>
82 #include <pthread.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <syslog.h>
87 #include <unistd.h>
88 #include "un-namespace.h"
89 
90 enum _nss_constants {
91 	/* Number of elements allocated when we grow a vector */
92 	ELEMSPERCHUNK =	8
93 };
94 
95 /*
96  * Global NSS data structures are mostly read-only, but we update
97  * them when we read or re-read the nsswitch.conf.
98  */
99 static	pthread_rwlock_t	nss_lock = PTHREAD_RWLOCK_INITIALIZER;
100 
101 /*
102  * Runtime determination of whether we are dynamically linked or not.
103  */
104 extern	int		_DYNAMIC __attribute__ ((weak));
105 #define	is_dynamic()	(&_DYNAMIC != NULL)
106 
107 /*
108  * default sourcelist: `files'
109  */
110 const ns_src __nsdefaultsrc[] = {
111 	{ NSSRC_FILES, NS_SUCCESS },
112 	{ 0 },
113 };
114 
115 /* Database, source mappings. */
116 static	unsigned int		 _nsmapsize;
117 static	ns_dbt			*_nsmap = NULL;
118 
119 /* NSS modules. */
120 static	unsigned int		 _nsmodsize;
121 static	ns_mod			*_nsmod;
122 
123 /* Placeholder for builtin modules' dlopen `handle'. */
124 static	int			 __nss_builtin_handle;
125 static	void			*nss_builtin_handle = &__nss_builtin_handle;
126 
127 /*
128  * Attempt to spew relatively uniform messages to syslog.
129  */
130 #define nss_log(level, fmt, ...) \
131 	syslog((level), "NSSWITCH(%s): " fmt, __func__, __VA_ARGS__)
132 #define nss_log_simple(level, s) \
133 	syslog((level), "NSSWITCH(%s): " s, __func__)
134 
135 /*
136  * Dynamically growable arrays are used for lists of databases, sources,
137  * and modules.  The following `vector' interface is used to isolate the
138  * common operations.
139  */
140 typedef	int	(*vector_comparison)(const void *, const void *);
141 typedef	void	(*vector_free_elem)(void *);
142 static	void	  vector_sort(void *, unsigned int, size_t,
143 		    vector_comparison);
144 static	void	  vector_free(void *, unsigned int *, size_t,
145 		    vector_free_elem);
146 static	void	 *vector_ref(unsigned int, void *, unsigned int, size_t);
147 static	void	 *vector_search(const void *, void *, unsigned int, size_t,
148 		    vector_comparison);
149 static	void	 *vector_append(const void *, void *, unsigned int *, size_t);
150 
151 
152 /*
153  * Internal interfaces.
154  */
155 static	int	 string_compare(const void *, const void *);
156 static	int	 mtab_compare(const void *, const void *);
157 static	int	 nss_configure(void);
158 static	void	 ns_dbt_free(ns_dbt *);
159 static	void	 ns_mod_free(ns_mod *);
160 static	void	 ns_src_free(ns_src **, int);
161 static	void	 nss_load_builtin_modules(void);
162 static	void	 nss_load_module(const char *, nss_module_register_fn);
163 static	void	 nss_atexit(void);
164 /* nsparser */
165 extern	FILE	*_nsyyin;
166 
167 
168 /*
169  * The vector operations
170  */
171 static void
172 vector_sort(void *vec, unsigned int count, size_t esize,
173     vector_comparison comparison)
174 {
175 	qsort(vec, count, esize, comparison);
176 }
177 
178 
179 static void *
180 vector_search(const void *key, void *vec, unsigned int count, size_t esize,
181     vector_comparison comparison)
182 {
183 	return (bsearch(key, vec, count, esize, comparison));
184 }
185 
186 
187 static void *
188 vector_append(const void *elem, void *vec, unsigned int *count, size_t esize)
189 {
190 	void	*p;
191 
192 	if ((*count % ELEMSPERCHUNK) == 0) {
193 		p = realloc(vec, (*count + ELEMSPERCHUNK) * esize);
194 		if (p == NULL) {
195 			nss_log_simple(LOG_ERR, "memory allocation failure");
196 			return (vec);
197 		}
198 		vec = p;
199 	}
200 	memmove((void *)(((uintptr_t)vec) + (*count * esize)), elem, esize);
201 	(*count)++;
202 	return (vec);
203 }
204 
205 
206 static void *
207 vector_ref(unsigned int i, void *vec, unsigned int count, size_t esize)
208 {
209 	if (i < count)
210 		return (void *)((uintptr_t)vec + (i * esize));
211 	else
212 		return (NULL);
213 }
214 
215 
216 #define VECTOR_FREE(v, c, s, f) \
217 	do { vector_free(v, c, s, f); v = NULL; } while (0)
218 static void
219 vector_free(void *vec, unsigned int *count, size_t esize,
220     vector_free_elem free_elem)
221 {
222 	unsigned int	 i;
223 	void		*elem;
224 
225 	for (i = 0; i < *count; i++) {
226 		elem = vector_ref(i, vec, *count, esize);
227 		if (elem != NULL)
228 			free_elem(elem);
229 	}
230 	free(vec);
231 	*count = 0;
232 }
233 
234 
235 
236 /*
237  * Comparison functions for vector_search.
238  */
239 static int
240 string_compare(const void *a, const void *b)
241 {
242       return (strcasecmp(*(const char * const *)a, *(const char * const *)b));
243 }
244 
245 
246 static int
247 mtab_compare(const void *a, const void *b)
248 {
249       int     cmp;
250 
251       cmp = strcmp(((const ns_mtab *)a)->name, ((const ns_mtab *)b)->name);
252       if (cmp != 0)
253 	      return (cmp);
254       else
255 	      return (strcmp(((const ns_mtab *)a)->database,
256 		  ((const ns_mtab *)b)->database));
257 }
258 
259 
260 
261 /*
262  * NSS nsmap management.
263  */
264 void
265 _nsdbtaddsrc(ns_dbt *dbt, const ns_src *src)
266 {
267 	const ns_mod	*modp;
268 
269 	dbt->srclist = vector_append(src, dbt->srclist, &dbt->srclistsize,
270 	    sizeof(*src));
271 	modp = vector_search(&src->name, _nsmod, _nsmodsize, sizeof(*_nsmod),
272 	    string_compare);
273 	if (modp == NULL)
274 		nss_load_module(src->name, NULL);
275 }
276 
277 
278 #ifdef _NSS_DEBUG
279 void
280 _nsdbtdump(const ns_dbt *dbt)
281 {
282 	int i;
283 
284 	printf("%s (%d source%s):", dbt->name, dbt->srclistsize,
285 	    dbt->srclistsize == 1 ? "" : "s");
286 	for (i = 0; i < (int)dbt->srclistsize; i++) {
287 		printf(" %s", dbt->srclist[i].name);
288 		if (!(dbt->srclist[i].flags &
289 		    (NS_UNAVAIL|NS_NOTFOUND|NS_TRYAGAIN)) &&
290 		    (dbt->srclist[i].flags & NS_SUCCESS))
291 			continue;
292 		printf(" [");
293 		if (!(dbt->srclist[i].flags & NS_SUCCESS))
294 			printf(" SUCCESS=continue");
295 		if (dbt->srclist[i].flags & NS_UNAVAIL)
296 			printf(" UNAVAIL=return");
297 		if (dbt->srclist[i].flags & NS_NOTFOUND)
298 			printf(" NOTFOUND=return");
299 		if (dbt->srclist[i].flags & NS_TRYAGAIN)
300 			printf(" TRYAGAIN=return");
301 		printf(" ]");
302 	}
303 	printf("\n");
304 }
305 #endif
306 
307 
308 /*
309  * The first time nsdispatch is called (during a process's lifetime,
310  * or after nsswitch.conf has been updated), nss_configure will
311  * prepare global data needed by NSS.
312  */
313 static int
314 nss_configure(void)
315 {
316 	static pthread_mutex_t conf_lock = PTHREAD_MUTEX_INITIALIZER;
317 	static time_t	 confmod;
318 	struct stat	 statbuf;
319 	int		 result, isthreaded;
320 	const char	*path;
321 
322 	result = 0;
323 	isthreaded = __isthreaded;
324 #if defined(_NSS_DEBUG) && defined(_NSS_SHOOT_FOOT)
325 	/* NOTE WELL:  THIS IS A SECURITY HOLE. This must only be built
326 	 * for debugging purposes and MUST NEVER be used in production.
327 	 */
328 	path = getenv("NSSWITCH_CONF");
329 	if (path == NULL)
330 #endif
331 	path = _PATH_NS_CONF;
332 	if (stat(path, &statbuf) != 0)
333 		return (0);
334 	if (statbuf.st_mtime <= confmod)
335 		return (0);
336 	if (isthreaded) {
337 	    result = _pthread_mutex_trylock(&conf_lock);
338 	    if (result != 0)
339 		    return (0);
340 	    (void)_pthread_rwlock_unlock(&nss_lock);
341 	    result = _pthread_rwlock_wrlock(&nss_lock);
342 	    if (result != 0)
343 		    goto fin2;
344 	}
345 	_nsyyin = fopen(path, "r");
346 	if (_nsyyin == NULL)
347 		goto fin;
348 	VECTOR_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap),
349 	    (vector_free_elem)ns_dbt_free);
350 	VECTOR_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod),
351 	    (vector_free_elem)ns_mod_free);
352 	nss_load_builtin_modules();
353 	_nsyyparse();
354 	(void)fclose(_nsyyin);
355 	vector_sort(_nsmap, _nsmapsize, sizeof(*_nsmap), string_compare);
356 	if (confmod == 0)
357 		(void)atexit(nss_atexit);
358 	confmod = statbuf.st_mtime;
359 fin:
360 	if (isthreaded) {
361 	    (void)_pthread_rwlock_unlock(&nss_lock);
362 	    if (result == 0)
363 		    result = _pthread_rwlock_rdlock(&nss_lock);
364 	}
365 fin2:
366 	if (isthreaded)
367 		(void)_pthread_mutex_unlock(&conf_lock);
368 	return (result);
369 }
370 
371 
372 void
373 _nsdbtput(const ns_dbt *dbt)
374 {
375 	unsigned int	 i;
376 	ns_dbt		*p;
377 
378 	for (i = 0; i < _nsmapsize; i++) {
379 		p = vector_ref(i, _nsmap, _nsmapsize, sizeof(*_nsmap));
380 		if (string_compare(&dbt->name, &p->name) == 0) {
381 			/* overwrite existing entry */
382 			if (p->srclist != NULL)
383 				ns_src_free(&p->srclist, p->srclistsize);
384 			memmove(p, dbt, sizeof(*dbt));
385 			return;
386 		}
387 	}
388 	_nsmap = vector_append(dbt, _nsmap, &_nsmapsize, sizeof(*_nsmap));
389 }
390 
391 
392 static void
393 ns_dbt_free(ns_dbt *dbt)
394 {
395 	ns_src_free(&dbt->srclist, dbt->srclistsize);
396 }
397 
398 
399 static void
400 ns_src_free(ns_src **src, int srclistsize)
401 {
402 	int	i;
403 
404 	for (i = 0; i < srclistsize; i++)
405 		if ((*src)[i].name != NULL)
406 			/* This one was allocated by nslexer. You'll just
407 			 * have to trust me.
408 			 */
409 			free((void *)((*src)[i].name));
410 	free(*src);
411 	*src = NULL;
412 }
413 
414 
415 
416 /*
417  * NSS module management.
418  */
419 /* The built-in NSS modules are all loaded at once. */
420 #define NSS_BACKEND(name, reg) \
421 ns_mtab	*reg(unsigned int *, nss_module_unregister_fn *);
422 #include "nss_backends.h"
423 #undef NSS_BACKEND
424 
425 static void
426 nss_load_builtin_modules(void)
427 {
428 #define NSS_BACKEND(name, reg) nss_load_module(#name, reg);
429 #include "nss_backends.h"
430 #undef NSS_BACKEND
431 }
432 
433 
434 /* Load a built-in or dynamically linked module.  If the `reg_fn'
435  * argument is non-NULL, assume a built-in module and use reg_fn to
436  * register it.  Otherwise, search for a dynamic NSS module.
437  */
438 static void
439 nss_load_module(const char *source, nss_module_register_fn reg_fn)
440 {
441 	char		 buf[PATH_MAX];
442 	ns_mod		 mod;
443 	nss_module_register_fn fn;
444 
445 	memset(&mod, 0, sizeof(mod));
446 	mod.name = strdup(source);
447 	if (mod.name == NULL) {
448 		nss_log_simple(LOG_ERR, "memory allocation failure");
449 		return;
450 	}
451 	if (reg_fn != NULL) {
452 		/* The placeholder is required, as a NULL handle
453 		 * represents an invalid module.
454 		 */
455 		mod.handle = nss_builtin_handle;
456 		fn = reg_fn;
457 	} else if (!is_dynamic())
458 		goto fin;
459 	else {
460 		if (snprintf(buf, sizeof(buf), "nss_%s.so.%d", mod.name,
461 		    NSS_MODULE_INTERFACE_VERSION) >= (int)sizeof(buf))
462 			goto fin;
463 		mod.handle = dlopen(buf, RTLD_LOCAL|RTLD_LAZY);
464 		if (mod.handle == NULL) {
465 #ifdef _NSS_DEBUG
466 			/* This gets pretty annoying since the built-in
467 			 * sources aren't modules yet.
468 			 */
469 			nss_log(LOG_DEBUG, "%s, %s", mod.name, dlerror());
470 #endif
471 			goto fin;
472 		}
473 		fn = (nss_module_register_fn)dlfunc(mod.handle,
474 		    "nss_module_register");
475 		if (fn == NULL) {
476 			(void)dlclose(mod.handle);
477 			mod.handle = NULL;
478 			nss_log(LOG_ERR, "%s, %s", mod.name, dlerror());
479 			goto fin;
480 		}
481 	}
482 	mod.mtab = fn(mod.name, &mod.mtabsize, &mod.unregister);
483 	if (mod.mtab == NULL || mod.mtabsize == 0) {
484 		if (mod.handle != nss_builtin_handle)
485 			(void)dlclose(mod.handle);
486 		mod.handle = NULL;
487 		nss_log(LOG_ERR, "%s, registration failed", mod.name);
488 		goto fin;
489 	}
490 	if (mod.mtabsize > 1)
491 		qsort(mod.mtab, mod.mtabsize, sizeof(mod.mtab[0]),
492 		    mtab_compare);
493 fin:
494 	_nsmod = vector_append(&mod, _nsmod, &_nsmodsize, sizeof(*_nsmod));
495 	vector_sort(_nsmod, _nsmodsize, sizeof(*_nsmod), string_compare);
496 }
497 
498 
499 
500 static void
501 ns_mod_free(ns_mod *mod)
502 {
503 
504 	free(mod->name);
505 	if (mod->handle == NULL)
506 		return;
507 	if (mod->unregister != NULL)
508 		mod->unregister(mod->mtab, mod->mtabsize);
509 	if (mod->handle != nss_builtin_handle)
510 		(void)dlclose(mod->handle);
511 }
512 
513 
514 
515 /*
516  * Cleanup
517  */
518 static void
519 nss_atexit(void)
520 {
521 	int isthreaded;
522 
523 	isthreaded = __isthreaded;
524 	if (isthreaded)
525 		(void)_pthread_rwlock_wrlock(&nss_lock);
526 	VECTOR_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap),
527 	    (vector_free_elem)ns_dbt_free);
528 	VECTOR_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod),
529 	    (vector_free_elem)ns_mod_free);
530 	if (isthreaded)
531 		(void)_pthread_rwlock_unlock(&nss_lock);
532 }
533 
534 
535 
536 /*
537  * Finally, the actual implementation.
538  */
539 static nss_method
540 nss_method_lookup(const char *source, const char *database,
541     const char *method, const ns_dtab disp_tab[], void **mdata)
542 {
543 	ns_mod	*mod;
544 	ns_mtab	*match, key;
545 	int	 i;
546 
547 	if (disp_tab != NULL)
548 		for (i = 0; disp_tab[i].src != NULL; i++)
549 			if (strcasecmp(source, disp_tab[i].src) == 0) {
550 				*mdata = disp_tab[i].mdata;
551 				return (disp_tab[i].method);
552 			}
553 	mod = vector_search(&source, _nsmod, _nsmodsize, sizeof(*_nsmod),
554 	    string_compare);
555 	if (mod != NULL && mod->handle != NULL) {
556 		key.database = database;
557 		key.name = method;
558 		match = bsearch(&key, mod->mtab, mod->mtabsize,
559 		    sizeof(mod->mtab[0]), mtab_compare);
560 		if (match != NULL) {
561 			*mdata = match->mdata;
562 			return (match->method);
563 		}
564 	}
565 	if (is_dynamic())
566 		nss_log(LOG_DEBUG, "%s, %s, %s, not found", source, database,
567 		    method);
568 	*mdata = NULL;
569 	return (NULL);
570 }
571 
572 
573 __weak_reference(_nsdispatch, nsdispatch);
574 
575 int
576 _nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database,
577 	    const char *method_name, const ns_src defaults[], ...)
578 {
579 	va_list		 ap;
580 	const ns_dbt	*dbt;
581 	const ns_src	*srclist;
582 	nss_method	 method;
583 	void		*mdata;
584 	int		 isthreaded, serrno, i, result, srclistsize;
585 
586 	isthreaded = __isthreaded;
587 	serrno = errno;
588 	if (isthreaded) {
589 		result = _pthread_rwlock_rdlock(&nss_lock);
590 		if (result != 0) {
591 			result = NS_UNAVAIL;
592 			goto fin;
593 		}
594 	}
595 	result = nss_configure();
596 	if (result != 0) {
597 		result = NS_UNAVAIL;
598 		goto fin;
599 	}
600 	dbt = vector_search(&database, _nsmap, _nsmapsize, sizeof(*_nsmap),
601 	    string_compare);
602 	if (dbt != NULL) {
603 		srclist = dbt->srclist;
604 		srclistsize = dbt->srclistsize;
605 	} else {
606 		srclist = defaults;
607 		srclistsize = 0;
608 		while (srclist[srclistsize].name != NULL)
609 			srclistsize++;
610 	}
611 	for (i = 0; i < srclistsize; i++) {
612 		result = NS_NOTFOUND;
613 		method = nss_method_lookup(srclist[i].name, database,
614 		    method_name, disp_tab, &mdata);
615 		if (method != NULL) {
616 			va_start(ap, defaults);
617 			result = method(retval, mdata, ap);
618 			va_end(ap);
619 			if (result & (srclist[i].flags))
620 				break;
621 		}
622 	}
623 	if (isthreaded)
624 		(void)_pthread_rwlock_unlock(&nss_lock);
625 fin:
626 	errno = serrno;
627 	return (result);
628 }
629