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