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