xref: /freebsd/lib/libc/net/nsdispatch.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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	int	  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 int
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 (0);
197 		} else
198 			*vec = p;
199 	}
200 	memmove((void *)(((uintptr_t)*vec) + (*count * esize)),
201 	    elem, esize);
202 	(*count)++;
203 	return (1);
204 }
205 
206 
207 static void *
208 vector_ref(unsigned int i, void *vec, unsigned int count, size_t esize)
209 {
210 	if (i < count)
211 		return (void *)((uintptr_t)vec + (i * esize));
212 	else
213 		return (NULL);
214 }
215 
216 
217 static void
218 vector_free(void **vec, unsigned int *count, size_t esize,
219     vector_free_elem free_elem)
220 {
221 	unsigned int	 i;
222 	void		*elem;
223 
224 	for (i = 0; i < *count; i++) {
225 		elem = vector_ref(i, *vec, *count, esize);
226 		if (elem != NULL)
227 			free_elem(elem);
228 	}
229 	free(*vec);
230 	*vec = NULL;
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 	vector_append(src, (void **)&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;
320 	const char	*path;
321 
322 #if defined(_NSS_DEBUG) && defined(_NSS_SHOOT_FOOT)
323 	/* NOTE WELL:  THIS IS A SECURITY HOLE. This must only be built
324 	 * for debugging purposes and MUST NEVER be used in production.
325 	 */
326 	path = getenv("NSSWITCH_CONF");
327 	if (path == NULL)
328 #endif
329 	path = _PATH_NS_CONF;
330 	if (stat(path, &statbuf) != 0)
331 		return (0);
332 	if (statbuf.st_mtime <= confmod)
333 		return (0);
334 	result = _pthread_mutex_trylock(&conf_lock);
335 	if (result != 0)
336 		return (0);
337 	(void)_pthread_rwlock_unlock(&nss_lock);
338 	result = _pthread_rwlock_wrlock(&nss_lock);
339 	if (result != 0)
340 		goto fin2;
341 	_nsyyin = fopen(path, "r");
342 	if (_nsyyin == NULL)
343 		goto fin;
344 	vector_free((void **)&_nsmap, &_nsmapsize, sizeof(*_nsmap),
345 	    (vector_free_elem)ns_dbt_free);
346 	vector_free((void **)&_nsmod, &_nsmodsize, sizeof(*_nsmod),
347 	    (vector_free_elem)ns_mod_free);
348 	nss_load_builtin_modules();
349 	_nsyyparse();
350 	(void)fclose(_nsyyin);
351 	vector_sort(_nsmap, _nsmapsize, sizeof(*_nsmap), string_compare);
352 	if (confmod == 0)
353 		(void)atexit(nss_atexit);
354 	confmod = statbuf.st_mtime;
355 fin:
356 	(void)_pthread_rwlock_unlock(&nss_lock);
357 	result = _pthread_rwlock_rdlock(&nss_lock);
358 fin2:
359 	(void)_pthread_mutex_unlock(&conf_lock);
360 	return (result);
361 }
362 
363 
364 void
365 _nsdbtput(const ns_dbt *dbt)
366 {
367 	unsigned int	 i;
368 	ns_dbt		*p;
369 
370 	for (i = 0; i < _nsmapsize; i++) {
371 		p = vector_ref(i, _nsmap, _nsmapsize, sizeof(*_nsmap));
372 		if (string_compare(&dbt->name, &p->name) == 0) {
373 			/* overwrite existing entry */
374 			if (p->srclist != NULL)
375 				ns_src_free(&p->srclist, p->srclistsize);
376 			memmove(p, dbt, sizeof(*dbt));
377 			return;
378 		}
379 	}
380 	vector_append(dbt, (void **)&_nsmap, &_nsmapsize, sizeof(*_nsmap));
381 }
382 
383 
384 static void
385 ns_dbt_free(ns_dbt *dbt)
386 {
387 	ns_src_free(&dbt->srclist, dbt->srclistsize);
388 }
389 
390 
391 static void
392 ns_src_free(ns_src **src, int srclistsize)
393 {
394 	int	i;
395 
396 	for (i = 0; i < srclistsize; i++)
397 		if ((*src)[i].name != NULL)
398 			/* This one was allocated by nslexer. You'll just
399 			 * have to trust me.
400 			 */
401 			free((void *)((*src)[i].name));
402 	free(*src);
403 	*src = NULL;
404 }
405 
406 
407 
408 /*
409  * NSS module management.
410  */
411 /* The built-in NSS modules are all loaded at once. */
412 #define NSS_BACKEND(name, reg) \
413 ns_mtab	*reg(unsigned int *, nss_module_unregister_fn *);
414 #include "nss_backends.h"
415 #undef NSS_BACKEND
416 
417 static void
418 nss_load_builtin_modules(void)
419 {
420 #define NSS_BACKEND(name, reg) nss_load_module(#name, reg);
421 #include "nss_backends.h"
422 #undef NSS_BACKEND
423 }
424 
425 
426 /* Load a built-in or dynamically linked module.  If the `reg_fn'
427  * argument is non-NULL, assume a built-in module and use reg_fn to
428  * register it.  Otherwise, search for a dynamic NSS module.
429  */
430 static void
431 nss_load_module(const char *source, nss_module_register_fn reg_fn)
432 {
433 	char		 buf[PATH_MAX];
434 	ns_mod		 mod;
435 	nss_module_register_fn fn;
436 
437 	memset(&mod, 0, sizeof(mod));
438 	mod.name = strdup(source);
439 	if (mod.name == NULL) {
440 		nss_log_simple(LOG_ERR, "memory allocation failure");
441 		return;
442 	}
443 	if (reg_fn != NULL) {
444 		/* The placeholder is required, as a NULL handle
445 		 * represents an invalid module.
446 		 */
447 		mod.handle = nss_builtin_handle;
448 		fn = reg_fn;
449 	} else if (!is_dynamic())
450 		goto fin;
451 	else {
452 		if (snprintf(buf, sizeof(buf), "nss_%s.so.%d", mod.name,
453 		    NSS_MODULE_INTERFACE_VERSION) >= (int)sizeof(buf))
454 			goto fin;
455 		mod.handle = dlopen(buf, RTLD_LOCAL|RTLD_LAZY);
456 		if (mod.handle == NULL) {
457 #ifdef _NSS_DEBUG
458 			/* This gets pretty annoying since the built-in
459 			 * sources aren't modules yet.
460 			 */
461 			nss_log(LOG_DEBUG, "%s, %s", mod.name, dlerror());
462 #endif
463 			goto fin;
464 		}
465 		fn = (nss_module_register_fn)dlfunc(mod.handle,
466 		    "nss_module_register");
467 		if (fn == NULL) {
468 			(void)dlclose(mod.handle);
469 			mod.handle = NULL;
470 			nss_log(LOG_ERR, "%s, %s", mod.name, dlerror());
471 			goto fin;
472 		}
473 	}
474 	mod.mtab = fn(mod.name, &mod.mtabsize, &mod.unregister);
475 	if (mod.mtab == NULL || mod.mtabsize == 0) {
476 		if (mod.handle != nss_builtin_handle)
477 			(void)dlclose(mod.handle);
478 		mod.handle = NULL;
479 		nss_log(LOG_ERR, "%s, registration failed", mod.name);
480 		goto fin;
481 	}
482 	if (mod.mtabsize > 1)
483 		qsort(mod.mtab, mod.mtabsize, sizeof(mod.mtab[0]),
484 		    mtab_compare);
485 fin:
486 	vector_append(&mod, (void **)&_nsmod, &_nsmodsize, sizeof(*_nsmod));
487 	vector_sort(_nsmod, _nsmodsize, sizeof(*_nsmod), string_compare);
488 }
489 
490 
491 
492 static void
493 ns_mod_free(ns_mod *mod)
494 {
495 
496 	free(mod->name);
497 	if (mod->handle == NULL)
498 		return;
499 	if (mod->unregister != NULL)
500 		mod->unregister(mod->mtab, mod->mtabsize);
501 	if (mod->handle != nss_builtin_handle)
502 		(void)dlclose(mod->handle);
503 }
504 
505 
506 
507 /*
508  * Cleanup
509  */
510 static void
511 nss_atexit(void)
512 {
513 	(void)_pthread_rwlock_wrlock(&nss_lock);
514 	vector_free((void **)&_nsmap, &_nsmapsize, sizeof(*_nsmap),
515 	    (vector_free_elem)ns_dbt_free);
516 	vector_free((void **)&_nsmod, &_nsmodsize, sizeof(*_nsmod),
517 	    (vector_free_elem)ns_mod_free);
518 	(void)_pthread_rwlock_unlock(&nss_lock);
519 }
520 
521 
522 
523 /*
524  * Finally, the actual implementation.
525  */
526 static nss_method
527 nss_method_lookup(const char *source, const char *database,
528     const char *method, const ns_dtab disp_tab[], void **mdata)
529 {
530 	ns_mod	*mod;
531 	ns_mtab	*match, key;
532 	int	 i;
533 
534 	if (disp_tab != NULL)
535 		for (i = 0; disp_tab[i].src != NULL; i++)
536 			if (strcasecmp(source, disp_tab[i].src) == 0) {
537 				*mdata = disp_tab[i].mdata;
538 				return (disp_tab[i].method);
539 			}
540 	mod = vector_search(&source, _nsmod, _nsmodsize, sizeof(*_nsmod),
541 	    string_compare);
542 	if (mod != NULL && mod->handle != NULL) {
543 		key.database = database;
544 		key.name = method;
545 		match = bsearch(&key, mod->mtab, mod->mtabsize,
546 		    sizeof(mod->mtab[0]), mtab_compare);
547 		if (match != NULL) {
548 			*mdata = match->mdata;
549 			return (match->method);
550 		}
551 	}
552 	if (is_dynamic())
553 		nss_log(LOG_DEBUG, "%s, %s, %s, not found", source, database,
554 		    method);
555 	*mdata = NULL;
556 	return (NULL);
557 }
558 
559 
560 __weak_reference(_nsdispatch, nsdispatch);
561 
562 int
563 _nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database,
564 	    const char *method_name, const ns_src defaults[], ...)
565 {
566 	va_list		 ap;
567 	const ns_dbt	*dbt;
568 	const ns_src	*srclist;
569 	nss_method	 method;
570 	void		*mdata;
571 	int		 serrno, i, result, srclistsize;
572 
573 	serrno = errno;
574 	result = _pthread_rwlock_rdlock(&nss_lock);
575 	if (result != 0) {
576 		result = NS_UNAVAIL;
577 		goto fin;
578 	}
579 	result = nss_configure();
580 	if (result != 0) {
581 		result = NS_UNAVAIL;
582 		goto fin;
583 	}
584 	dbt = vector_search(&database, _nsmap, _nsmapsize, sizeof(*_nsmap),
585 	    string_compare);
586 	if (dbt != NULL) {
587 		srclist = dbt->srclist;
588 		srclistsize = dbt->srclistsize;
589 	} else {
590 		srclist = defaults;
591 		srclistsize = 0;
592 		while (srclist[srclistsize].name != NULL)
593 			srclistsize++;
594 	}
595 	for (i = 0; i < srclistsize; i++) {
596 		result = NS_NOTFOUND;
597 		method = nss_method_lookup(srclist[i].name, database,
598 		    method_name, disp_tab, &mdata);
599 		if (method != NULL) {
600 			va_start(ap, defaults);
601 			result = method(retval, mdata, ap);
602 			va_end(ap);
603 			if (result & (srclist[i].flags))
604 				break;
605 		}
606 	}
607 	(void)_pthread_rwlock_unlock(&nss_lock);
608 fin:
609 	errno = serrno;
610 	return (result);
611 }
612