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