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