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