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