zfs_main.c revision 230449
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 * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2011 by Delphix. All rights reserved.
26 * Copyright (c) 2011-2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
27 * All rights reserved.
28 * Copyright (c) 2011 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
29 */
30
31#include <assert.h>
32#include <ctype.h>
33#include <errno.h>
34#include <libgen.h>
35#include <libintl.h>
36#include <libuutil.h>
37#include <libnvpair.h>
38#include <locale.h>
39#include <stddef.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <strings.h>
43#include <unistd.h>
44#include <fcntl.h>
45#include <zone.h>
46#include <grp.h>
47#include <pwd.h>
48#include <signal.h>
49#include <sys/list.h>
50#include <sys/mntent.h>
51#include <sys/mnttab.h>
52#include <sys/mount.h>
53#include <sys/stat.h>
54#include <sys/fs/zfs.h>
55#include <sys/types.h>
56#include <time.h>
57
58#include <libzfs.h>
59#include <zfs_prop.h>
60#include <zfs_deleg.h>
61#include <libuutil.h>
62#ifdef sun
63#include <aclutils.h>
64#include <directory.h>
65#endif
66
67#include "zfs_iter.h"
68#include "zfs_util.h"
69#include "zfs_comutil.h"
70
71libzfs_handle_t *g_zfs;
72
73static FILE *mnttab_file;
74static char history_str[HIS_MAX_RECORD_LEN];
75
76static int zfs_do_clone(int argc, char **argv);
77static int zfs_do_create(int argc, char **argv);
78static int zfs_do_destroy(int argc, char **argv);
79static int zfs_do_get(int argc, char **argv);
80static int zfs_do_inherit(int argc, char **argv);
81static int zfs_do_list(int argc, char **argv);
82static int zfs_do_mount(int argc, char **argv);
83static int zfs_do_rename(int argc, char **argv);
84static int zfs_do_rollback(int argc, char **argv);
85static int zfs_do_set(int argc, char **argv);
86static int zfs_do_upgrade(int argc, char **argv);
87static int zfs_do_snapshot(int argc, char **argv);
88static int zfs_do_unmount(int argc, char **argv);
89static int zfs_do_share(int argc, char **argv);
90static int zfs_do_unshare(int argc, char **argv);
91static int zfs_do_send(int argc, char **argv);
92static int zfs_do_receive(int argc, char **argv);
93static int zfs_do_promote(int argc, char **argv);
94static int zfs_do_userspace(int argc, char **argv);
95static int zfs_do_allow(int argc, char **argv);
96static int zfs_do_unallow(int argc, char **argv);
97static int zfs_do_hold(int argc, char **argv);
98static int zfs_do_holds(int argc, char **argv);
99static int zfs_do_release(int argc, char **argv);
100static int zfs_do_diff(int argc, char **argv);
101static int zfs_do_jail(int argc, char **argv);
102static int zfs_do_unjail(int argc, char **argv);
103
104/*
105 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
106 */
107
108#ifdef DEBUG
109const char *
110_umem_debug_init(void)
111{
112	return ("default,verbose"); /* $UMEM_DEBUG setting */
113}
114
115const char *
116_umem_logging_init(void)
117{
118	return ("fail,contents"); /* $UMEM_LOGGING setting */
119}
120#endif
121
122typedef enum {
123	HELP_CLONE,
124	HELP_CREATE,
125	HELP_DESTROY,
126	HELP_GET,
127	HELP_INHERIT,
128	HELP_UPGRADE,
129	HELP_JAIL,
130	HELP_UNJAIL,
131	HELP_LIST,
132	HELP_MOUNT,
133	HELP_PROMOTE,
134	HELP_RECEIVE,
135	HELP_RENAME,
136	HELP_ROLLBACK,
137	HELP_SEND,
138	HELP_SET,
139	HELP_SHARE,
140	HELP_SNAPSHOT,
141	HELP_UNMOUNT,
142	HELP_UNSHARE,
143	HELP_ALLOW,
144	HELP_UNALLOW,
145	HELP_USERSPACE,
146	HELP_GROUPSPACE,
147	HELP_HOLD,
148	HELP_HOLDS,
149	HELP_RELEASE,
150	HELP_DIFF,
151} zfs_help_t;
152
153typedef struct zfs_command {
154	const char	*name;
155	int		(*func)(int argc, char **argv);
156	zfs_help_t	usage;
157} zfs_command_t;
158
159/*
160 * Master command table.  Each ZFS command has a name, associated function, and
161 * usage message.  The usage messages need to be internationalized, so we have
162 * to have a function to return the usage message based on a command index.
163 *
164 * These commands are organized according to how they are displayed in the usage
165 * message.  An empty command (one with a NULL name) indicates an empty line in
166 * the generic usage message.
167 */
168static zfs_command_t command_table[] = {
169	{ "create",	zfs_do_create,		HELP_CREATE		},
170	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
171	{ NULL },
172	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
173	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
174	{ "clone",	zfs_do_clone,		HELP_CLONE		},
175	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
176	{ "rename",	zfs_do_rename,		HELP_RENAME		},
177	{ NULL },
178	{ "list",	zfs_do_list,		HELP_LIST		},
179	{ NULL },
180	{ "set",	zfs_do_set,		HELP_SET		},
181	{ "get",	zfs_do_get,		HELP_GET		},
182	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
183	{ "upgrade",	zfs_do_upgrade,		HELP_UPGRADE		},
184	{ "userspace",	zfs_do_userspace,	HELP_USERSPACE		},
185	{ "groupspace",	zfs_do_userspace,	HELP_GROUPSPACE		},
186	{ NULL },
187	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
188	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
189	{ "share",	zfs_do_share,		HELP_SHARE		},
190	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
191	{ NULL },
192	{ "send",	zfs_do_send,		HELP_SEND		},
193	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
194	{ NULL },
195	{ "allow",	zfs_do_allow,		HELP_ALLOW		},
196	{ NULL },
197	{ "unallow",	zfs_do_unallow,		HELP_UNALLOW		},
198	{ NULL },
199	{ "hold",	zfs_do_hold,		HELP_HOLD		},
200	{ "holds",	zfs_do_holds,		HELP_HOLDS		},
201	{ "release",	zfs_do_release,		HELP_RELEASE		},
202	{ "diff",	zfs_do_diff,		HELP_DIFF		},
203	{ NULL },
204	{ "jail",	zfs_do_jail,		HELP_JAIL		},
205	{ "unjail",	zfs_do_unjail,		HELP_UNJAIL		},
206};
207
208#define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
209
210zfs_command_t *current_command;
211
212static const char *
213get_usage(zfs_help_t idx)
214{
215	switch (idx) {
216	case HELP_CLONE:
217		return (gettext("\tclone [-p] [-o property=value] ... "
218		    "<snapshot> <filesystem|volume>\n"));
219	case HELP_CREATE:
220		return (gettext("\tcreate [-p] [-o property=value] ... "
221		    "<filesystem>\n"
222		    "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
223		    "-V <size> <volume>\n"));
224	case HELP_DESTROY:
225		return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
226		    "\tdestroy [-dnpRrv] "
227		    "<snapshot>[%<snapname>][,...]\n"));
228	case HELP_GET:
229		return (gettext("\tget [-rHp] [-d max] "
230		    "[-o \"all\" | field[,...]] [-s source[,...]]\n"
231		    "\t    <\"all\" | property[,...]> "
232		    "[filesystem|volume|snapshot] ...\n"));
233	case HELP_INHERIT:
234		return (gettext("\tinherit [-rS] <property> "
235		    "<filesystem|volume|snapshot> ...\n"));
236	case HELP_UPGRADE:
237		return (gettext("\tupgrade [-v]\n"
238		    "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
239	case HELP_JAIL:
240		return (gettext("\tjail <jailid> <filesystem>\n"));
241	case HELP_UNJAIL:
242		return (gettext("\tunjail <jailid> <filesystem>\n"));
243	case HELP_LIST:
244		return (gettext("\tlist [-rH][-d max] "
245		    "[-o property[,...]] [-t type[,...]] [-s property] ...\n"
246		    "\t    [-S property] ... "
247		    "[filesystem|volume|snapshot] ...\n"));
248	case HELP_MOUNT:
249		return (gettext("\tmount\n"
250		    "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
251	case HELP_PROMOTE:
252		return (gettext("\tpromote <clone-filesystem>\n"));
253	case HELP_RECEIVE:
254		return (gettext("\treceive [-vnFu] <filesystem|volume|"
255		"snapshot>\n"
256		"\treceive [-vnFu] [-d | -e] <filesystem>\n"));
257	case HELP_RENAME:
258		return (gettext("\trename <filesystem|volume|snapshot> "
259		    "<filesystem|volume|snapshot>\n"
260		    "\trename -p <filesystem|volume> <filesystem|volume>\n"
261		    "\trename -r <snapshot> <snapshot>\n"
262		    "\trename -u [-p] <filesystem> <filesystem>"));
263	case HELP_ROLLBACK:
264		return (gettext("\trollback [-rRf] <snapshot>\n"));
265	case HELP_SEND:
266		return (gettext("\tsend [-DnPpRrv] "
267		    "[-i snapshot | -I snapshot] <snapshot>\n"));
268	case HELP_SET:
269		return (gettext("\tset <property=value> "
270		    "<filesystem|volume|snapshot> ...\n"));
271	case HELP_SHARE:
272		return (gettext("\tshare <-a | filesystem>\n"));
273	case HELP_SNAPSHOT:
274		return (gettext("\tsnapshot [-r] [-o property=value] ... "
275		    "<filesystem@snapname|volume@snapname>\n"));
276	case HELP_UNMOUNT:
277		return (gettext("\tunmount [-f] "
278		    "<-a | filesystem|mountpoint>\n"));
279	case HELP_UNSHARE:
280		return (gettext("\tunshare "
281		    "<-a | filesystem|mountpoint>\n"));
282	case HELP_ALLOW:
283		return (gettext("\tallow <filesystem|volume>\n"
284		    "\tallow [-ldug] "
285		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
286		    "\t    <filesystem|volume>\n"
287		    "\tallow [-ld] -e <perm|@setname>[,...] "
288		    "<filesystem|volume>\n"
289		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
290		    "\tallow -s @setname <perm|@setname>[,...] "
291		    "<filesystem|volume>\n"));
292	case HELP_UNALLOW:
293		return (gettext("\tunallow [-rldug] "
294		    "<\"everyone\"|user|group>[,...]\n"
295		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
296		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
297		    "<filesystem|volume>\n"
298		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
299		    "<filesystem|volume>\n"
300		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
301		    "<filesystem|volume>\n"));
302	case HELP_USERSPACE:
303		return (gettext("\tuserspace [-niHp] [-o field[,...]] "
304		    "[-sS field] ... [-t type[,...]]\n"
305		    "\t    <filesystem|snapshot>\n"));
306	case HELP_GROUPSPACE:
307		return (gettext("\tgroupspace [-niHp] [-o field[,...]] "
308		    "[-sS field] ... [-t type[,...]]\n"
309		    "\t    <filesystem|snapshot>\n"));
310	case HELP_HOLD:
311		return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
312	case HELP_HOLDS:
313		return (gettext("\tholds [-r] <snapshot> ...\n"));
314	case HELP_RELEASE:
315		return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
316	case HELP_DIFF:
317		return (gettext("\tdiff [-FHt] <snapshot> "
318		    "[snapshot|filesystem]\n"));
319	}
320
321	abort();
322	/* NOTREACHED */
323}
324
325void
326nomem(void)
327{
328	(void) fprintf(stderr, gettext("internal error: out of memory\n"));
329	exit(1);
330}
331
332/*
333 * Utility function to guarantee malloc() success.
334 */
335
336void *
337safe_malloc(size_t size)
338{
339	void *data;
340
341	if ((data = calloc(1, size)) == NULL)
342		nomem();
343
344	return (data);
345}
346
347static char *
348safe_strdup(char *str)
349{
350	char *dupstr = strdup(str);
351
352	if (dupstr == NULL)
353		nomem();
354
355	return (dupstr);
356}
357
358/*
359 * Callback routine that will print out information for each of
360 * the properties.
361 */
362static int
363usage_prop_cb(int prop, void *cb)
364{
365	FILE *fp = cb;
366
367	(void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
368
369	if (zfs_prop_readonly(prop))
370		(void) fprintf(fp, " NO    ");
371	else
372		(void) fprintf(fp, "YES    ");
373
374	if (zfs_prop_inheritable(prop))
375		(void) fprintf(fp, "  YES   ");
376	else
377		(void) fprintf(fp, "   NO   ");
378
379	if (zfs_prop_values(prop) == NULL)
380		(void) fprintf(fp, "-\n");
381	else
382		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
383
384	return (ZPROP_CONT);
385}
386
387/*
388 * Display usage message.  If we're inside a command, display only the usage for
389 * that command.  Otherwise, iterate over the entire command table and display
390 * a complete usage message.
391 */
392static void
393usage(boolean_t requested)
394{
395	int i;
396	boolean_t show_properties = B_FALSE;
397	FILE *fp = requested ? stdout : stderr;
398
399	if (current_command == NULL) {
400
401		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
402		(void) fprintf(fp,
403		    gettext("where 'command' is one of the following:\n\n"));
404
405		for (i = 0; i < NCOMMAND; i++) {
406			if (command_table[i].name == NULL)
407				(void) fprintf(fp, "\n");
408			else
409				(void) fprintf(fp, "%s",
410				    get_usage(command_table[i].usage));
411		}
412
413		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
414		    "pool/[dataset/]*dataset[@name]\n"));
415	} else {
416		(void) fprintf(fp, gettext("usage:\n"));
417		(void) fprintf(fp, "%s", get_usage(current_command->usage));
418	}
419
420	if (current_command != NULL &&
421	    (strcmp(current_command->name, "set") == 0 ||
422	    strcmp(current_command->name, "get") == 0 ||
423	    strcmp(current_command->name, "inherit") == 0 ||
424	    strcmp(current_command->name, "list") == 0))
425		show_properties = B_TRUE;
426
427	if (show_properties) {
428		(void) fprintf(fp,
429		    gettext("\nThe following properties are supported:\n"));
430
431		(void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
432		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
433
434		/* Iterate over all properties */
435		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
436		    ZFS_TYPE_DATASET);
437
438		(void) fprintf(fp, "\t%-15s ", "userused@...");
439		(void) fprintf(fp, " NO       NO   <size>\n");
440		(void) fprintf(fp, "\t%-15s ", "groupused@...");
441		(void) fprintf(fp, " NO       NO   <size>\n");
442		(void) fprintf(fp, "\t%-15s ", "userquota@...");
443		(void) fprintf(fp, "YES       NO   <size> | none\n");
444		(void) fprintf(fp, "\t%-15s ", "groupquota@...");
445		(void) fprintf(fp, "YES       NO   <size> | none\n");
446		(void) fprintf(fp, "\t%-15s ", "written@<snap>");
447		(void) fprintf(fp, " NO       NO   <size>\n");
448
449		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
450		    "with standard units such as K, M, G, etc.\n"));
451		(void) fprintf(fp, gettext("\nUser-defined properties can "
452		    "be specified by using a name containing a colon (:).\n"));
453		(void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
454		    "properties must be appended with\n"
455		    "a user or group specifier of one of these forms:\n"
456		    "    POSIX name      (eg: \"matt\")\n"
457		    "    POSIX id        (eg: \"126829\")\n"
458		    "    SMB name@domain (eg: \"matt@sun\")\n"
459		    "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
460	} else {
461		(void) fprintf(fp,
462		    gettext("\nFor the property list, run: %s\n"),
463		    "zfs set|get");
464		(void) fprintf(fp,
465		    gettext("\nFor the delegated permission list, run: %s\n"),
466		    "zfs allow|unallow");
467	}
468
469	/*
470	 * See comments at end of main().
471	 */
472	if (getenv("ZFS_ABORT") != NULL) {
473		(void) printf("dumping core by request\n");
474		abort();
475	}
476
477	exit(requested ? 0 : 2);
478}
479
480static int
481parseprop(nvlist_t *props)
482{
483	char *propname = optarg;
484	char *propval, *strval;
485
486	if ((propval = strchr(propname, '=')) == NULL) {
487		(void) fprintf(stderr, gettext("missing "
488		    "'=' for -o option\n"));
489		return (-1);
490	}
491	*propval = '\0';
492	propval++;
493	if (nvlist_lookup_string(props, propname, &strval) == 0) {
494		(void) fprintf(stderr, gettext("property '%s' "
495		    "specified multiple times\n"), propname);
496		return (-1);
497	}
498	if (nvlist_add_string(props, propname, propval) != 0)
499		nomem();
500	return (0);
501}
502
503static int
504parse_depth(char *opt, int *flags)
505{
506	char *tmp;
507	int depth;
508
509	depth = (int)strtol(opt, &tmp, 0);
510	if (*tmp) {
511		(void) fprintf(stderr,
512		    gettext("%s is not an integer\n"), optarg);
513		usage(B_FALSE);
514	}
515	if (depth < 0) {
516		(void) fprintf(stderr,
517		    gettext("Depth can not be negative.\n"));
518		usage(B_FALSE);
519	}
520	*flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
521	return (depth);
522}
523
524#define	PROGRESS_DELAY 2		/* seconds */
525
526static char *pt_reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
527static time_t pt_begin;
528static char *pt_header = NULL;
529static boolean_t pt_shown;
530
531static void
532start_progress_timer(void)
533{
534	pt_begin = time(NULL) + PROGRESS_DELAY;
535	pt_shown = B_FALSE;
536}
537
538static void
539set_progress_header(char *header)
540{
541	assert(pt_header == NULL);
542	pt_header = safe_strdup(header);
543	if (pt_shown) {
544		(void) printf("%s: ", header);
545		(void) fflush(stdout);
546	}
547}
548
549static void
550update_progress(char *update)
551{
552	if (!pt_shown && time(NULL) > pt_begin) {
553		int len = strlen(update);
554
555		(void) printf("%s: %s%*.*s", pt_header, update, len, len,
556		    pt_reverse);
557		(void) fflush(stdout);
558		pt_shown = B_TRUE;
559	} else if (pt_shown) {
560		int len = strlen(update);
561
562		(void) printf("%s%*.*s", update, len, len, pt_reverse);
563		(void) fflush(stdout);
564	}
565}
566
567static void
568finish_progress(char *done)
569{
570	if (pt_shown) {
571		(void) printf("%s\n", done);
572		(void) fflush(stdout);
573	}
574	free(pt_header);
575	pt_header = NULL;
576}
577/*
578 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
579 *
580 * Given an existing dataset, create a writable copy whose initial contents
581 * are the same as the source.  The newly created dataset maintains a
582 * dependency on the original; the original cannot be destroyed so long as
583 * the clone exists.
584 *
585 * The '-p' flag creates all the non-existing ancestors of the target first.
586 */
587static int
588zfs_do_clone(int argc, char **argv)
589{
590	zfs_handle_t *zhp = NULL;
591	boolean_t parents = B_FALSE;
592	nvlist_t *props;
593	int ret;
594	int c;
595
596	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
597		nomem();
598
599	/* check options */
600	while ((c = getopt(argc, argv, "o:p")) != -1) {
601		switch (c) {
602		case 'o':
603			if (parseprop(props))
604				return (1);
605			break;
606		case 'p':
607			parents = B_TRUE;
608			break;
609		case '?':
610			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
611			    optopt);
612			goto usage;
613		}
614	}
615
616	argc -= optind;
617	argv += optind;
618
619	/* check number of arguments */
620	if (argc < 1) {
621		(void) fprintf(stderr, gettext("missing source dataset "
622		    "argument\n"));
623		goto usage;
624	}
625	if (argc < 2) {
626		(void) fprintf(stderr, gettext("missing target dataset "
627		    "argument\n"));
628		goto usage;
629	}
630	if (argc > 2) {
631		(void) fprintf(stderr, gettext("too many arguments\n"));
632		goto usage;
633	}
634
635	/* open the source dataset */
636	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
637		return (1);
638
639	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
640	    ZFS_TYPE_VOLUME)) {
641		/*
642		 * Now create the ancestors of the target dataset.  If the
643		 * target already exists and '-p' option was used we should not
644		 * complain.
645		 */
646		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
647		    ZFS_TYPE_VOLUME))
648			return (0);
649		if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
650			return (1);
651	}
652
653	/* pass to libzfs */
654	ret = zfs_clone(zhp, argv[1], props);
655
656	/* create the mountpoint if necessary */
657	if (ret == 0) {
658		zfs_handle_t *clone;
659
660		clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
661		if (clone != NULL) {
662			if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
663				if ((ret = zfs_mount(clone, NULL, 0)) == 0)
664					ret = zfs_share(clone);
665			zfs_close(clone);
666		}
667	}
668
669	zfs_close(zhp);
670	nvlist_free(props);
671
672	return (!!ret);
673
674usage:
675	if (zhp)
676		zfs_close(zhp);
677	nvlist_free(props);
678	usage(B_FALSE);
679	return (-1);
680}
681
682/*
683 * zfs create [-p] [-o prop=value] ... fs
684 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
685 *
686 * Create a new dataset.  This command can be used to create filesystems
687 * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
688 * For volumes, the user must specify a size to be used.
689 *
690 * The '-s' flag applies only to volumes, and indicates that we should not try
691 * to set the reservation for this volume.  By default we set a reservation
692 * equal to the size for any volume.  For pools with SPA_VERSION >=
693 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
694 *
695 * The '-p' flag creates all the non-existing ancestors of the target first.
696 */
697static int
698zfs_do_create(int argc, char **argv)
699{
700	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
701	zfs_handle_t *zhp = NULL;
702	uint64_t volsize;
703	int c;
704	boolean_t noreserve = B_FALSE;
705	boolean_t bflag = B_FALSE;
706	boolean_t parents = B_FALSE;
707	int ret = 1;
708	nvlist_t *props;
709	uint64_t intval;
710	int canmount = ZFS_CANMOUNT_OFF;
711
712	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
713		nomem();
714
715	/* check options */
716	while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
717		switch (c) {
718		case 'V':
719			type = ZFS_TYPE_VOLUME;
720			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
721				(void) fprintf(stderr, gettext("bad volume "
722				    "size '%s': %s\n"), optarg,
723				    libzfs_error_description(g_zfs));
724				goto error;
725			}
726
727			if (nvlist_add_uint64(props,
728			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
729				nomem();
730			volsize = intval;
731			break;
732		case 'p':
733			parents = B_TRUE;
734			break;
735		case 'b':
736			bflag = B_TRUE;
737			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
738				(void) fprintf(stderr, gettext("bad volume "
739				    "block size '%s': %s\n"), optarg,
740				    libzfs_error_description(g_zfs));
741				goto error;
742			}
743
744			if (nvlist_add_uint64(props,
745			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
746			    intval) != 0)
747				nomem();
748			break;
749		case 'o':
750			if (parseprop(props))
751				goto error;
752			break;
753		case 's':
754			noreserve = B_TRUE;
755			break;
756		case ':':
757			(void) fprintf(stderr, gettext("missing size "
758			    "argument\n"));
759			goto badusage;
760			break;
761		case '?':
762			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
763			    optopt);
764			goto badusage;
765		}
766	}
767
768	if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
769		(void) fprintf(stderr, gettext("'-s' and '-b' can only be "
770		    "used when creating a volume\n"));
771		goto badusage;
772	}
773
774	argc -= optind;
775	argv += optind;
776
777	/* check number of arguments */
778	if (argc == 0) {
779		(void) fprintf(stderr, gettext("missing %s argument\n"),
780		    zfs_type_to_name(type));
781		goto badusage;
782	}
783	if (argc > 1) {
784		(void) fprintf(stderr, gettext("too many arguments\n"));
785		goto badusage;
786	}
787
788	if (type == ZFS_TYPE_VOLUME && !noreserve) {
789		zpool_handle_t *zpool_handle;
790		uint64_t spa_version;
791		char *p;
792		zfs_prop_t resv_prop;
793		char *strval;
794
795		if (p = strchr(argv[0], '/'))
796			*p = '\0';
797		zpool_handle = zpool_open(g_zfs, argv[0]);
798		if (p != NULL)
799			*p = '/';
800		if (zpool_handle == NULL)
801			goto error;
802		spa_version = zpool_get_prop_int(zpool_handle,
803		    ZPOOL_PROP_VERSION, NULL);
804		zpool_close(zpool_handle);
805		if (spa_version >= SPA_VERSION_REFRESERVATION)
806			resv_prop = ZFS_PROP_REFRESERVATION;
807		else
808			resv_prop = ZFS_PROP_RESERVATION;
809		volsize = zvol_volsize_to_reservation(volsize, props);
810
811		if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
812		    &strval) != 0) {
813			if (nvlist_add_uint64(props,
814			    zfs_prop_to_name(resv_prop), volsize) != 0) {
815				nvlist_free(props);
816				nomem();
817			}
818		}
819	}
820
821	if (parents && zfs_name_valid(argv[0], type)) {
822		/*
823		 * Now create the ancestors of target dataset.  If the target
824		 * already exists and '-p' option was used we should not
825		 * complain.
826		 */
827		if (zfs_dataset_exists(g_zfs, argv[0], type)) {
828			ret = 0;
829			goto error;
830		}
831		if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
832			goto error;
833	}
834
835	/* pass to libzfs */
836	if (zfs_create(g_zfs, argv[0], type, props) != 0)
837		goto error;
838
839	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
840		goto error;
841
842	ret = 0;
843	/*
844	 * if the user doesn't want the dataset automatically mounted,
845	 * then skip the mount/share step
846	 */
847	if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
848		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
849
850	/*
851	 * Mount and/or share the new filesystem as appropriate.  We provide a
852	 * verbose error message to let the user know that their filesystem was
853	 * in fact created, even if we failed to mount or share it.
854	 */
855	if (canmount == ZFS_CANMOUNT_ON) {
856		if (zfs_mount(zhp, NULL, 0) != 0) {
857			(void) fprintf(stderr, gettext("filesystem "
858			    "successfully created, but not mounted\n"));
859			ret = 1;
860		} else if (zfs_share(zhp) != 0) {
861			(void) fprintf(stderr, gettext("filesystem "
862			    "successfully created, but not shared\n"));
863			ret = 1;
864		}
865	}
866
867error:
868	if (zhp)
869		zfs_close(zhp);
870	nvlist_free(props);
871	return (ret);
872badusage:
873	nvlist_free(props);
874	usage(B_FALSE);
875	return (2);
876}
877
878/*
879 * zfs destroy [-rRf] <fs, vol>
880 * zfs destroy [-rRd] <snap>
881 *
882 *	-r	Recursively destroy all children
883 *	-R	Recursively destroy all dependents, including clones
884 *	-f	Force unmounting of any dependents
885 *	-d	If we can't destroy now, mark for deferred destruction
886 *
887 * Destroys the given dataset.  By default, it will unmount any filesystems,
888 * and refuse to destroy a dataset that has any dependents.  A dependent can
889 * either be a child, or a clone of a child.
890 */
891typedef struct destroy_cbdata {
892	boolean_t	cb_first;
893	boolean_t	cb_force;
894	boolean_t	cb_recurse;
895	boolean_t	cb_error;
896	boolean_t	cb_doclones;
897	zfs_handle_t	*cb_target;
898	boolean_t	cb_defer_destroy;
899	boolean_t	cb_verbose;
900	boolean_t	cb_parsable;
901	boolean_t	cb_dryrun;
902	nvlist_t	*cb_nvl;
903
904	/* first snap in contiguous run */
905	zfs_handle_t	*cb_firstsnap;
906	/* previous snap in contiguous run */
907	zfs_handle_t	*cb_prevsnap;
908	int64_t		cb_snapused;
909	char		*cb_snapspec;
910} destroy_cbdata_t;
911
912/*
913 * Check for any dependents based on the '-r' or '-R' flags.
914 */
915static int
916destroy_check_dependent(zfs_handle_t *zhp, void *data)
917{
918	destroy_cbdata_t *cbp = data;
919	const char *tname = zfs_get_name(cbp->cb_target);
920	const char *name = zfs_get_name(zhp);
921
922	if (strncmp(tname, name, strlen(tname)) == 0 &&
923	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
924		/*
925		 * This is a direct descendant, not a clone somewhere else in
926		 * the hierarchy.
927		 */
928		if (cbp->cb_recurse)
929			goto out;
930
931		if (cbp->cb_first) {
932			(void) fprintf(stderr, gettext("cannot destroy '%s': "
933			    "%s has children\n"),
934			    zfs_get_name(cbp->cb_target),
935			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
936			(void) fprintf(stderr, gettext("use '-r' to destroy "
937			    "the following datasets:\n"));
938			cbp->cb_first = B_FALSE;
939			cbp->cb_error = B_TRUE;
940		}
941
942		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
943	} else {
944		/*
945		 * This is a clone.  We only want to report this if the '-r'
946		 * wasn't specified, or the target is a snapshot.
947		 */
948		if (!cbp->cb_recurse &&
949		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
950			goto out;
951
952		if (cbp->cb_first) {
953			(void) fprintf(stderr, gettext("cannot destroy '%s': "
954			    "%s has dependent clones\n"),
955			    zfs_get_name(cbp->cb_target),
956			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
957			(void) fprintf(stderr, gettext("use '-R' to destroy "
958			    "the following datasets:\n"));
959			cbp->cb_first = B_FALSE;
960			cbp->cb_error = B_TRUE;
961			cbp->cb_dryrun = B_TRUE;
962		}
963
964		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
965	}
966
967out:
968	zfs_close(zhp);
969	return (0);
970}
971
972static int
973destroy_callback(zfs_handle_t *zhp, void *data)
974{
975	destroy_cbdata_t *cb = data;
976	const char *name = zfs_get_name(zhp);
977
978	if (cb->cb_verbose) {
979		if (cb->cb_parsable) {
980			(void) printf("destroy\t%s\n", name);
981		} else if (cb->cb_dryrun) {
982			(void) printf(gettext("would destroy %s\n"),
983			    name);
984		} else {
985			(void) printf(gettext("will destroy %s\n"),
986			    name);
987		}
988	}
989
990	/*
991	 * Ignore pools (which we've already flagged as an error before getting
992	 * here).
993	 */
994	if (strchr(zfs_get_name(zhp), '/') == NULL &&
995	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
996		zfs_close(zhp);
997		return (0);
998	}
999
1000	if (!cb->cb_dryrun) {
1001		if (zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1002		    zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1003			zfs_close(zhp);
1004			return (-1);
1005		}
1006	}
1007
1008	zfs_close(zhp);
1009	return (0);
1010}
1011
1012static int
1013destroy_print_cb(zfs_handle_t *zhp, void *arg)
1014{
1015	destroy_cbdata_t *cb = arg;
1016	const char *name = zfs_get_name(zhp);
1017	int err = 0;
1018
1019	if (nvlist_exists(cb->cb_nvl, name)) {
1020		if (cb->cb_firstsnap == NULL)
1021			cb->cb_firstsnap = zfs_handle_dup(zhp);
1022		if (cb->cb_prevsnap != NULL)
1023			zfs_close(cb->cb_prevsnap);
1024		/* this snap continues the current range */
1025		cb->cb_prevsnap = zfs_handle_dup(zhp);
1026		if (cb->cb_verbose) {
1027			if (cb->cb_parsable) {
1028				(void) printf("destroy\t%s\n", name);
1029			} else if (cb->cb_dryrun) {
1030				(void) printf(gettext("would destroy %s\n"),
1031				    name);
1032			} else {
1033				(void) printf(gettext("will destroy %s\n"),
1034				    name);
1035			}
1036		}
1037	} else if (cb->cb_firstsnap != NULL) {
1038		/* end of this range */
1039		uint64_t used = 0;
1040		err = zfs_get_snapused_int(cb->cb_firstsnap,
1041		    cb->cb_prevsnap, &used);
1042		cb->cb_snapused += used;
1043		zfs_close(cb->cb_firstsnap);
1044		cb->cb_firstsnap = NULL;
1045		zfs_close(cb->cb_prevsnap);
1046		cb->cb_prevsnap = NULL;
1047	}
1048	zfs_close(zhp);
1049	return (err);
1050}
1051
1052static int
1053destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1054{
1055	int err;
1056	assert(cb->cb_firstsnap == NULL);
1057	assert(cb->cb_prevsnap == NULL);
1058	err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1059	if (cb->cb_firstsnap != NULL) {
1060		uint64_t used = 0;
1061		if (err == 0) {
1062			err = zfs_get_snapused_int(cb->cb_firstsnap,
1063			    cb->cb_prevsnap, &used);
1064		}
1065		cb->cb_snapused += used;
1066		zfs_close(cb->cb_firstsnap);
1067		cb->cb_firstsnap = NULL;
1068		zfs_close(cb->cb_prevsnap);
1069		cb->cb_prevsnap = NULL;
1070	}
1071	return (err);
1072}
1073
1074static int
1075snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1076{
1077	destroy_cbdata_t *cb = arg;
1078	int err = 0;
1079
1080	/* Check for clones. */
1081	if (!cb->cb_doclones) {
1082		cb->cb_target = zhp;
1083		cb->cb_first = B_TRUE;
1084		err = zfs_iter_dependents(zhp, B_TRUE,
1085		    destroy_check_dependent, cb);
1086	}
1087
1088	if (err == 0) {
1089		if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1090			nomem();
1091	}
1092	zfs_close(zhp);
1093	return (err);
1094}
1095
1096static int
1097gather_snapshots(zfs_handle_t *zhp, void *arg)
1098{
1099	destroy_cbdata_t *cb = arg;
1100	int err = 0;
1101
1102	err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1103	if (err == ENOENT)
1104		err = 0;
1105	if (err != 0)
1106		goto out;
1107
1108	if (cb->cb_verbose) {
1109		err = destroy_print_snapshots(zhp, cb);
1110		if (err != 0)
1111			goto out;
1112	}
1113
1114	if (cb->cb_recurse)
1115		err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1116
1117out:
1118	zfs_close(zhp);
1119	return (err);
1120}
1121
1122static int
1123destroy_clones(destroy_cbdata_t *cb)
1124{
1125	nvpair_t *pair;
1126	for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1127	    pair != NULL;
1128	    pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1129		zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1130		    ZFS_TYPE_SNAPSHOT);
1131		if (zhp != NULL) {
1132			boolean_t defer = cb->cb_defer_destroy;
1133			int err;
1134
1135			/*
1136			 * We can't defer destroy non-snapshots, so set it to
1137			 * false while destroying the clones.
1138			 */
1139			cb->cb_defer_destroy = B_FALSE;
1140			err = zfs_iter_dependents(zhp, B_FALSE,
1141			    destroy_callback, cb);
1142			cb->cb_defer_destroy = defer;
1143			zfs_close(zhp);
1144			if (err != 0)
1145				return (err);
1146		}
1147	}
1148	return (0);
1149}
1150
1151static int
1152zfs_do_destroy(int argc, char **argv)
1153{
1154	destroy_cbdata_t cb = { 0 };
1155	int c;
1156	zfs_handle_t *zhp;
1157	char *at;
1158	zfs_type_t type = ZFS_TYPE_DATASET;
1159
1160	/* check options */
1161	while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1162		switch (c) {
1163		case 'v':
1164			cb.cb_verbose = B_TRUE;
1165			break;
1166		case 'p':
1167			cb.cb_verbose = B_TRUE;
1168			cb.cb_parsable = B_TRUE;
1169			break;
1170		case 'n':
1171			cb.cb_dryrun = B_TRUE;
1172			break;
1173		case 'd':
1174			cb.cb_defer_destroy = B_TRUE;
1175			type = ZFS_TYPE_SNAPSHOT;
1176			break;
1177		case 'f':
1178			cb.cb_force = B_TRUE;
1179			break;
1180		case 'r':
1181			cb.cb_recurse = B_TRUE;
1182			break;
1183		case 'R':
1184			cb.cb_recurse = B_TRUE;
1185			cb.cb_doclones = B_TRUE;
1186			break;
1187		case '?':
1188		default:
1189			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1190			    optopt);
1191			usage(B_FALSE);
1192		}
1193	}
1194
1195	argc -= optind;
1196	argv += optind;
1197
1198	/* check number of arguments */
1199	if (argc == 0) {
1200		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1201		usage(B_FALSE);
1202	}
1203	if (argc > 1) {
1204		(void) fprintf(stderr, gettext("too many arguments\n"));
1205		usage(B_FALSE);
1206	}
1207
1208	at = strchr(argv[0], '@');
1209	if (at != NULL) {
1210		int err;
1211
1212		/* Build the list of snaps to destroy in cb_nvl. */
1213		if (nvlist_alloc(&cb.cb_nvl, NV_UNIQUE_NAME, 0) != 0)
1214			nomem();
1215
1216		*at = '\0';
1217		zhp = zfs_open(g_zfs, argv[0],
1218		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1219		if (zhp == NULL)
1220			return (1);
1221
1222		cb.cb_snapspec = at + 1;
1223		if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1224		    cb.cb_error) {
1225			zfs_close(zhp);
1226			nvlist_free(cb.cb_nvl);
1227			return (1);
1228		}
1229
1230		if (nvlist_empty(cb.cb_nvl)) {
1231			(void) fprintf(stderr, gettext("could not find any "
1232			    "snapshots to destroy; check snapshot names.\n"));
1233			zfs_close(zhp);
1234			nvlist_free(cb.cb_nvl);
1235			return (1);
1236		}
1237
1238		if (cb.cb_verbose) {
1239			char buf[16];
1240			zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1241			if (cb.cb_parsable) {
1242				(void) printf("reclaim\t%llu\n",
1243				    cb.cb_snapused);
1244			} else if (cb.cb_dryrun) {
1245				(void) printf(gettext("would reclaim %s\n"),
1246				    buf);
1247			} else {
1248				(void) printf(gettext("will reclaim %s\n"),
1249				    buf);
1250			}
1251		}
1252
1253		if (!cb.cb_dryrun) {
1254			if (cb.cb_doclones)
1255				err = destroy_clones(&cb);
1256			if (err == 0) {
1257				err = zfs_destroy_snaps_nvl(zhp, cb.cb_nvl,
1258				    cb.cb_defer_destroy);
1259			}
1260		}
1261
1262		zfs_close(zhp);
1263		nvlist_free(cb.cb_nvl);
1264		if (err != 0)
1265			return (1);
1266	} else {
1267		/* Open the given dataset */
1268		if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1269			return (1);
1270
1271		cb.cb_target = zhp;
1272
1273		/*
1274		 * Perform an explicit check for pools before going any further.
1275		 */
1276		if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1277		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1278			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1279			    "operation does not apply to pools\n"),
1280			    zfs_get_name(zhp));
1281			(void) fprintf(stderr, gettext("use 'zfs destroy -r "
1282			    "%s' to destroy all datasets in the pool\n"),
1283			    zfs_get_name(zhp));
1284			(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1285			    "to destroy the pool itself\n"), zfs_get_name(zhp));
1286			zfs_close(zhp);
1287			return (1);
1288		}
1289
1290		/*
1291		 * Check for any dependents and/or clones.
1292		 */
1293		cb.cb_first = B_TRUE;
1294		if (!cb.cb_doclones &&
1295		    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1296		    &cb) != 0) {
1297			zfs_close(zhp);
1298			return (1);
1299		}
1300
1301		if (cb.cb_error) {
1302			zfs_close(zhp);
1303			return (1);
1304		}
1305
1306		if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1307		    &cb) != 0) {
1308			zfs_close(zhp);
1309			return (1);
1310		}
1311
1312		/*
1313		 * Do the real thing.  The callback will close the
1314		 * handle regardless of whether it succeeds or not.
1315		 */
1316		if (destroy_callback(zhp, &cb) != 0)
1317			return (1);
1318	}
1319
1320	return (0);
1321}
1322
1323static boolean_t
1324is_recvd_column(zprop_get_cbdata_t *cbp)
1325{
1326	int i;
1327	zfs_get_column_t col;
1328
1329	for (i = 0; i < ZFS_GET_NCOLS &&
1330	    (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1331		if (col == GET_COL_RECVD)
1332			return (B_TRUE);
1333	return (B_FALSE);
1334}
1335
1336/*
1337 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1338 *	< all | property[,property]... > < fs | snap | vol > ...
1339 *
1340 *	-r	recurse over any child datasets
1341 *	-H	scripted mode.  Headers are stripped, and fields are separated
1342 *		by tabs instead of spaces.
1343 *	-o	Set of fields to display.  One of "name,property,value,
1344 *		received,source". Default is "name,property,value,source".
1345 *		"all" is an alias for all five.
1346 *	-s	Set of sources to allow.  One of
1347 *		"local,default,inherited,received,temporary,none".  Default is
1348 *		all six.
1349 *	-p	Display values in parsable (literal) format.
1350 *
1351 *  Prints properties for the given datasets.  The user can control which
1352 *  columns to display as well as which property types to allow.
1353 */
1354
1355/*
1356 * Invoked to display the properties for a single dataset.
1357 */
1358static int
1359get_callback(zfs_handle_t *zhp, void *data)
1360{
1361	char buf[ZFS_MAXPROPLEN];
1362	char rbuf[ZFS_MAXPROPLEN];
1363	zprop_source_t sourcetype;
1364	char source[ZFS_MAXNAMELEN];
1365	zprop_get_cbdata_t *cbp = data;
1366	nvlist_t *user_props = zfs_get_user_props(zhp);
1367	zprop_list_t *pl = cbp->cb_proplist;
1368	nvlist_t *propval;
1369	char *strval;
1370	char *sourceval;
1371	boolean_t received = is_recvd_column(cbp);
1372
1373	for (; pl != NULL; pl = pl->pl_next) {
1374		char *recvdval = NULL;
1375		/*
1376		 * Skip the special fake placeholder.  This will also skip over
1377		 * the name property when 'all' is specified.
1378		 */
1379		if (pl->pl_prop == ZFS_PROP_NAME &&
1380		    pl == cbp->cb_proplist)
1381			continue;
1382
1383		if (pl->pl_prop != ZPROP_INVAL) {
1384			if (zfs_prop_get(zhp, pl->pl_prop, buf,
1385			    sizeof (buf), &sourcetype, source,
1386			    sizeof (source),
1387			    cbp->cb_literal) != 0) {
1388				if (pl->pl_all)
1389					continue;
1390				if (!zfs_prop_valid_for_type(pl->pl_prop,
1391				    ZFS_TYPE_DATASET)) {
1392					(void) fprintf(stderr,
1393					    gettext("No such property '%s'\n"),
1394					    zfs_prop_to_name(pl->pl_prop));
1395					continue;
1396				}
1397				sourcetype = ZPROP_SRC_NONE;
1398				(void) strlcpy(buf, "-", sizeof (buf));
1399			}
1400
1401			if (received && (zfs_prop_get_recvd(zhp,
1402			    zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1403			    cbp->cb_literal) == 0))
1404				recvdval = rbuf;
1405
1406			zprop_print_one_property(zfs_get_name(zhp), cbp,
1407			    zfs_prop_to_name(pl->pl_prop),
1408			    buf, sourcetype, source, recvdval);
1409		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
1410			sourcetype = ZPROP_SRC_LOCAL;
1411
1412			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1413			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1414				sourcetype = ZPROP_SRC_NONE;
1415				(void) strlcpy(buf, "-", sizeof (buf));
1416			}
1417
1418			zprop_print_one_property(zfs_get_name(zhp), cbp,
1419			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1420		} else if (zfs_prop_written(pl->pl_user_prop)) {
1421			sourcetype = ZPROP_SRC_LOCAL;
1422
1423			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1424			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1425				sourcetype = ZPROP_SRC_NONE;
1426				(void) strlcpy(buf, "-", sizeof (buf));
1427			}
1428
1429			zprop_print_one_property(zfs_get_name(zhp), cbp,
1430			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1431		} else {
1432			if (nvlist_lookup_nvlist(user_props,
1433			    pl->pl_user_prop, &propval) != 0) {
1434				if (pl->pl_all)
1435					continue;
1436				sourcetype = ZPROP_SRC_NONE;
1437				strval = "-";
1438			} else {
1439				verify(nvlist_lookup_string(propval,
1440				    ZPROP_VALUE, &strval) == 0);
1441				verify(nvlist_lookup_string(propval,
1442				    ZPROP_SOURCE, &sourceval) == 0);
1443
1444				if (strcmp(sourceval,
1445				    zfs_get_name(zhp)) == 0) {
1446					sourcetype = ZPROP_SRC_LOCAL;
1447				} else if (strcmp(sourceval,
1448				    ZPROP_SOURCE_VAL_RECVD) == 0) {
1449					sourcetype = ZPROP_SRC_RECEIVED;
1450				} else {
1451					sourcetype = ZPROP_SRC_INHERITED;
1452					(void) strlcpy(source,
1453					    sourceval, sizeof (source));
1454				}
1455			}
1456
1457			if (received && (zfs_prop_get_recvd(zhp,
1458			    pl->pl_user_prop, rbuf, sizeof (rbuf),
1459			    cbp->cb_literal) == 0))
1460				recvdval = rbuf;
1461
1462			zprop_print_one_property(zfs_get_name(zhp), cbp,
1463			    pl->pl_user_prop, strval, sourcetype,
1464			    source, recvdval);
1465		}
1466	}
1467
1468	return (0);
1469}
1470
1471static int
1472zfs_do_get(int argc, char **argv)
1473{
1474	zprop_get_cbdata_t cb = { 0 };
1475	int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1476	char *value, *fields;
1477	int ret;
1478	int limit = 0;
1479	zprop_list_t fake_name = { 0 };
1480
1481	/*
1482	 * Set up default columns and sources.
1483	 */
1484	cb.cb_sources = ZPROP_SRC_ALL;
1485	cb.cb_columns[0] = GET_COL_NAME;
1486	cb.cb_columns[1] = GET_COL_PROPERTY;
1487	cb.cb_columns[2] = GET_COL_VALUE;
1488	cb.cb_columns[3] = GET_COL_SOURCE;
1489	cb.cb_type = ZFS_TYPE_DATASET;
1490
1491	/* check options */
1492	while ((c = getopt(argc, argv, ":d:o:s:rHp")) != -1) {
1493		switch (c) {
1494		case 'p':
1495			cb.cb_literal = B_TRUE;
1496			break;
1497		case 'd':
1498			limit = parse_depth(optarg, &flags);
1499			break;
1500		case 'r':
1501			flags |= ZFS_ITER_RECURSE;
1502			break;
1503		case 'H':
1504			cb.cb_scripted = B_TRUE;
1505			break;
1506		case ':':
1507			(void) fprintf(stderr, gettext("missing argument for "
1508			    "'%c' option\n"), optopt);
1509			usage(B_FALSE);
1510			break;
1511		case 'o':
1512			/*
1513			 * Process the set of columns to display.  We zero out
1514			 * the structure to give us a blank slate.
1515			 */
1516			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1517			i = 0;
1518			while (*optarg != '\0') {
1519				static char *col_subopts[] =
1520				    { "name", "property", "value", "received",
1521				    "source", "all", NULL };
1522
1523				if (i == ZFS_GET_NCOLS) {
1524					(void) fprintf(stderr, gettext("too "
1525					    "many fields given to -o "
1526					    "option\n"));
1527					usage(B_FALSE);
1528				}
1529
1530				switch (getsubopt(&optarg, col_subopts,
1531				    &value)) {
1532				case 0:
1533					cb.cb_columns[i++] = GET_COL_NAME;
1534					break;
1535				case 1:
1536					cb.cb_columns[i++] = GET_COL_PROPERTY;
1537					break;
1538				case 2:
1539					cb.cb_columns[i++] = GET_COL_VALUE;
1540					break;
1541				case 3:
1542					cb.cb_columns[i++] = GET_COL_RECVD;
1543					flags |= ZFS_ITER_RECVD_PROPS;
1544					break;
1545				case 4:
1546					cb.cb_columns[i++] = GET_COL_SOURCE;
1547					break;
1548				case 5:
1549					if (i > 0) {
1550						(void) fprintf(stderr,
1551						    gettext("\"all\" conflicts "
1552						    "with specific fields "
1553						    "given to -o option\n"));
1554						usage(B_FALSE);
1555					}
1556					cb.cb_columns[0] = GET_COL_NAME;
1557					cb.cb_columns[1] = GET_COL_PROPERTY;
1558					cb.cb_columns[2] = GET_COL_VALUE;
1559					cb.cb_columns[3] = GET_COL_RECVD;
1560					cb.cb_columns[4] = GET_COL_SOURCE;
1561					flags |= ZFS_ITER_RECVD_PROPS;
1562					i = ZFS_GET_NCOLS;
1563					break;
1564				default:
1565					(void) fprintf(stderr,
1566					    gettext("invalid column name "
1567					    "'%s'\n"), value);
1568					usage(B_FALSE);
1569				}
1570			}
1571			break;
1572
1573		case 's':
1574			cb.cb_sources = 0;
1575			while (*optarg != '\0') {
1576				static char *source_subopts[] = {
1577					"local", "default", "inherited",
1578					"received", "temporary", "none",
1579					NULL };
1580
1581				switch (getsubopt(&optarg, source_subopts,
1582				    &value)) {
1583				case 0:
1584					cb.cb_sources |= ZPROP_SRC_LOCAL;
1585					break;
1586				case 1:
1587					cb.cb_sources |= ZPROP_SRC_DEFAULT;
1588					break;
1589				case 2:
1590					cb.cb_sources |= ZPROP_SRC_INHERITED;
1591					break;
1592				case 3:
1593					cb.cb_sources |= ZPROP_SRC_RECEIVED;
1594					break;
1595				case 4:
1596					cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1597					break;
1598				case 5:
1599					cb.cb_sources |= ZPROP_SRC_NONE;
1600					break;
1601				default:
1602					(void) fprintf(stderr,
1603					    gettext("invalid source "
1604					    "'%s'\n"), value);
1605					usage(B_FALSE);
1606				}
1607			}
1608			break;
1609
1610		case '?':
1611			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1612			    optopt);
1613			usage(B_FALSE);
1614		}
1615	}
1616
1617	argc -= optind;
1618	argv += optind;
1619
1620	if (argc < 1) {
1621		(void) fprintf(stderr, gettext("missing property "
1622		    "argument\n"));
1623		usage(B_FALSE);
1624	}
1625
1626	fields = argv[0];
1627
1628	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1629	    != 0)
1630		usage(B_FALSE);
1631
1632	argc--;
1633	argv++;
1634
1635	/*
1636	 * As part of zfs_expand_proplist(), we keep track of the maximum column
1637	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1638	 * need to know the maximum name length.  However, the user likely did
1639	 * not specify 'name' as one of the properties to fetch, so we need to
1640	 * make sure we always include at least this property for
1641	 * print_get_headers() to work properly.
1642	 */
1643	if (cb.cb_proplist != NULL) {
1644		fake_name.pl_prop = ZFS_PROP_NAME;
1645		fake_name.pl_width = strlen(gettext("NAME"));
1646		fake_name.pl_next = cb.cb_proplist;
1647		cb.cb_proplist = &fake_name;
1648	}
1649
1650	cb.cb_first = B_TRUE;
1651
1652	/* run for each object */
1653	ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET, NULL,
1654	    &cb.cb_proplist, limit, get_callback, &cb);
1655
1656	if (cb.cb_proplist == &fake_name)
1657		zprop_free_list(fake_name.pl_next);
1658	else
1659		zprop_free_list(cb.cb_proplist);
1660
1661	return (ret);
1662}
1663
1664/*
1665 * inherit [-rS] <property> <fs|vol> ...
1666 *
1667 *	-r	Recurse over all children
1668 *	-S	Revert to received value, if any
1669 *
1670 * For each dataset specified on the command line, inherit the given property
1671 * from its parent.  Inheriting a property at the pool level will cause it to
1672 * use the default value.  The '-r' flag will recurse over all children, and is
1673 * useful for setting a property on a hierarchy-wide basis, regardless of any
1674 * local modifications for each dataset.
1675 */
1676
1677typedef struct inherit_cbdata {
1678	const char *cb_propname;
1679	boolean_t cb_received;
1680} inherit_cbdata_t;
1681
1682static int
1683inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1684{
1685	inherit_cbdata_t *cb = data;
1686	zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1687
1688	/*
1689	 * If we're doing it recursively, then ignore properties that
1690	 * are not valid for this type of dataset.
1691	 */
1692	if (prop != ZPROP_INVAL &&
1693	    !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1694		return (0);
1695
1696	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1697}
1698
1699static int
1700inherit_cb(zfs_handle_t *zhp, void *data)
1701{
1702	inherit_cbdata_t *cb = data;
1703
1704	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1705}
1706
1707static int
1708zfs_do_inherit(int argc, char **argv)
1709{
1710	int c;
1711	zfs_prop_t prop;
1712	inherit_cbdata_t cb = { 0 };
1713	char *propname;
1714	int ret;
1715	int flags = 0;
1716	boolean_t received = B_FALSE;
1717
1718	/* check options */
1719	while ((c = getopt(argc, argv, "rS")) != -1) {
1720		switch (c) {
1721		case 'r':
1722			flags |= ZFS_ITER_RECURSE;
1723			break;
1724		case 'S':
1725			received = B_TRUE;
1726			break;
1727		case '?':
1728		default:
1729			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1730			    optopt);
1731			usage(B_FALSE);
1732		}
1733	}
1734
1735	argc -= optind;
1736	argv += optind;
1737
1738	/* check number of arguments */
1739	if (argc < 1) {
1740		(void) fprintf(stderr, gettext("missing property argument\n"));
1741		usage(B_FALSE);
1742	}
1743	if (argc < 2) {
1744		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1745		usage(B_FALSE);
1746	}
1747
1748	propname = argv[0];
1749	argc--;
1750	argv++;
1751
1752	if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1753		if (zfs_prop_readonly(prop)) {
1754			(void) fprintf(stderr, gettext(
1755			    "%s property is read-only\n"),
1756			    propname);
1757			return (1);
1758		}
1759		if (!zfs_prop_inheritable(prop) && !received) {
1760			(void) fprintf(stderr, gettext("'%s' property cannot "
1761			    "be inherited\n"), propname);
1762			if (prop == ZFS_PROP_QUOTA ||
1763			    prop == ZFS_PROP_RESERVATION ||
1764			    prop == ZFS_PROP_REFQUOTA ||
1765			    prop == ZFS_PROP_REFRESERVATION)
1766				(void) fprintf(stderr, gettext("use 'zfs set "
1767				    "%s=none' to clear\n"), propname);
1768			return (1);
1769		}
1770		if (received && (prop == ZFS_PROP_VOLSIZE ||
1771		    prop == ZFS_PROP_VERSION)) {
1772			(void) fprintf(stderr, gettext("'%s' property cannot "
1773			    "be reverted to a received value\n"), propname);
1774			return (1);
1775		}
1776	} else if (!zfs_prop_user(propname)) {
1777		(void) fprintf(stderr, gettext("invalid property '%s'\n"),
1778		    propname);
1779		usage(B_FALSE);
1780	}
1781
1782	cb.cb_propname = propname;
1783	cb.cb_received = received;
1784
1785	if (flags & ZFS_ITER_RECURSE) {
1786		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1787		    NULL, NULL, 0, inherit_recurse_cb, &cb);
1788	} else {
1789		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1790		    NULL, NULL, 0, inherit_cb, &cb);
1791	}
1792
1793	return (ret);
1794}
1795
1796typedef struct upgrade_cbdata {
1797	uint64_t cb_numupgraded;
1798	uint64_t cb_numsamegraded;
1799	uint64_t cb_numfailed;
1800	uint64_t cb_version;
1801	boolean_t cb_newer;
1802	boolean_t cb_foundone;
1803	char cb_lastfs[ZFS_MAXNAMELEN];
1804} upgrade_cbdata_t;
1805
1806static int
1807same_pool(zfs_handle_t *zhp, const char *name)
1808{
1809	int len1 = strcspn(name, "/@");
1810	const char *zhname = zfs_get_name(zhp);
1811	int len2 = strcspn(zhname, "/@");
1812
1813	if (len1 != len2)
1814		return (B_FALSE);
1815	return (strncmp(name, zhname, len1) == 0);
1816}
1817
1818static int
1819upgrade_list_callback(zfs_handle_t *zhp, void *data)
1820{
1821	upgrade_cbdata_t *cb = data;
1822	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1823
1824	/* list if it's old/new */
1825	if ((!cb->cb_newer && version < ZPL_VERSION) ||
1826	    (cb->cb_newer && version > ZPL_VERSION)) {
1827		char *str;
1828		if (cb->cb_newer) {
1829			str = gettext("The following filesystems are "
1830			    "formatted using a newer software version and\n"
1831			    "cannot be accessed on the current system.\n\n");
1832		} else {
1833			str = gettext("The following filesystems are "
1834			    "out of date, and can be upgraded.  After being\n"
1835			    "upgraded, these filesystems (and any 'zfs send' "
1836			    "streams generated from\n"
1837			    "subsequent snapshots) will no longer be "
1838			    "accessible by older software versions.\n\n");
1839		}
1840
1841		if (!cb->cb_foundone) {
1842			(void) puts(str);
1843			(void) printf(gettext("VER  FILESYSTEM\n"));
1844			(void) printf(gettext("---  ------------\n"));
1845			cb->cb_foundone = B_TRUE;
1846		}
1847
1848		(void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1849	}
1850
1851	return (0);
1852}
1853
1854static int
1855upgrade_set_callback(zfs_handle_t *zhp, void *data)
1856{
1857	upgrade_cbdata_t *cb = data;
1858	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1859	int needed_spa_version;
1860	int spa_version;
1861
1862	if (zfs_spa_version(zhp, &spa_version) < 0)
1863		return (-1);
1864
1865	needed_spa_version = zfs_spa_version_map(cb->cb_version);
1866
1867	if (needed_spa_version < 0)
1868		return (-1);
1869
1870	if (spa_version < needed_spa_version) {
1871		/* can't upgrade */
1872		(void) printf(gettext("%s: can not be "
1873		    "upgraded; the pool version needs to first "
1874		    "be upgraded\nto version %d\n\n"),
1875		    zfs_get_name(zhp), needed_spa_version);
1876		cb->cb_numfailed++;
1877		return (0);
1878	}
1879
1880	/* upgrade */
1881	if (version < cb->cb_version) {
1882		char verstr[16];
1883		(void) snprintf(verstr, sizeof (verstr),
1884		    "%llu", cb->cb_version);
1885		if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1886			/*
1887			 * If they did "zfs upgrade -a", then we could
1888			 * be doing ioctls to different pools.  We need
1889			 * to log this history once to each pool.
1890			 */
1891			verify(zpool_stage_history(g_zfs, history_str) == 0);
1892		}
1893		if (zfs_prop_set(zhp, "version", verstr) == 0)
1894			cb->cb_numupgraded++;
1895		else
1896			cb->cb_numfailed++;
1897		(void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1898	} else if (version > cb->cb_version) {
1899		/* can't downgrade */
1900		(void) printf(gettext("%s: can not be downgraded; "
1901		    "it is already at version %u\n"),
1902		    zfs_get_name(zhp), version);
1903		cb->cb_numfailed++;
1904	} else {
1905		cb->cb_numsamegraded++;
1906	}
1907	return (0);
1908}
1909
1910/*
1911 * zfs upgrade
1912 * zfs upgrade -v
1913 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1914 */
1915static int
1916zfs_do_upgrade(int argc, char **argv)
1917{
1918	boolean_t all = B_FALSE;
1919	boolean_t showversions = B_FALSE;
1920	int ret;
1921	upgrade_cbdata_t cb = { 0 };
1922	char c;
1923	int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1924
1925	/* check options */
1926	while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1927		switch (c) {
1928		case 'r':
1929			flags |= ZFS_ITER_RECURSE;
1930			break;
1931		case 'v':
1932			showversions = B_TRUE;
1933			break;
1934		case 'V':
1935			if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1936			    optarg, &cb.cb_version) != 0) {
1937				(void) fprintf(stderr,
1938				    gettext("invalid version %s\n"), optarg);
1939				usage(B_FALSE);
1940			}
1941			break;
1942		case 'a':
1943			all = B_TRUE;
1944			break;
1945		case '?':
1946		default:
1947			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1948			    optopt);
1949			usage(B_FALSE);
1950		}
1951	}
1952
1953	argc -= optind;
1954	argv += optind;
1955
1956	if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1957		usage(B_FALSE);
1958	if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1959	    cb.cb_version || argc))
1960		usage(B_FALSE);
1961	if ((all || argc) && (showversions))
1962		usage(B_FALSE);
1963	if (all && argc)
1964		usage(B_FALSE);
1965
1966	if (showversions) {
1967		/* Show info on available versions. */
1968		(void) printf(gettext("The following filesystem versions are "
1969		    "supported:\n\n"));
1970		(void) printf(gettext("VER  DESCRIPTION\n"));
1971		(void) printf("---  -----------------------------------------"
1972		    "---------------\n");
1973		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1974		(void) printf(gettext(" 2   Enhanced directory entries\n"));
1975		(void) printf(gettext(" 3   Case insensitive and filesystem "
1976		    "user identifier (FUID)\n"));
1977		(void) printf(gettext(" 4   userquota, groupquota "
1978		    "properties\n"));
1979		(void) printf(gettext(" 5   System attributes\n"));
1980		(void) printf(gettext("\nFor more information on a particular "
1981		    "version, including supported releases,\n"));
1982		(void) printf("see the ZFS Administration Guide.\n\n");
1983		ret = 0;
1984	} else if (argc || all) {
1985		/* Upgrade filesystems */
1986		if (cb.cb_version == 0)
1987			cb.cb_version = ZPL_VERSION;
1988		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
1989		    NULL, NULL, 0, upgrade_set_callback, &cb);
1990		(void) printf(gettext("%llu filesystems upgraded\n"),
1991		    cb.cb_numupgraded);
1992		if (cb.cb_numsamegraded) {
1993			(void) printf(gettext("%llu filesystems already at "
1994			    "this version\n"),
1995			    cb.cb_numsamegraded);
1996		}
1997		if (cb.cb_numfailed != 0)
1998			ret = 1;
1999	} else {
2000		/* List old-version filesytems */
2001		boolean_t found;
2002		(void) printf(gettext("This system is currently running "
2003		    "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2004
2005		flags |= ZFS_ITER_RECURSE;
2006		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2007		    NULL, NULL, 0, upgrade_list_callback, &cb);
2008
2009		found = cb.cb_foundone;
2010		cb.cb_foundone = B_FALSE;
2011		cb.cb_newer = B_TRUE;
2012
2013		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2014		    NULL, NULL, 0, upgrade_list_callback, &cb);
2015
2016		if (!cb.cb_foundone && !found) {
2017			(void) printf(gettext("All filesystems are "
2018			    "formatted with the current version.\n"));
2019		}
2020	}
2021
2022	return (ret);
2023}
2024
2025#define	USTYPE_USR_BIT (0)
2026#define	USTYPE_GRP_BIT (1)
2027#define	USTYPE_PSX_BIT (2)
2028#define	USTYPE_SMB_BIT (3)
2029
2030#define	USTYPE_USR (1 << USTYPE_USR_BIT)
2031#define	USTYPE_GRP (1 << USTYPE_GRP_BIT)
2032
2033#define	USTYPE_PSX (1 << USTYPE_PSX_BIT)
2034#define	USTYPE_SMB (1 << USTYPE_SMB_BIT)
2035
2036#define	USTYPE_PSX_USR (USTYPE_PSX | USTYPE_USR)
2037#define	USTYPE_SMB_USR (USTYPE_SMB | USTYPE_USR)
2038#define	USTYPE_PSX_GRP (USTYPE_PSX | USTYPE_GRP)
2039#define	USTYPE_SMB_GRP (USTYPE_SMB | USTYPE_GRP)
2040#define	USTYPE_ALL (USTYPE_PSX_USR | USTYPE_SMB_USR \
2041		| USTYPE_PSX_GRP | USTYPE_SMB_GRP)
2042
2043
2044#define	USPROP_USED_BIT (0)
2045#define	USPROP_QUOTA_BIT (1)
2046
2047#define	USPROP_USED (1 << USPROP_USED_BIT)
2048#define	USPROP_QUOTA (1 << USPROP_QUOTA_BIT)
2049
2050typedef struct us_node {
2051	nvlist_t	*usn_nvl;
2052	uu_avl_node_t	usn_avlnode;
2053	uu_list_node_t	usn_listnode;
2054} us_node_t;
2055
2056typedef struct us_cbdata {
2057	nvlist_t		**cb_nvlp;
2058	uu_avl_pool_t		*cb_avl_pool;
2059	uu_avl_t		*cb_avl;
2060	boolean_t		cb_numname;
2061	boolean_t		cb_nicenum;
2062	boolean_t		cb_sid2posix;
2063	zfs_userquota_prop_t	cb_prop;
2064	zfs_sort_column_t	*cb_sortcol;
2065	size_t			cb_max_typelen;
2066	size_t			cb_max_namelen;
2067	size_t			cb_max_usedlen;
2068	size_t			cb_max_quotalen;
2069} us_cbdata_t;
2070
2071typedef struct {
2072	zfs_sort_column_t *si_sortcol;
2073	boolean_t si_num_name;
2074	boolean_t si_parsable;
2075} us_sort_info_t;
2076
2077static int
2078us_compare(const void *larg, const void *rarg, void *unused)
2079{
2080	const us_node_t *l = larg;
2081	const us_node_t *r = rarg;
2082	int rc = 0;
2083	us_sort_info_t *si = (us_sort_info_t *)unused;
2084	zfs_sort_column_t *sortcol = si->si_sortcol;
2085	boolean_t num_name = si->si_num_name;
2086	nvlist_t *lnvl = l->usn_nvl;
2087	nvlist_t *rnvl = r->usn_nvl;
2088
2089	for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2090		char *lvstr = "";
2091		char *rvstr = "";
2092		uint32_t lv32 = 0;
2093		uint32_t rv32 = 0;
2094		uint64_t lv64 = 0;
2095		uint64_t rv64 = 0;
2096		zfs_prop_t prop = sortcol->sc_prop;
2097		const char *propname = NULL;
2098		boolean_t reverse = sortcol->sc_reverse;
2099
2100		switch (prop) {
2101		case ZFS_PROP_TYPE:
2102			propname = "type";
2103			(void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2104			(void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2105			if (rv32 != lv32)
2106				rc = (rv32 > lv32) ? 1 : -1;
2107			break;
2108		case ZFS_PROP_NAME:
2109			propname = "name";
2110			if (num_name) {
2111				(void) nvlist_lookup_uint32(lnvl, propname,
2112				    &lv32);
2113				(void) nvlist_lookup_uint32(rnvl, propname,
2114				    &rv32);
2115				if (rv32 != lv32)
2116					rc = (rv32 > lv32) ? 1 : -1;
2117			} else {
2118				(void) nvlist_lookup_string(lnvl, propname,
2119				    &lvstr);
2120				(void) nvlist_lookup_string(rnvl, propname,
2121				    &rvstr);
2122				rc = strcmp(lvstr, rvstr);
2123			}
2124			break;
2125
2126		case ZFS_PROP_USED:
2127		case ZFS_PROP_QUOTA:
2128			if (ZFS_PROP_USED == prop)
2129				propname = "used";
2130			else
2131				propname = "quota";
2132			(void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2133			(void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2134			if (rv64 != lv64)
2135				rc = (rv64 > lv64) ? 1 : -1;
2136		}
2137
2138		if (rc)
2139			if (rc < 0)
2140				return (reverse ? 1 : -1);
2141			else
2142				return (reverse ? -1 : 1);
2143	}
2144
2145	return (rc);
2146}
2147
2148static inline const char *
2149us_type2str(unsigned field_type)
2150{
2151	switch (field_type) {
2152	case USTYPE_PSX_USR:
2153		return ("POSIX User");
2154	case USTYPE_PSX_GRP:
2155		return ("POSIX Group");
2156	case USTYPE_SMB_USR:
2157		return ("SMB User");
2158	case USTYPE_SMB_GRP:
2159		return ("SMB Group");
2160	default:
2161		return ("Undefined");
2162	}
2163}
2164
2165/*
2166 * zfs userspace
2167 */
2168static int
2169userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2170{
2171	us_cbdata_t *cb = (us_cbdata_t *)arg;
2172	zfs_userquota_prop_t prop = cb->cb_prop;
2173	char *name = NULL;
2174	char *propname;
2175	char namebuf[32];
2176	char sizebuf[32];
2177	us_node_t *node;
2178	uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2179	uu_avl_t *avl = cb->cb_avl;
2180	uu_avl_index_t idx;
2181	nvlist_t *props;
2182	us_node_t *n;
2183	zfs_sort_column_t *sortcol = cb->cb_sortcol;
2184	unsigned type;
2185	const char *typestr;
2186	size_t namelen;
2187	size_t typelen;
2188	size_t sizelen;
2189	us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2190
2191	if (domain == NULL || domain[0] == '\0') {
2192		/* POSIX */
2193		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2194			type = USTYPE_PSX_GRP;
2195			struct group *g = getgrgid(rid);
2196			if (g)
2197				name = g->gr_name;
2198		} else {
2199			type = USTYPE_PSX_USR;
2200			struct passwd *p = getpwuid(rid);
2201			if (p)
2202				name = p->pw_name;
2203		}
2204	} else {
2205		char sid[ZFS_MAXNAMELEN+32];
2206		uid_t id;
2207		uint64_t classes;
2208#ifdef sun
2209		int err;
2210		directory_error_t e;
2211#endif
2212
2213		(void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2214		/* SMB */
2215		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2216			type = USTYPE_SMB_GRP;
2217#ifdef sun
2218			err = sid_to_id(sid, B_FALSE, &id);
2219#endif
2220		} else {
2221			type = USTYPE_SMB_USR;
2222#ifdef sun
2223			err = sid_to_id(sid, B_TRUE, &id);
2224#endif
2225		}
2226
2227#ifdef sun
2228		if (err == 0) {
2229			rid = id;
2230
2231			e = directory_name_from_sid(NULL, sid, &name, &classes);
2232			if (e != NULL) {
2233				directory_error_free(e);
2234				return (NULL);
2235			}
2236
2237			if (name == NULL)
2238				name = sid;
2239		}
2240#endif
2241	}
2242
2243/*
2244 *	if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA)
2245 *		ug = "group";
2246 *	else
2247 *		ug = "user";
2248 */
2249
2250	if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED)
2251		propname = "used";
2252	else
2253		propname = "quota";
2254
2255	(void) snprintf(namebuf, sizeof (namebuf), "%u", rid);
2256	if (name == NULL)
2257		name = namebuf;
2258
2259	if (cb->cb_nicenum)
2260		zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2261	else
2262		(void) sprintf(sizebuf, "%llu", space);
2263
2264	node = safe_malloc(sizeof (us_node_t));
2265	uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2266
2267	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
2268		free(node);
2269		return (-1);
2270	}
2271
2272	if (nvlist_add_uint32(props, "type", type) != 0)
2273		nomem();
2274
2275	if (cb->cb_numname) {
2276		if (nvlist_add_uint32(props, "name", rid) != 0)
2277			nomem();
2278		namelen = strlen(namebuf);
2279	} else {
2280		if (nvlist_add_string(props, "name", name) != 0)
2281			nomem();
2282		namelen = strlen(name);
2283	}
2284
2285	typestr = us_type2str(type);
2286	typelen = strlen(gettext(typestr));
2287	if (typelen > cb->cb_max_typelen)
2288		cb->cb_max_typelen  = typelen;
2289
2290	if (namelen > cb->cb_max_namelen)
2291		cb->cb_max_namelen  = namelen;
2292
2293	sizelen = strlen(sizebuf);
2294	if (0 == strcmp(propname, "used")) {
2295		if (sizelen > cb->cb_max_usedlen)
2296			cb->cb_max_usedlen  = sizelen;
2297	} else {
2298		if (sizelen > cb->cb_max_quotalen)
2299			cb->cb_max_quotalen  = sizelen;
2300	}
2301
2302	node->usn_nvl = props;
2303
2304	n = uu_avl_find(avl, node, &sortinfo, &idx);
2305	if (n == NULL)
2306		uu_avl_insert(avl, node, idx);
2307	else {
2308		nvlist_free(props);
2309		free(node);
2310		node = n;
2311		props = node->usn_nvl;
2312	}
2313
2314	if (nvlist_add_uint64(props, propname, space) != 0)
2315		nomem();
2316
2317	return (0);
2318}
2319
2320static inline boolean_t
2321usprop_check(zfs_userquota_prop_t p, unsigned types, unsigned props)
2322{
2323	unsigned type;
2324	unsigned prop;
2325
2326	switch (p) {
2327	case ZFS_PROP_USERUSED:
2328		type = USTYPE_USR;
2329		prop = USPROP_USED;
2330		break;
2331	case ZFS_PROP_USERQUOTA:
2332		type = USTYPE_USR;
2333		prop = USPROP_QUOTA;
2334		break;
2335	case ZFS_PROP_GROUPUSED:
2336		type = USTYPE_GRP;
2337		prop = USPROP_USED;
2338		break;
2339	case ZFS_PROP_GROUPQUOTA:
2340		type = USTYPE_GRP;
2341		prop = USPROP_QUOTA;
2342		break;
2343	default: /* ALL */
2344		return (B_TRUE);
2345	};
2346
2347	return (type & types && prop & props);
2348}
2349
2350#define	USFIELD_TYPE (1 << 0)
2351#define	USFIELD_NAME (1 << 1)
2352#define	USFIELD_USED (1 << 2)
2353#define	USFIELD_QUOTA (1 << 3)
2354#define	USFIELD_ALL (USFIELD_TYPE | USFIELD_NAME | USFIELD_USED | USFIELD_QUOTA)
2355
2356static int
2357parsefields(unsigned *fieldsp, char **names, unsigned *bits, size_t len)
2358{
2359	char *field = optarg;
2360	char *delim;
2361
2362	do {
2363		int i;
2364		boolean_t found = B_FALSE;
2365		delim = strchr(field, ',');
2366		if (delim != NULL)
2367			*delim = '\0';
2368
2369		for (i = 0; i < len; i++)
2370			if (0 == strcmp(field, names[i])) {
2371				found = B_TRUE;
2372				*fieldsp |= bits[i];
2373				break;
2374			}
2375
2376		if (!found) {
2377			(void) fprintf(stderr, gettext("invalid type '%s'"
2378			    "for -t option\n"), field);
2379			return (-1);
2380		}
2381
2382		field = delim + 1;
2383	} while (delim);
2384
2385	return (0);
2386}
2387
2388
2389static char *type_names[] = { "posixuser", "smbuser", "posixgroup", "smbgroup",
2390	"all" };
2391static unsigned type_bits[] = {
2392	USTYPE_PSX_USR,
2393	USTYPE_SMB_USR,
2394	USTYPE_PSX_GRP,
2395	USTYPE_SMB_GRP,
2396	USTYPE_ALL
2397};
2398
2399static char *us_field_names[] = { "type", "name", "used", "quota" };
2400static unsigned us_field_bits[] = {
2401	USFIELD_TYPE,
2402	USFIELD_NAME,
2403	USFIELD_USED,
2404	USFIELD_QUOTA
2405};
2406
2407static void
2408print_us_node(boolean_t scripted, boolean_t parseable, unsigned fields,
2409		size_t type_width, size_t name_width, size_t used_width,
2410		size_t quota_width, us_node_t *node)
2411{
2412	nvlist_t *nvl = node->usn_nvl;
2413	nvpair_t *nvp = NULL;
2414	char valstr[ZFS_MAXNAMELEN];
2415	boolean_t first = B_TRUE;
2416	boolean_t quota_found = B_FALSE;
2417
2418	if (fields & USFIELD_QUOTA && !nvlist_exists(nvl, "quota"))
2419		if (nvlist_add_string(nvl, "quota", "none") != 0)
2420			nomem();
2421
2422	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2423		char *pname = nvpair_name(nvp);
2424		data_type_t type = nvpair_type(nvp);
2425		uint32_t val32 = 0;
2426		uint64_t val64 = 0;
2427		char *strval = NULL;
2428		unsigned field = 0;
2429		unsigned width = 0;
2430		int i;
2431		for (i = 0; i < 4; i++) {
2432			if (0 == strcmp(pname, us_field_names[i])) {
2433				field = us_field_bits[i];
2434				break;
2435			}
2436		}
2437
2438		if (!(field & fields))
2439			continue;
2440
2441		switch (type) {
2442		case DATA_TYPE_UINT32:
2443			(void) nvpair_value_uint32(nvp, &val32);
2444			break;
2445		case DATA_TYPE_UINT64:
2446			(void) nvpair_value_uint64(nvp, &val64);
2447			break;
2448		case DATA_TYPE_STRING:
2449			(void) nvpair_value_string(nvp, &strval);
2450			break;
2451		default:
2452			(void) fprintf(stderr, "Invalid data type\n");
2453		}
2454
2455		if (!first)
2456			if (scripted)
2457				(void) printf("\t");
2458			else
2459				(void) printf("  ");
2460
2461		switch (field) {
2462		case USFIELD_TYPE:
2463			strval = (char *)us_type2str(val32);
2464			width = type_width;
2465			break;
2466		case USFIELD_NAME:
2467			if (type == DATA_TYPE_UINT64) {
2468				(void) sprintf(valstr, "%llu", val64);
2469				strval = valstr;
2470			}
2471			width = name_width;
2472			break;
2473		case USFIELD_USED:
2474		case USFIELD_QUOTA:
2475			if (type == DATA_TYPE_UINT64) {
2476				(void) nvpair_value_uint64(nvp, &val64);
2477				if (parseable)
2478					(void) sprintf(valstr, "%llu", val64);
2479				else
2480					zfs_nicenum(val64, valstr,
2481					    sizeof (valstr));
2482				strval = valstr;
2483			}
2484
2485			if (field == USFIELD_USED)
2486				width = used_width;
2487			else {
2488				quota_found = B_FALSE;
2489				width = quota_width;
2490			}
2491
2492			break;
2493		}
2494
2495		if (field == USFIELD_QUOTA && !quota_found)
2496			(void) printf("%*s", width, strval);
2497		else {
2498			if (type == DATA_TYPE_STRING)
2499				(void) printf("%-*s", width, strval);
2500			else
2501				(void) printf("%*s", width, strval);
2502		}
2503
2504		first = B_FALSE;
2505
2506	}
2507
2508	(void) printf("\n");
2509}
2510
2511static void
2512print_us(boolean_t scripted, boolean_t parsable, unsigned fields,
2513		unsigned type_width, unsigned name_width, unsigned used_width,
2514		unsigned quota_width, boolean_t rmnode, uu_avl_t *avl)
2515{
2516	static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2517	us_node_t *node;
2518	const char *col;
2519	int i;
2520	size_t width[4] = { type_width, name_width, used_width, quota_width };
2521
2522	if (!scripted) {
2523		boolean_t first = B_TRUE;
2524		for (i = 0; i < 4; i++) {
2525			unsigned field = us_field_bits[i];
2526			if (!(field & fields))
2527				continue;
2528
2529			col = gettext(us_field_hdr[i]);
2530			if (field == USFIELD_TYPE || field == USFIELD_NAME)
2531				(void) printf(first?"%-*s":"  %-*s", width[i],
2532				    col);
2533			else
2534				(void) printf(first?"%*s":"  %*s", width[i],
2535				    col);
2536			first = B_FALSE;
2537		}
2538		(void) printf("\n");
2539	}
2540
2541	for (node = uu_avl_first(avl); node != NULL;
2542	    node = uu_avl_next(avl, node)) {
2543		print_us_node(scripted, parsable, fields, type_width,
2544		    name_width, used_width, used_width, node);
2545		if (rmnode)
2546			nvlist_free(node->usn_nvl);
2547	}
2548}
2549
2550static int
2551zfs_do_userspace(int argc, char **argv)
2552{
2553	zfs_handle_t *zhp;
2554	zfs_userquota_prop_t p;
2555
2556	uu_avl_pool_t *avl_pool;
2557	uu_avl_t *avl_tree;
2558	uu_avl_walk_t *walk;
2559
2560	char *cmd;
2561	boolean_t scripted = B_FALSE;
2562	boolean_t prtnum = B_FALSE;
2563	boolean_t parseable = B_FALSE;
2564	boolean_t sid2posix = B_FALSE;
2565	int error;
2566	int c;
2567	zfs_sort_column_t *default_sortcol = NULL;
2568	zfs_sort_column_t *sortcol = NULL;
2569	unsigned types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2570	unsigned fields = 0;
2571	unsigned props = USPROP_USED | USPROP_QUOTA;
2572	us_cbdata_t cb;
2573	us_node_t *node;
2574	boolean_t resort_avl = B_FALSE;
2575
2576	if (argc < 2)
2577		usage(B_FALSE);
2578
2579	cmd = argv[0];
2580	if (0 == strcmp(cmd, "groupspace"))
2581		/* toggle default group types */
2582		types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2583
2584	/* check options */
2585	while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2586		switch (c) {
2587		case 'n':
2588			prtnum = B_TRUE;
2589			break;
2590		case 'H':
2591			scripted = B_TRUE;
2592			break;
2593		case 'p':
2594			parseable = B_TRUE;
2595			break;
2596		case 'o':
2597			if (parsefields(&fields, us_field_names, us_field_bits,
2598			    4) != 0)
2599				return (1);
2600			break;
2601		case 's':
2602			if (zfs_add_sort_column(&sortcol, optarg,
2603			    B_FALSE) != 0) {
2604				(void) fprintf(stderr,
2605				    gettext("invalid property '%s'\n"), optarg);
2606				usage(B_FALSE);
2607			}
2608			break;
2609		case 'S':
2610			if (zfs_add_sort_column(&sortcol, optarg,
2611			    B_TRUE) != 0) {
2612				(void) fprintf(stderr,
2613				    gettext("invalid property '%s'\n"), optarg);
2614				usage(B_FALSE);
2615			}
2616			break;
2617		case 't':
2618			if (parsefields(&types, type_names, type_bits, 5))
2619				return (1);
2620			break;
2621		case 'i':
2622			sid2posix = B_TRUE;
2623			break;
2624		case ':':
2625			(void) fprintf(stderr, gettext("missing argument for "
2626			    "'%c' option\n"), optopt);
2627			usage(B_FALSE);
2628			break;
2629		case '?':
2630			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2631			    optopt);
2632			usage(B_FALSE);
2633		}
2634	}
2635
2636	argc -= optind;
2637	argv += optind;
2638
2639	/* ok, now we have sorted by default colums (type,name) avl tree */
2640	if (sortcol) {
2641		zfs_sort_column_t *sc;
2642		for (sc = sortcol; sc; sc = sc->sc_next) {
2643			if (sc->sc_prop == ZFS_PROP_QUOTA) {
2644				resort_avl = B_TRUE;
2645				break;
2646			}
2647		}
2648	}
2649
2650	if (!fields)
2651		fields = USFIELD_ALL;
2652
2653	if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
2654		return (1);
2655
2656	if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2657	    offsetof(us_node_t, usn_avlnode),
2658	    us_compare, UU_DEFAULT)) == NULL)
2659		nomem();
2660	if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2661		nomem();
2662
2663	if (sortcol && !resort_avl)
2664		cb.cb_sortcol = sortcol;
2665	else {
2666		(void) zfs_add_sort_column(&default_sortcol, "type", B_FALSE);
2667		(void) zfs_add_sort_column(&default_sortcol, "name", B_FALSE);
2668		cb.cb_sortcol = default_sortcol;
2669	}
2670	cb.cb_numname = prtnum;
2671	cb.cb_nicenum = !parseable;
2672	cb.cb_avl_pool = avl_pool;
2673	cb.cb_avl = avl_tree;
2674	cb.cb_sid2posix = sid2posix;
2675	cb.cb_max_typelen = strlen(gettext("TYPE"));
2676	cb.cb_max_namelen = strlen(gettext("NAME"));
2677	cb.cb_max_usedlen = strlen(gettext("USED"));
2678	cb.cb_max_quotalen = strlen(gettext("QUOTA"));
2679
2680	for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2681		if (!usprop_check(p, types, props))
2682			continue;
2683
2684		cb.cb_prop = p;
2685		error = zfs_userspace(zhp, p, userspace_cb, &cb);
2686
2687		if (error)
2688			break;
2689	}
2690
2691	if (resort_avl) {
2692		us_node_t *node;
2693		us_node_t *rmnode;
2694		uu_list_pool_t *listpool;
2695		uu_list_t *list;
2696		uu_avl_index_t idx = 0;
2697		uu_list_index_t idx2 = 0;
2698		listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2699		    offsetof(us_node_t, usn_listnode), NULL,
2700		    UU_DEFAULT);
2701		list = uu_list_create(listpool, NULL, UU_DEFAULT);
2702
2703		node = uu_avl_first(avl_tree);
2704		uu_list_node_init(node, &node->usn_listnode, listpool);
2705		while (node != NULL) {
2706			rmnode = node;
2707			node = uu_avl_next(avl_tree, node);
2708			uu_avl_remove(avl_tree, rmnode);
2709			if (uu_list_find(list, rmnode, NULL, &idx2) == NULL) {
2710				uu_list_insert(list, rmnode, idx2);
2711			}
2712		}
2713
2714		for (node = uu_list_first(list); node != NULL;
2715		    node = uu_list_next(list, node)) {
2716			us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2717			if (uu_avl_find(avl_tree, node, &sortinfo, &idx) ==
2718			    NULL)
2719			uu_avl_insert(avl_tree, node, idx);
2720		}
2721
2722		uu_list_destroy(list);
2723	}
2724
2725	/* print & free node`s nvlist memory */
2726	print_us(scripted, parseable, fields, cb.cb_max_typelen,
2727	    cb.cb_max_namelen, cb.cb_max_usedlen,
2728	    cb.cb_max_quotalen, B_TRUE, cb.cb_avl);
2729
2730	if (sortcol)
2731		zfs_free_sort_columns(sortcol);
2732	zfs_free_sort_columns(default_sortcol);
2733
2734	/*
2735	 * Finally, clean up the AVL tree.
2736	 */
2737	if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2738		nomem();
2739
2740	while ((node = uu_avl_walk_next(walk)) != NULL) {
2741		uu_avl_remove(cb.cb_avl, node);
2742		free(node);
2743	}
2744
2745	uu_avl_walk_end(walk);
2746	uu_avl_destroy(avl_tree);
2747	uu_avl_pool_destroy(avl_pool);
2748
2749	return (error);
2750}
2751
2752/*
2753 * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
2754 *      [-s property [-s property]...] [-S property [-S property]...]
2755 *      <dataset> ...
2756 *
2757 *	-r	Recurse over all children
2758 *	-d	Limit recursion by depth.
2759 *	-H	Scripted mode; elide headers and separate columns by tabs
2760 *	-o	Control which fields to display.
2761 *	-t	Control which object types to display.
2762 *	-s	Specify sort columns, descending order.
2763 *	-S	Specify sort columns, ascending order.
2764 *
2765 * When given no arguments, lists all filesystems in the system.
2766 * Otherwise, list the specified datasets, optionally recursing down them if
2767 * '-r' is specified.
2768 */
2769typedef struct list_cbdata {
2770	boolean_t	cb_first;
2771	boolean_t	cb_scripted;
2772	zprop_list_t	*cb_proplist;
2773} list_cbdata_t;
2774
2775/*
2776 * Given a list of columns to display, output appropriate headers for each one.
2777 */
2778static void
2779print_header(zprop_list_t *pl)
2780{
2781	char headerbuf[ZFS_MAXPROPLEN];
2782	const char *header;
2783	int i;
2784	boolean_t first = B_TRUE;
2785	boolean_t right_justify;
2786
2787	for (; pl != NULL; pl = pl->pl_next) {
2788		if (!first) {
2789			(void) printf("  ");
2790		} else {
2791			first = B_FALSE;
2792		}
2793
2794		right_justify = B_FALSE;
2795		if (pl->pl_prop != ZPROP_INVAL) {
2796			header = zfs_prop_column_name(pl->pl_prop);
2797			right_justify = zfs_prop_align_right(pl->pl_prop);
2798		} else {
2799			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2800				headerbuf[i] = toupper(pl->pl_user_prop[i]);
2801			headerbuf[i] = '\0';
2802			header = headerbuf;
2803		}
2804
2805		if (pl->pl_next == NULL && !right_justify)
2806			(void) printf("%s", header);
2807		else if (right_justify)
2808			(void) printf("%*s", pl->pl_width, header);
2809		else
2810			(void) printf("%-*s", pl->pl_width, header);
2811	}
2812
2813	(void) printf("\n");
2814}
2815
2816/*
2817 * Given a dataset and a list of fields, print out all the properties according
2818 * to the described layout.
2819 */
2820static void
2821print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
2822{
2823	boolean_t first = B_TRUE;
2824	char property[ZFS_MAXPROPLEN];
2825	nvlist_t *userprops = zfs_get_user_props(zhp);
2826	nvlist_t *propval;
2827	char *propstr;
2828	boolean_t right_justify;
2829	int width;
2830
2831	for (; pl != NULL; pl = pl->pl_next) {
2832		if (!first) {
2833			if (scripted)
2834				(void) printf("\t");
2835			else
2836				(void) printf("  ");
2837		} else {
2838			first = B_FALSE;
2839		}
2840
2841		if (pl->pl_prop == ZFS_PROP_NAME) {
2842			(void) strlcpy(property, zfs_get_name(zhp),
2843			    sizeof(property));
2844			propstr = property;
2845			right_justify = zfs_prop_align_right(pl->pl_prop);
2846		} else if (pl->pl_prop != ZPROP_INVAL) {
2847			if (zfs_prop_get(zhp, pl->pl_prop, property,
2848			    sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
2849				propstr = "-";
2850			else
2851				propstr = property;
2852
2853			right_justify = zfs_prop_align_right(pl->pl_prop);
2854		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
2855			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2856			    property, sizeof (property), B_FALSE) != 0)
2857				propstr = "-";
2858			else
2859				propstr = property;
2860			right_justify = B_TRUE;
2861		} else if (zfs_prop_written(pl->pl_user_prop)) {
2862			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2863			    property, sizeof (property), B_FALSE) != 0)
2864				propstr = "-";
2865			else
2866				propstr = property;
2867			right_justify = B_TRUE;
2868		} else {
2869			if (nvlist_lookup_nvlist(userprops,
2870			    pl->pl_user_prop, &propval) != 0)
2871				propstr = "-";
2872			else
2873				verify(nvlist_lookup_string(propval,
2874				    ZPROP_VALUE, &propstr) == 0);
2875			right_justify = B_FALSE;
2876		}
2877
2878		width = pl->pl_width;
2879
2880		/*
2881		 * If this is being called in scripted mode, or if this is the
2882		 * last column and it is left-justified, don't include a width
2883		 * format specifier.
2884		 */
2885		if (scripted || (pl->pl_next == NULL && !right_justify))
2886			(void) printf("%s", propstr);
2887		else if (right_justify)
2888			(void) printf("%*s", width, propstr);
2889		else
2890			(void) printf("%-*s", width, propstr);
2891	}
2892
2893	(void) printf("\n");
2894}
2895
2896/*
2897 * Generic callback function to list a dataset or snapshot.
2898 */
2899static int
2900list_callback(zfs_handle_t *zhp, void *data)
2901{
2902	list_cbdata_t *cbp = data;
2903
2904	if (cbp->cb_first) {
2905		if (!cbp->cb_scripted)
2906			print_header(cbp->cb_proplist);
2907		cbp->cb_first = B_FALSE;
2908	}
2909
2910	print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2911
2912	return (0);
2913}
2914
2915static int
2916zfs_do_list(int argc, char **argv)
2917{
2918	int c;
2919	boolean_t scripted = B_FALSE;
2920	static char default_fields[] =
2921	    "name,used,available,referenced,mountpoint";
2922	int types = ZFS_TYPE_DATASET;
2923	boolean_t types_specified = B_FALSE;
2924	char *fields = NULL;
2925	list_cbdata_t cb = { 0 };
2926	char *value;
2927	int limit = 0;
2928	int ret;
2929	zfs_sort_column_t *sortcol = NULL;
2930	int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2931
2932	/* check options */
2933	while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2934		switch (c) {
2935		case 'o':
2936			fields = optarg;
2937			break;
2938		case 'd':
2939			limit = parse_depth(optarg, &flags);
2940			break;
2941		case 'r':
2942			flags |= ZFS_ITER_RECURSE;
2943			break;
2944		case 'H':
2945			scripted = B_TRUE;
2946			break;
2947		case 's':
2948			if (zfs_add_sort_column(&sortcol, optarg,
2949			    B_FALSE) != 0) {
2950				(void) fprintf(stderr,
2951				    gettext("invalid property '%s'\n"), optarg);
2952				usage(B_FALSE);
2953			}
2954			break;
2955		case 'S':
2956			if (zfs_add_sort_column(&sortcol, optarg,
2957			    B_TRUE) != 0) {
2958				(void) fprintf(stderr,
2959				    gettext("invalid property '%s'\n"), optarg);
2960				usage(B_FALSE);
2961			}
2962			break;
2963		case 't':
2964			types = 0;
2965			types_specified = B_TRUE;
2966			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2967			while (*optarg != '\0') {
2968				static char *type_subopts[] = { "filesystem",
2969				    "volume", "snapshot", "all", NULL };
2970
2971				switch (getsubopt(&optarg, type_subopts,
2972				    &value)) {
2973				case 0:
2974					types |= ZFS_TYPE_FILESYSTEM;
2975					break;
2976				case 1:
2977					types |= ZFS_TYPE_VOLUME;
2978					break;
2979				case 2:
2980					types |= ZFS_TYPE_SNAPSHOT;
2981					break;
2982				case 3:
2983					types = ZFS_TYPE_DATASET;
2984					break;
2985
2986				default:
2987					(void) fprintf(stderr,
2988					    gettext("invalid type '%s'\n"),
2989					    value);
2990					usage(B_FALSE);
2991				}
2992			}
2993			break;
2994		case ':':
2995			(void) fprintf(stderr, gettext("missing argument for "
2996			    "'%c' option\n"), optopt);
2997			usage(B_FALSE);
2998			break;
2999		case '?':
3000			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3001			    optopt);
3002			usage(B_FALSE);
3003		}
3004	}
3005
3006	argc -= optind;
3007	argv += optind;
3008
3009	if (fields == NULL)
3010		fields = default_fields;
3011
3012	/*
3013	 * If we are only going to list snapshot names and sort by name,
3014	 * then we can use faster version.
3015	 */
3016	if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3017		flags |= ZFS_ITER_SIMPLE;
3018
3019	/*
3020	 * If "-o space" and no types were specified, don't display snapshots.
3021	 */
3022	if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3023		types &= ~ZFS_TYPE_SNAPSHOT;
3024
3025	/*
3026	 * If the user specifies '-o all', the zprop_get_list() doesn't
3027	 * normally include the name of the dataset.  For 'zfs list', we always
3028	 * want this property to be first.
3029	 */
3030	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3031	    != 0)
3032		usage(B_FALSE);
3033
3034	cb.cb_scripted = scripted;
3035	cb.cb_first = B_TRUE;
3036
3037	ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3038	    limit, list_callback, &cb);
3039
3040	zprop_free_list(cb.cb_proplist);
3041	zfs_free_sort_columns(sortcol);
3042
3043	if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3044		(void) printf(gettext("no datasets available\n"));
3045
3046	return (ret);
3047}
3048
3049/*
3050 * zfs rename <fs | snap | vol> <fs | snap | vol>
3051 * zfs rename -p <fs | vol> <fs | vol>
3052 * zfs rename -r <snap> <snap>
3053 * zfs rename -u [-p] <fs> <fs>
3054 *
3055 * Renames the given dataset to another of the same type.
3056 *
3057 * The '-p' flag creates all the non-existing ancestors of the target first.
3058 */
3059/* ARGSUSED */
3060static int
3061zfs_do_rename(int argc, char **argv)
3062{
3063	zfs_handle_t *zhp;
3064	renameflags_t flags = { 0 };
3065	int c, ret, types;
3066	boolean_t parents = B_FALSE;
3067
3068	/* check options */
3069	while ((c = getopt(argc, argv, "pru")) != -1) {
3070		switch (c) {
3071		case 'p':
3072			parents = B_TRUE;
3073			break;
3074		case 'r':
3075			flags.recurse = B_TRUE;
3076			break;
3077		case 'u':
3078			flags.nounmount = B_TRUE;
3079			break;
3080		case '?':
3081		default:
3082			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3083			    optopt);
3084			usage(B_FALSE);
3085		}
3086	}
3087
3088	argc -= optind;
3089	argv += optind;
3090
3091	/* check number of arguments */
3092	if (argc < 1) {
3093		(void) fprintf(stderr, gettext("missing source dataset "
3094		    "argument\n"));
3095		usage(B_FALSE);
3096	}
3097	if (argc < 2) {
3098		(void) fprintf(stderr, gettext("missing target dataset "
3099		    "argument\n"));
3100		usage(B_FALSE);
3101	}
3102	if (argc > 2) {
3103		(void) fprintf(stderr, gettext("too many arguments\n"));
3104		usage(B_FALSE);
3105	}
3106
3107	if (flags.recurse && parents) {
3108		(void) fprintf(stderr, gettext("-p and -r options are mutually "
3109		    "exclusive\n"));
3110		usage(B_FALSE);
3111	}
3112
3113	if (flags.recurse && strchr(argv[0], '@') == 0) {
3114		(void) fprintf(stderr, gettext("source dataset for recursive "
3115		    "rename must be a snapshot\n"));
3116		usage(B_FALSE);
3117	}
3118
3119	if (flags.nounmount && parents) {
3120		(void) fprintf(stderr, gettext("-u and -r options are mutually "
3121		    "exclusive\n"));
3122		usage(B_FALSE);
3123	}
3124
3125	if (flags.nounmount)
3126		types = ZFS_TYPE_FILESYSTEM;
3127	else if (parents)
3128		types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3129	else
3130		types = ZFS_TYPE_DATASET;
3131
3132	if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3133		return (1);
3134
3135	/* If we were asked and the name looks good, try to create ancestors. */
3136	if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3137	    zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3138		zfs_close(zhp);
3139		return (1);
3140	}
3141
3142	ret = (zfs_rename(zhp, argv[1], flags) != 0);
3143
3144	zfs_close(zhp);
3145	return (ret);
3146}
3147
3148/*
3149 * zfs promote <fs>
3150 *
3151 * Promotes the given clone fs to be the parent
3152 */
3153/* ARGSUSED */
3154static int
3155zfs_do_promote(int argc, char **argv)
3156{
3157	zfs_handle_t *zhp;
3158	int ret;
3159
3160	/* check options */
3161	if (argc > 1 && argv[1][0] == '-') {
3162		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3163		    argv[1][1]);
3164		usage(B_FALSE);
3165	}
3166
3167	/* check number of arguments */
3168	if (argc < 2) {
3169		(void) fprintf(stderr, gettext("missing clone filesystem"
3170		    " argument\n"));
3171		usage(B_FALSE);
3172	}
3173	if (argc > 2) {
3174		(void) fprintf(stderr, gettext("too many arguments\n"));
3175		usage(B_FALSE);
3176	}
3177
3178	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3179	if (zhp == NULL)
3180		return (1);
3181
3182	ret = (zfs_promote(zhp) != 0);
3183
3184
3185	zfs_close(zhp);
3186	return (ret);
3187}
3188
3189/*
3190 * zfs rollback [-rRf] <snapshot>
3191 *
3192 *	-r	Delete any intervening snapshots before doing rollback
3193 *	-R	Delete any snapshots and their clones
3194 *	-f	ignored for backwards compatability
3195 *
3196 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3197 * since then and making it the active dataset.  If more recent snapshots exist,
3198 * the command will complain unless the '-r' flag is given.
3199 */
3200typedef struct rollback_cbdata {
3201	uint64_t	cb_create;
3202	boolean_t	cb_first;
3203	int		cb_doclones;
3204	char		*cb_target;
3205	int		cb_error;
3206	boolean_t	cb_recurse;
3207	boolean_t	cb_dependent;
3208} rollback_cbdata_t;
3209
3210/*
3211 * Report any snapshots more recent than the one specified.  Used when '-r' is
3212 * not specified.  We reuse this same callback for the snapshot dependents - if
3213 * 'cb_dependent' is set, then this is a dependent and we should report it
3214 * without checking the transaction group.
3215 */
3216static int
3217rollback_check(zfs_handle_t *zhp, void *data)
3218{
3219	rollback_cbdata_t *cbp = data;
3220
3221	if (cbp->cb_doclones) {
3222		zfs_close(zhp);
3223		return (0);
3224	}
3225
3226	if (!cbp->cb_dependent) {
3227		if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
3228		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3229		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3230		    cbp->cb_create) {
3231
3232			if (cbp->cb_first && !cbp->cb_recurse) {
3233				(void) fprintf(stderr, gettext("cannot "
3234				    "rollback to '%s': more recent snapshots "
3235				    "exist\n"),
3236				    cbp->cb_target);
3237				(void) fprintf(stderr, gettext("use '-r' to "
3238				    "force deletion of the following "
3239				    "snapshots:\n"));
3240				cbp->cb_first = 0;
3241				cbp->cb_error = 1;
3242			}
3243
3244			if (cbp->cb_recurse) {
3245				cbp->cb_dependent = B_TRUE;
3246				if (zfs_iter_dependents(zhp, B_TRUE,
3247				    rollback_check, cbp) != 0) {
3248					zfs_close(zhp);
3249					return (-1);
3250				}
3251				cbp->cb_dependent = B_FALSE;
3252			} else {
3253				(void) fprintf(stderr, "%s\n",
3254				    zfs_get_name(zhp));
3255			}
3256		}
3257	} else {
3258		if (cbp->cb_first && cbp->cb_recurse) {
3259			(void) fprintf(stderr, gettext("cannot rollback to "
3260			    "'%s': clones of previous snapshots exist\n"),
3261			    cbp->cb_target);
3262			(void) fprintf(stderr, gettext("use '-R' to "
3263			    "force deletion of the following clones and "
3264			    "dependents:\n"));
3265			cbp->cb_first = 0;
3266			cbp->cb_error = 1;
3267		}
3268
3269		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3270	}
3271
3272	zfs_close(zhp);
3273	return (0);
3274}
3275
3276static int
3277zfs_do_rollback(int argc, char **argv)
3278{
3279	int ret;
3280	int c;
3281	boolean_t force = B_FALSE;
3282	rollback_cbdata_t cb = { 0 };
3283	zfs_handle_t *zhp, *snap;
3284	char parentname[ZFS_MAXNAMELEN];
3285	char *delim;
3286
3287	/* check options */
3288	while ((c = getopt(argc, argv, "rRf")) != -1) {
3289		switch (c) {
3290		case 'r':
3291			cb.cb_recurse = 1;
3292			break;
3293		case 'R':
3294			cb.cb_recurse = 1;
3295			cb.cb_doclones = 1;
3296			break;
3297		case 'f':
3298			force = B_TRUE;
3299			break;
3300		case '?':
3301			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3302			    optopt);
3303			usage(B_FALSE);
3304		}
3305	}
3306
3307	argc -= optind;
3308	argv += optind;
3309
3310	/* check number of arguments */
3311	if (argc < 1) {
3312		(void) fprintf(stderr, gettext("missing dataset argument\n"));
3313		usage(B_FALSE);
3314	}
3315	if (argc > 1) {
3316		(void) fprintf(stderr, gettext("too many arguments\n"));
3317		usage(B_FALSE);
3318	}
3319
3320	/* open the snapshot */
3321	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3322		return (1);
3323
3324	/* open the parent dataset */
3325	(void) strlcpy(parentname, argv[0], sizeof (parentname));
3326	verify((delim = strrchr(parentname, '@')) != NULL);
3327	*delim = '\0';
3328	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3329		zfs_close(snap);
3330		return (1);
3331	}
3332
3333	/*
3334	 * Check for more recent snapshots and/or clones based on the presence
3335	 * of '-r' and '-R'.
3336	 */
3337	cb.cb_target = argv[0];
3338	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3339	cb.cb_first = B_TRUE;
3340	cb.cb_error = 0;
3341	if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
3342		goto out;
3343
3344	if ((ret = cb.cb_error) != 0)
3345		goto out;
3346
3347	/*
3348	 * Rollback parent to the given snapshot.
3349	 */
3350	ret = zfs_rollback(zhp, snap, force);
3351
3352out:
3353	zfs_close(snap);
3354	zfs_close(zhp);
3355
3356	if (ret == 0)
3357		return (0);
3358	else
3359		return (1);
3360}
3361
3362/*
3363 * zfs set property=value { fs | snap | vol } ...
3364 *
3365 * Sets the given property for all datasets specified on the command line.
3366 */
3367typedef struct set_cbdata {
3368	char		*cb_propname;
3369	char		*cb_value;
3370} set_cbdata_t;
3371
3372static int
3373set_callback(zfs_handle_t *zhp, void *data)
3374{
3375	set_cbdata_t *cbp = data;
3376
3377	if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
3378		switch (libzfs_errno(g_zfs)) {
3379		case EZFS_MOUNTFAILED:
3380			(void) fprintf(stderr, gettext("property may be set "
3381			    "but unable to remount filesystem\n"));
3382			break;
3383		case EZFS_SHARENFSFAILED:
3384			(void) fprintf(stderr, gettext("property may be set "
3385			    "but unable to reshare filesystem\n"));
3386			break;
3387		}
3388		return (1);
3389	}
3390	return (0);
3391}
3392
3393static int
3394zfs_do_set(int argc, char **argv)
3395{
3396	set_cbdata_t cb;
3397	int ret;
3398
3399	/* check for options */
3400	if (argc > 1 && argv[1][0] == '-') {
3401		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3402		    argv[1][1]);
3403		usage(B_FALSE);
3404	}
3405
3406	/* check number of arguments */
3407	if (argc < 2) {
3408		(void) fprintf(stderr, gettext("missing property=value "
3409		    "argument\n"));
3410		usage(B_FALSE);
3411	}
3412	if (argc < 3) {
3413		(void) fprintf(stderr, gettext("missing dataset name\n"));
3414		usage(B_FALSE);
3415	}
3416
3417	/* validate property=value argument */
3418	cb.cb_propname = argv[1];
3419	if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
3420	    (cb.cb_value[1] == '\0')) {
3421		(void) fprintf(stderr, gettext("missing value in "
3422		    "property=value argument\n"));
3423		usage(B_FALSE);
3424	}
3425
3426	*cb.cb_value = '\0';
3427	cb.cb_value++;
3428
3429	if (*cb.cb_propname == '\0') {
3430		(void) fprintf(stderr,
3431		    gettext("missing property in property=value argument\n"));
3432		usage(B_FALSE);
3433	}
3434
3435	ret = zfs_for_each(argc - 2, argv + 2, 0,
3436	    ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
3437
3438	return (ret);
3439}
3440
3441/*
3442 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3443 *
3444 * Creates a snapshot with the given name.  While functionally equivalent to
3445 * 'zfs create', it is a separate command to differentiate intent.
3446 */
3447static int
3448zfs_do_snapshot(int argc, char **argv)
3449{
3450	boolean_t recursive = B_FALSE;
3451	int ret;
3452	char c;
3453	nvlist_t *props;
3454
3455	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3456		nomem();
3457
3458	/* check options */
3459	while ((c = getopt(argc, argv, "ro:")) != -1) {
3460		switch (c) {
3461		case 'o':
3462			if (parseprop(props))
3463				return (1);
3464			break;
3465		case 'r':
3466			recursive = B_TRUE;
3467			break;
3468		case '?':
3469			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3470			    optopt);
3471			goto usage;
3472		}
3473	}
3474
3475	argc -= optind;
3476	argv += optind;
3477
3478	/* check number of arguments */
3479	if (argc < 1) {
3480		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3481		goto usage;
3482	}
3483	if (argc > 1) {
3484		(void) fprintf(stderr, gettext("too many arguments\n"));
3485		goto usage;
3486	}
3487
3488	ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
3489	nvlist_free(props);
3490	if (ret && recursive)
3491		(void) fprintf(stderr, gettext("no snapshots were created\n"));
3492	return (ret != 0);
3493
3494usage:
3495	nvlist_free(props);
3496	usage(B_FALSE);
3497	return (-1);
3498}
3499
3500/*
3501 * Send a backup stream to stdout.
3502 */
3503static int
3504zfs_do_send(int argc, char **argv)
3505{
3506	char *fromname = NULL;
3507	char *toname = NULL;
3508	char *cp;
3509	zfs_handle_t *zhp;
3510	sendflags_t flags = { 0 };
3511	int c, err;
3512	nvlist_t *dbgnv = NULL;
3513	boolean_t extraverbose = B_FALSE;
3514
3515	/* check options */
3516	while ((c = getopt(argc, argv, ":i:I:RDpvnP")) != -1) {
3517		switch (c) {
3518		case 'i':
3519			if (fromname)
3520				usage(B_FALSE);
3521			fromname = optarg;
3522			break;
3523		case 'I':
3524			if (fromname)
3525				usage(B_FALSE);
3526			fromname = optarg;
3527			flags.doall = B_TRUE;
3528			break;
3529		case 'R':
3530			flags.replicate = B_TRUE;
3531			break;
3532		case 'p':
3533			flags.props = B_TRUE;
3534			break;
3535		case 'P':
3536			flags.parsable = B_TRUE;
3537			flags.verbose = B_TRUE;
3538			break;
3539		case 'v':
3540			if (flags.verbose)
3541				extraverbose = B_TRUE;
3542			flags.verbose = B_TRUE;
3543			break;
3544		case 'D':
3545			flags.dedup = B_TRUE;
3546			break;
3547		case 'n':
3548			flags.dryrun = B_TRUE;
3549			break;
3550		case ':':
3551			(void) fprintf(stderr, gettext("missing argument for "
3552			    "'%c' option\n"), optopt);
3553			usage(B_FALSE);
3554			break;
3555		case '?':
3556			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3557			    optopt);
3558			usage(B_FALSE);
3559		}
3560	}
3561
3562	argc -= optind;
3563	argv += optind;
3564
3565	/* check number of arguments */
3566	if (argc < 1) {
3567		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3568		usage(B_FALSE);
3569	}
3570	if (argc > 1) {
3571		(void) fprintf(stderr, gettext("too many arguments\n"));
3572		usage(B_FALSE);
3573	}
3574
3575	if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3576		(void) fprintf(stderr,
3577		    gettext("Error: Stream can not be written to a terminal.\n"
3578		    "You must redirect standard output.\n"));
3579		return (1);
3580	}
3581
3582	cp = strchr(argv[0], '@');
3583	if (cp == NULL) {
3584		(void) fprintf(stderr,
3585		    gettext("argument must be a snapshot\n"));
3586		usage(B_FALSE);
3587	}
3588	*cp = '\0';
3589	toname = cp + 1;
3590	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3591	if (zhp == NULL)
3592		return (1);
3593
3594	/*
3595	 * If they specified the full path to the snapshot, chop off
3596	 * everything except the short name of the snapshot, but special
3597	 * case if they specify the origin.
3598	 */
3599	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3600		char origin[ZFS_MAXNAMELEN];
3601		zprop_source_t src;
3602
3603		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3604		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3605
3606		if (strcmp(origin, fromname) == 0) {
3607			fromname = NULL;
3608			flags.fromorigin = B_TRUE;
3609		} else {
3610			*cp = '\0';
3611			if (cp != fromname && strcmp(argv[0], fromname)) {
3612				(void) fprintf(stderr,
3613				    gettext("incremental source must be "
3614				    "in same filesystem\n"));
3615				usage(B_FALSE);
3616			}
3617			fromname = cp + 1;
3618			if (strchr(fromname, '@') || strchr(fromname, '/')) {
3619				(void) fprintf(stderr,
3620				    gettext("invalid incremental source\n"));
3621				usage(B_FALSE);
3622			}
3623		}
3624	}
3625
3626	if (flags.replicate && fromname == NULL)
3627		flags.doall = B_TRUE;
3628
3629	err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3630	    extraverbose ? &dbgnv : NULL);
3631
3632	if (extraverbose && dbgnv != NULL) {
3633		/*
3634		 * dump_nvlist prints to stdout, but that's been
3635		 * redirected to a file.  Make it print to stderr
3636		 * instead.
3637		 */
3638		(void) dup2(STDERR_FILENO, STDOUT_FILENO);
3639		dump_nvlist(dbgnv, 0);
3640		nvlist_free(dbgnv);
3641	}
3642	zfs_close(zhp);
3643
3644	return (err != 0);
3645}
3646
3647/*
3648 * zfs receive [-vnFu] [-d | -e] <fs@snap>
3649 *
3650 * Restore a backup stream from stdin.
3651 */
3652static int
3653zfs_do_receive(int argc, char **argv)
3654{
3655	int c, err;
3656	recvflags_t flags = { 0 };
3657
3658	/* check options */
3659	while ((c = getopt(argc, argv, ":denuvF")) != -1) {
3660		switch (c) {
3661		case 'd':
3662			flags.isprefix = B_TRUE;
3663			break;
3664		case 'e':
3665			flags.isprefix = B_TRUE;
3666			flags.istail = B_TRUE;
3667			break;
3668		case 'n':
3669			flags.dryrun = B_TRUE;
3670			break;
3671		case 'u':
3672			flags.nomount = B_TRUE;
3673			break;
3674		case 'v':
3675			flags.verbose = B_TRUE;
3676			break;
3677		case 'F':
3678			flags.force = B_TRUE;
3679			break;
3680		case ':':
3681			(void) fprintf(stderr, gettext("missing argument for "
3682			    "'%c' option\n"), optopt);
3683			usage(B_FALSE);
3684			break;
3685		case '?':
3686			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3687			    optopt);
3688			usage(B_FALSE);
3689		}
3690	}
3691
3692	argc -= optind;
3693	argv += optind;
3694
3695	/* check number of arguments */
3696	if (argc < 1) {
3697		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3698		usage(B_FALSE);
3699	}
3700	if (argc > 1) {
3701		(void) fprintf(stderr, gettext("too many arguments\n"));
3702		usage(B_FALSE);
3703	}
3704
3705	if (isatty(STDIN_FILENO)) {
3706		(void) fprintf(stderr,
3707		    gettext("Error: Backup stream can not be read "
3708		    "from a terminal.\n"
3709		    "You must redirect standard input.\n"));
3710		return (1);
3711	}
3712
3713	err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
3714
3715	return (err != 0);
3716}
3717
3718/*
3719 * allow/unallow stuff
3720 */
3721/* copied from zfs/sys/dsl_deleg.h */
3722#define	ZFS_DELEG_PERM_CREATE		"create"
3723#define	ZFS_DELEG_PERM_DESTROY		"destroy"
3724#define	ZFS_DELEG_PERM_SNAPSHOT		"snapshot"
3725#define	ZFS_DELEG_PERM_ROLLBACK		"rollback"
3726#define	ZFS_DELEG_PERM_CLONE		"clone"
3727#define	ZFS_DELEG_PERM_PROMOTE		"promote"
3728#define	ZFS_DELEG_PERM_RENAME		"rename"
3729#define	ZFS_DELEG_PERM_MOUNT		"mount"
3730#define	ZFS_DELEG_PERM_SHARE		"share"
3731#define	ZFS_DELEG_PERM_SEND		"send"
3732#define	ZFS_DELEG_PERM_RECEIVE		"receive"
3733#define	ZFS_DELEG_PERM_ALLOW		"allow"
3734#define	ZFS_DELEG_PERM_USERPROP		"userprop"
3735#define	ZFS_DELEG_PERM_VSCAN		"vscan" /* ??? */
3736#define	ZFS_DELEG_PERM_USERQUOTA	"userquota"
3737#define	ZFS_DELEG_PERM_GROUPQUOTA	"groupquota"
3738#define	ZFS_DELEG_PERM_USERUSED		"userused"
3739#define	ZFS_DELEG_PERM_GROUPUSED	"groupused"
3740#define	ZFS_DELEG_PERM_HOLD		"hold"
3741#define	ZFS_DELEG_PERM_RELEASE		"release"
3742#define	ZFS_DELEG_PERM_DIFF		"diff"
3743
3744#define	ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
3745
3746static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
3747	{ ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
3748	{ ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
3749	{ ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
3750	{ ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
3751	{ ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
3752	{ ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
3753	{ ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
3754	{ ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
3755	{ ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
3756	{ ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
3757	{ ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
3758	{ ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
3759	{ ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
3760	{ ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
3761	{ ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
3762
3763	{ ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
3764	{ ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
3765	{ ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
3766	{ ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
3767	{ ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
3768	{ NULL, ZFS_DELEG_NOTE_NONE }
3769};
3770
3771/* permission structure */
3772typedef struct deleg_perm {
3773	zfs_deleg_who_type_t	dp_who_type;
3774	const char		*dp_name;
3775	boolean_t		dp_local;
3776	boolean_t		dp_descend;
3777} deleg_perm_t;
3778
3779/* */
3780typedef struct deleg_perm_node {
3781	deleg_perm_t		dpn_perm;
3782
3783	uu_avl_node_t		dpn_avl_node;
3784} deleg_perm_node_t;
3785
3786typedef struct fs_perm fs_perm_t;
3787
3788/* permissions set */
3789typedef struct who_perm {
3790	zfs_deleg_who_type_t	who_type;
3791	const char		*who_name;		/* id */
3792	char			who_ug_name[256];	/* user/group name */
3793	fs_perm_t		*who_fsperm;		/* uplink */
3794
3795	uu_avl_t		*who_deleg_perm_avl;	/* permissions */
3796} who_perm_t;
3797
3798/* */
3799typedef struct who_perm_node {
3800	who_perm_t	who_perm;
3801	uu_avl_node_t	who_avl_node;
3802} who_perm_node_t;
3803
3804typedef struct fs_perm_set fs_perm_set_t;
3805/* fs permissions */
3806struct fs_perm {
3807	const char		*fsp_name;
3808
3809	uu_avl_t		*fsp_sc_avl;	/* sets,create */
3810	uu_avl_t		*fsp_uge_avl;	/* user,group,everyone */
3811
3812	fs_perm_set_t		*fsp_set;	/* uplink */
3813};
3814
3815/* */
3816typedef struct fs_perm_node {
3817	fs_perm_t	fspn_fsperm;
3818	uu_avl_t	*fspn_avl;
3819
3820	uu_list_node_t	fspn_list_node;
3821} fs_perm_node_t;
3822
3823/* top level structure */
3824struct fs_perm_set {
3825	uu_list_pool_t	*fsps_list_pool;
3826	uu_list_t	*fsps_list; /* list of fs_perms */
3827
3828	uu_avl_pool_t	*fsps_named_set_avl_pool;
3829	uu_avl_pool_t	*fsps_who_perm_avl_pool;
3830	uu_avl_pool_t	*fsps_deleg_perm_avl_pool;
3831};
3832
3833static inline const char *
3834deleg_perm_type(zfs_deleg_note_t note)
3835{
3836	/* subcommands */
3837	switch (note) {
3838		/* SUBCOMMANDS */
3839		/* OTHER */
3840	case ZFS_DELEG_NOTE_GROUPQUOTA:
3841	case ZFS_DELEG_NOTE_GROUPUSED:
3842	case ZFS_DELEG_NOTE_USERPROP:
3843	case ZFS_DELEG_NOTE_USERQUOTA:
3844	case ZFS_DELEG_NOTE_USERUSED:
3845		/* other */
3846		return (gettext("other"));
3847	default:
3848		return (gettext("subcommand"));
3849	}
3850}
3851
3852static int inline
3853who_type2weight(zfs_deleg_who_type_t who_type)
3854{
3855	int res;
3856	switch (who_type) {
3857		case ZFS_DELEG_NAMED_SET_SETS:
3858		case ZFS_DELEG_NAMED_SET:
3859			res = 0;
3860			break;
3861		case ZFS_DELEG_CREATE_SETS:
3862		case ZFS_DELEG_CREATE:
3863			res = 1;
3864			break;
3865		case ZFS_DELEG_USER_SETS:
3866		case ZFS_DELEG_USER:
3867			res = 2;
3868			break;
3869		case ZFS_DELEG_GROUP_SETS:
3870		case ZFS_DELEG_GROUP:
3871			res = 3;
3872			break;
3873		case ZFS_DELEG_EVERYONE_SETS:
3874		case ZFS_DELEG_EVERYONE:
3875			res = 4;
3876			break;
3877		default:
3878			res = -1;
3879	}
3880
3881	return (res);
3882}
3883
3884/* ARGSUSED */
3885static int
3886who_perm_compare(const void *larg, const void *rarg, void *unused)
3887{
3888	const who_perm_node_t *l = larg;
3889	const who_perm_node_t *r = rarg;
3890	zfs_deleg_who_type_t ltype = l->who_perm.who_type;
3891	zfs_deleg_who_type_t rtype = r->who_perm.who_type;
3892	int lweight = who_type2weight(ltype);
3893	int rweight = who_type2weight(rtype);
3894	int res = lweight - rweight;
3895	if (res == 0)
3896		res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
3897		    ZFS_MAX_DELEG_NAME-1);
3898
3899	if (res == 0)
3900		return (0);
3901	if (res > 0)
3902		return (1);
3903	else
3904		return (-1);
3905}
3906
3907/* ARGSUSED */
3908static int
3909deleg_perm_compare(const void *larg, const void *rarg, void *unused)
3910{
3911	const deleg_perm_node_t *l = larg;
3912	const deleg_perm_node_t *r = rarg;
3913	int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
3914	    ZFS_MAX_DELEG_NAME-1);
3915
3916	if (res == 0)
3917		return (0);
3918
3919	if (res > 0)
3920		return (1);
3921	else
3922		return (-1);
3923}
3924
3925static inline void
3926fs_perm_set_init(fs_perm_set_t *fspset)
3927{
3928	bzero(fspset, sizeof (fs_perm_set_t));
3929
3930	if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
3931	    sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
3932	    NULL, UU_DEFAULT)) == NULL)
3933		nomem();
3934	if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
3935	    UU_DEFAULT)) == NULL)
3936		nomem();
3937
3938	if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
3939	    "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
3940	    who_perm_node_t, who_avl_node), who_perm_compare,
3941	    UU_DEFAULT)) == NULL)
3942		nomem();
3943
3944	if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
3945	    "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
3946	    who_perm_node_t, who_avl_node), who_perm_compare,
3947	    UU_DEFAULT)) == NULL)
3948		nomem();
3949
3950	if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
3951	    "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
3952	    deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
3953	    == NULL)
3954		nomem();
3955}
3956
3957static inline void fs_perm_fini(fs_perm_t *);
3958static inline void who_perm_fini(who_perm_t *);
3959
3960static inline void
3961fs_perm_set_fini(fs_perm_set_t *fspset)
3962{
3963	fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
3964
3965	while (node != NULL) {
3966		fs_perm_node_t *next_node =
3967		    uu_list_next(fspset->fsps_list, node);
3968		fs_perm_t *fsperm = &node->fspn_fsperm;
3969		fs_perm_fini(fsperm);
3970		uu_list_remove(fspset->fsps_list, node);
3971		free(node);
3972		node = next_node;
3973	}
3974
3975	uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
3976	uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
3977	uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
3978}
3979
3980static inline void
3981deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
3982    const char *name)
3983{
3984	deleg_perm->dp_who_type = type;
3985	deleg_perm->dp_name = name;
3986}
3987
3988static inline void
3989who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
3990    zfs_deleg_who_type_t type, const char *name)
3991{
3992	uu_avl_pool_t	*pool;
3993	pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
3994
3995	bzero(who_perm, sizeof (who_perm_t));
3996
3997	if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
3998	    UU_DEFAULT)) == NULL)
3999		nomem();
4000
4001	who_perm->who_type = type;
4002	who_perm->who_name = name;
4003	who_perm->who_fsperm = fsperm;
4004}
4005
4006static inline void
4007who_perm_fini(who_perm_t *who_perm)
4008{
4009	deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4010
4011	while (node != NULL) {
4012		deleg_perm_node_t *next_node =
4013		    uu_avl_next(who_perm->who_deleg_perm_avl, node);
4014
4015		uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4016		free(node);
4017		node = next_node;
4018	}
4019
4020	uu_avl_destroy(who_perm->who_deleg_perm_avl);
4021}
4022
4023static inline void
4024fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4025{
4026	uu_avl_pool_t	*nset_pool = fspset->fsps_named_set_avl_pool;
4027	uu_avl_pool_t	*who_pool = fspset->fsps_who_perm_avl_pool;
4028
4029	bzero(fsperm, sizeof (fs_perm_t));
4030
4031	if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4032	    == NULL)
4033		nomem();
4034
4035	if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4036	    == NULL)
4037		nomem();
4038
4039	fsperm->fsp_set = fspset;
4040	fsperm->fsp_name = fsname;
4041}
4042
4043static inline void
4044fs_perm_fini(fs_perm_t *fsperm)
4045{
4046	who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4047	while (node != NULL) {
4048		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4049		    node);
4050		who_perm_t *who_perm = &node->who_perm;
4051		who_perm_fini(who_perm);
4052		uu_avl_remove(fsperm->fsp_sc_avl, node);
4053		free(node);
4054		node = next_node;
4055	}
4056
4057	node = uu_avl_first(fsperm->fsp_uge_avl);
4058	while (node != NULL) {
4059		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4060		    node);
4061		who_perm_t *who_perm = &node->who_perm;
4062		who_perm_fini(who_perm);
4063		uu_avl_remove(fsperm->fsp_uge_avl, node);
4064		free(node);
4065		node = next_node;
4066	}
4067
4068	uu_avl_destroy(fsperm->fsp_sc_avl);
4069	uu_avl_destroy(fsperm->fsp_uge_avl);
4070}
4071
4072static void inline
4073set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4074    zfs_deleg_who_type_t who_type, const char *name, char locality)
4075{
4076	uu_avl_index_t idx = 0;
4077
4078	deleg_perm_node_t *found_node = NULL;
4079	deleg_perm_t	*deleg_perm = &node->dpn_perm;
4080
4081	deleg_perm_init(deleg_perm, who_type, name);
4082
4083	if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4084	    == NULL)
4085		uu_avl_insert(avl, node, idx);
4086	else {
4087		node = found_node;
4088		deleg_perm = &node->dpn_perm;
4089	}
4090
4091
4092	switch (locality) {
4093	case ZFS_DELEG_LOCAL:
4094		deleg_perm->dp_local = B_TRUE;
4095		break;
4096	case ZFS_DELEG_DESCENDENT:
4097		deleg_perm->dp_descend = B_TRUE;
4098		break;
4099	case ZFS_DELEG_NA:
4100		break;
4101	default:
4102		assert(B_FALSE); /* invalid locality */
4103	}
4104}
4105
4106static inline int
4107parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4108{
4109	nvpair_t *nvp = NULL;
4110	fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4111	uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4112	zfs_deleg_who_type_t who_type = who_perm->who_type;
4113
4114	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4115		const char *name = nvpair_name(nvp);
4116		data_type_t type = nvpair_type(nvp);
4117		uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4118		deleg_perm_node_t *node =
4119		    safe_malloc(sizeof (deleg_perm_node_t));
4120
4121		assert(type == DATA_TYPE_BOOLEAN);
4122
4123		uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4124		set_deleg_perm_node(avl, node, who_type, name, locality);
4125	}
4126
4127	return (0);
4128}
4129
4130static inline int
4131parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4132{
4133	nvpair_t *nvp = NULL;
4134	fs_perm_set_t *fspset = fsperm->fsp_set;
4135
4136	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4137		nvlist_t *nvl2 = NULL;
4138		const char *name = nvpair_name(nvp);
4139		uu_avl_t *avl = NULL;
4140		uu_avl_pool_t *avl_pool;
4141		zfs_deleg_who_type_t perm_type = name[0];
4142		char perm_locality = name[1];
4143		const char *perm_name = name + 3;
4144		boolean_t is_set = B_TRUE;
4145		who_perm_t *who_perm = NULL;
4146
4147		assert('$' == name[2]);
4148
4149		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4150			return (-1);
4151
4152		switch (perm_type) {
4153		case ZFS_DELEG_CREATE:
4154		case ZFS_DELEG_CREATE_SETS:
4155		case ZFS_DELEG_NAMED_SET:
4156		case ZFS_DELEG_NAMED_SET_SETS:
4157			avl_pool = fspset->fsps_named_set_avl_pool;
4158			avl = fsperm->fsp_sc_avl;
4159			break;
4160		case ZFS_DELEG_USER:
4161		case ZFS_DELEG_USER_SETS:
4162		case ZFS_DELEG_GROUP:
4163		case ZFS_DELEG_GROUP_SETS:
4164		case ZFS_DELEG_EVERYONE:
4165		case ZFS_DELEG_EVERYONE_SETS:
4166			avl_pool = fspset->fsps_who_perm_avl_pool;
4167			avl = fsperm->fsp_uge_avl;
4168			break;
4169		}
4170
4171		if (is_set) {
4172			who_perm_node_t *found_node = NULL;
4173			who_perm_node_t *node = safe_malloc(
4174			    sizeof (who_perm_node_t));
4175			who_perm = &node->who_perm;
4176			uu_avl_index_t idx = 0;
4177
4178			uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4179			who_perm_init(who_perm, fsperm, perm_type, perm_name);
4180
4181			if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4182			    == NULL) {
4183				if (avl == fsperm->fsp_uge_avl) {
4184					uid_t rid = 0;
4185					struct passwd *p = NULL;
4186					struct group *g = NULL;
4187					const char *nice_name = NULL;
4188
4189					switch (perm_type) {
4190					case ZFS_DELEG_USER_SETS:
4191					case ZFS_DELEG_USER:
4192						rid = atoi(perm_name);
4193						p = getpwuid(rid);
4194						if (p)
4195							nice_name = p->pw_name;
4196						break;
4197					case ZFS_DELEG_GROUP_SETS:
4198					case ZFS_DELEG_GROUP:
4199						rid = atoi(perm_name);
4200						g = getgrgid(rid);
4201						if (g)
4202							nice_name = g->gr_name;
4203						break;
4204					}
4205
4206					if (nice_name != NULL)
4207						(void) strlcpy(
4208						    node->who_perm.who_ug_name,
4209						    nice_name, 256);
4210				}
4211
4212				uu_avl_insert(avl, node, idx);
4213			} else {
4214				node = found_node;
4215				who_perm = &node->who_perm;
4216			}
4217		}
4218
4219		(void) parse_who_perm(who_perm, nvl2, perm_locality);
4220	}
4221
4222	return (0);
4223}
4224
4225static inline int
4226parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4227{
4228	nvpair_t *nvp = NULL;
4229	uu_avl_index_t idx = 0;
4230
4231	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4232		nvlist_t *nvl2 = NULL;
4233		const char *fsname = nvpair_name(nvp);
4234		data_type_t type = nvpair_type(nvp);
4235		fs_perm_t *fsperm = NULL;
4236		fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4237		if (node == NULL)
4238			nomem();
4239
4240		fsperm = &node->fspn_fsperm;
4241
4242		assert(DATA_TYPE_NVLIST == type);
4243
4244		uu_list_node_init(node, &node->fspn_list_node,
4245		    fspset->fsps_list_pool);
4246
4247		idx = uu_list_numnodes(fspset->fsps_list);
4248		fs_perm_init(fsperm, fspset, fsname);
4249
4250		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4251			return (-1);
4252
4253		(void) parse_fs_perm(fsperm, nvl2);
4254
4255		uu_list_insert(fspset->fsps_list, node, idx);
4256	}
4257
4258	return (0);
4259}
4260
4261static inline const char *
4262deleg_perm_comment(zfs_deleg_note_t note)
4263{
4264	const char *str = "";
4265
4266	/* subcommands */
4267	switch (note) {
4268		/* SUBCOMMANDS */
4269	case ZFS_DELEG_NOTE_ALLOW:
4270		str = gettext("Must also have the permission that is being"
4271		    "\n\t\t\t\tallowed");
4272		break;
4273	case ZFS_DELEG_NOTE_CLONE:
4274		str = gettext("Must also have the 'create' ability and 'mount'"
4275		    "\n\t\t\t\tability in the origin file system");
4276		break;
4277	case ZFS_DELEG_NOTE_CREATE:
4278		str = gettext("Must also have the 'mount' ability");
4279		break;
4280	case ZFS_DELEG_NOTE_DESTROY:
4281		str = gettext("Must also have the 'mount' ability");
4282		break;
4283	case ZFS_DELEG_NOTE_DIFF:
4284		str = gettext("Allows lookup of paths within a dataset;"
4285		    "\n\t\t\t\tgiven an object number. Ordinary users need this"
4286		    "\n\t\t\t\tin order to use zfs diff");
4287		break;
4288	case ZFS_DELEG_NOTE_HOLD:
4289		str = gettext("Allows adding a user hold to a snapshot");
4290		break;
4291	case ZFS_DELEG_NOTE_MOUNT:
4292		str = gettext("Allows mount/umount of ZFS datasets");
4293		break;
4294	case ZFS_DELEG_NOTE_PROMOTE:
4295		str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4296		    " 'promote' ability in the origin file system");
4297		break;
4298	case ZFS_DELEG_NOTE_RECEIVE:
4299		str = gettext("Must also have the 'mount' and 'create'"
4300		    " ability");
4301		break;
4302	case ZFS_DELEG_NOTE_RELEASE:
4303		str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4304		    "might destroy the snapshot");
4305		break;
4306	case ZFS_DELEG_NOTE_RENAME:
4307		str = gettext("Must also have the 'mount' and 'create'"
4308		    "\n\t\t\t\tability in the new parent");
4309		break;
4310	case ZFS_DELEG_NOTE_ROLLBACK:
4311		str = gettext("");
4312		break;
4313	case ZFS_DELEG_NOTE_SEND:
4314		str = gettext("");
4315		break;
4316	case ZFS_DELEG_NOTE_SHARE:
4317		str = gettext("Allows sharing file systems over NFS or SMB"
4318		    "\n\t\t\t\tprotocols");
4319		break;
4320	case ZFS_DELEG_NOTE_SNAPSHOT:
4321		str = gettext("");
4322		break;
4323/*
4324 *	case ZFS_DELEG_NOTE_VSCAN:
4325 *		str = gettext("");
4326 *		break;
4327 */
4328		/* OTHER */
4329	case ZFS_DELEG_NOTE_GROUPQUOTA:
4330		str = gettext("Allows accessing any groupquota@... property");
4331		break;
4332	case ZFS_DELEG_NOTE_GROUPUSED:
4333		str = gettext("Allows reading any groupused@... property");
4334		break;
4335	case ZFS_DELEG_NOTE_USERPROP:
4336		str = gettext("Allows changing any user property");
4337		break;
4338	case ZFS_DELEG_NOTE_USERQUOTA:
4339		str = gettext("Allows accessing any userquota@... property");
4340		break;
4341	case ZFS_DELEG_NOTE_USERUSED:
4342		str = gettext("Allows reading any userused@... property");
4343		break;
4344		/* other */
4345	default:
4346		str = "";
4347	}
4348
4349	return (str);
4350}
4351
4352struct allow_opts {
4353	boolean_t local;
4354	boolean_t descend;
4355	boolean_t user;
4356	boolean_t group;
4357	boolean_t everyone;
4358	boolean_t create;
4359	boolean_t set;
4360	boolean_t recursive; /* unallow only */
4361	boolean_t prt_usage;
4362
4363	boolean_t prt_perms;
4364	char *who;
4365	char *perms;
4366	const char *dataset;
4367};
4368
4369static inline int
4370prop_cmp(const void *a, const void *b)
4371{
4372	const char *str1 = *(const char **)a;
4373	const char *str2 = *(const char **)b;
4374	return (strcmp(str1, str2));
4375}
4376
4377static void
4378allow_usage(boolean_t un, boolean_t requested, const char *msg)
4379{
4380	const char *opt_desc[] = {
4381		"-h", gettext("show this help message and exit"),
4382		"-l", gettext("set permission locally"),
4383		"-d", gettext("set permission for descents"),
4384		"-u", gettext("set permission for user"),
4385		"-g", gettext("set permission for group"),
4386		"-e", gettext("set permission for everyone"),
4387		"-c", gettext("set create time permission"),
4388		"-s", gettext("define permission set"),
4389		/* unallow only */
4390		"-r", gettext("remove permissions recursively"),
4391	};
4392	size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4393	size_t allow_size = unallow_size - 2;
4394	const char *props[ZFS_NUM_PROPS];
4395	int i;
4396	size_t count = 0;
4397	FILE *fp = requested ? stdout : stderr;
4398	zprop_desc_t *pdtbl = zfs_prop_get_table();
4399	const char *fmt = gettext("%-16s %-14s\t%s\n");
4400
4401	(void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4402	    HELP_ALLOW));
4403	(void) fprintf(fp, gettext("Options:\n"));
4404	for (i = 0; i < (un ? unallow_size : allow_size); i++) {
4405		const char *opt = opt_desc[i++];
4406		const char *optdsc = opt_desc[i];
4407		(void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4408	}
4409
4410	(void) fprintf(fp, gettext("\nThe following permissions are "
4411	    "supported:\n\n"));
4412	(void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4413	    gettext("NOTES"));
4414	for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4415		const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4416		zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4417		const char *perm_type = deleg_perm_type(perm_note);
4418		const char *perm_comment = deleg_perm_comment(perm_note);
4419		(void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4420	}
4421
4422	for (i = 0; i < ZFS_NUM_PROPS; i++) {
4423		zprop_desc_t *pd = &pdtbl[i];
4424		if (pd->pd_visible != B_TRUE)
4425			continue;
4426
4427		if (pd->pd_attr == PROP_READONLY)
4428			continue;
4429
4430		props[count++] = pd->pd_name;
4431	}
4432	props[count] = NULL;
4433
4434	qsort(props, count, sizeof (char *), prop_cmp);
4435
4436	for (i = 0; i < count; i++)
4437		(void) fprintf(fp, fmt, props[i], gettext("property"), "");
4438
4439	if (msg != NULL)
4440		(void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4441
4442	exit(requested ? 0 : 2);
4443}
4444
4445static inline const char *
4446munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4447    char **permsp)
4448{
4449	if (un && argc == expected_argc - 1)
4450		*permsp = NULL;
4451	else if (argc == expected_argc)
4452		*permsp = argv[argc - 2];
4453	else
4454		allow_usage(un, B_FALSE,
4455		    gettext("wrong number of parameters\n"));
4456
4457	return (argv[argc - 1]);
4458}
4459
4460static void
4461parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4462{
4463	int uge_sum = opts->user + opts->group + opts->everyone;
4464	int csuge_sum = opts->create + opts->set + uge_sum;
4465	int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4466	int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4467
4468	if (uge_sum > 1)
4469		allow_usage(un, B_FALSE,
4470		    gettext("-u, -g, and -e are mutually exclusive\n"));
4471
4472	if (opts->prt_usage)
4473		if (argc == 0 && all_sum == 0)
4474			allow_usage(un, B_TRUE, NULL);
4475		else
4476			usage(B_FALSE);
4477
4478	if (opts->set) {
4479		if (csuge_sum > 1)
4480			allow_usage(un, B_FALSE,
4481			    gettext("invalid options combined with -s\n"));
4482
4483		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4484		if (argv[0][0] != '@')
4485			allow_usage(un, B_FALSE,
4486			    gettext("invalid set name: missing '@' prefix\n"));
4487		opts->who = argv[0];
4488	} else if (opts->create) {
4489		if (ldcsuge_sum > 1)
4490			allow_usage(un, B_FALSE,
4491			    gettext("invalid options combined with -c\n"));
4492		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4493	} else if (opts->everyone) {
4494		if (csuge_sum > 1)
4495			allow_usage(un, B_FALSE,
4496			    gettext("invalid options combined with -e\n"));
4497		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4498	} else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4499	    == 0) {
4500		opts->everyone = B_TRUE;
4501		argc--;
4502		argv++;
4503		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4504	} else if (argc == 1 && !un) {
4505		opts->prt_perms = B_TRUE;
4506		opts->dataset = argv[argc-1];
4507	} else {
4508		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4509		opts->who = argv[0];
4510	}
4511
4512	if (!opts->local && !opts->descend) {
4513		opts->local = B_TRUE;
4514		opts->descend = B_TRUE;
4515	}
4516}
4517
4518static void
4519store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4520    const char *who, char *perms, nvlist_t *top_nvl)
4521{
4522	int i;
4523	char ld[2] = { '\0', '\0' };
4524	char who_buf[ZFS_MAXNAMELEN+32];
4525	char base_type;
4526	char set_type;
4527	nvlist_t *base_nvl = NULL;
4528	nvlist_t *set_nvl = NULL;
4529	nvlist_t *nvl;
4530
4531	if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4532		nomem();
4533	if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4534		nomem();
4535
4536	switch (type) {
4537	case ZFS_DELEG_NAMED_SET_SETS:
4538	case ZFS_DELEG_NAMED_SET:
4539		set_type = ZFS_DELEG_NAMED_SET_SETS;
4540		base_type = ZFS_DELEG_NAMED_SET;
4541		ld[0] = ZFS_DELEG_NA;
4542		break;
4543	case ZFS_DELEG_CREATE_SETS:
4544	case ZFS_DELEG_CREATE:
4545		set_type = ZFS_DELEG_CREATE_SETS;
4546		base_type = ZFS_DELEG_CREATE;
4547		ld[0] = ZFS_DELEG_NA;
4548		break;
4549	case ZFS_DELEG_USER_SETS:
4550	case ZFS_DELEG_USER:
4551		set_type = ZFS_DELEG_USER_SETS;
4552		base_type = ZFS_DELEG_USER;
4553		if (local)
4554			ld[0] = ZFS_DELEG_LOCAL;
4555		if (descend)
4556			ld[1] = ZFS_DELEG_DESCENDENT;
4557		break;
4558	case ZFS_DELEG_GROUP_SETS:
4559	case ZFS_DELEG_GROUP:
4560		set_type = ZFS_DELEG_GROUP_SETS;
4561		base_type = ZFS_DELEG_GROUP;
4562		if (local)
4563			ld[0] = ZFS_DELEG_LOCAL;
4564		if (descend)
4565			ld[1] = ZFS_DELEG_DESCENDENT;
4566		break;
4567	case ZFS_DELEG_EVERYONE_SETS:
4568	case ZFS_DELEG_EVERYONE:
4569		set_type = ZFS_DELEG_EVERYONE_SETS;
4570		base_type = ZFS_DELEG_EVERYONE;
4571		if (local)
4572			ld[0] = ZFS_DELEG_LOCAL;
4573		if (descend)
4574			ld[1] = ZFS_DELEG_DESCENDENT;
4575	}
4576
4577	if (perms != NULL) {
4578		char *curr = perms;
4579		char *end = curr + strlen(perms);
4580
4581		while (curr < end) {
4582			char *delim = strchr(curr, ',');
4583			if (delim == NULL)
4584				delim = end;
4585			else
4586				*delim = '\0';
4587
4588			if (curr[0] == '@')
4589				nvl = set_nvl;
4590			else
4591				nvl = base_nvl;
4592
4593			(void) nvlist_add_boolean(nvl, curr);
4594			if (delim != end)
4595				*delim = ',';
4596			curr = delim + 1;
4597		}
4598
4599		for (i = 0; i < 2; i++) {
4600			char locality = ld[i];
4601			if (locality == 0)
4602				continue;
4603
4604			if (!nvlist_empty(base_nvl)) {
4605				if (who != NULL)
4606					(void) snprintf(who_buf,
4607					    sizeof (who_buf), "%c%c$%s",
4608					    base_type, locality, who);
4609				else
4610					(void) snprintf(who_buf,
4611					    sizeof (who_buf), "%c%c$",
4612					    base_type, locality);
4613
4614				(void) nvlist_add_nvlist(top_nvl, who_buf,
4615				    base_nvl);
4616			}
4617
4618
4619			if (!nvlist_empty(set_nvl)) {
4620				if (who != NULL)
4621					(void) snprintf(who_buf,
4622					    sizeof (who_buf), "%c%c$%s",
4623					    set_type, locality, who);
4624				else
4625					(void) snprintf(who_buf,
4626					    sizeof (who_buf), "%c%c$",
4627					    set_type, locality);
4628
4629				(void) nvlist_add_nvlist(top_nvl, who_buf,
4630				    set_nvl);
4631			}
4632		}
4633	} else {
4634		for (i = 0; i < 2; i++) {
4635			char locality = ld[i];
4636			if (locality == 0)
4637				continue;
4638
4639			if (who != NULL)
4640				(void) snprintf(who_buf, sizeof (who_buf),
4641				    "%c%c$%s", base_type, locality, who);
4642			else
4643				(void) snprintf(who_buf, sizeof (who_buf),
4644				    "%c%c$", base_type, locality);
4645			(void) nvlist_add_boolean(top_nvl, who_buf);
4646
4647			if (who != NULL)
4648				(void) snprintf(who_buf, sizeof (who_buf),
4649				    "%c%c$%s", set_type, locality, who);
4650			else
4651				(void) snprintf(who_buf, sizeof (who_buf),
4652				    "%c%c$", set_type, locality);
4653			(void) nvlist_add_boolean(top_nvl, who_buf);
4654		}
4655	}
4656}
4657
4658static int
4659construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4660{
4661	if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4662		nomem();
4663
4664	if (opts->set) {
4665		store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4666		    opts->descend, opts->who, opts->perms, *nvlp);
4667	} else if (opts->create) {
4668		store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4669		    opts->descend, NULL, opts->perms, *nvlp);
4670	} else if (opts->everyone) {
4671		store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4672		    opts->descend, NULL, opts->perms, *nvlp);
4673	} else {
4674		char *curr = opts->who;
4675		char *end = curr + strlen(curr);
4676
4677		while (curr < end) {
4678			const char *who;
4679			zfs_deleg_who_type_t who_type;
4680			char *endch;
4681			char *delim = strchr(curr, ',');
4682			char errbuf[256];
4683			char id[64];
4684			struct passwd *p = NULL;
4685			struct group *g = NULL;
4686
4687			uid_t rid;
4688			if (delim == NULL)
4689				delim = end;
4690			else
4691				*delim = '\0';
4692
4693			rid = (uid_t)strtol(curr, &endch, 0);
4694			if (opts->user) {
4695				who_type = ZFS_DELEG_USER;
4696				if (*endch != '\0')
4697					p = getpwnam(curr);
4698				else
4699					p = getpwuid(rid);
4700
4701				if (p != NULL)
4702					rid = p->pw_uid;
4703				else {
4704					(void) snprintf(errbuf, 256, gettext(
4705					    "invalid user %s"), curr);
4706					allow_usage(un, B_TRUE, errbuf);
4707				}
4708			} else if (opts->group) {
4709				who_type = ZFS_DELEG_GROUP;
4710				if (*endch != '\0')
4711					g = getgrnam(curr);
4712				else
4713					g = getgrgid(rid);
4714
4715				if (g != NULL)
4716					rid = g->gr_gid;
4717				else {
4718					(void) snprintf(errbuf, 256, gettext(
4719					    "invalid group %s"),  curr);
4720					allow_usage(un, B_TRUE, errbuf);
4721				}
4722			} else {
4723				if (*endch != '\0') {
4724					p = getpwnam(curr);
4725				} else {
4726					p = getpwuid(rid);
4727				}
4728
4729				if (p == NULL)
4730					if (*endch != '\0') {
4731						g = getgrnam(curr);
4732					} else {
4733						g = getgrgid(rid);
4734					}
4735
4736				if (p != NULL) {
4737					who_type = ZFS_DELEG_USER;
4738					rid = p->pw_uid;
4739				} else if (g != NULL) {
4740					who_type = ZFS_DELEG_GROUP;
4741					rid = g->gr_gid;
4742				} else {
4743					(void) snprintf(errbuf, 256, gettext(
4744					    "invalid user/group %s"), curr);
4745					allow_usage(un, B_TRUE, errbuf);
4746				}
4747			}
4748
4749			(void) sprintf(id, "%u", rid);
4750			who = id;
4751
4752			store_allow_perm(who_type, opts->local,
4753			    opts->descend, who, opts->perms, *nvlp);
4754			curr = delim + 1;
4755		}
4756	}
4757
4758	return (0);
4759}
4760
4761static void
4762print_set_creat_perms(uu_avl_t *who_avl)
4763{
4764	const char *sc_title[] = {
4765		gettext("Permission sets:\n"),
4766		gettext("Create time permissions:\n"),
4767		NULL
4768	};
4769	const char **title_ptr = sc_title;
4770	who_perm_node_t *who_node = NULL;
4771	int prev_weight = -1;
4772
4773	for (who_node = uu_avl_first(who_avl); who_node != NULL;
4774	    who_node = uu_avl_next(who_avl, who_node)) {
4775		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4776		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4777		const char *who_name = who_node->who_perm.who_name;
4778		int weight = who_type2weight(who_type);
4779		boolean_t first = B_TRUE;
4780		deleg_perm_node_t *deleg_node;
4781
4782		if (prev_weight != weight) {
4783			(void) printf(*title_ptr++);
4784			prev_weight = weight;
4785		}
4786
4787		if (who_name == NULL || strnlen(who_name, 1) == 0)
4788			(void) printf("\t");
4789		else
4790			(void) printf("\t%s ", who_name);
4791
4792		for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
4793		    deleg_node = uu_avl_next(avl, deleg_node)) {
4794			if (first) {
4795				(void) printf("%s",
4796				    deleg_node->dpn_perm.dp_name);
4797				first = B_FALSE;
4798			} else
4799				(void) printf(",%s",
4800				    deleg_node->dpn_perm.dp_name);
4801		}
4802
4803		(void) printf("\n");
4804	}
4805}
4806
4807static void inline
4808print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
4809    const char *title)
4810{
4811	who_perm_node_t *who_node = NULL;
4812	boolean_t prt_title = B_TRUE;
4813	uu_avl_walk_t *walk;
4814
4815	if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
4816		nomem();
4817
4818	while ((who_node = uu_avl_walk_next(walk)) != NULL) {
4819		const char *who_name = who_node->who_perm.who_name;
4820		const char *nice_who_name = who_node->who_perm.who_ug_name;
4821		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4822		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4823		char delim = ' ';
4824		deleg_perm_node_t *deleg_node;
4825		boolean_t prt_who = B_TRUE;
4826
4827		for (deleg_node = uu_avl_first(avl);
4828		    deleg_node != NULL;
4829		    deleg_node = uu_avl_next(avl, deleg_node)) {
4830			if (local != deleg_node->dpn_perm.dp_local ||
4831			    descend != deleg_node->dpn_perm.dp_descend)
4832				continue;
4833
4834			if (prt_who) {
4835				const char *who = NULL;
4836				if (prt_title) {
4837					prt_title = B_FALSE;
4838					(void) printf(title);
4839				}
4840
4841				switch (who_type) {
4842				case ZFS_DELEG_USER_SETS:
4843				case ZFS_DELEG_USER:
4844					who = gettext("user");
4845					if (nice_who_name)
4846						who_name  = nice_who_name;
4847					break;
4848				case ZFS_DELEG_GROUP_SETS:
4849				case ZFS_DELEG_GROUP:
4850					who = gettext("group");
4851					if (nice_who_name)
4852						who_name  = nice_who_name;
4853					break;
4854				case ZFS_DELEG_EVERYONE_SETS:
4855				case ZFS_DELEG_EVERYONE:
4856					who = gettext("everyone");
4857					who_name = NULL;
4858				}
4859
4860				prt_who = B_FALSE;
4861				if (who_name == NULL)
4862					(void) printf("\t%s", who);
4863				else
4864					(void) printf("\t%s %s", who, who_name);
4865			}
4866
4867			(void) printf("%c%s", delim,
4868			    deleg_node->dpn_perm.dp_name);
4869			delim = ',';
4870		}
4871
4872		if (!prt_who)
4873			(void) printf("\n");
4874	}
4875
4876	uu_avl_walk_end(walk);
4877}
4878
4879static void
4880print_fs_perms(fs_perm_set_t *fspset)
4881{
4882	fs_perm_node_t *node = NULL;
4883	char buf[ZFS_MAXNAMELEN+32];
4884	const char *dsname = buf;
4885
4886	for (node = uu_list_first(fspset->fsps_list); node != NULL;
4887	    node = uu_list_next(fspset->fsps_list, node)) {
4888		uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
4889		uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
4890		int left = 0;
4891
4892		(void) snprintf(buf, ZFS_MAXNAMELEN+32,
4893		    gettext("---- Permissions on %s "),
4894		    node->fspn_fsperm.fsp_name);
4895		(void) printf(dsname);
4896		left = 70 - strlen(buf);
4897		while (left-- > 0)
4898			(void) printf("-");
4899		(void) printf("\n");
4900
4901		print_set_creat_perms(sc_avl);
4902		print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
4903		    gettext("Local permissions:\n"));
4904		print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
4905		    gettext("Descendent permissions:\n"));
4906		print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
4907		    gettext("Local+Descendent permissions:\n"));
4908	}
4909}
4910
4911static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
4912
4913struct deleg_perms {
4914	boolean_t un;
4915	nvlist_t *nvl;
4916};
4917
4918static int
4919set_deleg_perms(zfs_handle_t *zhp, void *data)
4920{
4921	struct deleg_perms *perms = (struct deleg_perms *)data;
4922	zfs_type_t zfs_type = zfs_get_type(zhp);
4923
4924	if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
4925		return (0);
4926
4927	return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
4928}
4929
4930static int
4931zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
4932{
4933	zfs_handle_t *zhp;
4934	nvlist_t *perm_nvl = NULL;
4935	nvlist_t *update_perm_nvl = NULL;
4936	int error = 1;
4937	int c;
4938	struct allow_opts opts = { 0 };
4939
4940	const char *optstr = un ? "ldugecsrh" : "ldugecsh";
4941
4942	/* check opts */
4943	while ((c = getopt(argc, argv, optstr)) != -1) {
4944		switch (c) {
4945		case 'l':
4946			opts.local = B_TRUE;
4947			break;
4948		case 'd':
4949			opts.descend = B_TRUE;
4950			break;
4951		case 'u':
4952			opts.user = B_TRUE;
4953			break;
4954		case 'g':
4955			opts.group = B_TRUE;
4956			break;
4957		case 'e':
4958			opts.everyone = B_TRUE;
4959			break;
4960		case 's':
4961			opts.set = B_TRUE;
4962			break;
4963		case 'c':
4964			opts.create = B_TRUE;
4965			break;
4966		case 'r':
4967			opts.recursive = B_TRUE;
4968			break;
4969		case ':':
4970			(void) fprintf(stderr, gettext("missing argument for "
4971			    "'%c' option\n"), optopt);
4972			usage(B_FALSE);
4973			break;
4974		case 'h':
4975			opts.prt_usage = B_TRUE;
4976			break;
4977		case '?':
4978			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4979			    optopt);
4980			usage(B_FALSE);
4981		}
4982	}
4983
4984	argc -= optind;
4985	argv += optind;
4986
4987	/* check arguments */
4988	parse_allow_args(argc, argv, un, &opts);
4989
4990	/* try to open the dataset */
4991	if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
4992	    ZFS_TYPE_VOLUME)) == NULL) {
4993		(void) fprintf(stderr, "Failed to open dataset: %s\n",
4994		    opts.dataset);
4995		return (-1);
4996	}
4997
4998	if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
4999		goto cleanup2;
5000
5001	fs_perm_set_init(&fs_perm_set);
5002	if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5003		(void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5004		goto cleanup1;
5005	}
5006
5007	if (opts.prt_perms)
5008		print_fs_perms(&fs_perm_set);
5009	else {
5010		(void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5011		if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5012			goto cleanup0;
5013
5014		if (un && opts.recursive) {
5015			struct deleg_perms data = { un, update_perm_nvl };
5016			if (zfs_iter_filesystems(zhp, set_deleg_perms,
5017			    &data) != 0)
5018				goto cleanup0;
5019		}
5020	}
5021
5022	error = 0;
5023
5024cleanup0:
5025	nvlist_free(perm_nvl);
5026	if (update_perm_nvl != NULL)
5027		nvlist_free(update_perm_nvl);
5028cleanup1:
5029	fs_perm_set_fini(&fs_perm_set);
5030cleanup2:
5031	zfs_close(zhp);
5032
5033	return (error);
5034}
5035
5036/*
5037 * zfs allow [-r] [-t] <tag> <snap> ...
5038 *
5039 *	-r	Recursively hold
5040 *	-t	Temporary hold (hidden option)
5041 *
5042 * Apply a user-hold with the given tag to the list of snapshots.
5043 */
5044static int
5045zfs_do_allow(int argc, char **argv)
5046{
5047	return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5048}
5049
5050/*
5051 * zfs unallow [-r] [-t] <tag> <snap> ...
5052 *
5053 *	-r	Recursively hold
5054 *	-t	Temporary hold (hidden option)
5055 *
5056 * Apply a user-hold with the given tag to the list of snapshots.
5057 */
5058static int
5059zfs_do_unallow(int argc, char **argv)
5060{
5061	return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5062}
5063
5064static int
5065zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5066{
5067	int errors = 0;
5068	int i;
5069	const char *tag;
5070	boolean_t recursive = B_FALSE;
5071	boolean_t temphold = B_FALSE;
5072	const char *opts = holding ? "rt" : "r";
5073	int c;
5074
5075	/* check options */
5076	while ((c = getopt(argc, argv, opts)) != -1) {
5077		switch (c) {
5078		case 'r':
5079			recursive = B_TRUE;
5080			break;
5081		case 't':
5082			temphold = B_TRUE;
5083			break;
5084		case '?':
5085			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5086			    optopt);
5087			usage(B_FALSE);
5088		}
5089	}
5090
5091	argc -= optind;
5092	argv += optind;
5093
5094	/* check number of arguments */
5095	if (argc < 2)
5096		usage(B_FALSE);
5097
5098	tag = argv[0];
5099	--argc;
5100	++argv;
5101
5102	if (holding && tag[0] == '.') {
5103		/* tags starting with '.' are reserved for libzfs */
5104		(void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5105		usage(B_FALSE);
5106	}
5107
5108	for (i = 0; i < argc; ++i) {
5109		zfs_handle_t *zhp;
5110		char parent[ZFS_MAXNAMELEN];
5111		const char *delim;
5112		char *path = argv[i];
5113
5114		delim = strchr(path, '@');
5115		if (delim == NULL) {
5116			(void) fprintf(stderr,
5117			    gettext("'%s' is not a snapshot\n"), path);
5118			++errors;
5119			continue;
5120		}
5121		(void) strncpy(parent, path, delim - path);
5122		parent[delim - path] = '\0';
5123
5124		zhp = zfs_open(g_zfs, parent,
5125		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5126		if (zhp == NULL) {
5127			++errors;
5128			continue;
5129		}
5130		if (holding) {
5131			if (zfs_hold(zhp, delim+1, tag, recursive,
5132			    temphold, B_FALSE, -1, 0, 0) != 0)
5133				++errors;
5134		} else {
5135			if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5136				++errors;
5137		}
5138		zfs_close(zhp);
5139	}
5140
5141	return (errors != 0);
5142}
5143
5144/*
5145 * zfs hold [-r] [-t] <tag> <snap> ...
5146 *
5147 *	-r	Recursively hold
5148 *	-t	Temporary hold (hidden option)
5149 *
5150 * Apply a user-hold with the given tag to the list of snapshots.
5151 */
5152static int
5153zfs_do_hold(int argc, char **argv)
5154{
5155	return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5156}
5157
5158/*
5159 * zfs release [-r] <tag> <snap> ...
5160 *
5161 *	-r	Recursively release
5162 *
5163 * Release a user-hold with the given tag from the list of snapshots.
5164 */
5165static int
5166zfs_do_release(int argc, char **argv)
5167{
5168	return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5169}
5170
5171typedef struct holds_cbdata {
5172	boolean_t	cb_recursive;
5173	const char	*cb_snapname;
5174	nvlist_t	**cb_nvlp;
5175	size_t		cb_max_namelen;
5176	size_t		cb_max_taglen;
5177} holds_cbdata_t;
5178
5179#define	STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5180#define	DATETIME_BUF_LEN (32)
5181/*
5182 *
5183 */
5184static void
5185print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5186{
5187	int i;
5188	nvpair_t *nvp = NULL;
5189	char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5190	const char *col;
5191
5192	if (!scripted) {
5193		for (i = 0; i < 3; i++) {
5194			col = gettext(hdr_cols[i]);
5195			if (i < 2)
5196				(void) printf("%-*s  ", i ? tagwidth : nwidth,
5197				    col);
5198			else
5199				(void) printf("%s\n", col);
5200		}
5201	}
5202
5203	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5204		char *zname = nvpair_name(nvp);
5205		nvlist_t *nvl2;
5206		nvpair_t *nvp2 = NULL;
5207		(void) nvpair_value_nvlist(nvp, &nvl2);
5208		while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5209			char tsbuf[DATETIME_BUF_LEN];
5210			char *tagname = nvpair_name(nvp2);
5211			uint64_t val = 0;
5212			time_t time;
5213			struct tm t;
5214			char sep = scripted ? '\t' : ' ';
5215			size_t sepnum = scripted ? 1 : 2;
5216
5217			(void) nvpair_value_uint64(nvp2, &val);
5218			time = (time_t)val;
5219			(void) localtime_r(&time, &t);
5220			(void) strftime(tsbuf, DATETIME_BUF_LEN,
5221			    gettext(STRFTIME_FMT_STR), &t);
5222
5223			(void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5224			    sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5225		}
5226	}
5227}
5228
5229/*
5230 * Generic callback function to list a dataset or snapshot.
5231 */
5232static int
5233holds_callback(zfs_handle_t *zhp, void *data)
5234{
5235	holds_cbdata_t *cbp = data;
5236	nvlist_t *top_nvl = *cbp->cb_nvlp;
5237	nvlist_t *nvl = NULL;
5238	nvpair_t *nvp = NULL;
5239	const char *zname = zfs_get_name(zhp);
5240	size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5241
5242	if (cbp->cb_recursive) {
5243		const char *snapname;
5244		char *delim  = strchr(zname, '@');
5245		if (delim == NULL)
5246			return (0);
5247
5248		snapname = delim + 1;
5249		if (strcmp(cbp->cb_snapname, snapname))
5250			return (0);
5251	}
5252
5253	if (zfs_get_holds(zhp, &nvl) != 0)
5254		return (-1);
5255
5256	if (znamelen > cbp->cb_max_namelen)
5257		cbp->cb_max_namelen  = znamelen;
5258
5259	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5260		const char *tag = nvpair_name(nvp);
5261		size_t taglen = strnlen(tag, MAXNAMELEN);
5262		if (taglen > cbp->cb_max_taglen)
5263			cbp->cb_max_taglen  = taglen;
5264	}
5265
5266	return (nvlist_add_nvlist(top_nvl, zname, nvl));
5267}
5268
5269/*
5270 * zfs holds [-r] <snap> ...
5271 *
5272 *	-r	Recursively hold
5273 */
5274static int
5275zfs_do_holds(int argc, char **argv)
5276{
5277	int errors = 0;
5278	int c;
5279	int i;
5280	boolean_t scripted = B_FALSE;
5281	boolean_t recursive = B_FALSE;
5282	const char *opts = "rH";
5283	nvlist_t *nvl;
5284
5285	int types = ZFS_TYPE_SNAPSHOT;
5286	holds_cbdata_t cb = { 0 };
5287
5288	int limit = 0;
5289	int ret;
5290	int flags = 0;
5291
5292	/* check options */
5293	while ((c = getopt(argc, argv, opts)) != -1) {
5294		switch (c) {
5295		case 'r':
5296			recursive = B_TRUE;
5297			break;
5298		case 'H':
5299			scripted = B_TRUE;
5300			break;
5301		case '?':
5302			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5303			    optopt);
5304			usage(B_FALSE);
5305		}
5306	}
5307
5308	if (recursive) {
5309		types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5310		flags |= ZFS_ITER_RECURSE;
5311	}
5312
5313	argc -= optind;
5314	argv += optind;
5315
5316	/* check number of arguments */
5317	if (argc < 1)
5318		usage(B_FALSE);
5319
5320	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5321		nomem();
5322
5323	for (i = 0; i < argc; ++i) {
5324		char *snapshot = argv[i];
5325		const char *delim;
5326		const char *snapname;
5327
5328		delim = strchr(snapshot, '@');
5329		if (delim == NULL) {
5330			(void) fprintf(stderr,
5331			    gettext("'%s' is not a snapshot\n"), snapshot);
5332			++errors;
5333			continue;
5334		}
5335		snapname = delim + 1;
5336		if (recursive)
5337			snapshot[delim - snapshot] = '\0';
5338
5339		cb.cb_recursive = recursive;
5340		cb.cb_snapname = snapname;
5341		cb.cb_nvlp = &nvl;
5342
5343		/*
5344		 *  1. collect holds data, set format options
5345		 */
5346		ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5347		    holds_callback, &cb);
5348		if (ret != 0)
5349			++errors;
5350	}
5351
5352	/*
5353	 *  2. print holds data
5354	 */
5355	print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5356
5357	if (nvlist_empty(nvl))
5358		(void) printf(gettext("no datasets available\n"));
5359
5360	nvlist_free(nvl);
5361
5362	return (0 != errors);
5363}
5364
5365#define	CHECK_SPINNER 30
5366#define	SPINNER_TIME 3		/* seconds */
5367#define	MOUNT_TIME 5		/* seconds */
5368
5369static int
5370get_one_dataset(zfs_handle_t *zhp, void *data)
5371{
5372	static char *spin[] = { "-", "\\", "|", "/" };
5373	static int spinval = 0;
5374	static int spincheck = 0;
5375	static time_t last_spin_time = (time_t)0;
5376	get_all_cb_t *cbp = data;
5377	zfs_type_t type = zfs_get_type(zhp);
5378
5379	if (cbp->cb_verbose) {
5380		if (--spincheck < 0) {
5381			time_t now = time(NULL);
5382			if (last_spin_time + SPINNER_TIME < now) {
5383				update_progress(spin[spinval++ % 4]);
5384				last_spin_time = now;
5385			}
5386			spincheck = CHECK_SPINNER;
5387		}
5388	}
5389
5390	/*
5391	 * Interate over any nested datasets.
5392	 */
5393	if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5394		zfs_close(zhp);
5395		return (1);
5396	}
5397
5398	/*
5399	 * Skip any datasets whose type does not match.
5400	 */
5401	if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5402		zfs_close(zhp);
5403		return (0);
5404	}
5405	libzfs_add_handle(cbp, zhp);
5406	assert(cbp->cb_used <= cbp->cb_alloc);
5407
5408	return (0);
5409}
5410
5411static void
5412get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5413{
5414	get_all_cb_t cb = { 0 };
5415	cb.cb_verbose = verbose;
5416	cb.cb_getone = get_one_dataset;
5417
5418	if (verbose)
5419		set_progress_header(gettext("Reading ZFS config"));
5420	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5421
5422	*dslist = cb.cb_handles;
5423	*count = cb.cb_used;
5424
5425	if (verbose)
5426		finish_progress(gettext("done."));
5427}
5428
5429/*
5430 * Generic callback for sharing or mounting filesystems.  Because the code is so
5431 * similar, we have a common function with an extra parameter to determine which
5432 * mode we are using.
5433 */
5434#define	OP_SHARE	0x1
5435#define	OP_MOUNT	0x2
5436
5437/*
5438 * Share or mount a dataset.
5439 */
5440static int
5441share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5442    boolean_t explicit, const char *options)
5443{
5444	char mountpoint[ZFS_MAXPROPLEN];
5445	char shareopts[ZFS_MAXPROPLEN];
5446	char smbshareopts[ZFS_MAXPROPLEN];
5447	const char *cmdname = op == OP_SHARE ? "share" : "mount";
5448	struct mnttab mnt;
5449	uint64_t zoned, canmount;
5450	boolean_t shared_nfs, shared_smb;
5451
5452	assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5453
5454	/*
5455	 * Check to make sure we can mount/share this dataset.  If we
5456	 * are in the global zone and the filesystem is exported to a
5457	 * local zone, or if we are in a local zone and the
5458	 * filesystem is not exported, then it is an error.
5459	 */
5460	zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5461
5462	if (zoned && getzoneid() == GLOBAL_ZONEID) {
5463		if (!explicit)
5464			return (0);
5465
5466		(void) fprintf(stderr, gettext("cannot %s '%s': "
5467		    "dataset is exported to a local zone\n"), cmdname,
5468		    zfs_get_name(zhp));
5469		return (1);
5470
5471	} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5472		if (!explicit)
5473			return (0);
5474
5475		(void) fprintf(stderr, gettext("cannot %s '%s': "
5476		    "permission denied\n"), cmdname,
5477		    zfs_get_name(zhp));
5478		return (1);
5479	}
5480
5481	/*
5482	 * Ignore any filesystems which don't apply to us. This
5483	 * includes those with a legacy mountpoint, or those with
5484	 * legacy share options.
5485	 */
5486	verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5487	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5488	verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5489	    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5490	verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5491	    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5492
5493	if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5494	    strcmp(smbshareopts, "off") == 0) {
5495		if (!explicit)
5496			return (0);
5497
5498		(void) fprintf(stderr, gettext("cannot share '%s': "
5499		    "legacy share\n"), zfs_get_name(zhp));
5500		(void) fprintf(stderr, gettext("use share(1M) to "
5501		    "share this filesystem, or set "
5502		    "sharenfs property on\n"));
5503		return (1);
5504	}
5505
5506	/*
5507	 * We cannot share or mount legacy filesystems. If the
5508	 * shareopts is non-legacy but the mountpoint is legacy, we
5509	 * treat it as a legacy share.
5510	 */
5511	if (strcmp(mountpoint, "legacy") == 0) {
5512		if (!explicit)
5513			return (0);
5514
5515		(void) fprintf(stderr, gettext("cannot %s '%s': "
5516		    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5517		(void) fprintf(stderr, gettext("use %s(1M) to "
5518		    "%s this filesystem\n"), cmdname, cmdname);
5519		return (1);
5520	}
5521
5522	if (strcmp(mountpoint, "none") == 0) {
5523		if (!explicit)
5524			return (0);
5525
5526		(void) fprintf(stderr, gettext("cannot %s '%s': no "
5527		    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5528		return (1);
5529	}
5530
5531	/*
5532	 * canmount	explicit	outcome
5533	 * on		no		pass through
5534	 * on		yes		pass through
5535	 * off		no		return 0
5536	 * off		yes		display error, return 1
5537	 * noauto	no		return 0
5538	 * noauto	yes		pass through
5539	 */
5540	canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5541	if (canmount == ZFS_CANMOUNT_OFF) {
5542		if (!explicit)
5543			return (0);
5544
5545		(void) fprintf(stderr, gettext("cannot %s '%s': "
5546		    "'canmount' property is set to 'off'\n"), cmdname,
5547		    zfs_get_name(zhp));
5548		return (1);
5549	} else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5550		return (0);
5551	}
5552
5553	/*
5554	 * At this point, we have verified that the mountpoint and/or
5555	 * shareopts are appropriate for auto management. If the
5556	 * filesystem is already mounted or shared, return (failing
5557	 * for explicit requests); otherwise mount or share the
5558	 * filesystem.
5559	 */
5560	switch (op) {
5561	case OP_SHARE:
5562
5563		shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5564		shared_smb = zfs_is_shared_smb(zhp, NULL);
5565
5566		if (shared_nfs && shared_smb ||
5567		    (shared_nfs && strcmp(shareopts, "on") == 0 &&
5568		    strcmp(smbshareopts, "off") == 0) ||
5569		    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5570		    strcmp(shareopts, "off") == 0)) {
5571			if (!explicit)
5572				return (0);
5573
5574			(void) fprintf(stderr, gettext("cannot share "
5575			    "'%s': filesystem already shared\n"),
5576			    zfs_get_name(zhp));
5577			return (1);
5578		}
5579
5580		if (!zfs_is_mounted(zhp, NULL) &&
5581		    zfs_mount(zhp, NULL, 0) != 0)
5582			return (1);
5583
5584		if (protocol == NULL) {
5585			if (zfs_shareall(zhp) != 0)
5586				return (1);
5587		} else if (strcmp(protocol, "nfs") == 0) {
5588			if (zfs_share_nfs(zhp))
5589				return (1);
5590		} else if (strcmp(protocol, "smb") == 0) {
5591			if (zfs_share_smb(zhp))
5592				return (1);
5593		} else {
5594			(void) fprintf(stderr, gettext("cannot share "
5595			    "'%s': invalid share type '%s' "
5596			    "specified\n"),
5597			    zfs_get_name(zhp), protocol);
5598			return (1);
5599		}
5600
5601		break;
5602
5603	case OP_MOUNT:
5604		if (options == NULL)
5605			mnt.mnt_mntopts = "";
5606		else
5607			mnt.mnt_mntopts = (char *)options;
5608
5609		if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5610		    zfs_is_mounted(zhp, NULL)) {
5611			if (!explicit)
5612				return (0);
5613
5614			(void) fprintf(stderr, gettext("cannot mount "
5615			    "'%s': filesystem already mounted\n"),
5616			    zfs_get_name(zhp));
5617			return (1);
5618		}
5619
5620		if (zfs_mount(zhp, options, flags) != 0)
5621			return (1);
5622		break;
5623	}
5624
5625	return (0);
5626}
5627
5628/*
5629 * Reports progress in the form "(current/total)".  Not thread-safe.
5630 */
5631static void
5632report_mount_progress(int current, int total)
5633{
5634	static time_t last_progress_time = 0;
5635	time_t now = time(NULL);
5636	char info[32];
5637
5638	/* report 1..n instead of 0..n-1 */
5639	++current;
5640
5641	/* display header if we're here for the first time */
5642	if (current == 1) {
5643		set_progress_header(gettext("Mounting ZFS filesystems"));
5644	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5645		/* too soon to report again */
5646		return;
5647	}
5648
5649	last_progress_time = now;
5650
5651	(void) sprintf(info, "(%d/%d)", current, total);
5652
5653	if (current == total)
5654		finish_progress(info);
5655	else
5656		update_progress(info);
5657}
5658
5659static void
5660append_options(char *mntopts, char *newopts)
5661{
5662	int len = strlen(mntopts);
5663
5664	/* original length plus new string to append plus 1 for the comma */
5665	if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5666		(void) fprintf(stderr, gettext("the opts argument for "
5667		    "'%c' option is too long (more than %d chars)\n"),
5668		    "-o", MNT_LINE_MAX);
5669		usage(B_FALSE);
5670	}
5671
5672	if (*mntopts)
5673		mntopts[len++] = ',';
5674
5675	(void) strcpy(&mntopts[len], newopts);
5676}
5677
5678static int
5679share_mount(int op, int argc, char **argv)
5680{
5681	int do_all = 0;
5682	boolean_t verbose = B_FALSE;
5683	int c, ret = 0;
5684	char *options = NULL;
5685	int flags = 0;
5686
5687	/* check options */
5688	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5689	    != -1) {
5690		switch (c) {
5691		case 'a':
5692			do_all = 1;
5693			break;
5694		case 'v':
5695			verbose = B_TRUE;
5696			break;
5697		case 'o':
5698			if (*optarg == '\0') {
5699				(void) fprintf(stderr, gettext("empty mount "
5700				    "options (-o) specified\n"));
5701				usage(B_FALSE);
5702			}
5703
5704			if (options == NULL)
5705				options = safe_malloc(MNT_LINE_MAX + 1);
5706
5707			/* option validation is done later */
5708			append_options(options, optarg);
5709			break;
5710
5711		case 'O':
5712			warnx("no overlay mounts support on FreeBSD, ignoring");
5713			break;
5714		case ':':
5715			(void) fprintf(stderr, gettext("missing argument for "
5716			    "'%c' option\n"), optopt);
5717			usage(B_FALSE);
5718			break;
5719		case '?':
5720			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5721			    optopt);
5722			usage(B_FALSE);
5723		}
5724	}
5725
5726	argc -= optind;
5727	argv += optind;
5728
5729	/* check number of arguments */
5730	if (do_all) {
5731		zfs_handle_t **dslist = NULL;
5732		size_t i, count = 0;
5733		char *protocol = NULL;
5734
5735		if (op == OP_SHARE && argc > 0) {
5736			if (strcmp(argv[0], "nfs") != 0 &&
5737			    strcmp(argv[0], "smb") != 0) {
5738				(void) fprintf(stderr, gettext("share type "
5739				    "must be 'nfs' or 'smb'\n"));
5740				usage(B_FALSE);
5741			}
5742			protocol = argv[0];
5743			argc--;
5744			argv++;
5745		}
5746
5747		if (argc != 0) {
5748			(void) fprintf(stderr, gettext("too many arguments\n"));
5749			usage(B_FALSE);
5750		}
5751
5752		start_progress_timer();
5753		get_all_datasets(&dslist, &count, verbose);
5754
5755		if (count == 0)
5756			return (0);
5757
5758		qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
5759
5760		for (i = 0; i < count; i++) {
5761			if (verbose)
5762				report_mount_progress(i, count);
5763
5764			if (share_mount_one(dslist[i], op, flags, protocol,
5765			    B_FALSE, options) != 0)
5766				ret = 1;
5767			zfs_close(dslist[i]);
5768		}
5769
5770		free(dslist);
5771	} else if (argc == 0) {
5772		struct mnttab entry;
5773
5774		if ((op == OP_SHARE) || (options != NULL)) {
5775			(void) fprintf(stderr, gettext("missing filesystem "
5776			    "argument (specify -a for all)\n"));
5777			usage(B_FALSE);
5778		}
5779
5780		/*
5781		 * When mount is given no arguments, go through /etc/mnttab and
5782		 * display any active ZFS mounts.  We hide any snapshots, since
5783		 * they are controlled automatically.
5784		 */
5785		rewind(mnttab_file);
5786		while (getmntent(mnttab_file, &entry) == 0) {
5787			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
5788			    strchr(entry.mnt_special, '@') != NULL)
5789				continue;
5790
5791			(void) printf("%-30s  %s\n", entry.mnt_special,
5792			    entry.mnt_mountp);
5793		}
5794
5795	} else {
5796		zfs_handle_t *zhp;
5797
5798		if (argc > 1) {
5799			(void) fprintf(stderr,
5800			    gettext("too many arguments\n"));
5801			usage(B_FALSE);
5802		}
5803
5804		if ((zhp = zfs_open(g_zfs, argv[0],
5805		    ZFS_TYPE_FILESYSTEM)) == NULL) {
5806			ret = 1;
5807		} else {
5808			ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
5809			    options);
5810			zfs_close(zhp);
5811		}
5812	}
5813
5814	return (ret);
5815}
5816
5817/*
5818 * zfs mount -a [nfs]
5819 * zfs mount filesystem
5820 *
5821 * Mount all filesystems, or mount the given filesystem.
5822 */
5823static int
5824zfs_do_mount(int argc, char **argv)
5825{
5826	return (share_mount(OP_MOUNT, argc, argv));
5827}
5828
5829/*
5830 * zfs share -a [nfs | smb]
5831 * zfs share filesystem
5832 *
5833 * Share all filesystems, or share the given filesystem.
5834 */
5835static int
5836zfs_do_share(int argc, char **argv)
5837{
5838	return (share_mount(OP_SHARE, argc, argv));
5839}
5840
5841typedef struct unshare_unmount_node {
5842	zfs_handle_t	*un_zhp;
5843	char		*un_mountp;
5844	uu_avl_node_t	un_avlnode;
5845} unshare_unmount_node_t;
5846
5847/* ARGSUSED */
5848static int
5849unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
5850{
5851	const unshare_unmount_node_t *l = larg;
5852	const unshare_unmount_node_t *r = rarg;
5853
5854	return (strcmp(l->un_mountp, r->un_mountp));
5855}
5856
5857/*
5858 * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
5859 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
5860 * and unmount it appropriately.
5861 */
5862static int
5863unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
5864{
5865	zfs_handle_t *zhp;
5866	int ret;
5867	struct stat64 statbuf;
5868	struct extmnttab entry;
5869	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
5870	ino_t path_inode;
5871
5872	/*
5873	 * Search for the path in /etc/mnttab.  Rather than looking for the
5874	 * specific path, which can be fooled by non-standard paths (i.e. ".."
5875	 * or "//"), we stat() the path and search for the corresponding
5876	 * (major,minor) device pair.
5877	 */
5878	if (stat64(path, &statbuf) != 0) {
5879		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5880		    cmdname, path, strerror(errno));
5881		return (1);
5882	}
5883	path_inode = statbuf.st_ino;
5884
5885	/*
5886	 * Search for the given (major,minor) pair in the mount table.
5887	 */
5888#ifdef sun
5889	rewind(mnttab_file);
5890	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
5891		if (entry.mnt_major == major(statbuf.st_dev) &&
5892		    entry.mnt_minor == minor(statbuf.st_dev))
5893			break;
5894	}
5895#else
5896	{
5897		struct statfs sfs;
5898
5899		if (statfs(path, &sfs) != 0) {
5900			(void) fprintf(stderr, "%s: %s\n", path,
5901			    strerror(errno));
5902			ret = -1;
5903		}
5904		statfs2mnttab(&sfs, &entry);
5905	}
5906#endif
5907	if (ret != 0) {
5908		if (op == OP_SHARE) {
5909			(void) fprintf(stderr, gettext("cannot %s '%s': not "
5910			    "currently mounted\n"), cmdname, path);
5911			return (1);
5912		}
5913		(void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
5914		    path);
5915		if ((ret = umount2(path, flags)) != 0)
5916			(void) fprintf(stderr, gettext("%s: %s\n"), path,
5917			    strerror(errno));
5918		return (ret != 0);
5919	}
5920
5921	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
5922		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
5923		    "filesystem\n"), cmdname, path);
5924		return (1);
5925	}
5926
5927	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
5928	    ZFS_TYPE_FILESYSTEM)) == NULL)
5929		return (1);
5930
5931	ret = 1;
5932	if (stat64(entry.mnt_mountp, &statbuf) != 0) {
5933		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5934		    cmdname, path, strerror(errno));
5935		goto out;
5936	} else if (statbuf.st_ino != path_inode) {
5937		(void) fprintf(stderr, gettext("cannot "
5938		    "%s '%s': not a mountpoint\n"), cmdname, path);
5939		goto out;
5940	}
5941
5942	if (op == OP_SHARE) {
5943		char nfs_mnt_prop[ZFS_MAXPROPLEN];
5944		char smbshare_prop[ZFS_MAXPROPLEN];
5945
5946		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
5947		    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
5948		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
5949		    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
5950
5951		if (strcmp(nfs_mnt_prop, "off") == 0 &&
5952		    strcmp(smbshare_prop, "off") == 0) {
5953			(void) fprintf(stderr, gettext("cannot unshare "
5954			    "'%s': legacy share\n"), path);
5955			(void) fprintf(stderr, gettext("use "
5956			    "unshare(1M) to unshare this filesystem\n"));
5957		} else if (!zfs_is_shared(zhp)) {
5958			(void) fprintf(stderr, gettext("cannot unshare '%s': "
5959			    "not currently shared\n"), path);
5960		} else {
5961			ret = zfs_unshareall_bypath(zhp, path);
5962		}
5963	} else {
5964		char mtpt_prop[ZFS_MAXPROPLEN];
5965
5966		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
5967		    sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
5968
5969		if (is_manual) {
5970			ret = zfs_unmount(zhp, NULL, flags);
5971		} else if (strcmp(mtpt_prop, "legacy") == 0) {
5972			(void) fprintf(stderr, gettext("cannot unmount "
5973			    "'%s': legacy mountpoint\n"),
5974			    zfs_get_name(zhp));
5975			(void) fprintf(stderr, gettext("use umount(1M) "
5976			    "to unmount this filesystem\n"));
5977		} else {
5978			ret = zfs_unmountall(zhp, flags);
5979		}
5980	}
5981
5982out:
5983	zfs_close(zhp);
5984
5985	return (ret != 0);
5986}
5987
5988/*
5989 * Generic callback for unsharing or unmounting a filesystem.
5990 */
5991static int
5992unshare_unmount(int op, int argc, char **argv)
5993{
5994	int do_all = 0;
5995	int flags = 0;
5996	int ret = 0;
5997	int c;
5998	zfs_handle_t *zhp;
5999	char nfs_mnt_prop[ZFS_MAXPROPLEN];
6000	char sharesmb[ZFS_MAXPROPLEN];
6001
6002	/* check options */
6003	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6004		switch (c) {
6005		case 'a':
6006			do_all = 1;
6007			break;
6008		case 'f':
6009			flags = MS_FORCE;
6010			break;
6011		case '?':
6012			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6013			    optopt);
6014			usage(B_FALSE);
6015		}
6016	}
6017
6018	argc -= optind;
6019	argv += optind;
6020
6021	if (do_all) {
6022		/*
6023		 * We could make use of zfs_for_each() to walk all datasets in
6024		 * the system, but this would be very inefficient, especially
6025		 * since we would have to linearly search /etc/mnttab for each
6026		 * one.  Instead, do one pass through /etc/mnttab looking for
6027		 * zfs entries and call zfs_unmount() for each one.
6028		 *
6029		 * Things get a little tricky if the administrator has created
6030		 * mountpoints beneath other ZFS filesystems.  In this case, we
6031		 * have to unmount the deepest filesystems first.  To accomplish
6032		 * this, we place all the mountpoints in an AVL tree sorted by
6033		 * the special type (dataset name), and walk the result in
6034		 * reverse to make sure to get any snapshots first.
6035		 */
6036		struct mnttab entry;
6037		uu_avl_pool_t *pool;
6038		uu_avl_t *tree;
6039		unshare_unmount_node_t *node;
6040		uu_avl_index_t idx;
6041		uu_avl_walk_t *walk;
6042
6043		if (argc != 0) {
6044			(void) fprintf(stderr, gettext("too many arguments\n"));
6045			usage(B_FALSE);
6046		}
6047
6048		if (((pool = uu_avl_pool_create("unmount_pool",
6049		    sizeof (unshare_unmount_node_t),
6050		    offsetof(unshare_unmount_node_t, un_avlnode),
6051		    unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6052		    ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6053			nomem();
6054
6055		rewind(mnttab_file);
6056		while (getmntent(mnttab_file, &entry) == 0) {
6057
6058			/* ignore non-ZFS entries */
6059			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6060				continue;
6061
6062			/* ignore snapshots */
6063			if (strchr(entry.mnt_special, '@') != NULL)
6064				continue;
6065
6066			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6067			    ZFS_TYPE_FILESYSTEM)) == NULL) {
6068				ret = 1;
6069				continue;
6070			}
6071
6072			switch (op) {
6073			case OP_SHARE:
6074				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6075				    nfs_mnt_prop,
6076				    sizeof (nfs_mnt_prop),
6077				    NULL, NULL, 0, B_FALSE) == 0);
6078				if (strcmp(nfs_mnt_prop, "off") != 0)
6079					break;
6080				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6081				    nfs_mnt_prop,
6082				    sizeof (nfs_mnt_prop),
6083				    NULL, NULL, 0, B_FALSE) == 0);
6084				if (strcmp(nfs_mnt_prop, "off") == 0)
6085					continue;
6086				break;
6087			case OP_MOUNT:
6088				/* Ignore legacy mounts */
6089				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6090				    nfs_mnt_prop,
6091				    sizeof (nfs_mnt_prop),
6092				    NULL, NULL, 0, B_FALSE) == 0);
6093				if (strcmp(nfs_mnt_prop, "legacy") == 0)
6094					continue;
6095				/* Ignore canmount=noauto mounts */
6096				if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6097				    ZFS_CANMOUNT_NOAUTO)
6098					continue;
6099			default:
6100				break;
6101			}
6102
6103			node = safe_malloc(sizeof (unshare_unmount_node_t));
6104			node->un_zhp = zhp;
6105			node->un_mountp = safe_strdup(entry.mnt_mountp);
6106
6107			uu_avl_node_init(node, &node->un_avlnode, pool);
6108
6109			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6110				uu_avl_insert(tree, node, idx);
6111			} else {
6112				zfs_close(node->un_zhp);
6113				free(node->un_mountp);
6114				free(node);
6115			}
6116		}
6117
6118		/*
6119		 * Walk the AVL tree in reverse, unmounting each filesystem and
6120		 * removing it from the AVL tree in the process.
6121		 */
6122		if ((walk = uu_avl_walk_start(tree,
6123		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6124			nomem();
6125
6126		while ((node = uu_avl_walk_next(walk)) != NULL) {
6127			uu_avl_remove(tree, node);
6128
6129			switch (op) {
6130			case OP_SHARE:
6131				if (zfs_unshareall_bypath(node->un_zhp,
6132				    node->un_mountp) != 0)
6133					ret = 1;
6134				break;
6135
6136			case OP_MOUNT:
6137				if (zfs_unmount(node->un_zhp,
6138				    node->un_mountp, flags) != 0)
6139					ret = 1;
6140				break;
6141			}
6142
6143			zfs_close(node->un_zhp);
6144			free(node->un_mountp);
6145			free(node);
6146		}
6147
6148		uu_avl_walk_end(walk);
6149		uu_avl_destroy(tree);
6150		uu_avl_pool_destroy(pool);
6151
6152	} else {
6153		if (argc != 1) {
6154			if (argc == 0)
6155				(void) fprintf(stderr,
6156				    gettext("missing filesystem argument\n"));
6157			else
6158				(void) fprintf(stderr,
6159				    gettext("too many arguments\n"));
6160			usage(B_FALSE);
6161		}
6162
6163		/*
6164		 * We have an argument, but it may be a full path or a ZFS
6165		 * filesystem.  Pass full paths off to unmount_path() (shared by
6166		 * manual_unmount), otherwise open the filesystem and pass to
6167		 * zfs_unmount().
6168		 */
6169		if (argv[0][0] == '/')
6170			return (unshare_unmount_path(op, argv[0],
6171			    flags, B_FALSE));
6172
6173		if ((zhp = zfs_open(g_zfs, argv[0],
6174		    ZFS_TYPE_FILESYSTEM)) == NULL)
6175			return (1);
6176
6177		verify(zfs_prop_get(zhp, op == OP_SHARE ?
6178		    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6179		    nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6180		    NULL, 0, B_FALSE) == 0);
6181
6182		switch (op) {
6183		case OP_SHARE:
6184			verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6185			    nfs_mnt_prop,
6186			    sizeof (nfs_mnt_prop),
6187			    NULL, NULL, 0, B_FALSE) == 0);
6188			verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6189			    sharesmb, sizeof (sharesmb), NULL, NULL,
6190			    0, B_FALSE) == 0);
6191
6192			if (strcmp(nfs_mnt_prop, "off") == 0 &&
6193			    strcmp(sharesmb, "off") == 0) {
6194				(void) fprintf(stderr, gettext("cannot "
6195				    "unshare '%s': legacy share\n"),
6196				    zfs_get_name(zhp));
6197				(void) fprintf(stderr, gettext("use "
6198				    "unshare(1M) to unshare this "
6199				    "filesystem\n"));
6200				ret = 1;
6201			} else if (!zfs_is_shared(zhp)) {
6202				(void) fprintf(stderr, gettext("cannot "
6203				    "unshare '%s': not currently "
6204				    "shared\n"), zfs_get_name(zhp));
6205				ret = 1;
6206			} else if (zfs_unshareall(zhp) != 0) {
6207				ret = 1;
6208			}
6209			break;
6210
6211		case OP_MOUNT:
6212			if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6213				(void) fprintf(stderr, gettext("cannot "
6214				    "unmount '%s': legacy "
6215				    "mountpoint\n"), zfs_get_name(zhp));
6216				(void) fprintf(stderr, gettext("use "
6217				    "umount(1M) to unmount this "
6218				    "filesystem\n"));
6219				ret = 1;
6220			} else if (!zfs_is_mounted(zhp, NULL)) {
6221				(void) fprintf(stderr, gettext("cannot "
6222				    "unmount '%s': not currently "
6223				    "mounted\n"),
6224				    zfs_get_name(zhp));
6225				ret = 1;
6226			} else if (zfs_unmountall(zhp, flags) != 0) {
6227				ret = 1;
6228			}
6229			break;
6230		}
6231
6232		zfs_close(zhp);
6233	}
6234
6235	return (ret);
6236}
6237
6238/*
6239 * zfs unmount -a
6240 * zfs unmount filesystem
6241 *
6242 * Unmount all filesystems, or a specific ZFS filesystem.
6243 */
6244static int
6245zfs_do_unmount(int argc, char **argv)
6246{
6247	return (unshare_unmount(OP_MOUNT, argc, argv));
6248}
6249
6250/*
6251 * zfs unshare -a
6252 * zfs unshare filesystem
6253 *
6254 * Unshare all filesystems, or a specific ZFS filesystem.
6255 */
6256static int
6257zfs_do_unshare(int argc, char **argv)
6258{
6259	return (unshare_unmount(OP_SHARE, argc, argv));
6260}
6261
6262/*
6263 * Attach/detach the given dataset to/from the given jail
6264 */
6265/* ARGSUSED */
6266static int
6267do_jail(int argc, char **argv, int attach)
6268{
6269	zfs_handle_t *zhp;
6270	int jailid, ret;
6271
6272	/* check number of arguments */
6273	if (argc < 3) {
6274		(void) fprintf(stderr, gettext("missing argument(s)\n"));
6275		usage(B_FALSE);
6276	}
6277	if (argc > 3) {
6278		(void) fprintf(stderr, gettext("too many arguments\n"));
6279		usage(B_FALSE);
6280	}
6281
6282	jailid = atoi(argv[1]);
6283	if (jailid == 0) {
6284		(void) fprintf(stderr, gettext("invalid jailid\n"));
6285		usage(B_FALSE);
6286	}
6287
6288	zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
6289	if (zhp == NULL)
6290		return (1);
6291
6292	ret = (zfs_jail(zhp, jailid, attach) != 0);
6293
6294	zfs_close(zhp);
6295	return (ret);
6296}
6297
6298/*
6299 * zfs jail jailid filesystem
6300 *
6301 * Attach the given dataset to the given jail
6302 */
6303/* ARGSUSED */
6304static int
6305zfs_do_jail(int argc, char **argv)
6306{
6307
6308	return (do_jail(argc, argv, 1));
6309}
6310
6311/*
6312 * zfs unjail jailid filesystem
6313 *
6314 * Detach the given dataset from the given jail
6315 */
6316/* ARGSUSED */
6317static int
6318zfs_do_unjail(int argc, char **argv)
6319{
6320
6321	return (do_jail(argc, argv, 0));
6322}
6323
6324/*
6325 * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6326 * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6327 */
6328static int
6329manual_mount(int argc, char **argv)
6330{
6331	zfs_handle_t *zhp;
6332	char mountpoint[ZFS_MAXPROPLEN];
6333	char mntopts[MNT_LINE_MAX] = { '\0' };
6334	int ret;
6335	int c;
6336	int flags = 0;
6337	char *dataset, *path;
6338
6339	/* check options */
6340	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6341		switch (c) {
6342		case 'o':
6343			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
6344			break;
6345		case 'O':
6346			flags |= MS_OVERLAY;
6347			break;
6348		case 'm':
6349			flags |= MS_NOMNTTAB;
6350			break;
6351		case ':':
6352			(void) fprintf(stderr, gettext("missing argument for "
6353			    "'%c' option\n"), optopt);
6354			usage(B_FALSE);
6355			break;
6356		case '?':
6357			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6358			    optopt);
6359			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
6360			    "<path>\n"));
6361			return (2);
6362		}
6363	}
6364
6365	argc -= optind;
6366	argv += optind;
6367
6368	/* check that we only have two arguments */
6369	if (argc != 2) {
6370		if (argc == 0)
6371			(void) fprintf(stderr, gettext("missing dataset "
6372			    "argument\n"));
6373		else if (argc == 1)
6374			(void) fprintf(stderr,
6375			    gettext("missing mountpoint argument\n"));
6376		else
6377			(void) fprintf(stderr, gettext("too many arguments\n"));
6378		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6379		return (2);
6380	}
6381
6382	dataset = argv[0];
6383	path = argv[1];
6384
6385	/* try to open the dataset */
6386	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6387		return (1);
6388
6389	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6390	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6391
6392	/* check for legacy mountpoint and complain appropriately */
6393	ret = 0;
6394	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6395		if (zmount(dataset, path, flags, MNTTYPE_ZFS,
6396		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6397			(void) fprintf(stderr, gettext("mount failed: %s\n"),
6398			    strerror(errno));
6399			ret = 1;
6400		}
6401	} else {
6402		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6403		    "mounted using 'mount -F zfs'\n"), dataset);
6404		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6405		    "instead.\n"), path);
6406		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6407		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6408		(void) fprintf(stderr, gettext("See zfs(1M) for more "
6409		    "information.\n"));
6410		ret = 1;
6411	}
6412
6413	return (ret);
6414}
6415
6416/*
6417 * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6418 * unmounts of non-legacy filesystems, as this is the dominant administrative
6419 * interface.
6420 */
6421static int
6422manual_unmount(int argc, char **argv)
6423{
6424	int flags = 0;
6425	int c;
6426
6427	/* check options */
6428	while ((c = getopt(argc, argv, "f")) != -1) {
6429		switch (c) {
6430		case 'f':
6431			flags = MS_FORCE;
6432			break;
6433		case '?':
6434			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6435			    optopt);
6436			(void) fprintf(stderr, gettext("usage: unmount [-f] "
6437			    "<path>\n"));
6438			return (2);
6439		}
6440	}
6441
6442	argc -= optind;
6443	argv += optind;
6444
6445	/* check arguments */
6446	if (argc != 1) {
6447		if (argc == 0)
6448			(void) fprintf(stderr, gettext("missing path "
6449			    "argument\n"));
6450		else
6451			(void) fprintf(stderr, gettext("too many arguments\n"));
6452		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6453		return (2);
6454	}
6455
6456	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6457}
6458
6459static int
6460find_command_idx(char *command, int *idx)
6461{
6462	int i;
6463
6464	for (i = 0; i < NCOMMAND; i++) {
6465		if (command_table[i].name == NULL)
6466			continue;
6467
6468		if (strcmp(command, command_table[i].name) == 0) {
6469			*idx = i;
6470			return (0);
6471		}
6472	}
6473	return (1);
6474}
6475
6476static int
6477zfs_do_diff(int argc, char **argv)
6478{
6479	zfs_handle_t *zhp;
6480	int flags = 0;
6481	char *tosnap = NULL;
6482	char *fromsnap = NULL;
6483	char *atp, *copy;
6484	int err;
6485	int c;
6486
6487	while ((c = getopt(argc, argv, "FHt")) != -1) {
6488		switch (c) {
6489		case 'F':
6490			flags |= ZFS_DIFF_CLASSIFY;
6491			break;
6492		case 'H':
6493			flags |= ZFS_DIFF_PARSEABLE;
6494			break;
6495		case 't':
6496			flags |= ZFS_DIFF_TIMESTAMP;
6497			break;
6498		default:
6499			(void) fprintf(stderr,
6500			    gettext("invalid option '%c'\n"), optopt);
6501			usage(B_FALSE);
6502		}
6503	}
6504
6505	argc -= optind;
6506	argv += optind;
6507
6508	if (argc < 1) {
6509		(void) fprintf(stderr,
6510		gettext("must provide at least one snapshot name\n"));
6511		usage(B_FALSE);
6512	}
6513
6514	if (argc > 2) {
6515		(void) fprintf(stderr, gettext("too many arguments\n"));
6516		usage(B_FALSE);
6517	}
6518
6519	fromsnap = argv[0];
6520	tosnap = (argc == 2) ? argv[1] : NULL;
6521
6522	copy = NULL;
6523	if (*fromsnap != '@')
6524		copy = strdup(fromsnap);
6525	else if (tosnap)
6526		copy = strdup(tosnap);
6527	if (copy == NULL)
6528		usage(B_FALSE);
6529
6530	if (atp = strchr(copy, '@'))
6531		*atp = '\0';
6532
6533	if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6534		return (1);
6535
6536	free(copy);
6537
6538	/*
6539	 * Ignore SIGPIPE so that the library can give us
6540	 * information on any failure
6541	 */
6542	(void) sigignore(SIGPIPE);
6543
6544	err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6545
6546	zfs_close(zhp);
6547
6548	return (err != 0);
6549}
6550
6551int
6552main(int argc, char **argv)
6553{
6554	int ret;
6555	int i;
6556	char *progname;
6557	char *cmdname;
6558
6559	(void) setlocale(LC_ALL, "");
6560	(void) textdomain(TEXT_DOMAIN);
6561
6562	opterr = 0;
6563
6564	if ((g_zfs = libzfs_init()) == NULL) {
6565		(void) fprintf(stderr, gettext("internal error: failed to "
6566		    "initialize ZFS library\n"));
6567		return (1);
6568	}
6569
6570	zpool_set_history_str("zfs", argc, argv, history_str);
6571	verify(zpool_stage_history(g_zfs, history_str) == 0);
6572
6573	libzfs_print_on_error(g_zfs, B_TRUE);
6574
6575	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6576		(void) fprintf(stderr, gettext("internal error: unable to "
6577		    "open %s\n"), MNTTAB);
6578		return (1);
6579	}
6580
6581	/*
6582	 * This command also doubles as the /etc/fs mount and unmount program.
6583	 * Determine if we should take this behavior based on argv[0].
6584	 */
6585	progname = basename(argv[0]);
6586	if (strcmp(progname, "mount") == 0) {
6587		ret = manual_mount(argc, argv);
6588	} else if (strcmp(progname, "umount") == 0) {
6589		ret = manual_unmount(argc, argv);
6590	} else {
6591		/*
6592		 * Make sure the user has specified some command.
6593		 */
6594		if (argc < 2) {
6595			(void) fprintf(stderr, gettext("missing command\n"));
6596			usage(B_FALSE);
6597		}
6598
6599		cmdname = argv[1];
6600
6601		/*
6602		 * The 'umount' command is an alias for 'unmount'
6603		 */
6604		if (strcmp(cmdname, "umount") == 0)
6605			cmdname = "unmount";
6606
6607		/*
6608		 * The 'recv' command is an alias for 'receive'
6609		 */
6610		if (strcmp(cmdname, "recv") == 0)
6611			cmdname = "receive";
6612
6613		/*
6614		 * Special case '-?'
6615		 */
6616		if (strcmp(cmdname, "-?") == 0)
6617			usage(B_TRUE);
6618
6619		/*
6620		 * Run the appropriate command.
6621		 */
6622		libzfs_mnttab_cache(g_zfs, B_TRUE);
6623		if (find_command_idx(cmdname, &i) == 0) {
6624			current_command = &command_table[i];
6625			ret = command_table[i].func(argc - 1, argv + 1);
6626		} else if (strchr(cmdname, '=') != NULL) {
6627			verify(find_command_idx("set", &i) == 0);
6628			current_command = &command_table[i];
6629			ret = command_table[i].func(argc, argv);
6630		} else {
6631			(void) fprintf(stderr, gettext("unrecognized "
6632			    "command '%s'\n"), cmdname);
6633			usage(B_FALSE);
6634		}
6635		libzfs_mnttab_cache(g_zfs, B_FALSE);
6636	}
6637
6638	(void) fclose(mnttab_file);
6639
6640	libzfs_fini(g_zfs);
6641
6642	/*
6643	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6644	 * for the purposes of running ::findleaks.
6645	 */
6646	if (getenv("ZFS_ABORT") != NULL) {
6647		(void) printf("dumping core by request\n");
6648		abort();
6649	}
6650
6651	return (ret);
6652}
6653