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