]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/idmapd/idmapd.c
rpc.idmapd should tell the user more verbosely if Dnotify
[nfs-utils.git] / utils / idmapd / idmapd.c
1 /*
2  *  idmapd.c
3  *
4  *  Userland daemon for idmap.
5  *
6  *  Copyright (c) 2002 The Regents of the University of Michigan.
7  *  All rights reserved.
8  *
9  *  Marius Aamodt Eriksen <marius@umich.edu>
10  *
11  *  Redistribution and use in source and binary forms, with or without
12  *  modification, are permitted provided that the following conditions
13  *  are met:
14  *
15  *  1. Redistributions of source code must retain the above copyright
16  *     notice, this list of conditions and the following disclaimer.
17  *  2. Redistributions in binary form must reproduce the above copyright
18  *     notice, this list of conditions and the following disclaimer in the
19  *     documentation and/or other materials provided with the distribution.
20  *  3. Neither the name of the University nor the names of its
21  *     contributors may be used to endorse or promote products derived
22  *     from this software without specific prior written permission.
23  *
24  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
25  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
31  *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include <sys/types.h>
38 #include <sys/time.h>
39 #include <sys/poll.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <time.h>
43
44 #include "nfs_idmap.h"
45
46 #include <err.h>
47 #include <errno.h>
48 #include <event.h>
49 #include <fcntl.h>
50 #include <dirent.h>
51 #include <unistd.h>
52 #include <netdb.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <stdarg.h>
58 #include <pwd.h>
59 #include <grp.h>
60 #include <limits.h>
61 #include <ctype.h>
62 #include <nfsidmap.h>
63
64 #ifdef HAVE_CONFIG_H
65 #include "config.h"
66 #endif /* HAVE_CONFIG_H */
67
68 #include "xlog.h"
69 #include "cfg.h"
70 #include "queue.h"
71 #include "nfslib.h"
72
73 #ifndef PIPEFS_DIR
74 #define PIPEFS_DIR  "/var/lib/nfs/rpc_pipefs/"
75 #endif
76
77 #ifndef NFSD_DIR
78 #define NFSD_DIR  "/proc/net/rpc"
79 #endif
80
81 #ifndef CLIENT_CACHE_TIMEOUT_FILE
82 #define CLIENT_CACHE_TIMEOUT_FILE "/proc/sys/fs/nfs/idmap_cache_timeout"
83 #endif
84
85 #ifndef NFS4NOBODY_USER
86 #define NFS4NOBODY_USER "nobody"
87 #endif
88
89 #ifndef NFS4NOBODY_GROUP
90 #define NFS4NOBODY_GROUP "nobody"
91 #endif
92
93 /* From Niels */
94 #define CONF_SAVE(w, f) do {                    \
95         char *p = f;                            \
96         if (p != NULL)                          \
97                 (w) = p;                        \
98 } while (0)
99
100 #define IC_IDNAME 0
101 #define IC_IDNAME_CHAN  NFSD_DIR "/nfs4.idtoname/channel"
102 #define IC_IDNAME_FLUSH NFSD_DIR "/nfs4.idtoname/flush"
103
104 #define IC_NAMEID 1
105 #define IC_NAMEID_CHAN  NFSD_DIR "/nfs4.nametoid/channel"
106 #define IC_NAMEID_FLUSH NFSD_DIR "/nfs4.nametoid/flush"
107
108 struct idmap_client {
109         short                      ic_which;
110         char                       ic_clid[30];
111         char                      *ic_id;
112         char                       ic_path[PATH_MAX];
113         int                        ic_fd;
114         int                        ic_dirfd;
115         int                        ic_scanned;
116         struct event               ic_event;
117         TAILQ_ENTRY(idmap_client)  ic_next;
118 };
119 static struct idmap_client nfsd_ic[2] = {
120 {IC_IDNAME, "Server", "", IC_IDNAME_CHAN, -1, -1, 0},
121 {IC_NAMEID, "Server", "", IC_NAMEID_CHAN, -1, -1, 0},
122 };
123
124 TAILQ_HEAD(idmap_clientq, idmap_client);
125
126 static void dirscancb(int, short, void *);
127 static void clntscancb(int, short, void *);
128 static void svrreopen(int, short, void *);
129 static int  nfsopen(struct idmap_client *);
130 static void nfscb(int, short, void *);
131 static void nfsdcb(int, short, void *);
132 static int  validateascii(char *, u_int32_t);
133 static int  addfield(char **, ssize_t *, char *);
134 static int  getfield(char **, char *, size_t);
135
136 static void imconv(struct idmap_client *, struct idmap_msg *);
137 static void idtonameres(struct idmap_msg *);
138 static void nametoidres(struct idmap_msg *);
139
140 static int nfsdopen(void);
141 static int nfsdopenone(struct idmap_client *);
142 static void nfsdreopen(void);
143
144 size_t  strlcat(char *, const char *, size_t);
145 size_t  strlcpy(char *, const char *, size_t);
146 ssize_t atomicio(ssize_t (*f) (int, void*, size_t),
147                  int, void *, size_t);
148 void    mydaemon(int, int);
149 void    release_parent(void);
150
151 static int verbose = 0;
152 #define DEFAULT_IDMAP_CACHE_EXPIRY 600 /* seconds */
153 static int cache_entry_expiration = 0;
154 static char pipefsdir[PATH_MAX];
155 static char *nobodyuser, *nobodygroup;
156 static uid_t nobodyuid;
157 static gid_t nobodygid;
158
159 /* Used by cfg.c */
160 char *conf_path;
161
162 static int
163 flush_nfsd_cache(char *path, time_t now)
164 {
165         int fd;
166         char stime[20];
167
168         sprintf(stime, "%ld\n", now);
169         fd = open(path, O_RDWR);
170         if (fd == -1)
171                 return -1;
172         write(fd, stime, strlen(stime));
173         close(fd);
174         return 0;
175 }
176
177 static int
178 flush_nfsd_idmap_cache(void)
179 {
180         time_t now = time(NULL);
181         int ret;
182
183         ret = flush_nfsd_cache(IC_IDNAME_FLUSH, now);
184         if (ret)
185                 return ret;
186         ret = flush_nfsd_cache(IC_NAMEID_FLUSH, now);
187         return ret;
188 }
189
190 int
191 main(int argc, char **argv)
192 {
193         int fd = 0, opt, fg = 0, nfsdret = -1;
194         struct idmap_clientq icq;
195         struct event rootdirev, clntdirev, svrdirev;
196         struct event initialize;
197         struct passwd *pw;
198         struct group *gr;
199         struct stat sb;
200         char *xpipefsdir = NULL;
201         int serverstart = 1, clientstart = 1;
202         int ret;
203         char *progname;
204
205         conf_path = _PATH_IDMAPDCONF;
206         nobodyuser = NFS4NOBODY_USER;
207         nobodygroup = NFS4NOBODY_GROUP;
208         strlcpy(pipefsdir, PIPEFS_DIR, sizeof(pipefsdir));
209
210         if ((progname = strrchr(argv[0], '/')))
211                 progname++;
212         else
213                 progname = argv[0];
214         xlog_open(progname);
215
216 #define GETOPTSTR "vfd:p:U:G:c:CS"
217         opterr=0; /* Turn off error messages */
218         while ((opt = getopt(argc, argv, GETOPTSTR)) != -1) {
219                 if (opt == 'c')
220                         conf_path = optarg;
221                 if (opt == '?') {
222                         if (strchr(GETOPTSTR, optopt))
223                                 errx(1, "'-%c' option requires an argument.", optopt);
224                         else
225                                 errx(1, "'-%c' is an invalid argument.", optopt);
226                 }
227         }
228         optind = 1;
229
230         if (stat(conf_path, &sb) == -1 && (errno == ENOENT || errno == EACCES)) {
231                 warn("Skipping configuration file \"%s\"", conf_path);
232                 conf_path = NULL;
233         } else {
234                 conf_init();
235                 verbose = conf_get_num("General", "Verbosity", 0);
236                 cache_entry_expiration = conf_get_num("General",
237                                 "Cache-Expiration", DEFAULT_IDMAP_CACHE_EXPIRY);
238                 CONF_SAVE(xpipefsdir, conf_get_str("General", "Pipefs-Directory"));
239                 if (xpipefsdir != NULL)
240                         strlcpy(pipefsdir, xpipefsdir, sizeof(pipefsdir));
241                 CONF_SAVE(nobodyuser, conf_get_str("Mapping", "Nobody-User"));
242                 CONF_SAVE(nobodygroup, conf_get_str("Mapping", "Nobody-Group"));
243         }
244
245         while ((opt = getopt(argc, argv, GETOPTSTR)) != -1)
246                 switch (opt) {
247                 case 'v':
248                         verbose++;
249                         break;
250                 case 'f':
251                         fg = 1;
252                         break;
253                 case 'p':
254                         strlcpy(pipefsdir, optarg, sizeof(pipefsdir));
255                         break;
256                 case 'd':
257                 case 'U':
258                 case 'G':
259                         errx(1, "the -d, -U, and -G options have been removed;"
260                                 " please use the configuration file instead.");
261                 case 'C':
262                         serverstart = 0;
263                         break;
264                 case 'S':
265                         clientstart = 0;
266                         break;
267                 default:
268                         break;
269                 }
270
271         if (!serverstart && !clientstart)
272                 errx(1, "it is illegal to specify both -C and -S");
273
274         strncat(pipefsdir, "/nfs", sizeof(pipefsdir));
275
276         if ((pw = getpwnam(nobodyuser)) == NULL)
277                 errx(1, "Could not find user \"%s\"", nobodyuser);
278         nobodyuid = pw->pw_uid;
279
280         if ((gr = getgrnam(nobodygroup)) == NULL)
281                 errx(1, "Could not find group \"%s\"", nobodygroup);
282         nobodygid = gr->gr_gid;
283
284 #ifdef HAVE_NFS4_SET_DEBUG
285         nfs4_set_debug(verbose, xlog_warn);
286 #endif
287         if (conf_path == NULL)
288                 conf_path = _PATH_IDMAPDCONF;
289         if (nfs4_init_name_mapping(conf_path))
290                 errx(1, "Unable to create name to user id mappings.");
291
292         if (!fg)
293                 mydaemon(0, 0);
294
295         event_init();
296
297         if (verbose > 0)
298                 xlog_warn("Expiration time is %d seconds.",
299                              cache_entry_expiration);
300         if (serverstart) {
301                 nfsdret = nfsdopen();
302                 if (nfsdret == 0) {
303                         ret = flush_nfsd_idmap_cache();
304                         if (ret)
305                                 xlog_err("main: Failed to flush nfsd idmap cache\n: %s", strerror(errno));
306                 }
307         }
308
309         if (clientstart) {
310                 struct timeval now = {
311                         .tv_sec = 0,
312                         .tv_usec = 0,
313                 };
314
315                 if (cache_entry_expiration != DEFAULT_IDMAP_CACHE_EXPIRY) {
316                         int timeout_fd, len;
317                         char timeout_buf[12];
318                         if ((timeout_fd = open(CLIENT_CACHE_TIMEOUT_FILE,
319                                                O_RDWR)) == -1) {
320                                 xlog_warn("Unable to open '%s' to set "
321                                              "client cache expiration time "
322                                              "to %d seconds\n",
323                                              CLIENT_CACHE_TIMEOUT_FILE,
324                                              cache_entry_expiration);
325                         } else {
326                                 len = snprintf(timeout_buf, sizeof(timeout_buf),
327                                                "%d", cache_entry_expiration);
328                                 if ((write(timeout_fd, timeout_buf, len)) != len)
329                                         xlog_warn("Error writing '%s' to "
330                                                      "'%s' to set client "
331                                                      "cache expiration time\n",
332                                                      timeout_buf,
333                                                      CLIENT_CACHE_TIMEOUT_FILE);
334                                 close(timeout_fd);
335                         }
336                 }
337
338                 if ((fd = open(pipefsdir, O_RDONLY)) == -1)
339                         xlog_err("main: open(%s): %s", pipefsdir, strerror(errno));
340
341                 if (fcntl(fd, F_SETSIG, SIGUSR1) == -1)
342                         xlog_err("main: fcntl(%s): %s", pipefsdir, strerror(errno));
343
344                 if (fcntl(fd, F_NOTIFY,
345                         DN_CREATE | DN_DELETE | DN_MODIFY | DN_MULTISHOT) == -1) {
346                         xlog_err("main: fcntl(%s): %s", pipefsdir, strerror(errno));
347                         if (errno == EINVAL)
348                                 xlog_err("main: Possibly no Dnotify support in kernel.");
349                 }
350                 TAILQ_INIT(&icq);
351
352                 /* These events are persistent */
353                 signal_set(&rootdirev, SIGUSR1, dirscancb, &icq);
354                 signal_add(&rootdirev, NULL);
355                 signal_set(&clntdirev, SIGUSR2, clntscancb, &icq);
356                 signal_add(&clntdirev, NULL);
357                 signal_set(&svrdirev, SIGHUP, svrreopen, NULL);
358                 signal_add(&svrdirev, NULL);
359
360                 /* Fetch current state */
361                 /* (Delay till start of event_dispatch to avoid possibly losing
362                  * a SIGUSR1 between here and the call to event_dispatch().) */
363                 evtimer_set(&initialize, dirscancb, &icq);
364                 evtimer_add(&initialize, &now);
365         }
366
367         if (nfsdret != 0 && fd == 0)
368                 xlog_err("main: Neither NFS client nor NFSd found");
369
370         release_parent();
371
372         if (event_dispatch() < 0)
373                 xlog_err("main: event_dispatch returns errno %d (%s)",
374                             errno, strerror(errno));
375         /* NOTREACHED */
376         return 1;
377 }
378
379 static void
380 dirscancb(int fd, short which, void *data)
381 {
382         int nent, i;
383         struct dirent **ents;
384         struct idmap_client *ic, *nextic;
385         char path[PATH_MAX];
386         struct idmap_clientq *icq = data;
387
388         nent = scandir(pipefsdir, &ents, NULL, alphasort);
389         if (nent == -1) {
390                 xlog_warn("dirscancb: scandir(%s): %s", pipefsdir, strerror(errno));
391                 return;
392         }
393
394         for (i = 0;  i < nent; i++) {
395                 if (ents[i]->d_reclen > 4 &&
396                     strncmp(ents[i]->d_name, "clnt", 4) == 0) {
397                         TAILQ_FOREACH(ic, icq, ic_next)
398                             if (strcmp(ents[i]->d_name + 4, ic->ic_clid) == 0)
399                                     break;
400                         if (ic != NULL)
401                                 goto next;
402
403                         if ((ic = calloc(1, sizeof(*ic))) == NULL)
404                                 goto out;
405                         strlcpy(ic->ic_clid, ents[i]->d_name + 4,
406                             sizeof(ic->ic_clid));
407                         path[0] = '\0';
408                         snprintf(path, sizeof(path), "%s/%s",
409                             pipefsdir, ents[i]->d_name);
410
411                         if ((ic->ic_dirfd = open(path, O_RDONLY, 0)) == -1) {
412                                 xlog_warn("dirscancb: open(%s): %s", path, strerror(errno));
413                                 free(ic);
414                                 goto out;
415                         }
416
417                         strlcat(path, "/idmap", sizeof(path));
418                         strlcpy(ic->ic_path, path, sizeof(ic->ic_path));
419
420                         if (verbose > 0)
421                                 xlog_warn("New client: %s", ic->ic_clid);
422
423                         if (nfsopen(ic) == -1) {
424                                 close(ic->ic_dirfd);
425                                 free(ic);
426                                 goto out;
427                         }
428
429                         ic->ic_id = "Client";
430
431                         TAILQ_INSERT_TAIL(icq, ic, ic_next);
432
433                 next:
434                         ic->ic_scanned = 1;
435                 }
436         }
437
438         ic = TAILQ_FIRST(icq);
439         while(ic != NULL) {
440                 nextic=TAILQ_NEXT(ic, ic_next);
441                 if (!ic->ic_scanned) {
442                         event_del(&ic->ic_event);
443                         close(ic->ic_fd);
444                         close(ic->ic_dirfd);
445                         TAILQ_REMOVE(icq, ic, ic_next);
446                         if (verbose > 0) {
447                                 xlog_warn("Stale client: %s", ic->ic_clid);
448                                 xlog_warn("\t-> closed %s", ic->ic_path);
449                         }
450                         free(ic);
451                 } else
452                         ic->ic_scanned = 0;
453                 ic = nextic;
454         }
455
456 out:
457         for (i = 0;  i < nent; i++)
458                 free(ents[i]);
459         free(ents);
460         return;
461 }
462
463 static void
464 svrreopen(int fd, short which, void *data)
465 {
466         nfsdreopen();
467 }
468
469 static void
470 clntscancb(int fd, short which, void *data)
471 {
472         struct idmap_clientq *icq = data;
473         struct idmap_client *ic;
474
475         TAILQ_FOREACH(ic, icq, ic_next)
476                 if (ic->ic_fd == -1 && nfsopen(ic) == -1) {
477                         close(ic->ic_dirfd);
478                         TAILQ_REMOVE(icq, ic, ic_next);
479                         free(ic);
480                 }
481 }
482
483 static void
484 nfsdcb(int fd, short which, void *data)
485 {
486         struct idmap_client *ic = data;
487         struct idmap_msg im;
488         u_char buf[IDMAP_MAXMSGSZ + 1];
489         size_t len;
490         ssize_t bsiz;
491         char *bp, typebuf[IDMAP_MAXMSGSZ],
492                 buf1[IDMAP_MAXMSGSZ], authbuf[IDMAP_MAXMSGSZ], *p;
493         unsigned long tmp;
494
495         if (which != EV_READ)
496                 goto out;
497
498         if ((len = read(ic->ic_fd, buf, sizeof(buf))) <= 0) {
499                 xlog_warn("nfsdcb: read(%s) failed: errno %d (%s)",
500                              ic->ic_path, len?errno:0, 
501                              len?strerror(errno):"End of File");
502                 goto out;
503         }
504
505         /* Get rid of newline and terminate buffer*/
506         buf[len - 1] = '\0';
507         bp = (char *)buf;
508
509         memset(&im, 0, sizeof(im));
510
511         /* Authentication name -- ignored for now*/
512         if (getfield(&bp, authbuf, sizeof(authbuf)) == -1) {
513                 xlog_warn("nfsdcb: bad authentication name in upcall\n");
514                 return;
515         }
516         if (getfield(&bp, typebuf, sizeof(typebuf)) == -1) {
517                 xlog_warn("nfsdcb: bad type in upcall\n");
518                 return;
519         }
520         if (verbose > 0)
521                 xlog_warn("nfsdcb: authbuf=%s authtype=%s",
522                              authbuf, typebuf);
523
524         im.im_type = strcmp(typebuf, "user") == 0 ?
525                 IDMAP_TYPE_USER : IDMAP_TYPE_GROUP;
526
527         switch (ic->ic_which) {
528         case IC_NAMEID:
529                 im.im_conv = IDMAP_CONV_NAMETOID;
530                 if (getfield(&bp, im.im_name, sizeof(im.im_name)) == -1) {
531                         xlog_warn("nfsdcb: bad name in upcall\n");
532                         return;
533                 }
534                 break;
535         case IC_IDNAME:
536                 im.im_conv = IDMAP_CONV_IDTONAME;
537                 if (getfield(&bp, buf1, sizeof(buf1)) == -1) {
538                         xlog_warn("nfsdcb: bad id in upcall\n");
539                         return;
540                 }
541                 tmp = strtoul(buf1, (char **)NULL, 10);
542                 im.im_id = (u_int32_t)tmp;
543                 if ((tmp == ULONG_MAX && errno == ERANGE)
544                                 || (unsigned long)im.im_id != tmp) {
545                         xlog_warn("nfsdcb: id '%s' too big!\n", buf1);
546                         return;
547                 }
548                 break;
549         default:
550                 xlog_warn("nfsdcb: Unknown which type %d", ic->ic_which);
551                 return;
552         }
553
554         imconv(ic, &im);
555
556         buf[0] = '\0';
557         bp = (char *)buf;
558         bsiz = sizeof(buf);
559
560         /* Authentication name */
561         addfield(&bp, &bsiz, authbuf);
562
563         switch (ic->ic_which) {
564         case IC_NAMEID:
565                 /* Type */
566                 p = im.im_type == IDMAP_TYPE_USER ? "user" : "group";
567                 addfield(&bp, &bsiz, p);
568                 /* Name */
569                 addfield(&bp, &bsiz, im.im_name);
570                 /* expiry */
571                 snprintf(buf1, sizeof(buf1), "%lu",
572                          time(NULL) + cache_entry_expiration);
573                 addfield(&bp, &bsiz, buf1);
574                 /* Note that we don't want to write the id if the mapping
575                  * failed; instead, by leaving it off, we write a negative
576                  * cache entry which will result in an error returned to
577                  * the client.  We don't want a chown or setacl referring
578                  * to an unknown user to result in giving permissions to
579                  * "nobody"! */
580                 if (im.im_status == IDMAP_STATUS_SUCCESS) {
581                         /* ID */
582                         snprintf(buf1, sizeof(buf1), "%u", im.im_id);
583                         addfield(&bp, &bsiz, buf1);
584
585                 }
586                 //if (bsiz == sizeof(buf)) /* XXX */
587
588                 bp[-1] = '\n';
589
590                 break;
591         case IC_IDNAME:
592                 /* Type */
593                 p = im.im_type == IDMAP_TYPE_USER ? "user" : "group";
594                 addfield(&bp, &bsiz, p);
595                 /* ID */
596                 snprintf(buf1, sizeof(buf1), "%u", im.im_id);
597                 addfield(&bp, &bsiz, buf1);
598                 /* expiry */
599                 snprintf(buf1, sizeof(buf1), "%lu",
600                          time(NULL) + cache_entry_expiration);
601                 addfield(&bp, &bsiz, buf1);
602                 /* Note we're ignoring the status field in this case; we'll
603                  * just map to nobody instead. */
604                 /* Name */
605                 addfield(&bp, &bsiz, im.im_name);
606
607                 bp[-1] = '\n';
608
609                 break;
610         default:
611                 xlog_warn("nfsdcb: Unknown which type %d", ic->ic_which);
612                 return;
613         }
614
615         bsiz = sizeof(buf) - bsiz;
616
617         if (atomicio((void*)write, ic->ic_fd, buf, bsiz) != bsiz)
618                 xlog_warn("nfsdcb: write(%s) failed: errno %d (%s)",
619                              ic->ic_path, errno, strerror(errno));
620
621 out:
622         event_add(&ic->ic_event, NULL);
623 }
624
625 static void
626 imconv(struct idmap_client *ic, struct idmap_msg *im)
627 {
628         switch (im->im_conv) {
629         case IDMAP_CONV_IDTONAME:
630                 idtonameres(im);
631                 if (verbose > 1)
632                         xlog_warn("%s %s: (%s) id \"%d\" -> name \"%s\"",
633                             ic->ic_id, ic->ic_clid,
634                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
635                             im->im_id, im->im_name);
636                 break;
637         case IDMAP_CONV_NAMETOID:
638                 if (validateascii(im->im_name, sizeof(im->im_name)) == -1) {
639                         im->im_status |= IDMAP_STATUS_INVALIDMSG;
640                         return;
641                 }
642                 nametoidres(im);
643                 if (verbose > 1)
644                         xlog_warn("%s %s: (%s) name \"%s\" -> id \"%d\"",
645                             ic->ic_id, ic->ic_clid,
646                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
647                             im->im_name, im->im_id);
648                 break;
649         default:
650                 xlog_warn("imconv: Invalid conversion type (%d) in message",
651                              im->im_conv);
652                 im->im_status |= IDMAP_STATUS_INVALIDMSG;
653                 break;
654         }
655 }
656
657 static void
658 nfscb(int fd, short which, void *data)
659 {
660         struct idmap_client *ic = data;
661         struct idmap_msg im;
662
663         if (which != EV_READ)
664                 goto out;
665
666         if (atomicio(read, ic->ic_fd, &im, sizeof(im)) != sizeof(im)) {
667                 if (verbose > 0)
668                         xlog_warn("nfscb: read(%s): %s", ic->ic_path, strerror(errno));
669                 if (errno == EPIPE)
670                         return;
671                 goto out;
672         }
673
674         imconv(ic, &im);
675
676         /* XXX: I don't like ignoring this error in the id->name case,
677          * but we've never returned it, and I need to check that the client
678          * can handle it gracefully before starting to return it now. */
679
680         if (im.im_status == IDMAP_STATUS_LOOKUPFAIL)
681                 im.im_status = IDMAP_STATUS_SUCCESS;
682
683         if (atomicio((void*)write, ic->ic_fd, &im, sizeof(im)) != sizeof(im))
684                 xlog_warn("nfscb: write(%s): %s", ic->ic_path, strerror(errno));
685 out:
686         event_add(&ic->ic_event, NULL);
687 }
688
689 static void
690 nfsdreopen_one(struct idmap_client *ic)
691 {
692         int fd;
693
694         if (verbose > 0)
695                 xlog_warn("ReOpening %s", ic->ic_path);
696
697         if ((fd = open(ic->ic_path, O_RDWR, 0)) != -1) {
698                 if ((ic->ic_event.ev_flags & EVLIST_INIT))
699                         event_del(&ic->ic_event);
700                 if (ic->ic_fd != -1)
701                         close(ic->ic_fd);
702
703                 ic->ic_event.ev_fd = ic->ic_fd = fd;
704                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
705                 event_add(&ic->ic_event, NULL);
706         } else {
707                 xlog_warn("nfsdreopen: Opening '%s' failed: errno %d (%s)",
708                         ic->ic_path, errno, strerror(errno));
709         }
710 }
711
712 static void
713 nfsdreopen()
714 {
715         nfsdreopen_one(&nfsd_ic[IC_NAMEID]);
716         nfsdreopen_one(&nfsd_ic[IC_IDNAME]);
717         return;
718 }
719
720 static int
721 nfsdopen(void)
722 {
723         return ((nfsdopenone(&nfsd_ic[IC_NAMEID]) == 0 &&
724                     nfsdopenone(&nfsd_ic[IC_IDNAME]) == 0) ? 0 : -1);
725 }
726
727 static int
728 nfsdopenone(struct idmap_client *ic)
729 {
730         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
731                 if (verbose > 0)
732                         xlog_warn("nfsdopenone: Opening %s failed: "
733                                 "errno %d (%s)",
734                                 ic->ic_path, errno, strerror(errno));
735                 return (-1);
736         }
737
738         event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
739         event_add(&ic->ic_event, NULL);
740
741         if (verbose > 0)
742                 xlog_warn("Opened %s", ic->ic_path);
743
744         return (0);
745 }
746
747 static int
748 nfsopen(struct idmap_client *ic)
749 {
750         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
751                 switch (errno) {
752                 case ENOENT:
753                         fcntl(ic->ic_dirfd, F_SETSIG, SIGUSR2);
754                         fcntl(ic->ic_dirfd, F_NOTIFY,
755                             DN_CREATE | DN_DELETE | DN_MULTISHOT);
756                         break;
757                 default:
758                         xlog_warn("nfsopen: open(%s): %s", ic->ic_path, strerror(errno));
759                         return (-1);
760                 }
761         } else {
762                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfscb, ic);
763                 event_add(&ic->ic_event, NULL);
764                 fcntl(ic->ic_dirfd, F_SETSIG, 0);
765                 fcntl(ic->ic_dirfd, F_NOTIFY, 0);
766                 if (verbose > 0)
767                         xlog_warn("Opened %s", ic->ic_path);
768         }
769
770         return (0);
771 }
772
773 static void
774 idtonameres(struct idmap_msg *im)
775 {
776         char domain[NFS4_MAX_DOMAIN_LEN];
777         int ret = 0;
778
779         ret = nfs4_get_default_domain(NULL, domain, sizeof(domain));
780         switch (im->im_type) {
781         case IDMAP_TYPE_USER:
782                 ret = nfs4_uid_to_name(im->im_id, domain, im->im_name,
783                                 sizeof(im->im_name));
784                 if (ret) {
785                         if (strlen(nobodyuser) < sizeof(im->im_name))
786                                 strcpy(im->im_name, nobodyuser);
787                         else
788                                 strcpy(im->im_name, NFS4NOBODY_USER);
789                 }
790                 break;
791         case IDMAP_TYPE_GROUP:
792                 ret = nfs4_gid_to_name(im->im_id, domain, im->im_name,
793                                 sizeof(im->im_name));
794                 if (ret) {
795                         if (strlen(nobodygroup) < sizeof(im->im_name))
796                                 strcpy(im->im_name, nobodygroup);
797                         else
798                                 strcpy(im->im_name, NFS4NOBODY_GROUP);
799                 }
800                 break;
801         }
802         if (ret)
803                 im->im_status = IDMAP_STATUS_LOOKUPFAIL;
804         else
805                 im->im_status = IDMAP_STATUS_SUCCESS;
806 }
807
808 static void
809 nametoidres(struct idmap_msg *im)
810 {
811         uid_t uid;
812         gid_t gid;
813         int ret = 0;
814
815         /* XXX: move nobody stuff to library calls
816          * (nfs4_get_nobody_user(domain), nfs4_get_nobody_group(domain)) */
817
818         im->im_status = IDMAP_STATUS_SUCCESS;
819
820         switch (im->im_type) {
821         case IDMAP_TYPE_USER:
822                 ret = nfs4_name_to_uid(im->im_name, &uid);
823                 im->im_id = (u_int32_t) uid;
824                 if (ret) {
825                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
826                         im->im_id = nobodyuid;
827                 }
828                 return;
829         case IDMAP_TYPE_GROUP:
830                 ret = nfs4_name_to_gid(im->im_name, &gid);
831                 im->im_id = (u_int32_t) gid;
832                 if (ret) {
833                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
834                         im->im_id = nobodygid;
835                 }
836                 return;
837         }
838 }
839
840 static int
841 validateascii(char *string, u_int32_t len)
842 {
843         int i;
844
845         for (i = 0; i < len; i++) {
846                 if (string[i] == '\0')
847                         break;
848
849                 if (string[i] & 0x80)
850                         return (-1);
851         }
852
853         if ((i >= len) || string[i] != '\0')
854                 return (-1);
855
856         return (i + 1);
857 }
858
859 static int
860 addfield(char **bpp, ssize_t *bsizp, char *fld)
861 {
862         char ch, *bp = *bpp;
863         ssize_t bsiz = *bsizp;
864
865         while ((ch = *fld++) != '\0' && bsiz > 0) {
866                 switch(ch) {
867                 case ' ':
868                 case '\t':
869                 case '\n':
870                 case '\\':
871                         if (bsiz >= 4) {
872                                 bp += snprintf(bp, bsiz, "\\%03o", ch);
873                                 bsiz -= 4;
874                         }
875                         break;
876                 default:
877                         *bp++ = ch;
878                         bsiz--;
879                         break;
880                 }
881         }
882
883         if (bsiz < 1 || ch != '\0')
884                 return (-1);
885
886         *bp++ = ' ';
887         bsiz--;
888
889         *bpp = bp;
890         *bsizp = bsiz;
891
892         return (0);
893 }
894
895 static int
896 getfield(char **bpp, char *fld, size_t fldsz)
897 {
898         char *bp;
899         u_int val, n;
900
901         while ((bp = strsep(bpp, " ")) != NULL && bp[0] == '\0')
902                 ;
903
904         if (bp == NULL || bp[0] == '\0' || bp[0] == '\n')
905                 return (-1);
906
907         while (*bp != '\0' && fldsz > 1) {
908                 if (*bp == '\\') {
909                         if ((n = sscanf(bp, "\\%03o", &val)) != 1)
910                                 return (-1);
911                         if (val > (char)-1)
912                                 return (-1);
913                         *fld++ = (char)val;
914                         bp += 4;
915                 } else {
916                         *fld++ = *bp;
917                         bp++;
918                 }
919                 fldsz--;
920         }
921
922         if (*bp != '\0')
923                 return (-1);
924         *fld = '\0';
925
926         return (0);
927 }
928 /*
929  * mydaemon creates a pipe between the partent and child
930  * process. The parent process will wait until the
931  * child dies or writes a '1' on the pipe signaling
932  * that it started successfully.
933  */
934 int pipefds[2] = { -1, -1};
935
936 void
937 mydaemon(int nochdir, int noclose)
938 {
939         int pid, status, tempfd;
940
941         if (pipe(pipefds) < 0)
942                 err(1, "mydaemon: pipe() failed: errno %d", errno);
943
944         if ((pid = fork ()) < 0)
945                 err(1, "mydaemon: fork() failed: errno %d", errno);
946
947         if (pid != 0) {
948                 /*
949                  * Parent. Wait for status from child.
950                  */
951                 close(pipefds[1]);
952                 if (read(pipefds[0], &status, 1) != 1)
953                         exit(1);
954                 exit (0);
955         }
956         /* Child.       */
957         close(pipefds[0]);
958         setsid ();
959         if (nochdir == 0) {
960                 if (chdir ("/") == -1)
961                         err(1, "mydaemon: chdir() failed: errno %d", errno);
962         }
963
964         while (pipefds[1] <= 2) {
965                 pipefds[1] = dup(pipefds[1]);
966                 if (pipefds[1] < 0)
967                         err(1, "mydaemon: dup() failed: errno %d", errno);
968         }
969
970         if (noclose == 0) {
971                 tempfd = open("/dev/null", O_RDWR);
972                 if (tempfd < 0)
973                         tempfd = open("/", O_RDONLY);
974                 if (tempfd >= 0) {
975                         dup2(tempfd, 0);
976                         dup2(tempfd, 1);
977                         dup2(tempfd, 2);
978                         closeall(3);
979                 } else
980                         closeall(0);
981         }
982
983         return;
984 }
985 void
986 release_parent(void)
987 {
988         int status;
989
990         if (pipefds[1] > 0) {
991                 write(pipefds[1], &status, 1);
992                 close(pipefds[1]);
993                 pipefds[1] = -1;
994         }
995 }