nwrap: catch NULL ip in nwrap_add_ai
[kai/samba-autobuild/.git] / lib / nss_wrapper / nss_wrapper.c
1 /*
2  * Copyright (C) Stefan Metzmacher 2007 <metze@samba.org>
3  * Copyright (C) Guenther Deschner 2009 <gd@samba.org>
4  * Copyright (C) Andreas Schneider 2013 <asn@samba.org>
5  *
6  * All rights reserved.
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  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
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  *
19  * 3. Neither the name of the author nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #include "config.h"
37
38 #include <pthread.h>
39
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <sys/socket.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdarg.h>
46 #include <stdbool.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdint.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <ctype.h>
54
55 #include <search.h>
56 #include <assert.h>
57
58 /*
59  * Defining _POSIX_PTHREAD_SEMANTICS before including pwd.h and grp.h  gives us
60  * the posix getpwnam_r(), getpwuid_r(), getgrnam_r and getgrgid_r calls on
61  * Solaris
62  */
63 #ifndef _POSIX_PTHREAD_SEMANTICS
64 #define _POSIX_PTHREAD_SEMANTICS
65 #endif
66
67 #include <pwd.h>
68 #include <grp.h>
69 #ifdef HAVE_SHADOW_H
70 #include <shadow.h>
71 #endif /* HAVE_SHADOW_H */
72
73 #include <netdb.h>
74 #include <arpa/inet.h>
75 #include <netinet/in.h>
76
77 #include <dlfcn.h>
78
79 #if defined(HAVE_NSS_H)
80 /* Linux and BSD */
81 #include <nss.h>
82
83 typedef enum nss_status NSS_STATUS;
84 #elif defined(HAVE_NSS_COMMON_H)
85 /* Solaris */
86 #include <nss_common.h>
87 #include <nss_dbdefs.h>
88 #include <nsswitch.h>
89
90 typedef nss_status_t NSS_STATUS;
91
92 # define NSS_STATUS_SUCCESS     NSS_SUCCESS
93 # define NSS_STATUS_NOTFOUND    NSS_NOTFOUND
94 # define NSS_STATUS_UNAVAIL     NSS_UNAVAIL
95 # define NSS_STATUS_TRYAGAIN    NSS_TRYAGAIN
96 #else
97 # error "No nsswitch support detected"
98 #endif
99
100 #ifndef PTR_DIFF
101 #define PTR_DIFF(p1, p2) ((ptrdiff_t)(((const char *)(p1)) - (const char *)(p2)))
102 #endif
103
104 #ifndef _PUBLIC_
105 #define _PUBLIC_
106 #endif
107
108 #ifndef EAI_NODATA
109 #define EAI_NODATA EAI_NONAME
110 #endif
111
112 #ifndef EAI_ADDRFAMILY
113 #define EAI_ADDRFAMILY EAI_FAMILY
114 #endif
115
116 #ifndef __STRING
117 #define __STRING(x)    #x
118 #endif
119
120 #ifndef __STRINGSTRING
121 #define __STRINGSTRING(x) __STRING(x)
122 #endif
123
124 #ifndef __LINESTR__
125 #define __LINESTR__ __STRINGSTRING(__LINE__)
126 #endif
127
128 #ifndef __location__
129 #define __location__ __FILE__ ":" __LINESTR__
130 #endif
131
132 #ifndef DNS_NAME_MAX
133 #define DNS_NAME_MAX 255
134 #endif
135
136 /* GCC have printf type attribute check. */
137 #ifdef HAVE_ATTRIBUTE_PRINTF_FORMAT
138 #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
139 #else
140 #define PRINTF_ATTRIBUTE(a,b)
141 #endif /* HAVE_ATTRIBUTE_PRINTF_FORMAT */
142
143 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
144 #define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor))
145 #else
146 #define DESTRUCTOR_ATTRIBUTE
147 #endif /* HAVE_DESTRUCTOR_ATTRIBUTE */
148
149 #define ZERO_STRUCTP(x) do { if ((x) != NULL) memset((char *)(x), 0, sizeof(*(x))); } while(0)
150
151 #ifndef SAFE_FREE
152 #define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
153 #endif
154
155 #ifdef HAVE_IPV6
156 #define NWRAP_INET_ADDRSTRLEN INET6_ADDRSTRLEN
157 #else
158 #define NWRAP_INET_ADDRSTRLEN INET_ADDRSTRLEN
159 #endif
160
161 #define NWRAP_LOCK(m) do { \
162         pthread_mutex_lock(&( m ## _mutex)); \
163 } while(0)
164
165 #define NWRAP_UNLOCK(m) do { \
166         pthread_mutex_unlock(&( m ## _mutex)); \
167 } while(0)
168
169
170 static bool nwrap_initialized = false;
171 static pthread_mutex_t nwrap_initialized_mutex = PTHREAD_MUTEX_INITIALIZER;
172
173 /* The mutex or accessing the id */
174 static pthread_mutex_t nwrap_global_mutex = PTHREAD_MUTEX_INITIALIZER;
175 static pthread_mutex_t nwrap_gr_global_mutex = PTHREAD_MUTEX_INITIALIZER;
176 static pthread_mutex_t nwrap_he_global_mutex = PTHREAD_MUTEX_INITIALIZER;
177 static pthread_mutex_t nwrap_pw_global_mutex = PTHREAD_MUTEX_INITIALIZER;
178 static pthread_mutex_t nwrap_sp_global_mutex = PTHREAD_MUTEX_INITIALIZER;
179
180 /* Add new global locks here please */
181 /* Also don't forget to add locks to
182  * nwrap_init() function.
183  */
184 # define NWRAP_LOCK_ALL do { \
185         NWRAP_LOCK(nwrap_initialized); \
186         NWRAP_LOCK(nwrap_global); \
187         NWRAP_LOCK(nwrap_gr_global); \
188         NWRAP_LOCK(nwrap_he_global); \
189         NWRAP_LOCK(nwrap_pw_global); \
190         NWRAP_LOCK(nwrap_sp_global); \
191 } while (0);
192
193 # define NWRAP_UNLOCK_ALL do {\
194         NWRAP_UNLOCK(nwrap_sp_global); \
195         NWRAP_UNLOCK(nwrap_pw_global); \
196         NWRAP_UNLOCK(nwrap_he_global); \
197         NWRAP_UNLOCK(nwrap_gr_global); \
198         NWRAP_UNLOCK(nwrap_global); \
199         NWRAP_UNLOCK(nwrap_initialized); \
200 } while (0);
201
202 static void nwrap_thread_prepare(void)
203 {
204         NWRAP_LOCK_ALL;
205 }
206
207 static void nwrap_thread_parent(void)
208 {
209         NWRAP_UNLOCK_ALL;
210 }
211
212 static void nwrap_thread_child(void)
213 {
214         NWRAP_UNLOCK_ALL;
215 }
216
217 enum nwrap_dbglvl_e {
218         NWRAP_LOG_ERROR = 0,
219         NWRAP_LOG_WARN,
220         NWRAP_LOG_DEBUG,
221         NWRAP_LOG_TRACE
222 };
223
224 #ifdef NDEBUG
225 # define NWRAP_LOG(...)
226 #else
227
228 static void nwrap_log(enum nwrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
229 # define NWRAP_LOG(dbglvl, ...) nwrap_log((dbglvl), __func__, __VA_ARGS__)
230
231 static void nwrap_log(enum nwrap_dbglvl_e dbglvl,
232                       const char *func,
233                       const char *format, ...)
234 {
235         char buffer[1024];
236         va_list va;
237         const char *d;
238         unsigned int lvl = 0;
239         int pid = getpid();
240
241         d = getenv("NSS_WRAPPER_DEBUGLEVEL");
242         if (d != NULL) {
243                 lvl = atoi(d);
244         }
245
246         va_start(va, format);
247         vsnprintf(buffer, sizeof(buffer), format, va);
248         va_end(va);
249
250         if (lvl >= dbglvl) {
251                 switch (dbglvl) {
252                         case NWRAP_LOG_ERROR:
253                                 fprintf(stderr,
254                                         "NWRAP_ERROR(%d) - %s: %s\n",
255                                         pid, func, buffer);
256                                 break;
257                         case NWRAP_LOG_WARN:
258                                 fprintf(stderr,
259                                         "NWRAP_WARN(%d) - %s: %s\n",
260                                         pid, func, buffer);
261                                 break;
262                         case NWRAP_LOG_DEBUG:
263                                 fprintf(stderr,
264                                         "NWRAP_DEBUG(%d) - %s: %s\n",
265                                         pid, func, buffer);
266                                 break;
267                         case NWRAP_LOG_TRACE:
268                                 fprintf(stderr,
269                                         "NWRAP_TRACE(%d) - %s: %s\n",
270                                         pid, func, buffer);
271                                 break;
272                 }
273         }
274 }
275 #endif /* NDEBUG NWRAP_LOG */
276
277 struct nwrap_libc_fns {
278         struct passwd *(*_libc_getpwnam)(const char *name);
279         int (*_libc_getpwnam_r)(const char *name, struct passwd *pwd,
280                        char *buf, size_t buflen, struct passwd **result);
281         struct passwd *(*_libc_getpwuid)(uid_t uid);
282         int (*_libc_getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result);
283         void (*_libc_setpwent)(void);
284         struct passwd *(*_libc_getpwent)(void);
285 #ifdef HAVE_SOLARIS_GETPWENT_R
286         struct passwd *(*_libc_getpwent_r)(struct passwd *pwbuf, char *buf, size_t buflen);
287 #else
288         int (*_libc_getpwent_r)(struct passwd *pwbuf, char *buf, size_t buflen, struct passwd **pwbufp);
289 #endif
290         void (*_libc_endpwent)(void);
291         int (*_libc_initgroups)(const char *user, gid_t gid);
292         struct group *(*_libc_getgrnam)(const char *name);
293         int (*_libc_getgrnam_r)(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result);
294         struct group *(*_libc_getgrgid)(gid_t gid);
295         int (*_libc_getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t buflen, struct group **result);
296         void (*_libc_setgrent)(void);
297         struct group *(*_libc_getgrent)(void);
298 #ifdef HAVE_SOLARIS_GETGRENT_R
299         struct group *(*_libc_getgrent_r)(struct group *group, char *buf, size_t buflen);
300 #else
301         int (*_libc_getgrent_r)(struct group *group, char *buf, size_t buflen, struct group **result);
302 #endif
303         void (*_libc_endgrent)(void);
304         int (*_libc_getgrouplist)(const char *user, gid_t group, gid_t *groups, int *ngroups);
305
306         void (*_libc_sethostent)(int stayopen);
307         struct hostent *(*_libc_gethostent)(void);
308         void (*_libc_endhostent)(void);
309
310         struct hostent *(*_libc_gethostbyname)(const char *name);
311 #ifdef HAVE_GETHOSTBYNAME2 /* GNU extension */
312         struct hostent *(*_libc_gethostbyname2)(const char *name, int af);
313 #endif
314         struct hostent *(*_libc_gethostbyaddr)(const void *addr, socklen_t len, int type);
315
316         int (*_libc_getaddrinfo)(const char *node, const char *service,
317                                  const struct addrinfo *hints,
318                                  struct addrinfo **res);
319         int (*_libc_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
320                                  char *host, size_t hostlen,
321                                  char *serv, size_t servlen,
322                                  int flags);
323         int (*_libc_gethostname)(char *name, size_t len);
324 #ifdef HAVE_GETHOSTBYNAME_R
325         int (*_libc_gethostbyname_r)(const char *name,
326                                      struct hostent *ret,
327                                      char *buf, size_t buflen,
328                                      struct hostent **result, int *h_errnop);
329 #endif
330 #ifdef HAVE_GETHOSTBYADDR_R
331         int (*_libc_gethostbyaddr_r)(const void *addr, socklen_t len, int type,
332                                      struct hostent *ret,
333                                      char *buf, size_t buflen,
334                                      struct hostent **result, int *h_errnop);
335 #endif
336 };
337
338 struct nwrap_module_nss_fns {
339         NSS_STATUS (*_nss_getpwnam_r)(const char *name, struct passwd *result, char *buffer,
340                                       size_t buflen, int *errnop);
341         NSS_STATUS (*_nss_getpwuid_r)(uid_t uid, struct passwd *result, char *buffer,
342                                       size_t buflen, int *errnop);
343         NSS_STATUS (*_nss_setpwent)(void);
344         NSS_STATUS (*_nss_getpwent_r)(struct passwd *result, char *buffer,
345                                       size_t buflen, int *errnop);
346         NSS_STATUS (*_nss_endpwent)(void);
347         NSS_STATUS (*_nss_initgroups)(const char *user, gid_t group, long int *start,
348                                       long int *size, gid_t **groups, long int limit, int *errnop);
349         NSS_STATUS (*_nss_getgrnam_r)(const char *name, struct group *result, char *buffer,
350                                       size_t buflen, int *errnop);
351         NSS_STATUS (*_nss_getgrgid_r)(gid_t gid, struct group *result, char *buffer,
352                                       size_t buflen, int *errnop);
353         NSS_STATUS (*_nss_setgrent)(void);
354         NSS_STATUS (*_nss_getgrent_r)(struct group *result, char *buffer,
355                                       size_t buflen, int *errnop);
356         NSS_STATUS (*_nss_endgrent)(void);
357 };
358
359 struct nwrap_backend {
360         const char *name;
361         const char *so_path;
362         void *so_handle;
363         struct nwrap_ops *ops;
364         struct nwrap_module_nss_fns *fns;
365 };
366
367 struct nwrap_ops {
368         struct passwd * (*nw_getpwnam)(struct nwrap_backend *b,
369                                        const char *name);
370         int             (*nw_getpwnam_r)(struct nwrap_backend *b,
371                                          const char *name, struct passwd *pwdst,
372                                          char *buf, size_t buflen, struct passwd **pwdstp);
373         struct passwd * (*nw_getpwuid)(struct nwrap_backend *b,
374                                        uid_t uid);
375         int             (*nw_getpwuid_r)(struct nwrap_backend *b,
376                                          uid_t uid, struct passwd *pwdst,
377                                          char *buf, size_t buflen, struct passwd **pwdstp);
378         void            (*nw_setpwent)(struct nwrap_backend *b);
379         struct passwd * (*nw_getpwent)(struct nwrap_backend *b);
380         int             (*nw_getpwent_r)(struct nwrap_backend *b,
381                                          struct passwd *pwdst, char *buf,
382                                          size_t buflen, struct passwd **pwdstp);
383         void            (*nw_endpwent)(struct nwrap_backend *b);
384         int             (*nw_initgroups)(struct nwrap_backend *b,
385                                          const char *user, gid_t group);
386         struct group *  (*nw_getgrnam)(struct nwrap_backend *b,
387                                        const char *name);
388         int             (*nw_getgrnam_r)(struct nwrap_backend *b,
389                                          const char *name, struct group *grdst,
390                                          char *buf, size_t buflen, struct group **grdstp);
391         struct group *  (*nw_getgrgid)(struct nwrap_backend *b,
392                                        gid_t gid);
393         int             (*nw_getgrgid_r)(struct nwrap_backend *b,
394                                          gid_t gid, struct group *grdst,
395                                          char *buf, size_t buflen, struct group **grdstp);
396         void            (*nw_setgrent)(struct nwrap_backend *b);
397         struct group *  (*nw_getgrent)(struct nwrap_backend *b);
398         int             (*nw_getgrent_r)(struct nwrap_backend *b,
399                                          struct group *grdst, char *buf,
400                                          size_t buflen, struct group **grdstp);
401         void            (*nw_endgrent)(struct nwrap_backend *b);
402 };
403
404 /* Public prototypes */
405
406 bool nss_wrapper_enabled(void);
407 bool nss_wrapper_shadow_enabled(void);
408 bool nss_wrapper_hosts_enabled(void);
409
410 /* prototypes for files backend */
411
412
413 static struct passwd *nwrap_files_getpwnam(struct nwrap_backend *b,
414                                            const char *name);
415 static int nwrap_files_getpwnam_r(struct nwrap_backend *b,
416                                   const char *name, struct passwd *pwdst,
417                                   char *buf, size_t buflen, struct passwd **pwdstp);
418 static struct passwd *nwrap_files_getpwuid(struct nwrap_backend *b,
419                                            uid_t uid);
420 static int nwrap_files_getpwuid_r(struct nwrap_backend *b,
421                                   uid_t uid, struct passwd *pwdst,
422                                   char *buf, size_t buflen, struct passwd **pwdstp);
423 static void nwrap_files_setpwent(struct nwrap_backend *b);
424 static struct passwd *nwrap_files_getpwent(struct nwrap_backend *b);
425 static int nwrap_files_getpwent_r(struct nwrap_backend *b,
426                                   struct passwd *pwdst, char *buf,
427                                   size_t buflen, struct passwd **pwdstp);
428 static void nwrap_files_endpwent(struct nwrap_backend *b);
429 static int nwrap_files_initgroups(struct nwrap_backend *b,
430                                   const char *user, gid_t group);
431 static struct group *nwrap_files_getgrnam(struct nwrap_backend *b,
432                                           const char *name);
433 static int nwrap_files_getgrnam_r(struct nwrap_backend *b,
434                                   const char *name, struct group *grdst,
435                                   char *buf, size_t buflen, struct group **grdstp);
436 static struct group *nwrap_files_getgrgid(struct nwrap_backend *b,
437                                           gid_t gid);
438 static int nwrap_files_getgrgid_r(struct nwrap_backend *b,
439                                   gid_t gid, struct group *grdst,
440                                   char *buf, size_t buflen, struct group **grdstp);
441 static void nwrap_files_setgrent(struct nwrap_backend *b);
442 static struct group *nwrap_files_getgrent(struct nwrap_backend *b);
443 static int nwrap_files_getgrent_r(struct nwrap_backend *b,
444                                   struct group *grdst, char *buf,
445                                   size_t buflen, struct group **grdstp);
446 static void nwrap_files_endgrent(struct nwrap_backend *b);
447
448 /* prototypes for module backend */
449
450 static struct passwd *nwrap_module_getpwent(struct nwrap_backend *b);
451 static int nwrap_module_getpwent_r(struct nwrap_backend *b,
452                                    struct passwd *pwdst, char *buf,
453                                    size_t buflen, struct passwd **pwdstp);
454 static struct passwd *nwrap_module_getpwnam(struct nwrap_backend *b,
455                                             const char *name);
456 static int nwrap_module_getpwnam_r(struct nwrap_backend *b,
457                                    const char *name, struct passwd *pwdst,
458                                    char *buf, size_t buflen, struct passwd **pwdstp);
459 static struct passwd *nwrap_module_getpwuid(struct nwrap_backend *b,
460                                             uid_t uid);
461 static int nwrap_module_getpwuid_r(struct nwrap_backend *b,
462                                    uid_t uid, struct passwd *pwdst,
463                                    char *buf, size_t buflen, struct passwd **pwdstp);
464 static void nwrap_module_setpwent(struct nwrap_backend *b);
465 static void nwrap_module_endpwent(struct nwrap_backend *b);
466 static struct group *nwrap_module_getgrent(struct nwrap_backend *b);
467 static int nwrap_module_getgrent_r(struct nwrap_backend *b,
468                                    struct group *grdst, char *buf,
469                                    size_t buflen, struct group **grdstp);
470 static struct group *nwrap_module_getgrnam(struct nwrap_backend *b,
471                                            const char *name);
472 static int nwrap_module_getgrnam_r(struct nwrap_backend *b,
473                                    const char *name, struct group *grdst,
474                                    char *buf, size_t buflen, struct group **grdstp);
475 static struct group *nwrap_module_getgrgid(struct nwrap_backend *b,
476                                            gid_t gid);
477 static int nwrap_module_getgrgid_r(struct nwrap_backend *b,
478                                    gid_t gid, struct group *grdst,
479                                    char *buf, size_t buflen, struct group **grdstp);
480 static void nwrap_module_setgrent(struct nwrap_backend *b);
481 static void nwrap_module_endgrent(struct nwrap_backend *b);
482 static int nwrap_module_initgroups(struct nwrap_backend *b,
483                                    const char *user, gid_t group);
484
485 struct nwrap_ops nwrap_files_ops = {
486         .nw_getpwnam    = nwrap_files_getpwnam,
487         .nw_getpwnam_r  = nwrap_files_getpwnam_r,
488         .nw_getpwuid    = nwrap_files_getpwuid,
489         .nw_getpwuid_r  = nwrap_files_getpwuid_r,
490         .nw_setpwent    = nwrap_files_setpwent,
491         .nw_getpwent    = nwrap_files_getpwent,
492         .nw_getpwent_r  = nwrap_files_getpwent_r,
493         .nw_endpwent    = nwrap_files_endpwent,
494         .nw_initgroups  = nwrap_files_initgroups,
495         .nw_getgrnam    = nwrap_files_getgrnam,
496         .nw_getgrnam_r  = nwrap_files_getgrnam_r,
497         .nw_getgrgid    = nwrap_files_getgrgid,
498         .nw_getgrgid_r  = nwrap_files_getgrgid_r,
499         .nw_setgrent    = nwrap_files_setgrent,
500         .nw_getgrent    = nwrap_files_getgrent,
501         .nw_getgrent_r  = nwrap_files_getgrent_r,
502         .nw_endgrent    = nwrap_files_endgrent,
503 };
504
505 struct nwrap_ops nwrap_module_ops = {
506         .nw_getpwnam    = nwrap_module_getpwnam,
507         .nw_getpwnam_r  = nwrap_module_getpwnam_r,
508         .nw_getpwuid    = nwrap_module_getpwuid,
509         .nw_getpwuid_r  = nwrap_module_getpwuid_r,
510         .nw_setpwent    = nwrap_module_setpwent,
511         .nw_getpwent    = nwrap_module_getpwent,
512         .nw_getpwent_r  = nwrap_module_getpwent_r,
513         .nw_endpwent    = nwrap_module_endpwent,
514         .nw_initgroups  = nwrap_module_initgroups,
515         .nw_getgrnam    = nwrap_module_getgrnam,
516         .nw_getgrnam_r  = nwrap_module_getgrnam_r,
517         .nw_getgrgid    = nwrap_module_getgrgid,
518         .nw_getgrgid_r  = nwrap_module_getgrgid_r,
519         .nw_setgrent    = nwrap_module_setgrent,
520         .nw_getgrent    = nwrap_module_getgrent,
521         .nw_getgrent_r  = nwrap_module_getgrent_r,
522         .nw_endgrent    = nwrap_module_endgrent,
523 };
524
525 struct nwrap_libc {
526         void *handle;
527         void *nsl_handle;
528         void *sock_handle;
529         struct nwrap_libc_fns *fns;
530 };
531
532 struct nwrap_main {
533         int num_backends;
534         struct nwrap_backend *backends;
535         struct nwrap_libc *libc;
536 };
537
538 static struct nwrap_main *nwrap_main_global;
539 static struct nwrap_main __nwrap_main_global;
540
541 /*
542  * PROTOTYPES
543  */
544 static int nwrap_convert_he_ai(const struct hostent *he,
545                                unsigned short port,
546                                const struct addrinfo *hints,
547                                struct addrinfo **pai,
548                                bool skip_canonname);
549
550 /*
551  * VECTORS
552  */
553
554 #define DEFAULT_VECTOR_CAPACITY 16
555
556 struct nwrap_vector {
557         void **items;
558         size_t count;
559         size_t capacity;
560 };
561
562 /* Macro returns pointer to first element of vector->items array.
563  *
564  * nwrap_vector is used as a memory backend which take care of
565  * memory allocations and other stuff like memory growing.
566  * nwrap_vectors should not be considered as some abstract structures.
567  * On this level, vectors are more handy than direct realloc/malloc
568  * calls.
569  *
570  * nwrap_vector->items is array inside nwrap_vector which can be
571  * directly pointed by libc structure assembled by cwrap itself.
572  *
573  * EXAMPLE:
574  *
575  * 1) struct hostent contains char **h_addr_list element.
576  * 2) nwrap_vector holds array of pointers to addresses.
577  *    It's easier to use vector to store results of
578  *    file parsing etc.
579  *
580  * Now, pretend that cwrap assembled struct hostent and
581  * we need to set h_addr_list to point to nwrap_vector.
582  * Idea behind is to shield users from internal nwrap_vector
583  * implementation.
584  * (Yes, not fully - array terminated by NULL is needed because
585  * it's result expected by libc function caller.)
586  *
587  *
588  * CODE EXAMPLE:
589  *
590  * struct hostent he;
591  * struct nwrap_vector *vector = malloc(sizeof(struct nwrap_vector));
592  * ... don't care about failed allocation now ...
593  *
594  * ... fill nwrap vector ...
595  *
596  * struct hostent he;
597  * he.h_addr_list = nwrap_vector_head(vector);
598  *
599  */
600 #define nwrap_vector_head(vect) ((void *)((vect)->items))
601
602 #define nwrap_vector_foreach(item, vect, iter) \
603         for (iter = 0, (item) = (vect).items == NULL ? NULL : (vect).items[0]; \
604              item != NULL; \
605              (item) = (vect).items[++iter])
606
607 #define nwrap_vector_is_initialized(vector) ((vector)->items != NULL)
608
609 static inline bool nwrap_vector_init(struct nwrap_vector *const vector)
610 {
611         if (vector == NULL) {
612                 return false;
613         }
614
615         /* count is initialized by ZERO_STRUCTP */
616         ZERO_STRUCTP(vector);
617         vector->items = malloc(sizeof(void *) * (DEFAULT_VECTOR_CAPACITY + 1));
618         if (vector->items == NULL) {
619                 return false;
620         }
621         vector->capacity = DEFAULT_VECTOR_CAPACITY;
622         memset(vector->items, '\0', sizeof(void *) * (DEFAULT_VECTOR_CAPACITY + 1));
623
624         return true;
625 }
626
627 static bool nwrap_vector_add_item(struct nwrap_vector *vector, void *const item)
628 {
629         assert (vector != NULL);
630
631         if (vector->items == NULL) {
632                 nwrap_vector_init(vector);
633         }
634
635         if (vector->count == vector->capacity) {
636                 /* Items array _MUST_ be NULL terminated because it's passed
637                  * as result to caller which expect NULL terminated array from libc.
638                  */
639                 void **items = realloc(vector->items, sizeof(void *) * ((vector->capacity * 2) + 1));
640                 if (items == NULL) {
641                         return false;
642                 }
643                 vector->items = items;
644
645                 /* Don't count ending NULL to capacity */
646                 vector->capacity *= 2;
647         }
648
649         vector->items[vector->count] = item;
650
651         vector->count += 1;
652         vector->items[vector->count] = NULL;
653
654         return true;
655 }
656
657 static bool nwrap_vector_merge(struct nwrap_vector *dst,
658                                struct nwrap_vector *src)
659 {
660         void **dst_items = NULL;
661         size_t count;
662
663         if (src->count == 0) {
664                 return true;
665         }
666
667         count = dst->count + src->count;
668
669         /* We don't need reallocation if we have enough capacity. */
670         if (src->count > (dst->capacity - dst->count)) {
671                 dst_items = (void **)realloc(dst->items, (count + 1) * sizeof(void *));
672                 if (dst_items == NULL) {
673                         return false;
674                 }
675                 dst->items = dst_items;
676                 dst->capacity = count;
677         }
678
679         memcpy((void *)(((long *)dst->items) + dst->count),
680                src->items,
681                src->count * sizeof(void *));
682         dst->count = count;
683
684         return true;
685 }
686
687 struct nwrap_cache {
688         const char *path;
689         int fd;
690         FILE *fp;
691         struct stat st;
692         void *private_data;
693
694         struct nwrap_vector lines;
695
696         bool (*parse_line)(struct nwrap_cache *, char *line);
697         void (*unload)(struct nwrap_cache *);
698 };
699
700 /* passwd */
701 struct nwrap_pw {
702         struct nwrap_cache *cache;
703
704         struct passwd *list;
705         int num;
706         int idx;
707 };
708
709 struct nwrap_cache __nwrap_cache_pw;
710 struct nwrap_pw nwrap_pw_global;
711
712 static bool nwrap_pw_parse_line(struct nwrap_cache *nwrap, char *line);
713 static void nwrap_pw_unload(struct nwrap_cache *nwrap);
714
715 /* shadow */
716 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
717 struct nwrap_sp {
718         struct nwrap_cache *cache;
719
720         struct spwd *list;
721         int num;
722         int idx;
723 };
724
725 struct nwrap_cache __nwrap_cache_sp;
726 struct nwrap_sp nwrap_sp_global;
727
728 static bool nwrap_sp_parse_line(struct nwrap_cache *nwrap, char *line);
729 static void nwrap_sp_unload(struct nwrap_cache *nwrap);
730 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
731
732 /* group */
733 struct nwrap_gr {
734         struct nwrap_cache *cache;
735
736         struct group *list;
737         int num;
738         int idx;
739 };
740
741 struct nwrap_cache __nwrap_cache_gr;
742 struct nwrap_gr nwrap_gr_global;
743
744 /* hosts */
745 static bool nwrap_he_parse_line(struct nwrap_cache *nwrap, char *line);
746 static void nwrap_he_unload(struct nwrap_cache *nwrap);
747
748 struct nwrap_addrdata {
749         unsigned char host_addr[16]; /* IPv4 or IPv6 address */
750 };
751
752 static size_t max_hostents = 100;
753
754 struct nwrap_entdata {
755         struct nwrap_addrdata addr;
756         struct hostent ht;
757
758         struct nwrap_vector nwrap_addrdata;
759
760         ssize_t aliases_count;
761 };
762
763 struct nwrap_entlist {
764         struct nwrap_entlist *next;
765         struct nwrap_entdata *ed;
766 };
767
768 struct nwrap_he {
769         struct nwrap_cache *cache;
770
771         struct nwrap_entdata *list;
772         struct nwrap_vector entdata;
773
774         int num;
775         int idx;
776 };
777
778 static struct nwrap_cache __nwrap_cache_he;
779 static struct nwrap_he nwrap_he_global;
780
781
782 /*********************************************************
783  * NWRAP PROTOTYPES
784  *********************************************************/
785
786 static void nwrap_init(void);
787 static bool nwrap_gr_parse_line(struct nwrap_cache *nwrap, char *line);
788 static void nwrap_gr_unload(struct nwrap_cache *nwrap);
789 void nwrap_destructor(void) DESTRUCTOR_ATTRIBUTE;
790
791 /*********************************************************
792  * NWRAP LIBC LOADER FUNCTIONS
793  *********************************************************/
794
795 enum nwrap_lib {
796     NWRAP_LIBC,
797     NWRAP_LIBNSL,
798     NWRAP_LIBSOCKET,
799 };
800
801 #ifndef NDEBUG
802 static const char *nwrap_str_lib(enum nwrap_lib lib)
803 {
804         switch (lib) {
805         case NWRAP_LIBC:
806                 return "libc";
807         case NWRAP_LIBNSL:
808                 return "libnsl";
809         case NWRAP_LIBSOCKET:
810                 return "libsocket";
811         }
812
813         /* Compiler would warn us about unhandled enum value if we get here */
814         return "unknown";
815 }
816 #endif
817
818 static void *nwrap_load_lib_handle(enum nwrap_lib lib)
819 {
820         int flags = RTLD_LAZY;
821         void *handle = NULL;
822         int i;
823
824 #ifdef RTLD_DEEPBIND
825         flags |= RTLD_DEEPBIND;
826 #endif
827
828         switch (lib) {
829         case NWRAP_LIBNSL:
830 #ifdef HAVE_LIBNSL
831                 handle = nwrap_main_global->libc->nsl_handle;
832                 if (handle == NULL) {
833                         for (i = 10; i >= 0; i--) {
834                                 char soname[256] = {0};
835
836                                 snprintf(soname, sizeof(soname), "libnsl.so.%d", i);
837                                 handle = dlopen(soname, flags);
838                                 if (handle != NULL) {
839                                         break;
840                                 }
841                         }
842
843                         nwrap_main_global->libc->nsl_handle = handle;
844                 }
845                 break;
846 #endif
847                 /* FALL TROUGH */
848         case NWRAP_LIBSOCKET:
849 #ifdef HAVE_LIBSOCKET
850                 handle = nwrap_main_global->libc->sock_handle;
851                 if (handle == NULL) {
852                         for (i = 10; i >= 0; i--) {
853                                 char soname[256] = {0};
854
855                                 snprintf(soname, sizeof(soname), "libsocket.so.%d", i);
856                                 handle = dlopen(soname, flags);
857                                 if (handle != NULL) {
858                                         break;
859                                 }
860                         }
861
862                         nwrap_main_global->libc->sock_handle = handle;
863                 }
864                 break;
865 #endif
866                 /* FALL TROUGH */
867         case NWRAP_LIBC:
868                 handle = nwrap_main_global->libc->handle;
869                 if (handle == NULL) {
870                         for (i = 10; i >= 0; i--) {
871                                 char soname[256] = {0};
872
873                                 snprintf(soname, sizeof(soname), "libc.so.%d", i);
874                                 handle = dlopen(soname, flags);
875                                 if (handle != NULL) {
876                                         break;
877                                 }
878                         }
879
880                         nwrap_main_global->libc->handle = handle;
881                 }
882                 break;
883         }
884
885         if (handle == NULL) {
886 #ifdef RTLD_NEXT
887                 handle = nwrap_main_global->libc->handle
888                        = nwrap_main_global->libc->sock_handle
889                        = nwrap_main_global->libc->nsl_handle
890                        = RTLD_NEXT;
891 #else
892                 NWRAP_LOG(NWRAP_LOG_ERROR,
893                           "Failed to dlopen library: %s\n",
894                           dlerror());
895                 exit(-1);
896 #endif
897         }
898
899         return handle;
900 }
901
902 static void *_nwrap_load_lib_function(enum nwrap_lib lib, const char *fn_name)
903 {
904         void *handle;
905         void *func;
906
907         nwrap_init();
908
909         handle = nwrap_load_lib_handle(lib);
910
911         func = dlsym(handle, fn_name);
912         if (func == NULL) {
913                 NWRAP_LOG(NWRAP_LOG_ERROR,
914                                 "Failed to find %s: %s\n",
915                                 fn_name, dlerror());
916                 exit(-1);
917         }
918
919         NWRAP_LOG(NWRAP_LOG_TRACE,
920                         "Loaded %s from %s",
921                         fn_name, nwrap_str_lib(lib));
922         return func;
923 }
924
925 #define nwrap_load_lib_function(lib, fn_name) \
926         if (nwrap_main_global->libc->fns->_libc_##fn_name == NULL) { \
927                 *(void **) (&nwrap_main_global->libc->fns->_libc_##fn_name) = \
928                         _nwrap_load_lib_function(lib, #fn_name); \
929         }
930
931 /* INTERNAL HELPER FUNCTIONS */
932 static void nwrap_lines_unload(struct nwrap_cache *const nwrap)
933 {
934         size_t p;
935         void *item;
936         nwrap_vector_foreach(item, nwrap->lines, p) {
937                 /* Maybe some vectors were merged ... */
938                 SAFE_FREE(item);
939         }
940         SAFE_FREE(nwrap->lines.items);
941         ZERO_STRUCTP(&nwrap->lines);
942 }
943
944 /*
945  * IMPORTANT
946  *
947  * Functions expeciall from libc need to be loaded individually, you can't load
948  * all at once or gdb will segfault at startup. The same applies to valgrind and
949  * has probably something todo with with the linker.
950  * So we need load each function at the point it is called the first time.
951  */
952 static struct passwd *libc_getpwnam(const char *name)
953 {
954         nwrap_load_lib_function(NWRAP_LIBC, getpwnam);
955
956         return nwrap_main_global->libc->fns->_libc_getpwnam(name);
957 }
958
959 #ifdef HAVE_GETPWNAM_R
960 static int libc_getpwnam_r(const char *name,
961                            struct passwd *pwd,
962                            char *buf,
963                            size_t buflen,
964                            struct passwd **result)
965 {
966 #ifdef HAVE___POSIX_GETPWNAM_R
967         if (nwrap_main_global->libc->fns->_libc_getpwnam_r == NULL) {
968                 *(void **) (&nwrap_main_global->libc->fns->_libc_getpwnam_r) =
969                         _nwrap_load_lib_function(NWRAP_LIBC, "__posix_getpwnam_r");
970         }
971 #else
972         nwrap_load_lib_function(NWRAP_LIBC, getpwnam_r);
973 #endif
974
975         return nwrap_main_global->libc->fns->_libc_getpwnam_r(name,
976                                                               pwd,
977                                                               buf,
978                                                               buflen,
979                                                               result);
980 }
981 #endif
982
983 static struct passwd *libc_getpwuid(uid_t uid)
984 {
985         nwrap_load_lib_function(NWRAP_LIBC, getpwuid);
986
987         return nwrap_main_global->libc->fns->_libc_getpwuid(uid);
988 }
989
990 #ifdef HAVE_GETPWUID_R
991 static int libc_getpwuid_r(uid_t uid,
992                            struct passwd *pwd,
993                            char *buf,
994                            size_t buflen,
995                            struct passwd **result)
996 {
997 #ifdef HAVE___POSIX_GETPWUID_R
998         if (nwrap_main_global->libc->fns->_libc_getpwuid_r == NULL) {
999                 *(void **) (&nwrap_main_global->libc->fns->_libc_getpwuid_r) =
1000                         _nwrap_load_lib_function(NWRAP_LIBC, "__posix_getpwuid_r");
1001         }
1002 #else
1003         nwrap_load_lib_function(NWRAP_LIBC, getpwuid_r);
1004 #endif
1005
1006         return nwrap_main_global->libc->fns->_libc_getpwuid_r(uid,
1007                                                               pwd,
1008                                                               buf,
1009                                                               buflen,
1010                                                               result);
1011 }
1012 #endif
1013
1014 static inline void str_tolower(char *dst, char *src)
1015 {
1016         register char *src_tmp = src;
1017         register char *dst_tmp = dst;
1018
1019         while (*src_tmp != '\0') {
1020                 *dst_tmp = tolower(*src_tmp);
1021                 ++src_tmp;
1022                 ++dst_tmp;
1023         }
1024 }
1025
1026 static bool str_tolower_copy(char **dst_name, const char *const src_name)
1027 {
1028         char *h_name_lower;
1029
1030         if ((dst_name == NULL) || (src_name == NULL)) {
1031                 return false;
1032         }
1033
1034         h_name_lower = strdup(src_name);
1035         if (h_name_lower == NULL) {
1036                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Out of memory while strdup");
1037                 return false;
1038         }
1039
1040         str_tolower(h_name_lower, h_name_lower);
1041         *dst_name = h_name_lower;
1042         return true;
1043 }
1044
1045 static void libc_setpwent(void)
1046 {
1047         nwrap_load_lib_function(NWRAP_LIBC, setpwent);
1048
1049         nwrap_main_global->libc->fns->_libc_setpwent();
1050 }
1051
1052 static struct passwd *libc_getpwent(void)
1053 {
1054         nwrap_load_lib_function(NWRAP_LIBC, getpwent);
1055
1056         return nwrap_main_global->libc->fns->_libc_getpwent();
1057 }
1058
1059 #ifdef HAVE_SOLARIS_GETPWENT_R
1060 static struct passwd *libc_getpwent_r(struct passwd *pwdst,
1061                                       char *buf,
1062                                       int buflen)
1063 {
1064         nwrap_load_lib_function(NWRAP_LIBC, getpwent_r);
1065
1066         return nwrap_main_global->libc->fns->_libc_getpwent_r(pwdst,
1067                                                               buf,
1068                                                               buflen);
1069 }
1070 #else /* HAVE_SOLARIS_GETPWENT_R */
1071 static int libc_getpwent_r(struct passwd *pwdst,
1072                            char *buf,
1073                            size_t buflen,
1074                            struct passwd **pwdstp)
1075 {
1076         nwrap_load_lib_function(NWRAP_LIBC, getpwent_r);
1077
1078         return nwrap_main_global->libc->fns->_libc_getpwent_r(pwdst,
1079                                                               buf,
1080                                                               buflen,
1081                                                               pwdstp);
1082 }
1083 #endif /* HAVE_SOLARIS_GETPWENT_R */
1084
1085 static void libc_endpwent(void)
1086 {
1087         nwrap_load_lib_function(NWRAP_LIBC, endpwent);
1088
1089         nwrap_main_global->libc->fns->_libc_endpwent();
1090 }
1091
1092 static int libc_initgroups(const char *user, gid_t gid)
1093 {
1094         nwrap_load_lib_function(NWRAP_LIBC, initgroups);
1095
1096         return nwrap_main_global->libc->fns->_libc_initgroups(user, gid);
1097 }
1098
1099 static struct group *libc_getgrnam(const char *name)
1100 {
1101         nwrap_load_lib_function(NWRAP_LIBC, getgrnam);
1102
1103         return nwrap_main_global->libc->fns->_libc_getgrnam(name);
1104 }
1105
1106 #ifdef HAVE_GETGRNAM_R
1107 static int libc_getgrnam_r(const char *name,
1108                            struct group *grp,
1109                            char *buf,
1110                            size_t buflen,
1111                            struct group **result)
1112 {
1113 #ifdef HAVE___POSIX_GETGRNAM_R
1114         if (nwrap_main_global->libc->fns->_libc_getgrnam_r == NULL) {
1115                 *(void **) (&nwrap_main_global->libc->fns->_libc_getgrnam_r) =
1116                         _nwrap_load_lib_function(NWRAP_LIBC, "__posix_getgrnam_r");
1117         }
1118 #else
1119         nwrap_load_lib_function(NWRAP_LIBC, getgrnam_r);
1120 #endif
1121
1122         return nwrap_main_global->libc->fns->_libc_getgrnam_r(name,
1123                                                               grp,
1124                                                               buf,
1125                                                               buflen,
1126                                                               result);
1127 }
1128 #endif
1129
1130 static struct group *libc_getgrgid(gid_t gid)
1131 {
1132         nwrap_load_lib_function(NWRAP_LIBC, getgrgid);
1133
1134         return nwrap_main_global->libc->fns->_libc_getgrgid(gid);
1135 }
1136
1137 #ifdef HAVE_GETGRGID_R
1138 static int libc_getgrgid_r(gid_t gid,
1139                            struct group *grp,
1140                            char *buf,
1141                            size_t buflen,
1142                            struct group **result)
1143 {
1144 #ifdef HAVE___POSIX_GETGRGID_R
1145         if (nwrap_main_global->libc->fns->_libc_getgrgid_r == NULL) {
1146                 *(void **) (&nwrap_main_global->libc->fns->_libc_getgrgid_r) =
1147                         _nwrap_load_lib_function(NWRAP_LIBC, "__posix_getgrgid_r");
1148         }
1149 #else
1150         nwrap_load_lib_function(NWRAP_LIBC, getgrgid_r);
1151 #endif
1152
1153         return nwrap_main_global->libc->fns->_libc_getgrgid_r(gid,
1154                                                               grp,
1155                                                               buf,
1156                                                               buflen,
1157                                                               result);
1158 }
1159 #endif
1160
1161 static void libc_setgrent(void)
1162 {
1163         nwrap_load_lib_function(NWRAP_LIBC, setgrent);
1164
1165         nwrap_main_global->libc->fns->_libc_setgrent();
1166 }
1167
1168 static struct group *libc_getgrent(void)
1169 {
1170         nwrap_load_lib_function(NWRAP_LIBC, getgrent);
1171
1172         return nwrap_main_global->libc->fns->_libc_getgrent();
1173 }
1174
1175 #ifdef HAVE_GETGRENT_R
1176 #ifdef HAVE_SOLARIS_GETGRENT_R
1177 static struct group *libc_getgrent_r(struct group *group,
1178                                      char *buf,
1179                                      size_t buflen)
1180 {
1181         nwrap_load_lib_function(NWRAP_LIBC, getgrent_r);
1182
1183         return nwrap_main_global->libc->fns->_libc_getgrent_r(group,
1184                                                               buf,
1185                                                               buflen);
1186 }
1187 #else /* !HAVE_SOLARIS_GETGRENT_R */
1188 static int libc_getgrent_r(struct group *group,
1189                            char *buf,
1190                            size_t buflen,
1191                            struct group **result)
1192 {
1193         nwrap_load_lib_function(NWRAP_LIBC, getgrent_r);
1194
1195         return nwrap_main_global->libc->fns->_libc_getgrent_r(group,
1196                                                               buf,
1197                                                               buflen,
1198                                                               result);
1199 }
1200 #endif /* HAVE_SOLARIS_GETGRENT_R */
1201 #endif /* HAVE_GETGRENT_R */
1202
1203 static void libc_endgrent(void)
1204 {
1205         nwrap_load_lib_function(NWRAP_LIBC, endgrent);
1206
1207         nwrap_main_global->libc->fns->_libc_endgrent();
1208 }
1209
1210 #ifdef HAVE_GETGROUPLIST
1211 static int libc_getgrouplist(const char *user,
1212                              gid_t group,
1213                              gid_t *groups,
1214                              int *ngroups)
1215 {
1216         nwrap_load_lib_function(NWRAP_LIBC, getgrouplist);
1217
1218         return nwrap_main_global->libc->fns->_libc_getgrouplist(user,
1219                                                                 group,
1220                                                                 groups,
1221                                                                 ngroups);
1222 }
1223 #endif
1224
1225 static void libc_sethostent(int stayopen)
1226 {
1227         nwrap_load_lib_function(NWRAP_LIBNSL, sethostent);
1228
1229         nwrap_main_global->libc->fns->_libc_sethostent(stayopen);
1230 }
1231
1232 static struct hostent *libc_gethostent(void)
1233 {
1234         nwrap_load_lib_function(NWRAP_LIBNSL, gethostent);
1235
1236         return nwrap_main_global->libc->fns->_libc_gethostent();
1237 }
1238
1239 static void libc_endhostent(void)
1240 {
1241         nwrap_load_lib_function(NWRAP_LIBNSL, endhostent);
1242
1243         nwrap_main_global->libc->fns->_libc_endhostent();
1244 }
1245
1246 static struct hostent *libc_gethostbyname(const char *name)
1247 {
1248         nwrap_load_lib_function(NWRAP_LIBNSL, gethostbyname);
1249
1250         return nwrap_main_global->libc->fns->_libc_gethostbyname(name);
1251 }
1252
1253 #ifdef HAVE_GETHOSTBYNAME2 /* GNU extension */
1254 static struct hostent *libc_gethostbyname2(const char *name, int af)
1255 {
1256         nwrap_load_lib_function(NWRAP_LIBNSL, gethostbyname2);
1257
1258         return nwrap_main_global->libc->fns->_libc_gethostbyname2(name, af);
1259 }
1260 #endif
1261
1262 static struct hostent *libc_gethostbyaddr(const void *addr,
1263                                           socklen_t len,
1264                                           int type)
1265 {
1266         nwrap_load_lib_function(NWRAP_LIBNSL, gethostbyaddr);
1267
1268         return nwrap_main_global->libc->fns->_libc_gethostbyaddr(addr,
1269                                                                  len,
1270                                                                  type);
1271 }
1272
1273 static int libc_gethostname(char *name, size_t len)
1274 {
1275         nwrap_load_lib_function(NWRAP_LIBNSL, gethostname);
1276
1277         return nwrap_main_global->libc->fns->_libc_gethostname(name, len);
1278 }
1279
1280 #ifdef HAVE_GETHOSTBYNAME_R
1281 static int libc_gethostbyname_r(const char *name,
1282                                 struct hostent *ret,
1283                                 char *buf,
1284                                 size_t buflen,
1285                                 struct hostent **result,
1286                                 int *h_errnop)
1287 {
1288         nwrap_load_lib_function(NWRAP_LIBNSL, gethostbyname_r);
1289
1290         return nwrap_main_global->libc->fns->_libc_gethostbyname_r(name,
1291                                                                    ret,
1292                                                                    buf,
1293                                                                    buflen,
1294                                                                    result,
1295                                                                    h_errnop);
1296 }
1297 #endif
1298
1299 #ifdef HAVE_GETHOSTBYADDR_R
1300 static int libc_gethostbyaddr_r(const void *addr,
1301                                 socklen_t len,
1302                                 int type,
1303                                 struct hostent *ret,
1304                                 char *buf,
1305                                 size_t buflen,
1306                                 struct hostent **result,
1307                                 int *h_errnop)
1308 {
1309         nwrap_load_lib_function(NWRAP_LIBNSL, gethostbyaddr_r);
1310
1311         return nwrap_main_global->libc->fns->_libc_gethostbyaddr_r(addr,
1312                                                                    len,
1313                                                                    type,
1314                                                                    ret,
1315                                                                    buf,
1316                                                                    buflen,
1317                                                                    result,
1318                                                                    h_errnop);
1319 }
1320 #endif
1321
1322 static int libc_getaddrinfo(const char *node,
1323                             const char *service,
1324                             const struct addrinfo *hints,
1325                             struct addrinfo **res)
1326 {
1327         nwrap_load_lib_function(NWRAP_LIBSOCKET, getaddrinfo);
1328
1329         return nwrap_main_global->libc->fns->_libc_getaddrinfo(node,
1330                                                                service,
1331                                                                hints,
1332                                                                res);
1333 }
1334
1335 static int libc_getnameinfo(const struct sockaddr *sa,
1336                             socklen_t salen,
1337                             char *host,
1338                             size_t hostlen,
1339                             char *serv,
1340                             size_t servlen,
1341                             int flags)
1342 {
1343         nwrap_load_lib_function(NWRAP_LIBSOCKET, getnameinfo);
1344
1345         return nwrap_main_global->libc->fns->_libc_getnameinfo(sa,
1346                                                                salen,
1347                                                                host,
1348                                                                hostlen,
1349                                                                serv,
1350                                                                servlen,
1351                                                                flags);
1352 }
1353
1354 /*********************************************************
1355  * NWRAP NSS MODULE LOADER FUNCTIONS
1356  *********************************************************/
1357
1358 static void *nwrap_load_module_fn(struct nwrap_backend *b,
1359                                   const char *fn_name)
1360 {
1361         void *res;
1362         char *s;
1363
1364         if (!b->so_handle) {
1365                 NWRAP_LOG(NWRAP_LOG_ERROR, "No handle");
1366                 return NULL;
1367         }
1368
1369         if (asprintf(&s, "_nss_%s_%s", b->name, fn_name) == -1) {
1370                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
1371                 return NULL;
1372         }
1373
1374         res = dlsym(b->so_handle, s);
1375         if (!res) {
1376                 NWRAP_LOG(NWRAP_LOG_ERROR,
1377                           "Cannot find function %s in %s",
1378                           s, b->so_path);
1379         }
1380         SAFE_FREE(s);
1381         return res;
1382 }
1383
1384 static struct nwrap_module_nss_fns *nwrap_load_module_fns(struct nwrap_backend *b)
1385 {
1386         struct nwrap_module_nss_fns *fns;
1387
1388         if (!b->so_handle) {
1389                 return NULL;
1390         }
1391
1392         fns = (struct nwrap_module_nss_fns *)malloc(sizeof(struct nwrap_module_nss_fns));
1393         if (!fns) {
1394                 return NULL;
1395         }
1396
1397         *(void **)(&fns->_nss_getpwnam_r) =
1398                 nwrap_load_module_fn(b, "getpwnam_r");
1399         *(void **)(&fns->_nss_getpwuid_r) =
1400                 nwrap_load_module_fn(b, "getpwuid_r");
1401         *(void **)(&fns->_nss_setpwent) =
1402                 nwrap_load_module_fn(b, "setpwent");
1403         *(void **)(&fns->_nss_getpwent_r) =
1404                 nwrap_load_module_fn(b, "getpwent_r");
1405         *(void **)(&fns->_nss_endpwent) =
1406                 nwrap_load_module_fn(b, "endpwent");
1407         *(void **)(&fns->_nss_initgroups) =
1408                 nwrap_load_module_fn(b, "initgroups_dyn");
1409         *(void **)(&fns->_nss_getgrnam_r) =
1410                 nwrap_load_module_fn(b, "getgrnam_r");
1411         *(void **)(&fns->_nss_getgrgid_r)=
1412                 nwrap_load_module_fn(b, "getgrgid_r");
1413         *(void **)(&fns->_nss_setgrent) =
1414                 nwrap_load_module_fn(b, "setgrent");
1415         *(void **)(&fns->_nss_getgrent_r) =
1416                 nwrap_load_module_fn(b, "getgrent_r");
1417         *(void **)(&fns->_nss_endgrent) =
1418                 nwrap_load_module_fn(b, "endgrent");
1419
1420         return fns;
1421 }
1422
1423 static void *nwrap_load_module(const char *so_path)
1424 {
1425         void *h;
1426
1427         if (!so_path || !strlen(so_path)) {
1428                 return NULL;
1429         }
1430
1431         h = dlopen(so_path, RTLD_LAZY);
1432         if (!h) {
1433                 NWRAP_LOG(NWRAP_LOG_ERROR,
1434                           "Cannot open shared library %s",
1435                           so_path);
1436                 return NULL;
1437         }
1438
1439         return h;
1440 }
1441
1442 static bool nwrap_module_init(const char *name,
1443                               struct nwrap_ops *ops,
1444                               const char *so_path,
1445                               int *num_backends,
1446                               struct nwrap_backend **backends)
1447 {
1448         struct nwrap_backend *b;
1449
1450         *backends = (struct nwrap_backend *)realloc(*backends,
1451                 sizeof(struct nwrap_backend) * ((*num_backends) + 1));
1452         if (!*backends) {
1453                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
1454                 return false;
1455         }
1456
1457         b = &((*backends)[*num_backends]);
1458
1459         b->name = name;
1460         b->ops = ops;
1461         b->so_path = so_path;
1462
1463         if (so_path != NULL) {
1464                 b->so_handle = nwrap_load_module(so_path);
1465                 b->fns = nwrap_load_module_fns(b);
1466                 if (b->fns == NULL) {
1467                         return false;
1468                 }
1469         } else {
1470                 b->so_handle = NULL;
1471                 b->fns = NULL;
1472         }
1473
1474         (*num_backends)++;
1475
1476         return true;
1477 }
1478
1479 static void nwrap_libc_init(struct nwrap_main *r)
1480 {
1481         r->libc = malloc(sizeof(struct nwrap_libc));
1482         if (r->libc == NULL) {
1483                 printf("Failed to allocate memory for libc");
1484                 exit(-1);
1485         }
1486         ZERO_STRUCTP(r->libc);
1487
1488         r->libc->fns = malloc(sizeof(struct nwrap_libc_fns));
1489         if (r->libc->fns == NULL) {
1490                 printf("Failed to allocate memory for libc functions");
1491                 exit(-1);
1492         }
1493         ZERO_STRUCTP(r->libc->fns);
1494 }
1495
1496 static void nwrap_backend_init(struct nwrap_main *r)
1497 {
1498         const char *module_so_path = getenv("NSS_WRAPPER_MODULE_SO_PATH");
1499         const char *module_fn_name = getenv("NSS_WRAPPER_MODULE_FN_PREFIX");
1500
1501         r->num_backends = 0;
1502         r->backends = NULL;
1503
1504         if (!nwrap_module_init("files", &nwrap_files_ops, NULL,
1505                                &r->num_backends,
1506                                &r->backends)) {
1507                 NWRAP_LOG(NWRAP_LOG_ERROR,
1508                           "Failed to initialize 'files' backend");
1509                 return;
1510         }
1511
1512         if (module_so_path != NULL &&
1513             module_so_path[0] != '\0' &&
1514             module_fn_name != NULL &&
1515             module_fn_name[0] != '\0') {
1516                 if (!nwrap_module_init(module_fn_name,
1517                                        &nwrap_module_ops,
1518                                        module_so_path,
1519                                        &r->num_backends,
1520                                        &r->backends)) {
1521                         NWRAP_LOG(NWRAP_LOG_ERROR,
1522                                   "Failed to initialize '%s' backend",
1523                                   module_fn_name);
1524                         return;
1525                 }
1526         }
1527 }
1528
1529 static void nwrap_init(void)
1530 {
1531         const char *env;
1532         char *endptr;
1533         size_t max_hostents_tmp;
1534
1535         NWRAP_LOCK(nwrap_initialized);
1536         if (nwrap_initialized) {
1537                 NWRAP_UNLOCK(nwrap_initialized);
1538                 return;
1539         }
1540
1541         /*
1542          * Still holding nwrap_initialized lock here.
1543          * We don't use NWRAP_(UN)LOCK_ALL macros here because we
1544          * want to avoid overhead when other threads do their job.
1545          */
1546         NWRAP_LOCK(nwrap_global);
1547         NWRAP_LOCK(nwrap_gr_global);
1548         NWRAP_LOCK(nwrap_he_global);
1549         NWRAP_LOCK(nwrap_pw_global);
1550         NWRAP_LOCK(nwrap_sp_global);
1551
1552         nwrap_initialized = true;
1553
1554         /* Initialize pthread_atfork handlers */
1555         pthread_atfork(&nwrap_thread_prepare, &nwrap_thread_parent,
1556                        &nwrap_thread_child);
1557
1558         env = getenv("NSS_WRAPPER_MAX_HOSTENTS");
1559         if (env != NULL) {
1560                 max_hostents_tmp = (size_t)strtol(env, &endptr, 10);
1561                 if (((env != '\0') && (endptr == '\0')) ||
1562                     (max_hostents_tmp == 0)) {
1563                         NWRAP_LOG(NWRAP_LOG_DEBUG,
1564                                   "Error parsing NSS_WRAPPER_MAX_HOSTENTS "
1565                                   "value or value is too small. "
1566                                   "Using default value: %lu.",
1567                                   max_hostents);
1568                 } else {
1569                         max_hostents = max_hostents_tmp;
1570                 }
1571         }
1572         /* Initialize hash table */
1573         NWRAP_LOG(NWRAP_LOG_DEBUG,
1574                   "Initializing hash table of size %lu items.", max_hostents);
1575         if (hcreate(max_hostents) == 0) {
1576                 NWRAP_LOG(NWRAP_LOG_ERROR,
1577                           "Failed to initialize hash table");
1578                 goto done;
1579         }
1580
1581         nwrap_main_global = &__nwrap_main_global;
1582
1583         nwrap_libc_init(nwrap_main_global);
1584
1585         nwrap_backend_init(nwrap_main_global);
1586
1587         /* passwd */
1588         nwrap_pw_global.cache = &__nwrap_cache_pw;
1589
1590         nwrap_pw_global.cache->path = getenv("NSS_WRAPPER_PASSWD");
1591         nwrap_pw_global.cache->fp = NULL;
1592         nwrap_pw_global.cache->fd = -1;
1593         nwrap_pw_global.cache->private_data = &nwrap_pw_global;
1594         nwrap_pw_global.cache->parse_line = nwrap_pw_parse_line;
1595         nwrap_pw_global.cache->unload = nwrap_pw_unload;
1596
1597         /* shadow */
1598 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
1599         nwrap_sp_global.cache = &__nwrap_cache_sp;
1600
1601         nwrap_sp_global.cache->path = getenv("NSS_WRAPPER_SHADOW");
1602         nwrap_sp_global.cache->fp = NULL;
1603         nwrap_sp_global.cache->fd = -1;
1604         nwrap_sp_global.cache->private_data = &nwrap_sp_global;
1605         nwrap_sp_global.cache->parse_line = nwrap_sp_parse_line;
1606         nwrap_sp_global.cache->unload = nwrap_sp_unload;
1607 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
1608
1609         /* group */
1610         nwrap_gr_global.cache = &__nwrap_cache_gr;
1611
1612         nwrap_gr_global.cache->path = getenv("NSS_WRAPPER_GROUP");
1613         nwrap_gr_global.cache->fp = NULL;
1614         nwrap_gr_global.cache->fd = -1;
1615         nwrap_gr_global.cache->private_data = &nwrap_gr_global;
1616         nwrap_gr_global.cache->parse_line = nwrap_gr_parse_line;
1617         nwrap_gr_global.cache->unload = nwrap_gr_unload;
1618
1619         /* hosts */
1620         nwrap_he_global.cache = &__nwrap_cache_he;
1621
1622         nwrap_he_global.cache->path = getenv("NSS_WRAPPER_HOSTS");
1623         nwrap_he_global.cache->fp = NULL;
1624         nwrap_he_global.cache->fd = -1;
1625         nwrap_he_global.cache->private_data = &nwrap_he_global;
1626         nwrap_he_global.cache->parse_line = nwrap_he_parse_line;
1627         nwrap_he_global.cache->unload = nwrap_he_unload;
1628
1629 done:
1630         /* We hold all locks here so we can use NWRAP_UNLOCK_ALL. */
1631         NWRAP_UNLOCK_ALL;
1632 }
1633
1634 bool nss_wrapper_enabled(void)
1635 {
1636         nwrap_init();
1637
1638         if (nwrap_pw_global.cache->path == NULL ||
1639             nwrap_pw_global.cache->path[0] == '\0') {
1640                 return false;
1641         }
1642         if (nwrap_gr_global.cache->path == NULL ||
1643             nwrap_gr_global.cache->path[0] == '\0') {
1644                 return false;
1645         }
1646
1647         return true;
1648 }
1649
1650 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
1651 bool nss_wrapper_shadow_enabled(void)
1652 {
1653         nwrap_init();
1654
1655         if (nwrap_sp_global.cache->path == NULL ||
1656             nwrap_sp_global.cache->path[0] == '\0') {
1657                 return false;
1658         }
1659
1660         return true;
1661 }
1662 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
1663
1664 bool nss_wrapper_hosts_enabled(void)
1665 {
1666         nwrap_init();
1667
1668         if (nwrap_he_global.cache->path == NULL ||
1669             nwrap_he_global.cache->path[0] == '\0') {
1670                 return false;
1671         }
1672
1673         return true;
1674 }
1675
1676 static bool nwrap_hostname_enabled(void)
1677 {
1678         nwrap_init();
1679
1680         if (getenv("NSS_WRAPPER_HOSTNAME") == NULL) {
1681                 return false;
1682         }
1683
1684         return true;
1685 }
1686
1687 static bool nwrap_parse_file(struct nwrap_cache *nwrap)
1688 {
1689         char *line = NULL;
1690         ssize_t n;
1691         /* Unused but getline needs it */
1692         size_t len;
1693         bool ok;
1694
1695         if (nwrap->st.st_size == 0) {
1696                 NWRAP_LOG(NWRAP_LOG_DEBUG, "size == 0");
1697                 return true;
1698         }
1699
1700         /* Support for 32-bit system I guess */
1701         if (nwrap->st.st_size > INT32_MAX) {
1702                 NWRAP_LOG(NWRAP_LOG_ERROR,
1703                           "Size[%u] larger than INT32_MAX",
1704                           (unsigned)nwrap->st.st_size);
1705                 return false;
1706         }
1707
1708         rewind(nwrap->fp);
1709
1710         do {
1711                 n = getline(&line, &len, nwrap->fp);
1712                 if (n < 0) {
1713                         SAFE_FREE(line);
1714                         if (feof(nwrap->fp)) {
1715                                 break;
1716                         }
1717
1718                         NWRAP_LOG(NWRAP_LOG_ERROR,
1719                                   "Unable to read line from file: %s",
1720                                   nwrap->path);
1721                         return false;
1722                 }
1723
1724                 if (line[n - 1] == '\n') {
1725                         line[n - 1] = '\0';
1726                 }
1727
1728                 if (line[0] == '\0') {
1729                         SAFE_FREE(line);
1730                         continue;
1731                 }
1732
1733                 ok = nwrap->parse_line(nwrap, line);
1734                 if (!ok) {
1735                         NWRAP_LOG(NWRAP_LOG_ERROR,
1736                                   "Unable to parse line file: %s",
1737                                   line);
1738                         SAFE_FREE(line);
1739                         return false;
1740                 }
1741
1742                 /* Line is parsed without issues so add it to list */
1743                 ok = nwrap_vector_add_item(&(nwrap->lines), (void *const) line);
1744                 if (!ok) {
1745                         NWRAP_LOG(NWRAP_LOG_ERROR,
1746                                   "Unable to add line to vector");
1747                         return false;
1748                 }
1749
1750                 /* This forces getline to allocate new memory for line. */
1751                 line = NULL;
1752         } while (!feof(nwrap->fp));
1753
1754         return true;
1755 }
1756
1757 static void nwrap_files_cache_unload(struct nwrap_cache *nwrap)
1758 {
1759         nwrap->unload(nwrap);
1760
1761         nwrap_lines_unload(nwrap);
1762 }
1763
1764 static void nwrap_files_cache_reload(struct nwrap_cache *nwrap)
1765 {
1766         struct stat st;
1767         int ret;
1768         bool ok;
1769         bool retried = false;
1770
1771         assert(nwrap != NULL);
1772
1773 reopen:
1774         if (nwrap->fd < 0) {
1775                 nwrap->fp = fopen(nwrap->path, "re");
1776                 if (nwrap->fp == NULL) {
1777                         nwrap->fd = -1;
1778                         NWRAP_LOG(NWRAP_LOG_ERROR,
1779                                   "Unable to open '%s' readonly %d:%s",
1780                                   nwrap->path, nwrap->fd,
1781                                   strerror(errno));
1782                         return;
1783
1784                 }
1785                 nwrap->fd = fileno(nwrap->fp);
1786                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Open '%s'", nwrap->path);
1787         }
1788
1789         ret = fstat(nwrap->fd, &st);
1790         if (ret != 0) {
1791                 NWRAP_LOG(NWRAP_LOG_ERROR,
1792                           "fstat(%s) - %d:%s",
1793                           nwrap->path,
1794                           ret,
1795                           strerror(errno));
1796                 fclose(nwrap->fp);
1797                 nwrap->fp = NULL;
1798                 nwrap->fd = -1;
1799                 return;
1800         }
1801
1802         if (retried == false && st.st_nlink == 0) {
1803                 /* maybe someone has replaced the file... */
1804                 NWRAP_LOG(NWRAP_LOG_TRACE,
1805                           "st_nlink == 0, reopen %s",
1806                           nwrap->path);
1807                 retried = true;
1808                 memset(&nwrap->st, 0, sizeof(nwrap->st));
1809                 fclose(nwrap->fp);
1810                 nwrap->fp = NULL;
1811                 nwrap->fd = -1;
1812                 goto reopen;
1813         }
1814
1815         if (st.st_mtime == nwrap->st.st_mtime) {
1816                 NWRAP_LOG(NWRAP_LOG_TRACE,
1817                           "st_mtime[%u] hasn't changed, skip reload",
1818                           (unsigned)st.st_mtime);
1819                 return;
1820         }
1821
1822         NWRAP_LOG(NWRAP_LOG_TRACE,
1823                   "st_mtime has changed [%u] => [%u], start reload",
1824                   (unsigned)st.st_mtime,
1825                   (unsigned)nwrap->st.st_mtime);
1826
1827         nwrap->st = st;
1828
1829         nwrap_files_cache_unload(nwrap);
1830
1831         ok = nwrap_parse_file(nwrap);
1832         if (!ok) {
1833                 NWRAP_LOG(NWRAP_LOG_ERROR, "Failed to reload %s", nwrap->path);
1834                 nwrap_files_cache_unload(nwrap);
1835         }
1836
1837         NWRAP_LOG(NWRAP_LOG_TRACE, "Reloaded %s", nwrap->path);
1838 }
1839
1840 /*
1841  * the caller has to call nwrap_unload() on failure
1842  */
1843 static bool nwrap_pw_parse_line(struct nwrap_cache *nwrap, char *line)
1844 {
1845         struct nwrap_pw *nwrap_pw;
1846         char *c;
1847         char *p;
1848         char *e;
1849         struct passwd *pw;
1850         size_t list_size;
1851
1852         nwrap_pw = (struct nwrap_pw *)nwrap->private_data;
1853
1854         list_size = sizeof(*nwrap_pw->list) * (nwrap_pw->num+1);
1855         pw = (struct passwd *)realloc(nwrap_pw->list, list_size);
1856         if (!pw) {
1857                 NWRAP_LOG(NWRAP_LOG_ERROR,
1858                           "realloc(%u) failed",
1859                           (unsigned)list_size);
1860                 return false;
1861         }
1862         nwrap_pw->list = pw;
1863
1864         pw = &nwrap_pw->list[nwrap_pw->num];
1865
1866         c = line;
1867
1868         /* name */
1869         p = strchr(c, ':');
1870         if (!p) {
1871                 NWRAP_LOG(NWRAP_LOG_ERROR,
1872                           "Invalid line[%s]: '%s'",
1873                           line,
1874                           c);
1875                 return false;
1876         }
1877         *p = '\0';
1878         p++;
1879         pw->pw_name = c;
1880         c = p;
1881
1882         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]\n", pw->pw_name);
1883
1884         /* password */
1885         p = strchr(c, ':');
1886         if (!p) {
1887                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1888                 return false;
1889         }
1890         *p = '\0';
1891         p++;
1892         pw->pw_passwd = c;
1893         c = p;
1894
1895         NWRAP_LOG(NWRAP_LOG_TRACE, "password[%s]\n", pw->pw_passwd);
1896
1897         /* uid */
1898         p = strchr(c, ':');
1899         if (!p) {
1900                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1901                 return false;
1902         }
1903         *p = '\0';
1904         p++;
1905         e = NULL;
1906         pw->pw_uid = (uid_t)strtoul(c, &e, 10);
1907         if (c == e) {
1908                 NWRAP_LOG(NWRAP_LOG_ERROR,
1909                           "Invalid line[%s]: '%s' - %s",
1910                           line, c, strerror(errno));
1911                 return false;
1912         }
1913         if (e == NULL) {
1914                 NWRAP_LOG(NWRAP_LOG_ERROR,
1915                           "Invalid line[%s]: '%s' - %s",
1916                           line, c, strerror(errno));
1917                 return false;
1918         }
1919         if (e[0] != '\0') {
1920                 NWRAP_LOG(NWRAP_LOG_ERROR,
1921                           "Invalid line[%s]: '%s' - %s",
1922                           line, c, strerror(errno));
1923                 return false;
1924         }
1925         c = p;
1926
1927         NWRAP_LOG(NWRAP_LOG_TRACE, "uid[%u]", pw->pw_uid);
1928
1929         /* gid */
1930         p = strchr(c, ':');
1931         if (!p) {
1932                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1933                 return false;
1934         }
1935         *p = '\0';
1936         p++;
1937         e = NULL;
1938         pw->pw_gid = (gid_t)strtoul(c, &e, 10);
1939         if (c == e) {
1940                 NWRAP_LOG(NWRAP_LOG_ERROR,
1941                           "Invalid line[%s]: '%s' - %s",
1942                           line, c, strerror(errno));
1943                 return false;
1944         }
1945         if (e == NULL) {
1946                 NWRAP_LOG(NWRAP_LOG_ERROR,
1947                           "Invalid line[%s]: '%s' - %s",
1948                           line, c, strerror(errno));
1949                 return false;
1950         }
1951         if (e[0] != '\0') {
1952                 NWRAP_LOG(NWRAP_LOG_ERROR,
1953                           "Invalid line[%s]: '%s' - %s",
1954                           line, c, strerror(errno));
1955                 return false;
1956         }
1957         c = p;
1958
1959         NWRAP_LOG(NWRAP_LOG_TRACE, "gid[%u]\n", pw->pw_gid);
1960
1961         /* gecos */
1962         p = strchr(c, ':');
1963         if (!p) {
1964                 NWRAP_LOG(NWRAP_LOG_ERROR, "invalid line[%s]: '%s'", line, c);
1965                 return false;
1966         }
1967         *p = '\0';
1968         p++;
1969         pw->pw_gecos = c;
1970         c = p;
1971
1972         NWRAP_LOG(NWRAP_LOG_TRACE, "gecos[%s]", pw->pw_gecos);
1973
1974         /* dir */
1975         p = strchr(c, ':');
1976         if (!p) {
1977                 NWRAP_LOG(NWRAP_LOG_ERROR, "'%s'", c);
1978                 return false;
1979         }
1980         *p = '\0';
1981         p++;
1982         pw->pw_dir = c;
1983         c = p;
1984
1985         NWRAP_LOG(NWRAP_LOG_TRACE, "dir[%s]", pw->pw_dir);
1986
1987         /* shell */
1988         pw->pw_shell = c;
1989         NWRAP_LOG(NWRAP_LOG_TRACE, "shell[%s]", pw->pw_shell);
1990
1991         NWRAP_LOG(NWRAP_LOG_DEBUG,
1992                   "Added user[%s:%s:%u:%u:%s:%s:%s]",
1993                   pw->pw_name, pw->pw_passwd,
1994                   pw->pw_uid, pw->pw_gid,
1995                   pw->pw_gecos, pw->pw_dir, pw->pw_shell);
1996
1997         nwrap_pw->num++;
1998         return true;
1999 }
2000
2001 static void nwrap_pw_unload(struct nwrap_cache *nwrap)
2002 {
2003         struct nwrap_pw *nwrap_pw;
2004         nwrap_pw = (struct nwrap_pw *)nwrap->private_data;
2005
2006         SAFE_FREE(nwrap_pw->list);
2007         nwrap_pw->num = 0;
2008         nwrap_pw->idx = 0;
2009 }
2010
2011 static int nwrap_pw_copy_r(const struct passwd *src, struct passwd *dst,
2012                            char *buf, size_t buflen, struct passwd **dstp)
2013 {
2014         char *first;
2015         char *last;
2016         off_t ofs;
2017
2018         first = src->pw_name;
2019
2020         last = src->pw_shell;
2021         while (*last) last++;
2022
2023         ofs = PTR_DIFF(last + 1, first);
2024
2025         if (ofs > (off_t) buflen) {
2026                 return ERANGE;
2027         }
2028
2029         memcpy(buf, first, ofs);
2030
2031         ofs = PTR_DIFF(src->pw_name, first);
2032         dst->pw_name = buf + ofs;
2033         ofs = PTR_DIFF(src->pw_passwd, first);
2034         dst->pw_passwd = buf + ofs;
2035         dst->pw_uid = src->pw_uid;
2036         dst->pw_gid = src->pw_gid;
2037         ofs = PTR_DIFF(src->pw_gecos, first);
2038         dst->pw_gecos = buf + ofs;
2039         ofs = PTR_DIFF(src->pw_dir, first);
2040         dst->pw_dir = buf + ofs;
2041         ofs = PTR_DIFF(src->pw_shell, first);
2042         dst->pw_shell = buf + ofs;
2043
2044         if (dstp) {
2045                 *dstp = dst;
2046         }
2047
2048         return 0;
2049 }
2050
2051 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
2052 static bool nwrap_sp_parse_line(struct nwrap_cache *nwrap, char *line)
2053 {
2054         struct nwrap_sp *nwrap_sp;
2055         struct spwd *sp;
2056         size_t list_size;
2057         char *c;
2058         char *e;
2059         char *p;
2060
2061         nwrap_sp = (struct nwrap_sp *)nwrap->private_data;
2062
2063         list_size = sizeof(*nwrap_sp->list) * (nwrap_sp->num+1);
2064         sp = (struct spwd *)realloc(nwrap_sp->list, list_size);
2065         if (sp == NULL) {
2066                 NWRAP_LOG(NWRAP_LOG_ERROR,
2067                           "realloc(%u) failed",
2068                           (unsigned)list_size);
2069                 return false;
2070         }
2071         nwrap_sp->list = sp;
2072
2073         sp = &nwrap_sp->list[nwrap_sp->num];
2074
2075         c = line;
2076
2077         /* name */
2078         p = strchr(c, ':');
2079         if (p == NULL) {
2080                 NWRAP_LOG(NWRAP_LOG_ERROR,
2081                           "name -- Invalid line[%s]: '%s'",
2082                           line,
2083                           c);
2084                 return false;
2085         }
2086         *p = '\0';
2087         p++;
2088         sp->sp_namp = c;
2089         c = p;
2090
2091         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]\n", sp->sp_namp);
2092
2093         /* pwd */
2094         p = strchr(c, ':');
2095         if (p == NULL) {
2096                 NWRAP_LOG(NWRAP_LOG_ERROR,
2097                           "pwd -- Invalid line[%s]: '%s'",
2098                           line,
2099                           c);
2100                 return false;
2101         }
2102         *p = '\0';
2103         p++;
2104         sp->sp_pwdp = c;
2105         c = p;
2106
2107         /* lstchg (long) */
2108         if (c[0] == ':') {
2109                 sp->sp_lstchg = -1;
2110                 p++;
2111         } else {
2112                 p = strchr(c, ':');
2113                 if (p == NULL) {
2114                         NWRAP_LOG(NWRAP_LOG_ERROR,
2115                                   "lstchg -- Invalid line[%s]: '%s'",
2116                                   line,
2117                                   c);
2118                         return false;
2119                 }
2120                 *p = '\0';
2121                 p++;
2122                 sp->sp_lstchg = strtol(c, &e, 10);
2123                 if (c == e) {
2124                         NWRAP_LOG(NWRAP_LOG_ERROR,
2125                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2126                                   line, c, strerror(errno));
2127                         return false;
2128                 }
2129                 if (e == NULL) {
2130                         NWRAP_LOG(NWRAP_LOG_ERROR,
2131                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2132                                   line, c, strerror(errno));
2133                         return false;
2134                 }
2135                 if (e[0] != '\0') {
2136                         NWRAP_LOG(NWRAP_LOG_ERROR,
2137                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2138                                   line, c, strerror(errno));
2139                         return false;
2140                 }
2141         }
2142         c = p;
2143
2144         /* min (long) */
2145         if (c[0] == ':') {
2146                 sp->sp_min = -1;
2147                 p++;
2148         } else {
2149                 p = strchr(c, ':');
2150                 if (p == NULL) {
2151                         NWRAP_LOG(NWRAP_LOG_ERROR,
2152                                   "min -- Invalid line[%s]: '%s'",
2153                                   line,
2154                                   c);
2155                         return false;
2156                 }
2157                 *p = '\0';
2158                 p++;
2159                 sp->sp_min = strtol(c, &e, 10);
2160                 if (c == e) {
2161                         NWRAP_LOG(NWRAP_LOG_ERROR,
2162                                   "min -- Invalid line[%s]: '%s' - %s",
2163                                   line, c, strerror(errno));
2164                         return false;
2165                 }
2166                 if (e == NULL) {
2167                         NWRAP_LOG(NWRAP_LOG_ERROR,
2168                                   "min -- Invalid line[%s]: '%s' - %s",
2169                                   line, c, strerror(errno));
2170                         return false;
2171                 }
2172                 if (e[0] != '\0') {
2173                         NWRAP_LOG(NWRAP_LOG_ERROR,
2174                                   "min -- Invalid line[%s]: '%s' - %s",
2175                                   line, c, strerror(errno));
2176                         return false;
2177                 }
2178         }
2179         c = p;
2180
2181         /* max (long) */
2182         if (c[0] == ':') {
2183                 sp->sp_max = -1;
2184                 p++;
2185         } else {
2186                 p = strchr(c, ':');
2187                 if (p == NULL) {
2188                         NWRAP_LOG(NWRAP_LOG_ERROR,
2189                                   "max -- Invalid line[%s]: '%s'",
2190                                   line,
2191                                   c);
2192                         return false;
2193                 }
2194                 *p = '\0';
2195                 p++;
2196                 sp->sp_max = strtol(c, &e, 10);
2197                 if (c == e) {
2198                         NWRAP_LOG(NWRAP_LOG_ERROR,
2199                                   "max -- Invalid line[%s]: '%s' - %s",
2200                                   line, c, strerror(errno));
2201                         return false;
2202                 }
2203                 if (e == NULL) {
2204                         NWRAP_LOG(NWRAP_LOG_ERROR,
2205                                   "max -- Invalid line[%s]: '%s' - %s",
2206                                   line, c, strerror(errno));
2207                         return false;
2208                 }
2209                 if (e[0] != '\0') {
2210                         NWRAP_LOG(NWRAP_LOG_ERROR,
2211                                   "max -- Invalid line[%s]: '%s' - %s",
2212                                   line, c, strerror(errno));
2213                         return false;
2214                 }
2215         }
2216         c = p;
2217
2218         /* warn (long) */
2219         if (c[0] == ':') {
2220                 sp->sp_warn = -1;
2221                 p++;
2222         } else {
2223                 p = strchr(c, ':');
2224                 if (p == NULL) {
2225                         NWRAP_LOG(NWRAP_LOG_ERROR,
2226                                   "warn -- Invalid line[%s]: '%s'",
2227                                   line,
2228                                   c);
2229                         return false;
2230                 }
2231                 *p = '\0';
2232                 p++;
2233                 sp->sp_warn = strtol(c, &e, 10);
2234                 if (c == e) {
2235                         NWRAP_LOG(NWRAP_LOG_ERROR,
2236                                   "warn -- Invalid line[%s]: '%s' - %s",
2237                                   line, c, strerror(errno));
2238                         return false;
2239                 }
2240                 if (e == NULL) {
2241                         NWRAP_LOG(NWRAP_LOG_ERROR,
2242                                   "warn -- Invalid line[%s]: '%s' - %s",
2243                                   line, c, strerror(errno));
2244                         return false;
2245                 }
2246                 if (e[0] != '\0') {
2247                         NWRAP_LOG(NWRAP_LOG_ERROR,
2248                                   "warn -- Invalid line[%s]: '%s' - %s",
2249                                   line, c, strerror(errno));
2250                         return false;
2251                 }
2252         }
2253         c = p;
2254
2255         /* inact (long) */
2256         if (c[0] == ':') {
2257                 sp->sp_inact = -1;
2258                 p++;
2259         } else {
2260                 p = strchr(c, ':');
2261                 if (p == NULL) {
2262                         NWRAP_LOG(NWRAP_LOG_ERROR,
2263                                   "inact -- Invalid line[%s]: '%s'",
2264                                   line,
2265                                   c);
2266                         return false;
2267                 }
2268                 *p = '\0';
2269                 p++;
2270                 sp->sp_inact = strtol(c, &e, 10);
2271                 if (c == e) {
2272                         NWRAP_LOG(NWRAP_LOG_ERROR,
2273                                   "inact -- Invalid line[%s]: '%s' - %s",
2274                                   line, c, strerror(errno));
2275                         return false;
2276                 }
2277                 if (e == NULL) {
2278                         NWRAP_LOG(NWRAP_LOG_ERROR,
2279                                   "inact -- Invalid line[%s]: '%s' - %s",
2280                                   line, c, strerror(errno));
2281                         return false;
2282                 }
2283                 if (e[0] != '\0') {
2284                         NWRAP_LOG(NWRAP_LOG_ERROR,
2285                                   "inact -- Invalid line[%s]: '%s' - %s",
2286                                   line, c, strerror(errno));
2287                         return false;
2288                 }
2289         }
2290         c = p;
2291
2292         /* expire (long) */
2293         if (c[0] == ':') {
2294                 sp->sp_expire = -1;
2295                 p++;
2296         } else {
2297                 p = strchr(c, ':');
2298                 if (p == NULL) {
2299                         NWRAP_LOG(NWRAP_LOG_ERROR,
2300                                   "expire -- Invalid line[%s]: '%s'",
2301                                   line,
2302                                   c);
2303                         return false;
2304                 }
2305                 *p = '\0';
2306                 p++;
2307                 sp->sp_expire = strtol(c, &e, 10);
2308                 if (c == e) {
2309                         NWRAP_LOG(NWRAP_LOG_ERROR,
2310                                   "expire -- Invalid line[%s]: '%s' - %s",
2311                                   line, c, strerror(errno));
2312                         return false;
2313                 }
2314                 if (e == NULL) {
2315                         NWRAP_LOG(NWRAP_LOG_ERROR,
2316                                   "expire -- Invalid line[%s]: '%s' - %s",
2317                                   line, c, strerror(errno));
2318                         return false;
2319                 }
2320                 if (e[0] != '\0') {
2321                         NWRAP_LOG(NWRAP_LOG_ERROR,
2322                                   "expire -- Invalid line[%s]: '%s' - %s",
2323                                   line, c, strerror(errno));
2324                         return false;
2325                 }
2326         }
2327         c = p;
2328
2329         nwrap_sp->num++;
2330         return true;
2331 }
2332
2333 static void nwrap_sp_unload(struct nwrap_cache *nwrap)
2334 {
2335         struct nwrap_sp *nwrap_sp;
2336         nwrap_sp = (struct nwrap_sp *)nwrap->private_data;
2337
2338         SAFE_FREE(nwrap_sp->list);
2339         nwrap_sp->num = 0;
2340         nwrap_sp->idx = 0;
2341 }
2342 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
2343
2344 /*
2345  * the caller has to call nwrap_unload() on failure
2346  */
2347 static bool nwrap_gr_parse_line(struct nwrap_cache *nwrap, char *line)
2348 {
2349         struct nwrap_gr *nwrap_gr;
2350         char *c;
2351         char *p;
2352         char *e;
2353         struct group *gr;
2354         size_t list_size;
2355         unsigned nummem;
2356
2357         nwrap_gr = (struct nwrap_gr *)nwrap->private_data;
2358
2359         list_size = sizeof(*nwrap_gr->list) * (nwrap_gr->num+1);
2360         gr = (struct group *)realloc(nwrap_gr->list, list_size);
2361         if (!gr) {
2362                 NWRAP_LOG(NWRAP_LOG_ERROR, "realloc failed");
2363                 return false;
2364         }
2365         nwrap_gr->list = gr;
2366
2367         gr = &nwrap_gr->list[nwrap_gr->num];
2368
2369         c = line;
2370
2371         /* name */
2372         p = strchr(c, ':');
2373         if (!p) {
2374                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2375                 return false;
2376         }
2377         *p = '\0';
2378         p++;
2379         gr->gr_name = c;
2380         c = p;
2381
2382         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]", gr->gr_name);
2383
2384         /* password */
2385         p = strchr(c, ':');
2386         if (!p) {
2387                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2388                 return false;
2389         }
2390         *p = '\0';
2391         p++;
2392         gr->gr_passwd = c;
2393         c = p;
2394
2395         NWRAP_LOG(NWRAP_LOG_TRACE, "password[%s]", gr->gr_passwd);
2396
2397         /* gid */
2398         p = strchr(c, ':');
2399         if (!p) {
2400                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2401                 return false;
2402         }
2403         *p = '\0';
2404         p++;
2405         e = NULL;
2406         gr->gr_gid = (gid_t)strtoul(c, &e, 10);
2407         if (c == e) {
2408                 NWRAP_LOG(NWRAP_LOG_ERROR,
2409                           "Invalid line[%s]: '%s' - %s",
2410                           line, c, strerror(errno));
2411                 return false;
2412         }
2413         if (e == NULL) {
2414                 NWRAP_LOG(NWRAP_LOG_ERROR,
2415                           "Invalid line[%s]: '%s' - %s",
2416                           line, c, strerror(errno));
2417                 return false;
2418         }
2419         if (e[0] != '\0') {
2420                 NWRAP_LOG(NWRAP_LOG_ERROR,
2421                           "Invalid line[%s]: '%s' - %s",
2422                           line, c, strerror(errno));
2423                 return false;
2424         }
2425         c = p;
2426
2427         NWRAP_LOG(NWRAP_LOG_TRACE, "gid[%u]", gr->gr_gid);
2428
2429         /* members */
2430         gr->gr_mem = (char **)malloc(sizeof(char *));
2431         if (!gr->gr_mem) {
2432                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
2433                 return false;
2434         }
2435         gr->gr_mem[0] = NULL;
2436
2437         for(nummem=0; p; nummem++) {
2438                 char **m;
2439                 size_t m_size;
2440                 c = p;
2441                 p = strchr(c, ',');
2442                 if (p) {
2443                         *p = '\0';
2444                         p++;
2445                 }
2446
2447                 if (strlen(c) == 0) {
2448                         break;
2449                 }
2450
2451                 m_size = sizeof(char *) * (nummem+2);
2452                 m = (char **)realloc(gr->gr_mem, m_size);
2453                 if (!m) {
2454                         NWRAP_LOG(NWRAP_LOG_ERROR,
2455                                   "realloc(%zd) failed",
2456                                   m_size);
2457                         return false;
2458                 }
2459                 gr->gr_mem = m;
2460                 gr->gr_mem[nummem] = c;
2461                 gr->gr_mem[nummem+1] = NULL;
2462
2463                 NWRAP_LOG(NWRAP_LOG_TRACE,
2464                           "member[%u]: '%s'",
2465                           nummem, gr->gr_mem[nummem]);
2466         }
2467
2468         NWRAP_LOG(NWRAP_LOG_DEBUG,
2469                   "Added group[%s:%s:%u:] with %u members",
2470                   gr->gr_name, gr->gr_passwd, gr->gr_gid, nummem);
2471
2472         nwrap_gr->num++;
2473         return true;
2474 }
2475
2476 static void nwrap_gr_unload(struct nwrap_cache *nwrap)
2477 {
2478         int i;
2479         struct nwrap_gr *nwrap_gr;
2480         nwrap_gr = (struct nwrap_gr *)nwrap->private_data;
2481
2482         if (nwrap_gr->list) {
2483                 for (i=0; i < nwrap_gr->num; i++) {
2484                         SAFE_FREE(nwrap_gr->list[i].gr_mem);
2485                 }
2486                 SAFE_FREE(nwrap_gr->list);
2487         }
2488
2489         nwrap_gr->num = 0;
2490         nwrap_gr->idx = 0;
2491 }
2492
2493 static int nwrap_gr_copy_r(const struct group *src, struct group *dst,
2494                            char *buf, size_t buflen, struct group **dstp)
2495 {
2496         char *first;
2497         char **lastm;
2498         char *last = NULL;
2499         off_t ofsb;
2500         off_t ofsm;
2501         off_t ofs;
2502         unsigned i;
2503
2504         first = src->gr_name;
2505
2506         lastm = src->gr_mem;
2507         while (*lastm) {
2508                 last = *lastm;
2509                 lastm++;
2510         }
2511
2512         if (last == NULL) {
2513                 last = src->gr_passwd;
2514         }
2515         while (*last) last++;
2516
2517         ofsb = PTR_DIFF(last + 1, first);
2518         ofsm = PTR_DIFF(lastm + 1, src->gr_mem);
2519
2520         if ((ofsb + ofsm) > (off_t) buflen) {
2521                 return ERANGE;
2522         }
2523
2524         memcpy(buf, first, ofsb);
2525         memcpy(buf + ofsb, src->gr_mem, ofsm);
2526
2527         ofs = PTR_DIFF(src->gr_name, first);
2528         dst->gr_name = buf + ofs;
2529         ofs = PTR_DIFF(src->gr_passwd, first);
2530         dst->gr_passwd = buf + ofs;
2531         dst->gr_gid = src->gr_gid;
2532
2533         dst->gr_mem = (char **)(buf + ofsb);
2534         for (i=0; src->gr_mem[i]; i++) {
2535                 ofs = PTR_DIFF(src->gr_mem[i], first);
2536                 dst->gr_mem[i] = buf + ofs;
2537         }
2538
2539         if (dstp) {
2540                 *dstp = dst;
2541         }
2542
2543         return 0;
2544 }
2545
2546 static struct nwrap_entlist *nwrap_entlist_init(struct nwrap_entdata *ed)
2547 {
2548         struct nwrap_entlist *el;
2549
2550         if (ed == NULL) {
2551                 NWRAP_LOG(NWRAP_LOG_ERROR,
2552                           "entry is NULL, can't create list item");
2553                 return NULL;
2554         }
2555
2556         el = (struct nwrap_entlist *)malloc(sizeof(struct nwrap_entlist));
2557         if (el == NULL) {
2558                 NWRAP_LOG(NWRAP_LOG_ERROR, "malloc failed");
2559                 return NULL;
2560         }
2561
2562         el->next = NULL;
2563         el->ed = ed;
2564
2565         return el;
2566 }
2567
2568 static bool nwrap_add_ai(char *const ip_addr, struct nwrap_entdata *const ed)
2569 {
2570         ENTRY e;
2571         ENTRY *p;
2572         struct nwrap_entlist *el;
2573
2574         if (ip_addr == NULL) {
2575                 NWRAP_LOG(NWRAP_LOG_ERROR, "ip_addr NULL - can't add");
2576                 return false;
2577         }
2578
2579         el = nwrap_entlist_init(ed);
2580         if (el == NULL) {
2581                 return false;
2582         }
2583
2584         e.key = ip_addr;
2585         e.data = el;
2586
2587         p = hsearch(e, ENTER);
2588         if (p == NULL) {
2589                 NWRAP_LOG(NWRAP_LOG_ERROR, "Hash table is full");
2590                 return false;
2591         }
2592
2593         return true;
2594 }
2595
2596
2597 static bool nwrap_add_hname_add_new(char *const h_name,
2598                                     struct nwrap_entdata *const ed)
2599 {
2600         ENTRY e;
2601         ENTRY *p;
2602         struct nwrap_entlist *el;
2603
2604         el = nwrap_entlist_init(ed);
2605         if (el == NULL) {
2606                 return false;
2607         }
2608
2609         e.key = h_name;
2610         e.data = (void *)el;
2611
2612         p = hsearch(e, ENTER);
2613         if (p == NULL) {
2614                 NWRAP_LOG(NWRAP_LOG_ERROR, "Hash table is full!");
2615                 return false;
2616         }
2617
2618         return true;
2619 }
2620
2621 static bool nwrap_add_hname_add_to_existing(struct nwrap_entdata *const ed,
2622                                             struct nwrap_entlist *const el)
2623 {
2624         struct nwrap_entlist *cursor;
2625         struct nwrap_entlist *el_new;
2626
2627         el_new = nwrap_entlist_init(ed);
2628         if (el_new == NULL) {
2629                 return false;
2630         }
2631
2632         for (cursor = el; cursor->next != NULL; cursor = cursor->next)
2633         {
2634                 if (cursor->ed == ed) {
2635                         free(el_new);
2636                         return false;
2637                 }
2638         }
2639
2640         if (cursor->ed == ed) {
2641                 free(el_new);
2642                 return false;
2643         }
2644
2645         cursor->next = el_new;
2646         return true;
2647 }
2648
2649 static bool nwrap_add_hname_alias(char *const h_name_a,
2650                                   struct nwrap_entdata *const ed)
2651 {
2652         ENTRY e;
2653         ENTRY *p;
2654
2655         assert(ed != NULL);
2656         assert(h_name_a != NULL);
2657
2658         e.key = h_name_a;
2659         e.data = NULL;
2660         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching name: %s", e.key);
2661         p = hsearch(e, FIND);
2662         if (p == NULL) {
2663                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found. Adding...", h_name_a);
2664                 nwrap_add_hname_add_new(h_name_a, ed);
2665         } else {
2666                 struct nwrap_entlist *el = (struct nwrap_entlist *)p->data;
2667
2668                 assert(p->data != NULL);
2669                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s found. Add record to list.", h_name_a);
2670                 nwrap_add_hname_add_to_existing(ed, el);
2671         }
2672
2673         return true;
2674 }
2675
2676 static bool nwrap_add_hname(struct nwrap_entdata *const ed)
2677 {
2678         char *const h_name = (char *const)(ed->ht.h_name);
2679         ENTRY e;
2680         ENTRY *p;
2681         unsigned i;
2682
2683         assert(ed != NULL);
2684         assert(h_name != NULL);
2685
2686         e.key = h_name;
2687         e.data = NULL;
2688         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching name: %s", e.key);
2689         p = hsearch(e, FIND);
2690         if (p == NULL) {
2691                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found. Adding...", h_name);
2692                 nwrap_add_hname_add_new(h_name, ed);
2693         } else {
2694                 struct nwrap_entlist *el = (struct nwrap_entlist *)p->data;
2695
2696                 assert(p->data != NULL);
2697                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s found. Add record to list.", h_name);
2698                 nwrap_add_hname_add_to_existing(ed, el);
2699         }
2700
2701         if (ed->ht.h_aliases == NULL) {
2702                 return true;
2703         }
2704
2705         /* Itemize aliases */
2706         for (i = 0; ed->ht.h_aliases[i] != NULL; ++i) {
2707                 char *h_name_alias;
2708
2709                 h_name_alias = ed->ht.h_aliases[i];
2710                 assert(h_name_alias != NULL);
2711
2712                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Add alias: %s", h_name_alias);
2713
2714                 if (!nwrap_add_hname_alias(h_name_alias, ed)) {
2715                         NWRAP_LOG(NWRAP_LOG_DEBUG,
2716                                   "Unable to add alias: %s", h_name_alias);
2717                 }
2718         }
2719
2720         return true;
2721 }
2722
2723 static bool nwrap_he_parse_line(struct nwrap_cache *nwrap, char *line)
2724 {
2725         struct nwrap_he *nwrap_he = (struct nwrap_he *)nwrap->private_data;
2726         bool do_aliases = true;
2727         ssize_t aliases_count = 0;
2728         char *p;
2729         char *i;
2730         char *n;
2731
2732         char *ip;
2733
2734         struct nwrap_entdata *ed = (struct nwrap_entdata *)
2735                                    malloc(sizeof(struct nwrap_entdata));
2736         if (ed == NULL) {
2737                 NWRAP_LOG(NWRAP_LOG_ERROR,
2738                           "Unable to allocate memory for nwrap_entdata");
2739                 return false;
2740         }
2741         ZERO_STRUCTP(ed);
2742
2743         i = line;
2744
2745         /*
2746          * IP
2747          */
2748
2749         /* Walk to first char */
2750         for (p = i; *p != '.' && *p != ':' && !isxdigit((int) *p); p++) {
2751                 if (*p == '\0') {
2752                         NWRAP_LOG(NWRAP_LOG_ERROR,
2753                                   "Invalid line[%s]: '%s'",
2754                                   line, i);
2755                         free(ed);
2756                         return false;
2757                 }
2758         }
2759
2760         for (i = p; !isspace((int)*p); p++) {
2761                 if (*p == '\0') {
2762                         NWRAP_LOG(NWRAP_LOG_ERROR,
2763                                   "Invalid line[%s]: '%s'",
2764                                   line, i);
2765                         free(ed);
2766                         return false;
2767                 }
2768         }
2769
2770         *p = '\0';
2771
2772         if (inet_pton(AF_INET, i, ed->addr.host_addr)) {
2773                 ed->ht.h_addrtype = AF_INET;
2774                 ed->ht.h_length = 4;
2775 #ifdef HAVE_IPV6
2776         } else if (inet_pton(AF_INET6, i, ed->addr.host_addr)) {
2777                 ed->ht.h_addrtype = AF_INET6;
2778                 ed->ht.h_length = 16;
2779 #endif
2780         } else {
2781                 NWRAP_LOG(NWRAP_LOG_ERROR,
2782                           "Invalid line[%s]: '%s'",
2783                           line, i);
2784
2785                 free(ed);
2786                 return false;
2787         }
2788         ip = i;
2789
2790         nwrap_vector_add_item(&(ed->nwrap_addrdata),
2791                               (void *const)ed->addr.host_addr);
2792         ed->ht.h_addr_list = nwrap_vector_head(&ed->nwrap_addrdata);
2793
2794         p++;
2795
2796         /*
2797          * FQDN
2798          */
2799
2800         /* Walk to first char */
2801         for (n = p; *p != '_' && !isalnum((int) *p); p++) {
2802                 if (*p == '\0') {
2803                         NWRAP_LOG(NWRAP_LOG_ERROR,
2804                                   "Invalid line[%s]: '%s'",
2805                                   line, n);
2806
2807                         free(ed);
2808                         return false;
2809                 }
2810         }
2811
2812         for (n = p; !isspace((int)*p); p++) {
2813                 if (*p == '\0') {
2814                         do_aliases = false;
2815                         break;
2816                 }
2817         }
2818
2819         *p = '\0';
2820
2821         /* Convert to lowercase. This operate on same memory region */
2822         str_tolower(n, n);
2823         ed->ht.h_name = n;
2824
2825         /* glib's getent always dereferences he->h_aliases */
2826         ed->ht.h_aliases = malloc(sizeof(char *));
2827         if (ed->ht.h_aliases == NULL) {
2828                 free(ed);
2829                 return false;
2830         }
2831         ed->ht.h_aliases[0] = NULL;
2832
2833         /*
2834          * Aliases
2835          */
2836         while (do_aliases) {
2837                 char **aliases;
2838                 char *a;
2839
2840                 p++;
2841
2842                 /* Walk to first char */
2843                 for (a = p; *p != '_' && !isalnum((int) *p); p++) {
2844                         if (*p == '\0') {
2845                                 do_aliases = false;
2846                                 break;
2847                         }
2848                 }
2849                 /* Only trailing spaces are left */
2850                 if (!do_aliases) {
2851                         break;
2852                 }
2853
2854                 for (a = p; !isspace((int)*p); p++) {
2855                         if (*p == '\0') {
2856                                 do_aliases = false;
2857                                 break;
2858                         }
2859                 }
2860
2861                 *p = '\0';
2862
2863                 aliases = realloc(ed->ht.h_aliases, sizeof(char *) * (aliases_count + 2));
2864                 if (aliases == NULL) {
2865                         free(ed);
2866                         return false;
2867                 }
2868                 ed->ht.h_aliases = aliases;
2869
2870                 str_tolower(a, a);
2871                 aliases[aliases_count] = a;
2872                 aliases[aliases_count + 1] = NULL;
2873
2874                 aliases_count += 1;
2875         }
2876
2877         nwrap_vector_add_item(&(nwrap_he->entdata), (void *const)ed);
2878
2879         ed->aliases_count = aliases_count;
2880         /* Inventarize item */
2881         nwrap_add_hname(ed);
2882         nwrap_add_ai(ip, ed);
2883
2884         nwrap_he->num++;
2885         return true;
2886 }
2887
2888 static void nwrap_he_unload(struct nwrap_cache *nwrap)
2889 {
2890         struct nwrap_he *nwrap_he =
2891                 (struct nwrap_he *)nwrap->private_data;
2892         struct nwrap_entdata *ed;
2893         size_t i;
2894
2895         nwrap_vector_foreach (ed, nwrap_he->entdata, i)
2896         {
2897                 SAFE_FREE(ed->nwrap_addrdata.items);
2898                 SAFE_FREE(ed->ht.h_aliases);
2899                 SAFE_FREE(ed);
2900         }
2901         SAFE_FREE(nwrap_he->entdata.items);
2902         nwrap_he->entdata.count = nwrap_he->entdata.capacity = 0;
2903
2904         nwrap_he->num = 0;
2905         nwrap_he->idx = 0;
2906 }
2907
2908
2909 /* user functions */
2910 static struct passwd *nwrap_files_getpwnam(struct nwrap_backend *b,
2911                                            const char *name)
2912 {
2913         int i;
2914
2915         (void) b; /* unused */
2916
2917         NWRAP_LOG(NWRAP_LOG_DEBUG, "Lookup user %s in files", name);
2918
2919         nwrap_files_cache_reload(nwrap_pw_global.cache);
2920
2921         for (i=0; i<nwrap_pw_global.num; i++) {
2922                 if (strcmp(nwrap_pw_global.list[i].pw_name, name) == 0) {
2923                         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] found", name);
2924                         return &nwrap_pw_global.list[i];
2925                 }
2926                 NWRAP_LOG(NWRAP_LOG_DEBUG,
2927                           "user[%s] does not match [%s]",
2928                           name,
2929                           nwrap_pw_global.list[i].pw_name);
2930         }
2931
2932         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] not found\n", name);
2933
2934         errno = ENOENT;
2935         return NULL;
2936 }
2937
2938 static int nwrap_files_getpwnam_r(struct nwrap_backend *b,
2939                                   const char *name, struct passwd *pwdst,
2940                                   char *buf, size_t buflen, struct passwd **pwdstp)
2941 {
2942         struct passwd *pw;
2943
2944         pw = nwrap_files_getpwnam(b, name);
2945         if (!pw) {
2946                 if (errno == 0) {
2947                         return ENOENT;
2948                 }
2949                 return errno;
2950         }
2951
2952         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
2953 }
2954
2955 static struct passwd *nwrap_files_getpwuid(struct nwrap_backend *b,
2956                                            uid_t uid)
2957 {
2958         int i;
2959
2960         (void) b; /* unused */
2961
2962         nwrap_files_cache_reload(nwrap_pw_global.cache);
2963
2964         for (i=0; i<nwrap_pw_global.num; i++) {
2965                 if (nwrap_pw_global.list[i].pw_uid == uid) {
2966                         NWRAP_LOG(NWRAP_LOG_DEBUG, "uid[%u] found", uid);
2967                         return &nwrap_pw_global.list[i];
2968                 }
2969                 NWRAP_LOG(NWRAP_LOG_DEBUG,
2970                           "uid[%u] does not match [%u]",
2971                           uid,
2972                           nwrap_pw_global.list[i].pw_uid);
2973         }
2974
2975         NWRAP_LOG(NWRAP_LOG_DEBUG, "uid[%u] not found\n", uid);
2976
2977         errno = ENOENT;
2978         return NULL;
2979 }
2980
2981 static int nwrap_files_getpwuid_r(struct nwrap_backend *b,
2982                                   uid_t uid, struct passwd *pwdst,
2983                                   char *buf, size_t buflen, struct passwd **pwdstp)
2984 {
2985         struct passwd *pw;
2986
2987         pw = nwrap_files_getpwuid(b, uid);
2988         if (!pw) {
2989                 if (errno == 0) {
2990                         return ENOENT;
2991                 }
2992                 return errno;
2993         }
2994
2995         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
2996 }
2997
2998 /* user enum functions */
2999 static void nwrap_files_setpwent(struct nwrap_backend *b)
3000 {
3001         (void) b; /* unused */
3002
3003         nwrap_pw_global.idx = 0;
3004 }
3005
3006 static struct passwd *nwrap_files_getpwent(struct nwrap_backend *b)
3007 {
3008         struct passwd *pw;
3009
3010         (void) b; /* unused */
3011
3012         if (nwrap_pw_global.idx == 0) {
3013                 nwrap_files_cache_reload(nwrap_pw_global.cache);
3014         }
3015
3016         if (nwrap_pw_global.idx >= nwrap_pw_global.num) {
3017                 errno = ENOENT;
3018                 return NULL;
3019         }
3020
3021         pw = &nwrap_pw_global.list[nwrap_pw_global.idx++];
3022
3023         NWRAP_LOG(NWRAP_LOG_DEBUG,
3024                   "return user[%s] uid[%u]",
3025                   pw->pw_name, pw->pw_uid);
3026
3027         return pw;
3028 }
3029
3030 static int nwrap_files_getpwent_r(struct nwrap_backend *b,
3031                                   struct passwd *pwdst, char *buf,
3032                                   size_t buflen, struct passwd **pwdstp)
3033 {
3034         struct passwd *pw;
3035
3036         pw = nwrap_files_getpwent(b);
3037         if (!pw) {
3038                 if (errno == 0) {
3039                         return ENOENT;
3040                 }
3041                 return errno;
3042         }
3043
3044         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
3045 }
3046
3047 static void nwrap_files_endpwent(struct nwrap_backend *b)
3048 {
3049         (void) b; /* unused */
3050
3051         nwrap_pw_global.idx = 0;
3052 }
3053
3054 /* shadow */
3055
3056 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
3057
3058 #ifdef HAVE_SETSPENT
3059 static void nwrap_files_setspent(void)
3060 {
3061         nwrap_sp_global.idx = 0;
3062 }
3063
3064 static struct spwd *nwrap_files_getspent(void)
3065 {
3066         struct spwd *sp;
3067
3068         if (nwrap_sp_global.idx == 0) {
3069                 nwrap_files_cache_reload(nwrap_sp_global.cache);
3070         }
3071
3072         if (nwrap_sp_global.idx >= nwrap_sp_global.num) {
3073                 errno = ENOENT;
3074                 return NULL;
3075         }
3076
3077         sp = &nwrap_sp_global.list[nwrap_sp_global.idx++];
3078
3079         NWRAP_LOG(NWRAP_LOG_DEBUG,
3080                   "return user[%s]",
3081                   sp->sp_namp);
3082
3083         return sp;
3084 }
3085
3086 static void nwrap_files_endspent(void)
3087 {
3088         nwrap_sp_global.idx = 0;
3089 }
3090 #endif /* HAVE_SETSPENT */
3091
3092 static struct spwd *nwrap_files_getspnam(const char *name)
3093 {
3094         int i;
3095
3096         NWRAP_LOG(NWRAP_LOG_DEBUG, "Lookup user %s in files", name);
3097
3098         nwrap_files_cache_reload(nwrap_sp_global.cache);
3099
3100         for (i=0; i<nwrap_sp_global.num; i++) {
3101                 if (strcmp(nwrap_sp_global.list[i].sp_namp, name) == 0) {
3102                         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] found", name);
3103                         return &nwrap_sp_global.list[i];
3104                 }
3105                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3106                           "user[%s] does not match [%s]",
3107                           name,
3108                           nwrap_sp_global.list[i].sp_namp);
3109         }
3110
3111         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] not found\n", name);
3112
3113         errno = ENOENT;
3114         return NULL;
3115 }
3116 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
3117
3118 /* misc functions */
3119 static int nwrap_files_initgroups(struct nwrap_backend *b,
3120                                   const char *user,
3121                                   gid_t group)
3122 {
3123         struct group *grp;
3124         gid_t *groups;
3125         int size = 1;
3126         int rc;
3127
3128         groups = (gid_t *)malloc(size * sizeof(gid_t));
3129         if (groups == NULL) {
3130                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
3131                 errno = ENOMEM;
3132                 return -1;
3133         }
3134         groups[0] = group;
3135
3136         nwrap_files_setgrent(b);
3137         while ((grp = nwrap_files_getgrent(b)) != NULL) {
3138                 int i = 0;
3139
3140                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3141                           "Inspecting %s for group membership",
3142                           grp->gr_name);
3143
3144                 for (i=0; grp->gr_mem && grp->gr_mem[i] != NULL; i++) {
3145                         if (group != grp->gr_gid &&
3146                             (strcmp(user, grp->gr_mem[i]) == 0)) {
3147                                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3148                                           "%s is member of %s",
3149                                           user,
3150                                           grp->gr_name);
3151
3152                                 groups = (gid_t *)realloc(groups,
3153                                                           (size + 1) * sizeof(gid_t));
3154                                 if (groups == NULL) {
3155                                         NWRAP_LOG(NWRAP_LOG_ERROR,
3156                                                   "Out of memory");
3157                                         errno = ENOMEM;
3158                                         return -1;
3159                                 }
3160
3161                                 groups[size] = grp->gr_gid;
3162                                 size++;
3163                         }
3164                 }
3165         }
3166
3167         nwrap_files_endgrent(b);
3168
3169         NWRAP_LOG(NWRAP_LOG_DEBUG,
3170                   "%s is member of %d groups",
3171                   user, size);
3172
3173         /* This really only works if uid_wrapper is loaded */
3174         rc = setgroups(size, groups);
3175
3176         free(groups);
3177
3178         return rc;
3179 }
3180
3181 /* group functions */
3182 static struct group *nwrap_files_getgrnam(struct nwrap_backend *b,
3183                                           const char *name)
3184 {
3185         int i;
3186
3187         (void) b; /* unused */
3188
3189         nwrap_files_cache_reload(nwrap_gr_global.cache);
3190
3191         for (i=0; i<nwrap_gr_global.num; i++) {
3192                 if (strcmp(nwrap_gr_global.list[i].gr_name, name) == 0) {
3193                         NWRAP_LOG(NWRAP_LOG_DEBUG, "group[%s] found", name);
3194                         return &nwrap_gr_global.list[i];
3195                 }
3196                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3197                           "group[%s] does not match [%s]",
3198                           name,
3199                           nwrap_gr_global.list[i].gr_name);
3200         }
3201
3202         NWRAP_LOG(NWRAP_LOG_DEBUG, "group[%s] not found", name);
3203
3204         errno = ENOENT;
3205         return NULL;
3206 }
3207
3208 static int nwrap_files_getgrnam_r(struct nwrap_backend *b,
3209                                   const char *name, struct group *grdst,
3210                                   char *buf, size_t buflen, struct group **grdstp)
3211 {
3212         struct group *gr;
3213
3214         gr = nwrap_files_getgrnam(b, name);
3215         if (!gr) {
3216                 if (errno == 0) {
3217                         return ENOENT;
3218                 }
3219                 return errno;
3220         }
3221
3222         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3223 }
3224
3225 static struct group *nwrap_files_getgrgid(struct nwrap_backend *b,
3226                                           gid_t gid)
3227 {
3228         int i;
3229
3230         (void) b; /* unused */
3231
3232         nwrap_files_cache_reload(nwrap_gr_global.cache);
3233
3234         for (i=0; i<nwrap_gr_global.num; i++) {
3235                 if (nwrap_gr_global.list[i].gr_gid == gid) {
3236                         NWRAP_LOG(NWRAP_LOG_DEBUG, "gid[%u] found", gid);
3237                         return &nwrap_gr_global.list[i];
3238                 }
3239                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3240                           "gid[%u] does not match [%u]",
3241                           gid,
3242                           nwrap_gr_global.list[i].gr_gid);
3243         }
3244
3245         NWRAP_LOG(NWRAP_LOG_DEBUG, "gid[%u] not found", gid);
3246
3247         errno = ENOENT;
3248         return NULL;
3249 }
3250
3251 static int nwrap_files_getgrgid_r(struct nwrap_backend *b,
3252                                   gid_t gid, struct group *grdst,
3253                                   char *buf, size_t buflen, struct group **grdstp)
3254 {
3255         struct group *gr;
3256
3257         gr = nwrap_files_getgrgid(b, gid);
3258         if (!gr) {
3259                 if (errno == 0) {
3260                         return ENOENT;
3261                 }
3262                 return errno;
3263         }
3264
3265         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3266 }
3267
3268 /* group enum functions */
3269 static void nwrap_files_setgrent(struct nwrap_backend *b)
3270 {
3271         (void) b; /* unused */
3272
3273         nwrap_gr_global.idx = 0;
3274 }
3275
3276 static struct group *nwrap_files_getgrent(struct nwrap_backend *b)
3277 {
3278         struct group *gr;
3279
3280         (void) b; /* unused */
3281
3282         if (nwrap_gr_global.idx == 0) {
3283                 nwrap_files_cache_reload(nwrap_gr_global.cache);
3284         }
3285
3286         if (nwrap_gr_global.idx >= nwrap_gr_global.num) {
3287                 errno = ENOENT;
3288                 return NULL;
3289         }
3290
3291         gr = &nwrap_gr_global.list[nwrap_gr_global.idx++];
3292
3293         NWRAP_LOG(NWRAP_LOG_DEBUG,
3294                   "return group[%s] gid[%u]",
3295                   gr->gr_name, gr->gr_gid);
3296
3297         return gr;
3298 }
3299
3300 static int nwrap_files_getgrent_r(struct nwrap_backend *b,
3301                                   struct group *grdst, char *buf,
3302                                   size_t buflen, struct group **grdstp)
3303 {
3304         struct group *gr;
3305
3306         gr = nwrap_files_getgrent(b);
3307         if (!gr) {
3308                 if (errno == 0) {
3309                         return ENOENT;
3310                 }
3311                 return errno;
3312         }
3313
3314         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3315 }
3316
3317 static void nwrap_files_endgrent(struct nwrap_backend *b)
3318 {
3319         (void) b; /* unused */
3320
3321         nwrap_gr_global.idx = 0;
3322 }
3323
3324 /* hosts functions */
3325 static int nwrap_files_gethostbyname(const char *name, int af,
3326                                      struct hostent *result,
3327                                      struct nwrap_vector *addr_list)
3328 {
3329         struct nwrap_entlist *el;
3330         struct hostent *he;
3331         char *h_name_lower;
3332         ENTRY e;
3333         ENTRY *e_p;
3334         char canon_name[DNS_NAME_MAX] = { 0 };
3335         size_t name_len;
3336         bool he_found = false;
3337
3338         nwrap_files_cache_reload(nwrap_he_global.cache);
3339
3340         name_len = strlen(name);
3341         if (name_len < sizeof(canon_name) && name[name_len - 1] == '.') {
3342                 strncpy(canon_name, name, name_len - 1);
3343                 name = canon_name;
3344         }
3345
3346         if (!str_tolower_copy(&h_name_lower, name)) {
3347                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3348                           "Out of memory while converting to lower case");
3349                 goto no_ent;
3350         }
3351
3352         /* Look at hash table for element */
3353         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching for name: %s", h_name_lower);
3354         e.key = h_name_lower;
3355         e.data = NULL;
3356         e_p = hsearch(e, FIND);
3357         if (e_p == NULL) {
3358                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found.", h_name_lower);
3359                 SAFE_FREE(h_name_lower);
3360                 goto no_ent;
3361         }
3362         SAFE_FREE(h_name_lower);
3363
3364         /* Always cleanup vector and results */
3365         if (!nwrap_vector_is_initialized(addr_list)) {
3366                 if (!nwrap_vector_init(addr_list)) {
3367                         NWRAP_LOG(NWRAP_LOG_DEBUG,
3368                                   "Unable to initialize memory for addr_list vector");
3369                         goto no_ent;
3370                 }
3371         } else {
3372                 /* When vector is initialized data are valid no more.
3373                  * Quick way how to free vector is: */
3374                 addr_list->count = 0;
3375         }
3376
3377         /* Iterate through results */
3378         for (el = (struct nwrap_entlist *)e_p->data; el != NULL; el = el->next)
3379         {
3380                 he = &(el->ed->ht);
3381
3382                 /* Filter by address familiy if provided */
3383                 if (af != AF_UNSPEC && he->h_addrtype != af) {
3384                         continue;
3385                 }
3386
3387                 /*
3388                  * GLIBC HACK?
3389                  * glibc doesn't return ipv6 addresses when AF_UNSPEC is used
3390                  */
3391                 if (af == AF_UNSPEC && he->h_addrtype != AF_INET) {
3392                         continue;
3393                 }
3394
3395                 if (!he_found) {
3396                         memcpy(result, he, sizeof(struct hostent));
3397                         NWRAP_LOG(NWRAP_LOG_DEBUG,
3398                                   "Name found. Returning record for %s",
3399                                   he->h_name);
3400                         he_found = true;
3401                 }
3402                 nwrap_vector_merge(addr_list, &el->ed->nwrap_addrdata);
3403                 result->h_addr_list = nwrap_vector_head(addr_list);
3404         }
3405
3406         if (he_found) {
3407                 return 0;
3408         }
3409         NWRAP_LOG(NWRAP_LOG_DEBUG,
3410                   "Name found in database. No records matches type.");
3411
3412 no_ent:
3413         errno = ENOENT;
3414         return -1;
3415 }
3416
3417 #ifdef HAVE_GETHOSTBYNAME_R
3418 static int nwrap_gethostbyname_r(const char *name,
3419                                  struct hostent *ret,
3420                                  char *buf, size_t buflen,
3421                                  struct hostent **result, int *h_errnop)
3422 {
3423         struct nwrap_vector *addr_list = malloc(sizeof(struct nwrap_vector));
3424         int rc;
3425
3426         if (addr_list == NULL) {
3427                 NWRAP_LOG(NWRAP_LOG_ERROR,
3428                           "Unable to allocate memory for address list");
3429                 errno = ENOENT;
3430                 return -1;
3431         }
3432
3433         ZERO_STRUCTP(addr_list);
3434
3435         rc = nwrap_files_gethostbyname(name, AF_UNSPEC, ret, addr_list);
3436         if (rc == -1) {
3437                 *h_errnop = h_errno;
3438                 if (addr_list->items != NULL) {
3439                         free(addr_list->items);
3440                 }
3441                 SAFE_FREE(addr_list);
3442                 errno = ENOENT;
3443                 return -1;
3444         }
3445
3446         if (buflen < (addr_list->count * sizeof(void *))) {
3447                 SAFE_FREE(addr_list->items);
3448                 SAFE_FREE(addr_list);
3449                 return ERANGE;
3450         }
3451
3452         /* Copy all to user provided buffer and change
3453          * pointers in returned structure.
3454          * +1 is for ending NULL pointer. */
3455         memcpy(buf, addr_list->items, (addr_list->count + 1) * sizeof(void *));
3456
3457         free(addr_list->items);
3458         free(addr_list);
3459
3460         ret->h_addr_list = (char **)buf;
3461         *result = ret;
3462         return 0;
3463 }
3464
3465 int gethostbyname_r(const char *name,
3466                     struct hostent *ret,
3467                     char *buf, size_t buflen,
3468                     struct hostent **result, int *h_errnop)
3469 {
3470         if (!nss_wrapper_hosts_enabled()) {
3471                 return libc_gethostbyname_r(name,
3472                                             ret,
3473                                             buf,
3474                                             buflen,
3475                                             result,
3476                                             h_errnop);
3477         }
3478
3479         return nwrap_gethostbyname_r(name, ret, buf, buflen, result, h_errnop);
3480 }
3481 #endif
3482
3483 static struct addrinfo *nwrap_files_getaddrinfo(const char *name,
3484                                                 unsigned short port,
3485                                                 const struct addrinfo *hints,
3486                                                 struct addrinfo **ai_tail)
3487 {
3488         struct nwrap_entlist *el;
3489         struct hostent *he;
3490         struct addrinfo *ai = NULL;
3491         struct addrinfo *ai_head = NULL;
3492         struct addrinfo *ai_prev = NULL;
3493         char *h_name_lower;
3494         size_t name_len;
3495         char canon_name[DNS_NAME_MAX] = { 0 };
3496         bool skip_canonname = false;
3497         ENTRY e = { 0 };
3498         ENTRY *e_p = NULL;
3499
3500         nwrap_files_cache_reload(nwrap_he_global.cache);
3501
3502         name_len = strlen(name);
3503         if (name_len < DNS_NAME_MAX && name[name_len - 1] == '.') {
3504                 strncpy(canon_name, name, name_len - 1);
3505                 name = canon_name;
3506         }
3507
3508         if (!str_tolower_copy(&h_name_lower, name)) {
3509                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3510                           "Out of memory while converting to lower case");
3511                 return NULL;
3512         }
3513
3514         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching for name: %s", h_name_lower);
3515         e.key = h_name_lower;
3516         e.data = NULL;
3517         e_p = hsearch(e, FIND);
3518         if (e_p == NULL) {
3519                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found.", h_name_lower);
3520                 SAFE_FREE(h_name_lower);
3521                 errno = ENOENT;
3522                 return NULL;
3523         }
3524         NWRAP_LOG(NWRAP_LOG_DEBUG, "Name: %s found.", h_name_lower);
3525         SAFE_FREE(h_name_lower);
3526
3527         for (el = (struct nwrap_entlist *)e_p->data; el != NULL; el = el->next)
3528         {
3529                 int rc;
3530
3531                 he = &(el->ed->ht);
3532
3533                 if (hints->ai_family != AF_UNSPEC &&
3534                     he->h_addrtype != hints->ai_family) {
3535                         continue;
3536                 }
3537
3538                 /* Function allocates memory and returns it in ai. */
3539                 rc = nwrap_convert_he_ai(he,
3540                                          port,
3541                                          hints,
3542                                          &ai,
3543                                          skip_canonname);
3544                 if (rc != 0) {
3545                         /* FIXME: Investigate if this is nice to do... */
3546                         NWRAP_LOG(NWRAP_LOG_ERROR,
3547                                   "Error in converting he to ai! Skipping.");
3548                         continue;
3549                 }
3550                 skip_canonname = true;
3551
3552                 if (ai_head == NULL) {
3553                         ai_head = ai;
3554                 }
3555                 if (ai_prev != NULL) {
3556                         ai_prev->ai_next = ai;
3557                 }
3558                 ai_prev = ai;
3559         }
3560
3561         *ai_tail = ai;
3562         return ai_head;
3563 }
3564
3565 static struct hostent *nwrap_files_gethostbyaddr(const void *addr,
3566                                                  socklen_t len, int type)
3567 {
3568         struct hostent *he;
3569         char ip[NWRAP_INET_ADDRSTRLEN] = {0};
3570         struct nwrap_entdata *ed;
3571         const char *a;
3572         size_t i;
3573
3574         (void) len; /* unused */
3575
3576         nwrap_files_cache_reload(nwrap_he_global.cache);
3577
3578         a = inet_ntop(type, addr, ip, sizeof(ip));
3579         if (a == NULL) {
3580                 errno = EINVAL;
3581                 return NULL;
3582         }
3583
3584         nwrap_vector_foreach(ed, nwrap_he_global.entdata, i)
3585         {
3586                 he = &(ed->ht);
3587                 if (he->h_addrtype != type) {
3588                         continue;
3589                 }
3590
3591                 if (memcmp(addr, he->h_addr_list[0], he->h_length) == 0) {
3592                         return he;
3593                 }
3594         }
3595
3596         errno = ENOENT;
3597         return NULL;
3598 }
3599
3600 #ifdef HAVE_GETHOSTBYADDR_R
3601 static int nwrap_gethostbyaddr_r(const void *addr, socklen_t len, int type,
3602                                  struct hostent *ret,
3603                                  char *buf, size_t buflen,
3604                                  struct hostent **result, int *h_errnop)
3605 {
3606         *result = nwrap_files_gethostbyaddr(addr, len, type);
3607         if (*result != NULL) {
3608                 memset(buf, '\0', buflen);
3609                 *ret = **result;
3610                 return 0;
3611         } else {
3612                 *h_errnop = h_errno;
3613                 return -1;
3614         }
3615 }
3616
3617 int gethostbyaddr_r(const void *addr, socklen_t len, int type,
3618                     struct hostent *ret,
3619                     char *buf, size_t buflen,
3620                     struct hostent **result, int *h_errnop)
3621 {
3622         if (!nss_wrapper_hosts_enabled()) {
3623                 return libc_gethostbyaddr_r(addr,
3624                                             len,
3625                                             type,
3626                                             ret,
3627                                             buf,
3628                                             buflen,
3629                                             result,
3630                                             h_errnop);
3631         }
3632
3633         return nwrap_gethostbyaddr_r(addr, len, type, ret, buf, buflen, result, h_errnop);
3634 }
3635 #endif
3636
3637 /* hosts enum functions */
3638 static void nwrap_files_sethostent(void)
3639 {
3640         nwrap_he_global.idx = 0;
3641 }
3642
3643 static struct hostent *nwrap_files_gethostent(void)
3644 {
3645         struct hostent *he;
3646
3647         if (nwrap_he_global.idx == 0) {
3648                 nwrap_files_cache_reload(nwrap_he_global.cache);
3649         }
3650
3651         if (nwrap_he_global.idx >= nwrap_he_global.num) {
3652                 errno = ENOENT;
3653                 return NULL;
3654         }
3655
3656         he = &((struct nwrap_entdata *)nwrap_he_global.entdata.items[nwrap_he_global.idx++])->ht;
3657
3658         NWRAP_LOG(NWRAP_LOG_DEBUG, "return hosts[%s]", he->h_name);
3659
3660         return he;
3661 }
3662
3663 static void nwrap_files_endhostent(void)
3664 {
3665         nwrap_he_global.idx = 0;
3666 }
3667
3668 /*
3669  * module backend
3670  */
3671
3672
3673 static struct passwd *nwrap_module_getpwnam(struct nwrap_backend *b,
3674                                             const char *name)
3675 {
3676         static struct passwd pwd;
3677         static char buf[1000];
3678         NSS_STATUS status;
3679
3680         if (!b->fns->_nss_getpwnam_r) {
3681                 return NULL;
3682         }
3683
3684         status = b->fns->_nss_getpwnam_r(name, &pwd, buf, sizeof(buf), &errno);
3685         if (status == NSS_STATUS_NOTFOUND) {
3686                 return NULL;
3687         }
3688         if (status != NSS_STATUS_SUCCESS) {
3689                 return NULL;
3690         }
3691
3692         return &pwd;
3693 }
3694
3695 static int nwrap_module_getpwnam_r(struct nwrap_backend *b,
3696                                    const char *name, struct passwd *pwdst,
3697                                    char *buf, size_t buflen, struct passwd **pwdstp)
3698 {
3699         int ret;
3700
3701         (void) b; /* unused */
3702         (void) pwdst; /* unused */
3703         (void) pwdstp; /* unused */
3704
3705         if (!b->fns->_nss_getpwnam_r) {
3706                 return NSS_STATUS_NOTFOUND;
3707         }
3708
3709         ret = b->fns->_nss_getpwnam_r(name, pwdst, buf, buflen, &errno);
3710         switch (ret) {
3711         case NSS_STATUS_SUCCESS:
3712                 return 0;
3713         case NSS_STATUS_NOTFOUND:
3714                 if (errno != 0) {
3715                         return errno;
3716                 }
3717                 return ENOENT;
3718         case NSS_STATUS_TRYAGAIN:
3719                 if (errno != 0) {
3720                         return errno;
3721                 }
3722                 return ERANGE;
3723         default:
3724                 if (errno != 0) {
3725                         return errno;
3726                 }
3727                 return ret;
3728         }
3729 }
3730
3731 static struct passwd *nwrap_module_getpwuid(struct nwrap_backend *b,
3732                                             uid_t uid)
3733 {
3734         static struct passwd pwd;
3735         static char buf[1000];
3736         NSS_STATUS status;
3737
3738         if (!b->fns->_nss_getpwuid_r) {
3739                 return NULL;
3740         }
3741
3742         status = b->fns->_nss_getpwuid_r(uid, &pwd, buf, sizeof(buf), &errno);
3743         if (status == NSS_STATUS_NOTFOUND) {
3744                 return NULL;
3745         }
3746         if (status != NSS_STATUS_SUCCESS) {
3747                 return NULL;
3748         }
3749         return &pwd;
3750 }
3751
3752 static int nwrap_module_getpwuid_r(struct nwrap_backend *b,
3753                                    uid_t uid, struct passwd *pwdst,
3754                                    char *buf, size_t buflen, struct passwd **pwdstp)
3755 {
3756         int ret;
3757
3758         (void) pwdstp; /* unused */
3759
3760         if (!b->fns->_nss_getpwuid_r) {
3761                 return ENOENT;
3762         }
3763
3764         ret = b->fns->_nss_getpwuid_r(uid, pwdst, buf, buflen, &errno);
3765         switch (ret) {
3766         case NSS_STATUS_SUCCESS:
3767                 return 0;
3768         case NSS_STATUS_NOTFOUND:
3769                 if (errno != 0) {
3770                         return errno;
3771                 }
3772                 return ENOENT;
3773         case NSS_STATUS_TRYAGAIN:
3774                 if (errno != 0) {
3775                         return errno;
3776                 }
3777                 return ERANGE;
3778         default:
3779                 if (errno != 0) {
3780                         return errno;
3781                 }
3782                 return ret;
3783         }
3784 }
3785
3786 static void nwrap_module_setpwent(struct nwrap_backend *b)
3787 {
3788         if (!b->fns->_nss_setpwent) {
3789                 return;
3790         }
3791
3792         b->fns->_nss_setpwent();
3793 }
3794
3795 static struct passwd *nwrap_module_getpwent(struct nwrap_backend *b)
3796 {
3797         static struct passwd pwd;
3798         static char buf[1000];
3799         NSS_STATUS status;
3800
3801         if (!b->fns->_nss_getpwent_r) {
3802                 return NULL;
3803         }
3804
3805         status = b->fns->_nss_getpwent_r(&pwd, buf, sizeof(buf), &errno);
3806         if (status == NSS_STATUS_NOTFOUND) {
3807                 return NULL;
3808         }
3809         if (status != NSS_STATUS_SUCCESS) {
3810                 return NULL;
3811         }
3812         return &pwd;
3813 }
3814
3815 static int nwrap_module_getpwent_r(struct nwrap_backend *b,
3816                                    struct passwd *pwdst, char *buf,
3817                                    size_t buflen, struct passwd **pwdstp)
3818 {
3819         int ret;
3820
3821         (void) pwdstp; /* unused */
3822
3823         if (!b->fns->_nss_getpwent_r) {
3824                 return ENOENT;
3825         }
3826
3827         ret = b->fns->_nss_getpwent_r(pwdst, buf, buflen, &errno);
3828         switch (ret) {
3829         case NSS_STATUS_SUCCESS:
3830                 return 0;
3831         case NSS_STATUS_NOTFOUND:
3832                 if (errno != 0) {
3833                         return errno;
3834                 }
3835                 return ENOENT;
3836         case NSS_STATUS_TRYAGAIN:
3837                 if (errno != 0) {
3838                         return errno;
3839                 }
3840                 return ERANGE;
3841         default:
3842                 if (errno != 0) {
3843                         return errno;
3844                 }
3845                 return ret;
3846         }
3847 }
3848
3849 static void nwrap_module_endpwent(struct nwrap_backend *b)
3850 {
3851         if (!b->fns->_nss_endpwent) {
3852                 return;
3853         }
3854
3855         b->fns->_nss_endpwent();
3856 }
3857
3858 static int nwrap_module_initgroups(struct nwrap_backend *b,
3859                                    const char *user, gid_t group)
3860 {
3861         gid_t *groups;
3862         long int start;
3863         long int size;
3864
3865         if (!b->fns->_nss_initgroups) {
3866                 return NSS_STATUS_UNAVAIL;
3867         }
3868
3869         return b->fns->_nss_initgroups(user, group, &start, &size, &groups, 0, &errno);
3870 }
3871
3872 static struct group *nwrap_module_getgrnam(struct nwrap_backend *b,
3873                                            const char *name)
3874 {
3875         static struct group grp;
3876         static char *buf;
3877         static int buflen = 1000;
3878         NSS_STATUS status;
3879
3880         if (!b->fns->_nss_getgrnam_r) {
3881                 return NULL;
3882         }
3883
3884         if (!buf) {
3885                 buf = (char *)malloc(buflen);
3886         }
3887 again:
3888         status = b->fns->_nss_getgrnam_r(name, &grp, buf, buflen, &errno);
3889         if (status == NSS_STATUS_TRYAGAIN) {
3890                 buflen *= 2;
3891                 buf = (char *)realloc(buf, buflen);
3892                 if (!buf) {
3893                         return NULL;
3894                 }
3895                 goto again;
3896         }
3897         if (status == NSS_STATUS_NOTFOUND) {
3898                 SAFE_FREE(buf);
3899                 return NULL;
3900         }
3901         if (status != NSS_STATUS_SUCCESS) {
3902                 SAFE_FREE(buf);
3903                 return NULL;
3904         }
3905         return &grp;
3906 }
3907
3908 static int nwrap_module_getgrnam_r(struct nwrap_backend *b,
3909                                    const char *name, struct group *grdst,
3910                                    char *buf, size_t buflen, struct group **grdstp)
3911 {
3912         int ret;
3913
3914         (void) grdstp; /* unused */
3915
3916         if (!b->fns->_nss_getgrnam_r) {
3917                 return ENOENT;
3918         }
3919
3920         ret = b->fns->_nss_getgrnam_r(name, grdst, buf, buflen, &errno);
3921         switch (ret) {
3922         case NSS_STATUS_SUCCESS:
3923                 return 0;
3924         case NSS_STATUS_NOTFOUND:
3925                 if (errno != 0) {
3926                         return errno;
3927                 }
3928                 return ENOENT;
3929         case NSS_STATUS_TRYAGAIN:
3930                 if (errno != 0) {
3931                         return errno;
3932                 }
3933                 return ERANGE;
3934         default:
3935                 if (errno != 0) {
3936                         return errno;
3937                 }
3938                 return ret;
3939         }
3940 }
3941
3942 static struct group *nwrap_module_getgrgid(struct nwrap_backend *b,
3943                                            gid_t gid)
3944 {
3945         static struct group grp;
3946         static char *buf;
3947         static int buflen = 1000;
3948         NSS_STATUS status;
3949
3950         if (!b->fns->_nss_getgrgid_r) {
3951                 return NULL;
3952         }
3953
3954         if (!buf) {
3955                 buf = (char *)malloc(buflen);
3956         }
3957
3958 again:
3959         status = b->fns->_nss_getgrgid_r(gid, &grp, buf, buflen, &errno);
3960         if (status == NSS_STATUS_TRYAGAIN) {
3961                 buflen *= 2;
3962                 buf = (char *)realloc(buf, buflen);
3963                 if (!buf) {
3964                         return NULL;
3965                 }
3966                 goto again;
3967         }
3968         if (status == NSS_STATUS_NOTFOUND) {
3969                 SAFE_FREE(buf);
3970                 return NULL;
3971         }
3972         if (status != NSS_STATUS_SUCCESS) {
3973                 SAFE_FREE(buf);
3974                 return NULL;
3975         }
3976         return &grp;
3977 }
3978
3979 static int nwrap_module_getgrgid_r(struct nwrap_backend *b,
3980                                    gid_t gid, struct group *grdst,
3981                                    char *buf, size_t buflen, struct group **grdstp)
3982 {
3983         int ret;
3984
3985         (void) grdstp; /* unused */
3986
3987         if (!b->fns->_nss_getgrgid_r) {
3988                 return ENOENT;
3989         }
3990
3991         ret = b->fns->_nss_getgrgid_r(gid, grdst, buf, buflen, &errno);
3992         switch (ret) {
3993         case NSS_STATUS_SUCCESS:
3994                 return 0;
3995         case NSS_STATUS_NOTFOUND:
3996                 if (errno != 0) {
3997                         return errno;
3998                 }
3999                 return ENOENT;
4000         case NSS_STATUS_TRYAGAIN:
4001                 if (errno != 0) {
4002                         return errno;
4003                 }
4004                 return ERANGE;
4005         default:
4006                 if (errno != 0) {
4007                         return errno;
4008                 }
4009                 return ret;
4010         }
4011 }
4012
4013 static void nwrap_module_setgrent(struct nwrap_backend *b)
4014 {
4015         if (!b->fns->_nss_setgrent) {
4016                 return;
4017         }
4018
4019         b->fns->_nss_setgrent();
4020 }
4021
4022 static struct group *nwrap_module_getgrent(struct nwrap_backend *b)
4023 {
4024         static struct group grp;
4025         static char *buf;
4026         static int buflen = 1024;
4027         NSS_STATUS status;
4028
4029         if (!b->fns->_nss_getgrent_r) {
4030                 return NULL;
4031         }
4032
4033         if (!buf) {
4034                 buf = (char *)malloc(buflen);
4035         }
4036
4037 again:
4038         status = b->fns->_nss_getgrent_r(&grp, buf, buflen, &errno);
4039         if (status == NSS_STATUS_TRYAGAIN) {
4040                 buflen *= 2;
4041                 buf = (char *)realloc(buf, buflen);
4042                 if (!buf) {
4043                         return NULL;
4044                 }
4045                 goto again;
4046         }
4047         if (status == NSS_STATUS_NOTFOUND) {
4048                 SAFE_FREE(buf);
4049                 return NULL;
4050         }
4051         if (status != NSS_STATUS_SUCCESS) {
4052                 SAFE_FREE(buf);
4053                 return NULL;
4054         }
4055         return &grp;
4056 }
4057
4058 static int nwrap_module_getgrent_r(struct nwrap_backend *b,
4059                                    struct group *grdst, char *buf,
4060                                    size_t buflen, struct group **grdstp)
4061 {
4062         int ret;
4063
4064         (void) grdstp; /* unused */
4065
4066         if (!b->fns->_nss_getgrent_r) {
4067                 return ENOENT;
4068         }
4069
4070         ret = b->fns->_nss_getgrent_r(grdst, buf, buflen, &errno);
4071         switch (ret) {
4072         case NSS_STATUS_SUCCESS:
4073                 return 0;
4074         case NSS_STATUS_NOTFOUND:
4075                 if (errno != 0) {
4076                         return errno;
4077                 }
4078                 return ENOENT;
4079         case NSS_STATUS_TRYAGAIN:
4080                 if (errno != 0) {
4081                         return errno;
4082                 }
4083                 return ERANGE;
4084         default:
4085                 if (errno != 0) {
4086                         return errno;
4087                 }
4088                 return ret;
4089         }
4090 }
4091
4092 static void nwrap_module_endgrent(struct nwrap_backend *b)
4093 {
4094         if (!b->fns->_nss_endgrent) {
4095                 return;
4096         }
4097
4098         b->fns->_nss_endgrent();
4099 }
4100
4101 /****************************************************************************
4102  *   GETPWNAM
4103  ***************************************************************************/
4104
4105 static struct passwd *nwrap_getpwnam(const char *name)
4106 {
4107         int i;
4108         struct passwd *pwd;
4109
4110         for (i=0; i < nwrap_main_global->num_backends; i++) {
4111                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4112                 pwd = b->ops->nw_getpwnam(b, name);
4113                 if (pwd) {
4114                         return pwd;
4115                 }
4116         }
4117
4118         return NULL;
4119 }
4120
4121 struct passwd *getpwnam(const char *name)
4122 {
4123         if (!nss_wrapper_enabled()) {
4124                 return libc_getpwnam(name);
4125         }
4126
4127         return nwrap_getpwnam(name);
4128 }
4129
4130 /****************************************************************************
4131  *   GETPWNAM_R
4132  ***************************************************************************/
4133
4134 static int nwrap_getpwnam_r(const char *name, struct passwd *pwdst,
4135                             char *buf, size_t buflen, struct passwd **pwdstp)
4136 {
4137         int i,ret;
4138
4139         for (i=0; i < nwrap_main_global->num_backends; i++) {
4140                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4141                 ret = b->ops->nw_getpwnam_r(b, name, pwdst, buf, buflen, pwdstp);
4142                 if (ret == ENOENT) {
4143                         continue;
4144                 }
4145                 return ret;
4146         }
4147
4148         return ENOENT;
4149 }
4150
4151 #ifdef HAVE_GETPWNAM_R
4152 # ifdef HAVE_SOLARIS_GETPWNAM_R
4153 int getpwnam_r(const char *name, struct passwd *pwdst,
4154                char *buf, int buflen, struct passwd **pwdstp)
4155 # else /* HAVE_SOLARIS_GETPWNAM_R */
4156 int getpwnam_r(const char *name, struct passwd *pwdst,
4157                char *buf, size_t buflen, struct passwd **pwdstp)
4158 # endif /* HAVE_SOLARIS_GETPWNAM_R */
4159 {
4160         if (!nss_wrapper_enabled()) {
4161                 return libc_getpwnam_r(name, pwdst, buf, buflen, pwdstp);
4162         }
4163
4164         return nwrap_getpwnam_r(name, pwdst, buf, buflen, pwdstp);
4165 }
4166 #endif
4167
4168 /****************************************************************************
4169  *   GETPWUID
4170  ***************************************************************************/
4171
4172 static struct passwd *nwrap_getpwuid(uid_t uid)
4173 {
4174         int i;
4175         struct passwd *pwd;
4176
4177         for (i=0; i < nwrap_main_global->num_backends; i++) {
4178                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4179                 pwd = b->ops->nw_getpwuid(b, uid);
4180                 if (pwd) {
4181                         return pwd;
4182                 }
4183         }
4184
4185         return NULL;
4186 }
4187
4188 struct passwd *getpwuid(uid_t uid)
4189 {
4190         if (!nss_wrapper_enabled()) {
4191                 return libc_getpwuid(uid);
4192         }
4193
4194         return nwrap_getpwuid(uid);
4195 }
4196
4197 /****************************************************************************
4198  *   GETPWUID_R
4199  ***************************************************************************/
4200
4201 static int nwrap_getpwuid_r(uid_t uid, struct passwd *pwdst,
4202                             char *buf, size_t buflen, struct passwd **pwdstp)
4203 {
4204         int i,ret;
4205
4206         for (i=0; i < nwrap_main_global->num_backends; i++) {
4207                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4208                 ret = b->ops->nw_getpwuid_r(b, uid, pwdst, buf, buflen, pwdstp);
4209                 if (ret == ENOENT) {
4210                         continue;
4211                 }
4212                 return ret;
4213         }
4214
4215         return ENOENT;
4216 }
4217
4218 #ifdef HAVE_SOLARIS_GETPWUID_R
4219 int getpwuid_r(uid_t uid, struct passwd *pwdst,
4220                char *buf, int buflen, struct passwd **pwdstp)
4221 #else
4222 int getpwuid_r(uid_t uid, struct passwd *pwdst,
4223                char *buf, size_t buflen, struct passwd **pwdstp)
4224 #endif
4225 {
4226         if (!nss_wrapper_enabled()) {
4227                 return libc_getpwuid_r(uid, pwdst, buf, buflen, pwdstp);
4228         }
4229
4230         return nwrap_getpwuid_r(uid, pwdst, buf, buflen, pwdstp);
4231 }
4232
4233 /****************************************************************************
4234  *   SETPWENT
4235  ***************************************************************************/
4236
4237 static void nwrap_setpwent(void)
4238 {
4239         int i;
4240
4241         for (i=0; i < nwrap_main_global->num_backends; i++) {
4242                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4243                 b->ops->nw_setpwent(b);
4244         }
4245 }
4246
4247 void setpwent(void)
4248 {
4249         if (!nss_wrapper_enabled()) {
4250                 libc_setpwent();
4251                 return;
4252         }
4253
4254         nwrap_setpwent();
4255 }
4256
4257 /****************************************************************************
4258  *   GETPWENT
4259  ***************************************************************************/
4260
4261 static struct passwd *nwrap_getpwent(void)
4262 {
4263         int i;
4264         struct passwd *pwd;
4265
4266         for (i=0; i < nwrap_main_global->num_backends; i++) {
4267                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4268                 pwd = b->ops->nw_getpwent(b);
4269                 if (pwd) {
4270                         return pwd;
4271                 }
4272         }
4273
4274         return NULL;
4275 }
4276
4277 struct passwd *getpwent(void)
4278 {
4279         if (!nss_wrapper_enabled()) {
4280                 return libc_getpwent();
4281         }
4282
4283         return nwrap_getpwent();
4284 }
4285
4286 /****************************************************************************
4287  *   GETPWENT_R
4288  ***************************************************************************/
4289
4290 static int nwrap_getpwent_r(struct passwd *pwdst, char *buf,
4291                             size_t buflen, struct passwd **pwdstp)
4292 {
4293         int i,ret;
4294
4295         for (i=0; i < nwrap_main_global->num_backends; i++) {
4296                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4297                 ret = b->ops->nw_getpwent_r(b, pwdst, buf, buflen, pwdstp);
4298                 if (ret == ENOENT) {
4299                         continue;
4300                 }
4301                 return ret;
4302         }
4303
4304         return ENOENT;
4305 }
4306
4307 #ifdef HAVE_SOLARIS_GETPWENT_R
4308 struct passwd *getpwent_r(struct passwd *pwdst, char *buf, int buflen)
4309 {
4310         struct passwd *pwdstp = NULL;
4311         int rc;
4312
4313         if (!nss_wrapper_enabled()) {
4314                 return libc_getpwent_r(pwdst, buf, buflen);
4315         }
4316         rc = nwrap_getpwent_r(pwdst, buf, buflen, &pwdstp);
4317         if (rc < 0) {
4318                 return NULL;
4319         }
4320
4321         return pwdstp;
4322 }
4323 #else /* HAVE_SOLARIS_GETPWENT_R */
4324 int getpwent_r(struct passwd *pwdst, char *buf,
4325                size_t buflen, struct passwd **pwdstp)
4326 {
4327         if (!nss_wrapper_enabled()) {
4328                 return libc_getpwent_r(pwdst, buf, buflen, pwdstp);
4329         }
4330
4331         return nwrap_getpwent_r(pwdst, buf, buflen, pwdstp);
4332 }
4333 #endif /* HAVE_SOLARIS_GETPWENT_R */
4334
4335 /****************************************************************************
4336  *   ENDPWENT
4337  ***************************************************************************/
4338
4339 static void nwrap_endpwent(void)
4340 {
4341         int i;
4342
4343         for (i=0; i < nwrap_main_global->num_backends; i++) {
4344                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4345                 b->ops->nw_endpwent(b);
4346         }
4347 }
4348
4349 void endpwent(void)
4350 {
4351         if (!nss_wrapper_enabled()) {
4352                 libc_endpwent();
4353                 return;
4354         }
4355
4356         nwrap_endpwent();
4357 }
4358
4359 /****************************************************************************
4360  *   INITGROUPS
4361  ***************************************************************************/
4362
4363 static int nwrap_initgroups(const char *user, gid_t group)
4364 {
4365         int i;
4366
4367         for (i=0; i < nwrap_main_global->num_backends; i++) {
4368                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4369                 int rc;
4370
4371                 rc = b->ops->nw_initgroups(b, user, group);
4372                 if (rc == 0) {
4373                         return 0;
4374                 }
4375         }
4376
4377         errno = ENOENT;
4378         return -1;
4379 }
4380
4381 int initgroups(const char *user, gid_t group)
4382 {
4383         if (!nss_wrapper_enabled()) {
4384                 return libc_initgroups(user, group);
4385         }
4386
4387         return nwrap_initgroups(user, group);
4388 }
4389
4390 /****************************************************************************
4391  *   GETGRNAM
4392  ***************************************************************************/
4393
4394 static struct group *nwrap_getgrnam(const char *name)
4395 {
4396         int i;
4397         struct group *grp;
4398
4399         for (i=0; i < nwrap_main_global->num_backends; i++) {
4400                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4401                 grp = b->ops->nw_getgrnam(b, name);
4402                 if (grp) {
4403                         return grp;
4404                 }
4405         }
4406
4407         return NULL;
4408 }
4409
4410 struct group *getgrnam(const char *name)
4411 {
4412         if (!nss_wrapper_enabled()) {
4413                 return libc_getgrnam(name);
4414         }
4415
4416         return nwrap_getgrnam(name);
4417 }
4418
4419 /****************************************************************************
4420  *   GETGRNAM_R
4421  ***************************************************************************/
4422
4423 static int nwrap_getgrnam_r(const char *name, struct group *grdst,
4424                             char *buf, size_t buflen, struct group **grdstp)
4425 {
4426         int i, ret;
4427
4428         for (i=0; i < nwrap_main_global->num_backends; i++) {
4429                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4430                 ret = b->ops->nw_getgrnam_r(b, name, grdst, buf, buflen, grdstp);
4431                 if (ret == ENOENT) {
4432                         continue;
4433                 }
4434                 return ret;
4435         }
4436
4437         return ENOENT;
4438 }
4439
4440 #ifdef HAVE_GETGRNAM_R
4441 # ifdef HAVE_SOLARIS_GETGRNAM_R
4442 int getgrnam_r(const char *name, struct group *grp,
4443                 char *buf, int buflen, struct group **pgrp)
4444 # else /* HAVE_SOLARIS_GETGRNAM_R */
4445 int getgrnam_r(const char *name, struct group *grp,
4446                char *buf, size_t buflen, struct group **pgrp)
4447 # endif /* HAVE_SOLARIS_GETGRNAM_R */
4448 {
4449         if (!nss_wrapper_enabled()) {
4450                 return libc_getgrnam_r(name,
4451                                        grp,
4452                                        buf,
4453                                        buflen,
4454                                        pgrp);
4455         }
4456
4457         return nwrap_getgrnam_r(name, grp, buf, buflen, pgrp);
4458 }
4459 #endif /* HAVE_GETGRNAM_R */
4460
4461 /****************************************************************************
4462  *   GETGRGID
4463  ***************************************************************************/
4464
4465 static struct group *nwrap_getgrgid(gid_t gid)
4466 {
4467         int i;
4468         struct group *grp;
4469
4470         for (i=0; i < nwrap_main_global->num_backends; i++) {
4471                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4472                 grp = b->ops->nw_getgrgid(b, gid);
4473                 if (grp) {
4474                         return grp;
4475                 }
4476         }
4477
4478         return NULL;
4479 }
4480
4481 struct group *getgrgid(gid_t gid)
4482 {
4483         if (!nss_wrapper_enabled()) {
4484                 return libc_getgrgid(gid);
4485         }
4486
4487         return nwrap_getgrgid(gid);
4488 }
4489
4490 /****************************************************************************
4491  *   GETGRGID_R
4492  ***************************************************************************/
4493
4494 static int nwrap_getgrgid_r(gid_t gid, struct group *grdst,
4495                             char *buf, size_t buflen, struct group **grdstp)
4496 {
4497         int i,ret;
4498
4499         for (i=0; i < nwrap_main_global->num_backends; i++) {
4500                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4501                 ret = b->ops->nw_getgrgid_r(b, gid, grdst, buf, buflen, grdstp);
4502                 if (ret == ENOENT) {
4503                         continue;
4504                 }
4505                 return ret;
4506         }
4507
4508         return ENOENT;
4509 }
4510
4511 #ifdef HAVE_GETGRGID_R
4512 # ifdef HAVE_SOLARIS_GETGRGID_R
4513 int getgrgid_r(gid_t gid, struct group *grdst,
4514                char *buf, int buflen, struct group **grdstp)
4515 # else /* HAVE_SOLARIS_GETGRGID_R */
4516 int getgrgid_r(gid_t gid, struct group *grdst,
4517                char *buf, size_t buflen, struct group **grdstp)
4518 # endif /* HAVE_SOLARIS_GETGRGID_R */
4519 {
4520         if (!nss_wrapper_enabled()) {
4521                 return libc_getgrgid_r(gid, grdst, buf, buflen, grdstp);
4522         }
4523
4524         return nwrap_getgrgid_r(gid, grdst, buf, buflen, grdstp);
4525 }
4526 #endif
4527
4528 /****************************************************************************
4529  *   SETGRENT
4530  ***************************************************************************/
4531
4532 static void nwrap_setgrent(void)
4533 {
4534         int i;
4535
4536         for (i=0; i < nwrap_main_global->num_backends; i++) {
4537                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4538                 b->ops->nw_setgrent(b);
4539         }
4540 }
4541
4542 #ifdef HAVE_BSD_SETGRENT
4543 int setgrent(void)
4544 #else
4545 void setgrent(void)
4546 #endif
4547 {
4548         if (!nss_wrapper_enabled()) {
4549                 libc_setgrent();
4550                 goto out;
4551         }
4552
4553         nwrap_setgrent();
4554
4555 out:
4556 #ifdef HAVE_BSD_SETGRENT
4557         return 0;
4558 #else
4559         return;
4560 #endif
4561 }
4562
4563 /****************************************************************************
4564  *   GETGRENT
4565  ***************************************************************************/
4566
4567 static struct group *nwrap_getgrent(void)
4568 {
4569         int i;
4570         struct group *grp;
4571
4572         for (i=0; i < nwrap_main_global->num_backends; i++) {
4573                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4574                 grp = b->ops->nw_getgrent(b);
4575                 if (grp) {
4576                         return grp;
4577                 }
4578         }
4579
4580         return NULL;
4581 }
4582
4583 struct group *getgrent(void)
4584 {
4585         if (!nss_wrapper_enabled()) {
4586                 return libc_getgrent();
4587         }
4588
4589         return nwrap_getgrent();
4590 }
4591
4592 /****************************************************************************
4593  *   GETGRENT_R
4594  ***************************************************************************/
4595
4596 static int nwrap_getgrent_r(struct group *grdst, char *buf,
4597                             size_t buflen, struct group **grdstp)
4598 {
4599         int i,ret;
4600
4601         for (i=0; i < nwrap_main_global->num_backends; i++) {
4602                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4603                 ret = b->ops->nw_getgrent_r(b, grdst, buf, buflen, grdstp);
4604                 if (ret == ENOENT) {
4605                         continue;
4606                 }
4607                 return ret;
4608         }
4609
4610         return ENOENT;
4611 }
4612
4613 #ifdef HAVE_SOLARIS_GETGRENT_R
4614 struct group *getgrent_r(struct group *src, char *buf, int buflen)
4615 {
4616         struct group *grdstp = NULL;
4617         int rc;
4618
4619         if (!nss_wrapper_enabled()) {
4620                 return libc_getgrent_r(src, buf, buflen);
4621         }
4622
4623         rc = nwrap_getgrent_r(src, buf, buflen, &grdstp);
4624         if (rc < 0) {
4625                 return NULL;
4626         }
4627
4628         return grdstp;
4629 }
4630 #else /* HAVE_SOLARIS_GETGRENT_R */
4631 int getgrent_r(struct group *src, char *buf,
4632                size_t buflen, struct group **grdstp)
4633 {
4634         if (!nss_wrapper_enabled()) {
4635                 return libc_getgrent_r(src, buf, buflen, grdstp);
4636         }
4637
4638         return nwrap_getgrent_r(src, buf, buflen, grdstp);
4639 }
4640 #endif /* HAVE_SOLARIS_GETGRENT_R */
4641
4642 /****************************************************************************
4643  *   ENDGRENT
4644  ***************************************************************************/
4645
4646 static void nwrap_endgrent(void)
4647 {
4648         int i;
4649
4650         for (i=0; i < nwrap_main_global->num_backends; i++) {
4651                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4652                 b->ops->nw_endgrent(b);
4653         }
4654 }
4655
4656 void endgrent(void)
4657 {
4658         if (!nss_wrapper_enabled()) {
4659                 libc_endgrent();
4660                 return;
4661         }
4662
4663         nwrap_endgrent();
4664 }
4665
4666 /****************************************************************************
4667  *   GETGROUPLIST
4668  ***************************************************************************/
4669
4670 #ifdef HAVE_GETGROUPLIST
4671 static int nwrap_getgrouplist(const char *user, gid_t group,
4672                               gid_t *groups, int *ngroups)
4673 {
4674         struct group *grp;
4675         gid_t *groups_tmp;
4676         int count = 1;
4677
4678         NWRAP_LOG(NWRAP_LOG_DEBUG, "getgrouplist called for %s", user);
4679
4680         groups_tmp = (gid_t *)malloc(count * sizeof(gid_t));
4681         if (!groups_tmp) {
4682                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
4683                 errno = ENOMEM;
4684                 return -1;
4685         }
4686         groups_tmp[0] = group;
4687
4688         nwrap_setgrent();
4689         while ((grp = nwrap_getgrent()) != NULL) {
4690                 int i = 0;
4691
4692                 NWRAP_LOG(NWRAP_LOG_DEBUG,
4693                           "Inspecting %s for group membership",
4694                           grp->gr_name);
4695
4696                 for (i=0; grp->gr_mem && grp->gr_mem[i] != NULL; i++) {
4697
4698                         if (group != grp->gr_gid &&
4699                             (strcmp(user, grp->gr_mem[i]) == 0)) {
4700
4701                                 NWRAP_LOG(NWRAP_LOG_DEBUG,
4702                                           "%s is member of %s",
4703                                           user,
4704                                           grp->gr_name);
4705
4706                                 groups_tmp = (gid_t *)realloc(groups_tmp, (count + 1) * sizeof(gid_t));
4707                                 if (!groups_tmp) {
4708                                         NWRAP_LOG(NWRAP_LOG_ERROR,
4709                                                   "Out of memory");
4710                                         errno = ENOMEM;
4711                                         return -1;
4712                                 }
4713                                 groups_tmp[count] = grp->gr_gid;
4714
4715                                 count++;
4716                         }
4717                 }
4718         }
4719
4720         nwrap_endgrent();
4721
4722         NWRAP_LOG(NWRAP_LOG_DEBUG,
4723                   "%s is member of %d groups",
4724                   user, *ngroups);
4725
4726         if (*ngroups < count) {
4727                 *ngroups = count;
4728                 free(groups_tmp);
4729                 return -1;
4730         }
4731
4732         *ngroups = count;
4733         memcpy(groups, groups_tmp, count * sizeof(gid_t));
4734         free(groups_tmp);
4735
4736         return count;
4737 }
4738
4739 int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups)
4740 {
4741         if (!nss_wrapper_enabled()) {
4742                 return libc_getgrouplist(user, group, groups, ngroups);
4743         }
4744
4745         return nwrap_getgrouplist(user, group, groups, ngroups);
4746 }
4747 #endif
4748
4749 /**********************************************************
4750  * SHADOW
4751  **********************************************************/
4752
4753 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
4754
4755 #ifdef HAVE_SETSPENT
4756 static void nwrap_setspent(void)
4757 {
4758         nwrap_files_setspent();
4759 }
4760
4761 void setspent(void)
4762 {
4763         if (!nss_wrapper_shadow_enabled()) {
4764                 return;
4765         }
4766
4767         nwrap_setspent();
4768 }
4769
4770 static struct spwd *nwrap_getspent(void)
4771 {
4772         return nwrap_files_getspent();
4773 }
4774
4775 struct spwd *getspent(void)
4776 {
4777         if (!nss_wrapper_shadow_enabled()) {
4778                 return NULL;
4779         }
4780
4781         return nwrap_getspent();
4782 }
4783
4784 static void nwrap_endspent(void)
4785 {
4786         nwrap_files_endspent();
4787 }
4788
4789 void endspent(void)
4790 {
4791         if (!nss_wrapper_shadow_enabled()) {
4792                 return;
4793         }
4794
4795         nwrap_endspent();
4796 }
4797 #endif /* HAVE_SETSPENT */
4798
4799 static struct spwd *nwrap_getspnam(const char *name)
4800 {
4801         return nwrap_files_getspnam(name);
4802 }
4803
4804 struct spwd *getspnam(const char *name)
4805 {
4806         if (!nss_wrapper_shadow_enabled()) {
4807                 return NULL;
4808         }
4809
4810         return nwrap_getspnam(name);
4811 }
4812
4813 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
4814
4815 /**********************************************************
4816  * NETDB
4817  **********************************************************/
4818
4819 static void nwrap_sethostent(int stayopen) {
4820         (void) stayopen; /* ignored */
4821
4822         nwrap_files_sethostent();
4823 }
4824
4825 #ifdef HAVE_SOLARIS_SETHOSTENT
4826 int sethostent(int stayopen)
4827 {
4828         if (!nss_wrapper_hosts_enabled()) {
4829                 libc_sethostent(stayopen);
4830                 return 0;
4831         }
4832
4833         nwrap_sethostent(stayopen);
4834
4835         return 0;
4836 }
4837 #else /* HAVE_SOLARIS_SETHOSTENT */
4838 void sethostent(int stayopen)
4839 {
4840         if (!nss_wrapper_hosts_enabled()) {
4841                 libc_sethostent(stayopen);
4842                 return;
4843         }
4844
4845         nwrap_sethostent(stayopen);
4846 }
4847 #endif /* HAVE_SOLARIS_SETHOSTENT */
4848
4849 static struct hostent *nwrap_gethostent(void)
4850 {
4851         return nwrap_files_gethostent();
4852 }
4853
4854 struct hostent *gethostent(void) {
4855         if (!nss_wrapper_hosts_enabled()) {
4856                 return libc_gethostent();
4857         }
4858
4859         return nwrap_gethostent();
4860 }
4861
4862 static void nwrap_endhostent(void) {
4863         nwrap_files_endhostent();
4864 }
4865
4866 #ifdef HAVE_SOLARIS_ENDHOSTENT
4867 int endhostent(void)
4868 {
4869         if (!nss_wrapper_hosts_enabled()) {
4870                 libc_endhostent();
4871                 return 0;
4872         }
4873
4874         nwrap_endhostent();
4875
4876         return 0;
4877 }
4878 #else /* HAVE_SOLARIS_ENDHOSTENT */
4879 void endhostent(void)
4880 {
4881         if (!nss_wrapper_hosts_enabled()) {
4882                 libc_endhostent();
4883                 return;
4884         }
4885
4886         nwrap_endhostent();
4887 }
4888 #endif /* HAVE_SOLARIS_ENDHOSTENT */
4889
4890 #ifdef BSD
4891 /* BSD implementation stores data in thread local storage but GLIBC does not */
4892 static __thread struct hostent user_he;
4893 static __thread struct nwrap_vector user_addrlist;
4894 #else
4895 static struct hostent user_he;
4896 static struct nwrap_vector user_addrlist;
4897 #endif /* BSD */
4898 static struct hostent *nwrap_gethostbyname(const char *name)
4899 {
4900         if (nwrap_files_gethostbyname(name, AF_UNSPEC, &user_he, &user_addrlist) == -1) {
4901                 return NULL;
4902         }
4903         return &user_he;
4904 }
4905
4906 struct hostent *gethostbyname(const char *name)
4907 {
4908         if (!nss_wrapper_hosts_enabled()) {
4909                 return libc_gethostbyname(name);
4910         }
4911
4912         return nwrap_gethostbyname(name);
4913 }
4914
4915 /* This is a GNU extension - Also can be found on BSD systems */
4916 #ifdef HAVE_GETHOSTBYNAME2
4917 #ifdef BSD
4918 /* BSD implementation stores data in  thread local storage but GLIBC not */
4919 static __thread struct hostent user_he2;
4920 static __thread struct nwrap_vector user_addrlist2;
4921 #else
4922 static struct hostent user_he2;
4923 static struct nwrap_vector user_addrlist2;
4924 #endif /* BSD */
4925 static struct hostent *nwrap_gethostbyname2(const char *name, int af)
4926 {
4927         if (nwrap_files_gethostbyname(name, af, &user_he2, &user_addrlist2) == -1) {
4928                 return NULL;
4929         }
4930         return &user_he2;
4931 }
4932
4933 struct hostent *gethostbyname2(const char *name, int af)
4934 {
4935         if (!nss_wrapper_hosts_enabled()) {
4936                 return libc_gethostbyname2(name, af);
4937         }
4938
4939         return nwrap_gethostbyname2(name, af);
4940 }
4941 #endif
4942
4943 static struct hostent *nwrap_gethostbyaddr(const void *addr,
4944                                            socklen_t len, int type)
4945 {
4946         return nwrap_files_gethostbyaddr(addr, len, type);
4947 }
4948
4949 struct hostent *gethostbyaddr(const void *addr,
4950                               socklen_t len, int type)
4951 {
4952         if (!nss_wrapper_hosts_enabled()) {
4953                 return libc_gethostbyaddr(addr, len, type);
4954         }
4955
4956         return nwrap_gethostbyaddr(addr, len, type);
4957 }
4958
4959 static const struct addrinfo default_hints =
4960 {
4961         .ai_flags = AI_ADDRCONFIG|AI_V4MAPPED,
4962         .ai_family = AF_UNSPEC,
4963         .ai_socktype = 0,
4964         .ai_protocol = 0,
4965         .ai_addrlen = 0,
4966         .ai_addr = NULL,
4967         .ai_canonname = NULL,
4968         .ai_next = NULL
4969 };
4970
4971 static int nwrap_convert_he_ai(const struct hostent *he,
4972                                unsigned short port,
4973                                const struct addrinfo *hints,
4974                                struct addrinfo **pai,
4975                                bool skip_canonname)
4976 {
4977         struct addrinfo *ai;
4978         socklen_t socklen;
4979
4980         if (he == NULL) {
4981                 return EAI_MEMORY;
4982         }
4983
4984         switch (he->h_addrtype) {
4985                 case AF_INET:
4986                         socklen = sizeof(struct sockaddr_in);
4987                         break;
4988 #ifdef HAVE_IPV6
4989                 case AF_INET6:
4990                         socklen = sizeof(struct sockaddr_in6);
4991                         break;
4992 #endif
4993                 default:
4994                         return EAI_FAMILY;
4995         }
4996
4997         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo) + socklen);
4998         if (ai == NULL) {
4999                 return EAI_MEMORY;
5000         }
5001
5002         ai->ai_flags = 0;
5003         ai->ai_family = he->h_addrtype;
5004         ai->ai_socktype = hints->ai_socktype;
5005         ai->ai_protocol = hints->ai_protocol;
5006         ai->ai_canonname = NULL;
5007
5008         ai->ai_addrlen = socklen;
5009         ai->ai_addr = (void *)(ai + 1);
5010
5011 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
5012         ai->ai_addr->sa_len = socklen;
5013 #endif
5014         ai->ai_addr->sa_family = he->h_addrtype;
5015
5016         switch (he->h_addrtype) {
5017                 case AF_INET:
5018                 {
5019                         struct sockaddr_in *sinp =
5020                                 (struct sockaddr_in *) ai->ai_addr;
5021
5022                         memset(sinp, 0, sizeof(struct sockaddr_in));
5023
5024                         sinp->sin_port = htons(port);
5025                         sinp->sin_family = AF_INET;
5026
5027                         memset (sinp->sin_zero, '\0', sizeof (sinp->sin_zero));
5028                         memcpy(&sinp->sin_addr, he->h_addr_list[0], he->h_length);
5029
5030                 }
5031                 break;
5032 #ifdef HAVE_IPV6
5033                 case AF_INET6:
5034                 {
5035                         struct sockaddr_in6 *sin6p =
5036                                 (struct sockaddr_in6 *) ai->ai_addr;
5037
5038                         memset(sin6p, 0, sizeof(struct sockaddr_in6));
5039
5040                         sin6p->sin6_port = htons(port);
5041                         sin6p->sin6_family = AF_INET6;
5042
5043                         memcpy(&sin6p->sin6_addr,
5044                                he->h_addr_list[0],
5045                                he->h_length);
5046                 }
5047                 break;
5048 #endif
5049         }
5050
5051         ai->ai_next = NULL;
5052
5053         if (he->h_name && !skip_canonname) {
5054                 ai->ai_canonname = strdup(he->h_name);
5055                 if (ai->ai_canonname == NULL) {
5056                         freeaddrinfo(ai);
5057                         return EAI_MEMORY;
5058                 }
5059         }
5060
5061         *pai = ai;
5062         return 0;
5063 }
5064
5065 static int nwrap_getaddrinfo(const char *node,
5066                              const char *service,
5067                              const struct addrinfo *hints,
5068                              struct addrinfo **res)
5069 {
5070         struct addrinfo *ai = NULL;
5071         struct addrinfo *ai_tail;
5072         unsigned short port = 0;
5073         struct {
5074                 int family;
5075                 union {
5076                         struct in_addr v4;
5077 #ifdef HAVE_IPV6
5078                         struct in6_addr v6;
5079                 } in;
5080 #endif
5081         } addr = {
5082                 .family = AF_UNSPEC,
5083         };
5084
5085         if (node == NULL && service == NULL) {
5086                 return EAI_NONAME;
5087         }
5088
5089         if (hints == NULL) {
5090                 hints = &default_hints;
5091         }
5092
5093         /* EAI_BADFLAGS
5094               hints.ai_flags   contains   invalid  flags;  or,  hints.ai_flags
5095               included AI_CANONNAME and name was NULL.
5096         */
5097         if ((hints->ai_flags & AI_CANONNAME) && (node == NULL)) {
5098                 return EAI_BADFLAGS;
5099         }
5100
5101         /* If no node has been specified, let glibc deal with it */
5102         if (node == NULL) {
5103                 int ret;
5104                 struct addrinfo *p = NULL;
5105
5106                 ret = libc_getaddrinfo(node, service, hints, &p);
5107
5108                 if (ret == 0) {
5109                         *res = p;
5110                 }
5111                 return ret;
5112         }
5113
5114         if (service != NULL && service[0] != '\0') {
5115                 const char *proto = NULL;
5116                 struct servent *s;
5117                 char *end_ptr;
5118                 long sl;
5119
5120                 errno = 0;
5121                 sl = strtol(service, &end_ptr, 10);
5122
5123                 if (*end_ptr == '\0') {
5124                         port = sl;
5125                         goto valid_port;
5126                 } else if (hints->ai_flags & AI_NUMERICSERV) {
5127                         return EAI_NONAME;
5128                 }
5129
5130                 if (hints->ai_protocol != 0) {
5131                         struct protoent *pent;
5132
5133                         pent = getprotobynumber(hints->ai_protocol);
5134                         if (pent != NULL) {
5135                                 proto = pent->p_name;
5136                         }
5137                 }
5138
5139                 s = getservbyname(service, proto);
5140                 if (s == NULL) {
5141                         return EAI_NONAME;
5142                 }
5143                 port = ntohs(s->s_port);
5144         }
5145
5146 valid_port:
5147         if (hints->ai_family == AF_UNSPEC || hints->ai_family == AF_INET) {
5148                 int rc = inet_pton(AF_INET, node, &addr.in.v4);
5149                 if (rc == 1) {
5150                         addr.family = AF_INET;
5151                 }
5152         }
5153 #ifdef HAVE_IPV6
5154         if (addr.family == AF_UNSPEC) {
5155                 int rc = inet_pton(AF_INET6, node, &addr.in.v6);
5156                 if (rc == 1) {
5157                         addr.family = AF_INET6;
5158                 }
5159         }
5160 #endif
5161
5162         ai = nwrap_files_getaddrinfo(node, port, hints, &ai_tail);
5163         if (ai == NULL) {
5164                 int ret;
5165                 struct addrinfo *p = NULL;
5166
5167                 ret = libc_getaddrinfo(node, service, hints, &p);
5168
5169                 if (ret == 0) {
5170                         /*
5171                          * nwrap_files_getaddrinfo failed, but libc was
5172                          * successful -- use the result from libc.
5173                          */
5174                         *res = p;
5175                         return 0;
5176                 }
5177
5178                 return EAI_SYSTEM;
5179         }
5180
5181         if (ai->ai_flags == 0) {
5182                 ai->ai_flags = hints->ai_flags;
5183         }
5184         if (ai->ai_socktype == 0) {
5185                 ai->ai_socktype = SOCK_DGRAM;
5186         }
5187         if (ai->ai_protocol == 0 && ai->ai_socktype == SOCK_DGRAM) {
5188                 ai->ai_protocol = 17; /* UDP */
5189         } else if (ai->ai_protocol == 0 && ai->ai_socktype == SOCK_STREAM) {
5190                 ai->ai_protocol = 6; /* TCP */
5191         }
5192
5193         if (hints->ai_socktype == 0) {
5194                 /* Add second ai */
5195                 struct addrinfo *ai_head = ai;
5196                 struct addrinfo *ai_tmp;
5197                 struct addrinfo *ai_new_tail = ai_tail;
5198
5199                 /* Add at least one more struct */
5200                 do {
5201                         /* CHECKS! */
5202                         ai_tmp = malloc(sizeof(struct addrinfo));
5203                         memcpy(ai_tmp, ai_head, sizeof(struct addrinfo));
5204                         ai_tmp->ai_next = NULL;
5205
5206                         /* We need a deep copy or freeaddrinfo() will blow up */
5207                         if (ai_head->ai_canonname != NULL) {
5208                                 ai_tmp->ai_canonname =
5209                                         strdup(ai_head->ai_canonname);
5210                         }
5211                         /* ai_head should point inside hints. */
5212                         ai_tmp->ai_addr = ai_head->ai_addr;
5213
5214                         if (ai_head->ai_flags == 0) {
5215                                 ai_tmp->ai_flags = hints->ai_flags;
5216                         }
5217                         if (ai_head->ai_socktype == SOCK_DGRAM) {
5218                                 ai_tmp->ai_socktype = SOCK_STREAM;
5219                         } else if (ai_head->ai_socktype == SOCK_STREAM) {
5220                                 ai_tmp->ai_socktype = SOCK_DGRAM;
5221                         }
5222                         if (ai_head->ai_socktype == SOCK_DGRAM) {
5223                                 ai_tmp->ai_protocol = 17; /* UDP */
5224                         } else if (ai_head->ai_socktype == SOCK_STREAM) {
5225                                 ai_tmp->ai_protocol = 6; /* TCP */
5226                         }
5227                         ai_new_tail->ai_next = ai_tmp;
5228                         ai_new_tail = ai_tmp;
5229
5230                         if (ai_head == ai_tail) {
5231                                 break;
5232                         }
5233                         ai_head = ai_head->ai_next;
5234                 } while (1);
5235         }
5236
5237         *res = ai;
5238
5239         return 0;
5240 }
5241
5242 int getaddrinfo(const char *node, const char *service,
5243                 const struct addrinfo *hints,
5244                 struct addrinfo **res)
5245 {
5246         if (!nss_wrapper_hosts_enabled()) {
5247                 return libc_getaddrinfo(node, service, hints, res);
5248         }
5249
5250         return nwrap_getaddrinfo(node, service, hints, res);
5251 }
5252
5253 static int nwrap_getnameinfo(const struct sockaddr *sa, socklen_t salen,
5254                              char *host, size_t hostlen,
5255                              char *serv, size_t servlen,
5256                              int flags)
5257 {
5258         struct hostent *he;
5259         struct servent *service;
5260         const char *proto;
5261         const void *addr;
5262         socklen_t addrlen;
5263         uint16_t port;
5264         sa_family_t type;
5265
5266         if (sa == NULL || salen < sizeof(sa_family_t)) {
5267                 return EAI_FAMILY;
5268         }
5269
5270         if ((flags & NI_NAMEREQD) && host == NULL && serv == NULL) {
5271                 return EAI_NONAME;
5272         }
5273
5274         type = sa->sa_family;
5275         switch (type) {
5276         case AF_INET:
5277                 if (salen < sizeof(struct sockaddr_in))
5278                         return EAI_FAMILY;
5279                 addr = &((const struct sockaddr_in *)sa)->sin_addr;
5280                 addrlen = sizeof(((const struct sockaddr_in *)sa)->sin_addr);
5281                 port = ntohs(((const struct sockaddr_in *)sa)->sin_port);
5282                 break;
5283 #ifdef HAVE_IPV6
5284         case AF_INET6:
5285                 if (salen < sizeof(struct sockaddr_in6))
5286                         return EAI_FAMILY;
5287                 addr = &((const struct sockaddr_in6 *)sa)->sin6_addr;
5288                 addrlen = sizeof(((const struct sockaddr_in6 *)sa)->sin6_addr);
5289                 port = ntohs(((const struct sockaddr_in6 *)sa)->sin6_port);
5290                 break;
5291 #endif
5292         default:
5293                 return EAI_FAMILY;
5294         }
5295
5296         if (host != NULL) {
5297                 he = NULL;
5298                 if ((flags & NI_NUMERICHOST) == 0) {
5299                         he = nwrap_files_gethostbyaddr(addr, addrlen, type);
5300                         if ((flags & NI_NAMEREQD) && (he == NULL || he->h_name == NULL))
5301                                 return EAI_NONAME;
5302                 }
5303                 if (he != NULL && he->h_name != NULL) {
5304                         if (strlen(he->h_name) >= hostlen)
5305                                 return EAI_OVERFLOW;
5306                         strcpy(host, he->h_name);
5307                         if (flags & NI_NOFQDN)
5308                                 host[strcspn(host, ".")] = '\0';
5309                 } else {
5310                         if (inet_ntop(type, addr, host, hostlen) == NULL)
5311                                 return (errno == ENOSPC) ? EAI_OVERFLOW : EAI_FAIL;
5312                 }
5313         }
5314
5315         if (serv != NULL) {
5316                 service = NULL;
5317                 if ((flags & NI_NUMERICSERV) == 0) {
5318                         proto = (flags & NI_DGRAM) ? "udp" : "tcp";
5319                         service = getservbyport(htons(port), proto);
5320                 }
5321                 if (service != NULL) {
5322                         if (strlen(service->s_name) >= servlen)
5323                                 return EAI_OVERFLOW;
5324                         strcpy(serv, service->s_name);
5325                 } else {
5326                         if (snprintf(serv, servlen, "%u", port) >= (int) servlen)
5327                                 return EAI_OVERFLOW;
5328                 }
5329         }
5330
5331         return 0;
5332 }
5333
5334 #ifdef HAVE_LINUX_GETNAMEINFO
5335 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5336                 char *host, socklen_t hostlen,
5337                 char *serv, socklen_t servlen,
5338                 int flags)
5339 #elif defined(HAVE_LINUX_GETNAMEINFO_UNSIGNED)
5340 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5341                 char *host, socklen_t hostlen,
5342                 char *serv, socklen_t servlen,
5343                 unsigned int flags)
5344 #else
5345 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5346                 char *host, size_t hostlen,
5347                 char *serv, size_t servlen,
5348                 int flags)
5349 #endif
5350 {
5351         if (!nss_wrapper_hosts_enabled()) {
5352                 return libc_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
5353         }
5354
5355         return nwrap_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
5356 }
5357
5358 static int nwrap_gethostname(char *name, size_t len)
5359 {
5360         const char *hostname = getenv("NSS_WRAPPER_HOSTNAME");
5361
5362         if (strlen(hostname) >= len) {
5363                 errno = ENAMETOOLONG;
5364                 return -1;
5365         }
5366         snprintf(name, len, "%s", hostname);
5367
5368         return 0;
5369 }
5370
5371 #ifdef HAVE_SOLARIS_GETHOSTNAME
5372 int gethostname(char *name, int len)
5373 #else /* HAVE_SOLARIS_GETHOSTNAME */
5374 int gethostname(char *name, size_t len)
5375 #endif /* HAVE_SOLARIS_GETHOSTNAME */
5376 {
5377         if (!nwrap_hostname_enabled()) {
5378                 return libc_gethostname(name, len);
5379         }
5380
5381         return nwrap_gethostname(name, len);
5382 }
5383
5384 /****************************
5385  * DESTRUCTOR
5386  ***************************/
5387
5388 /*
5389  * This function is called when the library is unloaded and makes sure that
5390  * sockets get closed and the unix file for the socket are unlinked.
5391  */
5392 void nwrap_destructor(void)
5393 {
5394         int i;
5395
5396         NWRAP_LOCK_ALL;
5397         if (nwrap_main_global != NULL) {
5398                 struct nwrap_main *m = nwrap_main_global;
5399
5400                 /* libc */
5401                 SAFE_FREE(m->libc->fns);
5402                 if (m->libc->handle != NULL) {
5403                         dlclose(m->libc->handle);
5404                 }
5405                 if (m->libc->nsl_handle != NULL) {
5406                         dlclose(m->libc->nsl_handle);
5407                 }
5408                 if (m->libc->sock_handle != NULL) {
5409                         dlclose(m->libc->sock_handle);
5410                 }
5411                 SAFE_FREE(m->libc);
5412
5413                 /* backends */
5414                 for (i = 0; i < m->num_backends; i++) {
5415                         struct nwrap_backend *b = &(m->backends[i]);
5416
5417                         if (b->so_handle != NULL) {
5418                                 dlclose(b->so_handle);
5419                         }
5420                         SAFE_FREE(b->fns);
5421                 }
5422                 SAFE_FREE(m->backends);
5423         }
5424
5425         if (nwrap_pw_global.cache != NULL) {
5426                 struct nwrap_cache *c = nwrap_pw_global.cache;
5427
5428                 nwrap_files_cache_unload(c);
5429                 if (c->fd >= 0) {
5430                         fclose(c->fp);
5431                         c->fd = -1;
5432                 }
5433
5434                 SAFE_FREE(nwrap_pw_global.list);
5435                 nwrap_pw_global.num = 0;
5436         }
5437
5438         if (nwrap_gr_global.cache != NULL) {
5439                 struct nwrap_cache *c = nwrap_gr_global.cache;
5440
5441                 nwrap_files_cache_unload(c);
5442                 if (c->fd >= 0) {
5443                         fclose(c->fp);
5444                         c->fd = -1;
5445                 }
5446
5447                 SAFE_FREE(nwrap_gr_global.list);
5448                 nwrap_pw_global.num = 0;
5449         }
5450
5451         if (nwrap_he_global.cache != NULL) {
5452                 struct nwrap_cache *c = nwrap_he_global.cache;
5453
5454                 nwrap_files_cache_unload(c);
5455                 if (c->fd >= 0) {
5456                         fclose(c->fp);
5457                         c->fd = -1;
5458                 }
5459
5460                 nwrap_he_global.num = 0;
5461         }
5462
5463         hdestroy();
5464         NWRAP_UNLOCK_ALL;
5465 }