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