]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/idmapd/idmapd.c
idmapd: allow non-ASCII characters (UTF-8) in NFSv4 domain name
[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                                 xlog_warn("dirscancb: open(%s): %s", path, strerror(errno));
428                                 free(ic);
429                                 goto out;
430                         }
431
432                         strlcat(path, "/idmap", sizeof(path));
433                         strlcpy(ic->ic_path, path, sizeof(ic->ic_path));
434
435                         if (verbose > 0)
436                                 xlog_warn("New client: %s", ic->ic_clid);
437
438                         if (nfsopen(ic) == -1) {
439                                 close(ic->ic_dirfd);
440                                 free(ic);
441                                 goto out;
442                         }
443
444                         ic->ic_id = "Client";
445
446                         TAILQ_INSERT_TAIL(icq, ic, ic_next);
447
448                 next:
449                         ic->ic_scanned = 1;
450                 }
451         }
452
453         ic = TAILQ_FIRST(icq);
454         while(ic != NULL) {
455                 nextic=TAILQ_NEXT(ic, ic_next);
456                 if (!ic->ic_scanned) {
457                         event_del(&ic->ic_event);
458                         close(ic->ic_fd);
459                         close(ic->ic_dirfd);
460                         TAILQ_REMOVE(icq, ic, ic_next);
461                         if (verbose > 0) {
462                                 xlog_warn("Stale client: %s", ic->ic_clid);
463                                 xlog_warn("\t-> closed %s", ic->ic_path);
464                         }
465                         free(ic);
466                 } else
467                         ic->ic_scanned = 0;
468                 ic = nextic;
469         }
470
471 out:
472         for (i = 0;  i < nent; i++)
473                 free(ents[i]);
474         free(ents);
475         return;
476 }
477
478 static void
479 svrreopen(int UNUSED(fd), short UNUSED(which), void *UNUSED(data))
480 {
481         nfsdreopen();
482 }
483
484 static void
485 clntscancb(int UNUSED(fd), short UNUSED(which), void *data)
486 {
487         struct idmap_clientq *icq = data;
488         struct idmap_client *ic;
489
490         TAILQ_FOREACH(ic, icq, ic_next)
491                 if (ic->ic_fd == -1 && nfsopen(ic) == -1) {
492                         close(ic->ic_dirfd);
493                         TAILQ_REMOVE(icq, ic, ic_next);
494                         free(ic);
495                 }
496 }
497
498 static void
499 nfsdcb(int UNUSED(fd), short which, void *data)
500 {
501         struct idmap_client *ic = data;
502         struct idmap_msg im;
503         u_char buf[IDMAP_MAXMSGSZ + 1];
504         size_t len;
505         ssize_t bsiz;
506         char *bp, typebuf[IDMAP_MAXMSGSZ],
507                 buf1[IDMAP_MAXMSGSZ], authbuf[IDMAP_MAXMSGSZ], *p;
508         unsigned long tmp;
509
510         if (which != EV_READ)
511                 goto out;
512
513         if ((len = read(ic->ic_fd, buf, sizeof(buf))) <= 0) {
514                 xlog_warn("nfsdcb: read(%s) failed: errno %d (%s)",
515                              ic->ic_path, len?errno:0, 
516                              len?strerror(errno):"End of File");
517                 nfsdreopen_one(ic);
518                 return;
519         }
520
521         /* Get rid of newline and terminate buffer*/
522         buf[len - 1] = '\0';
523         bp = (char *)buf;
524
525         memset(&im, 0, sizeof(im));
526
527         /* Authentication name -- ignored for now*/
528         if (getfield(&bp, authbuf, sizeof(authbuf)) == -1) {
529                 xlog_warn("nfsdcb: bad authentication name in upcall\n");
530                 goto out;
531         }
532         if (getfield(&bp, typebuf, sizeof(typebuf)) == -1) {
533                 xlog_warn("nfsdcb: bad type in upcall\n");
534                 goto out;
535         }
536         if (verbose > 0)
537                 xlog_warn("nfsdcb: authbuf=%s authtype=%s",
538                              authbuf, typebuf);
539
540         im.im_type = strcmp(typebuf, "user") == 0 ?
541                 IDMAP_TYPE_USER : IDMAP_TYPE_GROUP;
542
543         switch (ic->ic_which) {
544         case IC_NAMEID:
545                 im.im_conv = IDMAP_CONV_NAMETOID;
546                 if (getfield(&bp, im.im_name, sizeof(im.im_name)) == -1) {
547                         xlog_warn("nfsdcb: bad name in upcall\n");
548                         goto out;
549                 }
550                 break;
551         case IC_IDNAME:
552                 im.im_conv = IDMAP_CONV_IDTONAME;
553                 if (getfield(&bp, buf1, sizeof(buf1)) == -1) {
554                         xlog_warn("nfsdcb: bad id in upcall\n");
555                         goto out;
556                 }
557                 tmp = strtoul(buf1, (char **)NULL, 10);
558                 im.im_id = (u_int32_t)tmp;
559                 if ((tmp == ULONG_MAX && errno == ERANGE)
560                                 || (unsigned long)im.im_id != tmp) {
561                         xlog_warn("nfsdcb: id '%s' too big!\n", buf1);
562                         goto out;
563                 }
564                 break;
565         default:
566                 xlog_warn("nfsdcb: Unknown which type %d", ic->ic_which);
567                 goto out;
568         }
569
570         imconv(ic, &im);
571
572         buf[0] = '\0';
573         bp = (char *)buf;
574         bsiz = sizeof(buf);
575
576         /* Authentication name */
577         addfield(&bp, &bsiz, authbuf);
578
579         switch (ic->ic_which) {
580         case IC_NAMEID:
581                 /* Type */
582                 p = im.im_type == IDMAP_TYPE_USER ? "user" : "group";
583                 addfield(&bp, &bsiz, p);
584                 /* Name */
585                 addfield(&bp, &bsiz, im.im_name);
586                 /* expiry */
587                 snprintf(buf1, sizeof(buf1), "%lu",
588                          time(NULL) + cache_entry_expiration);
589                 addfield(&bp, &bsiz, buf1);
590                 /* Note that we don't want to write the id if the mapping
591                  * failed; instead, by leaving it off, we write a negative
592                  * cache entry which will result in an error returned to
593                  * the client.  We don't want a chown or setacl referring
594                  * to an unknown user to result in giving permissions to
595                  * "nobody"! */
596                 if (im.im_status == IDMAP_STATUS_SUCCESS) {
597                         /* ID */
598                         snprintf(buf1, sizeof(buf1), "%u", im.im_id);
599                         addfield(&bp, &bsiz, buf1);
600
601                 }
602                 //if (bsiz == sizeof(buf)) /* XXX */
603
604                 bp[-1] = '\n';
605
606                 break;
607         case IC_IDNAME:
608                 /* Type */
609                 p = im.im_type == IDMAP_TYPE_USER ? "user" : "group";
610                 addfield(&bp, &bsiz, p);
611                 /* ID */
612                 snprintf(buf1, sizeof(buf1), "%u", im.im_id);
613                 addfield(&bp, &bsiz, buf1);
614                 /* expiry */
615                 snprintf(buf1, sizeof(buf1), "%lu",
616                          time(NULL) + cache_entry_expiration);
617                 addfield(&bp, &bsiz, buf1);
618                 /* Note we're ignoring the status field in this case; we'll
619                  * just map to nobody instead. */
620                 /* Name */
621                 addfield(&bp, &bsiz, im.im_name);
622
623                 bp[-1] = '\n';
624
625                 break;
626         default:
627                 xlog_warn("nfsdcb: Unknown which type %d", ic->ic_which);
628                 goto out;
629         }
630
631         bsiz = sizeof(buf) - bsiz;
632
633         if (atomicio((void*)write, ic->ic_fd, buf, bsiz) != bsiz)
634                 xlog_warn("nfsdcb: write(%s) failed: errno %d (%s)",
635                              ic->ic_path, errno, strerror(errno));
636
637 out:
638         event_add(&ic->ic_event, NULL);
639 }
640
641 static void
642 imconv(struct idmap_client *ic, struct idmap_msg *im)
643 {
644         u_int32_t len;
645
646         switch (im->im_conv) {
647         case IDMAP_CONV_IDTONAME:
648                 idtonameres(im);
649                 if (verbose > 1)
650                         xlog_warn("%s %s: (%s) id \"%d\" -> name \"%s\"",
651                             ic->ic_id, ic->ic_clid,
652                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
653                             im->im_id, im->im_name);
654                 break;
655         case IDMAP_CONV_NAMETOID:
656                 len = strnlen(im->im_name, IDMAP_NAMESZ - 1);
657                 /* Check for NULL termination just to be careful */
658                 if (im->im_name[len+1] != '\0')
659                         return;
660                 nametoidres(im);
661                 if (verbose > 1)
662                         xlog_warn("%s %s: (%s) name \"%s\" -> id \"%d\"",
663                             ic->ic_id, ic->ic_clid,
664                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
665                             im->im_name, im->im_id);
666                 break;
667         default:
668                 xlog_warn("imconv: Invalid conversion type (%d) in message",
669                              im->im_conv);
670                 im->im_status |= IDMAP_STATUS_INVALIDMSG;
671                 break;
672         }
673 }
674
675 static void
676 nfscb(int UNUSED(fd), short which, void *data)
677 {
678         struct idmap_client *ic = data;
679         struct idmap_msg im;
680
681         if (which != EV_READ)
682                 goto out;
683
684         if (atomicio(read, ic->ic_fd, &im, sizeof(im)) != sizeof(im)) {
685                 if (verbose > 0)
686                         xlog_warn("nfscb: read(%s): %s", ic->ic_path, strerror(errno));
687                 if (errno == EPIPE)
688                         return;
689                 goto out;
690         }
691
692         imconv(ic, &im);
693
694         /* XXX: I don't like ignoring this error in the id->name case,
695          * but we've never returned it, and I need to check that the client
696          * can handle it gracefully before starting to return it now. */
697
698         if (im.im_status == IDMAP_STATUS_LOOKUPFAIL)
699                 im.im_status = IDMAP_STATUS_SUCCESS;
700
701         if (atomicio((void*)write, ic->ic_fd, &im, sizeof(im)) != sizeof(im))
702                 xlog_warn("nfscb: write(%s): %s", ic->ic_path, strerror(errno));
703 out:
704         event_add(&ic->ic_event, NULL);
705 }
706
707 static void
708 nfsdreopen_one(struct idmap_client *ic)
709 {
710         int fd;
711
712         if (verbose > 0)
713                 xlog_warn("ReOpening %s", ic->ic_path);
714
715         if ((fd = open(ic->ic_path, O_RDWR, 0)) != -1) {
716                 if ((ic->ic_event.ev_flags & EVLIST_INIT))
717                         event_del(&ic->ic_event);
718                 if (ic->ic_fd != -1)
719                         close(ic->ic_fd);
720
721                 ic->ic_event.ev_fd = ic->ic_fd = fd;
722                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
723                 event_add(&ic->ic_event, NULL);
724         } else {
725                 xlog_warn("nfsdreopen: Opening '%s' failed: errno %d (%s)",
726                         ic->ic_path, errno, strerror(errno));
727         }
728 }
729
730 static void
731 nfsdreopen()
732 {
733         nfsdreopen_one(&nfsd_ic[IC_NAMEID]);
734         nfsdreopen_one(&nfsd_ic[IC_IDNAME]);
735         return;
736 }
737
738 static int
739 nfsdopen(void)
740 {
741         return ((nfsdopenone(&nfsd_ic[IC_NAMEID]) == 0 &&
742                     nfsdopenone(&nfsd_ic[IC_IDNAME]) == 0) ? 0 : -1);
743 }
744
745 static int
746 nfsdopenone(struct idmap_client *ic)
747 {
748         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
749                 if (verbose > 0)
750                         xlog_warn("nfsdopenone: Opening %s failed: "
751                                 "errno %d (%s)",
752                                 ic->ic_path, errno, strerror(errno));
753                 return (-1);
754         }
755
756         event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
757         event_add(&ic->ic_event, NULL);
758
759         if (verbose > 0)
760                 xlog_warn("Opened %s", ic->ic_path);
761
762         return (0);
763 }
764
765 static int
766 nfsopen(struct idmap_client *ic)
767 {
768         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
769                 switch (errno) {
770                 case ENOENT:
771                         fcntl(ic->ic_dirfd, F_SETSIG, SIGUSR2);
772                         fcntl(ic->ic_dirfd, F_NOTIFY,
773                             DN_CREATE | DN_DELETE | DN_MULTISHOT);
774                         break;
775                 default:
776                         xlog_warn("nfsopen: open(%s): %s", ic->ic_path, strerror(errno));
777                         return (-1);
778                 }
779         } else {
780                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfscb, ic);
781                 event_add(&ic->ic_event, NULL);
782                 fcntl(ic->ic_dirfd, F_NOTIFY, 0);
783                 fcntl(ic->ic_dirfd, F_SETSIG, 0);
784                 if (verbose > 0)
785                         xlog_warn("Opened %s", ic->ic_path);
786         }
787
788         return (0);
789 }
790
791 static void
792 idtonameres(struct idmap_msg *im)
793 {
794         char domain[NFS4_MAX_DOMAIN_LEN];
795         int ret = 0;
796
797         ret = nfs4_get_default_domain(NULL, domain, sizeof(domain));
798         switch (im->im_type) {
799         case IDMAP_TYPE_USER:
800                 ret = nfs4_uid_to_name(im->im_id, domain, im->im_name,
801                                 sizeof(im->im_name));
802                 if (ret) {
803                         if (strlen(nobodyuser) < sizeof(im->im_name))
804                                 strcpy(im->im_name, nobodyuser);
805                         else
806                                 strcpy(im->im_name, NFS4NOBODY_USER);
807                 }
808                 break;
809         case IDMAP_TYPE_GROUP:
810                 ret = nfs4_gid_to_name(im->im_id, domain, im->im_name,
811                                 sizeof(im->im_name));
812                 if (ret) {
813                         if (strlen(nobodygroup) < sizeof(im->im_name))
814                                 strcpy(im->im_name, nobodygroup);
815                         else
816                                 strcpy(im->im_name, NFS4NOBODY_GROUP);
817                 }
818                 break;
819         }
820         if (ret)
821                 im->im_status = IDMAP_STATUS_LOOKUPFAIL;
822         else
823                 im->im_status = IDMAP_STATUS_SUCCESS;
824 }
825
826 static void
827 nametoidres(struct idmap_msg *im)
828 {
829         uid_t uid;
830         gid_t gid;
831         int ret = 0;
832
833         /* XXX: move nobody stuff to library calls
834          * (nfs4_get_nobody_user(domain), nfs4_get_nobody_group(domain)) */
835
836         im->im_status = IDMAP_STATUS_SUCCESS;
837
838         switch (im->im_type) {
839         case IDMAP_TYPE_USER:
840                 ret = nfs4_name_to_uid(im->im_name, &uid);
841                 im->im_id = (u_int32_t) uid;
842                 if (ret) {
843                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
844                         im->im_id = nobodyuid;
845                 }
846                 return;
847         case IDMAP_TYPE_GROUP:
848                 ret = nfs4_name_to_gid(im->im_name, &gid);
849                 im->im_id = (u_int32_t) gid;
850                 if (ret) {
851                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
852                         im->im_id = nobodygid;
853                 }
854                 return;
855         }
856 }
857
858 static int
859 addfield(char **bpp, ssize_t *bsizp, char *fld)
860 {
861         char ch, *bp = *bpp;
862         ssize_t bsiz = *bsizp;
863
864         while ((ch = *fld++) != '\0' && bsiz > 0) {
865                 switch(ch) {
866                 case ' ':
867                 case '\t':
868                 case '\n':
869                 case '\\':
870                         if (bsiz >= 4) {
871                                 bp += snprintf(bp, bsiz, "\\%03o", ch);
872                                 bsiz -= 4;
873                         }
874                         break;
875                 default:
876                         *bp++ = ch;
877                         bsiz--;
878                         break;
879                 }
880         }
881
882         if (bsiz < 1 || ch != '\0')
883                 return (-1);
884
885         *bp++ = ' ';
886         bsiz--;
887
888         *bpp = bp;
889         *bsizp = bsiz;
890
891         return (0);
892 }
893
894 static int
895 getfield(char **bpp, char *fld, size_t fldsz)
896 {
897         char *bp;
898         int val, n;
899
900         while ((bp = strsep(bpp, " ")) != NULL && bp[0] == '\0')
901                 ;
902
903         if (bp == NULL || bp[0] == '\0' || bp[0] == '\n')
904                 return (-1);
905
906         while (*bp != '\0' && fldsz > 1) {
907                 if (*bp == '\\') {
908                         if ((n = sscanf(bp, "\\%03o", &val)) != 1)
909                                 return (-1);
910                         if (val > UCHAR_MAX)
911                                 return (-1);
912                         *fld++ = val;
913                         bp += 4;
914                 } else {
915                         *fld++ = *bp;
916                         bp++;
917                 }
918                 fldsz--;
919         }
920
921         if (*bp != '\0')
922                 return (-1);
923         *fld = '\0';
924
925         return (0);
926 }
927 /*
928  * mydaemon creates a pipe between the partent and child
929  * process. The parent process will wait until the
930  * child dies or writes a '1' on the pipe signaling
931  * that it started successfully.
932  */
933 int pipefds[2] = { -1, -1};
934
935 void
936 mydaemon(int nochdir, int noclose)
937 {
938         int pid, status, tempfd;
939
940         if (pipe(pipefds) < 0)
941                 err(1, "mydaemon: pipe() failed: errno %d", errno);
942
943         if ((pid = fork ()) < 0)
944                 err(1, "mydaemon: fork() failed: errno %d", errno);
945
946         if (pid != 0) {
947                 /*
948                  * Parent. Wait for status from child.
949                  */
950                 close(pipefds[1]);
951                 if (read(pipefds[0], &status, 1) != 1)
952                         exit(1);
953                 exit (0);
954         }
955         /* Child.       */
956         close(pipefds[0]);
957         setsid ();
958         if (nochdir == 0) {
959                 if (chdir ("/") == -1)
960                         err(1, "mydaemon: chdir() failed: errno %d", errno);
961         }
962
963         while (pipefds[1] <= 2) {
964                 pipefds[1] = dup(pipefds[1]);
965                 if (pipefds[1] < 0)
966                         err(1, "mydaemon: dup() failed: errno %d", errno);
967         }
968
969         if (noclose == 0) {
970                 tempfd = open("/dev/null", O_RDWR);
971                 if (tempfd < 0)
972                         tempfd = open("/", O_RDONLY);
973                 if (tempfd >= 0) {
974                         dup2(tempfd, 0);
975                         dup2(tempfd, 1);
976                         dup2(tempfd, 2);
977                         close(tempfd);
978                 } else {
979                         err(1, "mydaemon: can't open /dev/null: errno %d",
980                                errno);
981                         exit(1);
982                 }
983         }
984
985         return;
986 }
987 void
988 release_parent(void)
989 {
990         int status;
991
992         if (pipefds[1] > 0) {
993                 if (write(pipefds[1], &status, 1) != 1) {
994                         err(1, "Writing to parent pipe failed: errno %d (%s)\n",
995                                 errno, strerror(errno));
996                 }
997                 close(pipefds[1]);
998                 pipefds[1] = -1;
999         }
1000 }