]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mountd/cache.c
mountd: Report the absolute path used to load the junction plug-in
[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 /* True iff e1 is a child of e2 and e2 has crossmnt set: */
347 static bool subexport(struct exportent *e1, struct exportent *e2)
348 {
349         char *p1 = e1->e_path, *p2 = e2->e_path;
350         size_t l2 = strlen(p2);
351
352         return e2->e_flags & NFSEXP_CROSSMOUNT
353                && strncmp(p1, p2, l2) == 0
354                && p1[l2] == '/';
355 }
356
357 struct parsed_fsid {
358         int fsidtype;
359         /* We could use a union for this, but it would be more
360          * complicated; why bother? */
361         unsigned int inode;
362         unsigned int minor;
363         unsigned int major;
364         unsigned int fsidnum;
365         size_t uuidlen;
366         char *fhuuid;
367 };
368
369 static int parse_fsid(int fsidtype, int fsidlen, char *fsid,
370                 struct parsed_fsid *parsed)
371 {
372         unsigned int dev;
373         unsigned long long inode64;
374
375         memset(parsed, 0, sizeof(*parsed));
376         parsed->fsidtype = fsidtype;
377         switch(fsidtype) {
378         case FSID_DEV: /* 4 bytes: 2 major, 2 minor, 4 inode */
379                 if (fsidlen != 8)
380                         return -1;
381                 memcpy(&dev, fsid, 4);
382                 memcpy(&parsed->inode, fsid+4, 4);
383                 parsed->major = ntohl(dev)>>16;
384                 parsed->minor = ntohl(dev) & 0xFFFF;
385                 break;
386
387         case FSID_NUM: /* 4 bytes - fsid */
388                 if (fsidlen != 4)
389                         return -1;
390                 memcpy(&parsed->fsidnum, fsid, 4);
391                 break;
392
393         case FSID_MAJOR_MINOR: /* 12 bytes: 4 major, 4 minor, 4 inode 
394                  * This format is never actually used but was
395                  * an historical accident
396                  */
397                 if (fsidlen != 12)
398                         return -1;
399                 memcpy(&dev, fsid, 4);
400                 parsed->major = ntohl(dev);
401                 memcpy(&dev, fsid+4, 4);
402                 parsed->minor = ntohl(dev);
403                 memcpy(&parsed->inode, fsid+8, 4);
404                 break;
405
406         case FSID_ENCODE_DEV: /* 8 bytes: 4 byte packed device number, 4 inode */
407                 /* This is *host* endian, not net-byte-order, because
408                  * no-one outside this host has any business interpreting it
409                  */
410                 if (fsidlen != 8)
411                         return -1;
412                 memcpy(&dev, fsid, 4);
413                 memcpy(&parsed->inode, fsid+4, 4);
414                 parsed->major = (dev & 0xfff00) >> 8;
415                 parsed->minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
416                 break;
417
418         case FSID_UUID4_INUM: /* 4 byte inode number and 4 byte uuid */
419                 if (fsidlen != 8)
420                         return -1;
421                 memcpy(&parsed->inode, fsid, 4);
422                 parsed->uuidlen = 4;
423                 parsed->fhuuid = fsid+4;
424                 break;
425         case FSID_UUID8: /* 8 byte uuid */
426                 if (fsidlen != 8)
427                         return -1;
428                 parsed->uuidlen = 8;
429                 parsed->fhuuid = fsid;
430                 break;
431         case FSID_UUID16: /* 16 byte uuid */
432                 if (fsidlen != 16)
433                         return -1;
434                 parsed->uuidlen = 16;
435                 parsed->fhuuid = fsid;
436                 break;
437         case FSID_UUID16_INUM: /* 8 byte inode number and 16 byte uuid */
438                 if (fsidlen != 24)
439                         return -1;
440                 memcpy(&inode64, fsid, 8);
441                 parsed->inode = inode64;
442                 parsed->uuidlen = 16;
443                 parsed->fhuuid = fsid+8;
444                 break;
445         }
446         return 0;
447 }
448
449 static bool match_fsid(struct parsed_fsid *parsed, nfs_export *exp, char *path)
450 {
451         struct stat stb;
452         int type;
453         char u[16];
454
455         if (stat(path, &stb) != 0)
456                 return false;
457         if (!S_ISDIR(stb.st_mode) && !S_ISREG(stb.st_mode))
458                 return false;
459
460         switch (parsed->fsidtype) {
461         case FSID_DEV:
462         case FSID_MAJOR_MINOR:
463         case FSID_ENCODE_DEV:
464                 if (stb.st_ino != parsed->inode)
465                         return false;
466                 if (parsed->major != major(stb.st_dev) ||
467                     parsed->minor != minor(stb.st_dev))
468                         return false;
469                 return true;
470         case FSID_NUM:
471                 if (((exp->m_export.e_flags & NFSEXP_FSID) == 0 ||
472                      exp->m_export.e_fsid != parsed->fsidnum))
473                         return false;
474                 return true;
475         case FSID_UUID4_INUM:
476         case FSID_UUID16_INUM:
477                 if (stb.st_ino != parsed->inode)
478                         return false;
479                 goto check_uuid;
480         case FSID_UUID8:
481         case FSID_UUID16:
482                 if (!is_mountpoint(path))
483                         return false;
484         check_uuid:
485                 if (exp->m_export.e_uuid)
486                         get_uuid(exp->m_export.e_uuid, parsed->uuidlen, u);
487                 else
488                         for (type = 0;
489                              uuid_by_path(path, type, parsed->uuidlen, u);
490                              type++)
491                                 if (memcmp(u, parsed->fhuuid, parsed->uuidlen) == 0)
492                                         return true;
493
494                 if (memcmp(u, parsed->fhuuid, parsed->uuidlen) != 0)
495                         return false;
496                 return true;
497         }
498         /* Well, unreachable, actually: */
499         return false;
500 }
501
502 static struct addrinfo *lookup_client_addr(char *dom)
503 {
504         struct addrinfo *ret;
505         struct addrinfo *tmp;
506
507         dom++; /* skip initial "$" */
508
509         tmp = host_pton(dom);
510         if (tmp == NULL)
511                 return NULL;
512         ret = client_resolve(tmp->ai_addr);
513         freeaddrinfo(tmp);
514         return ret;
515 }
516
517 static void nfsd_fh(FILE *f)
518 {
519         /* request are:
520          *  domain fsidtype fsid
521          * interpret fsid, find export point and options, and write:
522          *  domain fsidtype fsid expiry path
523          */
524         char *cp;
525         char *dom;
526         int fsidtype;
527         int fsidlen;
528         char fsid[32];
529         struct parsed_fsid parsed;
530         struct exportent *found = NULL;
531         struct addrinfo *ai = NULL;
532         char *found_path = NULL;
533         nfs_export *exp;
534         int i;
535         int dev_missing = 0;
536
537         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
538                 return;
539
540         xlog(D_CALL, "nfsd_fh: inbuf '%s'", lbuf);
541
542         cp = lbuf;
543
544         dom = malloc(strlen(cp));
545         if (dom == NULL)
546                 return;
547         if (qword_get(&cp, dom, strlen(cp)) <= 0)
548                 goto out;
549         if (qword_get_int(&cp, &fsidtype) != 0)
550                 goto out;
551         if (fsidtype < 0 || fsidtype > 7)
552                 goto out; /* unknown type */
553         if ((fsidlen = qword_get(&cp, fsid, 32)) <= 0)
554                 goto out;
555         if (parse_fsid(fsidtype, fsidlen, fsid, &parsed))
556                 goto out;
557
558         auth_reload();
559
560         if (is_ipaddr_client(dom)) {
561                 ai = lookup_client_addr(dom);
562                 if (!ai)
563                         goto out;
564         }
565
566         /* Now determine export point for this fsid/domain */
567         for (i=0 ; i < MCL_MAXTYPES; i++) {
568                 nfs_export *next_exp;
569                 for (exp = exportlist[i].p_head; exp; exp = next_exp) {
570                         char *path;
571
572                         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT) {
573                                 static nfs_export *prev = NULL;
574                                 static void *mnt = NULL;
575                                 
576                                 if (prev == exp) {
577                                         /* try a submount */
578                                         path = next_mnt(&mnt, exp->m_export.e_path);
579                                         if (!path) {
580                                                 next_exp = exp->m_next;
581                                                 prev = NULL;
582                                                 continue;
583                                         }
584                                         next_exp = exp;
585                                 } else {
586                                         prev = exp;
587                                         mnt = NULL;
588                                         path = exp->m_export.e_path;
589                                         next_exp = exp;
590                                 }
591                         } else {
592                                 path = exp->m_export.e_path;
593                                 next_exp = exp->m_next;
594                         }
595
596                         if (!is_ipaddr_client(dom)
597                                         && !namelist_client_matches(exp, dom))
598                                 continue;
599                         if (exp->m_export.e_mountpoint &&
600                             !is_mountpoint(exp->m_export.e_mountpoint[0]?
601                                            exp->m_export.e_mountpoint:
602                                            exp->m_export.e_path))
603                                 dev_missing ++;
604
605                         if (!match_fsid(&parsed, exp, path))
606                                 continue;
607                         if (is_ipaddr_client(dom)
608                                         && !ipaddr_client_matches(exp, ai))
609                                 continue;
610                         if (!found || subexport(&exp->m_export, found)) {
611                                 found = &exp->m_export;
612                                 free(found_path);
613                                 found_path = strdup(path);
614                                 if (found_path == NULL)
615                                         goto out;
616                         } else if (strcmp(found->e_path, exp->m_export.e_path) != 0
617                                    && !subexport(found, &exp->m_export))
618                         {
619                                 xlog(L_WARNING, "%s and %s have same filehandle for %s, using first",
620                                      found_path, path, dom);
621                         } else {
622                                 /* same path, if one is V4ROOT, choose the other */
623                                 if (found->e_flags & NFSEXP_V4ROOT) {
624                                         found = &exp->m_export;
625                                         free(found_path);
626                                         found_path = strdup(path);
627                                         if (found_path == NULL)
628                                                 goto out;
629                                 }
630                         }
631                 }
632         }
633         if (found && 
634             found->e_mountpoint &&
635             !is_mountpoint(found->e_mountpoint[0]?
636                            found->e_mountpoint:
637                            found->e_path)) {
638                 /* Cannot export this yet 
639                  * should log a warning, but need to rate limit
640                    xlog(L_WARNING, "%s not exported as %d not a mountpoint",
641                    found->e_path, found->e_mountpoint);
642                  */
643                 /* FIXME we need to make sure we re-visit this later */
644                 goto out;
645         }
646         if (!found && dev_missing) {
647                 /* The missing dev could be what we want, so just be
648                  * quite rather than returning stale yet
649                  */
650                 goto out;
651         }
652
653         if (found)
654                 if (cache_export_ent(dom, found, found_path) < 0)
655                         found = 0;
656
657         qword_print(f, dom);
658         qword_printint(f, fsidtype);
659         qword_printhex(f, fsid, fsidlen);
660         /* The fsid -> path lookup can be quite expensive as it
661          * potentially stats and reads lots of devices, and some of those
662          * might have spun-down.  The Answer is not likely to
663          * change underneath us, and an 'exportfs -f' can always
664          * remove this from the kernel, so use a really log
665          * timeout.  Maybe this should be configurable on the command
666          * line.
667          */
668         qword_printint(f, 0x7fffffff);
669         if (found)
670                 qword_print(f, found_path);
671         qword_eol(f);
672  out:
673         if (found_path)
674                 free(found_path);
675         freeaddrinfo(ai);
676         free(dom);
677         xlog(D_CALL, "nfsd_fh: found %p path %s", found, found ? found->e_path : NULL);
678         return;         
679 }
680
681 static void write_fsloc(FILE *f, struct exportent *ep)
682 {
683         struct servers *servers;
684
685         if (ep->e_fslocmethod == FSLOC_NONE)
686                 return;
687
688         servers = replicas_lookup(ep->e_fslocmethod, ep->e_fslocdata);
689         if (!servers)
690                 return;
691         qword_print(f, "fsloc");
692         qword_printint(f, servers->h_num);
693         if (servers->h_num >= 0) {
694                 int i;
695                 for (i=0; i<servers->h_num; i++) {
696                         qword_print(f, servers->h_mp[i]->h_host);
697                         qword_print(f, servers->h_mp[i]->h_path);
698                 }
699         }
700         qword_printint(f, servers->h_referral);
701         release_replicas(servers);
702 }
703
704 static void write_secinfo(FILE *f, struct exportent *ep, int flag_mask)
705 {
706         struct sec_entry *p;
707
708         for (p = ep->e_secinfo; p->flav; p++)
709                 ; /* Do nothing */
710         if (p == ep->e_secinfo) {
711                 /* There was no sec= option */
712                 return;
713         }
714         qword_print(f, "secinfo");
715         qword_printint(f, p - ep->e_secinfo);
716         for (p = ep->e_secinfo; p->flav; p++) {
717                 qword_printint(f, p->flav->fnum);
718                 qword_printint(f, p->flags & flag_mask);
719         }
720
721 }
722
723 static int dump_to_cache(FILE *f, char *domain, char *path, struct exportent *exp)
724 {
725         qword_print(f, domain);
726         qword_print(f, path);
727         if (exp) {
728                 int different_fs = strcmp(path, exp->e_path) != 0;
729                 int flag_mask = different_fs ? ~NFSEXP_FSID : ~0;
730
731                 qword_printtimefrom(f, exp->e_ttl);
732                 qword_printint(f, exp->e_flags & flag_mask);
733                 qword_printint(f, exp->e_anonuid);
734                 qword_printint(f, exp->e_anongid);
735                 qword_printint(f, exp->e_fsid);
736                 write_fsloc(f, exp);
737                 write_secinfo(f, exp, flag_mask);
738                 if (exp->e_uuid == NULL || different_fs) {
739                         char u[16];
740                         if (uuid_by_path(path, 0, 16, u)) {
741                                 qword_print(f, "uuid");
742                                 qword_printhex(f, u, 16);
743                         }
744                 } else {
745                         char u[16];
746                         get_uuid(exp->e_uuid, 16, u);
747                         qword_print(f, "uuid");
748                         qword_printhex(f, u, 16);
749                 }
750         } else
751                 qword_printtimefrom(f, DEFAULT_TTL);
752         return qword_eol(f);
753 }
754
755 static int is_subdirectory(char *child, char *parent)
756 {
757         size_t l = strlen(parent);
758
759         return strcmp(child, parent) == 0
760                 || (strncmp(child, parent, l) == 0 && child[l] == '/');
761 }
762
763 static int path_matches(nfs_export *exp, char *path)
764 {
765         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)
766                 return is_subdirectory(path, exp->m_export.e_path);
767         return strcmp(path, exp->m_export.e_path) == 0;
768 }
769
770 static int
771 export_matches(nfs_export *exp, char *dom, char *path, struct addrinfo *ai)
772 {
773         return path_matches(exp, path) && client_matches(exp, dom, ai);
774 }
775
776 static nfs_export *
777 lookup_export(char *dom, char *path, struct addrinfo *ai)
778 {
779         nfs_export *exp;
780         nfs_export *found = NULL;
781         int found_type = 0;
782         int i;
783
784         for (i=0 ; i < MCL_MAXTYPES; i++) {
785                 for (exp = exportlist[i].p_head; exp; exp = exp->m_next) {
786                         if (!export_matches(exp, dom, path, ai))
787                                 continue;
788                         if (!found) {
789                                 found = exp;
790                                 found_type = i;
791                                 continue;
792                         }
793                         /* Always prefer non-V4ROOT exports */
794                         if (exp->m_export.e_flags & NFSEXP_V4ROOT)
795                                 continue;
796                         if (found->m_export.e_flags & NFSEXP_V4ROOT) {
797                                 found = exp;
798                                 found_type = i;
799                                 continue;
800                         }
801
802                         /* If one is a CROSSMOUNT, then prefer the longest path */
803                         if (((found->m_export.e_flags & NFSEXP_CROSSMOUNT) ||
804                              (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)) &&
805                             strlen(found->m_export.e_path) !=
806                             strlen(exp->m_export.e_path)) {
807
808                                 if (strlen(exp->m_export.e_path) >
809                                     strlen(found->m_export.e_path)) {
810                                         found = exp;
811                                         found_type = i;
812                                 }
813                                 continue;
814
815                         } else if (found_type == i && found->m_warned == 0) {
816                                 xlog(L_WARNING, "%s exported to both %s and %s, "
817                                      "arbitrarily choosing options from first",
818                                      path, found->m_client->m_hostname, exp->m_client->m_hostname,
819                                      dom);
820                                 found->m_warned = 1;
821                         }
822                 }
823         }
824         return found;
825 }
826
827 #ifdef HAVE_NFS_PLUGIN_H
828 #include <dlfcn.h>
829 #include <link.h>
830 #include <nfs-plugin.h>
831
832 /*
833  * Find the export entry for the parent of "pathname".
834  * Caller must not free returned exportent.
835  */
836 static struct exportent *lookup_parent_export(char *dom,
837                 const char *pathname, struct addrinfo *ai)
838 {
839         char *parent, *slash;
840         nfs_export *result;
841
842         parent = strdup(pathname);
843         if (parent == NULL) {
844                 xlog(D_GENERAL, "%s: failed to allocate parent path buffer",
845                         __func__);
846                 goto out_default;
847         }
848         xlog(D_CALL, "%s: pathname = '%s'", __func__, pathname);
849
850 again:
851         /* shorten pathname by one component */
852         slash = strrchr(parent, '/');
853         if (slash == NULL) {
854                 xlog(D_GENERAL, "%s: no slash found in pathname",
855                         __func__);
856                 goto out_default;
857         }
858         *slash = '\0';
859
860         if (strlen(parent) == 0) {
861                 result = lookup_export(dom, "/", ai);
862                 if (result == NULL) {
863                         xlog(L_ERROR, "%s: no root export found.", __func__);
864                         goto out_default;
865                 }
866                 goto out;
867         }
868
869         result = lookup_export(dom, parent, ai);
870         if (result == NULL) {
871                 xlog(D_GENERAL, "%s: lookup_export(%s) found nothing",
872                         __func__, parent);
873                 goto again;
874         }
875
876 out:
877         xlog(D_CALL, "%s: found export for %s", __func__, parent);
878         free(parent);
879         return &result->m_export;
880
881 out_default:
882         free(parent);
883         return mkexportent("*", "/", "insecure");
884 }
885
886 /*
887  * Walk through a set of FS locations and build an e_fslocdata string.
888  * Returns true if all went to plan; otherwise, false.
889  */
890 static bool locations_to_fslocdata(struct jp_ops *ops,
891                 nfs_fsloc_set_t locations, char *fslocdata,
892                 size_t remaining, int *ttl)
893 {
894         char *server, *last_path, *rootpath, *ptr;
895         _Bool seen = false;
896
897         last_path = NULL;
898         rootpath = NULL;
899         server = NULL;
900         ptr = fslocdata;
901         *ttl = 0;
902
903         for (;;) {
904                 enum jp_status status;
905                 int len;
906
907                 status = ops->jp_get_next_location(locations, &server,
908                                                         &rootpath, ttl);
909                 if (status == JP_EMPTY)
910                         break;
911                 if (status != JP_OK) {
912                         xlog(D_GENERAL, "%s: failed to parse location: %s",
913                                 __func__, ops->jp_error(status));
914                         goto out_false;
915                 }
916                 xlog(D_GENERAL, "%s: Location: %s:%s",
917                         __func__, server, rootpath);
918
919                 if (last_path && strcmp(rootpath, last_path) == 0) {
920                         len = snprintf(ptr, remaining, "+%s", server);
921                         if (len < 0) {
922                                 xlog(D_GENERAL, "%s: snprintf: %m", __func__);
923                                 goto out_false;
924                         }
925                         if ((size_t)len >= remaining) {
926                                 xlog(D_GENERAL, "%s: fslocdata buffer overflow", __func__);
927                                 goto out_false;
928                         }
929                         remaining -= (size_t)len;
930                         ptr += len;
931                 } else {
932                         if (last_path == NULL)
933                                 len = snprintf(ptr, remaining, "%s@%s",
934                                                         rootpath, server);
935                         else
936                                 len = snprintf(ptr, remaining, ":%s@%s",
937                                                         rootpath, server);
938                         if (len < 0) {
939                                 xlog(D_GENERAL, "%s: snprintf: %m", __func__);
940                                 goto out_false;
941                         }
942                         if ((size_t)len >= remaining) {
943                                 xlog(D_GENERAL, "%s: fslocdata buffer overflow",
944                                         __func__);
945                                 goto out_false;
946                         }
947                         remaining -= (size_t)len;
948                         ptr += len;
949                         last_path = rootpath;
950                 }
951
952                 seen = true;
953                 free(rootpath);
954                 free(server);
955         }
956
957         xlog(D_CALL, "%s: fslocdata='%s', ttl=%d",
958                 __func__, fslocdata, *ttl);
959         return seen;
960
961 out_false:
962         free(rootpath);
963         free(server);
964         return false;
965 }
966
967 /*
968  * Duplicate the junction's parent's export options and graft in
969  * the fslocdata we constructed from the locations list.
970  */
971 static struct exportent *create_junction_exportent(struct exportent *parent,
972                 const char *junction, const char *fslocdata, int ttl)
973 {
974         static struct exportent *eep;
975
976         eep = (struct exportent *)malloc(sizeof(*eep));
977         if (eep == NULL)
978                 goto out_nomem;
979
980         dupexportent(eep, parent);
981         strcpy(eep->e_path, junction);
982         eep->e_hostname = strdup(parent->e_hostname);
983         if (eep->e_hostname == NULL) {
984                 free(eep);
985                 goto out_nomem;
986         }
987         free(eep->e_uuid);
988         eep->e_uuid = NULL;
989         eep->e_ttl = (unsigned int)ttl;
990
991         free(eep->e_fslocdata);
992         eep->e_fslocdata = strdup(fslocdata);
993         if (eep->e_fslocdata == NULL) {
994                 free(eep->e_hostname);
995                 free(eep);
996                 goto out_nomem;
997         }
998         eep->e_fslocmethod = FSLOC_REFER;
999         return eep;
1000
1001 out_nomem:
1002         xlog(L_ERROR, "%s: No memory", __func__);
1003         return NULL;
1004 }
1005
1006 /*
1007  * Walk through the set of FS locations and build an exportent.
1008  * Returns pointer to an exportent if "junction" refers to a junction.
1009  */
1010 static struct exportent *locations_to_export(struct jp_ops *ops,
1011                 nfs_fsloc_set_t locations, const char *junction,
1012                 struct exportent *parent)
1013 {
1014         static char fslocdata[BUFSIZ];
1015         int ttl;
1016
1017         fslocdata[0] = '\0';
1018         if (!locations_to_fslocdata(ops, locations,
1019                                         fslocdata, sizeof(fslocdata), &ttl))
1020                 return NULL;
1021         return create_junction_exportent(parent, junction, fslocdata, ttl);
1022 }
1023
1024 /*
1025  * Retrieve locations information in "junction" and dump it to the
1026  * kernel.  Returns pointer to an exportent if "junction" refers
1027  * to a junction.
1028  */
1029 static struct exportent *invoke_junction_ops(void *handle, char *dom,
1030                 const char *junction, struct addrinfo *ai)
1031 {
1032         struct exportent *parent, *exp = NULL;
1033         nfs_fsloc_set_t locations;
1034         enum jp_status status;
1035         struct jp_ops *ops;
1036         char *error;
1037
1038         ops = (struct jp_ops *)dlsym(handle, "nfs_junction_ops");
1039         error = dlerror();
1040         if (error != NULL) {
1041                 xlog(D_GENERAL, "%s: dlsym(jp_junction_ops): %s",
1042                         __func__, error);
1043                 return NULL;
1044         }
1045         if (ops->jp_api_version != JP_API_VERSION) {
1046                 xlog(D_GENERAL, "%s: unrecognized junction API version: %u",
1047                         __func__, ops->jp_api_version);
1048                 return NULL;
1049         }
1050
1051         status = ops->jp_init(false);
1052         if (status != JP_OK) {
1053                 xlog(D_GENERAL, "%s: failed to resolve %s: %s",
1054                         __func__, junction, ops->jp_error(status));
1055                 return NULL;
1056         }
1057
1058         status = ops->jp_get_locations(junction, &locations);
1059         switch (status) {
1060         case JP_OK:
1061                 break;
1062         case JP_NOTJUNCTION:
1063                 xlog(D_GENERAL, "%s: %s is not a junction",
1064                         __func__, junction);
1065                 goto out;
1066         default:
1067                 xlog(L_WARNING, "Dangling junction %s: %s",
1068                         junction, ops->jp_error(status));
1069                 goto out;
1070         }
1071
1072         parent = lookup_parent_export(dom, junction, ai);
1073         if (parent == NULL)
1074                 goto out;
1075
1076         exp = locations_to_export(ops, locations, junction, parent);
1077
1078         ops->jp_put_locations(locations);
1079
1080 out:
1081         ops->jp_done();
1082         return exp;
1083 }
1084
1085 /*
1086  * Load the junction plug-in, then try to resolve "pathname".
1087  * Returns pointer to an initialized exportent if "junction"
1088  * refers to a junction, or NULL if not.
1089  */
1090 static struct exportent *lookup_junction(char *dom, const char *pathname,
1091                 struct addrinfo *ai)
1092 {
1093         struct exportent *exp;
1094         struct link_map *map;
1095         void *handle;
1096
1097         handle = dlopen("libnfsjunct.so", RTLD_NOW);
1098         if (handle == NULL) {
1099                 xlog(D_GENERAL, "%s: dlopen: %s", __func__, dlerror());
1100                 return NULL;
1101         }
1102
1103         if (dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0)
1104                 xlog(D_GENERAL, "%s: loaded plug-in %s",
1105                         __func__, map->l_name);
1106
1107         (void)dlerror();        /* Clear any error */
1108
1109         exp = invoke_junction_ops(handle, dom, pathname, ai);
1110
1111         /* We could leave it loaded to make junction resolution
1112          * faster next time.  However, if we want to replace the
1113          * library, that would require restarting mountd. */
1114         (void)dlclose(handle);
1115         return exp;
1116 }
1117
1118 static void lookup_nonexport(FILE *f, char *dom, char *path,
1119                 struct addrinfo *ai)
1120 {
1121         struct exportent *eep;
1122
1123         eep = lookup_junction(dom, path, ai);
1124         dump_to_cache(f, dom, path, eep);
1125         if (eep == NULL)
1126                 return;
1127         exportent_release(eep);
1128         free(eep);
1129 }
1130 #else   /* !HAVE_NFS_PLUGIN_H */
1131 static void lookup_nonexport(FILE *f, char *dom, char *path,
1132                 struct addrinfo *UNUSED(ai))
1133 {
1134         dump_to_cache(f, dom, path, NULL);
1135 }
1136 #endif  /* !HAVE_NFS_PLUGIN_H */
1137
1138 static void nfsd_export(FILE *f)
1139 {
1140         /* requests are:
1141          *  domain path
1142          * determine export options and return:
1143          *  domain path expiry flags anonuid anongid fsid
1144          */
1145
1146         char *cp;
1147         char *dom, *path;
1148         nfs_export *found = NULL;
1149         struct addrinfo *ai = NULL;
1150
1151         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
1152                 return;
1153
1154         xlog(D_CALL, "nfsd_export: inbuf '%s'", lbuf);
1155
1156         cp = lbuf;
1157         dom = malloc(strlen(cp));
1158         path = malloc(strlen(cp));
1159
1160         if (!dom || !path)
1161                 goto out;
1162
1163         if (qword_get(&cp, dom, strlen(lbuf)) <= 0)
1164                 goto out;
1165         if (qword_get(&cp, path, strlen(lbuf)) <= 0)
1166                 goto out;
1167
1168         auth_reload();
1169
1170         if (is_ipaddr_client(dom)) {
1171                 ai = lookup_client_addr(dom);
1172                 if (!ai)
1173                         goto out;
1174         }
1175
1176         found = lookup_export(dom, path, ai);
1177
1178         if (found) {
1179                 if (dump_to_cache(f, dom, path, &found->m_export) < 0) {
1180                         xlog(L_WARNING,
1181                              "Cannot export %s, possibly unsupported filesystem"
1182                              " or fsid= required", path);
1183                         dump_to_cache(f, dom, path, NULL);
1184                 }
1185         } else
1186                 lookup_nonexport(f, dom, path, ai);
1187
1188  out:
1189         xlog(D_CALL, "nfsd_export: found %p path %s", found, path ? path : NULL);
1190         if (dom) free(dom);
1191         if (path) free(path);
1192         freeaddrinfo(ai);
1193 }
1194
1195
1196 struct {
1197         char *cache_name;
1198         void (*cache_handle)(FILE *f);
1199         FILE *f;
1200         char vbuf[RPC_CHAN_BUF_SIZE];
1201 } cachelist[] = {
1202         { "auth.unix.ip", auth_unix_ip, NULL, ""},
1203         { "auth.unix.gid", auth_unix_gid, NULL, ""},
1204         { "nfsd.export", nfsd_export, NULL, ""},
1205         { "nfsd.fh", nfsd_fh, NULL, ""},
1206         { NULL, NULL, NULL, ""}
1207 };
1208
1209 extern int manage_gids;
1210
1211 /**
1212  * cache_open - prepare communications channels with kernel RPC caches
1213  *
1214  */
1215 void cache_open(void) 
1216 {
1217         int i;
1218         for (i=0; cachelist[i].cache_name; i++ ) {
1219                 char path[100];
1220                 if (!manage_gids && cachelist[i].cache_handle == auth_unix_gid)
1221                         continue;
1222                 sprintf(path, "/proc/net/rpc/%s/channel", cachelist[i].cache_name);
1223                 cachelist[i].f = fopen(path, "r+");
1224                 if (cachelist[i].f != NULL) {
1225                         setvbuf(cachelist[i].f, cachelist[i].vbuf, _IOLBF, 
1226                                 RPC_CHAN_BUF_SIZE);
1227                 }
1228         }
1229 }
1230
1231 /**
1232  * cache_set_fds - prepare cache file descriptors for one iteration of the service loop
1233  * @fdset: pointer to fd_set to prepare
1234  */
1235 void cache_set_fds(fd_set *fdset)
1236 {
1237         int i;
1238         for (i=0; cachelist[i].cache_name; i++) {
1239                 if (cachelist[i].f)
1240                         FD_SET(fileno(cachelist[i].f), fdset);
1241         }
1242 }
1243
1244 /**
1245  * cache_process_req - process any active cache file descriptors during service loop iteration
1246  * @fdset: pointer to fd_set to examine for activity
1247  */
1248 int cache_process_req(fd_set *readfds) 
1249 {
1250         int i;
1251         int cnt = 0;
1252         for (i=0; cachelist[i].cache_name; i++) {
1253                 if (cachelist[i].f != NULL &&
1254                     FD_ISSET(fileno(cachelist[i].f), readfds)) {
1255                         cnt++;
1256                         cachelist[i].cache_handle(cachelist[i].f);
1257                         FD_CLR(fileno(cachelist[i].f), readfds);
1258                 }
1259         }
1260         return cnt;
1261 }
1262
1263
1264 /*
1265  * Give IP->domain and domain+path->options to kernel
1266  * % echo nfsd $IP  $[now+DEFAULT_TTL] $domain > /proc/net/rpc/auth.unix.ip/channel
1267  * % echo $domain $path $[now+DEFAULT_TTL] $options $anonuid $anongid $fsid > /proc/net/rpc/nfsd.export/channel
1268  */
1269
1270 static int cache_export_ent(char *domain, struct exportent *exp, char *path)
1271 {
1272         int err;
1273         FILE *f = fopen("/proc/net/rpc/nfsd.export/channel", "w");
1274         if (!f)
1275                 return -1;
1276
1277         err = dump_to_cache(f, domain, exp->e_path, exp);
1278         if (err) {
1279                 xlog(L_WARNING,
1280                      "Cannot export %s, possibly unsupported filesystem or"
1281                      " fsid= required", exp->e_path);
1282         }
1283
1284         while (err == 0 && (exp->e_flags & NFSEXP_CROSSMOUNT) && path) {
1285                 /* really an 'if', but we can break out of
1286                  * a 'while' more easily */
1287                 /* Look along 'path' for other filesystems
1288                  * and export them with the same options
1289                  */
1290                 struct stat stb;
1291                 size_t l = strlen(exp->e_path);
1292                 __dev_t dev;
1293
1294                 if (strlen(path) <= l || path[l] != '/' ||
1295                     strncmp(exp->e_path, path, l) != 0)
1296                         break;
1297                 if (stat(exp->e_path, &stb) != 0)
1298                         break;
1299                 dev = stb.st_dev;
1300                 while(path[l] == '/') {
1301                         char c;
1302                         /* errors for submount should fail whole filesystem */
1303                         int err2;
1304
1305                         l++;
1306                         while (path[l] != '/' && path[l])
1307                                 l++;
1308                         c = path[l];
1309                         path[l] = 0;
1310                         err2 = lstat(path, &stb);
1311                         path[l] = c;
1312                         if (err2 < 0)
1313                                 break;
1314                         if (stb.st_dev == dev)
1315                                 continue;
1316                         dev = stb.st_dev;
1317                         path[l] = 0;
1318                         dump_to_cache(f, domain, path, exp);
1319                         path[l] = c;
1320                 }
1321                 break;
1322         }
1323
1324         fclose(f);
1325         return err;
1326 }
1327
1328 /**
1329  * cache_export - Inform kernel of a new nfs_export
1330  * @exp: target nfs_export
1331  * @path: NUL-terminated C string containing export path
1332  */
1333 int cache_export(nfs_export *exp, char *path)
1334 {
1335         char buf[INET6_ADDRSTRLEN];
1336         int err;
1337         FILE *f;
1338
1339         f = fopen("/proc/net/rpc/auth.unix.ip/channel", "w");
1340         if (!f)
1341                 return -1;
1342
1343
1344         qword_print(f, "nfsd");
1345         qword_print(f,
1346                 host_ntop(get_addrlist(exp->m_client, 0), buf, sizeof(buf)));
1347         qword_printtimefrom(f, exp->m_export.e_ttl);
1348         qword_print(f, exp->m_client->m_hostname);
1349         err = qword_eol(f);
1350         
1351         fclose(f);
1352
1353         err = cache_export_ent(exp->m_client->m_hostname, &exp->m_export, path)
1354                 || err;
1355         return err;
1356 }
1357
1358 /**
1359  * cache_get_filehandle - given an nfs_export, get its root filehandle
1360  * @exp: target nfs_export
1361  * @len: length of requested file handle
1362  * @p: NUL-terminated C string containing export path
1363  *
1364  * Returns pointer to NFS file handle of root directory of export
1365  *
1366  * { 
1367  *   echo $domain $path $length 
1368  *   read filehandle <&0
1369  * } <> /proc/fs/nfsd/filehandle
1370  */
1371 struct nfs_fh_len *
1372 cache_get_filehandle(nfs_export *exp, int len, char *p)
1373 {
1374         FILE *f = fopen("/proc/fs/nfsd/filehandle", "r+");
1375         char buf[200];
1376         char *bp = buf;
1377         int failed;
1378         static struct nfs_fh_len fh;
1379
1380         if (!f)
1381                 f = fopen("/proc/fs/nfs/filehandle", "r+");
1382         if (!f)
1383                 return NULL;
1384
1385         qword_print(f, exp->m_client->m_hostname);
1386         qword_print(f, p);
1387         qword_printint(f, len); 
1388         failed = qword_eol(f);
1389         
1390         if (!failed)
1391                 failed = (fgets(buf, sizeof(buf), f) == NULL);
1392         fclose(f);
1393         if (failed)
1394                 return NULL;
1395         memset(fh.fh_handle, 0, sizeof(fh.fh_handle));
1396         fh.fh_size = qword_get(&bp, (char *)fh.fh_handle, NFS3_FHSIZE);
1397         return &fh;
1398 }