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