nwrap: rename _ai -> ai_new in nwrap_files_getaddrinfo()
[samba.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 bool 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 false;
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 false;
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 true;
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                 return false;
1836         }
1837
1838         NWRAP_LOG(NWRAP_LOG_TRACE, "Reloaded %s", nwrap->path);
1839         return true;
1840 }
1841
1842 /*
1843  * the caller has to call nwrap_unload() on failure
1844  */
1845 static bool nwrap_pw_parse_line(struct nwrap_cache *nwrap, char *line)
1846 {
1847         struct nwrap_pw *nwrap_pw;
1848         char *c;
1849         char *p;
1850         char *e;
1851         struct passwd *pw;
1852         size_t list_size;
1853
1854         nwrap_pw = (struct nwrap_pw *)nwrap->private_data;
1855
1856         list_size = sizeof(*nwrap_pw->list) * (nwrap_pw->num+1);
1857         pw = (struct passwd *)realloc(nwrap_pw->list, list_size);
1858         if (!pw) {
1859                 NWRAP_LOG(NWRAP_LOG_ERROR,
1860                           "realloc(%u) failed",
1861                           (unsigned)list_size);
1862                 return false;
1863         }
1864         nwrap_pw->list = pw;
1865
1866         pw = &nwrap_pw->list[nwrap_pw->num];
1867
1868         c = line;
1869
1870         /* name */
1871         p = strchr(c, ':');
1872         if (!p) {
1873                 NWRAP_LOG(NWRAP_LOG_ERROR,
1874                           "Invalid line[%s]: '%s'",
1875                           line,
1876                           c);
1877                 return false;
1878         }
1879         *p = '\0';
1880         p++;
1881         pw->pw_name = c;
1882         c = p;
1883
1884         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]\n", pw->pw_name);
1885
1886         /* password */
1887         p = strchr(c, ':');
1888         if (!p) {
1889                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1890                 return false;
1891         }
1892         *p = '\0';
1893         p++;
1894         pw->pw_passwd = c;
1895         c = p;
1896
1897         NWRAP_LOG(NWRAP_LOG_TRACE, "password[%s]\n", pw->pw_passwd);
1898
1899         /* uid */
1900         p = strchr(c, ':');
1901         if (!p) {
1902                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1903                 return false;
1904         }
1905         *p = '\0';
1906         p++;
1907         e = NULL;
1908         pw->pw_uid = (uid_t)strtoul(c, &e, 10);
1909         if (c == e) {
1910                 NWRAP_LOG(NWRAP_LOG_ERROR,
1911                           "Invalid line[%s]: '%s' - %s",
1912                           line, c, strerror(errno));
1913                 return false;
1914         }
1915         if (e == NULL) {
1916                 NWRAP_LOG(NWRAP_LOG_ERROR,
1917                           "Invalid line[%s]: '%s' - %s",
1918                           line, c, strerror(errno));
1919                 return false;
1920         }
1921         if (e[0] != '\0') {
1922                 NWRAP_LOG(NWRAP_LOG_ERROR,
1923                           "Invalid line[%s]: '%s' - %s",
1924                           line, c, strerror(errno));
1925                 return false;
1926         }
1927         c = p;
1928
1929         NWRAP_LOG(NWRAP_LOG_TRACE, "uid[%u]", pw->pw_uid);
1930
1931         /* gid */
1932         p = strchr(c, ':');
1933         if (!p) {
1934                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
1935                 return false;
1936         }
1937         *p = '\0';
1938         p++;
1939         e = NULL;
1940         pw->pw_gid = (gid_t)strtoul(c, &e, 10);
1941         if (c == e) {
1942                 NWRAP_LOG(NWRAP_LOG_ERROR,
1943                           "Invalid line[%s]: '%s' - %s",
1944                           line, c, strerror(errno));
1945                 return false;
1946         }
1947         if (e == NULL) {
1948                 NWRAP_LOG(NWRAP_LOG_ERROR,
1949                           "Invalid line[%s]: '%s' - %s",
1950                           line, c, strerror(errno));
1951                 return false;
1952         }
1953         if (e[0] != '\0') {
1954                 NWRAP_LOG(NWRAP_LOG_ERROR,
1955                           "Invalid line[%s]: '%s' - %s",
1956                           line, c, strerror(errno));
1957                 return false;
1958         }
1959         c = p;
1960
1961         NWRAP_LOG(NWRAP_LOG_TRACE, "gid[%u]\n", pw->pw_gid);
1962
1963         /* gecos */
1964         p = strchr(c, ':');
1965         if (!p) {
1966                 NWRAP_LOG(NWRAP_LOG_ERROR, "invalid line[%s]: '%s'", line, c);
1967                 return false;
1968         }
1969         *p = '\0';
1970         p++;
1971         pw->pw_gecos = c;
1972         c = p;
1973
1974         NWRAP_LOG(NWRAP_LOG_TRACE, "gecos[%s]", pw->pw_gecos);
1975
1976         /* dir */
1977         p = strchr(c, ':');
1978         if (!p) {
1979                 NWRAP_LOG(NWRAP_LOG_ERROR, "'%s'", c);
1980                 return false;
1981         }
1982         *p = '\0';
1983         p++;
1984         pw->pw_dir = c;
1985         c = p;
1986
1987         NWRAP_LOG(NWRAP_LOG_TRACE, "dir[%s]", pw->pw_dir);
1988
1989         /* shell */
1990         pw->pw_shell = c;
1991         NWRAP_LOG(NWRAP_LOG_TRACE, "shell[%s]", pw->pw_shell);
1992
1993         NWRAP_LOG(NWRAP_LOG_DEBUG,
1994                   "Added user[%s:%s:%u:%u:%s:%s:%s]",
1995                   pw->pw_name, pw->pw_passwd,
1996                   pw->pw_uid, pw->pw_gid,
1997                   pw->pw_gecos, pw->pw_dir, pw->pw_shell);
1998
1999         nwrap_pw->num++;
2000         return true;
2001 }
2002
2003 static void nwrap_pw_unload(struct nwrap_cache *nwrap)
2004 {
2005         struct nwrap_pw *nwrap_pw;
2006         nwrap_pw = (struct nwrap_pw *)nwrap->private_data;
2007
2008         SAFE_FREE(nwrap_pw->list);
2009         nwrap_pw->num = 0;
2010         nwrap_pw->idx = 0;
2011 }
2012
2013 static int nwrap_pw_copy_r(const struct passwd *src, struct passwd *dst,
2014                            char *buf, size_t buflen, struct passwd **dstp)
2015 {
2016         char *first;
2017         char *last;
2018         off_t ofs;
2019
2020         first = src->pw_name;
2021
2022         last = src->pw_shell;
2023         while (*last) last++;
2024
2025         ofs = PTR_DIFF(last + 1, first);
2026
2027         if (ofs > (off_t) buflen) {
2028                 return ERANGE;
2029         }
2030
2031         memcpy(buf, first, ofs);
2032
2033         ofs = PTR_DIFF(src->pw_name, first);
2034         dst->pw_name = buf + ofs;
2035         ofs = PTR_DIFF(src->pw_passwd, first);
2036         dst->pw_passwd = buf + ofs;
2037         dst->pw_uid = src->pw_uid;
2038         dst->pw_gid = src->pw_gid;
2039         ofs = PTR_DIFF(src->pw_gecos, first);
2040         dst->pw_gecos = buf + ofs;
2041         ofs = PTR_DIFF(src->pw_dir, first);
2042         dst->pw_dir = buf + ofs;
2043         ofs = PTR_DIFF(src->pw_shell, first);
2044         dst->pw_shell = buf + ofs;
2045
2046         if (dstp) {
2047                 *dstp = dst;
2048         }
2049
2050         return 0;
2051 }
2052
2053 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
2054 static bool nwrap_sp_parse_line(struct nwrap_cache *nwrap, char *line)
2055 {
2056         struct nwrap_sp *nwrap_sp;
2057         struct spwd *sp;
2058         size_t list_size;
2059         char *c;
2060         char *e;
2061         char *p;
2062
2063         nwrap_sp = (struct nwrap_sp *)nwrap->private_data;
2064
2065         list_size = sizeof(*nwrap_sp->list) * (nwrap_sp->num+1);
2066         sp = (struct spwd *)realloc(nwrap_sp->list, list_size);
2067         if (sp == NULL) {
2068                 NWRAP_LOG(NWRAP_LOG_ERROR,
2069                           "realloc(%u) failed",
2070                           (unsigned)list_size);
2071                 return false;
2072         }
2073         nwrap_sp->list = sp;
2074
2075         sp = &nwrap_sp->list[nwrap_sp->num];
2076
2077         c = line;
2078
2079         /* name */
2080         p = strchr(c, ':');
2081         if (p == NULL) {
2082                 NWRAP_LOG(NWRAP_LOG_ERROR,
2083                           "name -- Invalid line[%s]: '%s'",
2084                           line,
2085                           c);
2086                 return false;
2087         }
2088         *p = '\0';
2089         p++;
2090         sp->sp_namp = c;
2091         c = p;
2092
2093         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]\n", sp->sp_namp);
2094
2095         /* pwd */
2096         p = strchr(c, ':');
2097         if (p == NULL) {
2098                 NWRAP_LOG(NWRAP_LOG_ERROR,
2099                           "pwd -- Invalid line[%s]: '%s'",
2100                           line,
2101                           c);
2102                 return false;
2103         }
2104         *p = '\0';
2105         p++;
2106         sp->sp_pwdp = c;
2107         c = p;
2108
2109         /* lstchg (long) */
2110         if (c[0] == ':') {
2111                 sp->sp_lstchg = -1;
2112                 p++;
2113         } else {
2114                 p = strchr(c, ':');
2115                 if (p == NULL) {
2116                         NWRAP_LOG(NWRAP_LOG_ERROR,
2117                                   "lstchg -- Invalid line[%s]: '%s'",
2118                                   line,
2119                                   c);
2120                         return false;
2121                 }
2122                 *p = '\0';
2123                 p++;
2124                 sp->sp_lstchg = strtol(c, &e, 10);
2125                 if (c == e) {
2126                         NWRAP_LOG(NWRAP_LOG_ERROR,
2127                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2128                                   line, c, strerror(errno));
2129                         return false;
2130                 }
2131                 if (e == NULL) {
2132                         NWRAP_LOG(NWRAP_LOG_ERROR,
2133                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2134                                   line, c, strerror(errno));
2135                         return false;
2136                 }
2137                 if (e[0] != '\0') {
2138                         NWRAP_LOG(NWRAP_LOG_ERROR,
2139                                   "lstchg -- Invalid line[%s]: '%s' - %s",
2140                                   line, c, strerror(errno));
2141                         return false;
2142                 }
2143         }
2144         c = p;
2145
2146         /* min (long) */
2147         if (c[0] == ':') {
2148                 sp->sp_min = -1;
2149                 p++;
2150         } else {
2151                 p = strchr(c, ':');
2152                 if (p == NULL) {
2153                         NWRAP_LOG(NWRAP_LOG_ERROR,
2154                                   "min -- Invalid line[%s]: '%s'",
2155                                   line,
2156                                   c);
2157                         return false;
2158                 }
2159                 *p = '\0';
2160                 p++;
2161                 sp->sp_min = strtol(c, &e, 10);
2162                 if (c == e) {
2163                         NWRAP_LOG(NWRAP_LOG_ERROR,
2164                                   "min -- Invalid line[%s]: '%s' - %s",
2165                                   line, c, strerror(errno));
2166                         return false;
2167                 }
2168                 if (e == NULL) {
2169                         NWRAP_LOG(NWRAP_LOG_ERROR,
2170                                   "min -- Invalid line[%s]: '%s' - %s",
2171                                   line, c, strerror(errno));
2172                         return false;
2173                 }
2174                 if (e[0] != '\0') {
2175                         NWRAP_LOG(NWRAP_LOG_ERROR,
2176                                   "min -- Invalid line[%s]: '%s' - %s",
2177                                   line, c, strerror(errno));
2178                         return false;
2179                 }
2180         }
2181         c = p;
2182
2183         /* max (long) */
2184         if (c[0] == ':') {
2185                 sp->sp_max = -1;
2186                 p++;
2187         } else {
2188                 p = strchr(c, ':');
2189                 if (p == NULL) {
2190                         NWRAP_LOG(NWRAP_LOG_ERROR,
2191                                   "max -- Invalid line[%s]: '%s'",
2192                                   line,
2193                                   c);
2194                         return false;
2195                 }
2196                 *p = '\0';
2197                 p++;
2198                 sp->sp_max = strtol(c, &e, 10);
2199                 if (c == e) {
2200                         NWRAP_LOG(NWRAP_LOG_ERROR,
2201                                   "max -- Invalid line[%s]: '%s' - %s",
2202                                   line, c, strerror(errno));
2203                         return false;
2204                 }
2205                 if (e == NULL) {
2206                         NWRAP_LOG(NWRAP_LOG_ERROR,
2207                                   "max -- Invalid line[%s]: '%s' - %s",
2208                                   line, c, strerror(errno));
2209                         return false;
2210                 }
2211                 if (e[0] != '\0') {
2212                         NWRAP_LOG(NWRAP_LOG_ERROR,
2213                                   "max -- Invalid line[%s]: '%s' - %s",
2214                                   line, c, strerror(errno));
2215                         return false;
2216                 }
2217         }
2218         c = p;
2219
2220         /* warn (long) */
2221         if (c[0] == ':') {
2222                 sp->sp_warn = -1;
2223                 p++;
2224         } else {
2225                 p = strchr(c, ':');
2226                 if (p == NULL) {
2227                         NWRAP_LOG(NWRAP_LOG_ERROR,
2228                                   "warn -- Invalid line[%s]: '%s'",
2229                                   line,
2230                                   c);
2231                         return false;
2232                 }
2233                 *p = '\0';
2234                 p++;
2235                 sp->sp_warn = strtol(c, &e, 10);
2236                 if (c == e) {
2237                         NWRAP_LOG(NWRAP_LOG_ERROR,
2238                                   "warn -- Invalid line[%s]: '%s' - %s",
2239                                   line, c, strerror(errno));
2240                         return false;
2241                 }
2242                 if (e == NULL) {
2243                         NWRAP_LOG(NWRAP_LOG_ERROR,
2244                                   "warn -- Invalid line[%s]: '%s' - %s",
2245                                   line, c, strerror(errno));
2246                         return false;
2247                 }
2248                 if (e[0] != '\0') {
2249                         NWRAP_LOG(NWRAP_LOG_ERROR,
2250                                   "warn -- Invalid line[%s]: '%s' - %s",
2251                                   line, c, strerror(errno));
2252                         return false;
2253                 }
2254         }
2255         c = p;
2256
2257         /* inact (long) */
2258         if (c[0] == ':') {
2259                 sp->sp_inact = -1;
2260                 p++;
2261         } else {
2262                 p = strchr(c, ':');
2263                 if (p == NULL) {
2264                         NWRAP_LOG(NWRAP_LOG_ERROR,
2265                                   "inact -- Invalid line[%s]: '%s'",
2266                                   line,
2267                                   c);
2268                         return false;
2269                 }
2270                 *p = '\0';
2271                 p++;
2272                 sp->sp_inact = strtol(c, &e, 10);
2273                 if (c == e) {
2274                         NWRAP_LOG(NWRAP_LOG_ERROR,
2275                                   "inact -- Invalid line[%s]: '%s' - %s",
2276                                   line, c, strerror(errno));
2277                         return false;
2278                 }
2279                 if (e == NULL) {
2280                         NWRAP_LOG(NWRAP_LOG_ERROR,
2281                                   "inact -- Invalid line[%s]: '%s' - %s",
2282                                   line, c, strerror(errno));
2283                         return false;
2284                 }
2285                 if (e[0] != '\0') {
2286                         NWRAP_LOG(NWRAP_LOG_ERROR,
2287                                   "inact -- Invalid line[%s]: '%s' - %s",
2288                                   line, c, strerror(errno));
2289                         return false;
2290                 }
2291         }
2292         c = p;
2293
2294         /* expire (long) */
2295         if (c[0] == ':') {
2296                 sp->sp_expire = -1;
2297                 p++;
2298         } else {
2299                 p = strchr(c, ':');
2300                 if (p == NULL) {
2301                         NWRAP_LOG(NWRAP_LOG_ERROR,
2302                                   "expire -- Invalid line[%s]: '%s'",
2303                                   line,
2304                                   c);
2305                         return false;
2306                 }
2307                 *p = '\0';
2308                 p++;
2309                 sp->sp_expire = strtol(c, &e, 10);
2310                 if (c == e) {
2311                         NWRAP_LOG(NWRAP_LOG_ERROR,
2312                                   "expire -- Invalid line[%s]: '%s' - %s",
2313                                   line, c, strerror(errno));
2314                         return false;
2315                 }
2316                 if (e == NULL) {
2317                         NWRAP_LOG(NWRAP_LOG_ERROR,
2318                                   "expire -- Invalid line[%s]: '%s' - %s",
2319                                   line, c, strerror(errno));
2320                         return false;
2321                 }
2322                 if (e[0] != '\0') {
2323                         NWRAP_LOG(NWRAP_LOG_ERROR,
2324                                   "expire -- Invalid line[%s]: '%s' - %s",
2325                                   line, c, strerror(errno));
2326                         return false;
2327                 }
2328         }
2329         c = p;
2330
2331         nwrap_sp->num++;
2332         return true;
2333 }
2334
2335 static void nwrap_sp_unload(struct nwrap_cache *nwrap)
2336 {
2337         struct nwrap_sp *nwrap_sp;
2338         nwrap_sp = (struct nwrap_sp *)nwrap->private_data;
2339
2340         SAFE_FREE(nwrap_sp->list);
2341         nwrap_sp->num = 0;
2342         nwrap_sp->idx = 0;
2343 }
2344 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
2345
2346 /*
2347  * the caller has to call nwrap_unload() on failure
2348  */
2349 static bool nwrap_gr_parse_line(struct nwrap_cache *nwrap, char *line)
2350 {
2351         struct nwrap_gr *nwrap_gr;
2352         char *c;
2353         char *p;
2354         char *e;
2355         struct group *gr;
2356         size_t list_size;
2357         unsigned nummem;
2358
2359         nwrap_gr = (struct nwrap_gr *)nwrap->private_data;
2360
2361         list_size = sizeof(*nwrap_gr->list) * (nwrap_gr->num+1);
2362         gr = (struct group *)realloc(nwrap_gr->list, list_size);
2363         if (!gr) {
2364                 NWRAP_LOG(NWRAP_LOG_ERROR, "realloc failed");
2365                 return false;
2366         }
2367         nwrap_gr->list = gr;
2368
2369         gr = &nwrap_gr->list[nwrap_gr->num];
2370
2371         c = line;
2372
2373         /* name */
2374         p = strchr(c, ':');
2375         if (!p) {
2376                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2377                 return false;
2378         }
2379         *p = '\0';
2380         p++;
2381         gr->gr_name = c;
2382         c = p;
2383
2384         NWRAP_LOG(NWRAP_LOG_TRACE, "name[%s]", gr->gr_name);
2385
2386         /* password */
2387         p = strchr(c, ':');
2388         if (!p) {
2389                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2390                 return false;
2391         }
2392         *p = '\0';
2393         p++;
2394         gr->gr_passwd = c;
2395         c = p;
2396
2397         NWRAP_LOG(NWRAP_LOG_TRACE, "password[%s]", gr->gr_passwd);
2398
2399         /* gid */
2400         p = strchr(c, ':');
2401         if (!p) {
2402                 NWRAP_LOG(NWRAP_LOG_ERROR, "Invalid line[%s]: '%s'", line, c);
2403                 return false;
2404         }
2405         *p = '\0';
2406         p++;
2407         e = NULL;
2408         gr->gr_gid = (gid_t)strtoul(c, &e, 10);
2409         if (c == e) {
2410                 NWRAP_LOG(NWRAP_LOG_ERROR,
2411                           "Invalid line[%s]: '%s' - %s",
2412                           line, c, strerror(errno));
2413                 return false;
2414         }
2415         if (e == NULL) {
2416                 NWRAP_LOG(NWRAP_LOG_ERROR,
2417                           "Invalid line[%s]: '%s' - %s",
2418                           line, c, strerror(errno));
2419                 return false;
2420         }
2421         if (e[0] != '\0') {
2422                 NWRAP_LOG(NWRAP_LOG_ERROR,
2423                           "Invalid line[%s]: '%s' - %s",
2424                           line, c, strerror(errno));
2425                 return false;
2426         }
2427         c = p;
2428
2429         NWRAP_LOG(NWRAP_LOG_TRACE, "gid[%u]", gr->gr_gid);
2430
2431         /* members */
2432         gr->gr_mem = (char **)malloc(sizeof(char *));
2433         if (!gr->gr_mem) {
2434                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
2435                 return false;
2436         }
2437         gr->gr_mem[0] = NULL;
2438
2439         for(nummem=0; p; nummem++) {
2440                 char **m;
2441                 size_t m_size;
2442                 c = p;
2443                 p = strchr(c, ',');
2444                 if (p) {
2445                         *p = '\0';
2446                         p++;
2447                 }
2448
2449                 if (strlen(c) == 0) {
2450                         break;
2451                 }
2452
2453                 m_size = sizeof(char *) * (nummem+2);
2454                 m = (char **)realloc(gr->gr_mem, m_size);
2455                 if (!m) {
2456                         NWRAP_LOG(NWRAP_LOG_ERROR,
2457                                   "realloc(%zd) failed",
2458                                   m_size);
2459                         return false;
2460                 }
2461                 gr->gr_mem = m;
2462                 gr->gr_mem[nummem] = c;
2463                 gr->gr_mem[nummem+1] = NULL;
2464
2465                 NWRAP_LOG(NWRAP_LOG_TRACE,
2466                           "member[%u]: '%s'",
2467                           nummem, gr->gr_mem[nummem]);
2468         }
2469
2470         NWRAP_LOG(NWRAP_LOG_DEBUG,
2471                   "Added group[%s:%s:%u:] with %u members",
2472                   gr->gr_name, gr->gr_passwd, gr->gr_gid, nummem);
2473
2474         nwrap_gr->num++;
2475         return true;
2476 }
2477
2478 static void nwrap_gr_unload(struct nwrap_cache *nwrap)
2479 {
2480         int i;
2481         struct nwrap_gr *nwrap_gr;
2482         nwrap_gr = (struct nwrap_gr *)nwrap->private_data;
2483
2484         if (nwrap_gr->list) {
2485                 for (i=0; i < nwrap_gr->num; i++) {
2486                         SAFE_FREE(nwrap_gr->list[i].gr_mem);
2487                 }
2488                 SAFE_FREE(nwrap_gr->list);
2489         }
2490
2491         nwrap_gr->num = 0;
2492         nwrap_gr->idx = 0;
2493 }
2494
2495 static int nwrap_gr_copy_r(const struct group *src, struct group *dst,
2496                            char *buf, size_t buflen, struct group **dstp)
2497 {
2498         char *first;
2499         char **lastm;
2500         char *last = NULL;
2501         off_t ofsb;
2502         off_t ofsm;
2503         off_t ofs;
2504         unsigned i;
2505
2506         first = src->gr_name;
2507
2508         lastm = src->gr_mem;
2509         while (*lastm) {
2510                 last = *lastm;
2511                 lastm++;
2512         }
2513
2514         if (last == NULL) {
2515                 last = src->gr_passwd;
2516         }
2517         while (*last) last++;
2518
2519         ofsb = PTR_DIFF(last + 1, first);
2520         ofsm = PTR_DIFF(lastm + 1, src->gr_mem);
2521
2522         if ((ofsb + ofsm) > (off_t) buflen) {
2523                 return ERANGE;
2524         }
2525
2526         memcpy(buf, first, ofsb);
2527         memcpy(buf + ofsb, src->gr_mem, ofsm);
2528
2529         ofs = PTR_DIFF(src->gr_name, first);
2530         dst->gr_name = buf + ofs;
2531         ofs = PTR_DIFF(src->gr_passwd, first);
2532         dst->gr_passwd = buf + ofs;
2533         dst->gr_gid = src->gr_gid;
2534
2535         dst->gr_mem = (char **)(buf + ofsb);
2536         for (i=0; src->gr_mem[i]; i++) {
2537                 ofs = PTR_DIFF(src->gr_mem[i], first);
2538                 dst->gr_mem[i] = buf + ofs;
2539         }
2540
2541         if (dstp) {
2542                 *dstp = dst;
2543         }
2544
2545         return 0;
2546 }
2547
2548 static struct nwrap_entlist *nwrap_entlist_init(struct nwrap_entdata *ed)
2549 {
2550         struct nwrap_entlist *el;
2551
2552         if (ed == NULL) {
2553                 NWRAP_LOG(NWRAP_LOG_ERROR,
2554                           "entry is NULL, can't create list item");
2555                 return NULL;
2556         }
2557
2558         el = (struct nwrap_entlist *)malloc(sizeof(struct nwrap_entlist));
2559         if (el == NULL) {
2560                 NWRAP_LOG(NWRAP_LOG_ERROR, "malloc failed");
2561                 return NULL;
2562         }
2563
2564         el->next = NULL;
2565         el->ed = ed;
2566
2567         return el;
2568 }
2569
2570 static bool nwrap_ed_inventarize_add_new(char *const h_name,
2571                                          struct nwrap_entdata *const ed)
2572 {
2573         ENTRY e;
2574         ENTRY *p;
2575         struct nwrap_entlist *el;
2576
2577         if (h_name == NULL) {
2578                 NWRAP_LOG(NWRAP_LOG_ERROR, "h_name NULL - can't add");
2579                 return false;
2580         }
2581
2582         el = nwrap_entlist_init(ed);
2583         if (el == NULL) {
2584                 return false;
2585         }
2586
2587         e.key = h_name;
2588         e.data = (void *)el;
2589
2590         p = hsearch(e, ENTER);
2591         if (p == NULL) {
2592                 NWRAP_LOG(NWRAP_LOG_ERROR, "Hash table is full!");
2593                 return false;
2594         }
2595
2596         return true;
2597 }
2598
2599 static bool nwrap_ed_inventarize_add_to_existing(struct nwrap_entdata *const ed,
2600                                                  struct nwrap_entlist *const el)
2601 {
2602         struct nwrap_entlist *cursor;
2603         struct nwrap_entlist *el_new;
2604
2605         if (el == NULL) {
2606                 NWRAP_LOG(NWRAP_LOG_ERROR, "list is NULL, can not add");
2607                 return false;
2608         }
2609
2610         el_new = nwrap_entlist_init(ed);
2611         if (el_new == NULL) {
2612                 return false;
2613         }
2614
2615         for (cursor = el; cursor->next != NULL; cursor = cursor->next)
2616         {
2617                 if (cursor->ed == ed) {
2618                         free(el_new);
2619                         return false;
2620                 }
2621         }
2622
2623         if (cursor->ed == ed) {
2624                 free(el_new);
2625                 return false;
2626         }
2627
2628         cursor->next = el_new;
2629         return true;
2630 }
2631
2632 static bool nwrap_ed_inventarize(char *const name,
2633                                  struct nwrap_entdata *const ed)
2634 {
2635         ENTRY e;
2636         ENTRY *p;
2637         bool ok;
2638
2639         e.key = name;
2640         e.data = NULL;
2641
2642         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching name: %s", e.key);
2643
2644         p = hsearch(e, FIND);
2645         if (p == NULL) {
2646                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found. Adding...", name);
2647                 ok = nwrap_ed_inventarize_add_new(name, ed);
2648         } else {
2649                 struct nwrap_entlist *el = (struct nwrap_entlist *)p->data;
2650
2651                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s found. Add record to list.", name);
2652                 ok = nwrap_ed_inventarize_add_to_existing(ed, el);
2653         }
2654
2655         return ok;
2656 }
2657
2658 static bool nwrap_add_hname(struct nwrap_entdata *const ed)
2659 {
2660         char *const h_name = (char *const)(ed->ht.h_name);
2661         unsigned i;
2662         bool ok;
2663
2664         ok = nwrap_ed_inventarize(h_name, ed);
2665         if (!ok) {
2666                 return false;
2667         }
2668
2669         if (ed->ht.h_aliases == NULL) {
2670                 return true;
2671         }
2672
2673         /* Itemize aliases */
2674         for (i = 0; ed->ht.h_aliases[i] != NULL; ++i) {
2675                 char *h_name_alias;
2676
2677                 h_name_alias = ed->ht.h_aliases[i];
2678
2679                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Add alias: %s", h_name_alias);
2680
2681                 if (!nwrap_ed_inventarize(h_name_alias, ed)) {
2682                         NWRAP_LOG(NWRAP_LOG_ERROR,
2683                                   "Unable to add alias: %s", h_name_alias);
2684                         return false;
2685                 }
2686         }
2687
2688         return true;
2689 }
2690
2691 static bool nwrap_he_parse_line(struct nwrap_cache *nwrap, char *line)
2692 {
2693         struct nwrap_he *nwrap_he = (struct nwrap_he *)nwrap->private_data;
2694         bool do_aliases = true;
2695         ssize_t aliases_count = 0;
2696         char *p;
2697         char *i;
2698         char *n;
2699
2700         char *ip;
2701         bool ok;
2702
2703         struct nwrap_entdata *ed = (struct nwrap_entdata *)
2704                                    malloc(sizeof(struct nwrap_entdata));
2705         if (ed == NULL) {
2706                 NWRAP_LOG(NWRAP_LOG_ERROR,
2707                           "Unable to allocate memory for nwrap_entdata");
2708                 return false;
2709         }
2710         ZERO_STRUCTP(ed);
2711
2712         i = line;
2713
2714         /*
2715          * IP
2716          */
2717
2718         /* Walk to first char */
2719         for (p = i; *p != '.' && *p != ':' && !isxdigit((int) *p); p++) {
2720                 if (*p == '\0') {
2721                         NWRAP_LOG(NWRAP_LOG_ERROR,
2722                                   "Invalid line[%s]: '%s'",
2723                                   line, i);
2724                         free(ed);
2725                         return false;
2726                 }
2727         }
2728
2729         for (i = p; !isspace((int)*p); p++) {
2730                 if (*p == '\0') {
2731                         NWRAP_LOG(NWRAP_LOG_ERROR,
2732                                   "Invalid line[%s]: '%s'",
2733                                   line, i);
2734                         free(ed);
2735                         return false;
2736                 }
2737         }
2738
2739         *p = '\0';
2740
2741         if (inet_pton(AF_INET, i, ed->addr.host_addr)) {
2742                 ed->ht.h_addrtype = AF_INET;
2743                 ed->ht.h_length = 4;
2744 #ifdef HAVE_IPV6
2745         } else if (inet_pton(AF_INET6, i, ed->addr.host_addr)) {
2746                 ed->ht.h_addrtype = AF_INET6;
2747                 ed->ht.h_length = 16;
2748 #endif
2749         } else {
2750                 NWRAP_LOG(NWRAP_LOG_ERROR,
2751                           "Invalid line[%s]: '%s'",
2752                           line, i);
2753
2754                 free(ed);
2755                 return false;
2756         }
2757         ip = i;
2758
2759         nwrap_vector_add_item(&(ed->nwrap_addrdata),
2760                               (void *const)ed->addr.host_addr);
2761         ed->ht.h_addr_list = nwrap_vector_head(&ed->nwrap_addrdata);
2762
2763         p++;
2764
2765         /*
2766          * FQDN
2767          */
2768
2769         /* Walk to first char */
2770         for (n = p; *p != '_' && !isalnum((int) *p); p++) {
2771                 if (*p == '\0') {
2772                         NWRAP_LOG(NWRAP_LOG_ERROR,
2773                                   "Invalid line[%s]: '%s'",
2774                                   line, n);
2775
2776                         free(ed);
2777                         return false;
2778                 }
2779         }
2780
2781         for (n = p; !isspace((int)*p); p++) {
2782                 if (*p == '\0') {
2783                         do_aliases = false;
2784                         break;
2785                 }
2786         }
2787
2788         *p = '\0';
2789
2790         /* Convert to lowercase. This operate on same memory region */
2791         str_tolower(n, n);
2792         ed->ht.h_name = n;
2793
2794         /* glib's getent always dereferences he->h_aliases */
2795         ed->ht.h_aliases = malloc(sizeof(char *));
2796         if (ed->ht.h_aliases == NULL) {
2797                 free(ed);
2798                 return false;
2799         }
2800         ed->ht.h_aliases[0] = NULL;
2801
2802         /*
2803          * Aliases
2804          */
2805         while (do_aliases) {
2806                 char **aliases;
2807                 char *a;
2808
2809                 p++;
2810
2811                 /* Walk to first char */
2812                 for (a = p; *p != '_' && !isalnum((int) *p); p++) {
2813                         if (*p == '\0') {
2814                                 do_aliases = false;
2815                                 break;
2816                         }
2817                 }
2818                 /* Only trailing spaces are left */
2819                 if (!do_aliases) {
2820                         break;
2821                 }
2822
2823                 for (a = p; !isspace((int)*p); p++) {
2824                         if (*p == '\0') {
2825                                 do_aliases = false;
2826                                 break;
2827                         }
2828                 }
2829
2830                 *p = '\0';
2831
2832                 aliases = realloc(ed->ht.h_aliases, sizeof(char *) * (aliases_count + 2));
2833                 if (aliases == NULL) {
2834                         free(ed);
2835                         return false;
2836                 }
2837                 ed->ht.h_aliases = aliases;
2838
2839                 str_tolower(a, a);
2840                 aliases[aliases_count] = a;
2841                 aliases[aliases_count + 1] = NULL;
2842
2843                 aliases_count += 1;
2844         }
2845
2846         nwrap_vector_add_item(&(nwrap_he->entdata), (void *const)ed);
2847
2848         ed->aliases_count = aliases_count;
2849         /* Inventarize item */
2850         ok = nwrap_add_hname(ed);
2851         if (!ok) {
2852                 return false;
2853         }
2854
2855         ok = nwrap_ed_inventarize(ip, ed);
2856         if (!ok) {
2857                 return false;
2858         }
2859
2860         nwrap_he->num++;
2861         return true;
2862 }
2863
2864 static void nwrap_he_unload(struct nwrap_cache *nwrap)
2865 {
2866         struct nwrap_he *nwrap_he =
2867                 (struct nwrap_he *)nwrap->private_data;
2868         struct nwrap_entdata *ed;
2869         size_t i;
2870
2871         nwrap_vector_foreach (ed, nwrap_he->entdata, i)
2872         {
2873                 SAFE_FREE(ed->nwrap_addrdata.items);
2874                 SAFE_FREE(ed->ht.h_aliases);
2875                 SAFE_FREE(ed);
2876         }
2877         SAFE_FREE(nwrap_he->entdata.items);
2878         nwrap_he->entdata.count = nwrap_he->entdata.capacity = 0;
2879
2880         nwrap_he->num = 0;
2881         nwrap_he->idx = 0;
2882 }
2883
2884
2885 /* user functions */
2886 static struct passwd *nwrap_files_getpwnam(struct nwrap_backend *b,
2887                                            const char *name)
2888 {
2889         int i;
2890         bool ok;
2891
2892         (void) b; /* unused */
2893
2894         NWRAP_LOG(NWRAP_LOG_DEBUG, "Lookup user %s in files", name);
2895
2896         ok = nwrap_files_cache_reload(nwrap_pw_global.cache);
2897         if (!ok) {
2898                 NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading passwd file");
2899                 return NULL;
2900         }
2901
2902         for (i=0; i<nwrap_pw_global.num; i++) {
2903                 if (strcmp(nwrap_pw_global.list[i].pw_name, name) == 0) {
2904                         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] found", name);
2905                         return &nwrap_pw_global.list[i];
2906                 }
2907                 NWRAP_LOG(NWRAP_LOG_DEBUG,
2908                           "user[%s] does not match [%s]",
2909                           name,
2910                           nwrap_pw_global.list[i].pw_name);
2911         }
2912
2913         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] not found\n", name);
2914
2915         errno = ENOENT;
2916         return NULL;
2917 }
2918
2919 static int nwrap_files_getpwnam_r(struct nwrap_backend *b,
2920                                   const char *name, struct passwd *pwdst,
2921                                   char *buf, size_t buflen, struct passwd **pwdstp)
2922 {
2923         struct passwd *pw;
2924
2925         pw = nwrap_files_getpwnam(b, name);
2926         if (!pw) {
2927                 if (errno == 0) {
2928                         return ENOENT;
2929                 }
2930                 return errno;
2931         }
2932
2933         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
2934 }
2935
2936 static struct passwd *nwrap_files_getpwuid(struct nwrap_backend *b,
2937                                            uid_t uid)
2938 {
2939         int i;
2940         bool ok;
2941
2942         (void) b; /* unused */
2943
2944         ok = nwrap_files_cache_reload(nwrap_pw_global.cache);
2945         if (!ok) {
2946                 NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading passwd file");
2947                 return NULL;
2948         }
2949
2950         for (i=0; i<nwrap_pw_global.num; i++) {
2951                 if (nwrap_pw_global.list[i].pw_uid == uid) {
2952                         NWRAP_LOG(NWRAP_LOG_DEBUG, "uid[%u] found", uid);
2953                         return &nwrap_pw_global.list[i];
2954                 }
2955                 NWRAP_LOG(NWRAP_LOG_DEBUG,
2956                           "uid[%u] does not match [%u]",
2957                           uid,
2958                           nwrap_pw_global.list[i].pw_uid);
2959         }
2960
2961         NWRAP_LOG(NWRAP_LOG_DEBUG, "uid[%u] not found\n", uid);
2962
2963         errno = ENOENT;
2964         return NULL;
2965 }
2966
2967 static int nwrap_files_getpwuid_r(struct nwrap_backend *b,
2968                                   uid_t uid, struct passwd *pwdst,
2969                                   char *buf, size_t buflen, struct passwd **pwdstp)
2970 {
2971         struct passwd *pw;
2972
2973         pw = nwrap_files_getpwuid(b, uid);
2974         if (!pw) {
2975                 if (errno == 0) {
2976                         return ENOENT;
2977                 }
2978                 return errno;
2979         }
2980
2981         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
2982 }
2983
2984 /* user enum functions */
2985 static void nwrap_files_setpwent(struct nwrap_backend *b)
2986 {
2987         (void) b; /* unused */
2988
2989         nwrap_pw_global.idx = 0;
2990 }
2991
2992 static struct passwd *nwrap_files_getpwent(struct nwrap_backend *b)
2993 {
2994         struct passwd *pw;
2995
2996         (void) b; /* unused */
2997
2998         if (nwrap_pw_global.idx == 0) {
2999                 bool ok;
3000                 ok = nwrap_files_cache_reload(nwrap_pw_global.cache);
3001                 if (!ok) {
3002                         NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading passwd file");
3003                         return NULL;
3004                 }
3005         }
3006
3007         if (nwrap_pw_global.idx >= nwrap_pw_global.num) {
3008                 errno = ENOENT;
3009                 return NULL;
3010         }
3011
3012         pw = &nwrap_pw_global.list[nwrap_pw_global.idx++];
3013
3014         NWRAP_LOG(NWRAP_LOG_DEBUG,
3015                   "return user[%s] uid[%u]",
3016                   pw->pw_name, pw->pw_uid);
3017
3018         return pw;
3019 }
3020
3021 static int nwrap_files_getpwent_r(struct nwrap_backend *b,
3022                                   struct passwd *pwdst, char *buf,
3023                                   size_t buflen, struct passwd **pwdstp)
3024 {
3025         struct passwd *pw;
3026
3027         pw = nwrap_files_getpwent(b);
3028         if (!pw) {
3029                 if (errno == 0) {
3030                         return ENOENT;
3031                 }
3032                 return errno;
3033         }
3034
3035         return nwrap_pw_copy_r(pw, pwdst, buf, buflen, pwdstp);
3036 }
3037
3038 static void nwrap_files_endpwent(struct nwrap_backend *b)
3039 {
3040         (void) b; /* unused */
3041
3042         nwrap_pw_global.idx = 0;
3043 }
3044
3045 /* shadow */
3046
3047 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
3048
3049 #ifdef HAVE_SETSPENT
3050 static void nwrap_files_setspent(void)
3051 {
3052         nwrap_sp_global.idx = 0;
3053 }
3054
3055 static struct spwd *nwrap_files_getspent(void)
3056 {
3057         struct spwd *sp;
3058
3059         if (nwrap_sp_global.idx == 0) {
3060                 bool ok;
3061
3062                 ok = nwrap_files_cache_reload(nwrap_sp_global.cache);
3063                 if (!ok) {
3064                         NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading shadow file");
3065                         return NULL;
3066                 }
3067         }
3068
3069         if (nwrap_sp_global.idx >= nwrap_sp_global.num) {
3070                 errno = ENOENT;
3071                 return NULL;
3072         }
3073
3074         sp = &nwrap_sp_global.list[nwrap_sp_global.idx++];
3075
3076         NWRAP_LOG(NWRAP_LOG_DEBUG,
3077                   "return user[%s]",
3078                   sp->sp_namp);
3079
3080         return sp;
3081 }
3082
3083 static void nwrap_files_endspent(void)
3084 {
3085         nwrap_sp_global.idx = 0;
3086 }
3087 #endif /* HAVE_SETSPENT */
3088
3089 static struct spwd *nwrap_files_getspnam(const char *name)
3090 {
3091         int i;
3092         bool ok;
3093
3094         NWRAP_LOG(NWRAP_LOG_DEBUG, "Lookup user %s in files", name);
3095
3096         ok = nwrap_files_cache_reload(nwrap_sp_global.cache);
3097         if (!ok) {
3098                 NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading shadow file");
3099                 return NULL;
3100         }
3101
3102         for (i=0; i<nwrap_sp_global.num; i++) {
3103                 if (strcmp(nwrap_sp_global.list[i].sp_namp, name) == 0) {
3104                         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] found", name);
3105                         return &nwrap_sp_global.list[i];
3106                 }
3107                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3108                           "user[%s] does not match [%s]",
3109                           name,
3110                           nwrap_sp_global.list[i].sp_namp);
3111         }
3112
3113         NWRAP_LOG(NWRAP_LOG_DEBUG, "user[%s] not found\n", name);
3114
3115         errno = ENOENT;
3116         return NULL;
3117 }
3118 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
3119
3120 /* misc functions */
3121 static int nwrap_files_initgroups(struct nwrap_backend *b,
3122                                   const char *user,
3123                                   gid_t group)
3124 {
3125         struct group *grp;
3126         gid_t *groups;
3127         int size = 1;
3128         int rc;
3129
3130         groups = (gid_t *)malloc(size * sizeof(gid_t));
3131         if (groups == NULL) {
3132                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
3133                 errno = ENOMEM;
3134                 return -1;
3135         }
3136         groups[0] = group;
3137
3138         nwrap_files_setgrent(b);
3139         while ((grp = nwrap_files_getgrent(b)) != NULL) {
3140                 int i = 0;
3141
3142                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3143                           "Inspecting %s for group membership",
3144                           grp->gr_name);
3145
3146                 for (i=0; grp->gr_mem && grp->gr_mem[i] != NULL; i++) {
3147                         if (group != grp->gr_gid &&
3148                             (strcmp(user, grp->gr_mem[i]) == 0)) {
3149                                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3150                                           "%s is member of %s",
3151                                           user,
3152                                           grp->gr_name);
3153
3154                                 groups = (gid_t *)realloc(groups,
3155                                                           (size + 1) * sizeof(gid_t));
3156                                 if (groups == NULL) {
3157                                         NWRAP_LOG(NWRAP_LOG_ERROR,
3158                                                   "Out of memory");
3159                                         errno = ENOMEM;
3160                                         return -1;
3161                                 }
3162
3163                                 groups[size] = grp->gr_gid;
3164                                 size++;
3165                         }
3166                 }
3167         }
3168
3169         nwrap_files_endgrent(b);
3170
3171         NWRAP_LOG(NWRAP_LOG_DEBUG,
3172                   "%s is member of %d groups",
3173                   user, size);
3174
3175         /* This really only works if uid_wrapper is loaded */
3176         rc = setgroups(size, groups);
3177
3178         free(groups);
3179
3180         return rc;
3181 }
3182
3183 /* group functions */
3184 static struct group *nwrap_files_getgrnam(struct nwrap_backend *b,
3185                                           const char *name)
3186 {
3187         int i;
3188         bool ok;
3189
3190         (void) b; /* unused */
3191
3192         ok = nwrap_files_cache_reload(nwrap_gr_global.cache);
3193         if (!ok) {
3194                 NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading group file");
3195                 return NULL;
3196         }
3197
3198         for (i=0; i<nwrap_gr_global.num; i++) {
3199                 if (strcmp(nwrap_gr_global.list[i].gr_name, name) == 0) {
3200                         NWRAP_LOG(NWRAP_LOG_DEBUG, "group[%s] found", name);
3201                         return &nwrap_gr_global.list[i];
3202                 }
3203                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3204                           "group[%s] does not match [%s]",
3205                           name,
3206                           nwrap_gr_global.list[i].gr_name);
3207         }
3208
3209         NWRAP_LOG(NWRAP_LOG_DEBUG, "group[%s] not found", name);
3210
3211         errno = ENOENT;
3212         return NULL;
3213 }
3214
3215 static int nwrap_files_getgrnam_r(struct nwrap_backend *b,
3216                                   const char *name, struct group *grdst,
3217                                   char *buf, size_t buflen, struct group **grdstp)
3218 {
3219         struct group *gr;
3220
3221         gr = nwrap_files_getgrnam(b, name);
3222         if (!gr) {
3223                 if (errno == 0) {
3224                         return ENOENT;
3225                 }
3226                 return errno;
3227         }
3228
3229         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3230 }
3231
3232 static struct group *nwrap_files_getgrgid(struct nwrap_backend *b,
3233                                           gid_t gid)
3234 {
3235         int i;
3236         bool ok;
3237
3238         (void) b; /* unused */
3239
3240         ok = nwrap_files_cache_reload(nwrap_gr_global.cache);
3241         if (!ok) {
3242                 NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading group file");
3243                 return NULL;
3244         }
3245
3246         for (i=0; i<nwrap_gr_global.num; i++) {
3247                 if (nwrap_gr_global.list[i].gr_gid == gid) {
3248                         NWRAP_LOG(NWRAP_LOG_DEBUG, "gid[%u] found", gid);
3249                         return &nwrap_gr_global.list[i];
3250                 }
3251                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3252                           "gid[%u] does not match [%u]",
3253                           gid,
3254                           nwrap_gr_global.list[i].gr_gid);
3255         }
3256
3257         NWRAP_LOG(NWRAP_LOG_DEBUG, "gid[%u] not found", gid);
3258
3259         errno = ENOENT;
3260         return NULL;
3261 }
3262
3263 static int nwrap_files_getgrgid_r(struct nwrap_backend *b,
3264                                   gid_t gid, struct group *grdst,
3265                                   char *buf, size_t buflen, struct group **grdstp)
3266 {
3267         struct group *gr;
3268
3269         gr = nwrap_files_getgrgid(b, gid);
3270         if (!gr) {
3271                 if (errno == 0) {
3272                         return ENOENT;
3273                 }
3274                 return errno;
3275         }
3276
3277         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3278 }
3279
3280 /* group enum functions */
3281 static void nwrap_files_setgrent(struct nwrap_backend *b)
3282 {
3283         (void) b; /* unused */
3284
3285         nwrap_gr_global.idx = 0;
3286 }
3287
3288 static struct group *nwrap_files_getgrent(struct nwrap_backend *b)
3289 {
3290         struct group *gr;
3291
3292         (void) b; /* unused */
3293
3294         if (nwrap_gr_global.idx == 0) {
3295                 bool ok;
3296
3297                 ok = nwrap_files_cache_reload(nwrap_gr_global.cache);
3298                 if (!ok) {
3299                         NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading group file");
3300                         return NULL;
3301                 }
3302         }
3303
3304         if (nwrap_gr_global.idx >= nwrap_gr_global.num) {
3305                 errno = ENOENT;
3306                 return NULL;
3307         }
3308
3309         gr = &nwrap_gr_global.list[nwrap_gr_global.idx++];
3310
3311         NWRAP_LOG(NWRAP_LOG_DEBUG,
3312                   "return group[%s] gid[%u]",
3313                   gr->gr_name, gr->gr_gid);
3314
3315         return gr;
3316 }
3317
3318 static int nwrap_files_getgrent_r(struct nwrap_backend *b,
3319                                   struct group *grdst, char *buf,
3320                                   size_t buflen, struct group **grdstp)
3321 {
3322         struct group *gr;
3323
3324         gr = nwrap_files_getgrent(b);
3325         if (!gr) {
3326                 if (errno == 0) {
3327                         return ENOENT;
3328                 }
3329                 return errno;
3330         }
3331
3332         return nwrap_gr_copy_r(gr, grdst, buf, buflen, grdstp);
3333 }
3334
3335 static void nwrap_files_endgrent(struct nwrap_backend *b)
3336 {
3337         (void) b; /* unused */
3338
3339         nwrap_gr_global.idx = 0;
3340 }
3341
3342 /* hosts functions */
3343 static int nwrap_files_gethostbyname(const char *name, int af,
3344                                      struct hostent *result,
3345                                      struct nwrap_vector *addr_list)
3346 {
3347         struct nwrap_entlist *el;
3348         struct hostent *he;
3349         char *h_name_lower;
3350         ENTRY e;
3351         ENTRY *e_p;
3352         char canon_name[DNS_NAME_MAX] = { 0 };
3353         size_t name_len;
3354         bool he_found = false;
3355         bool ok;
3356
3357         ok = nwrap_files_cache_reload(nwrap_he_global.cache);
3358         if (!ok) {
3359                 NWRAP_LOG(NWRAP_LOG_ERROR, "error loading hosts file");
3360                 goto no_ent;
3361         }
3362
3363         name_len = strlen(name);
3364         if (name_len < sizeof(canon_name) && name[name_len - 1] == '.') {
3365                 strncpy(canon_name, name, name_len - 1);
3366                 name = canon_name;
3367         }
3368
3369         if (!str_tolower_copy(&h_name_lower, name)) {
3370                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3371                           "Out of memory while converting to lower case");
3372                 goto no_ent;
3373         }
3374
3375         /* Look at hash table for element */
3376         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching for name: %s", h_name_lower);
3377         e.key = h_name_lower;
3378         e.data = NULL;
3379         e_p = hsearch(e, FIND);
3380         if (e_p == NULL) {
3381                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found.", h_name_lower);
3382                 SAFE_FREE(h_name_lower);
3383                 goto no_ent;
3384         }
3385         SAFE_FREE(h_name_lower);
3386
3387         /* Always cleanup vector and results */
3388         if (!nwrap_vector_is_initialized(addr_list)) {
3389                 if (!nwrap_vector_init(addr_list)) {
3390                         NWRAP_LOG(NWRAP_LOG_DEBUG,
3391                                   "Unable to initialize memory for addr_list vector");
3392                         goto no_ent;
3393                 }
3394         } else {
3395                 /* When vector is initialized data are valid no more.
3396                  * Quick way how to free vector is: */
3397                 addr_list->count = 0;
3398         }
3399
3400         /* Iterate through results */
3401         for (el = (struct nwrap_entlist *)e_p->data; el != NULL; el = el->next)
3402         {
3403                 he = &(el->ed->ht);
3404
3405                 /* Filter by address familiy if provided */
3406                 if (af != AF_UNSPEC && he->h_addrtype != af) {
3407                         continue;
3408                 }
3409
3410                 /*
3411                  * GLIBC HACK?
3412                  * glibc doesn't return ipv6 addresses when AF_UNSPEC is used
3413                  */
3414                 if (af == AF_UNSPEC && he->h_addrtype != AF_INET) {
3415                         continue;
3416                 }
3417
3418                 if (!he_found) {
3419                         memcpy(result, he, sizeof(struct hostent));
3420                         NWRAP_LOG(NWRAP_LOG_DEBUG,
3421                                   "Name found. Returning record for %s",
3422                                   he->h_name);
3423                         he_found = true;
3424                 }
3425                 nwrap_vector_merge(addr_list, &el->ed->nwrap_addrdata);
3426                 result->h_addr_list = nwrap_vector_head(addr_list);
3427         }
3428
3429         if (he_found) {
3430                 return 0;
3431         }
3432         NWRAP_LOG(NWRAP_LOG_DEBUG,
3433                   "Name found in database. No records matches type.");
3434
3435 no_ent:
3436         errno = ENOENT;
3437         return -1;
3438 }
3439
3440 #ifdef HAVE_GETHOSTBYNAME_R
3441 static int nwrap_gethostbyname_r(const char *name,
3442                                  struct hostent *ret,
3443                                  char *buf, size_t buflen,
3444                                  struct hostent **result, int *h_errnop)
3445 {
3446         struct nwrap_vector *addr_list = malloc(sizeof(struct nwrap_vector));
3447         int rc;
3448
3449         if (addr_list == NULL) {
3450                 NWRAP_LOG(NWRAP_LOG_ERROR,
3451                           "Unable to allocate memory for address list");
3452                 errno = ENOENT;
3453                 return -1;
3454         }
3455
3456         ZERO_STRUCTP(addr_list);
3457
3458         rc = nwrap_files_gethostbyname(name, AF_UNSPEC, ret, addr_list);
3459         if (rc == -1) {
3460                 *h_errnop = h_errno;
3461                 if (addr_list->items != NULL) {
3462                         free(addr_list->items);
3463                 }
3464                 SAFE_FREE(addr_list);
3465                 errno = ENOENT;
3466                 return -1;
3467         }
3468
3469         if (buflen < (addr_list->count * sizeof(void *))) {
3470                 SAFE_FREE(addr_list->items);
3471                 SAFE_FREE(addr_list);
3472                 return ERANGE;
3473         }
3474
3475         /* Copy all to user provided buffer and change
3476          * pointers in returned structure.
3477          * +1 is for ending NULL pointer. */
3478         memcpy(buf, addr_list->items, (addr_list->count + 1) * sizeof(void *));
3479
3480         free(addr_list->items);
3481         free(addr_list);
3482
3483         ret->h_addr_list = (char **)buf;
3484         *result = ret;
3485         return 0;
3486 }
3487
3488 int gethostbyname_r(const char *name,
3489                     struct hostent *ret,
3490                     char *buf, size_t buflen,
3491                     struct hostent **result, int *h_errnop)
3492 {
3493         if (!nss_wrapper_hosts_enabled()) {
3494                 return libc_gethostbyname_r(name,
3495                                             ret,
3496                                             buf,
3497                                             buflen,
3498                                             result,
3499                                             h_errnop);
3500         }
3501
3502         return nwrap_gethostbyname_r(name, ret, buf, buflen, result, h_errnop);
3503 }
3504 #endif
3505
3506 static int nwrap_files_getaddrinfo(const char *name,
3507                                    unsigned short port,
3508                                    const struct addrinfo *hints,
3509                                    struct addrinfo **ai,
3510                                    struct addrinfo **ai_tail)
3511 {
3512         struct nwrap_entlist *el;
3513         struct hostent *he;
3514         struct addrinfo *ai_new = NULL;
3515         struct addrinfo *ai_head = NULL;
3516         struct addrinfo *ai_cur = NULL;
3517         char *h_name_lower;
3518         size_t name_len;
3519         char canon_name[DNS_NAME_MAX] = { 0 };
3520         bool skip_canonname = false;
3521         ENTRY e = { 0 };
3522         ENTRY *e_p = NULL;
3523         int rc;
3524         bool ok;
3525
3526         ok = nwrap_files_cache_reload(nwrap_he_global.cache);
3527         if (!ok) {
3528                 NWRAP_LOG(NWRAP_LOG_ERROR, "error loading hosts file");
3529                 return EAI_SYSTEM;
3530         }
3531
3532         name_len = strlen(name);
3533         if (name_len < DNS_NAME_MAX && name[name_len - 1] == '.') {
3534                 strncpy(canon_name, name, name_len - 1);
3535                 name = canon_name;
3536         }
3537
3538         if (!str_tolower_copy(&h_name_lower, name)) {
3539                 NWRAP_LOG(NWRAP_LOG_DEBUG,
3540                           "Out of memory while converting to lower case");
3541                 return EAI_MEMORY;
3542         }
3543
3544         NWRAP_LOG(NWRAP_LOG_DEBUG, "Searching for name: %s", h_name_lower);
3545         e.key = h_name_lower;
3546         e.data = NULL;
3547         e_p = hsearch(e, FIND);
3548         if (e_p == NULL) {
3549                 NWRAP_LOG(NWRAP_LOG_DEBUG, "Name %s not found.", h_name_lower);
3550                 SAFE_FREE(h_name_lower);
3551                 errno = ENOENT;
3552                 return EAI_NONAME;
3553         }
3554         NWRAP_LOG(NWRAP_LOG_DEBUG, "Name: %s found.", h_name_lower);
3555         SAFE_FREE(h_name_lower);
3556
3557         rc = EAI_NONAME;
3558         for (el = (struct nwrap_entlist *)e_p->data; el != NULL; el = el->next)
3559         {
3560                 int rc2;
3561
3562                 he = &(el->ed->ht);
3563
3564                 if (hints->ai_family != AF_UNSPEC &&
3565                     he->h_addrtype != hints->ai_family)
3566                 {
3567                         NWRAP_LOG(NWRAP_LOG_DEBUG,
3568                                   "Entry found but with wrong AF - "
3569                                   "remembering EAI_ADDRINFO.");
3570                         rc = EAI_ADDRFAMILY;
3571                         continue;
3572                 }
3573
3574                 /* Function allocates memory and returns it in ai. */
3575                 rc2 = nwrap_convert_he_ai(he,
3576                                          port,
3577                                          hints,
3578                                          &ai_new,
3579                                          skip_canonname);
3580                 if (rc2 != 0) {
3581                         NWRAP_LOG(NWRAP_LOG_ERROR, "Error converting he to ai");
3582                         if (ai_head != NULL) {
3583                                 freeaddrinfo(ai_head);
3584                         }
3585                         return rc2;
3586                 }
3587                 skip_canonname = true;
3588
3589                 if (ai_head == NULL) {
3590                         ai_head = ai_new;
3591                 }
3592                 if (ai_cur != NULL) {
3593                         ai_cur->ai_next = ai_new;
3594                 }
3595                 ai_cur = ai_new;
3596         }
3597
3598         if (ai_head != NULL) {
3599                 rc = 0;
3600         }
3601
3602         *ai = ai_head;
3603         *ai_tail = ai_new;
3604
3605         return rc;
3606 }
3607
3608 static struct hostent *nwrap_files_gethostbyaddr(const void *addr,
3609                                                  socklen_t len, int type)
3610 {
3611         struct hostent *he;
3612         char ip[NWRAP_INET_ADDRSTRLEN] = {0};
3613         struct nwrap_entdata *ed;
3614         const char *a;
3615         size_t i;
3616         bool ok;
3617
3618         (void) len; /* unused */
3619
3620         ok = nwrap_files_cache_reload(nwrap_he_global.cache);
3621         if (!ok) {
3622                 NWRAP_LOG(NWRAP_LOG_ERROR, "error loading hosts file");
3623                 return NULL;
3624         }
3625
3626         a = inet_ntop(type, addr, ip, sizeof(ip));
3627         if (a == NULL) {
3628                 errno = EINVAL;
3629                 return NULL;
3630         }
3631
3632         nwrap_vector_foreach(ed, nwrap_he_global.entdata, i)
3633         {
3634                 he = &(ed->ht);
3635                 if (he->h_addrtype != type) {
3636                         continue;
3637                 }
3638
3639                 if (memcmp(addr, he->h_addr_list[0], he->h_length) == 0) {
3640                         return he;
3641                 }
3642         }
3643
3644         errno = ENOENT;
3645         return NULL;
3646 }
3647
3648 #ifdef HAVE_GETHOSTBYADDR_R
3649 static int nwrap_gethostbyaddr_r(const void *addr, socklen_t len, int type,
3650                                  struct hostent *ret,
3651                                  char *buf, size_t buflen,
3652                                  struct hostent **result, int *h_errnop)
3653 {
3654         *result = nwrap_files_gethostbyaddr(addr, len, type);
3655         if (*result != NULL) {
3656                 memset(buf, '\0', buflen);
3657                 *ret = **result;
3658                 return 0;
3659         } else {
3660                 *h_errnop = h_errno;
3661                 return -1;
3662         }
3663 }
3664
3665 int gethostbyaddr_r(const void *addr, socklen_t len, int type,
3666                     struct hostent *ret,
3667                     char *buf, size_t buflen,
3668                     struct hostent **result, int *h_errnop)
3669 {
3670         if (!nss_wrapper_hosts_enabled()) {
3671                 return libc_gethostbyaddr_r(addr,
3672                                             len,
3673                                             type,
3674                                             ret,
3675                                             buf,
3676                                             buflen,
3677                                             result,
3678                                             h_errnop);
3679         }
3680
3681         return nwrap_gethostbyaddr_r(addr, len, type, ret, buf, buflen, result, h_errnop);
3682 }
3683 #endif
3684
3685 /* hosts enum functions */
3686 static void nwrap_files_sethostent(void)
3687 {
3688         nwrap_he_global.idx = 0;
3689 }
3690
3691 static struct hostent *nwrap_files_gethostent(void)
3692 {
3693         struct hostent *he;
3694
3695         if (nwrap_he_global.idx == 0) {
3696                 bool ok;
3697
3698                 ok = nwrap_files_cache_reload(nwrap_he_global.cache);
3699                 if (!ok) {
3700                         NWRAP_LOG(NWRAP_LOG_ERROR, "Error loading hosts file");
3701                         return NULL;
3702                 }
3703         }
3704
3705         if (nwrap_he_global.idx >= nwrap_he_global.num) {
3706                 errno = ENOENT;
3707                 return NULL;
3708         }
3709
3710         he = &((struct nwrap_entdata *)nwrap_he_global.entdata.items[nwrap_he_global.idx++])->ht;
3711
3712         NWRAP_LOG(NWRAP_LOG_DEBUG, "return hosts[%s]", he->h_name);
3713
3714         return he;
3715 }
3716
3717 static void nwrap_files_endhostent(void)
3718 {
3719         nwrap_he_global.idx = 0;
3720 }
3721
3722 /*
3723  * module backend
3724  */
3725
3726
3727 static struct passwd *nwrap_module_getpwnam(struct nwrap_backend *b,
3728                                             const char *name)
3729 {
3730         static struct passwd pwd;
3731         static char buf[1000];
3732         NSS_STATUS status;
3733
3734         if (!b->fns->_nss_getpwnam_r) {
3735                 return NULL;
3736         }
3737
3738         status = b->fns->_nss_getpwnam_r(name, &pwd, buf, sizeof(buf), &errno);
3739         if (status == NSS_STATUS_NOTFOUND) {
3740                 return NULL;
3741         }
3742         if (status != NSS_STATUS_SUCCESS) {
3743                 return NULL;
3744         }
3745
3746         return &pwd;
3747 }
3748
3749 static int nwrap_module_getpwnam_r(struct nwrap_backend *b,
3750                                    const char *name, struct passwd *pwdst,
3751                                    char *buf, size_t buflen, struct passwd **pwdstp)
3752 {
3753         int ret;
3754
3755         (void) b; /* unused */
3756         (void) pwdst; /* unused */
3757         (void) pwdstp; /* unused */
3758
3759         if (!b->fns->_nss_getpwnam_r) {
3760                 return NSS_STATUS_NOTFOUND;
3761         }
3762
3763         ret = b->fns->_nss_getpwnam_r(name, pwdst, buf, buflen, &errno);
3764         switch (ret) {
3765         case NSS_STATUS_SUCCESS:
3766                 return 0;
3767         case NSS_STATUS_NOTFOUND:
3768                 if (errno != 0) {
3769                         return errno;
3770                 }
3771                 return ENOENT;
3772         case NSS_STATUS_TRYAGAIN:
3773                 if (errno != 0) {
3774                         return errno;
3775                 }
3776                 return ERANGE;
3777         default:
3778                 if (errno != 0) {
3779                         return errno;
3780                 }
3781                 return ret;
3782         }
3783 }
3784
3785 static struct passwd *nwrap_module_getpwuid(struct nwrap_backend *b,
3786                                             uid_t uid)
3787 {
3788         static struct passwd pwd;
3789         static char buf[1000];
3790         NSS_STATUS status;
3791
3792         if (!b->fns->_nss_getpwuid_r) {
3793                 return NULL;
3794         }
3795
3796         status = b->fns->_nss_getpwuid_r(uid, &pwd, buf, sizeof(buf), &errno);
3797         if (status == NSS_STATUS_NOTFOUND) {
3798                 return NULL;
3799         }
3800         if (status != NSS_STATUS_SUCCESS) {
3801                 return NULL;
3802         }
3803         return &pwd;
3804 }
3805
3806 static int nwrap_module_getpwuid_r(struct nwrap_backend *b,
3807                                    uid_t uid, struct passwd *pwdst,
3808                                    char *buf, size_t buflen, struct passwd **pwdstp)
3809 {
3810         int ret;
3811
3812         (void) pwdstp; /* unused */
3813
3814         if (!b->fns->_nss_getpwuid_r) {
3815                 return ENOENT;
3816         }
3817
3818         ret = b->fns->_nss_getpwuid_r(uid, pwdst, buf, buflen, &errno);
3819         switch (ret) {
3820         case NSS_STATUS_SUCCESS:
3821                 return 0;
3822         case NSS_STATUS_NOTFOUND:
3823                 if (errno != 0) {
3824                         return errno;
3825                 }
3826                 return ENOENT;
3827         case NSS_STATUS_TRYAGAIN:
3828                 if (errno != 0) {
3829                         return errno;
3830                 }
3831                 return ERANGE;
3832         default:
3833                 if (errno != 0) {
3834                         return errno;
3835                 }
3836                 return ret;
3837         }
3838 }
3839
3840 static void nwrap_module_setpwent(struct nwrap_backend *b)
3841 {
3842         if (!b->fns->_nss_setpwent) {
3843                 return;
3844         }
3845
3846         b->fns->_nss_setpwent();
3847 }
3848
3849 static struct passwd *nwrap_module_getpwent(struct nwrap_backend *b)
3850 {
3851         static struct passwd pwd;
3852         static char buf[1000];
3853         NSS_STATUS status;
3854
3855         if (!b->fns->_nss_getpwent_r) {
3856                 return NULL;
3857         }
3858
3859         status = b->fns->_nss_getpwent_r(&pwd, buf, sizeof(buf), &errno);
3860         if (status == NSS_STATUS_NOTFOUND) {
3861                 return NULL;
3862         }
3863         if (status != NSS_STATUS_SUCCESS) {
3864                 return NULL;
3865         }
3866         return &pwd;
3867 }
3868
3869 static int nwrap_module_getpwent_r(struct nwrap_backend *b,
3870                                    struct passwd *pwdst, char *buf,
3871                                    size_t buflen, struct passwd **pwdstp)
3872 {
3873         int ret;
3874
3875         (void) pwdstp; /* unused */
3876
3877         if (!b->fns->_nss_getpwent_r) {
3878                 return ENOENT;
3879         }
3880
3881         ret = b->fns->_nss_getpwent_r(pwdst, buf, buflen, &errno);
3882         switch (ret) {
3883         case NSS_STATUS_SUCCESS:
3884                 return 0;
3885         case NSS_STATUS_NOTFOUND:
3886                 if (errno != 0) {
3887                         return errno;
3888                 }
3889                 return ENOENT;
3890         case NSS_STATUS_TRYAGAIN:
3891                 if (errno != 0) {
3892                         return errno;
3893                 }
3894                 return ERANGE;
3895         default:
3896                 if (errno != 0) {
3897                         return errno;
3898                 }
3899                 return ret;
3900         }
3901 }
3902
3903 static void nwrap_module_endpwent(struct nwrap_backend *b)
3904 {
3905         if (!b->fns->_nss_endpwent) {
3906                 return;
3907         }
3908
3909         b->fns->_nss_endpwent();
3910 }
3911
3912 static int nwrap_module_initgroups(struct nwrap_backend *b,
3913                                    const char *user, gid_t group)
3914 {
3915         gid_t *groups;
3916         long int start;
3917         long int size;
3918
3919         if (!b->fns->_nss_initgroups) {
3920                 return NSS_STATUS_UNAVAIL;
3921         }
3922
3923         return b->fns->_nss_initgroups(user, group, &start, &size, &groups, 0, &errno);
3924 }
3925
3926 static struct group *nwrap_module_getgrnam(struct nwrap_backend *b,
3927                                            const char *name)
3928 {
3929         static struct group grp;
3930         static char *buf;
3931         static int buflen = 1000;
3932         NSS_STATUS status;
3933
3934         if (!b->fns->_nss_getgrnam_r) {
3935                 return NULL;
3936         }
3937
3938         if (!buf) {
3939                 buf = (char *)malloc(buflen);
3940         }
3941 again:
3942         status = b->fns->_nss_getgrnam_r(name, &grp, buf, buflen, &errno);
3943         if (status == NSS_STATUS_TRYAGAIN) {
3944                 buflen *= 2;
3945                 buf = (char *)realloc(buf, buflen);
3946                 if (!buf) {
3947                         return NULL;
3948                 }
3949                 goto again;
3950         }
3951         if (status == NSS_STATUS_NOTFOUND) {
3952                 SAFE_FREE(buf);
3953                 return NULL;
3954         }
3955         if (status != NSS_STATUS_SUCCESS) {
3956                 SAFE_FREE(buf);
3957                 return NULL;
3958         }
3959         return &grp;
3960 }
3961
3962 static int nwrap_module_getgrnam_r(struct nwrap_backend *b,
3963                                    const char *name, struct group *grdst,
3964                                    char *buf, size_t buflen, struct group **grdstp)
3965 {
3966         int ret;
3967
3968         (void) grdstp; /* unused */
3969
3970         if (!b->fns->_nss_getgrnam_r) {
3971                 return ENOENT;
3972         }
3973
3974         ret = b->fns->_nss_getgrnam_r(name, grdst, buf, buflen, &errno);
3975         switch (ret) {
3976         case NSS_STATUS_SUCCESS:
3977                 return 0;
3978         case NSS_STATUS_NOTFOUND:
3979                 if (errno != 0) {
3980                         return errno;
3981                 }
3982                 return ENOENT;
3983         case NSS_STATUS_TRYAGAIN:
3984                 if (errno != 0) {
3985                         return errno;
3986                 }
3987                 return ERANGE;
3988         default:
3989                 if (errno != 0) {
3990                         return errno;
3991                 }
3992                 return ret;
3993         }
3994 }
3995
3996 static struct group *nwrap_module_getgrgid(struct nwrap_backend *b,
3997                                            gid_t gid)
3998 {
3999         static struct group grp;
4000         static char *buf;
4001         static int buflen = 1000;
4002         NSS_STATUS status;
4003
4004         if (!b->fns->_nss_getgrgid_r) {
4005                 return NULL;
4006         }
4007
4008         if (!buf) {
4009                 buf = (char *)malloc(buflen);
4010         }
4011
4012 again:
4013         status = b->fns->_nss_getgrgid_r(gid, &grp, buf, buflen, &errno);
4014         if (status == NSS_STATUS_TRYAGAIN) {
4015                 buflen *= 2;
4016                 buf = (char *)realloc(buf, buflen);
4017                 if (!buf) {
4018                         return NULL;
4019                 }
4020                 goto again;
4021         }
4022         if (status == NSS_STATUS_NOTFOUND) {
4023                 SAFE_FREE(buf);
4024                 return NULL;
4025         }
4026         if (status != NSS_STATUS_SUCCESS) {
4027                 SAFE_FREE(buf);
4028                 return NULL;
4029         }
4030         return &grp;
4031 }
4032
4033 static int nwrap_module_getgrgid_r(struct nwrap_backend *b,
4034                                    gid_t gid, struct group *grdst,
4035                                    char *buf, size_t buflen, struct group **grdstp)
4036 {
4037         int ret;
4038
4039         (void) grdstp; /* unused */
4040
4041         if (!b->fns->_nss_getgrgid_r) {
4042                 return ENOENT;
4043         }
4044
4045         ret = b->fns->_nss_getgrgid_r(gid, grdst, buf, buflen, &errno);
4046         switch (ret) {
4047         case NSS_STATUS_SUCCESS:
4048                 return 0;
4049         case NSS_STATUS_NOTFOUND:
4050                 if (errno != 0) {
4051                         return errno;
4052                 }
4053                 return ENOENT;
4054         case NSS_STATUS_TRYAGAIN:
4055                 if (errno != 0) {
4056                         return errno;
4057                 }
4058                 return ERANGE;
4059         default:
4060                 if (errno != 0) {
4061                         return errno;
4062                 }
4063                 return ret;
4064         }
4065 }
4066
4067 static void nwrap_module_setgrent(struct nwrap_backend *b)
4068 {
4069         if (!b->fns->_nss_setgrent) {
4070                 return;
4071         }
4072
4073         b->fns->_nss_setgrent();
4074 }
4075
4076 static struct group *nwrap_module_getgrent(struct nwrap_backend *b)
4077 {
4078         static struct group grp;
4079         static char *buf;
4080         static int buflen = 1024;
4081         NSS_STATUS status;
4082
4083         if (!b->fns->_nss_getgrent_r) {
4084                 return NULL;
4085         }
4086
4087         if (!buf) {
4088                 buf = (char *)malloc(buflen);
4089         }
4090
4091 again:
4092         status = b->fns->_nss_getgrent_r(&grp, buf, buflen, &errno);
4093         if (status == NSS_STATUS_TRYAGAIN) {
4094                 buflen *= 2;
4095                 buf = (char *)realloc(buf, buflen);
4096                 if (!buf) {
4097                         return NULL;
4098                 }
4099                 goto again;
4100         }
4101         if (status == NSS_STATUS_NOTFOUND) {
4102                 SAFE_FREE(buf);
4103                 return NULL;
4104         }
4105         if (status != NSS_STATUS_SUCCESS) {
4106                 SAFE_FREE(buf);
4107                 return NULL;
4108         }
4109         return &grp;
4110 }
4111
4112 static int nwrap_module_getgrent_r(struct nwrap_backend *b,
4113                                    struct group *grdst, char *buf,
4114                                    size_t buflen, struct group **grdstp)
4115 {
4116         int ret;
4117
4118         (void) grdstp; /* unused */
4119
4120         if (!b->fns->_nss_getgrent_r) {
4121                 return ENOENT;
4122         }
4123
4124         ret = b->fns->_nss_getgrent_r(grdst, buf, buflen, &errno);
4125         switch (ret) {
4126         case NSS_STATUS_SUCCESS:
4127                 return 0;
4128         case NSS_STATUS_NOTFOUND:
4129                 if (errno != 0) {
4130                         return errno;
4131                 }
4132                 return ENOENT;
4133         case NSS_STATUS_TRYAGAIN:
4134                 if (errno != 0) {
4135                         return errno;
4136                 }
4137                 return ERANGE;
4138         default:
4139                 if (errno != 0) {
4140                         return errno;
4141                 }
4142                 return ret;
4143         }
4144 }
4145
4146 static void nwrap_module_endgrent(struct nwrap_backend *b)
4147 {
4148         if (!b->fns->_nss_endgrent) {
4149                 return;
4150         }
4151
4152         b->fns->_nss_endgrent();
4153 }
4154
4155 /****************************************************************************
4156  *   GETPWNAM
4157  ***************************************************************************/
4158
4159 static struct passwd *nwrap_getpwnam(const char *name)
4160 {
4161         int i;
4162         struct passwd *pwd;
4163
4164         for (i=0; i < nwrap_main_global->num_backends; i++) {
4165                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4166                 pwd = b->ops->nw_getpwnam(b, name);
4167                 if (pwd) {
4168                         return pwd;
4169                 }
4170         }
4171
4172         return NULL;
4173 }
4174
4175 struct passwd *getpwnam(const char *name)
4176 {
4177         if (!nss_wrapper_enabled()) {
4178                 return libc_getpwnam(name);
4179         }
4180
4181         return nwrap_getpwnam(name);
4182 }
4183
4184 /****************************************************************************
4185  *   GETPWNAM_R
4186  ***************************************************************************/
4187
4188 static int nwrap_getpwnam_r(const char *name, struct passwd *pwdst,
4189                             char *buf, size_t buflen, struct passwd **pwdstp)
4190 {
4191         int i,ret;
4192
4193         for (i=0; i < nwrap_main_global->num_backends; i++) {
4194                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4195                 ret = b->ops->nw_getpwnam_r(b, name, pwdst, buf, buflen, pwdstp);
4196                 if (ret == ENOENT) {
4197                         continue;
4198                 }
4199                 return ret;
4200         }
4201
4202         return ENOENT;
4203 }
4204
4205 #ifdef HAVE_GETPWNAM_R
4206 # ifdef HAVE_SOLARIS_GETPWNAM_R
4207 int getpwnam_r(const char *name, struct passwd *pwdst,
4208                char *buf, int buflen, struct passwd **pwdstp)
4209 # else /* HAVE_SOLARIS_GETPWNAM_R */
4210 int getpwnam_r(const char *name, struct passwd *pwdst,
4211                char *buf, size_t buflen, struct passwd **pwdstp)
4212 # endif /* HAVE_SOLARIS_GETPWNAM_R */
4213 {
4214         if (!nss_wrapper_enabled()) {
4215                 return libc_getpwnam_r(name, pwdst, buf, buflen, pwdstp);
4216         }
4217
4218         return nwrap_getpwnam_r(name, pwdst, buf, buflen, pwdstp);
4219 }
4220 #endif
4221
4222 /****************************************************************************
4223  *   GETPWUID
4224  ***************************************************************************/
4225
4226 static struct passwd *nwrap_getpwuid(uid_t uid)
4227 {
4228         int i;
4229         struct passwd *pwd;
4230
4231         for (i=0; i < nwrap_main_global->num_backends; i++) {
4232                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4233                 pwd = b->ops->nw_getpwuid(b, uid);
4234                 if (pwd) {
4235                         return pwd;
4236                 }
4237         }
4238
4239         return NULL;
4240 }
4241
4242 struct passwd *getpwuid(uid_t uid)
4243 {
4244         if (!nss_wrapper_enabled()) {
4245                 return libc_getpwuid(uid);
4246         }
4247
4248         return nwrap_getpwuid(uid);
4249 }
4250
4251 /****************************************************************************
4252  *   GETPWUID_R
4253  ***************************************************************************/
4254
4255 static int nwrap_getpwuid_r(uid_t uid, struct passwd *pwdst,
4256                             char *buf, size_t buflen, struct passwd **pwdstp)
4257 {
4258         int i,ret;
4259
4260         for (i=0; i < nwrap_main_global->num_backends; i++) {
4261                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4262                 ret = b->ops->nw_getpwuid_r(b, uid, pwdst, buf, buflen, pwdstp);
4263                 if (ret == ENOENT) {
4264                         continue;
4265                 }
4266                 return ret;
4267         }
4268
4269         return ENOENT;
4270 }
4271
4272 #ifdef HAVE_SOLARIS_GETPWUID_R
4273 int getpwuid_r(uid_t uid, struct passwd *pwdst,
4274                char *buf, int buflen, struct passwd **pwdstp)
4275 #else
4276 int getpwuid_r(uid_t uid, struct passwd *pwdst,
4277                char *buf, size_t buflen, struct passwd **pwdstp)
4278 #endif
4279 {
4280         if (!nss_wrapper_enabled()) {
4281                 return libc_getpwuid_r(uid, pwdst, buf, buflen, pwdstp);
4282         }
4283
4284         return nwrap_getpwuid_r(uid, pwdst, buf, buflen, pwdstp);
4285 }
4286
4287 /****************************************************************************
4288  *   SETPWENT
4289  ***************************************************************************/
4290
4291 static void nwrap_setpwent(void)
4292 {
4293         int i;
4294
4295         for (i=0; i < nwrap_main_global->num_backends; i++) {
4296                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4297                 b->ops->nw_setpwent(b);
4298         }
4299 }
4300
4301 void setpwent(void)
4302 {
4303         if (!nss_wrapper_enabled()) {
4304                 libc_setpwent();
4305                 return;
4306         }
4307
4308         nwrap_setpwent();
4309 }
4310
4311 /****************************************************************************
4312  *   GETPWENT
4313  ***************************************************************************/
4314
4315 static struct passwd *nwrap_getpwent(void)
4316 {
4317         int i;
4318         struct passwd *pwd;
4319
4320         for (i=0; i < nwrap_main_global->num_backends; i++) {
4321                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4322                 pwd = b->ops->nw_getpwent(b);
4323                 if (pwd) {
4324                         return pwd;
4325                 }
4326         }
4327
4328         return NULL;
4329 }
4330
4331 struct passwd *getpwent(void)
4332 {
4333         if (!nss_wrapper_enabled()) {
4334                 return libc_getpwent();
4335         }
4336
4337         return nwrap_getpwent();
4338 }
4339
4340 /****************************************************************************
4341  *   GETPWENT_R
4342  ***************************************************************************/
4343
4344 static int nwrap_getpwent_r(struct passwd *pwdst, char *buf,
4345                             size_t buflen, struct passwd **pwdstp)
4346 {
4347         int i,ret;
4348
4349         for (i=0; i < nwrap_main_global->num_backends; i++) {
4350                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4351                 ret = b->ops->nw_getpwent_r(b, pwdst, buf, buflen, pwdstp);
4352                 if (ret == ENOENT) {
4353                         continue;
4354                 }
4355                 return ret;
4356         }
4357
4358         return ENOENT;
4359 }
4360
4361 #ifdef HAVE_SOLARIS_GETPWENT_R
4362 struct passwd *getpwent_r(struct passwd *pwdst, char *buf, int buflen)
4363 {
4364         struct passwd *pwdstp = NULL;
4365         int rc;
4366
4367         if (!nss_wrapper_enabled()) {
4368                 return libc_getpwent_r(pwdst, buf, buflen);
4369         }
4370         rc = nwrap_getpwent_r(pwdst, buf, buflen, &pwdstp);
4371         if (rc < 0) {
4372                 return NULL;
4373         }
4374
4375         return pwdstp;
4376 }
4377 #else /* HAVE_SOLARIS_GETPWENT_R */
4378 int getpwent_r(struct passwd *pwdst, char *buf,
4379                size_t buflen, struct passwd **pwdstp)
4380 {
4381         if (!nss_wrapper_enabled()) {
4382                 return libc_getpwent_r(pwdst, buf, buflen, pwdstp);
4383         }
4384
4385         return nwrap_getpwent_r(pwdst, buf, buflen, pwdstp);
4386 }
4387 #endif /* HAVE_SOLARIS_GETPWENT_R */
4388
4389 /****************************************************************************
4390  *   ENDPWENT
4391  ***************************************************************************/
4392
4393 static void nwrap_endpwent(void)
4394 {
4395         int i;
4396
4397         for (i=0; i < nwrap_main_global->num_backends; i++) {
4398                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4399                 b->ops->nw_endpwent(b);
4400         }
4401 }
4402
4403 void endpwent(void)
4404 {
4405         if (!nss_wrapper_enabled()) {
4406                 libc_endpwent();
4407                 return;
4408         }
4409
4410         nwrap_endpwent();
4411 }
4412
4413 /****************************************************************************
4414  *   INITGROUPS
4415  ***************************************************************************/
4416
4417 static int nwrap_initgroups(const char *user, gid_t group)
4418 {
4419         int i;
4420
4421         for (i=0; i < nwrap_main_global->num_backends; i++) {
4422                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4423                 int rc;
4424
4425                 rc = b->ops->nw_initgroups(b, user, group);
4426                 if (rc == 0) {
4427                         return 0;
4428                 }
4429         }
4430
4431         errno = ENOENT;
4432         return -1;
4433 }
4434
4435 int initgroups(const char *user, gid_t group)
4436 {
4437         if (!nss_wrapper_enabled()) {
4438                 return libc_initgroups(user, group);
4439         }
4440
4441         return nwrap_initgroups(user, group);
4442 }
4443
4444 /****************************************************************************
4445  *   GETGRNAM
4446  ***************************************************************************/
4447
4448 static struct group *nwrap_getgrnam(const char *name)
4449 {
4450         int i;
4451         struct group *grp;
4452
4453         for (i=0; i < nwrap_main_global->num_backends; i++) {
4454                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4455                 grp = b->ops->nw_getgrnam(b, name);
4456                 if (grp) {
4457                         return grp;
4458                 }
4459         }
4460
4461         return NULL;
4462 }
4463
4464 struct group *getgrnam(const char *name)
4465 {
4466         if (!nss_wrapper_enabled()) {
4467                 return libc_getgrnam(name);
4468         }
4469
4470         return nwrap_getgrnam(name);
4471 }
4472
4473 /****************************************************************************
4474  *   GETGRNAM_R
4475  ***************************************************************************/
4476
4477 static int nwrap_getgrnam_r(const char *name, struct group *grdst,
4478                             char *buf, size_t buflen, struct group **grdstp)
4479 {
4480         int i, ret;
4481
4482         for (i=0; i < nwrap_main_global->num_backends; i++) {
4483                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4484                 ret = b->ops->nw_getgrnam_r(b, name, grdst, buf, buflen, grdstp);
4485                 if (ret == ENOENT) {
4486                         continue;
4487                 }
4488                 return ret;
4489         }
4490
4491         return ENOENT;
4492 }
4493
4494 #ifdef HAVE_GETGRNAM_R
4495 # ifdef HAVE_SOLARIS_GETGRNAM_R
4496 int getgrnam_r(const char *name, struct group *grp,
4497                 char *buf, int buflen, struct group **pgrp)
4498 # else /* HAVE_SOLARIS_GETGRNAM_R */
4499 int getgrnam_r(const char *name, struct group *grp,
4500                char *buf, size_t buflen, struct group **pgrp)
4501 # endif /* HAVE_SOLARIS_GETGRNAM_R */
4502 {
4503         if (!nss_wrapper_enabled()) {
4504                 return libc_getgrnam_r(name,
4505                                        grp,
4506                                        buf,
4507                                        buflen,
4508                                        pgrp);
4509         }
4510
4511         return nwrap_getgrnam_r(name, grp, buf, buflen, pgrp);
4512 }
4513 #endif /* HAVE_GETGRNAM_R */
4514
4515 /****************************************************************************
4516  *   GETGRGID
4517  ***************************************************************************/
4518
4519 static struct group *nwrap_getgrgid(gid_t gid)
4520 {
4521         int i;
4522         struct group *grp;
4523
4524         for (i=0; i < nwrap_main_global->num_backends; i++) {
4525                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4526                 grp = b->ops->nw_getgrgid(b, gid);
4527                 if (grp) {
4528                         return grp;
4529                 }
4530         }
4531
4532         return NULL;
4533 }
4534
4535 struct group *getgrgid(gid_t gid)
4536 {
4537         if (!nss_wrapper_enabled()) {
4538                 return libc_getgrgid(gid);
4539         }
4540
4541         return nwrap_getgrgid(gid);
4542 }
4543
4544 /****************************************************************************
4545  *   GETGRGID_R
4546  ***************************************************************************/
4547
4548 static int nwrap_getgrgid_r(gid_t gid, struct group *grdst,
4549                             char *buf, size_t buflen, struct group **grdstp)
4550 {
4551         int i,ret;
4552
4553         for (i=0; i < nwrap_main_global->num_backends; i++) {
4554                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4555                 ret = b->ops->nw_getgrgid_r(b, gid, grdst, buf, buflen, grdstp);
4556                 if (ret == ENOENT) {
4557                         continue;
4558                 }
4559                 return ret;
4560         }
4561
4562         return ENOENT;
4563 }
4564
4565 #ifdef HAVE_GETGRGID_R
4566 # ifdef HAVE_SOLARIS_GETGRGID_R
4567 int getgrgid_r(gid_t gid, struct group *grdst,
4568                char *buf, int buflen, struct group **grdstp)
4569 # else /* HAVE_SOLARIS_GETGRGID_R */
4570 int getgrgid_r(gid_t gid, struct group *grdst,
4571                char *buf, size_t buflen, struct group **grdstp)
4572 # endif /* HAVE_SOLARIS_GETGRGID_R */
4573 {
4574         if (!nss_wrapper_enabled()) {
4575                 return libc_getgrgid_r(gid, grdst, buf, buflen, grdstp);
4576         }
4577
4578         return nwrap_getgrgid_r(gid, grdst, buf, buflen, grdstp);
4579 }
4580 #endif
4581
4582 /****************************************************************************
4583  *   SETGRENT
4584  ***************************************************************************/
4585
4586 static void nwrap_setgrent(void)
4587 {
4588         int i;
4589
4590         for (i=0; i < nwrap_main_global->num_backends; i++) {
4591                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4592                 b->ops->nw_setgrent(b);
4593         }
4594 }
4595
4596 #ifdef HAVE_BSD_SETGRENT
4597 int setgrent(void)
4598 #else
4599 void setgrent(void)
4600 #endif
4601 {
4602         if (!nss_wrapper_enabled()) {
4603                 libc_setgrent();
4604                 goto out;
4605         }
4606
4607         nwrap_setgrent();
4608
4609 out:
4610 #ifdef HAVE_BSD_SETGRENT
4611         return 0;
4612 #else
4613         return;
4614 #endif
4615 }
4616
4617 /****************************************************************************
4618  *   GETGRENT
4619  ***************************************************************************/
4620
4621 static struct group *nwrap_getgrent(void)
4622 {
4623         int i;
4624         struct group *grp;
4625
4626         for (i=0; i < nwrap_main_global->num_backends; i++) {
4627                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4628                 grp = b->ops->nw_getgrent(b);
4629                 if (grp) {
4630                         return grp;
4631                 }
4632         }
4633
4634         return NULL;
4635 }
4636
4637 struct group *getgrent(void)
4638 {
4639         if (!nss_wrapper_enabled()) {
4640                 return libc_getgrent();
4641         }
4642
4643         return nwrap_getgrent();
4644 }
4645
4646 /****************************************************************************
4647  *   GETGRENT_R
4648  ***************************************************************************/
4649
4650 static int nwrap_getgrent_r(struct group *grdst, char *buf,
4651                             size_t buflen, struct group **grdstp)
4652 {
4653         int i,ret;
4654
4655         for (i=0; i < nwrap_main_global->num_backends; i++) {
4656                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4657                 ret = b->ops->nw_getgrent_r(b, grdst, buf, buflen, grdstp);
4658                 if (ret == ENOENT) {
4659                         continue;
4660                 }
4661                 return ret;
4662         }
4663
4664         return ENOENT;
4665 }
4666
4667 #ifdef HAVE_SOLARIS_GETGRENT_R
4668 struct group *getgrent_r(struct group *src, char *buf, int buflen)
4669 {
4670         struct group *grdstp = NULL;
4671         int rc;
4672
4673         if (!nss_wrapper_enabled()) {
4674                 return libc_getgrent_r(src, buf, buflen);
4675         }
4676
4677         rc = nwrap_getgrent_r(src, buf, buflen, &grdstp);
4678         if (rc < 0) {
4679                 return NULL;
4680         }
4681
4682         return grdstp;
4683 }
4684 #else /* HAVE_SOLARIS_GETGRENT_R */
4685 int getgrent_r(struct group *src, char *buf,
4686                size_t buflen, struct group **grdstp)
4687 {
4688         if (!nss_wrapper_enabled()) {
4689                 return libc_getgrent_r(src, buf, buflen, grdstp);
4690         }
4691
4692         return nwrap_getgrent_r(src, buf, buflen, grdstp);
4693 }
4694 #endif /* HAVE_SOLARIS_GETGRENT_R */
4695
4696 /****************************************************************************
4697  *   ENDGRENT
4698  ***************************************************************************/
4699
4700 static void nwrap_endgrent(void)
4701 {
4702         int i;
4703
4704         for (i=0; i < nwrap_main_global->num_backends; i++) {
4705                 struct nwrap_backend *b = &nwrap_main_global->backends[i];
4706                 b->ops->nw_endgrent(b);
4707         }
4708 }
4709
4710 void endgrent(void)
4711 {
4712         if (!nss_wrapper_enabled()) {
4713                 libc_endgrent();
4714                 return;
4715         }
4716
4717         nwrap_endgrent();
4718 }
4719
4720 /****************************************************************************
4721  *   GETGROUPLIST
4722  ***************************************************************************/
4723
4724 #ifdef HAVE_GETGROUPLIST
4725 static int nwrap_getgrouplist(const char *user, gid_t group,
4726                               gid_t *groups, int *ngroups)
4727 {
4728         struct group *grp;
4729         gid_t *groups_tmp;
4730         int count = 1;
4731
4732         NWRAP_LOG(NWRAP_LOG_DEBUG, "getgrouplist called for %s", user);
4733
4734         groups_tmp = (gid_t *)malloc(count * sizeof(gid_t));
4735         if (!groups_tmp) {
4736                 NWRAP_LOG(NWRAP_LOG_ERROR, "Out of memory");
4737                 errno = ENOMEM;
4738                 return -1;
4739         }
4740         groups_tmp[0] = group;
4741
4742         nwrap_setgrent();
4743         while ((grp = nwrap_getgrent()) != NULL) {
4744                 int i = 0;
4745
4746                 NWRAP_LOG(NWRAP_LOG_DEBUG,
4747                           "Inspecting %s for group membership",
4748                           grp->gr_name);
4749
4750                 for (i=0; grp->gr_mem && grp->gr_mem[i] != NULL; i++) {
4751
4752                         if (group != grp->gr_gid &&
4753                             (strcmp(user, grp->gr_mem[i]) == 0)) {
4754
4755                                 NWRAP_LOG(NWRAP_LOG_DEBUG,
4756                                           "%s is member of %s",
4757                                           user,
4758                                           grp->gr_name);
4759
4760                                 groups_tmp = (gid_t *)realloc(groups_tmp, (count + 1) * sizeof(gid_t));
4761                                 if (!groups_tmp) {
4762                                         NWRAP_LOG(NWRAP_LOG_ERROR,
4763                                                   "Out of memory");
4764                                         errno = ENOMEM;
4765                                         return -1;
4766                                 }
4767                                 groups_tmp[count] = grp->gr_gid;
4768
4769                                 count++;
4770                         }
4771                 }
4772         }
4773
4774         nwrap_endgrent();
4775
4776         NWRAP_LOG(NWRAP_LOG_DEBUG,
4777                   "%s is member of %d groups",
4778                   user, *ngroups);
4779
4780         if (*ngroups < count) {
4781                 *ngroups = count;
4782                 free(groups_tmp);
4783                 return -1;
4784         }
4785
4786         *ngroups = count;
4787         memcpy(groups, groups_tmp, count * sizeof(gid_t));
4788         free(groups_tmp);
4789
4790         return count;
4791 }
4792
4793 int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups)
4794 {
4795         if (!nss_wrapper_enabled()) {
4796                 return libc_getgrouplist(user, group, groups, ngroups);
4797         }
4798
4799         return nwrap_getgrouplist(user, group, groups, ngroups);
4800 }
4801 #endif
4802
4803 /**********************************************************
4804  * SHADOW
4805  **********************************************************/
4806
4807 #if defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM)
4808
4809 #ifdef HAVE_SETSPENT
4810 static void nwrap_setspent(void)
4811 {
4812         nwrap_files_setspent();
4813 }
4814
4815 void setspent(void)
4816 {
4817         if (!nss_wrapper_shadow_enabled()) {
4818                 return;
4819         }
4820
4821         nwrap_setspent();
4822 }
4823
4824 static struct spwd *nwrap_getspent(void)
4825 {
4826         return nwrap_files_getspent();
4827 }
4828
4829 struct spwd *getspent(void)
4830 {
4831         if (!nss_wrapper_shadow_enabled()) {
4832                 return NULL;
4833         }
4834
4835         return nwrap_getspent();
4836 }
4837
4838 static void nwrap_endspent(void)
4839 {
4840         nwrap_files_endspent();
4841 }
4842
4843 void endspent(void)
4844 {
4845         if (!nss_wrapper_shadow_enabled()) {
4846                 return;
4847         }
4848
4849         nwrap_endspent();
4850 }
4851 #endif /* HAVE_SETSPENT */
4852
4853 static struct spwd *nwrap_getspnam(const char *name)
4854 {
4855         return nwrap_files_getspnam(name);
4856 }
4857
4858 struct spwd *getspnam(const char *name)
4859 {
4860         if (!nss_wrapper_shadow_enabled()) {
4861                 return NULL;
4862         }
4863
4864         return nwrap_getspnam(name);
4865 }
4866
4867 #endif /* defined(HAVE_SHADOW_H) && defined(HAVE_GETSPNAM) */
4868
4869 /**********************************************************
4870  * NETDB
4871  **********************************************************/
4872
4873 static void nwrap_sethostent(int stayopen) {
4874         (void) stayopen; /* ignored */
4875
4876         nwrap_files_sethostent();
4877 }
4878
4879 #ifdef HAVE_SOLARIS_SETHOSTENT
4880 int sethostent(int stayopen)
4881 {
4882         if (!nss_wrapper_hosts_enabled()) {
4883                 libc_sethostent(stayopen);
4884                 return 0;
4885         }
4886
4887         nwrap_sethostent(stayopen);
4888
4889         return 0;
4890 }
4891 #else /* HAVE_SOLARIS_SETHOSTENT */
4892 void sethostent(int stayopen)
4893 {
4894         if (!nss_wrapper_hosts_enabled()) {
4895                 libc_sethostent(stayopen);
4896                 return;
4897         }
4898
4899         nwrap_sethostent(stayopen);
4900 }
4901 #endif /* HAVE_SOLARIS_SETHOSTENT */
4902
4903 static struct hostent *nwrap_gethostent(void)
4904 {
4905         return nwrap_files_gethostent();
4906 }
4907
4908 struct hostent *gethostent(void) {
4909         if (!nss_wrapper_hosts_enabled()) {
4910                 return libc_gethostent();
4911         }
4912
4913         return nwrap_gethostent();
4914 }
4915
4916 static void nwrap_endhostent(void) {
4917         nwrap_files_endhostent();
4918 }
4919
4920 #ifdef HAVE_SOLARIS_ENDHOSTENT
4921 int endhostent(void)
4922 {
4923         if (!nss_wrapper_hosts_enabled()) {
4924                 libc_endhostent();
4925                 return 0;
4926         }
4927
4928         nwrap_endhostent();
4929
4930         return 0;
4931 }
4932 #else /* HAVE_SOLARIS_ENDHOSTENT */
4933 void endhostent(void)
4934 {
4935         if (!nss_wrapper_hosts_enabled()) {
4936                 libc_endhostent();
4937                 return;
4938         }
4939
4940         nwrap_endhostent();
4941 }
4942 #endif /* HAVE_SOLARIS_ENDHOSTENT */
4943
4944 #ifdef BSD
4945 /* BSD implementation stores data in thread local storage but GLIBC does not */
4946 static __thread struct hostent user_he;
4947 static __thread struct nwrap_vector user_addrlist;
4948 #else
4949 static struct hostent user_he;
4950 static struct nwrap_vector user_addrlist;
4951 #endif /* BSD */
4952 static struct hostent *nwrap_gethostbyname(const char *name)
4953 {
4954         if (nwrap_files_gethostbyname(name, AF_UNSPEC, &user_he, &user_addrlist) == -1) {
4955                 return NULL;
4956         }
4957         return &user_he;
4958 }
4959
4960 struct hostent *gethostbyname(const char *name)
4961 {
4962         if (!nss_wrapper_hosts_enabled()) {
4963                 return libc_gethostbyname(name);
4964         }
4965
4966         return nwrap_gethostbyname(name);
4967 }
4968
4969 /* This is a GNU extension - Also can be found on BSD systems */
4970 #ifdef HAVE_GETHOSTBYNAME2
4971 #ifdef BSD
4972 /* BSD implementation stores data in  thread local storage but GLIBC not */
4973 static __thread struct hostent user_he2;
4974 static __thread struct nwrap_vector user_addrlist2;
4975 #else
4976 static struct hostent user_he2;
4977 static struct nwrap_vector user_addrlist2;
4978 #endif /* BSD */
4979 static struct hostent *nwrap_gethostbyname2(const char *name, int af)
4980 {
4981         if (nwrap_files_gethostbyname(name, af, &user_he2, &user_addrlist2) == -1) {
4982                 return NULL;
4983         }
4984         return &user_he2;
4985 }
4986
4987 struct hostent *gethostbyname2(const char *name, int af)
4988 {
4989         if (!nss_wrapper_hosts_enabled()) {
4990                 return libc_gethostbyname2(name, af);
4991         }
4992
4993         return nwrap_gethostbyname2(name, af);
4994 }
4995 #endif
4996
4997 static struct hostent *nwrap_gethostbyaddr(const void *addr,
4998                                            socklen_t len, int type)
4999 {
5000         return nwrap_files_gethostbyaddr(addr, len, type);
5001 }
5002
5003 struct hostent *gethostbyaddr(const void *addr,
5004                               socklen_t len, int type)
5005 {
5006         if (!nss_wrapper_hosts_enabled()) {
5007                 return libc_gethostbyaddr(addr, len, type);
5008         }
5009
5010         return nwrap_gethostbyaddr(addr, len, type);
5011 }
5012
5013 static const struct addrinfo default_hints =
5014 {
5015         .ai_flags = AI_ADDRCONFIG|AI_V4MAPPED,
5016         .ai_family = AF_UNSPEC,
5017         .ai_socktype = 0,
5018         .ai_protocol = 0,
5019         .ai_addrlen = 0,
5020         .ai_addr = NULL,
5021         .ai_canonname = NULL,
5022         .ai_next = NULL
5023 };
5024
5025 static int nwrap_convert_he_ai(const struct hostent *he,
5026                                unsigned short port,
5027                                const struct addrinfo *hints,
5028                                struct addrinfo **pai,
5029                                bool skip_canonname)
5030 {
5031         struct addrinfo *ai;
5032         socklen_t socklen;
5033
5034         if (he == NULL) {
5035                 return EAI_MEMORY;
5036         }
5037
5038         switch (he->h_addrtype) {
5039                 case AF_INET:
5040                         socklen = sizeof(struct sockaddr_in);
5041                         break;
5042 #ifdef HAVE_IPV6
5043                 case AF_INET6:
5044                         socklen = sizeof(struct sockaddr_in6);
5045                         break;
5046 #endif
5047                 default:
5048                         return EAI_FAMILY;
5049         }
5050
5051         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo) + socklen);
5052         if (ai == NULL) {
5053                 return EAI_MEMORY;
5054         }
5055
5056         ai->ai_flags = 0;
5057         ai->ai_family = he->h_addrtype;
5058         ai->ai_socktype = hints->ai_socktype;
5059         ai->ai_protocol = hints->ai_protocol;
5060         ai->ai_canonname = NULL;
5061
5062         ai->ai_addrlen = socklen;
5063         ai->ai_addr = (void *)(ai + 1);
5064
5065 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
5066         ai->ai_addr->sa_len = socklen;
5067 #endif
5068         ai->ai_addr->sa_family = he->h_addrtype;
5069
5070         switch (he->h_addrtype) {
5071                 case AF_INET:
5072                 {
5073                         struct sockaddr_in *sinp =
5074                                 (struct sockaddr_in *) ai->ai_addr;
5075
5076                         memset(sinp, 0, sizeof(struct sockaddr_in));
5077
5078                         sinp->sin_port = htons(port);
5079                         sinp->sin_family = AF_INET;
5080
5081                         memset (sinp->sin_zero, '\0', sizeof (sinp->sin_zero));
5082                         memcpy(&sinp->sin_addr, he->h_addr_list[0], he->h_length);
5083
5084                 }
5085                 break;
5086 #ifdef HAVE_IPV6
5087                 case AF_INET6:
5088                 {
5089                         struct sockaddr_in6 *sin6p =
5090                                 (struct sockaddr_in6 *) ai->ai_addr;
5091
5092                         memset(sin6p, 0, sizeof(struct sockaddr_in6));
5093
5094                         sin6p->sin6_port = htons(port);
5095                         sin6p->sin6_family = AF_INET6;
5096
5097                         memcpy(&sin6p->sin6_addr,
5098                                he->h_addr_list[0],
5099                                he->h_length);
5100                 }
5101                 break;
5102 #endif
5103         }
5104
5105         ai->ai_next = NULL;
5106
5107         if (he->h_name && !skip_canonname) {
5108                 ai->ai_canonname = strdup(he->h_name);
5109                 if (ai->ai_canonname == NULL) {
5110                         freeaddrinfo(ai);
5111                         return EAI_MEMORY;
5112                 }
5113         }
5114
5115         *pai = ai;
5116         return 0;
5117 }
5118
5119 static int nwrap_getaddrinfo(const char *node,
5120                              const char *service,
5121                              const struct addrinfo *hints,
5122                              struct addrinfo **res)
5123 {
5124         struct addrinfo *ai = NULL;
5125         struct addrinfo *ai_tail;
5126         unsigned short port = 0;
5127         struct {
5128                 int family;
5129                 union {
5130                         struct in_addr v4;
5131 #ifdef HAVE_IPV6
5132                         struct in6_addr v6;
5133                 } in;
5134 #endif
5135         } addr = {
5136                 .family = AF_UNSPEC,
5137         };
5138         int rc;
5139
5140         if (node == NULL && service == NULL) {
5141                 return EAI_NONAME;
5142         }
5143
5144         if (hints == NULL) {
5145                 hints = &default_hints;
5146         }
5147
5148         /* EAI_BADFLAGS
5149               hints.ai_flags   contains   invalid  flags;  or,  hints.ai_flags
5150               included AI_CANONNAME and name was NULL.
5151         */
5152         if ((hints->ai_flags & AI_CANONNAME) && (node == NULL)) {
5153                 return EAI_BADFLAGS;
5154         }
5155
5156         /* If no node has been specified, let glibc deal with it */
5157         if (node == NULL) {
5158                 int ret;
5159                 struct addrinfo *p = NULL;
5160
5161                 ret = libc_getaddrinfo(node, service, hints, &p);
5162
5163                 if (ret == 0) {
5164                         *res = p;
5165                 }
5166                 return ret;
5167         }
5168
5169         if (service != NULL && service[0] != '\0') {
5170                 const char *proto = NULL;
5171                 struct servent *s;
5172                 char *end_ptr;
5173                 long sl;
5174
5175                 errno = 0;
5176                 sl = strtol(service, &end_ptr, 10);
5177
5178                 if (*end_ptr == '\0') {
5179                         port = sl;
5180                         goto valid_port;
5181                 } else if (hints->ai_flags & AI_NUMERICSERV) {
5182                         return EAI_NONAME;
5183                 }
5184
5185                 if (hints->ai_protocol != 0) {
5186                         struct protoent *pent;
5187
5188                         pent = getprotobynumber(hints->ai_protocol);
5189                         if (pent != NULL) {
5190                                 proto = pent->p_name;
5191                         }
5192                 }
5193
5194                 s = getservbyname(service, proto);
5195                 if (s == NULL) {
5196                         return EAI_NONAME;
5197                 }
5198                 port = ntohs(s->s_port);
5199         }
5200
5201 valid_port:
5202
5203         rc = inet_pton(AF_INET, node, &addr.in.v4);
5204         if (rc == 1) {
5205                 addr.family = AF_INET;
5206         }
5207 #ifdef HAVE_IPV6
5208         if (addr.family == AF_UNSPEC) {
5209                 rc = inet_pton(AF_INET6, node, &addr.in.v6);
5210                 if (rc == 1) {
5211                         addr.family = AF_INET6;
5212                 }
5213         }
5214 #endif
5215
5216         if (addr.family == AF_UNSPEC) {
5217                if (hints->ai_flags & AI_NUMERICHOST) {
5218                         return EAI_NONAME;
5219                 }
5220         } else if ((hints->ai_family != AF_UNSPEC) &&
5221                    (hints->ai_family != addr.family))
5222         {
5223                 return EAI_ADDRFAMILY;
5224         }
5225
5226         rc = nwrap_files_getaddrinfo(node, port, hints, &ai, &ai_tail);
5227         if (rc != 0) {
5228                 int ret;
5229                 struct addrinfo *p = NULL;
5230
5231                 ret = libc_getaddrinfo(node, service, hints, &p);
5232
5233                 if (ret == 0) {
5234                         /*
5235                          * nwrap_files_getaddrinfo failed, but libc was
5236                          * successful -- use the result from libc.
5237                          */
5238                         *res = p;
5239                         return 0;
5240                 }
5241
5242                 return rc;
5243         }
5244
5245         if (ai->ai_flags == 0) {
5246                 ai->ai_flags = hints->ai_flags;
5247         }
5248         if (ai->ai_socktype == 0) {
5249                 ai->ai_socktype = SOCK_DGRAM;
5250         }
5251         if (ai->ai_protocol == 0 && ai->ai_socktype == SOCK_DGRAM) {
5252                 ai->ai_protocol = 17; /* UDP */
5253         } else if (ai->ai_protocol == 0 && ai->ai_socktype == SOCK_STREAM) {
5254                 ai->ai_protocol = 6; /* TCP */
5255         }
5256
5257         if (hints->ai_socktype == 0) {
5258                 /* Add second ai */
5259                 struct addrinfo *ai_head = ai;
5260                 struct addrinfo *ai_tmp;
5261                 struct addrinfo *ai_new_tail = ai_tail;
5262
5263                 /* Add at least one more struct */
5264                 do {
5265                         /* CHECKS! */
5266                         ai_tmp = malloc(sizeof(struct addrinfo));
5267                         memcpy(ai_tmp, ai_head, sizeof(struct addrinfo));
5268                         ai_tmp->ai_next = NULL;
5269
5270                         /* We need a deep copy or freeaddrinfo() will blow up */
5271                         if (ai_head->ai_canonname != NULL) {
5272                                 ai_tmp->ai_canonname =
5273                                         strdup(ai_head->ai_canonname);
5274                         }
5275                         /* ai_head should point inside hints. */
5276                         ai_tmp->ai_addr = ai_head->ai_addr;
5277
5278                         if (ai_head->ai_flags == 0) {
5279                                 ai_tmp->ai_flags = hints->ai_flags;
5280                         }
5281                         if (ai_head->ai_socktype == SOCK_DGRAM) {
5282                                 ai_tmp->ai_socktype = SOCK_STREAM;
5283                         } else if (ai_head->ai_socktype == SOCK_STREAM) {
5284                                 ai_tmp->ai_socktype = SOCK_DGRAM;
5285                         }
5286                         if (ai_head->ai_socktype == SOCK_DGRAM) {
5287                                 ai_tmp->ai_protocol = 17; /* UDP */
5288                         } else if (ai_head->ai_socktype == SOCK_STREAM) {
5289                                 ai_tmp->ai_protocol = 6; /* TCP */
5290                         }
5291                         ai_new_tail->ai_next = ai_tmp;
5292                         ai_new_tail = ai_tmp;
5293
5294                         if (ai_head == ai_tail) {
5295                                 break;
5296                         }
5297                         ai_head = ai_head->ai_next;
5298                 } while (1);
5299         }
5300
5301         *res = ai;
5302
5303         return 0;
5304 }
5305
5306 int getaddrinfo(const char *node, const char *service,
5307                 const struct addrinfo *hints,
5308                 struct addrinfo **res)
5309 {
5310         if (!nss_wrapper_hosts_enabled()) {
5311                 return libc_getaddrinfo(node, service, hints, res);
5312         }
5313
5314         return nwrap_getaddrinfo(node, service, hints, res);
5315 }
5316
5317 static int nwrap_getnameinfo(const struct sockaddr *sa, socklen_t salen,
5318                              char *host, size_t hostlen,
5319                              char *serv, size_t servlen,
5320                              int flags)
5321 {
5322         struct hostent *he;
5323         struct servent *service;
5324         const char *proto;
5325         const void *addr;
5326         socklen_t addrlen;
5327         uint16_t port;
5328         sa_family_t type;
5329
5330         if (sa == NULL || salen < sizeof(sa_family_t)) {
5331                 return EAI_FAMILY;
5332         }
5333
5334         if ((flags & NI_NAMEREQD) && host == NULL && serv == NULL) {
5335                 return EAI_NONAME;
5336         }
5337
5338         type = sa->sa_family;
5339         switch (type) {
5340         case AF_INET:
5341                 if (salen < sizeof(struct sockaddr_in))
5342                         return EAI_FAMILY;
5343                 addr = &((const struct sockaddr_in *)sa)->sin_addr;
5344                 addrlen = sizeof(((const struct sockaddr_in *)sa)->sin_addr);
5345                 port = ntohs(((const struct sockaddr_in *)sa)->sin_port);
5346                 break;
5347 #ifdef HAVE_IPV6
5348         case AF_INET6:
5349                 if (salen < sizeof(struct sockaddr_in6))
5350                         return EAI_FAMILY;
5351                 addr = &((const struct sockaddr_in6 *)sa)->sin6_addr;
5352                 addrlen = sizeof(((const struct sockaddr_in6 *)sa)->sin6_addr);
5353                 port = ntohs(((const struct sockaddr_in6 *)sa)->sin6_port);
5354                 break;
5355 #endif
5356         default:
5357                 return EAI_FAMILY;
5358         }
5359
5360         if (host != NULL) {
5361                 he = NULL;
5362                 if ((flags & NI_NUMERICHOST) == 0) {
5363                         he = nwrap_files_gethostbyaddr(addr, addrlen, type);
5364                         if ((flags & NI_NAMEREQD) && (he == NULL || he->h_name == NULL))
5365                                 return EAI_NONAME;
5366                 }
5367                 if (he != NULL && he->h_name != NULL) {
5368                         if (strlen(he->h_name) >= hostlen)
5369                                 return EAI_OVERFLOW;
5370                         strcpy(host, he->h_name);
5371                         if (flags & NI_NOFQDN)
5372                                 host[strcspn(host, ".")] = '\0';
5373                 } else {
5374                         if (inet_ntop(type, addr, host, hostlen) == NULL)
5375                                 return (errno == ENOSPC) ? EAI_OVERFLOW : EAI_FAIL;
5376                 }
5377         }
5378
5379         if (serv != NULL) {
5380                 service = NULL;
5381                 if ((flags & NI_NUMERICSERV) == 0) {
5382                         proto = (flags & NI_DGRAM) ? "udp" : "tcp";
5383                         service = getservbyport(htons(port), proto);
5384                 }
5385                 if (service != NULL) {
5386                         if (strlen(service->s_name) >= servlen)
5387                                 return EAI_OVERFLOW;
5388                         strcpy(serv, service->s_name);
5389                 } else {
5390                         if (snprintf(serv, servlen, "%u", port) >= (int) servlen)
5391                                 return EAI_OVERFLOW;
5392                 }
5393         }
5394
5395         return 0;
5396 }
5397
5398 #ifdef HAVE_LINUX_GETNAMEINFO
5399 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5400                 char *host, socklen_t hostlen,
5401                 char *serv, socklen_t servlen,
5402                 int flags)
5403 #elif defined(HAVE_LINUX_GETNAMEINFO_UNSIGNED)
5404 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5405                 char *host, socklen_t hostlen,
5406                 char *serv, socklen_t servlen,
5407                 unsigned int flags)
5408 #else
5409 int getnameinfo(const struct sockaddr *sa, socklen_t salen,
5410                 char *host, size_t hostlen,
5411                 char *serv, size_t servlen,
5412                 int flags)
5413 #endif
5414 {
5415         if (!nss_wrapper_hosts_enabled()) {
5416                 return libc_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
5417         }
5418
5419         return nwrap_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
5420 }
5421
5422 static int nwrap_gethostname(char *name, size_t len)
5423 {
5424         const char *hostname = getenv("NSS_WRAPPER_HOSTNAME");
5425
5426         if (strlen(hostname) >= len) {
5427                 errno = ENAMETOOLONG;
5428                 return -1;
5429         }
5430         snprintf(name, len, "%s", hostname);
5431
5432         return 0;
5433 }
5434
5435 #ifdef HAVE_SOLARIS_GETHOSTNAME
5436 int gethostname(char *name, int len)
5437 #else /* HAVE_SOLARIS_GETHOSTNAME */
5438 int gethostname(char *name, size_t len)
5439 #endif /* HAVE_SOLARIS_GETHOSTNAME */
5440 {
5441         if (!nwrap_hostname_enabled()) {
5442                 return libc_gethostname(name, len);
5443         }
5444
5445         return nwrap_gethostname(name, len);
5446 }
5447
5448 /****************************
5449  * DESTRUCTOR
5450  ***************************/
5451
5452 /*
5453  * This function is called when the library is unloaded and makes sure that
5454  * sockets get closed and the unix file for the socket are unlinked.
5455  */
5456 void nwrap_destructor(void)
5457 {
5458         int i;
5459
5460         NWRAP_LOCK_ALL;
5461         if (nwrap_main_global != NULL) {
5462                 struct nwrap_main *m = nwrap_main_global;
5463
5464                 /* libc */
5465                 SAFE_FREE(m->libc->fns);
5466                 if (m->libc->handle != NULL) {
5467                         dlclose(m->libc->handle);
5468                 }
5469                 if (m->libc->nsl_handle != NULL) {
5470                         dlclose(m->libc->nsl_handle);
5471                 }
5472                 if (m->libc->sock_handle != NULL) {
5473                         dlclose(m->libc->sock_handle);
5474                 }
5475                 SAFE_FREE(m->libc);
5476
5477                 /* backends */
5478                 for (i = 0; i < m->num_backends; i++) {
5479                         struct nwrap_backend *b = &(m->backends[i]);
5480
5481                         if (b->so_handle != NULL) {
5482                                 dlclose(b->so_handle);
5483                         }
5484                         SAFE_FREE(b->fns);
5485                 }
5486                 SAFE_FREE(m->backends);
5487         }
5488
5489         if (nwrap_pw_global.cache != NULL) {
5490                 struct nwrap_cache *c = nwrap_pw_global.cache;
5491
5492                 nwrap_files_cache_unload(c);
5493                 if (c->fd >= 0) {
5494                         fclose(c->fp);
5495                         c->fd = -1;
5496                 }
5497
5498                 SAFE_FREE(nwrap_pw_global.list);
5499                 nwrap_pw_global.num = 0;
5500         }
5501
5502         if (nwrap_gr_global.cache != NULL) {
5503                 struct nwrap_cache *c = nwrap_gr_global.cache;
5504
5505                 nwrap_files_cache_unload(c);
5506                 if (c->fd >= 0) {
5507                         fclose(c->fp);
5508                         c->fd = -1;
5509                 }
5510
5511                 SAFE_FREE(nwrap_gr_global.list);
5512                 nwrap_pw_global.num = 0;
5513         }
5514
5515         if (nwrap_he_global.cache != NULL) {
5516                 struct nwrap_cache *c = nwrap_he_global.cache;
5517
5518                 nwrap_files_cache_unload(c);
5519                 if (c->fd >= 0) {
5520                         fclose(c->fp);
5521                         c->fd = -1;
5522                 }
5523
5524                 nwrap_he_global.num = 0;
5525         }
5526
5527         hdestroy();
5528         NWRAP_UNLOCK_ALL;
5529 }