]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mountd/cache.c
mountd: gather fsid information into one struct
[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 static void nfsd_fh(FILE *f)
368 {
369         /* request are:
370          *  domain fsidtype fsid
371          * interpret fsid, find export point and options, and write:
372          *  domain fsidtype fsid expiry path
373          */
374         char *cp;
375         char *dom;
376         int fsidtype;
377         int fsidlen;
378         unsigned long long inode64;
379         unsigned int dev;
380         char fsid[32];
381         struct parsed_fsid parsed;
382         struct exportent *found = NULL;
383         struct addrinfo *ai = NULL;
384         char *found_path = NULL;
385         nfs_export *exp;
386         int i;
387         int dev_missing = 0;
388
389         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
390                 return;
391
392         xlog(D_CALL, "nfsd_fh: inbuf '%s'", lbuf);
393
394         cp = lbuf;
395         
396         dom = malloc(strlen(cp));
397         if (dom == NULL)
398                 return;
399         if (qword_get(&cp, dom, strlen(cp)) <= 0)
400                 goto out;
401         if (qword_get_int(&cp, &fsidtype) != 0)
402                 goto out;
403         if (fsidtype < 0 || fsidtype > 7)
404                 goto out; /* unknown type */
405         if ((fsidlen = qword_get(&cp, fsid, 32)) <= 0)
406                 goto out;
407         switch(fsidtype) {
408         case FSID_DEV: /* 4 bytes: 2 major, 2 minor, 4 inode */
409                 if (fsidlen != 8)
410                         goto out;
411                 memcpy(&dev, fsid, 4);
412                 memcpy(&parsed.inode, fsid+4, 4);
413                 parsed.major = ntohl(dev)>>16;
414                 parsed.minor = ntohl(dev) & 0xFFFF;
415                 break;
416
417         case FSID_NUM: /* 4 bytes - fsid */
418                 if (fsidlen != 4)
419                         goto out;
420                 memcpy(&parsed.fsidnum, fsid, 4);
421                 break;
422
423         case FSID_MAJOR_MINOR: /* 12 bytes: 4 major, 4 minor, 4 inode 
424                  * This format is never actually used but was
425                  * an historical accident
426                  */
427                 if (fsidlen != 12)
428                         goto out;
429                 memcpy(&dev, fsid, 4);
430                 parsed.major = ntohl(dev);
431                 memcpy(&dev, fsid+4, 4);
432                 parsed.minor = ntohl(dev);
433                 memcpy(&parsed.inode, fsid+8, 4);
434                 break;
435
436         case FSID_ENCODE_DEV: /* 8 bytes: 4 byte packed device number, 4 inode */
437                 /* This is *host* endian, not net-byte-order, because
438                  * no-one outside this host has any business interpreting it
439                  */
440                 if (fsidlen != 8)
441                         goto out;
442                 memcpy(&dev, fsid, 4);
443                 memcpy(&parsed.inode, fsid+4, 4);
444                 parsed.major = (dev & 0xfff00) >> 8;
445                 parsed.minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
446                 break;
447
448         case FSID_UUID4_INUM: /* 4 byte inode number and 4 byte uuid */
449                 if (fsidlen != 8)
450                         goto out;
451                 memcpy(&parsed.inode, fsid, 4);
452                 parsed.uuidlen = 4;
453                 parsed.fhuuid = fsid+4;
454                 break;
455         case FSID_UUID8: /* 8 byte uuid */
456                 if (fsidlen != 8)
457                         goto out;
458                 parsed.uuidlen = 8;
459                 parsed.fhuuid = fsid;
460                 break;
461         case FSID_UUID16: /* 16 byte uuid */
462                 if (fsidlen != 16)
463                         goto out;
464                 parsed.uuidlen = 16;
465                 parsed.fhuuid = fsid;
466                 break;
467         case FSID_UUID16_INUM: /* 8 byte inode number and 16 byte uuid */
468                 if (fsidlen != 24)
469                         goto out;
470                 memcpy(&inode64, fsid, 8);
471                 parsed.inode = inode64;
472                 parsed.uuidlen = 16;
473                 parsed.fhuuid = fsid+8;
474                 break;
475         }
476
477         auth_reload();
478
479         /* Now determine export point for this fsid/domain */
480         for (i=0 ; i < MCL_MAXTYPES; i++) {
481                 nfs_export *next_exp;
482                 for (exp = exportlist[i].p_head; exp; exp = next_exp) {
483                         struct stat stb;
484                         char u[16];
485                         char *path;
486                         int type;
487
488                         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT) {
489                                 static nfs_export *prev = NULL;
490                                 static void *mnt = NULL;
491                                 
492                                 if (prev == exp) {
493                                         /* try a submount */
494                                         path = next_mnt(&mnt, exp->m_export.e_path);
495                                         if (!path) {
496                                                 next_exp = exp->m_next;
497                                                 prev = NULL;
498                                                 continue;
499                                         }
500                                         next_exp = exp;
501                                 } else {
502                                         prev = exp;
503                                         mnt = NULL;
504                                         path = exp->m_export.e_path;
505                                         next_exp = exp;
506                                 }
507                         } else {
508                                 path = exp->m_export.e_path;
509                                 next_exp = exp->m_next;
510                         }
511
512                         if (!use_ipaddr && !client_member(dom, exp->m_client->m_hostname))
513                                 continue;
514                         if (exp->m_export.e_mountpoint &&
515                             !is_mountpoint(exp->m_export.e_mountpoint[0]?
516                                            exp->m_export.e_mountpoint:
517                                            exp->m_export.e_path))
518                                 dev_missing ++;
519                         if (stat(path, &stb) != 0)
520                                 continue;
521                         if (!S_ISDIR(stb.st_mode) && !S_ISREG(stb.st_mode)) {
522                                 continue;
523                         }
524                         switch(fsidtype){
525                         case FSID_DEV:
526                         case FSID_MAJOR_MINOR:
527                         case FSID_ENCODE_DEV:
528                                 if (stb.st_ino != parsed.inode)
529                                         continue;
530                                 if (parsed.major != major(stb.st_dev) ||
531                                     parsed.minor != minor(stb.st_dev))
532                                         continue;
533                                 break;
534                         case FSID_NUM:
535                                 if (((exp->m_export.e_flags & NFSEXP_FSID) == 0 ||
536                                      exp->m_export.e_fsid != parsed.fsidnum))
537                                         continue;
538                                 break;
539                         case FSID_UUID4_INUM:
540                         case FSID_UUID16_INUM:
541                                 if (stb.st_ino != parsed.inode)
542                                         continue;
543                                 goto check_uuid;
544                         case FSID_UUID8:
545                         case FSID_UUID16:
546                                 if (!is_mountpoint(path))
547                                         continue;
548                         check_uuid:
549                                 if (exp->m_export.e_uuid)
550                                         get_uuid(exp->m_export.e_uuid,
551                                                  parsed.uuidlen, u);
552                                 else
553                                         for (type = 0;
554                                              uuid_by_path(path, type, parsed.uuidlen, u);
555                                              type++)
556                                                 if (memcmp(u, parsed.fhuuid, parsed.uuidlen) == 0)
557                                                         break;
558
559                                 if (memcmp(u, parsed.fhuuid, parsed.uuidlen) != 0)
560                                         continue;
561                                 break;
562                         }
563                         if (use_ipaddr) {
564                                 if (ai == NULL) {
565                                         struct addrinfo *tmp;
566                                         tmp = host_pton(dom);
567                                         if (tmp == NULL)
568                                                 goto out;
569                                         ai = client_resolve(tmp->ai_addr);
570                                         freeaddrinfo(tmp);
571                                 }
572                                 if (!client_check(exp->m_client, ai))
573                                         continue;
574                         }
575                         if (!found || subexport(&exp->m_export, found)) {
576                                 found = &exp->m_export;
577                                 free(found_path);
578                                 found_path = strdup(path);
579                                 if (found_path == NULL)
580                                         goto out;
581                         } else if (strcmp(found->e_path, exp->m_export.e_path)
582                                    && !subexport(found, &exp->m_export))
583                         {
584                                 xlog(L_WARNING, "%s and %s have same filehandle for %s, using first",
585                                      found_path, path, dom);
586                         }
587                 }
588         }
589         if (found && 
590             found->e_mountpoint &&
591             !is_mountpoint(found->e_mountpoint[0]?
592                            found->e_mountpoint:
593                            found->e_path)) {
594                 /* Cannot export this yet 
595                  * should log a warning, but need to rate limit
596                    xlog(L_WARNING, "%s not exported as %d not a mountpoint",
597                    found->e_path, found->e_mountpoint);
598                  */
599                 /* FIXME we need to make sure we re-visit this later */
600                 goto out;
601         }
602         if (!found && dev_missing) {
603                 /* The missing dev could be what we want, so just be
604                  * quite rather than returning stale yet
605                  */
606                 goto out;
607         }
608
609         if (found)
610                 if (cache_export_ent(dom, found, found_path) < 0)
611                         found = 0;
612
613         qword_print(f, dom);
614         qword_printint(f, fsidtype);
615         qword_printhex(f, fsid, fsidlen);
616         /* The fsid -> path lookup can be quite expensive as it
617          * potentially stats and reads lots of devices, and some of those
618          * might have spun-down.  The Answer is not likely to
619          * change underneath us, and an 'exportfs -f' can always
620          * remove this from the kernel, so use a really log
621          * timeout.  Maybe this should be configurable on the command
622          * line.
623          */
624         qword_printint(f, 0x7fffffff);
625         if (found)
626                 qword_print(f, found_path);
627         qword_eol(f);
628  out:
629         if (found_path)
630                 free(found_path);
631         freeaddrinfo(ai);
632         free(dom);
633         xlog(D_CALL, "nfsd_fh: found %p path %s", found, found ? found->e_path : NULL);
634         return;         
635 }
636
637 static void write_fsloc(FILE *f, struct exportent *ep)
638 {
639         struct servers *servers;
640
641         if (ep->e_fslocmethod == FSLOC_NONE)
642                 return;
643
644         servers = replicas_lookup(ep->e_fslocmethod, ep->e_fslocdata);
645         if (!servers)
646                 return;
647         qword_print(f, "fsloc");
648         qword_printint(f, servers->h_num);
649         if (servers->h_num >= 0) {
650                 int i;
651                 for (i=0; i<servers->h_num; i++) {
652                         qword_print(f, servers->h_mp[i]->h_host);
653                         qword_print(f, servers->h_mp[i]->h_path);
654                 }
655         }
656         qword_printint(f, servers->h_referral);
657         release_replicas(servers);
658 }
659
660 static void write_secinfo(FILE *f, struct exportent *ep, int flag_mask)
661 {
662         struct sec_entry *p;
663
664         for (p = ep->e_secinfo; p->flav; p++)
665                 ; /* Do nothing */
666         if (p == ep->e_secinfo) {
667                 /* There was no sec= option */
668                 return;
669         }
670         qword_print(f, "secinfo");
671         qword_printint(f, p - ep->e_secinfo);
672         for (p = ep->e_secinfo; p->flav; p++) {
673                 qword_printint(f, p->flav->fnum);
674                 qword_printint(f, p->flags & flag_mask);
675         }
676
677 }
678
679 static int dump_to_cache(FILE *f, char *domain, char *path, struct exportent *exp)
680 {
681         qword_print(f, domain);
682         qword_print(f, path);
683         if (exp) {
684                 int different_fs = strcmp(path, exp->e_path) != 0;
685                 int flag_mask = different_fs ? ~NFSEXP_FSID : ~0;
686
687                 qword_printuint(f, time(0) + exp->e_ttl);
688                 qword_printint(f, exp->e_flags & flag_mask);
689                 qword_printint(f, exp->e_anonuid);
690                 qword_printint(f, exp->e_anongid);
691                 qword_printint(f, exp->e_fsid);
692                 write_fsloc(f, exp);
693                 write_secinfo(f, exp, flag_mask);
694                 if (exp->e_uuid == NULL || different_fs) {
695                         char u[16];
696                         if (uuid_by_path(path, 0, 16, u)) {
697                                 qword_print(f, "uuid");
698                                 qword_printhex(f, u, 16);
699                         }
700                 } else {
701                         char u[16];
702                         get_uuid(exp->e_uuid, 16, u);
703                         qword_print(f, "uuid");
704                         qword_printhex(f, u, 16);
705                 }
706         } else
707                 qword_printuint(f, time(0) + DEFAULT_TTL);
708         return qword_eol(f);
709 }
710
711 static int is_subdirectory(char *child, char *parent)
712 {
713         int l = strlen(parent);
714
715         return strcmp(child, parent) == 0
716                 || (strncmp(child, parent, l) == 0 && child[l] == '/');
717 }
718
719 static int path_matches(nfs_export *exp, char *path)
720 {
721         if (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)
722                 return is_subdirectory(path, exp->m_export.e_path);
723         return strcmp(path, exp->m_export.e_path) == 0;
724 }
725
726 static int
727 client_matches(nfs_export *exp, char *dom, struct addrinfo *ai)
728 {
729         if (use_ipaddr)
730                 return client_check(exp->m_client, ai);
731         return client_member(dom, exp->m_client->m_hostname);
732 }
733
734 static int
735 export_matches(nfs_export *exp, char *dom, char *path, struct addrinfo *ai)
736 {
737         return path_matches(exp, path) && client_matches(exp, dom, ai);
738 }
739
740 static nfs_export *
741 lookup_export(char *dom, char *path, struct addrinfo *ai)
742 {
743         nfs_export *exp;
744         nfs_export *found = NULL;
745         int found_type = 0;
746         int i;
747
748         for (i=0 ; i < MCL_MAXTYPES; i++) {
749                 for (exp = exportlist[i].p_head; exp; exp = exp->m_next) {
750                         if (!export_matches(exp, dom, path, ai))
751                                 continue;
752                         if (!found) {
753                                 found = exp;
754                                 found_type = i;
755                                 continue;
756                         }
757
758                         /* Always prefer non-V4ROOT mounts */
759                         if (found->m_export.e_flags & NFSEXP_V4ROOT)
760                                 continue;
761
762                         /* If one is a CROSSMOUNT, then prefer the longest path */
763                         if (((found->m_export.e_flags & NFSEXP_CROSSMOUNT) ||
764                              (exp->m_export.e_flags & NFSEXP_CROSSMOUNT)) &&
765                             strlen(found->m_export.e_path) !=
766                             strlen(exp->m_export.e_path)) {
767
768                                 if (strlen(exp->m_export.e_path) >
769                                     strlen(found->m_export.e_path)) {
770                                         found = exp;
771                                         found_type = i;
772                                 }
773                                 continue;
774
775                         } else if (found_type == i && found->m_warned == 0) {
776                                 xlog(L_WARNING, "%s exported to both %s and %s, "
777                                      "arbitrarily choosing options from first",
778                                      path, found->m_client->m_hostname, exp->m_client->m_hostname,
779                                      dom);
780                                 found->m_warned = 1;
781                         }
782                 }
783         }
784         return found;
785 }
786
787 static void nfsd_export(FILE *f)
788 {
789         /* requests are:
790          *  domain path
791          * determine export options and return:
792          *  domain path expiry flags anonuid anongid fsid
793          */
794
795         char *cp;
796         char *dom, *path;
797         nfs_export *found = NULL;
798         struct addrinfo *ai = NULL;
799
800         if (readline(fileno(f), &lbuf, &lbuflen) != 1)
801                 return;
802
803         xlog(D_CALL, "nfsd_export: inbuf '%s'", lbuf);
804
805         cp = lbuf;
806         dom = malloc(strlen(cp));
807         path = malloc(strlen(cp));
808
809         if (!dom || !path)
810                 goto out;
811
812         if (qword_get(&cp, dom, strlen(lbuf)) <= 0)
813                 goto out;
814         if (qword_get(&cp, path, strlen(lbuf)) <= 0)
815                 goto out;
816
817         auth_reload();
818
819         if (use_ipaddr) {
820                 struct addrinfo *tmp;
821                 tmp = host_pton(dom);
822                 if (tmp == NULL)
823                         goto out;
824                 ai = client_resolve(tmp->ai_addr);
825                 freeaddrinfo(tmp);
826                         goto out;
827         }
828
829         found = lookup_export(dom, path, ai);
830
831         if (found) {
832                 if (dump_to_cache(f, dom, path, &found->m_export) < 0) {
833                         xlog(L_WARNING,
834                              "Cannot export %s, possibly unsupported filesystem"
835                              " or fsid= required", path);
836                         dump_to_cache(f, dom, path, NULL);
837                 }
838         } else {
839                 dump_to_cache(f, dom, path, NULL);
840         }
841  out:
842         xlog(D_CALL, "nfsd_export: found %p path %s", found, path ? path : NULL);
843         if (dom) free(dom);
844         if (path) free(path);
845         freeaddrinfo(ai);
846 }
847
848
849 struct {
850         char *cache_name;
851         void (*cache_handle)(FILE *f);
852         FILE *f;
853         char vbuf[RPC_CHAN_BUF_SIZE];
854 } cachelist[] = {
855         { "auth.unix.ip", auth_unix_ip, NULL, ""},
856         { "auth.unix.gid", auth_unix_gid, NULL, ""},
857         { "nfsd.export", nfsd_export, NULL, ""},
858         { "nfsd.fh", nfsd_fh, NULL, ""},
859         { NULL, NULL, NULL, ""}
860 };
861
862 extern int manage_gids;
863
864 /**
865  * cache_open - prepare communications channels with kernel RPC caches
866  *
867  */
868 void cache_open(void) 
869 {
870         int i;
871         for (i=0; cachelist[i].cache_name; i++ ) {
872                 char path[100];
873                 if (!manage_gids && cachelist[i].cache_handle == auth_unix_gid)
874                         continue;
875                 sprintf(path, "/proc/net/rpc/%s/channel", cachelist[i].cache_name);
876                 cachelist[i].f = fopen(path, "r+");
877                 if (cachelist[i].f != NULL) {
878                         setvbuf(cachelist[i].f, cachelist[i].vbuf, _IOLBF, 
879                                 RPC_CHAN_BUF_SIZE);
880                 }
881         }
882 }
883
884 /**
885  * cache_set_fds - prepare cache file descriptors for one iteration of the service loop
886  * @fdset: pointer to fd_set to prepare
887  */
888 void cache_set_fds(fd_set *fdset)
889 {
890         int i;
891         for (i=0; cachelist[i].cache_name; i++) {
892                 if (cachelist[i].f)
893                         FD_SET(fileno(cachelist[i].f), fdset);
894         }
895 }
896
897 /**
898  * cache_process_req - process any active cache file descriptors during service loop iteration
899  * @fdset: pointer to fd_set to examine for activity
900  */
901 int cache_process_req(fd_set *readfds) 
902 {
903         int i;
904         int cnt = 0;
905         for (i=0; cachelist[i].cache_name; i++) {
906                 if (cachelist[i].f != NULL &&
907                     FD_ISSET(fileno(cachelist[i].f), readfds)) {
908                         cnt++;
909                         cachelist[i].cache_handle(cachelist[i].f);
910                         FD_CLR(fileno(cachelist[i].f), readfds);
911                 }
912         }
913         return cnt;
914 }
915
916
917 /*
918  * Give IP->domain and domain+path->options to kernel
919  * % echo nfsd $IP  $[now+DEFAULT_TTL] $domain > /proc/net/rpc/auth.unix.ip/channel
920  * % echo $domain $path $[now+DEFAULT_TTL] $options $anonuid $anongid $fsid > /proc/net/rpc/nfsd.export/channel
921  */
922
923 static int cache_export_ent(char *domain, struct exportent *exp, char *path)
924 {
925         int err;
926         FILE *f = fopen("/proc/net/rpc/nfsd.export/channel", "w");
927         if (!f)
928                 return -1;
929
930         err = dump_to_cache(f, domain, exp->e_path, exp);
931         if (err) {
932                 xlog(L_WARNING,
933                      "Cannot export %s, possibly unsupported filesystem or"
934                      " fsid= required", exp->e_path);
935         }
936
937         while (err == 0 && (exp->e_flags & NFSEXP_CROSSMOUNT) && path) {
938                 /* really an 'if', but we can break out of
939                  * a 'while' more easily */
940                 /* Look along 'path' for other filesystems
941                  * and export them with the same options
942                  */
943                 struct stat stb;
944                 size_t l = strlen(exp->e_path);
945                 __dev_t dev;
946
947                 if (strlen(path) <= l || path[l] != '/' ||
948                     strncmp(exp->e_path, path, l) != 0)
949                         break;
950                 if (stat(exp->e_path, &stb) != 0)
951                         break;
952                 dev = stb.st_dev;
953                 while(path[l] == '/') {
954                         char c;
955                         /* errors for submount should fail whole filesystem */
956                         int err2;
957
958                         l++;
959                         while (path[l] != '/' && path[l])
960                                 l++;
961                         c = path[l];
962                         path[l] = 0;
963                         err2 = lstat(path, &stb);
964                         path[l] = c;
965                         if (err2 < 0)
966                                 break;
967                         if (stb.st_dev == dev)
968                                 continue;
969                         dev = stb.st_dev;
970                         path[l] = 0;
971                         dump_to_cache(f, domain, path, exp);
972                         path[l] = c;
973                 }
974                 break;
975         }
976
977         fclose(f);
978         return err;
979 }
980
981 /**
982  * cache_export - Inform kernel of a new nfs_export
983  * @exp: target nfs_export
984  * @path: NUL-terminated C string containing export path
985  */
986 int cache_export(nfs_export *exp, char *path)
987 {
988         char buf[INET6_ADDRSTRLEN];
989         int err;
990         FILE *f;
991
992         f = fopen("/proc/net/rpc/auth.unix.ip/channel", "w");
993         if (!f)
994                 return -1;
995
996
997         qword_print(f, "nfsd");
998         qword_print(f,
999                 host_ntop(get_addrlist(exp->m_client, 0), buf, sizeof(buf)));
1000         qword_printuint(f, time(0) + exp->m_export.e_ttl);
1001         qword_print(f, exp->m_client->m_hostname);
1002         err = qword_eol(f);
1003         
1004         fclose(f);
1005
1006         err = cache_export_ent(exp->m_client->m_hostname, &exp->m_export, path)
1007                 || err;
1008         return err;
1009 }
1010
1011 /**
1012  * cache_get_filehandle - given an nfs_export, get its root filehandle
1013  * @exp: target nfs_export
1014  * @len: length of requested file handle
1015  * @p: NUL-terminated C string containing export path
1016  *
1017  * Returns pointer to NFS file handle of root directory of export
1018  *
1019  * { 
1020  *   echo $domain $path $length 
1021  *   read filehandle <&0
1022  * } <> /proc/fs/nfsd/filehandle
1023  */
1024 struct nfs_fh_len *
1025 cache_get_filehandle(nfs_export *exp, int len, char *p)
1026 {
1027         FILE *f = fopen("/proc/fs/nfsd/filehandle", "r+");
1028         char buf[200];
1029         char *bp = buf;
1030         int failed;
1031         static struct nfs_fh_len fh;
1032
1033         if (!f)
1034                 f = fopen("/proc/fs/nfs/filehandle", "r+");
1035         if (!f)
1036                 return NULL;
1037
1038         qword_print(f, exp->m_client->m_hostname);
1039         qword_print(f, p);
1040         qword_printint(f, len); 
1041         failed = qword_eol(f);
1042         
1043         if (!failed)
1044                 failed = (fgets(buf, sizeof(buf), f) == NULL);
1045         fclose(f);
1046         if (failed)
1047                 return NULL;
1048         memset(fh.fh_handle, 0, sizeof(fh.fh_handle));
1049         fh.fh_size = qword_get(&bp, (char *)fh.fh_handle, NFS3_FHSIZE);
1050         return &fh;
1051 }