]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/idmapd/idmapd.c
nfsd: allow choosing server 41 support at runtime
[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  validateascii(char *, u_int32_t);
149 static int  addfield(char **, ssize_t *, char *);
150 static int  getfield(char **, char *, size_t);
151
152 static void imconv(struct idmap_client *, struct idmap_msg *);
153 static void idtonameres(struct idmap_msg *);
154 static void nametoidres(struct idmap_msg *);
155
156 static int nfsdopen(void);
157 static int nfsdopenone(struct idmap_client *);
158 static void nfsdreopen_one(struct idmap_client *);
159 static void nfsdreopen(void);
160
161 void    mydaemon(int, int);
162 void    release_parent(void);
163
164 static int verbose = 0;
165 #define DEFAULT_IDMAP_CACHE_EXPIRY 600 /* seconds */
166 static int cache_entry_expiration = 0;
167 static char pipefsdir[PATH_MAX];
168 static char *nobodyuser, *nobodygroup;
169 static uid_t nobodyuid;
170 static gid_t nobodygid;
171
172 /* Used by conffile.c in libnfs.a */
173 char *conf_path;
174
175 static int
176 flush_nfsd_cache(char *path, time_t now)
177 {
178         int fd;
179         char stime[20];
180
181         sprintf(stime, "%ld\n", now);
182         fd = open(path, O_RDWR);
183         if (fd == -1)
184                 return -1;
185         if (write(fd, stime, strlen(stime)) != (ssize_t)strlen(stime)) {
186                 errx(1, "Flushing nfsd cache failed: errno %d (%s)",
187                         errno, strerror(errno));
188         }
189         close(fd);
190         return 0;
191 }
192
193 static int
194 flush_nfsd_idmap_cache(void)
195 {
196         time_t now = time(NULL);
197         int ret;
198
199         ret = flush_nfsd_cache(IC_IDNAME_FLUSH, now);
200         if (ret)
201                 return ret;
202         ret = flush_nfsd_cache(IC_NAMEID_FLUSH, now);
203         return ret;
204 }
205
206 int
207 main(int argc, char **argv)
208 {
209         int fd = 0, opt, fg = 0, nfsdret = -1;
210         struct idmap_clientq icq;
211         struct event rootdirev, clntdirev, svrdirev;
212         struct event initialize;
213         struct passwd *pw;
214         struct group *gr;
215         struct stat sb;
216         char *xpipefsdir = NULL;
217         int serverstart = 1, clientstart = 1;
218         int ret;
219         char *progname;
220
221         conf_path = _PATH_IDMAPDCONF;
222         nobodyuser = NFS4NOBODY_USER;
223         nobodygroup = NFS4NOBODY_GROUP;
224         strlcpy(pipefsdir, PIPEFS_DIR, sizeof(pipefsdir));
225
226         if ((progname = strrchr(argv[0], '/')))
227                 progname++;
228         else
229                 progname = argv[0];
230         xlog_open(progname);
231
232 #define GETOPTSTR "vfd:p:U:G:c:CS"
233         opterr=0; /* Turn off error messages */
234         while ((opt = getopt(argc, argv, GETOPTSTR)) != -1) {
235                 if (opt == 'c')
236                         conf_path = optarg;
237                 if (opt == '?') {
238                         if (strchr(GETOPTSTR, optopt))
239                                 errx(1, "'-%c' option requires an argument.", optopt);
240                         else
241                                 errx(1, "'-%c' is an invalid argument.", optopt);
242                 }
243         }
244         optind = 1;
245
246         if (stat(conf_path, &sb) == -1 && (errno == ENOENT || errno == EACCES)) {
247                 warn("Skipping configuration file \"%s\"", conf_path);
248                 conf_path = NULL;
249         } else {
250                 conf_init();
251                 verbose = conf_get_num("General", "Verbosity", 0);
252                 cache_entry_expiration = conf_get_num("General",
253                                 "Cache-Expiration", DEFAULT_IDMAP_CACHE_EXPIRY);
254                 CONF_SAVE(xpipefsdir, conf_get_str("General", "Pipefs-Directory"));
255                 if (xpipefsdir != NULL)
256                         strlcpy(pipefsdir, xpipefsdir, sizeof(pipefsdir));
257                 CONF_SAVE(nobodyuser, conf_get_str("Mapping", "Nobody-User"));
258                 CONF_SAVE(nobodygroup, conf_get_str("Mapping", "Nobody-Group"));
259         }
260
261         while ((opt = getopt(argc, argv, GETOPTSTR)) != -1)
262                 switch (opt) {
263                 case 'v':
264                         verbose++;
265                         break;
266                 case 'f':
267                         fg = 1;
268                         break;
269                 case 'p':
270                         strlcpy(pipefsdir, optarg, sizeof(pipefsdir));
271                         break;
272                 case 'd':
273                 case 'U':
274                 case 'G':
275                         errx(1, "the -d, -U, and -G options have been removed;"
276                                 " please use the configuration file instead.");
277                 case 'C':
278                         serverstart = 0;
279                         break;
280                 case 'S':
281                         clientstart = 0;
282                         break;
283                 default:
284                         break;
285                 }
286
287         if (!serverstart && !clientstart)
288                 errx(1, "it is illegal to specify both -C and -S");
289
290         strncat(pipefsdir, "/nfs", sizeof(pipefsdir));
291
292         if ((pw = getpwnam(nobodyuser)) == NULL)
293                 errx(1, "Could not find user \"%s\"", nobodyuser);
294         nobodyuid = pw->pw_uid;
295
296         if ((gr = getgrnam(nobodygroup)) == NULL)
297                 errx(1, "Could not find group \"%s\"", nobodygroup);
298         nobodygid = gr->gr_gid;
299
300 #ifdef HAVE_NFS4_SET_DEBUG
301         nfs4_set_debug(verbose, xlog_warn);
302 #endif
303         if (conf_path == NULL)
304                 conf_path = _PATH_IDMAPDCONF;
305         if (nfs4_init_name_mapping(conf_path))
306                 errx(1, "Unable to create name to user id mappings.");
307
308         if (!fg)
309                 mydaemon(0, 0);
310
311         event_init();
312
313         if (verbose > 0)
314                 xlog_warn("Expiration time is %d seconds.",
315                              cache_entry_expiration);
316         if (serverstart) {
317                 nfsdret = nfsdopen();
318                 if (nfsdret == 0) {
319                         ret = flush_nfsd_idmap_cache();
320                         if (ret)
321                                 xlog_err("main: Failed to flush nfsd idmap cache\n: %s", strerror(errno));
322                 }
323         }
324
325         if (clientstart) {
326                 struct timeval now = {
327                         .tv_sec = 0,
328                         .tv_usec = 0,
329                 };
330
331                 if (cache_entry_expiration != DEFAULT_IDMAP_CACHE_EXPIRY) {
332                         int timeout_fd, len;
333                         char timeout_buf[12];
334                         if ((timeout_fd = open(CLIENT_CACHE_TIMEOUT_FILE,
335                                                O_RDWR)) == -1) {
336                                 xlog_warn("Unable to open '%s' to set "
337                                              "client cache expiration time "
338                                              "to %d seconds\n",
339                                              CLIENT_CACHE_TIMEOUT_FILE,
340                                              cache_entry_expiration);
341                         } else {
342                                 len = snprintf(timeout_buf, sizeof(timeout_buf),
343                                                "%d", cache_entry_expiration);
344                                 if ((write(timeout_fd, timeout_buf, len)) != len)
345                                         xlog_warn("Error writing '%s' to "
346                                                      "'%s' to set client "
347                                                      "cache expiration time\n",
348                                                      timeout_buf,
349                                                      CLIENT_CACHE_TIMEOUT_FILE);
350                                 close(timeout_fd);
351                         }
352                 }
353
354                 if ((fd = open(pipefsdir, O_RDONLY)) == -1)
355                         xlog_err("main: open(%s): %s", pipefsdir, strerror(errno));
356
357                 if (fcntl(fd, F_SETSIG, SIGUSR1) == -1)
358                         xlog_err("main: fcntl(%s): %s", pipefsdir, strerror(errno));
359
360                 if (fcntl(fd, F_NOTIFY,
361                         DN_CREATE | DN_DELETE | DN_MODIFY | DN_MULTISHOT) == -1) {
362                         xlog_err("main: fcntl(%s): %s", pipefsdir, strerror(errno));
363                         if (errno == EINVAL)
364                                 xlog_err("main: Possibly no Dnotify support in kernel.");
365                 }
366                 TAILQ_INIT(&icq);
367
368                 /* These events are persistent */
369                 signal_set(&rootdirev, SIGUSR1, dirscancb, &icq);
370                 signal_add(&rootdirev, NULL);
371                 signal_set(&clntdirev, SIGUSR2, clntscancb, &icq);
372                 signal_add(&clntdirev, NULL);
373                 signal_set(&svrdirev, SIGHUP, svrreopen, NULL);
374                 signal_add(&svrdirev, NULL);
375
376                 /* Fetch current state */
377                 /* (Delay till start of event_dispatch to avoid possibly losing
378                  * a SIGUSR1 between here and the call to event_dispatch().) */
379                 evtimer_set(&initialize, dirscancb, &icq);
380                 evtimer_add(&initialize, &now);
381         }
382
383         if (nfsdret != 0 && fd == 0)
384                 xlog_err("main: Neither NFS client nor NFSd found");
385
386         release_parent();
387
388         if (event_dispatch() < 0)
389                 xlog_err("main: event_dispatch returns errno %d (%s)",
390                             errno, strerror(errno));
391         /* NOTREACHED */
392         return 1;
393 }
394
395 static void
396 dirscancb(int UNUSED(fd), short UNUSED(which), void *data)
397 {
398         int nent, i;
399         struct dirent **ents;
400         struct idmap_client *ic, *nextic;
401         char path[PATH_MAX];
402         struct idmap_clientq *icq = data;
403
404         nent = scandir(pipefsdir, &ents, NULL, alphasort);
405         if (nent == -1) {
406                 xlog_warn("dirscancb: scandir(%s): %s", pipefsdir, strerror(errno));
407                 return;
408         }
409
410         for (i = 0;  i < nent; i++) {
411                 if (ents[i]->d_reclen > 4 &&
412                     strncmp(ents[i]->d_name, "clnt", 4) == 0) {
413                         TAILQ_FOREACH(ic, icq, ic_next)
414                             if (strcmp(ents[i]->d_name + 4, ic->ic_clid) == 0)
415                                     break;
416                         if (ic != NULL)
417                                 goto next;
418
419                         if ((ic = calloc(1, sizeof(*ic))) == NULL)
420                                 goto out;
421                         strlcpy(ic->ic_clid, ents[i]->d_name + 4,
422                             sizeof(ic->ic_clid));
423                         path[0] = '\0';
424                         snprintf(path, sizeof(path), "%s/%s",
425                             pipefsdir, ents[i]->d_name);
426
427                         if ((ic->ic_dirfd = open(path, O_RDONLY, 0)) == -1) {
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         switch (im->im_conv) {
646         case IDMAP_CONV_IDTONAME:
647                 idtonameres(im);
648                 if (verbose > 1)
649                         xlog_warn("%s %s: (%s) id \"%d\" -> name \"%s\"",
650                             ic->ic_id, ic->ic_clid,
651                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
652                             im->im_id, im->im_name);
653                 break;
654         case IDMAP_CONV_NAMETOID:
655                 if (validateascii(im->im_name, sizeof(im->im_name)) == -1) {
656                         im->im_status |= IDMAP_STATUS_INVALIDMSG;
657                         return;
658                 }
659                 nametoidres(im);
660                 if (verbose > 1)
661                         xlog_warn("%s %s: (%s) name \"%s\" -> id \"%d\"",
662                             ic->ic_id, ic->ic_clid,
663                             im->im_type == IDMAP_TYPE_USER ? "user" : "group",
664                             im->im_name, im->im_id);
665                 break;
666         default:
667                 xlog_warn("imconv: Invalid conversion type (%d) in message",
668                              im->im_conv);
669                 im->im_status |= IDMAP_STATUS_INVALIDMSG;
670                 break;
671         }
672 }
673
674 static void
675 nfscb(int UNUSED(fd), short which, void *data)
676 {
677         struct idmap_client *ic = data;
678         struct idmap_msg im;
679
680         if (which != EV_READ)
681                 goto out;
682
683         if (atomicio(read, ic->ic_fd, &im, sizeof(im)) != sizeof(im)) {
684                 if (verbose > 0)
685                         xlog_warn("nfscb: read(%s): %s", ic->ic_path, strerror(errno));
686                 if (errno == EPIPE)
687                         return;
688                 goto out;
689         }
690
691         imconv(ic, &im);
692
693         /* XXX: I don't like ignoring this error in the id->name case,
694          * but we've never returned it, and I need to check that the client
695          * can handle it gracefully before starting to return it now. */
696
697         if (im.im_status == IDMAP_STATUS_LOOKUPFAIL)
698                 im.im_status = IDMAP_STATUS_SUCCESS;
699
700         if (atomicio((void*)write, ic->ic_fd, &im, sizeof(im)) != sizeof(im))
701                 xlog_warn("nfscb: write(%s): %s", ic->ic_path, strerror(errno));
702 out:
703         event_add(&ic->ic_event, NULL);
704 }
705
706 static void
707 nfsdreopen_one(struct idmap_client *ic)
708 {
709         int fd;
710
711         if (verbose > 0)
712                 xlog_warn("ReOpening %s", ic->ic_path);
713
714         if ((fd = open(ic->ic_path, O_RDWR, 0)) != -1) {
715                 if ((ic->ic_event.ev_flags & EVLIST_INIT))
716                         event_del(&ic->ic_event);
717                 if (ic->ic_fd != -1)
718                         close(ic->ic_fd);
719
720                 ic->ic_event.ev_fd = ic->ic_fd = fd;
721                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
722                 event_add(&ic->ic_event, NULL);
723         } else {
724                 xlog_warn("nfsdreopen: Opening '%s' failed: errno %d (%s)",
725                         ic->ic_path, errno, strerror(errno));
726         }
727 }
728
729 static void
730 nfsdreopen()
731 {
732         nfsdreopen_one(&nfsd_ic[IC_NAMEID]);
733         nfsdreopen_one(&nfsd_ic[IC_IDNAME]);
734         return;
735 }
736
737 static int
738 nfsdopen(void)
739 {
740         return ((nfsdopenone(&nfsd_ic[IC_NAMEID]) == 0 &&
741                     nfsdopenone(&nfsd_ic[IC_IDNAME]) == 0) ? 0 : -1);
742 }
743
744 static int
745 nfsdopenone(struct idmap_client *ic)
746 {
747         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
748                 if (verbose > 0)
749                         xlog_warn("nfsdopenone: Opening %s failed: "
750                                 "errno %d (%s)",
751                                 ic->ic_path, errno, strerror(errno));
752                 return (-1);
753         }
754
755         event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfsdcb, ic);
756         event_add(&ic->ic_event, NULL);
757
758         if (verbose > 0)
759                 xlog_warn("Opened %s", ic->ic_path);
760
761         return (0);
762 }
763
764 static int
765 nfsopen(struct idmap_client *ic)
766 {
767         if ((ic->ic_fd = open(ic->ic_path, O_RDWR, 0)) == -1) {
768                 switch (errno) {
769                 case ENOENT:
770                         fcntl(ic->ic_dirfd, F_SETSIG, SIGUSR2);
771                         fcntl(ic->ic_dirfd, F_NOTIFY,
772                             DN_CREATE | DN_DELETE | DN_MULTISHOT);
773                         break;
774                 default:
775                         xlog_warn("nfsopen: open(%s): %s", ic->ic_path, strerror(errno));
776                         return (-1);
777                 }
778         } else {
779                 event_set(&ic->ic_event, ic->ic_fd, EV_READ, nfscb, ic);
780                 event_add(&ic->ic_event, NULL);
781                 fcntl(ic->ic_dirfd, F_SETSIG, 0);
782                 fcntl(ic->ic_dirfd, F_NOTIFY, 0);
783                 if (verbose > 0)
784                         xlog_warn("Opened %s", ic->ic_path);
785         }
786
787         return (0);
788 }
789
790 static void
791 idtonameres(struct idmap_msg *im)
792 {
793         char domain[NFS4_MAX_DOMAIN_LEN];
794         int ret = 0;
795
796         ret = nfs4_get_default_domain(NULL, domain, sizeof(domain));
797         switch (im->im_type) {
798         case IDMAP_TYPE_USER:
799                 ret = nfs4_uid_to_name(im->im_id, domain, im->im_name,
800                                 sizeof(im->im_name));
801                 if (ret) {
802                         if (strlen(nobodyuser) < sizeof(im->im_name))
803                                 strcpy(im->im_name, nobodyuser);
804                         else
805                                 strcpy(im->im_name, NFS4NOBODY_USER);
806                 }
807                 break;
808         case IDMAP_TYPE_GROUP:
809                 ret = nfs4_gid_to_name(im->im_id, domain, im->im_name,
810                                 sizeof(im->im_name));
811                 if (ret) {
812                         if (strlen(nobodygroup) < sizeof(im->im_name))
813                                 strcpy(im->im_name, nobodygroup);
814                         else
815                                 strcpy(im->im_name, NFS4NOBODY_GROUP);
816                 }
817                 break;
818         }
819         if (ret)
820                 im->im_status = IDMAP_STATUS_LOOKUPFAIL;
821         else
822                 im->im_status = IDMAP_STATUS_SUCCESS;
823 }
824
825 static void
826 nametoidres(struct idmap_msg *im)
827 {
828         uid_t uid;
829         gid_t gid;
830         int ret = 0;
831
832         /* XXX: move nobody stuff to library calls
833          * (nfs4_get_nobody_user(domain), nfs4_get_nobody_group(domain)) */
834
835         im->im_status = IDMAP_STATUS_SUCCESS;
836
837         switch (im->im_type) {
838         case IDMAP_TYPE_USER:
839                 ret = nfs4_name_to_uid(im->im_name, &uid);
840                 im->im_id = (u_int32_t) uid;
841                 if (ret) {
842                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
843                         im->im_id = nobodyuid;
844                 }
845                 return;
846         case IDMAP_TYPE_GROUP:
847                 ret = nfs4_name_to_gid(im->im_name, &gid);
848                 im->im_id = (u_int32_t) gid;
849                 if (ret) {
850                         im->im_status = IDMAP_STATUS_LOOKUPFAIL;
851                         im->im_id = nobodygid;
852                 }
853                 return;
854         }
855 }
856
857 static int
858 validateascii(char *string, u_int32_t len)
859 {
860         u_int32_t i;
861
862         for (i = 0; i < len; i++) {
863                 if (string[i] == '\0')
864                         break;
865
866                 if (string[i] & 0x80)
867                         return (-1);
868         }
869
870         if ((i >= len) || string[i] != '\0')
871                 return (-1);
872
873         return (i + 1);
874 }
875
876 static int
877 addfield(char **bpp, ssize_t *bsizp, char *fld)
878 {
879         char ch, *bp = *bpp;
880         ssize_t bsiz = *bsizp;
881
882         while ((ch = *fld++) != '\0' && bsiz > 0) {
883                 switch(ch) {
884                 case ' ':
885                 case '\t':
886                 case '\n':
887                 case '\\':
888                         if (bsiz >= 4) {
889                                 bp += snprintf(bp, bsiz, "\\%03o", ch);
890                                 bsiz -= 4;
891                         }
892                         break;
893                 default:
894                         *bp++ = ch;
895                         bsiz--;
896                         break;
897                 }
898         }
899
900         if (bsiz < 1 || ch != '\0')
901                 return (-1);
902
903         *bp++ = ' ';
904         bsiz--;
905
906         *bpp = bp;
907         *bsizp = bsiz;
908
909         return (0);
910 }
911
912 static int
913 getfield(char **bpp, char *fld, size_t fldsz)
914 {
915         char *bp;
916         int val, n;
917
918         while ((bp = strsep(bpp, " ")) != NULL && bp[0] == '\0')
919                 ;
920
921         if (bp == NULL || bp[0] == '\0' || bp[0] == '\n')
922                 return (-1);
923
924         while (*bp != '\0' && fldsz > 1) {
925                 if (*bp == '\\') {
926                         if ((n = sscanf(bp, "\\%03o", &val)) != 1)
927                                 return (-1);
928                         if (val > (char)-1)
929                                 return (-1);
930                         *fld++ = (char)val;
931                         bp += 4;
932                 } else {
933                         *fld++ = *bp;
934                         bp++;
935                 }
936                 fldsz--;
937         }
938
939         if (*bp != '\0')
940                 return (-1);
941         *fld = '\0';
942
943         return (0);
944 }
945 /*
946  * mydaemon creates a pipe between the partent and child
947  * process. The parent process will wait until the
948  * child dies or writes a '1' on the pipe signaling
949  * that it started successfully.
950  */
951 int pipefds[2] = { -1, -1};
952
953 void
954 mydaemon(int nochdir, int noclose)
955 {
956         int pid, status, tempfd;
957
958         if (pipe(pipefds) < 0)
959                 err(1, "mydaemon: pipe() failed: errno %d", errno);
960
961         if ((pid = fork ()) < 0)
962                 err(1, "mydaemon: fork() failed: errno %d", errno);
963
964         if (pid != 0) {
965                 /*
966                  * Parent. Wait for status from child.
967                  */
968                 close(pipefds[1]);
969                 if (read(pipefds[0], &status, 1) != 1)
970                         exit(1);
971                 exit (0);
972         }
973         /* Child.       */
974         close(pipefds[0]);
975         setsid ();
976         if (nochdir == 0) {
977                 if (chdir ("/") == -1)
978                         err(1, "mydaemon: chdir() failed: errno %d", errno);
979         }
980
981         while (pipefds[1] <= 2) {
982                 pipefds[1] = dup(pipefds[1]);
983                 if (pipefds[1] < 0)
984                         err(1, "mydaemon: dup() failed: errno %d", errno);
985         }
986
987         if (noclose == 0) {
988                 tempfd = open("/dev/null", O_RDWR);
989                 if (tempfd < 0)
990                         tempfd = open("/", O_RDONLY);
991                 if (tempfd >= 0) {
992                         dup2(tempfd, 0);
993                         dup2(tempfd, 1);
994                         dup2(tempfd, 2);
995                         close(tempfd);
996                 } else {
997                         err(1, "mydaemon: can't open /dev/null: errno %d",
998                                errno);
999                         exit(1);
1000                 }
1001         }
1002
1003         return;
1004 }
1005 void
1006 release_parent(void)
1007 {
1008         int status;
1009
1010         if (pipefds[1] > 0) {
1011                 if (write(pipefds[1], &status, 1) != 1) {
1012                         err(1, "Writing to parent pipe failed: errno %d (%s)\n",
1013                                 errno, strerror(errno));
1014                 }
1015                 close(pipefds[1]);
1016                 pipefds[1] = -1;
1017         }
1018 }