]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mountd/cache.c
mountd: regression in crossmounts
[nfs-utils.git] / utils / mountd / cache.c
1
2 /*
3  * Handle communication with knfsd internal cache
4  *
5  * We open /proc/net/rpc/{auth.unix.ip,nfsd.export,nfsd.fh}/channel
6  * and listen for requests (using my_svc_run)
7  * 
8  */
9
10 #ifdef HAVE_CONFIG_H
11 #include <config.h>
12 #endif
13
14 #include <sys/types.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/vfs.h>
18 #include <time.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <pwd.h>
26 #include <grp.h>
27 #include <mntent.h>
28 #include "misc.h"
29 #include "nfslib.h"
30 #include "exportfs.h"
31 #include "mountd.h"
32 #include "fsloc.h"
33 #include "pseudoflavors.h"
34
35 #ifdef USE_BLKID
36 #include "blkid/blkid.h"
37 #endif
38
39 /*
40  * Invoked by RPC service loop
41  */
42 void    cache_set_fds(fd_set *fdset);
43 int     cache_process_req(fd_set *readfds);
44
45 enum nfsd_fsid {
46         FSID_DEV = 0,
47         FSID_NUM,
48         FSID_MAJOR_MINOR,
49         FSID_ENCODE_DEV,
50         FSID_UUID4_INUM,
51         FSID_UUID8,
52         FSID_UUID16,
53         FSID_UUID16_INUM,
54 };
55
56 /*
57  * Support routines for text-based upcalls.
58  * Fields are separated by spaces.
59  * Fields are either mangled to quote space tab newline slosh with slosh
60  * or a hexified with a leading \x
61  * Record is terminated with newline.
62  *
63  */
64 static int cache_export_ent(char *domain, struct exportent *exp, char *p);
65
66 #define INITIAL_MANAGED_GROUPS 100
67
68 char *lbuf  = NULL;
69 int lbuflen = 0;
70 extern int use_ipaddr;
71
72 static void auth_unix_ip(FILE *f)
73 {
74         /* requests are
75          *  class IP-ADDR
76          * Ignore if class != "nfsd"
77          * Otherwise find domainname and write back:
78          *
79          *  "nfsd" IP-ADDR expiry domainname
80          */
81         char *cp;
82         char class[20];
83         char ipaddr[INET6_ADDRSTRLEN];
84         char *client = NULL;
85         struct addrinfo *tmp = NULL;
86         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
87                 return;
88
89         xlog(D_CALL, "auth_unix_ip: inbuf '%s'", lbuf);
90
91         cp = lbuf;
92
93         if (qword_get(&cp, class, 20) <= 0 ||
94             strcmp(class, "nfsd") != 0)
95                 return;
96
97         if (qword_get(&cp, ipaddr, sizeof(ipaddr)) <= 0)
98                 return;
99
100         tmp = host_pton(ipaddr);
101         if (tmp == NULL)
102                 return;
103
104         auth_reload();
105
106         /* addr is a valid, interesting address, find the domain name... */
107         if (!use_ipaddr) {
108                 struct addrinfo *ai = NULL;
109
110                 ai = client_resolve(tmp->ai_addr);
111                 if (ai) {
112                         client = client_compose(ai);
113                         freeaddrinfo(ai);
114                 }
115         }
116         qword_print(f, "nfsd");
117         qword_print(f, ipaddr);
118         qword_printtimefrom(f, DEFAULT_TTL);
119         if (use_ipaddr)
120                 qword_print(f, ipaddr);
121         else if (client)
122                 qword_print(f, *client?client:"DEFAULT");
123         qword_eol(f);
124         xlog(D_CALL, "auth_unix_ip: client %p '%s'", client, client?client: "DEFAULT");
125
126         free(client);
127         freeaddrinfo(tmp);
128
129 }
130
131 static void auth_unix_gid(FILE *f)
132 {
133         /* Request are
134          *  uid
135          * reply is
136          *  uid expiry count list of group ids
137          */
138         uid_t uid;
139         struct passwd *pw;
140         static gid_t *groups = NULL;
141         static int groups_len = 0;
142         gid_t *more_groups;
143         int ngroups;
144         int rv, i;
145         char *cp;
146
147         if (groups_len == 0) {
148                 groups = malloc(sizeof(gid_t) * INITIAL_MANAGED_GROUPS);
149                 if (!groups)
150                         return;
151
152                 groups_len = INITIAL_MANAGED_GROUPS;
153         }
154
155         ngroups = groups_len;
156
157         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
158                 return;
159
160         cp = lbuf;
161         if (qword_get_uint(&cp, &uid) != 0)
162                 return;
163
164         pw = getpwuid(uid);
165         if (!pw)
166                 rv = -1;
167         else {
168                 rv = getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
169                 if (rv == -1 && ngroups >= groups_len) {
170                         more_groups = realloc(groups, sizeof(gid_t)*ngroups);
171                         if (!more_groups)
172                                 rv = -1;
173                         else {
174                                 groups = more_groups;
175                                 groups_len = ngroups;
176                                 rv = getgrouplist(pw->pw_name, pw->pw_gid,
177                                                   groups, &ngroups);
178                         }
179                 }
180         }
181         qword_printuint(f, uid);
182         qword_printtimefrom(f, DEFAULT_TTL);
183         if (rv >= 0) {
184                 qword_printuint(f, ngroups);
185                 for (i=0; i<ngroups; i++)
186                         qword_printuint(f, groups[i]);
187         } else
188                 qword_printuint(f, 0);
189         qword_eol(f);
190 }
191
192 #if USE_BLKID
193 static const char *get_uuid_blkdev(char *path)
194 {
195         /* We set *safe if we know that we need the
196          * fsid from statfs too.
197          */
198         static blkid_cache cache = NULL;
199         struct stat stb;
200         char *devname;
201         blkid_tag_iterate iter;
202         blkid_dev dev;
203         const char *type;
204         const char *val, *uuid = NULL;
205
206         if (cache == NULL)
207                 blkid_get_cache(&cache, NULL);
208
209         if (stat(path, &stb) != 0)
210                 return NULL;
211         devname = blkid_devno_to_devname(stb.st_dev);
212         if (!devname)
213                 return NULL;
214         dev = blkid_get_dev(cache, devname, BLKID_DEV_NORMAL);
215         free(devname);
216         if (!dev)
217                 return NULL;
218         iter = blkid_tag_iterate_begin(dev);
219         if (!iter)
220                 return NULL;
221         while (blkid_tag_next(iter, &type, &val) == 0) {
222                 if (strcmp(type, "UUID") == 0)
223                         uuid = val;
224                 if (strcmp(type, "TYPE") == 0 &&
225                     strcmp(val, "btrfs") == 0) {
226                         uuid = NULL;
227                         break;
228                 }
229         }
230         blkid_tag_iterate_end(iter);
231         return uuid;
232 }
233 #else
234 #define get_uuid_blkdev(path) (NULL)
235 #endif
236
237 static int get_uuid(const char *val, size_t uuidlen, char *u)
238 {
239         /* extract hex digits from uuidstr and compose a uuid
240          * of the given length (max 16), xoring bytes to make
241          * a smaller uuid.
242          */
243         size_t i = 0;
244         
245         memset(u, 0, uuidlen);
246         for ( ; *val ; val++) {
247                 int c = *val;
248                 if (!isxdigit(c))
249                         continue;
250                 if (isalpha(c)) {
251                         if (isupper(c))
252                                 c = c - 'A' + 10;
253                         else
254                                 c = c - 'a' + 10;
255                 } else
256                         c = c - '0' + 0;
257                 if ((i&1) == 0)
258                         c <<= 4;
259                 u[i/2] ^= (char)c;
260                 i++;
261                 if (i == uuidlen*2)
262                         i = 0;
263         }
264         return 1;
265 }
266
267 static int uuid_by_path(char *path, int type, size_t uuidlen, char *uuid)
268 {
269         /* get a uuid for the filesystem found at 'path'.
270          * There are several possible ways of generating the
271          * uuids (types).
272          * Type 0 is used for new filehandles, while other types
273          * may be used to interpret old filehandle - to ensure smooth
274          * forward migration.
275          * We return 1 if a uuid was found (and it might be worth 
276          * trying the next type) or 0 if no more uuid types can be
277          * extracted.
278          */
279
280         /* Possible sources of uuid are
281          * - blkid uuid
282          * - statfs64 uuid
283          *
284          * On some filesystems (e.g. vfat) the statfs64 uuid is simply an
285          * encoding of the device that the filesystem is mounted from, so
286          * it we be very bad to use that (as device numbers change).  blkid
287          * must be preferred.
288          * On other filesystems (e.g. btrfs) the statfs64 uuid contains
289          * important info that the blkid uuid cannot contain:  This happens
290          * when multiple subvolumes are exported (they have the same
291          * blkid uuid but different statfs64 uuids).
292          * We rely on get_uuid_blkdev *knowing* which is which and not returning
293          * a uuid for filesystems where the statfs64 uuid is better.
294          *
295          */
296         struct statfs64 st;
297         char fsid_val[17];
298         const char *blkid_val;
299         const char *val;
300
301         blkid_val = get_uuid_blkdev(path);
302
303         if (statfs64(path, &st) == 0 &&
304             (st.f_fsid.__val[0] || st.f_fsid.__val[1]))
305                 snprintf(fsid_val, 17, "%08x%08x",
306                          st.f_fsid.__val[0], st.f_fsid.__val[1]);
307         else
308                 fsid_val[0] = 0;
309
310         if (blkid_val && (type--) == 0)
311                 val = blkid_val;
312         else if (fsid_val[0] && (type--) == 0)
313                 val = fsid_val;
314         else
315                 return 0;
316
317         get_uuid(val, uuidlen, uuid);
318         return 1;
319 }
320
321 /* Iterate through /etc/mtab, finding mountpoints
322  * at or below a given path
323  */
324 static char *next_mnt(void **v, char *p)
325 {
326         FILE *f;
327         struct mntent *me;
328         size_t l = strlen(p);
329         if (*v == NULL) {
330                 f = setmntent("/etc/mtab", "r");
331                 *v = f;
332         } else
333                 f = *v;
334         while ((me = getmntent(f)) != NULL &&
335                (strncmp(me->mnt_dir, p, l) != 0 ||
336                 me->mnt_dir[l] != '/'))
337                 ;
338         if (me == NULL) {
339                 endmntent(f);
340                 *v = NULL;
341                 return NULL;
342         }
343         return me->mnt_dir;
344 }
345
346 static int is_subdirectory(char *child, char *parent)
347 {
348         size_t l = strlen(parent);
349
350         if (strcmp(parent, "/") == 0)
351                 return 1;
352
353         return strcmp(child, parent) == 0
354                 || (strncmp(child, parent, l) == 0 && child[l] == '/');
355 }
356
357 static int path_matches(nfs_export *exp, char *path)
358 {
359         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)
360                 return is_subdirectory(path, exp->m_export.e_path);
361         return strcmp(path, exp->m_export.e_path) == 0;
362 }
363
364 static int
365 export_matches(nfs_export *exp, char *dom, char *path, struct addrinfo *ai)
366 {
367         return path_matches(exp, path) && client_matches(exp, dom, ai);
368 }
369
370 /* True iff e1 is a child of e2 and e2 has crossmnt set: */
371 static bool subexport(struct exportent *e1, struct exportent *e2)
372 {
373         char *p1 = e1->e_path, *p2 = e2->e_path;
374         size_t l2 = strlen(p2);
375
376         return e2->e_flags & NFSEXP_CROSSMOUNT
377                 && strncmp(p1, p2, l2) == 0
378                 && p1[l2] == '/';
379 }
380
381 struct parsed_fsid {
382         int fsidtype;
383         /* We could use a union for this, but it would be more
384          * complicated; why bother? */
385         unsigned int inode;
386         unsigned int minor;
387         unsigned int major;
388         unsigned int fsidnum;
389         size_t uuidlen;
390         char *fhuuid;
391 };
392
393 static int parse_fsid(int fsidtype, int fsidlen, char *fsid,
394                 struct parsed_fsid *parsed)
395 {
396         unsigned int dev;
397         unsigned long long inode64;
398
399         memset(parsed, 0, sizeof(*parsed));
400         parsed->fsidtype = fsidtype;
401         switch(fsidtype) {
402         case FSID_DEV: /* 4 bytes: 2 major, 2 minor, 4 inode */
403                 if (fsidlen != 8)
404                         return -1;
405                 memcpy(&dev, fsid, 4);
406                 memcpy(&parsed->inode, fsid+4, 4);
407                 parsed->major = ntohl(dev)>>16;
408                 parsed->minor = ntohl(dev) & 0xFFFF;
409                 break;
410
411         case FSID_NUM: /* 4 bytes - fsid */
412                 if (fsidlen != 4)
413                         return -1;
414                 memcpy(&parsed->fsidnum, fsid, 4);
415                 break;
416
417         case FSID_MAJOR_MINOR: /* 12 bytes: 4 major, 4 minor, 4 inode 
418                  * This format is never actually used but was
419                  * an historical accident
420                  */
421                 if (fsidlen != 12)
422                         return -1;
423                 memcpy(&dev, fsid, 4);
424                 parsed->major = ntohl(dev);
425                 memcpy(&dev, fsid+4, 4);
426                 parsed->minor = ntohl(dev);
427                 memcpy(&parsed->inode, fsid+8, 4);
428                 break;
429
430         case FSID_ENCODE_DEV: /* 8 bytes: 4 byte packed device number, 4 inode */
431                 /* This is *host* endian, not net-byte-order, because
432                  * no-one outside this host has any business interpreting it
433                  */
434                 if (fsidlen != 8)
435                         return -1;
436                 memcpy(&dev, fsid, 4);
437                 memcpy(&parsed->inode, fsid+4, 4);
438                 parsed->major = (dev & 0xfff00) >> 8;
439                 parsed->minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
440                 break;
441
442         case FSID_UUID4_INUM: /* 4 byte inode number and 4 byte uuid */
443                 if (fsidlen != 8)
444                         return -1;
445                 memcpy(&parsed->inode, fsid, 4);
446                 parsed->uuidlen = 4;
447                 parsed->fhuuid = fsid+4;
448                 break;
449         case FSID_UUID8: /* 8 byte uuid */
450                 if (fsidlen != 8)
451                         return -1;
452                 parsed->uuidlen = 8;
453                 parsed->fhuuid = fsid;
454                 break;
455         case FSID_UUID16: /* 16 byte uuid */
456                 if (fsidlen != 16)
457                         return -1;
458                 parsed->uuidlen = 16;
459                 parsed->fhuuid = fsid;
460                 break;
461         case FSID_UUID16_INUM: /* 8 byte inode number and 16 byte uuid */
462                 if (fsidlen != 24)
463                         return -1;
464                 memcpy(&inode64, fsid, 8);
465                 parsed->inode = inode64;
466                 parsed->uuidlen = 16;
467                 parsed->fhuuid = fsid+8;
468                 break;
469         }
470         return 0;
471 }
472
473 static bool match_fsid(struct parsed_fsid *parsed, nfs_export *exp, char *path)
474 {
475         struct stat stb;
476         int type;
477         char u[16];
478
479         if (stat(path, &stb) != 0)
480                 return false;
481         if (!S_ISDIR(stb.st_mode) && !S_ISREG(stb.st_mode))
482                 return false;
483
484         switch (parsed->fsidtype) {
485         case FSID_DEV:
486         case FSID_MAJOR_MINOR:
487         case FSID_ENCODE_DEV:
488                 if (stb.st_ino != parsed->inode)
489                         return false;
490                 if (parsed->major != major(stb.st_dev) ||
491                     parsed->minor != minor(stb.st_dev))
492                         return false;
493                 return true;
494         case FSID_NUM:
495                 if (((exp->m_export.e_flags & NFSEXP_FSID) == 0 ||
496                      exp->m_export.e_fsid != parsed->fsidnum))
497                         return false;
498                 return true;
499         case FSID_UUID4_INUM:
500         case FSID_UUID16_INUM:
501                 if (stb.st_ino != parsed->inode)
502                         return false;
503                 goto check_uuid;
504         case FSID_UUID8:
505         case FSID_UUID16:
506                 if (!is_mountpoint(path))
507                         return false;
508         check_uuid:
509                 if (exp->m_export.e_uuid)
510                         get_uuid(exp->m_export.e_uuid, parsed->uuidlen, u);
511                 else
512                         for (type = 0;
513                              uuid_by_path(path, type, parsed->uuidlen, u);
514                              type++)
515                                 if (memcmp(u, parsed->fhuuid, parsed->uuidlen) == 0)
516                                         return true;
517
518                 if (memcmp(u, parsed->fhuuid, parsed->uuidlen) != 0)
519                         return false;
520                 return true;
521         }
522         /* Well, unreachable, actually: */
523         return false;
524 }
525
526 static struct addrinfo *lookup_client_addr(char *dom)
527 {
528         struct addrinfo *ret;
529         struct addrinfo *tmp;
530
531         dom++; /* skip initial "$" */
532
533         tmp = host_pton(dom);
534         if (tmp == NULL)
535                 return NULL;
536         ret = client_resolve(tmp->ai_addr);
537         freeaddrinfo(tmp);
538         return ret;
539 }
540
541 static void nfsd_fh(FILE *f)
542 {
543         /* request are:
544          *  domain fsidtype fsid
545          * interpret fsid, find export point and options, and write:
546          *  domain fsidtype fsid expiry path
547          */
548         char *cp;
549         char *dom;
550         int fsidtype;
551         int fsidlen;
552         char fsid[32];
553         struct parsed_fsid parsed;
554         struct exportent *found = NULL;
555         struct addrinfo *ai = NULL;
556         char *found_path = NULL;
557         nfs_export *exp;
558         int i;
559         int dev_missing = 0;
560
561         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
562                 return;
563
564         xlog(D_CALL, "nfsd_fh: inbuf '%s'", lbuf);
565
566         cp = lbuf;
567
568         dom = malloc(strlen(cp));
569         if (dom == NULL)
570                 return;
571         if (qword_get(&cp, dom, strlen(cp)) <= 0)
572                 goto out;
573         if (qword_get_int(&cp, &fsidtype) != 0)
574                 goto out;
575         if (fsidtype < 0 || fsidtype > 7)
576                 goto out; /* unknown type */
577         if ((fsidlen = qword_get(&cp, fsid, 32)) <= 0)
578                 goto out;
579         if (parse_fsid(fsidtype, fsidlen, fsid, &parsed))
580                 goto out;
581
582         auth_reload();
583
584         if (is_ipaddr_client(dom)) {
585                 ai = lookup_client_addr(dom);
586                 if (!ai)
587                         goto out;
588         }
589
590         /* Now determine export point for this fsid/domain */
591         for (i=0 ; i < MCL_MAXTYPES; i++) {
592                 nfs_export *next_exp;
593                 for (exp = exportlist[i].p_head; exp; exp = next_exp) {
594                         char *path;
595
596                         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT) {
597                                 static nfs_export *prev = NULL;
598                                 static void *mnt = NULL;
599                                 
600                                 if (prev == exp) {
601                                         /* try a submount */
602                                         path = next_mnt(&mnt, exp->m_export.e_path);
603                                         if (!path) {
604                                                 next_exp = exp->m_next;
605                                                 prev = NULL;
606                                                 continue;
607                                         }
608                                         next_exp = exp;
609                                 } else {
610                                         prev = exp;
611                                         mnt = NULL;
612                                         path = exp->m_export.e_path;
613                                         next_exp = exp;
614                                 }
615                         } else {
616                                 path = exp->m_export.e_path;
617                                 next_exp = exp->m_next;
618                         }
619
620                         if (!is_ipaddr_client(dom)
621                                         && !namelist_client_matches(exp, dom))
622                                 continue;
623                         if (exp->m_export.e_mountpoint &&
624                             !is_mountpoint(exp->m_export.e_mountpoint[0]?
625                                            exp->m_export.e_mountpoint:
626                                            exp->m_export.e_path))
627                                 dev_missing ++;
628
629                         if (!match_fsid(&parsed, exp, path))
630                                 continue;
631                         if (is_ipaddr_client(dom)
632                                         && !ipaddr_client_matches(exp, ai))
633                                 continue;
634                         if (!found || subexport(&exp->m_export, found)) {
635                                 found = &exp->m_export;
636                                 free(found_path);
637                                 found_path = strdup(path);
638                                 if (found_path == NULL)
639                                         goto out;
640                         } else if (strcmp(found->e_path, exp->m_export.e_path) != 0
641                                    && !subexport(found, &exp->m_export))
642                         {
643                                 xlog(L_WARNING, "%s and %s have same filehandle for %s, using first",
644                                      found_path, path, dom);
645                         } else {
646                                 /* same path, if one is V4ROOT, choose the other */
647                                 if (found->e_flags & NFSEXP_V4ROOT) {
648                                         found = &exp->m_export;
649                                         free(found_path);
650                                         found_path = strdup(path);
651                                         if (found_path == NULL)
652                                                 goto out;
653                                 }
654                         }
655                 }
656         }
657         if (found && 
658             found->e_mountpoint &&
659             !is_mountpoint(found->e_mountpoint[0]?
660                            found->e_mountpoint:
661                            found->e_path)) {
662                 /* Cannot export this yet 
663                  * should log a warning, but need to rate limit
664                    xlog(L_WARNING, "%s not exported as %d not a mountpoint",
665                    found->e_path, found->e_mountpoint);
666                  */
667                 /* FIXME we need to make sure we re-visit this later */
668                 goto out;
669         }
670         if (!found && dev_missing) {
671                 /* The missing dev could be what we want, so just be
672                  * quite rather than returning stale yet
673                  */
674                 goto out;
675         }
676
677         if (found)
678                 if (cache_export_ent(dom, found, found_path) < 0)
679                         found = 0;
680
681         qword_print(f, dom);
682         qword_printint(f, fsidtype);
683         qword_printhex(f, fsid, fsidlen);
684         /* The fsid -> path lookup can be quite expensive as it
685          * potentially stats and reads lots of devices, and some of those
686          * might have spun-down.  The Answer is not likely to
687          * change underneath us, and an 'exportfs -f' can always
688          * remove this from the kernel, so use a really log
689          * timeout.  Maybe this should be configurable on the command
690          * line.
691          */
692         qword_printint(f, 0x7fffffff);
693         if (found)
694                 qword_print(f, found_path);
695         qword_eol(f);
696  out:
697         if (found_path)
698                 free(found_path);
699         freeaddrinfo(ai);
700         free(dom);
701         xlog(D_CALL, "nfsd_fh: found %p path %s", found, found ? found->e_path : NULL);
702         return;         
703 }
704
705 static void write_fsloc(FILE *f, struct exportent *ep)
706 {
707         struct servers *servers;
708
709         if (ep->e_fslocmethod == FSLOC_NONE)
710                 return;
711
712         servers = replicas_lookup(ep->e_fslocmethod, ep->e_fslocdata);
713         if (!servers)
714                 return;
715         qword_print(f, "fsloc");
716         qword_printint(f, servers->h_num);
717         if (servers->h_num >= 0) {
718                 int i;
719                 for (i=0; i<servers->h_num; i++) {
720                         qword_print(f, servers->h_mp[i]->h_host);
721                         qword_print(f, servers->h_mp[i]->h_path);
722                 }
723         }
724         qword_printint(f, servers->h_referral);
725         release_replicas(servers);
726 }
727
728 static void write_secinfo(FILE *f, struct exportent *ep, int flag_mask)
729 {
730         struct sec_entry *p;
731
732         for (p = ep->e_secinfo; p->flav; p++)
733                 ; /* Do nothing */
734         if (p == ep->e_secinfo) {
735                 /* There was no sec= option */
736                 return;
737         }
738         qword_print(f, "secinfo");
739         qword_printint(f, p - ep->e_secinfo);
740         for (p = ep->e_secinfo; p->flav; p++) {
741                 qword_printint(f, p->flav->fnum);
742                 qword_printint(f, p->flags & flag_mask);
743         }
744
745 }
746
747 static int dump_to_cache(FILE *f, char *domain, char *path, struct exportent *exp)
748 {
749         qword_print(f, domain);
750         qword_print(f, path);
751         if (exp) {
752                 int different_fs = strcmp(path, exp->e_path) != 0;
753                 int flag_mask = different_fs ? ~NFSEXP_FSID : ~0;
754
755                 qword_printtimefrom(f, exp->e_ttl);
756                 qword_printint(f, exp->e_flags & flag_mask);
757                 qword_printint(f, exp->e_anonuid);
758                 qword_printint(f, exp->e_anongid);
759                 qword_printint(f, exp->e_fsid);
760                 write_fsloc(f, exp);
761                 write_secinfo(f, exp, flag_mask);
762                 if (exp->e_uuid == NULL || different_fs) {
763                         char u[16];
764                         if (uuid_by_path(path, 0, 16, u)) {
765                                 qword_print(f, "uuid");
766                                 qword_printhex(f, u, 16);
767                         }
768                 } else {
769                         char u[16];
770                         get_uuid(exp->e_uuid, 16, u);
771                         qword_print(f, "uuid");
772                         qword_printhex(f, u, 16);
773                 }
774         } else
775                 qword_printtimefrom(f, DEFAULT_TTL);
776         return qword_eol(f);
777 }
778
779 static nfs_export *
780 lookup_export(char *dom, char *path, struct addrinfo *ai)
781 {
782         nfs_export *exp;
783         nfs_export *found = NULL;
784         int found_type = 0;
785         int i;
786
787         for (i=0 ; i < MCL_MAXTYPES; i++) {
788                 for (exp = exportlist[i].p_head; exp; exp = exp->m_next) {
789                         if (!export_matches(exp, dom, path, ai))
790                                 continue;
791                         if (!found) {
792                                 found = exp;
793                                 found_type = i;
794                                 continue;
795                         }
796                         /* Always prefer non-V4ROOT exports */
797                         if (exp->m_export.e_flags & NFSEXP_V4ROOT)
798                                 continue;
799                         if (found->m_export.e_flags & NFSEXP_V4ROOT) {
800                                 found = exp;
801                                 found_type = i;
802                                 continue;
803                         }
804
805                         /* If one is a CROSSMOUNT, then prefer the longest path */
806                         if (((found->m_export.e_flags & NFSEXP_CROSSMOUNT) ||
807                              (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)) &&
808                             strlen(found->m_export.e_path) !=
809                             strlen(exp->m_export.e_path)) {
810
811                                 if (strlen(exp->m_export.e_path) >
812                                     strlen(found->m_export.e_path)) {
813                                         found = exp;
814                                         found_type = i;
815                                 }
816                                 continue;
817
818                         } else if (found_type == i && found->m_warned == 0) {
819                                 xlog(L_WARNING, "%s exported to both %s and %s, "
820                                      "arbitrarily choosing options from first",
821                                      path, found->m_client->m_hostname, exp->m_client->m_hostname,
822                                      dom);
823                                 found->m_warned = 1;
824                         }
825                 }
826         }
827         return found;
828 }
829
830 #ifdef HAVE_NFS_PLUGIN_H
831 #include <dlfcn.h>
832 #include <link.h>
833 #include <nfs-plugin.h>
834
835 /*
836  * Find the export entry for the parent of "pathname".
837  * Caller must not free returned exportent.
838  */
839 static struct exportent *lookup_parent_export(char *dom,
840                 const char *pathname, struct addrinfo *ai)
841 {
842         char *parent, *slash;
843         nfs_export *result;
844
845         parent = strdup(pathname);
846         if (parent == NULL) {
847                 xlog(D_GENERAL, "%s: failed to allocate parent path buffer",
848                         __func__);
849                 goto out_default;
850         }
851         xlog(D_CALL, "%s: pathname = '%s'", __func__, pathname);
852
853 again:
854         /* shorten pathname by one component */
855         slash = strrchr(parent, '/');
856         if (slash == NULL) {
857                 xlog(D_GENERAL, "%s: no slash found in pathname",
858                         __func__);
859                 goto out_default;
860         }
861         *slash = '\0';
862
863         if (strlen(parent) == 0) {
864                 result = lookup_export(dom, "/", ai);
865                 if (result == NULL) {
866                         xlog(L_ERROR, "%s: no root export found.", __func__);
867                         goto out_default;
868                 }
869                 goto out;
870         }
871
872         result = lookup_export(dom, parent, ai);
873         if (result == NULL) {
874                 xlog(D_GENERAL, "%s: lookup_export(%s) found nothing",
875                         __func__, parent);
876                 goto again;
877         }
878
879 out:
880         xlog(D_CALL, "%s: found export for %s", __func__, parent);
881         free(parent);
882         return &result->m_export;
883
884 out_default:
885         free(parent);
886         return mkexportent("*", "/", "insecure");
887 }
888
889 /*
890  * Walk through a set of FS locations and build an e_fslocdata string.
891  * Returns true if all went to plan; otherwise, false.
892  */
893 static bool locations_to_fslocdata(struct jp_ops *ops,
894                 nfs_fsloc_set_t locations, char *fslocdata,
895                 size_t remaining, int *ttl)
896 {
897         char *server, *last_path, *rootpath, *ptr;
898         _Bool seen = false;
899
900         last_path = NULL;
901         rootpath = NULL;
902         server = NULL;
903         ptr = fslocdata;
904         *ttl = 0;
905
906         for (;;) {
907                 enum jp_status status;
908                 int len;
909
910                 status = ops->jp_get_next_location(locations, &server,
911                                                         &rootpath, ttl);
912                 if (status == JP_EMPTY)
913                         break;
914                 if (status != JP_OK) {
915                         xlog(D_GENERAL, "%s: failed to parse location: %s",
916                                 __func__, ops->jp_error(status));
917                         goto out_false;
918                 }
919                 xlog(D_GENERAL, "%s: Location: %s:%s",
920                         __func__, server, rootpath);
921
922                 if (last_path && strcmp(rootpath, last_path) == 0) {
923                         len = snprintf(ptr, remaining, "+%s", server);
924                         if (len < 0) {
925                                 xlog(D_GENERAL, "%s: snprintf: %m", __func__);
926                                 goto out_false;
927                         }
928                         if ((size_t)len >= remaining) {
929                                 xlog(D_GENERAL, "%s: fslocdata buffer overflow", __func__);
930                                 goto out_false;
931                         }
932                         remaining -= (size_t)len;
933                         ptr += len;
934                 } else {
935                         if (last_path == NULL)
936                                 len = snprintf(ptr, remaining, "%s@%s",
937                                                         rootpath, server);
938                         else
939                                 len = snprintf(ptr, remaining, ":%s@%s",
940                                                         rootpath, server);
941                         if (len < 0) {
942                                 xlog(D_GENERAL, "%s: snprintf: %m", __func__);
943                                 goto out_false;
944                         }
945                         if ((size_t)len >= remaining) {
946                                 xlog(D_GENERAL, "%s: fslocdata buffer overflow",
947                                         __func__);
948                                 goto out_false;
949                         }
950                         remaining -= (size_t)len;
951                         ptr += len;
952                         last_path = rootpath;
953                 }
954
955                 seen = true;
956                 free(rootpath);
957                 free(server);
958         }
959
960         xlog(D_CALL, "%s: fslocdata='%s', ttl=%d",
961                 __func__, fslocdata, *ttl);
962         return seen;
963
964 out_false:
965         free(rootpath);
966         free(server);
967         return false;
968 }
969
970 /*
971  * Duplicate the junction's parent's export options and graft in
972  * the fslocdata we constructed from the locations list.
973  */
974 static struct exportent *create_junction_exportent(struct exportent *parent,
975                 const char *junction, const char *fslocdata, int ttl)
976 {
977         static struct exportent *eep;
978
979         eep = (struct exportent *)malloc(sizeof(*eep));
980         if (eep == NULL)
981                 goto out_nomem;
982
983         dupexportent(eep, parent);
984         strcpy(eep->e_path, junction);
985         eep->e_hostname = strdup(parent->e_hostname);
986         if (eep->e_hostname == NULL) {
987                 free(eep);
988                 goto out_nomem;
989         }
990         free(eep->e_uuid);
991         eep->e_uuid = NULL;
992         eep->e_ttl = (unsigned int)ttl;
993
994         free(eep->e_fslocdata);
995         eep->e_fslocdata = strdup(fslocdata);
996         if (eep->e_fslocdata == NULL) {
997                 free(eep->e_hostname);
998                 free(eep);
999                 goto out_nomem;
1000         }
1001         eep->e_fslocmethod = FSLOC_REFER;
1002         return eep;
1003
1004 out_nomem:
1005         xlog(L_ERROR, "%s: No memory", __func__);
1006         return NULL;
1007 }
1008
1009 /*
1010  * Walk through the set of FS locations and build an exportent.
1011  * Returns pointer to an exportent if "junction" refers to a junction.
1012  */
1013 static struct exportent *locations_to_export(struct jp_ops *ops,
1014                 nfs_fsloc_set_t locations, const char *junction,
1015                 struct exportent *parent)
1016 {
1017         static char fslocdata[BUFSIZ];
1018         int ttl;
1019
1020         fslocdata[0] = '\0';
1021         if (!locations_to_fslocdata(ops, locations,
1022                                         fslocdata, sizeof(fslocdata), &ttl))
1023                 return NULL;
1024         return create_junction_exportent(parent, junction, fslocdata, ttl);
1025 }
1026
1027 /*
1028  * Retrieve locations information in "junction" and dump it to the
1029  * kernel.  Returns pointer to an exportent if "junction" refers
1030  * to a junction.
1031  */
1032 static struct exportent *invoke_junction_ops(void *handle, char *dom,
1033                 const char *junction, struct addrinfo *ai)
1034 {
1035         struct exportent *parent, *exp = NULL;
1036         nfs_fsloc_set_t locations;
1037         enum jp_status status;
1038         struct jp_ops *ops;
1039         char *error;
1040
1041         ops = (struct jp_ops *)dlsym(handle, "nfs_junction_ops");
1042         error = dlerror();
1043         if (error != NULL) {
1044                 xlog(D_GENERAL, "%s: dlsym(jp_junction_ops): %s",
1045                         __func__, error);
1046                 return NULL;
1047         }
1048         if (ops->jp_api_version != JP_API_VERSION) {
1049                 xlog(D_GENERAL, "%s: unrecognized junction API version: %u",
1050                         __func__, ops->jp_api_version);
1051                 return NULL;
1052         }
1053
1054         status = ops->jp_init(false);
1055         if (status != JP_OK) {
1056                 xlog(D_GENERAL, "%s: failed to resolve %s: %s",
1057                         __func__, junction, ops->jp_error(status));
1058                 return NULL;
1059         }
1060
1061         status = ops->jp_get_locations(junction, &locations);
1062         switch (status) {
1063         case JP_OK:
1064                 break;
1065         case JP_NOTJUNCTION:
1066                 xlog(D_GENERAL, "%s: %s is not a junction",
1067                         __func__, junction);
1068                 goto out;
1069         default:
1070                 xlog(L_WARNING, "Dangling junction %s: %s",
1071                         junction, ops->jp_error(status));
1072                 goto out;
1073         }
1074
1075         parent = lookup_parent_export(dom, junction, ai);
1076         if (parent == NULL)
1077                 goto out;
1078
1079         exp = locations_to_export(ops, locations, junction, parent);
1080
1081         ops->jp_put_locations(locations);
1082
1083 out:
1084         ops->jp_done();
1085         return exp;
1086 }
1087
1088 /*
1089  * Load the junction plug-in, then try to resolve "pathname".
1090  * Returns pointer to an initialized exportent if "junction"
1091  * refers to a junction, or NULL if not.
1092  */
1093 static struct exportent *lookup_junction(char *dom, const char *pathname,
1094                 struct addrinfo *ai)
1095 {
1096         struct exportent *exp;
1097         struct link_map *map;
1098         void *handle;
1099
1100         handle = dlopen("libnfsjunct.so", RTLD_NOW);
1101         if (handle == NULL) {
1102                 xlog(D_GENERAL, "%s: dlopen: %s", __func__, dlerror());
1103                 return NULL;
1104         }
1105
1106         if (dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0)
1107                 xlog(D_GENERAL, "%s: loaded plug-in %s",
1108                         __func__, map->l_name);
1109
1110         (void)dlerror();        /* Clear any error */
1111
1112         exp = invoke_junction_ops(handle, dom, pathname, ai);
1113
1114         /* We could leave it loaded to make junction resolution
1115          * faster next time.  However, if we want to replace the
1116          * library, that would require restarting mountd. */
1117         (void)dlclose(handle);
1118         return exp;
1119 }
1120
1121 static void lookup_nonexport(FILE *f, char *dom, char *path,
1122                 struct addrinfo *ai)
1123 {
1124         struct exportent *eep;
1125
1126         eep = lookup_junction(dom, path, ai);
1127         dump_to_cache(f, dom, path, eep);
1128         if (eep == NULL)
1129                 return;
1130         exportent_release(eep);
1131         free(eep);
1132 }
1133 #else   /* !HAVE_NFS_PLUGIN_H */
1134 static void lookup_nonexport(FILE *f, char *dom, char *path,
1135                 struct addrinfo *UNUSED(ai))
1136 {
1137         dump_to_cache(f, dom, path, NULL);
1138 }
1139 #endif  /* !HAVE_NFS_PLUGIN_H */
1140
1141 static void nfsd_export(FILE *f)
1142 {
1143         /* requests are:
1144          *  domain path
1145          * determine export options and return:
1146          *  domain path expiry flags anonuid anongid fsid
1147          */
1148
1149         char *cp;
1150         char *dom, *path;
1151         nfs_export *found = NULL;
1152         struct addrinfo *ai = NULL;
1153
1154         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
1155                 return;
1156
1157         xlog(D_CALL, "nfsd_export: inbuf '%s'", lbuf);
1158
1159         cp = lbuf;
1160         dom = malloc(strlen(cp));
1161         path = malloc(strlen(cp));
1162
1163         if (!dom || !path)
1164                 goto out;
1165
1166         if (qword_get(&cp, dom, strlen(lbuf)) <= 0)
1167                 goto out;
1168         if (qword_get(&cp, path, strlen(lbuf)) <= 0)
1169                 goto out;
1170
1171         auth_reload();
1172
1173         if (is_ipaddr_client(dom)) {
1174                 ai = lookup_client_addr(dom);
1175                 if (!ai)
1176                         goto out;
1177         }
1178
1179         found = lookup_export(dom, path, ai);
1180
1181         if (found) {
1182                 if (dump_to_cache(f, dom, path, &found->m_export) < 0) {
1183                         xlog(L_WARNING,
1184                              "Cannot export %s, possibly unsupported filesystem"
1185                              " or fsid= required", path);
1186                         dump_to_cache(f, dom, path, NULL);
1187                 }
1188         } else
1189                 lookup_nonexport(f, dom, path, ai);
1190
1191  out:
1192         xlog(D_CALL, "nfsd_export: found %p path %s", found, path ? path : NULL);
1193         if (dom) free(dom);
1194         if (path) free(path);
1195         freeaddrinfo(ai);
1196 }
1197
1198
1199 struct {
1200         char *cache_name;
1201         void (*cache_handle)(FILE *f);
1202         FILE *f;
1203         char vbuf[RPC_CHAN_BUF_SIZE];
1204 } cachelist[] = {
1205         { "auth.unix.ip", auth_unix_ip, NULL, ""},
1206         { "auth.unix.gid", auth_unix_gid, NULL, ""},
1207         { "nfsd.export", nfsd_export, NULL, ""},
1208         { "nfsd.fh", nfsd_fh, NULL, ""},
1209         { NULL, NULL, NULL, ""}
1210 };
1211
1212 extern int manage_gids;
1213
1214 /**
1215  * cache_open - prepare communications channels with kernel RPC caches
1216  *
1217  */
1218 void cache_open(void) 
1219 {
1220         int i;
1221         for (i=0; cachelist[i].cache_name; i++ ) {
1222                 char path[100];
1223                 if (!manage_gids && cachelist[i].cache_handle == auth_unix_gid)
1224                         continue;
1225                 sprintf(path, "/proc/net/rpc/%s/channel", cachelist[i].cache_name);
1226                 cachelist[i].f = fopen(path, "r+");
1227                 if (cachelist[i].f != NULL) {
1228                         setvbuf(cachelist[i].f, cachelist[i].vbuf, _IOLBF, 
1229                                 RPC_CHAN_BUF_SIZE);
1230                 }
1231         }
1232 }
1233
1234 /**
1235  * cache_set_fds - prepare cache file descriptors for one iteration of the service loop
1236  * @fdset: pointer to fd_set to prepare
1237  */
1238 void cache_set_fds(fd_set *fdset)
1239 {
1240         int i;
1241         for (i=0; cachelist[i].cache_name; i++) {
1242                 if (cachelist[i].f)
1243                         FD_SET(fileno(cachelist[i].f), fdset);
1244         }
1245 }
1246
1247 /**
1248  * cache_process_req - process any active cache file descriptors during service loop iteration
1249  * @fdset: pointer to fd_set to examine for activity
1250  */
1251 int cache_process_req(fd_set *readfds) 
1252 {
1253         int i;
1254         int cnt = 0;
1255         for (i=0; cachelist[i].cache_name; i++) {
1256                 if (cachelist[i].f != NULL &&
1257                     FD_ISSET(fileno(cachelist[i].f), readfds)) {
1258                         cnt++;
1259                         cachelist[i].cache_handle(cachelist[i].f);
1260                         FD_CLR(fileno(cachelist[i].f), readfds);
1261                 }
1262         }
1263         return cnt;
1264 }
1265
1266
1267 /*
1268  * Give IP->domain and domain+path->options to kernel
1269  * % echo nfsd $IP  $[now+DEFAULT_TTL] $domain > /proc/net/rpc/auth.unix.ip/channel
1270  * % echo $domain $path $[now+DEFAULT_TTL] $options $anonuid $anongid $fsid > /proc/net/rpc/nfsd.export/channel
1271  */
1272
1273 static int cache_export_ent(char *domain, struct exportent *exp, char *path)
1274 {
1275         int err;
1276         FILE *f = fopen("/proc/net/rpc/nfsd.export/channel", "w");
1277         if (!f)
1278                 return -1;
1279
1280         err = dump_to_cache(f, domain, exp->e_path, exp);
1281         if (err) {
1282                 xlog(L_WARNING,
1283                      "Cannot export %s, possibly unsupported filesystem or"
1284                      " fsid= required", exp->e_path);
1285         }
1286
1287         while (err == 0 && (exp->e_flags & NFSEXP_CROSSMOUNT) && path) {
1288                 /* really an 'if', but we can break out of
1289                  * a 'while' more easily */
1290                 /* Look along 'path' for other filesystems
1291                  * and export them with the same options
1292                  */
1293                 struct stat stb;
1294                 size_t l = strlen(exp->e_path);
1295                 __dev_t dev;
1296
1297                 if (strlen(path) <= l || path[l] != '/' ||
1298                     strncmp(exp->e_path, path, l) != 0)
1299                         break;
1300                 if (stat(exp->e_path, &stb) != 0)
1301                         break;
1302                 dev = stb.st_dev;
1303                 while(path[l] == '/') {
1304                         char c;
1305                         /* errors for submount should fail whole filesystem */
1306                         int err2;
1307
1308                         l++;
1309                         while (path[l] != '/' && path[l])
1310                                 l++;
1311                         c = path[l];
1312                         path[l] = 0;
1313                         err2 = lstat(path, &stb);
1314                         path[l] = c;
1315                         if (err2 < 0)
1316                                 break;
1317                         if (stb.st_dev == dev)
1318                                 continue;
1319                         dev = stb.st_dev;
1320                         path[l] = 0;
1321                         dump_to_cache(f, domain, path, exp);
1322                         path[l] = c;
1323                 }
1324                 break;
1325         }
1326
1327         fclose(f);
1328         return err;
1329 }
1330
1331 /**
1332  * cache_export - Inform kernel of a new nfs_export
1333  * @exp: target nfs_export
1334  * @path: NUL-terminated C string containing export path
1335  */
1336 int cache_export(nfs_export *exp, char *path)
1337 {
1338         char buf[INET6_ADDRSTRLEN];
1339         int err;
1340         FILE *f;
1341
1342         f = fopen("/proc/net/rpc/auth.unix.ip/channel", "w");
1343         if (!f)
1344                 return -1;
1345
1346
1347         qword_print(f, "nfsd");
1348         qword_print(f,
1349                 host_ntop(get_addrlist(exp->m_client, 0), buf, sizeof(buf)));
1350         qword_printtimefrom(f, exp->m_export.e_ttl);
1351         qword_print(f, exp->m_client->m_hostname);
1352         err = qword_eol(f);
1353         
1354         fclose(f);
1355
1356         err = cache_export_ent(exp->m_client->m_hostname, &exp->m_export, path)
1357                 || err;
1358         return err;
1359 }
1360
1361 /**
1362  * cache_get_filehandle - given an nfs_export, get its root filehandle
1363  * @exp: target nfs_export
1364  * @len: length of requested file handle
1365  * @p: NUL-terminated C string containing export path
1366  *
1367  * Returns pointer to NFS file handle of root directory of export
1368  *
1369  * { 
1370  *   echo $domain $path $length 
1371  *   read filehandle <&0
1372  * } <> /proc/fs/nfsd/filehandle
1373  */
1374 struct nfs_fh_len *
1375 cache_get_filehandle(nfs_export *exp, int len, char *p)
1376 {
1377         FILE *f = fopen("/proc/fs/nfsd/filehandle", "r+");
1378         char buf[200];
1379         char *bp = buf;
1380         int failed;
1381         static struct nfs_fh_len fh;
1382
1383         if (!f)
1384                 f = fopen("/proc/fs/nfs/filehandle", "r+");
1385         if (!f)
1386                 return NULL;
1387
1388         qword_print(f, exp->m_client->m_hostname);
1389         qword_print(f, p);
1390         qword_printint(f, len); 
1391         failed = qword_eol(f);
1392         
1393         if (!failed)
1394                 failed = (fgets(buf, sizeof(buf), f) == NULL);
1395         fclose(f);
1396         if (failed)
1397                 return NULL;
1398         memset(fh.fh_handle, 0, sizeof(fh.fh_handle));
1399         fh.fh_size = qword_get(&bp, (char *)fh.fh_handle, NFS3_FHSIZE);
1400         return &fh;
1401 }