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