Fix mount helper
[zfs.git] / lib / libzfs / libzfs_mount.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25
26 /*
27  * Routines to manage ZFS mounts.  We separate all the nasty routines that have
28  * to deal with the OS.  The following functions are the main entry points --
29  * they are used by mount and unmount and when changing a filesystem's
30  * mountpoint.
31  *
32  *      zfs_is_mounted()
33  *      zfs_mount()
34  *      zfs_unmount()
35  *      zfs_unmountall()
36  *
37  * This file also contains the functions used to manage sharing filesystems via
38  * NFS and iSCSI:
39  *
40  *      zfs_is_shared()
41  *      zfs_share()
42  *      zfs_unshare()
43  *
44  *      zfs_is_shared_nfs()
45  *      zfs_is_shared_smb()
46  *      zfs_share_proto()
47  *      zfs_shareall();
48  *      zfs_unshare_nfs()
49  *      zfs_unshare_smb()
50  *      zfs_unshareall_nfs()
51  *      zfs_unshareall_smb()
52  *      zfs_unshareall()
53  *      zfs_unshareall_bypath()
54  *
55  * The following functions are available for pool consumers, and will
56  * mount/unmount and share/unshare all datasets within pool:
57  *
58  *      zpool_enable_datasets()
59  *      zpool_disable_datasets()
60  */
61
62 #include <dirent.h>
63 #include <dlfcn.h>
64 #include <errno.h>
65 #include <libgen.h>
66 #include <libintl.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <strings.h>
70 #include <unistd.h>
71 #include <zone.h>
72 #include <sys/mntent.h>
73 #include <sys/mount.h>
74 #include <sys/stat.h>
75
76 #include <libzfs.h>
77
78 #include "libzfs_impl.h"
79
80 #include <libshare.h>
81 #include <sys/systeminfo.h>
82 #define MAXISALEN       257     /* based on sysinfo(2) man page */
83
84 static int zfs_share_proto(zfs_handle_t *, zfs_share_proto_t *);
85 zfs_share_type_t zfs_is_shared_proto(zfs_handle_t *, char **,
86     zfs_share_proto_t);
87
88 /*
89  * The share protocols table must be in the same order as the zfs_share_prot_t
90  * enum in libzfs_impl.h
91  */
92 typedef struct {
93         zfs_prop_t p_prop;
94         char *p_name;
95         int p_share_err;
96         int p_unshare_err;
97 } proto_table_t;
98
99 proto_table_t proto_table[PROTO_END] = {
100         {ZFS_PROP_SHARENFS, "nfs", EZFS_SHARENFSFAILED, EZFS_UNSHARENFSFAILED},
101         {ZFS_PROP_SHARESMB, "smb", EZFS_SHARESMBFAILED, EZFS_UNSHARESMBFAILED},
102 };
103
104 zfs_share_proto_t nfs_only[] = {
105         PROTO_NFS,
106         PROTO_END
107 };
108
109 zfs_share_proto_t smb_only[] = {
110         PROTO_SMB,
111         PROTO_END
112 };
113 zfs_share_proto_t share_all_proto[] = {
114         PROTO_NFS,
115         PROTO_SMB,
116         PROTO_END
117 };
118
119 /*
120  * Search for NFS and SMB exports for the given mountpoint and protocol, returning
121  * a zfs_share_type_t value.
122  */
123 static zfs_share_type_t
124 is_shared(libzfs_handle_t *hdl, const char *mountpoint, zfs_share_proto_t proto)
125 {
126         char buf[MAXPATHLEN], *tab;
127
128         if (hdl->libzfs_sharetab == NULL)
129                 return (SHARED_NOT_SHARED);
130
131         (void) fseek(hdl->libzfs_sharetab, 0, SEEK_SET);
132
133         /* Search /etc/exports for NFS exports */
134         /* FIXME: Assumes the file is tab delimited. */
135         while (fgets(buf, sizeof (buf), hdl->libzfs_sharetab) != NULL) {
136
137                 /* the mountpoint is the first entry on each line */
138                 if ((tab = strchr(buf, '\t')) == NULL)
139                         continue;
140
141                 *tab = '\0';
142                 if (strcmp(buf, mountpoint) == 0) {
143                         if (proto == PROTO_NFS)
144                                 return (SHARED_NFS);
145                         else
146                                 return (SHARED_NOT_SHARED);
147                 }
148         }
149
150         /* XXX: Search /etc/samba/smb.conf for SMB exports, return SHARED_SMB */
151
152         return (SHARED_NOT_SHARED);
153 }
154
155 /*
156  * Returns true if the specified directory is empty.  If we can't open the
157  * directory at all, return true so that the mount can fail with a more
158  * informative error message.
159  */
160 static boolean_t
161 dir_is_empty(const char *dirname)
162 {
163         DIR *dirp;
164         struct dirent64 *dp;
165
166         if ((dirp = opendir(dirname)) == NULL)
167                 return (B_TRUE);
168
169         while ((dp = readdir64(dirp)) != NULL) {
170
171                 if (strcmp(dp->d_name, ".") == 0 ||
172                     strcmp(dp->d_name, "..") == 0)
173                         continue;
174
175                 (void) closedir(dirp);
176                 return (B_FALSE);
177         }
178
179         (void) closedir(dirp);
180         return (B_TRUE);
181 }
182
183 /*
184  * Checks to see if the mount is active.  If the filesystem is mounted, we fill
185  * in 'where' with the current mountpoint, and return 1.  Otherwise, we return
186  * 0.
187  */
188 boolean_t
189 is_mounted(libzfs_handle_t *zfs_hdl, const char *special, char **where)
190 {
191         struct mnttab entry;
192
193         if (libzfs_mnttab_find(zfs_hdl, special, &entry) != 0)
194                 return (B_FALSE);
195
196         if (where != NULL)
197                 *where = zfs_strdup(zfs_hdl, entry.mnt_mountp);
198
199         return (B_TRUE);
200 }
201
202 boolean_t
203 zfs_is_mounted(zfs_handle_t *zhp, char **where)
204 {
205         return (is_mounted(zhp->zfs_hdl, zfs_get_name(zhp), where));
206 }
207
208 /*
209  * Returns true if the given dataset is mountable, false otherwise.  Returns the
210  * mountpoint in 'buf'.
211  */
212 static boolean_t
213 zfs_is_mountable(zfs_handle_t *zhp, char *buf, size_t buflen,
214     zprop_source_t *source)
215 {
216         char sourceloc[ZFS_MAXNAMELEN];
217         zprop_source_t sourcetype;
218
219         if (!zfs_prop_valid_for_type(ZFS_PROP_MOUNTPOINT, zhp->zfs_type))
220                 return (B_FALSE);
221
222         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, buf, buflen,
223             &sourcetype, sourceloc, sizeof (sourceloc), B_FALSE) == 0);
224
225         if (strcmp(buf, ZFS_MOUNTPOINT_NONE) == 0 ||
226             strcmp(buf, ZFS_MOUNTPOINT_LEGACY) == 0)
227                 return (B_FALSE);
228
229         if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_OFF)
230                 return (B_FALSE);
231
232         if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
233             getzoneid() == GLOBAL_ZONEID)
234                 return (B_FALSE);
235
236         if (source)
237                 *source = sourcetype;
238
239         return (B_TRUE);
240 }
241
242 /*
243  * The filesystem is mounted by invoking the system mount utility rather
244  * than by the system call mount(2).  This ensures that the /etc/mtab
245  * file is correctly locked for the update.  Performing our own locking
246  * and /etc/mtab update requires making an unsafe assumption about how
247  * the mount utility performs its locking.  Unfortunately, this also means
248  * in the case of a mount failure we do not have the exact errno.  We must
249  * make due with return value from the mount process.
250  *
251  * In the long term a shared library called libmount is under development
252  * which provides a common API to address the locking and errno issues.
253  * Once the standard mount utility has been updated to use this library
254  * we can add an autoconf check to conditionally use it.
255  *
256  * http://www.kernel.org/pub/linux/utils/util-linux/libmount-docs/index.html
257  */
258
259 static int
260 do_mount(const char *src, const char *mntpt, char *opts)
261 {
262         char *argv[8] = {
263             "/bin/mount",
264             "-t", MNTTYPE_ZFS,
265             "-o", opts,
266             (char *)src,
267             (char *)mntpt,
268             (char *)NULL };
269         int rc;
270
271         /* Return only the most critical mount error */
272         rc = libzfs_run_process(argv[0], argv);
273         if (rc) {
274                 if (rc & MOUNT_FILEIO)
275                         return EIO;
276                 if (rc & MOUNT_USER)
277                         return EINTR;
278                 if (rc & MOUNT_SOFTWARE)
279                         return EPIPE;
280                 if (rc & MOUNT_SYSERR)
281                         return EAGAIN;
282                 if (rc & MOUNT_USAGE)
283                         return EINVAL;
284
285                 return ENXIO; /* Generic error */
286         }
287
288         return 0;
289 }
290
291 static int
292 do_unmount(const char *mntpt, int flags)
293 {
294         char force_opt[] = "-f";
295         char lazy_opt[] = "-l";
296         char *argv[7] = {
297             "/bin/umount",
298             "-t", MNTTYPE_ZFS,
299             NULL, NULL, NULL, NULL };
300         int rc, count = 3;
301
302         if (flags & MS_FORCE) {
303                 argv[count] = force_opt;
304                 count++;
305         }
306
307         if (flags & MS_DETACH) {
308                 argv[count] = lazy_opt;
309                 count++;
310         }
311
312         argv[count] = (char *)mntpt;
313         rc = libzfs_run_process(argv[0], argv);
314
315         return (rc ? EINVAL : 0);
316 }
317
318 /*
319  * Mount the given filesystem.
320  */
321 int
322 zfs_mount(zfs_handle_t *zhp, const char *options, int flags)
323 {
324         struct stat buf;
325         char mountpoint[ZFS_MAXPROPLEN];
326         char mntopts[MNT_LINE_MAX];
327         libzfs_handle_t *hdl = zhp->zfs_hdl;
328         int rc;
329
330         if (options == NULL)
331                 (void) strlcpy(mntopts, MNTOPT_DEFAULTS, sizeof (mntopts));
332         else
333                 (void) strlcpy(mntopts, options, sizeof (mntopts));
334
335         /*
336          * If the pool is imported read-only then all mounts must be read-only
337          */
338         if (zpool_get_prop_int(zhp->zpool_hdl, ZPOOL_PROP_READONLY, NULL))
339                 (void) strlcat(mntopts, "," MNTOPT_RO, sizeof (mntopts));
340
341         /*
342          * Append zfsutil option so the mount helper allow the mount
343          */
344         strlcat(mntopts, "," MNTOPT_ZFSUTIL, sizeof (mntopts));
345
346         if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL))
347                 return (0);
348
349         /* Create the directory if it doesn't already exist */
350         if (lstat(mountpoint, &buf) != 0) {
351                 if (mkdirp(mountpoint, 0755) != 0) {
352                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
353                             "failed to create mountpoint"));
354                         return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
355                             dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
356                             mountpoint));
357                 }
358         }
359
360         /*
361          * Determine if the mountpoint is empty.  If so, refuse to perform the
362          * mount.  We don't perform this check if 'remount' is specified.
363          */
364         if (strstr(mntopts, MNTOPT_REMOUNT) == NULL &&
365             !dir_is_empty(mountpoint)) {
366                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
367                     "directory is not empty"));
368                 return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
369                     dgettext(TEXT_DOMAIN, "cannot mount '%s'"), mountpoint));
370         }
371
372         /* perform the mount */
373         rc = do_mount(zfs_get_name(zhp), mountpoint, mntopts);
374         if (rc) {
375                 /*
376                  * Generic errors are nasty, but there are just way too many
377                  * from mount(), and they're well-understood.  We pick a few
378                  * common ones to improve upon.
379                  */
380                 if (rc == EBUSY) {
381                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
382                             "mountpoint or dataset is busy"));
383                 } else if (rc == EPERM) {
384                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
385                             "Insufficient privileges"));
386                 } else if (rc == ENOTSUP) {
387                         char buf[256];
388                         int spa_version;
389
390                         VERIFY(zfs_spa_version(zhp, &spa_version) == 0);
391                         (void) snprintf(buf, sizeof (buf),
392                             dgettext(TEXT_DOMAIN, "Can't mount a version %lld "
393                             "file system on a version %d pool. Pool must be"
394                             " upgraded to mount this file system."),
395                             (u_longlong_t)zfs_prop_get_int(zhp,
396                             ZFS_PROP_VERSION), spa_version);
397                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, buf));
398                 } else {
399                         zfs_error_aux(hdl, strerror(rc));
400                 }
401                 return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
402                     dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
403                     zhp->zfs_name));
404         }
405
406         /* add the mounted entry into our cache */
407         libzfs_mnttab_add(hdl, zfs_get_name(zhp), mountpoint, mntopts);
408         return (0);
409 }
410
411 /*
412  * Unmount a single filesystem.
413  */
414 static int
415 unmount_one(libzfs_handle_t *hdl, const char *mountpoint, int flags)
416 {
417         if (do_unmount(mountpoint, flags) != 0) {
418                 zfs_error_aux(hdl, strerror(errno));
419                 return (zfs_error_fmt(hdl, EZFS_UMOUNTFAILED,
420                     dgettext(TEXT_DOMAIN, "cannot unmount '%s'"),
421                     mountpoint));
422         }
423
424         return (0);
425 }
426
427 /*
428  * Unmount the given filesystem.
429  */
430 int
431 zfs_unmount(zfs_handle_t *zhp, const char *mountpoint, int flags)
432 {
433         libzfs_handle_t *hdl = zhp->zfs_hdl;
434         struct mnttab entry;
435         char *mntpt = NULL;
436
437         /* check to see if we need to unmount the filesystem */
438         if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
439             libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0)) {
440                 /*
441                  * mountpoint may have come from a call to
442                  * getmnt/getmntany if it isn't NULL. If it is NULL,
443                  * we know it comes from libzfs_mnttab_find which can
444                  * then get freed later. We strdup it to play it safe.
445                  */
446                 if (mountpoint == NULL)
447                         mntpt = zfs_strdup(hdl, entry.mnt_mountp);
448                 else
449                         mntpt = zfs_strdup(hdl, mountpoint);
450
451                 /*
452                  * Unshare and unmount the filesystem
453                  */
454                 if (zfs_unshare_proto(zhp, mntpt, share_all_proto) != 0)
455                         return (-1);
456
457                 if (unmount_one(hdl, mntpt, flags) != 0) {
458                         free(mntpt);
459                         (void) zfs_shareall(zhp);
460                         return (-1);
461                 }
462                 libzfs_mnttab_remove(hdl, zhp->zfs_name);
463                 free(mntpt);
464         }
465
466         return (0);
467 }
468
469 /*
470  * Unmount this filesystem and any children inheriting the mountpoint property.
471  * To do this, just act like we're changing the mountpoint property, but don't
472  * remount the filesystems afterwards.
473  */
474 int
475 zfs_unmountall(zfs_handle_t *zhp, int flags)
476 {
477         prop_changelist_t *clp;
478         int ret;
479
480         clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT, 0, flags);
481         if (clp == NULL)
482                 return (-1);
483
484         ret = changelist_prefix(clp);
485         changelist_free(clp);
486
487         return (ret);
488 }
489
490 boolean_t
491 zfs_is_shared(zfs_handle_t *zhp)
492 {
493         zfs_share_type_t rc = 0;
494         zfs_share_proto_t *curr_proto;
495
496         if (ZFS_IS_VOLUME(zhp))
497                 return (B_FALSE);
498
499         for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
500             curr_proto++)
501                 rc |= zfs_is_shared_proto(zhp, NULL, *curr_proto);
502
503         return (rc ? B_TRUE : B_FALSE);
504 }
505
506 int
507 zfs_share(zfs_handle_t *zhp)
508 {
509         assert(!ZFS_IS_VOLUME(zhp));
510         return (zfs_share_proto(zhp, share_all_proto));
511 }
512
513 int
514 zfs_unshare(zfs_handle_t *zhp)
515 {
516         assert(!ZFS_IS_VOLUME(zhp));
517         return (zfs_unshareall(zhp));
518 }
519
520 /*
521  * Check to see if the filesystem is currently shared.
522  */
523 zfs_share_type_t
524 zfs_is_shared_proto(zfs_handle_t *zhp, char **where, zfs_share_proto_t proto)
525 {
526         char *mountpoint;
527         zfs_share_type_t rc;
528
529         if (!zfs_is_mounted(zhp, &mountpoint))
530                 return (SHARED_NOT_SHARED);
531
532         if ((rc = is_shared(zhp->zfs_hdl, mountpoint, proto))) {
533                 if (where != NULL)
534                         *where = mountpoint;
535                 else
536                         free(mountpoint);
537                 return (rc);
538         } else {
539                 free(mountpoint);
540                 return (SHARED_NOT_SHARED);
541         }
542 }
543
544 boolean_t
545 zfs_is_shared_nfs(zfs_handle_t *zhp, char **where)
546 {
547         return (zfs_is_shared_proto(zhp, where,
548             PROTO_NFS) != SHARED_NOT_SHARED);
549 }
550
551 boolean_t
552 zfs_is_shared_smb(zfs_handle_t *zhp, char **where)
553 {
554         return (zfs_is_shared_proto(zhp, where,
555             PROTO_SMB) != SHARED_NOT_SHARED);
556 }
557
558 /*
559  * Make sure things will work if libshare isn't installed by using
560  * wrapper functions that check to see that the pointers to functions
561  * initialized in _zfs_init_libshare() are actually present.
562  */
563
564 static sa_handle_t (*_sa_init)(int);
565 static void (*_sa_fini)(sa_handle_t);
566 static sa_share_t (*_sa_find_share)(sa_handle_t, char *);
567 static int (*_sa_enable_share)(sa_share_t, char *);
568 static int (*_sa_disable_share)(sa_share_t, char *);
569 static char *(*_sa_errorstr)(int);
570 static int (*_sa_parse_legacy_options)(sa_group_t, char *, char *);
571 static boolean_t (*_sa_needs_refresh)(sa_handle_t *);
572 static libzfs_handle_t *(*_sa_get_zfs_handle)(sa_handle_t);
573 static int (*_sa_zfs_process_share)(sa_handle_t, sa_group_t, sa_share_t,
574     char *, char *, zprop_source_t, char *, char *, char *);
575 static void (*_sa_update_sharetab_ts)(sa_handle_t);
576
577 /*
578  * _zfs_init_libshare()
579  *
580  * Find the libshare.so.1 entry points that we use here and save the
581  * values to be used later. This is triggered by the runtime loader.
582  * Make sure the correct ISA version is loaded.
583  */
584 #ifdef __GNUC__
585 static void
586 _zfs_init_libshare(void) __attribute__((constructor));
587 #else
588 #pragma init(_zfs_init_libshare)
589 #endif
590 static void
591 _zfs_init_libshare(void)
592 {
593         void *libshare;
594         char path[MAXPATHLEN];
595         char isa[MAXISALEN];
596
597 #if defined(_LP64)
598         if (sysinfo(SI_ARCHITECTURE_64, isa, MAXISALEN) == -1)
599                 isa[0] = '\0';
600 #else
601         isa[0] = '\0';
602 #endif
603         (void) snprintf(path, MAXPATHLEN,
604             "/usr/lib/%s/libshare.so.1", isa);
605
606         if ((libshare = dlopen(path, RTLD_LAZY | RTLD_GLOBAL)) != NULL) {
607                 _sa_init = (sa_handle_t (*)(int))dlsym(libshare, "sa_init");
608                 _sa_fini = (void (*)(sa_handle_t))dlsym(libshare, "sa_fini");
609                 _sa_find_share = (sa_share_t (*)(sa_handle_t, char *))
610                     dlsym(libshare, "sa_find_share");
611                 _sa_enable_share = (int (*)(sa_share_t, char *))dlsym(libshare,
612                     "sa_enable_share");
613                 _sa_disable_share = (int (*)(sa_share_t, char *))dlsym(libshare,
614                     "sa_disable_share");
615                 _sa_errorstr = (char *(*)(int))dlsym(libshare, "sa_errorstr");
616                 _sa_parse_legacy_options = (int (*)(sa_group_t, char *, char *))
617                     dlsym(libshare, "sa_parse_legacy_options");
618                 _sa_needs_refresh = (boolean_t (*)(sa_handle_t *))
619                     dlsym(libshare, "sa_needs_refresh");
620                 _sa_get_zfs_handle = (libzfs_handle_t *(*)(sa_handle_t))
621                     dlsym(libshare, "sa_get_zfs_handle");
622                 _sa_zfs_process_share = (int (*)(sa_handle_t, sa_group_t,
623                     sa_share_t, char *, char *, zprop_source_t, char *,
624                     char *, char *))dlsym(libshare, "sa_zfs_process_share");
625                 _sa_update_sharetab_ts = (void (*)(sa_handle_t))
626                     dlsym(libshare, "sa_update_sharetab_ts");
627                 if (_sa_init == NULL || _sa_fini == NULL ||
628                     _sa_find_share == NULL || _sa_enable_share == NULL ||
629                     _sa_disable_share == NULL || _sa_errorstr == NULL ||
630                     _sa_parse_legacy_options == NULL ||
631                     _sa_needs_refresh == NULL || _sa_get_zfs_handle == NULL ||
632                     _sa_zfs_process_share == NULL ||
633                     _sa_update_sharetab_ts == NULL) {
634                         _sa_init = NULL;
635                         _sa_fini = NULL;
636                         _sa_disable_share = NULL;
637                         _sa_enable_share = NULL;
638                         _sa_errorstr = NULL;
639                         _sa_parse_legacy_options = NULL;
640                         (void) dlclose(libshare);
641                         _sa_needs_refresh = NULL;
642                         _sa_get_zfs_handle = NULL;
643                         _sa_zfs_process_share = NULL;
644                         _sa_update_sharetab_ts = NULL;
645                 }
646         }
647 }
648
649 /*
650  * zfs_init_libshare(zhandle, service)
651  *
652  * Initialize the libshare API if it hasn't already been initialized.
653  * In all cases it returns 0 if it succeeded and an error if not. The
654  * service value is which part(s) of the API to initialize and is a
655  * direct map to the libshare sa_init(service) interface.
656  */
657 int
658 zfs_init_libshare(libzfs_handle_t *zhandle, int service)
659 {
660         int ret = SA_OK;
661
662         if (_sa_init == NULL)
663                 ret = SA_CONFIG_ERR;
664
665         if (ret == SA_OK && zhandle->libzfs_shareflags & ZFSSHARE_MISS) {
666                 /*
667                  * We had a cache miss. Most likely it is a new ZFS
668                  * dataset that was just created. We want to make sure
669                  * so check timestamps to see if a different process
670                  * has updated any of the configuration. If there was
671                  * some non-ZFS change, we need to re-initialize the
672                  * internal cache.
673                  */
674                 zhandle->libzfs_shareflags &= ~ZFSSHARE_MISS;
675                 if (_sa_needs_refresh != NULL &&
676                     _sa_needs_refresh(zhandle->libzfs_sharehdl)) {
677                         zfs_uninit_libshare(zhandle);
678                         zhandle->libzfs_sharehdl = _sa_init(service);
679                 }
680         }
681
682         if (ret == SA_OK && zhandle && zhandle->libzfs_sharehdl == NULL)
683                 zhandle->libzfs_sharehdl = _sa_init(service);
684
685         if (ret == SA_OK && zhandle->libzfs_sharehdl == NULL)
686                 ret = SA_NO_MEMORY;
687
688         return (ret);
689 }
690
691 /*
692  * zfs_uninit_libshare(zhandle)
693  *
694  * Uninitialize the libshare API if it hasn't already been
695  * uninitialized. It is OK to call multiple times.
696  */
697 void
698 zfs_uninit_libshare(libzfs_handle_t *zhandle)
699 {
700         if (zhandle != NULL && zhandle->libzfs_sharehdl != NULL) {
701                 if (_sa_fini != NULL)
702                         _sa_fini(zhandle->libzfs_sharehdl);
703                 zhandle->libzfs_sharehdl = NULL;
704         }
705 }
706
707 /*
708  * zfs_parse_options(options, proto)
709  *
710  * Call the legacy parse interface to get the protocol specific
711  * options using the NULL arg to indicate that this is a "parse" only.
712  */
713 int
714 zfs_parse_options(char *options, zfs_share_proto_t proto)
715 {
716         if (_sa_parse_legacy_options != NULL) {
717                 return (_sa_parse_legacy_options(NULL, options,
718                     proto_table[proto].p_name));
719         }
720         return (SA_CONFIG_ERR);
721 }
722
723 /*
724  * zfs_sa_find_share(handle, path)
725  *
726  * wrapper around sa_find_share to find a share path in the
727  * configuration.
728  */
729 static sa_share_t
730 zfs_sa_find_share(sa_handle_t handle, char *path)
731 {
732         if (_sa_find_share != NULL)
733                 return (_sa_find_share(handle, path));
734         return (NULL);
735 }
736
737 /*
738  * zfs_sa_enable_share(share, proto)
739  *
740  * Wrapper for sa_enable_share which enables a share for a specified
741  * protocol.
742  */
743 static int
744 zfs_sa_enable_share(sa_share_t share, char *proto)
745 {
746         if (_sa_enable_share != NULL)
747                 return (_sa_enable_share(share, proto));
748         return (SA_CONFIG_ERR);
749 }
750
751 /*
752  * zfs_sa_disable_share(share, proto)
753  *
754  * Wrapper for sa_enable_share which disables a share for a specified
755  * protocol.
756  */
757 static int
758 zfs_sa_disable_share(sa_share_t share, char *proto)
759 {
760         if (_sa_disable_share != NULL)
761                 return (_sa_disable_share(share, proto));
762         return (SA_CONFIG_ERR);
763 }
764
765 /*
766  * Share the given filesystem according to the options in the specified
767  * protocol specific properties (sharenfs, sharesmb).  We rely
768  * on "libshare" to the dirty work for us.
769  */
770 static int
771 zfs_share_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
772 {
773         char mountpoint[ZFS_MAXPROPLEN];
774         char shareopts[ZFS_MAXPROPLEN];
775         char sourcestr[ZFS_MAXPROPLEN];
776         libzfs_handle_t *hdl = zhp->zfs_hdl;
777         sa_share_t share;
778         zfs_share_proto_t *curr_proto;
779         zprop_source_t sourcetype;
780         int ret;
781
782         if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL))
783                 return (0);
784
785         if ((ret = zfs_init_libshare(hdl, SA_INIT_SHARE_API)) != SA_OK) {
786 #ifdef HAVE_SHARE
787                 (void) zfs_error_fmt(hdl, EZFS_SHARENFSFAILED,
788                     dgettext(TEXT_DOMAIN, "cannot share '%s': %s"),
789                     zfs_get_name(zhp), _sa_errorstr != NULL ?
790                     _sa_errorstr(ret) : "");
791                 return (-1);
792 #endif /* HAVE_SHARE */
793                 return (0);
794         }
795
796         for (curr_proto = proto; *curr_proto != PROTO_END; curr_proto++) {
797                 /*
798                  * Return success if there are no share options.
799                  */
800                 if (zfs_prop_get(zhp, proto_table[*curr_proto].p_prop,
801                     shareopts, sizeof (shareopts), &sourcetype, sourcestr,
802                     ZFS_MAXPROPLEN, B_FALSE) != 0 ||
803                     strcmp(shareopts, "off") == 0)
804                         continue;
805
806                 /*
807                  * If the 'zoned' property is set, then zfs_is_mountable()
808                  * will have already bailed out if we are in the global zone.
809                  * But local zones cannot be NFS servers, so we ignore it for
810                  * local zones as well.
811                  */
812                 if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED))
813                         continue;
814
815                 share = zfs_sa_find_share(hdl->libzfs_sharehdl, mountpoint);
816                 if (share == NULL) {
817                         /*
818                          * This may be a new file system that was just
819                          * created so isn't in the internal cache
820                          * (second time through). Rather than
821                          * reloading the entire configuration, we can
822                          * assume ZFS has done the checking and it is
823                          * safe to add this to the internal
824                          * configuration.
825                          */
826                         if (_sa_zfs_process_share(hdl->libzfs_sharehdl,
827                             NULL, NULL, mountpoint,
828                             proto_table[*curr_proto].p_name, sourcetype,
829                             shareopts, sourcestr, zhp->zfs_name) != SA_OK) {
830                                 (void) zfs_error_fmt(hdl,
831                                     proto_table[*curr_proto].p_share_err,
832                                     dgettext(TEXT_DOMAIN, "cannot share '%s'"),
833                                     zfs_get_name(zhp));
834                                 return (-1);
835                         }
836                         hdl->libzfs_shareflags |= ZFSSHARE_MISS;
837                         share = zfs_sa_find_share(hdl->libzfs_sharehdl,
838                             mountpoint);
839                 }
840                 if (share != NULL) {
841                         int err;
842                         err = zfs_sa_enable_share(share,
843                             proto_table[*curr_proto].p_name);
844                         if (err != SA_OK) {
845                                 (void) zfs_error_fmt(hdl,
846                                     proto_table[*curr_proto].p_share_err,
847                                     dgettext(TEXT_DOMAIN, "cannot share '%s'"),
848                                     zfs_get_name(zhp));
849                                 return (-1);
850                         }
851                 } else {
852                         (void) zfs_error_fmt(hdl,
853                             proto_table[*curr_proto].p_share_err,
854                             dgettext(TEXT_DOMAIN, "cannot share '%s'"),
855                             zfs_get_name(zhp));
856                         return (-1);
857                 }
858
859         }
860         return (0);
861 }
862
863
864 int
865 zfs_share_nfs(zfs_handle_t *zhp)
866 {
867         return (zfs_share_proto(zhp, nfs_only));
868 }
869
870 int
871 zfs_share_smb(zfs_handle_t *zhp)
872 {
873         return (zfs_share_proto(zhp, smb_only));
874 }
875
876 int
877 zfs_shareall(zfs_handle_t *zhp)
878 {
879         return (zfs_share_proto(zhp, share_all_proto));
880 }
881
882 /*
883  * Unshare a filesystem by mountpoint.
884  */
885 static int
886 unshare_one(libzfs_handle_t *hdl, const char *name, const char *mountpoint,
887     zfs_share_proto_t proto)
888 {
889         sa_share_t share;
890         int err;
891         char *mntpt;
892         /*
893          * Mountpoint could get trashed if libshare calls getmntany
894          * which it does during API initialization, so strdup the
895          * value.
896          */
897         mntpt = zfs_strdup(hdl, mountpoint);
898
899         /* make sure libshare initialized */
900         if ((err = zfs_init_libshare(hdl, SA_INIT_SHARE_API)) != SA_OK) {
901                 free(mntpt);    /* don't need the copy anymore */
902                 return (zfs_error_fmt(hdl, EZFS_SHARENFSFAILED,
903                     dgettext(TEXT_DOMAIN, "cannot unshare '%s': %s"),
904                     name, _sa_errorstr(err)));
905         }
906
907         share = zfs_sa_find_share(hdl->libzfs_sharehdl, mntpt);
908         free(mntpt);    /* don't need the copy anymore */
909
910         if (share != NULL) {
911                 err = zfs_sa_disable_share(share, proto_table[proto].p_name);
912                 if (err != SA_OK) {
913                         return (zfs_error_fmt(hdl, EZFS_UNSHARENFSFAILED,
914                             dgettext(TEXT_DOMAIN, "cannot unshare '%s': %s"),
915                             name, _sa_errorstr(err)));
916                 }
917         } else {
918                 return (zfs_error_fmt(hdl, EZFS_UNSHARENFSFAILED,
919                     dgettext(TEXT_DOMAIN, "cannot unshare '%s': not found"),
920                     name));
921         }
922         return (0);
923 }
924
925 /*
926  * Unshare the given filesystem.
927  */
928 int
929 zfs_unshare_proto(zfs_handle_t *zhp, const char *mountpoint,
930     zfs_share_proto_t *proto)
931 {
932         libzfs_handle_t *hdl = zhp->zfs_hdl;
933         struct mnttab entry;
934         char *mntpt = NULL;
935
936         /* check to see if need to unmount the filesystem */
937         rewind(zhp->zfs_hdl->libzfs_mnttab);
938         if (mountpoint != NULL)
939                 mountpoint = mntpt = zfs_strdup(hdl, mountpoint);
940
941         if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
942             libzfs_mnttab_find(hdl, zfs_get_name(zhp), &entry) == 0)) {
943                 zfs_share_proto_t *curr_proto;
944
945                 if (mountpoint == NULL)
946                         mntpt = zfs_strdup(zhp->zfs_hdl, entry.mnt_mountp);
947
948                 for (curr_proto = proto; *curr_proto != PROTO_END;
949                     curr_proto++) {
950
951                         if (is_shared(hdl, mntpt, *curr_proto) &&
952                             unshare_one(hdl, zhp->zfs_name,
953                             mntpt, *curr_proto) != 0) {
954                                 if (mntpt != NULL)
955                                         free(mntpt);
956                                 return (-1);
957                         }
958                 }
959         }
960         if (mntpt != NULL)
961                 free(mntpt);
962
963         return (0);
964 }
965
966 int
967 zfs_unshare_nfs(zfs_handle_t *zhp, const char *mountpoint)
968 {
969         return (zfs_unshare_proto(zhp, mountpoint, nfs_only));
970 }
971
972 int
973 zfs_unshare_smb(zfs_handle_t *zhp, const char *mountpoint)
974 {
975         return (zfs_unshare_proto(zhp, mountpoint, smb_only));
976 }
977
978 /*
979  * Same as zfs_unmountall(), but for NFS and SMB unshares.
980  */
981 int
982 zfs_unshareall_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
983 {
984         prop_changelist_t *clp;
985         int ret;
986
987         clp = changelist_gather(zhp, ZFS_PROP_SHARENFS, 0, 0);
988         if (clp == NULL)
989                 return (-1);
990
991         ret = changelist_unshare(clp, proto);
992         changelist_free(clp);
993
994         return (ret);
995 }
996
997 int
998 zfs_unshareall_nfs(zfs_handle_t *zhp)
999 {
1000         return (zfs_unshareall_proto(zhp, nfs_only));
1001 }
1002
1003 int
1004 zfs_unshareall_smb(zfs_handle_t *zhp)
1005 {
1006         return (zfs_unshareall_proto(zhp, smb_only));
1007 }
1008
1009 int
1010 zfs_unshareall(zfs_handle_t *zhp)
1011 {
1012         return (zfs_unshareall_proto(zhp, share_all_proto));
1013 }
1014
1015 int
1016 zfs_unshareall_bypath(zfs_handle_t *zhp, const char *mountpoint)
1017 {
1018         return (zfs_unshare_proto(zhp, mountpoint, share_all_proto));
1019 }
1020
1021 /*
1022  * Remove the mountpoint associated with the current dataset, if necessary.
1023  * We only remove the underlying directory if:
1024  *
1025  *      - The mountpoint is not 'none' or 'legacy'
1026  *      - The mountpoint is non-empty
1027  *      - The mountpoint is the default or inherited
1028  *      - The 'zoned' property is set, or we're in a local zone
1029  *
1030  * Any other directories we leave alone.
1031  */
1032 void
1033 remove_mountpoint(zfs_handle_t *zhp)
1034 {
1035         char mountpoint[ZFS_MAXPROPLEN];
1036         zprop_source_t source;
1037
1038         if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint),
1039             &source))
1040                 return;
1041
1042         if (source == ZPROP_SRC_DEFAULT ||
1043             source == ZPROP_SRC_INHERITED) {
1044                 /*
1045                  * Try to remove the directory, silently ignoring any errors.
1046                  * The filesystem may have since been removed or moved around,
1047                  * and this error isn't really useful to the administrator in
1048                  * any way.
1049                  */
1050                 (void) rmdir(mountpoint);
1051         }
1052 }
1053
1054 void
1055 libzfs_add_handle(get_all_cb_t *cbp, zfs_handle_t *zhp)
1056 {
1057         if (cbp->cb_alloc == cbp->cb_used) {
1058                 size_t newsz;
1059                 void *ptr;
1060
1061                 newsz = cbp->cb_alloc ? cbp->cb_alloc * 2 : 64;
1062                 ptr = zfs_realloc(zhp->zfs_hdl,
1063                     cbp->cb_handles, cbp->cb_alloc * sizeof (void *),
1064                     newsz * sizeof (void *));
1065                 cbp->cb_handles = ptr;
1066                 cbp->cb_alloc = newsz;
1067         }
1068         cbp->cb_handles[cbp->cb_used++] = zhp;
1069 }
1070
1071 static int
1072 mount_cb(zfs_handle_t *zhp, void *data)
1073 {
1074         get_all_cb_t *cbp = data;
1075
1076         if (!(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM)) {
1077                 zfs_close(zhp);
1078                 return (0);
1079         }
1080
1081         if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_NOAUTO) {
1082                 zfs_close(zhp);
1083                 return (0);
1084         }
1085
1086         libzfs_add_handle(cbp, zhp);
1087         if (zfs_iter_filesystems(zhp, mount_cb, cbp) != 0) {
1088                 zfs_close(zhp);
1089                 return (-1);
1090         }
1091         return (0);
1092 }
1093
1094 int
1095 libzfs_dataset_cmp(const void *a, const void *b)
1096 {
1097         zfs_handle_t **za = (zfs_handle_t **)a;
1098         zfs_handle_t **zb = (zfs_handle_t **)b;
1099         char mounta[MAXPATHLEN];
1100         char mountb[MAXPATHLEN];
1101         boolean_t gota, gotb;
1102
1103         if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
1104                 verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
1105                     sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
1106         if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
1107                 verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
1108                     sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
1109
1110         if (gota && gotb)
1111                 return (strcmp(mounta, mountb));
1112
1113         if (gota)
1114                 return (-1);
1115         if (gotb)
1116                 return (1);
1117
1118         return (strcmp(zfs_get_name(a), zfs_get_name(b)));
1119 }
1120
1121 /*
1122  * Mount and share all datasets within the given pool.  This assumes that no
1123  * datasets within the pool are currently mounted.  Because users can create
1124  * complicated nested hierarchies of mountpoints, we first gather all the
1125  * datasets and mountpoints within the pool, and sort them by mountpoint.  Once
1126  * we have the list of all filesystems, we iterate over them in order and mount
1127  * and/or share each one.
1128  */
1129 #pragma weak zpool_mount_datasets = zpool_enable_datasets
1130 int
1131 zpool_enable_datasets(zpool_handle_t *zhp, const char *mntopts, int flags)
1132 {
1133         get_all_cb_t cb = { 0 };
1134         libzfs_handle_t *hdl = zhp->zpool_hdl;
1135         zfs_handle_t *zfsp;
1136         int i, ret = -1;
1137         int *good;
1138
1139         /*
1140          * Gather all non-snap datasets within the pool.
1141          */
1142         if ((zfsp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_DATASET)) == NULL)
1143                 goto out;
1144
1145         libzfs_add_handle(&cb, zfsp);
1146         if (zfs_iter_filesystems(zfsp, mount_cb, &cb) != 0)
1147                 goto out;
1148         /*
1149          * Sort the datasets by mountpoint.
1150          */
1151         qsort(cb.cb_handles, cb.cb_used, sizeof (void *),
1152             libzfs_dataset_cmp);
1153
1154         /*
1155          * And mount all the datasets, keeping track of which ones
1156          * succeeded or failed.
1157          */
1158         if ((good = zfs_alloc(zhp->zpool_hdl,
1159             cb.cb_used * sizeof (int))) == NULL)
1160                 goto out;
1161
1162         ret = 0;
1163         for (i = 0; i < cb.cb_used; i++) {
1164                 if (zfs_mount(cb.cb_handles[i], mntopts, flags) != 0)
1165                         ret = -1;
1166                 else
1167                         good[i] = 1;
1168         }
1169
1170         /*
1171          * Then share all the ones that need to be shared. This needs
1172          * to be a separate pass in order to avoid excessive reloading
1173          * of the configuration. Good should never be NULL since
1174          * zfs_alloc is supposed to exit if memory isn't available.
1175          */
1176         for (i = 0; i < cb.cb_used; i++) {
1177                 if (good[i] && zfs_share(cb.cb_handles[i]) != 0)
1178                         ret = -1;
1179         }
1180
1181         free(good);
1182
1183 out:
1184         for (i = 0; i < cb.cb_used; i++)
1185                 zfs_close(cb.cb_handles[i]);
1186         free(cb.cb_handles);
1187
1188         return (ret);
1189 }
1190
1191 static int
1192 mountpoint_compare(const void *a, const void *b)
1193 {
1194         const char *mounta = *((char **)a);
1195         const char *mountb = *((char **)b);
1196
1197         return (strcmp(mountb, mounta));
1198 }
1199
1200 /* alias for 2002/240 */
1201 #pragma weak zpool_unmount_datasets = zpool_disable_datasets
1202 /*
1203  * Unshare and unmount all datasets within the given pool.  We don't want to
1204  * rely on traversing the DSL to discover the filesystems within the pool,
1205  * because this may be expensive (if not all of them are mounted), and can fail
1206  * arbitrarily (on I/O error, for example).  Instead, we walk /etc/mtab and
1207  * gather all the filesystems that are currently mounted.
1208  */
1209 int
1210 zpool_disable_datasets(zpool_handle_t *zhp, boolean_t force)
1211 {
1212         int used, alloc;
1213         struct mnttab entry;
1214         size_t namelen;
1215         char **mountpoints = NULL;
1216         zfs_handle_t **datasets = NULL;
1217         libzfs_handle_t *hdl = zhp->zpool_hdl;
1218         int i;
1219         int ret = -1;
1220         int flags = (force ? MS_FORCE : 0);
1221
1222         namelen = strlen(zhp->zpool_name);
1223
1224         rewind(hdl->libzfs_mnttab);
1225         used = alloc = 0;
1226         while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
1227                 /*
1228                  * Ignore non-ZFS entries.
1229                  */
1230                 if (entry.mnt_fstype == NULL ||
1231                     strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
1232                         continue;
1233
1234                 /*
1235                  * Ignore filesystems not within this pool.
1236                  */
1237                 if (entry.mnt_mountp == NULL ||
1238                     strncmp(entry.mnt_special, zhp->zpool_name, namelen) != 0 ||
1239                     (entry.mnt_special[namelen] != '/' &&
1240                     entry.mnt_special[namelen] != '\0'))
1241                         continue;
1242
1243                 /*
1244                  * At this point we've found a filesystem within our pool.  Add
1245                  * it to our growing list.
1246                  */
1247                 if (used == alloc) {
1248                         if (alloc == 0) {
1249                                 if ((mountpoints = zfs_alloc(hdl,
1250                                     8 * sizeof (void *))) == NULL)
1251                                         goto out;
1252
1253                                 if ((datasets = zfs_alloc(hdl,
1254                                     8 * sizeof (void *))) == NULL)
1255                                         goto out;
1256
1257                                 alloc = 8;
1258                         } else {
1259                                 void *ptr;
1260
1261                                 if ((ptr = zfs_realloc(hdl, mountpoints,
1262                                     alloc * sizeof (void *),
1263                                     alloc * 2 * sizeof (void *))) == NULL)
1264                                         goto out;
1265                                 mountpoints = ptr;
1266
1267                                 if ((ptr = zfs_realloc(hdl, datasets,
1268                                     alloc * sizeof (void *),
1269                                     alloc * 2 * sizeof (void *))) == NULL)
1270                                         goto out;
1271                                 datasets = ptr;
1272
1273                                 alloc *= 2;
1274                         }
1275                 }
1276
1277                 if ((mountpoints[used] = zfs_strdup(hdl,
1278                     entry.mnt_mountp)) == NULL)
1279                         goto out;
1280
1281                 /*
1282                  * This is allowed to fail, in case there is some I/O error.  It
1283                  * is only used to determine if we need to remove the underlying
1284                  * mountpoint, so failure is not fatal.
1285                  */
1286                 datasets[used] = make_dataset_handle(hdl, entry.mnt_special);
1287
1288                 used++;
1289         }
1290
1291         /*
1292          * At this point, we have the entire list of filesystems, so sort it by
1293          * mountpoint.
1294          */
1295         qsort(mountpoints, used, sizeof (char *), mountpoint_compare);
1296
1297         /*
1298          * Walk through and first unshare everything.
1299          */
1300         for (i = 0; i < used; i++) {
1301                 zfs_share_proto_t *curr_proto;
1302                 for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
1303                     curr_proto++) {
1304                         if (is_shared(hdl, mountpoints[i], *curr_proto) &&
1305                             unshare_one(hdl, mountpoints[i],
1306                             mountpoints[i], *curr_proto) != 0)
1307                                 goto out;
1308                 }
1309         }
1310
1311         /*
1312          * Now unmount everything, removing the underlying directories as
1313          * appropriate.
1314          */
1315         for (i = 0; i < used; i++) {
1316                 if (unmount_one(hdl, mountpoints[i], flags) != 0)
1317                         goto out;
1318         }
1319
1320         for (i = 0; i < used; i++) {
1321                 if (datasets[i])
1322                         remove_mountpoint(datasets[i]);
1323         }
1324
1325         ret = 0;
1326 out:
1327         for (i = 0; i < used; i++) {
1328                 if (datasets[i])
1329                         zfs_close(datasets[i]);
1330                 free(mountpoints[i]);
1331         }
1332         free(datasets);
1333         free(mountpoints);
1334
1335         return (ret);
1336 }