Merge branch 'sid'
[nfs-utils.git] / utils / exportfs / exportfs.c
1 /*
2  * utils/exportfs/exportfs.c
3  *
4  * Export file systems to knfsd
5  *
6  * Copyright (C) 1995, 1996, 1997 Olaf Kirch <okir@monad.swb.de>
7  *
8  * Extensive changes, 1999, Neil Brown <neilb@cse.unsw.edu.au>
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/vfs.h>
18 #include <sys/stat.h>
19 #include <sys/file.h>
20 #include <unistd.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdarg.h>
25 #include <getopt.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <errno.h>
29 #include <dirent.h>
30
31 #include "sockaddr.h"
32 #include "misc.h"
33 #include "nfslib.h"
34 #include "exportfs.h"
35 #include "xlog.h"
36
37 static void     export_all(int verbose);
38 static void     exportfs(char *arg, char *options, int verbose);
39 static void     unexportfs(char *arg, int verbose);
40 static void     exports_update(int verbose);
41 static void     dump(int verbose);
42 static void     error(nfs_export *exp, int err);
43 static void     usage(const char *progname, int n);
44 static void     validate_export(nfs_export *exp);
45 static int      matchhostname(const char *hostname1, const char *hostname2);
46 static void     export_d_read(const char *dname);
47 static void grab_lockfile(void);
48 static void release_lockfile(void);
49
50 static const char *lockfile = EXP_LOCKFILE;
51 static int _lockfd = -1;
52
53 /*
54  * If we aren't careful, changes made by exportfs can be lost
55  * when multiple exports process run at once:
56  *
57  *      exportfs process 1      exportfs process 2
58  *      ------------------------------------------
59  *      reads etab version A    reads etab version A
60  *      adds new export B       adds new export C
61  *      writes A+B              writes A+C
62  *
63  * The locking in support/export/xtab.c will prevent mountd from
64  * seeing a partially written version of etab, and will prevent 
65  * the two writers above from writing simultaneously and
66  * corrupting etab, but to prevent problems like the above we
67  * need these additional lockfile() routines.
68  */
69 static void 
70 grab_lockfile()
71 {
72         _lockfd = open(lockfile, O_CREAT|O_RDWR, 0666);
73         if (_lockfd != -1) 
74                 lockf(_lockfd, F_LOCK, 0);
75 }
76 static void 
77 release_lockfile()
78 {
79         if (_lockfd != -1)
80                 lockf(_lockfd, F_ULOCK, 0);
81 }
82
83 int
84 main(int argc, char **argv)
85 {
86         char    *options = NULL;
87         char    *progname = NULL;
88         int     f_export = 1;
89         int     f_all = 0;
90         int     f_verbose = 0;
91         int     f_reexport = 0;
92         int     f_ignore = 0;
93         int     i, c;
94         int     new_cache = 0;
95         int     force_flush = 0;
96
97         if ((progname = strrchr(argv[0], '/')) != NULL)
98                 progname++;
99         else
100                 progname = argv[0];
101
102         xlog_open(progname);
103         xlog_stderr(1);
104         xlog_syslog(0);
105
106         export_errno = 0;
107
108         while ((c = getopt(argc, argv, "afhio:ruv")) != EOF) {
109                 switch(c) {
110                 case 'a':
111                         f_all = 1;
112                         break;
113                 case 'f':
114                         force_flush = 1;
115                         break;
116                 case 'h':
117                         usage(progname, 0);
118                         break;
119                 case 'i':
120                         f_ignore = 1;
121                         break;
122                 case 'o':
123                         options = optarg;
124                         break;
125                 case 'r':
126                         f_reexport = 1;
127                         f_all = 1;
128                         break;
129                 case 'u':
130                         f_export = 0;
131                         break;
132                 case 'v':
133                         f_verbose = 1;
134                         break;
135                 default:
136                         usage(progname, 1);
137                         break;
138                 }
139         }
140
141         if (optind != argc && f_all) {
142                 xlog(L_ERROR, "extra arguments are not permitted with -a or -r");
143                 return 1;
144         }
145         if (f_ignore && (f_all || ! f_export)) {
146                 xlog(L_ERROR, "-i not meaningful with -a, -r or -u");
147                 return 1;
148         }
149         if (f_reexport && ! f_export) {
150                 xlog(L_ERROR, "-r and -u are incompatible");
151                 return 1;
152         }
153         new_cache = check_new_cache();
154         if (optind == argc && ! f_all) {
155                 if (force_flush) {
156                         if (new_cache)
157                                 cache_flush(1);
158                         else {
159                                 xlog(L_ERROR, "-f is available only "
160                                         "with new cache controls. "
161                                         "Mount /proc/fs/nfsd first");
162                                 return 1;
163                         }
164                         return 0;
165                 } else {
166                         xtab_export_read();
167                         dump(f_verbose);
168                         return 0;
169                 }
170         }
171
172         /*
173          * Serialize things as best we can
174          */
175         grab_lockfile();
176         atexit(release_lockfile);
177
178         if (f_export && ! f_ignore) {
179                 export_read(_PATH_EXPORTS);
180                 export_d_read(_PATH_EXPORTS_D);
181         }
182         if (f_export) {
183                 if (f_all)
184                         export_all(f_verbose);
185                 else
186                         for (i = optind; i < argc ; i++)
187                                 exportfs(argv[i], options, f_verbose);
188         }
189         /* If we are unexporting everything, then
190          * don't care about what should be exported, as that
191          * may require DNS lookups..
192          */
193         if (! ( !f_export && f_all)) {
194                 /* note: xtab_*_read does not update entries if they already exist,
195                  * so this will not lose new options
196                  */
197                 if (!f_reexport)
198                         xtab_export_read();
199                 if (!f_export)
200                         for (i = optind ; i < argc ; i++)
201                                 unexportfs(argv[i], f_verbose);
202                 if (!new_cache)
203                         rmtab_read();
204         }
205         if (!new_cache) {
206                 xtab_mount_read();
207                 exports_update(f_verbose);
208         }
209         xtab_export_write();
210         if (new_cache)
211                 cache_flush(force_flush);
212         if (!new_cache)
213                 xtab_mount_write();
214
215         return export_errno;
216 }
217
218 static void
219 exports_update_one(nfs_export *exp, int verbose)
220 {
221                 /* check mountpoint option */
222         if (exp->m_mayexport &&
223             exp->m_export.e_mountpoint &&
224             !is_mountpoint(exp->m_export.e_mountpoint[0]?
225                            exp->m_export.e_mountpoint:
226                            exp->m_export.e_path)) {
227                 printf("%s not exported as %s not a mountpoint.\n",
228                        exp->m_export.e_path, exp->m_export.e_mountpoint);
229                 exp->m_mayexport = 0;
230         }
231         if (exp->m_mayexport && ((exp->m_exported<1) || exp->m_changed)) {
232                 if (verbose)
233                         printf("%sexporting %s:%s to kernel\n",
234                                exp->m_exported ?"re":"",
235                                exp->m_client->m_hostname,
236                                exp->m_export.e_path);
237                 if (!export_export(exp))
238                         error(exp, errno);
239         }
240         if (exp->m_exported && ! exp->m_mayexport) {
241                 if (verbose)
242                         printf("unexporting %s:%s from kernel\n",
243                                exp->m_client->m_hostname,
244                                exp->m_export.e_path);
245                 if (!export_unexport(exp))
246                         error(exp, errno);
247         }
248 }
249
250
251 /* we synchronise intention with reality.
252  * entries with m_mayexport get exported
253  * entries with m_exported but not m_mayexport get unexported
254  * looking at m_client->m_type == MCL_FQDN and m_client->m_type == MCL_GSS only
255  */
256 static void
257 exports_update(int verbose)
258 {
259         nfs_export      *exp;
260
261         for (exp = exportlist[MCL_FQDN].p_head; exp; exp=exp->m_next) {
262                 exports_update_one(exp, verbose);
263         }
264         for (exp = exportlist[MCL_GSS].p_head; exp; exp=exp->m_next) {
265                 exports_update_one(exp, verbose);
266         }
267 }
268                         
269 /*
270  * export_all finds all entries and
271  *    marks them xtabent and mayexport so that they get exported
272  */
273 static void
274 export_all(int verbose)
275 {
276         nfs_export      *exp;
277         int             i;
278
279         for (i = 0; i < MCL_MAXTYPES; i++) {
280                 for (exp = exportlist[i].p_head; exp; exp = exp->m_next) {
281                         if (verbose)
282                                 printf("exporting %s:%s\n",
283                                        exp->m_client->m_hostname, 
284                                        exp->m_export.e_path);
285                         exp->m_xtabent = 1;
286                         exp->m_mayexport = 1;
287                         exp->m_changed = 1;
288                         exp->m_warned = 0;
289                         validate_export(exp);
290                 }
291         }
292 }
293
294
295 static void
296 exportfs(char *arg, char *options, int verbose)
297 {
298         struct exportent *eep;
299         nfs_export      *exp = NULL;
300         struct addrinfo *ai = NULL;
301         char            *path;
302         char            *hname = arg;
303         int             htype;
304
305         if ((path = strchr(arg, ':')) != NULL)
306                 *path++ = '\0';
307
308         if (!path || *path != '/') {
309                 xlog(L_ERROR, "Invalid exporting option: %s", arg);
310                 return;
311         }
312
313         if ((htype = client_gettype(hname)) == MCL_FQDN) {
314                 ai = host_addrinfo(hname);
315                 if (ai != NULL) {
316                         exp = export_find(ai, path);
317                         hname = ai->ai_canonname;
318                 }
319         } else
320                 exp = export_lookup(hname, path, 0);
321
322         if (!exp) {
323                 if (!(eep = mkexportent(hname, path, options)) ||
324                     !(exp = export_create(eep, 0)))
325                         goto out;
326         } else if (!updateexportent(&exp->m_export, options))
327                 goto out;
328
329         if (verbose)
330                 printf("exporting %s:%s\n", exp->m_client->m_hostname, 
331                         exp->m_export.e_path);
332         exp->m_xtabent = 1;
333         exp->m_mayexport = 1;
334         exp->m_changed = 1;
335         exp->m_warned = 0;
336         validate_export(exp);
337
338 out:
339         freeaddrinfo(ai);
340 }
341
342 static void
343 unexportfs(char *arg, int verbose)
344 {
345         nfs_export      *exp;
346         struct addrinfo *ai = NULL;
347         char            *path;
348         char            *hname = arg;
349         int             htype;
350
351         if ((path = strchr(arg, ':')) != NULL)
352                 *path++ = '\0';
353
354         if (!path || *path != '/') {
355                 xlog(L_ERROR, "Invalid unexporting option: %s", arg);
356                 return;
357         }
358
359         if ((htype = client_gettype(hname)) == MCL_FQDN) {
360                 ai = host_addrinfo(hname);
361                 if (ai)
362                         hname = ai->ai_canonname;
363         }
364
365         for (exp = exportlist[htype].p_head; exp; exp = exp->m_next) {
366                 if (path && strcmp(path, exp->m_export.e_path))
367                         continue;
368                 if (htype != exp->m_client->m_type)
369                         continue;
370                 if (htype == MCL_FQDN
371                     && !matchhostname(exp->m_export.e_hostname,
372                                           hname))
373                         continue;
374                 if (htype != MCL_FQDN
375                     && strcasecmp(exp->m_export.e_hostname, hname))
376                         continue;
377                 if (verbose) {
378 #if 0
379                         if (exp->m_exported) {
380                                 printf("unexporting %s:%s from kernel\n",
381                                        exp->m_client->m_hostname,
382                                        exp->m_export.e_path);
383                         }
384                         else
385 #endif
386                                 printf("unexporting %s:%s\n",
387                                         exp->m_client->m_hostname, 
388                                         exp->m_export.e_path);
389                 }
390 #if 0
391                 if (exp->m_exported && !export_unexport(exp))
392                         error(exp, errno);
393 #endif
394                 exp->m_xtabent = 0;
395                 exp->m_mayexport = 0;
396         }
397
398         freeaddrinfo(ai);
399 }
400
401 static int can_test(void)
402 {
403         int fd;
404         int n;
405         char *setup = "nfsd 0.0.0.0 2147483647 -test-client-\n";
406         fd = open("/proc/net/rpc/auth.unix.ip/channel", O_WRONLY);
407         if ( fd < 0) return 0;
408         n = write(fd, setup, strlen(setup));
409         close(fd);
410         if (n < 0)
411                 return 0;
412         fd = open("/proc/net/rpc/nfsd.export/channel", O_WRONLY);
413         if ( fd < 0) return 0;
414         close(fd);
415         return 1;
416 }
417
418 static int test_export(char *path, int with_fsid)
419 {
420         char buf[1024];
421         int fd, n;
422
423         sprintf(buf, "-test-client- %s 3 %d -1 -1 0\n",
424                 path,
425                 with_fsid ? NFSEXP_FSID : 0);
426         fd = open("/proc/net/rpc/nfsd.export/channel", O_WRONLY);
427         if (fd < 0)
428                 return 0;
429         n = write(fd, buf, strlen(buf));
430         close(fd);
431         if (n < 0)
432                 return 0;
433         return 1;
434 }
435
436 static void
437 validate_export(nfs_export *exp)
438 {
439         /* Check that the given export point is potentially exportable.
440          * We just give warnings here, don't cause anything to fail.
441          * If a path doesn't exist, or is not a dir or file, give an warning
442          * otherwise trial-export to '-test-client-' and check for failure.
443          */
444         struct stat stb;
445         char *path = exp->m_export.e_path;
446         struct statfs64 stf;
447         int fs_has_fsid = 0;
448
449         if (stat(path, &stb) < 0) {
450                 xlog(L_ERROR, "Failed to stat %s: %m", path);
451                 return;
452         }
453         if (!S_ISDIR(stb.st_mode) && !S_ISREG(stb.st_mode)) {
454                 xlog(L_ERROR, "%s is neither a directory nor a file. "
455                         "Remote access will fail", path);
456                 return;
457         }
458         if (!can_test())
459                 return;
460
461         if (!statfs64(path, &stf) &&
462             (stf.f_fsid.__val[0] || stf.f_fsid.__val[1]))
463                 fs_has_fsid = 1;
464
465         if ((exp->m_export.e_flags & NFSEXP_FSID) || exp->m_export.e_uuid ||
466             fs_has_fsid) {
467                 if ( !test_export(path, 1)) {
468                         xlog(L_ERROR, "%s does not support NFS export", path);
469                         return;
470                 }
471         } else if ( ! test_export(path, 0)) {
472                 if (test_export(path, 1))
473                         xlog(L_ERROR, "%s requires fsid= for NFS export", path);
474                 else
475                         xlog(L_ERROR, "%s does not support NFS export", path);
476                 return;
477
478         }
479 }
480
481 static _Bool
482 is_hostname(const char *sp)
483 {
484         if (*sp == '\0' || *sp == '@')
485                 return false;
486
487         for (; *sp != '\0'; sp++) {
488                 if (*sp == '*' || *sp == '?' || *sp == '[' || *sp == '/')
489                         return false;
490                 if (*sp == '\\' && sp[1] != '\0')
491                         sp++;
492         }
493
494         return true;
495 }
496
497 /*
498  * Take care to perform an explicit reverse lookup on presentation
499  * addresses.  Otherwise we don't get a real canonical name or a
500  * complete list of addresses.
501  */
502 static struct addrinfo *
503 address_list(const char *hostname)
504 {
505         struct addrinfo *ai;
506         char *cname;
507
508         ai = host_pton(hostname);
509         if (ai != NULL) {
510                 /* @hostname was a presentation address */
511                 cname = host_canonname(ai->ai_addr);
512                 freeaddrinfo(ai);
513                 if (cname != NULL)
514                         goto out;
515         }
516         /* @hostname was a hostname or had no reverse mapping */
517         cname = strdup(hostname);
518         if (cname == NULL)
519                 return NULL;
520
521 out:
522         ai = host_addrinfo(cname);
523         free(cname);
524         return ai;
525 }
526
527 static int
528 matchhostname(const char *hostname1, const char *hostname2)
529 {
530         struct addrinfo *results1 = NULL, *results2 = NULL;
531         struct addrinfo *ai1, *ai2;
532         int result = 0;
533
534         if (strcasecmp(hostname1, hostname2) == 0)
535                 return 1;
536
537         /*
538          * Don't pass export wildcards or netgroup names to DNS
539          */
540         if (!is_hostname(hostname1) || !is_hostname(hostname2))
541                 return 0;
542
543         results1 = address_list(hostname1);
544         if (results1 == NULL)
545                 goto out;
546         results2 = address_list(hostname2);
547         if (results2 == NULL)
548                 goto out;
549
550         if (strcasecmp(results1->ai_canonname, results2->ai_canonname) == 0) {
551                 result = 1;
552                 goto out;
553         }
554
555         for (ai1 = results1; ai1 != NULL; ai1 = ai1->ai_next)
556                 for (ai2 = results2; ai2 != NULL; ai2 = ai2->ai_next)
557                         if (nfs_compare_sockaddr(ai1->ai_addr, ai2->ai_addr)) {
558                                 result = 1;
559                                 break;
560                         }
561
562 out:
563         freeaddrinfo(results1);
564         freeaddrinfo(results2);
565         return result;
566 }
567
568 /* Based on mnt_table_parse_dir() in
569    util-linux-ng/shlibs/mount/src/tab_parse.c */
570 static void
571 export_d_read(const char *dname)
572 {
573         int n = 0, i;
574         struct dirent **namelist = NULL;
575
576
577         n = scandir(dname, &namelist, NULL, versionsort);
578         if (n < 0) {
579                 if (errno == ENOENT)
580                         /* Silently return */
581                         return;
582                 xlog(L_NOTICE, "scandir %s: %s", dname, strerror(errno));
583         } else if (n == 0)
584                 return;
585
586         for (i = 0; i < n; i++) {
587                 struct dirent *d = namelist[i];
588                 size_t namesz;
589                 char fname[PATH_MAX + 1];
590                 int fname_len;
591
592
593                 if (d->d_type != DT_UNKNOWN 
594                     && d->d_type != DT_REG
595                     && d->d_type != DT_LNK)
596                         continue;
597                 if (*d->d_name == '.')
598                         continue;
599
600 #define _EXT_EXPORT_SIZ   (sizeof(_EXT_EXPORT) - 1)
601                 namesz = strlen(d->d_name);
602                 if (!namesz 
603                     || namesz < _EXT_EXPORT_SIZ + 1
604                     || strcmp(d->d_name + (namesz - _EXT_EXPORT_SIZ),
605                               _EXT_EXPORT))
606                         continue;
607
608                 fname_len = snprintf(fname, PATH_MAX +1, "%s/%s", dname, d->d_name);
609                 if (fname_len > PATH_MAX) {
610                         xlog(L_WARNING, "Too long file name: %s in %s", d->d_name, dname);
611                         continue;
612                 }
613
614                 export_read(fname);
615         }
616                 
617         for (i = 0; i < n; i++)
618                 free(namelist[i]);
619         free(namelist);
620
621         return;
622 }
623
624 static char
625 dumpopt(char c, char *fmt, ...)
626 {
627         va_list ap;
628
629         va_start(ap, fmt);
630         printf("%c", c);
631         vprintf(fmt, ap);
632         va_end(ap);
633         return ',';
634 }
635
636 static void
637 dump(int verbose)
638 {
639         nfs_export      *exp;
640         struct exportent *ep;
641         int             htype;
642         char            *hname, c;
643
644         for (htype = 0; htype < MCL_MAXTYPES; htype++) {
645                 for (exp = exportlist[htype].p_head; exp; exp = exp->m_next) {
646                         ep = &exp->m_export;
647                         if (!exp->m_xtabent)
648                             continue; /* neilb */
649                         if (htype == MCL_ANONYMOUS)
650                                 hname = "<world>";
651                         else
652                                 hname = ep->e_hostname;
653                         if (strlen(ep->e_path) > 14)
654                                 printf("%-14s\n\t\t%s", ep->e_path, hname);
655                         else
656                                 printf("%-14s\t%s", ep->e_path, hname);
657                         if (!verbose) {
658                                 printf("\n");
659                                 continue;
660                         }
661                         c = '(';
662                         if (ep->e_flags & NFSEXP_READONLY)
663                                 c = dumpopt(c, "ro");
664                         else
665                                 c = dumpopt(c, "rw");
666                         if (ep->e_flags & NFSEXP_ASYNC)
667                                 c = dumpopt(c, "async");
668                         if (ep->e_flags & NFSEXP_GATHERED_WRITES)
669                                 c = dumpopt(c, "wdelay");
670                         if (ep->e_flags & NFSEXP_NOHIDE)
671                                 c = dumpopt(c, "nohide");
672                         if (ep->e_flags & NFSEXP_CROSSMOUNT)
673                                 c = dumpopt(c, "crossmnt");
674                         if (ep->e_flags & NFSEXP_INSECURE_PORT)
675                                 c = dumpopt(c, "insecure");
676                         if (ep->e_flags & NFSEXP_ROOTSQUASH)
677                                 c = dumpopt(c, "root_squash");
678                         else
679                                 c = dumpopt(c, "no_root_squash");
680                         if (ep->e_flags & NFSEXP_ALLSQUASH)
681                                 c = dumpopt(c, "all_squash");
682                         if (ep->e_flags & NFSEXP_NOSUBTREECHECK)
683                                 c = dumpopt(c, "no_subtree_check");
684                         if (ep->e_flags & NFSEXP_NOAUTHNLM)
685                                 c = dumpopt(c, "insecure_locks");
686                         if (ep->e_flags & NFSEXP_NOACL)
687                                 c = dumpopt(c, "no_acl");
688                         if (ep->e_flags & NFSEXP_FSID)
689                                 c = dumpopt(c, "fsid=%d", ep->e_fsid);
690                         if (ep->e_uuid)
691                                 c = dumpopt(c, "fsid=%s", ep->e_uuid);
692                         if (ep->e_mountpoint)
693                                 c = dumpopt(c, "mountpoint%s%s", 
694                                             ep->e_mountpoint[0]?"=":"", 
695                                             ep->e_mountpoint);
696                         if (ep->e_anonuid != 65534)
697                                 c = dumpopt(c, "anonuid=%d", ep->e_anonuid);
698                         if (ep->e_anongid != 65534)
699                                 c = dumpopt(c, "anongid=%d", ep->e_anongid);
700                         switch(ep->e_fslocmethod) {
701                         case FSLOC_NONE:
702                                 break;
703                         case FSLOC_REFER:
704                                 c = dumpopt(c, "refer=%s", ep->e_fslocdata);
705                                 break;
706                         case FSLOC_REPLICA:
707                                 c = dumpopt(c, "replicas=%s", ep->e_fslocdata);
708                                 break;
709 #ifdef DEBUG
710                         case FSLOC_STUB:
711                                 c = dumpopt(c, "fsloc=stub");
712                                 break;
713 #endif
714                         }
715                         secinfo_show(stdout, ep);
716                         printf("%c\n", (c != '(')? ')' : ' ');
717                 }
718         }
719 }
720
721 static void
722 error(nfs_export *exp, int err)
723 {
724         xlog(L_ERROR, "%s:%s: %s", exp->m_client->m_hostname,
725                 exp->m_export.e_path, strerror(err));
726 }
727
728 static void
729 usage(const char *progname, int n)
730 {
731         fprintf(stderr, "usage: %s [-afhioruv] [host:/path]\n", progname);
732         exit(n);
733 }