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