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