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