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