xref: /freebsd/sys/contrib/openzfs/cmd/zfs/zfs_main.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright 2012 Milan Jurik. All rights reserved.
27  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
28  * Copyright (c) 2013 Steven Hartland.  All rights reserved.
29  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
30  * Copyright 2016 Nexenta Systems, Inc.
31  * Copyright (c) 2019 Datto Inc.
32  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
33  * Copyright 2019 Joyent, Inc.
34  * Copyright (c) 2019, 2020 by Christian Schwarz. All rights reserved.
35  */
36 
37 #include <assert.h>
38 #include <ctype.h>
39 #include <sys/debug.h>
40 #include <errno.h>
41 #include <getopt.h>
42 #include <libgen.h>
43 #include <libintl.h>
44 #include <libuutil.h>
45 #include <libnvpair.h>
46 #include <locale.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <zone.h>
54 #include <grp.h>
55 #include <pwd.h>
56 #include <umem.h>
57 #include <pthread.h>
58 #include <signal.h>
59 #include <sys/list.h>
60 #include <sys/mkdev.h>
61 #include <sys/mntent.h>
62 #include <sys/mnttab.h>
63 #include <sys/mount.h>
64 #include <sys/stat.h>
65 #include <sys/fs/zfs.h>
66 #include <sys/systeminfo.h>
67 #include <sys/types.h>
68 #include <time.h>
69 #include <sys/zfs_project.h>
70 
71 #include <libzfs.h>
72 #include <libzfs_core.h>
73 #include <zfs_prop.h>
74 #include <zfs_deleg.h>
75 #include <libzutil.h>
76 #ifdef HAVE_IDMAP
77 #include <aclutils.h>
78 #include <directory.h>
79 #endif /* HAVE_IDMAP */
80 
81 #include "zfs_iter.h"
82 #include "zfs_util.h"
83 #include "zfs_comutil.h"
84 #include "zfs_projectutil.h"
85 
86 libzfs_handle_t *g_zfs;
87 
88 static char history_str[HIS_MAX_RECORD_LEN];
89 static boolean_t log_history = B_TRUE;
90 
91 static int zfs_do_clone(int argc, char **argv);
92 static int zfs_do_create(int argc, char **argv);
93 static int zfs_do_destroy(int argc, char **argv);
94 static int zfs_do_get(int argc, char **argv);
95 static int zfs_do_inherit(int argc, char **argv);
96 static int zfs_do_list(int argc, char **argv);
97 static int zfs_do_mount(int argc, char **argv);
98 static int zfs_do_rename(int argc, char **argv);
99 static int zfs_do_rollback(int argc, char **argv);
100 static int zfs_do_set(int argc, char **argv);
101 static int zfs_do_upgrade(int argc, char **argv);
102 static int zfs_do_snapshot(int argc, char **argv);
103 static int zfs_do_unmount(int argc, char **argv);
104 static int zfs_do_share(int argc, char **argv);
105 static int zfs_do_unshare(int argc, char **argv);
106 static int zfs_do_send(int argc, char **argv);
107 static int zfs_do_receive(int argc, char **argv);
108 static int zfs_do_promote(int argc, char **argv);
109 static int zfs_do_userspace(int argc, char **argv);
110 static int zfs_do_allow(int argc, char **argv);
111 static int zfs_do_unallow(int argc, char **argv);
112 static int zfs_do_hold(int argc, char **argv);
113 static int zfs_do_holds(int argc, char **argv);
114 static int zfs_do_release(int argc, char **argv);
115 static int zfs_do_diff(int argc, char **argv);
116 static int zfs_do_bookmark(int argc, char **argv);
117 static int zfs_do_channel_program(int argc, char **argv);
118 static int zfs_do_load_key(int argc, char **argv);
119 static int zfs_do_unload_key(int argc, char **argv);
120 static int zfs_do_change_key(int argc, char **argv);
121 static int zfs_do_project(int argc, char **argv);
122 static int zfs_do_version(int argc, char **argv);
123 static int zfs_do_redact(int argc, char **argv);
124 static int zfs_do_wait(int argc, char **argv);
125 
126 #ifdef __FreeBSD__
127 static int zfs_do_jail(int argc, char **argv);
128 static int zfs_do_unjail(int argc, char **argv);
129 #endif
130 
131 #ifdef __linux__
132 static int zfs_do_zone(int argc, char **argv);
133 static int zfs_do_unzone(int argc, char **argv);
134 #endif
135 
136 static int zfs_do_help(int argc, char **argv);
137 
138 enum zfs_options {
139 	ZFS_OPTION_JSON_NUMS_AS_INT = 1024
140 };
141 
142 /*
143  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
144  */
145 
146 #ifdef DEBUG
147 const char *
_umem_debug_init(void)148 _umem_debug_init(void)
149 {
150 	return ("default,verbose"); /* $UMEM_DEBUG setting */
151 }
152 
153 const char *
_umem_logging_init(void)154 _umem_logging_init(void)
155 {
156 	return ("fail,contents"); /* $UMEM_LOGGING setting */
157 }
158 #endif
159 
160 typedef enum {
161 	HELP_CLONE,
162 	HELP_CREATE,
163 	HELP_DESTROY,
164 	HELP_GET,
165 	HELP_INHERIT,
166 	HELP_UPGRADE,
167 	HELP_LIST,
168 	HELP_MOUNT,
169 	HELP_PROMOTE,
170 	HELP_RECEIVE,
171 	HELP_RENAME,
172 	HELP_ROLLBACK,
173 	HELP_SEND,
174 	HELP_SET,
175 	HELP_SHARE,
176 	HELP_SNAPSHOT,
177 	HELP_UNMOUNT,
178 	HELP_UNSHARE,
179 	HELP_ALLOW,
180 	HELP_UNALLOW,
181 	HELP_USERSPACE,
182 	HELP_GROUPSPACE,
183 	HELP_PROJECTSPACE,
184 	HELP_PROJECT,
185 	HELP_HOLD,
186 	HELP_HOLDS,
187 	HELP_RELEASE,
188 	HELP_DIFF,
189 	HELP_BOOKMARK,
190 	HELP_CHANNEL_PROGRAM,
191 	HELP_LOAD_KEY,
192 	HELP_UNLOAD_KEY,
193 	HELP_CHANGE_KEY,
194 	HELP_VERSION,
195 	HELP_REDACT,
196 	HELP_JAIL,
197 	HELP_UNJAIL,
198 	HELP_WAIT,
199 	HELP_ZONE,
200 	HELP_UNZONE,
201 } zfs_help_t;
202 
203 typedef struct zfs_command {
204 	const char	*name;
205 	int		(*func)(int argc, char **argv);
206 	zfs_help_t	usage;
207 } zfs_command_t;
208 
209 /*
210  * Master command table.  Each ZFS command has a name, associated function, and
211  * usage message.  The usage messages need to be internationalized, so we have
212  * to have a function to return the usage message based on a command index.
213  *
214  * These commands are organized according to how they are displayed in the usage
215  * message.  An empty command (one with a NULL name) indicates an empty line in
216  * the generic usage message.
217  */
218 static zfs_command_t command_table[] = {
219 	{ "version",	zfs_do_version, 	HELP_VERSION		},
220 	{ NULL },
221 	{ "create",	zfs_do_create,		HELP_CREATE		},
222 	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
223 	{ NULL },
224 	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
225 	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
226 	{ "clone",	zfs_do_clone,		HELP_CLONE		},
227 	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
228 	{ "rename",	zfs_do_rename,		HELP_RENAME		},
229 	{ "bookmark",	zfs_do_bookmark,	HELP_BOOKMARK		},
230 	{ "program",    zfs_do_channel_program, HELP_CHANNEL_PROGRAM    },
231 	{ NULL },
232 	{ "list",	zfs_do_list,		HELP_LIST		},
233 	{ NULL },
234 	{ "set",	zfs_do_set,		HELP_SET		},
235 	{ "get",	zfs_do_get,		HELP_GET		},
236 	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
237 	{ "upgrade",	zfs_do_upgrade,		HELP_UPGRADE		},
238 	{ NULL },
239 	{ "userspace",	zfs_do_userspace,	HELP_USERSPACE		},
240 	{ "groupspace",	zfs_do_userspace,	HELP_GROUPSPACE		},
241 	{ "projectspace", zfs_do_userspace,	HELP_PROJECTSPACE	},
242 	{ NULL },
243 	{ "project",	zfs_do_project,		HELP_PROJECT		},
244 	{ NULL },
245 	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
246 	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
247 	{ "share",	zfs_do_share,		HELP_SHARE		},
248 	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
249 	{ NULL },
250 	{ "send",	zfs_do_send,		HELP_SEND		},
251 	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
252 	{ NULL },
253 	{ "allow",	zfs_do_allow,		HELP_ALLOW		},
254 	{ NULL },
255 	{ "unallow",	zfs_do_unallow,		HELP_UNALLOW		},
256 	{ NULL },
257 	{ "hold",	zfs_do_hold,		HELP_HOLD		},
258 	{ "holds",	zfs_do_holds,		HELP_HOLDS		},
259 	{ "release",	zfs_do_release,		HELP_RELEASE		},
260 	{ "diff",	zfs_do_diff,		HELP_DIFF		},
261 	{ "load-key",	zfs_do_load_key,	HELP_LOAD_KEY		},
262 	{ "unload-key",	zfs_do_unload_key,	HELP_UNLOAD_KEY		},
263 	{ "change-key",	zfs_do_change_key,	HELP_CHANGE_KEY		},
264 	{ "redact",	zfs_do_redact,		HELP_REDACT		},
265 	{ "wait",	zfs_do_wait,		HELP_WAIT		},
266 
267 #ifdef __FreeBSD__
268 	{ "jail",	zfs_do_jail,		HELP_JAIL		},
269 	{ "unjail",	zfs_do_unjail,		HELP_UNJAIL		},
270 #endif
271 
272 #ifdef __linux__
273 	{ "zone",	zfs_do_zone,		HELP_ZONE		},
274 	{ "unzone",	zfs_do_unzone,		HELP_UNZONE		},
275 #endif
276 };
277 
278 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
279 
280 #define	MAX_CMD_LEN	256
281 
282 zfs_command_t *current_command;
283 
284 static const char *
get_usage(zfs_help_t idx)285 get_usage(zfs_help_t idx)
286 {
287 	switch (idx) {
288 	case HELP_CLONE:
289 		return (gettext("\tclone [-p] [-o property=value] ... "
290 		    "<snapshot> <filesystem|volume>\n"));
291 	case HELP_CREATE:
292 		return (gettext("\tcreate [-Pnpuv] [-o property=value] ... "
293 		    "<filesystem>\n"
294 		    "\tcreate [-Pnpsv] [-b blocksize] [-o property=value] ... "
295 		    "-V <size> <volume>\n"));
296 	case HELP_DESTROY:
297 		return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
298 		    "\tdestroy [-dnpRrv] "
299 		    "<filesystem|volume>@<snap>[%<snap>][,...]\n"
300 		    "\tdestroy <filesystem|volume>#<bookmark>\n"));
301 	case HELP_GET:
302 		return (gettext("\tget [-rHp] [-j [--json-int]] [-d max] "
303 		    "[-o \"all\" | field[,...]]\n"
304 		    "\t    [-t type[,...]] [-s source[,...]]\n"
305 		    "\t    <\"all\" | property[,...]> "
306 		    "[filesystem|volume|snapshot|bookmark] ...\n"));
307 	case HELP_INHERIT:
308 		return (gettext("\tinherit [-rS] <property> "
309 		    "<filesystem|volume|snapshot> ...\n"));
310 	case HELP_UPGRADE:
311 		return (gettext("\tupgrade [-v]\n"
312 		    "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
313 	case HELP_LIST:
314 		return (gettext("\tlist [-Hp] [-j [--json-int]] [-r|-d max] "
315 		    "[-o property[,...]] [-s property]...\n\t    "
316 		    "[-S property]... [-t type[,...]] "
317 		    "[filesystem|volume|snapshot] ...\n"));
318 	case HELP_MOUNT:
319 		return (gettext("\tmount [-j]\n"
320 		    "\tmount [-flvO] [-o opts] <-a|-R filesystem|"
321 		    "filesystem>\n"));
322 	case HELP_PROMOTE:
323 		return (gettext("\tpromote <clone-filesystem>\n"));
324 	case HELP_RECEIVE:
325 		return (gettext("\treceive [-vMnsFhu] "
326 		    "[-o <property>=<value>] ... [-x <property>] ...\n"
327 		    "\t    <filesystem|volume|snapshot>\n"
328 		    "\treceive [-vMnsFhu] [-o <property>=<value>] ... "
329 		    "[-x <property>] ... \n"
330 		    "\t    [-d | -e] <filesystem>\n"
331 		    "\treceive -A <filesystem|volume>\n"));
332 	case HELP_RENAME:
333 		return (gettext("\trename [-f] <filesystem|volume|snapshot> "
334 		    "<filesystem|volume|snapshot>\n"
335 		    "\trename -p [-f] <filesystem|volume> <filesystem|volume>\n"
336 		    "\trename -u [-f] <filesystem> <filesystem>\n"
337 		    "\trename -r <snapshot> <snapshot>\n"));
338 	case HELP_ROLLBACK:
339 		return (gettext("\trollback [-rRf] <snapshot>\n"));
340 	case HELP_SEND:
341 		return (gettext("\tsend [-DLPbcehnpsVvw] "
342 		    "[-i|-I snapshot]\n"
343 		    "\t     [-R [-X dataset[,dataset]...]]     <snapshot>\n"
344 		    "\tsend [-DnVvPLecw] [-i snapshot|bookmark] "
345 		    "<filesystem|volume|snapshot>\n"
346 		    "\tsend [-DnPpVvLec] [-i bookmark|snapshot] "
347 		    "--redact <bookmark> <snapshot>\n"
348 		    "\tsend [-nVvPe] -t <receive_resume_token>\n"
349 		    "\tsend [-PnVv] --saved filesystem\n"));
350 	case HELP_SET:
351 		return (gettext("\tset [-u] <property=value> ... "
352 		    "<filesystem|volume|snapshot> ...\n"));
353 	case HELP_SHARE:
354 		return (gettext("\tshare [-l] <-a [nfs|smb] | filesystem>\n"));
355 	case HELP_SNAPSHOT:
356 		return (gettext("\tsnapshot [-r] [-o property=value] ... "
357 		    "<filesystem|volume>@<snap> ...\n"));
358 	case HELP_UNMOUNT:
359 		return (gettext("\tunmount [-fu] "
360 		    "<-a | filesystem|mountpoint>\n"));
361 	case HELP_UNSHARE:
362 		return (gettext("\tunshare "
363 		    "<-a [nfs|smb] | filesystem|mountpoint>\n"));
364 	case HELP_ALLOW:
365 		return (gettext("\tallow <filesystem|volume>\n"
366 		    "\tallow [-ldug] "
367 		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
368 		    "\t    <filesystem|volume>\n"
369 		    "\tallow [-ld] -e <perm|@setname>[,...] "
370 		    "<filesystem|volume>\n"
371 		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
372 		    "\tallow -s @setname <perm|@setname>[,...] "
373 		    "<filesystem|volume>\n"));
374 	case HELP_UNALLOW:
375 		return (gettext("\tunallow [-rldug] "
376 		    "<\"everyone\"|user|group>[,...]\n"
377 		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
378 		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
379 		    "<filesystem|volume>\n"
380 		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
381 		    "<filesystem|volume>\n"
382 		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
383 		    "<filesystem|volume>\n"));
384 	case HELP_USERSPACE:
385 		return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
386 		    "[-s field] ...\n"
387 		    "\t    [-S field] ... [-t type[,...]] "
388 		    "<filesystem|snapshot|path>\n"));
389 	case HELP_GROUPSPACE:
390 		return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
391 		    "[-s field] ...\n"
392 		    "\t    [-S field] ... [-t type[,...]] "
393 		    "<filesystem|snapshot|path>\n"));
394 	case HELP_PROJECTSPACE:
395 		return (gettext("\tprojectspace [-Hp] [-o field[,...]] "
396 		    "[-s field] ... \n"
397 		    "\t    [-S field] ... <filesystem|snapshot|path>\n"));
398 	case HELP_PROJECT:
399 		return (gettext("\tproject [-d|-r] <directory|file ...>\n"
400 		    "\tproject -c [-0] [-d|-r] [-p id] <directory|file ...>\n"
401 		    "\tproject -C [-k] [-r] <directory ...>\n"
402 		    "\tproject [-p id] [-r] [-s] <directory ...>\n"));
403 	case HELP_HOLD:
404 		return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
405 	case HELP_HOLDS:
406 		return (gettext("\tholds [-rHp] <snapshot> ...\n"));
407 	case HELP_RELEASE:
408 		return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
409 	case HELP_DIFF:
410 		return (gettext("\tdiff [-FHth] <snapshot> "
411 		    "[snapshot|filesystem]\n"));
412 	case HELP_BOOKMARK:
413 		return (gettext("\tbookmark <snapshot|bookmark> "
414 		    "<newbookmark>\n"));
415 	case HELP_CHANNEL_PROGRAM:
416 		return (gettext("\tprogram [-jn] [-t <instruction limit>] "
417 		    "[-m <memory limit (b)>]\n"
418 		    "\t    <pool> <program file> [lua args...]\n"));
419 	case HELP_LOAD_KEY:
420 		return (gettext("\tload-key [-rn] [-L <keylocation>] "
421 		    "<-a | filesystem|volume>\n"));
422 	case HELP_UNLOAD_KEY:
423 		return (gettext("\tunload-key [-r] "
424 		    "<-a | filesystem|volume>\n"));
425 	case HELP_CHANGE_KEY:
426 		return (gettext("\tchange-key [-l] [-o keyformat=<value>]\n"
427 		    "\t    [-o keylocation=<value>] [-o pbkdf2iters=<value>]\n"
428 		    "\t    <filesystem|volume>\n"
429 		    "\tchange-key -i [-l] <filesystem|volume>\n"));
430 	case HELP_VERSION:
431 		return (gettext("\tversion [-j]\n"));
432 	case HELP_REDACT:
433 		return (gettext("\tredact <snapshot> <bookmark> "
434 		    "<redaction_snapshot> ...\n"));
435 	case HELP_JAIL:
436 		return (gettext("\tjail <jailid|jailname> <filesystem>\n"));
437 	case HELP_UNJAIL:
438 		return (gettext("\tunjail <jailid|jailname> <filesystem>\n"));
439 	case HELP_WAIT:
440 		return (gettext("\twait [-t <activity>] <filesystem>\n"));
441 	case HELP_ZONE:
442 		return (gettext("\tzone <nsfile> <filesystem>\n"));
443 	case HELP_UNZONE:
444 		return (gettext("\tunzone <nsfile> <filesystem>\n"));
445 	default:
446 		__builtin_unreachable();
447 	}
448 }
449 
450 void
nomem(void)451 nomem(void)
452 {
453 	(void) fprintf(stderr, gettext("internal error: out of memory\n"));
454 	exit(1);
455 }
456 
457 /*
458  * Utility function to guarantee malloc() success.
459  */
460 
461 void *
safe_malloc(size_t size)462 safe_malloc(size_t size)
463 {
464 	void *data;
465 
466 	if ((data = calloc(1, size)) == NULL)
467 		nomem();
468 
469 	return (data);
470 }
471 
472 static void *
safe_realloc(void * data,size_t size)473 safe_realloc(void *data, size_t size)
474 {
475 	void *newp;
476 	if ((newp = realloc(data, size)) == NULL) {
477 		free(data);
478 		nomem();
479 	}
480 
481 	return (newp);
482 }
483 
484 static char *
safe_strdup(const char * str)485 safe_strdup(const char *str)
486 {
487 	char *dupstr = strdup(str);
488 
489 	if (dupstr == NULL)
490 		nomem();
491 
492 	return (dupstr);
493 }
494 
495 /*
496  * Callback routine that will print out information for each of
497  * the properties.
498  */
499 static int
usage_prop_cb(int prop,void * cb)500 usage_prop_cb(int prop, void *cb)
501 {
502 	FILE *fp = cb;
503 
504 	(void) fprintf(fp, "\t%-22s ", zfs_prop_to_name(prop));
505 
506 	if (zfs_prop_readonly(prop))
507 		(void) fprintf(fp, " NO    ");
508 	else
509 		(void) fprintf(fp, "YES    ");
510 
511 	if (zfs_prop_inheritable(prop))
512 		(void) fprintf(fp, "  YES   ");
513 	else
514 		(void) fprintf(fp, "   NO   ");
515 
516 	(void) fprintf(fp, "%s\n", zfs_prop_values(prop) ?: "-");
517 
518 	return (ZPROP_CONT);
519 }
520 
521 /*
522  * Display usage message.  If we're inside a command, display only the usage for
523  * that command.  Otherwise, iterate over the entire command table and display
524  * a complete usage message.
525  */
526 static __attribute__((noreturn)) void
usage(boolean_t requested)527 usage(boolean_t requested)
528 {
529 	int i;
530 	boolean_t show_properties = B_FALSE;
531 	FILE *fp = requested ? stdout : stderr;
532 
533 	if (current_command == NULL) {
534 
535 		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
536 		(void) fprintf(fp,
537 		    gettext("where 'command' is one of the following:\n\n"));
538 
539 		for (i = 0; i < NCOMMAND; i++) {
540 			if (command_table[i].name == NULL)
541 				(void) fprintf(fp, "\n");
542 			else
543 				(void) fprintf(fp, "%s",
544 				    get_usage(command_table[i].usage));
545 		}
546 
547 		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
548 		    "pool/[dataset/]*dataset[@name]\n"));
549 	} else {
550 		(void) fprintf(fp, gettext("usage:\n"));
551 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
552 	}
553 
554 	if (current_command != NULL &&
555 	    (strcmp(current_command->name, "set") == 0 ||
556 	    strcmp(current_command->name, "get") == 0 ||
557 	    strcmp(current_command->name, "inherit") == 0 ||
558 	    strcmp(current_command->name, "list") == 0))
559 		show_properties = B_TRUE;
560 
561 	if (show_properties) {
562 		(void) fprintf(fp, "%s",
563 		    gettext("\nThe following properties are supported:\n"));
564 
565 		(void) fprintf(fp, "\n\t%-21s %s  %s   %s\n\n",
566 		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
567 
568 		/* Iterate over all properties */
569 		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
570 		    ZFS_TYPE_DATASET);
571 
572 		(void) fprintf(fp, "\t%-22s ", "userused@...");
573 		(void) fprintf(fp, " NO       NO   <size>\n");
574 		(void) fprintf(fp, "\t%-22s ", "groupused@...");
575 		(void) fprintf(fp, " NO       NO   <size>\n");
576 		(void) fprintf(fp, "\t%-22s ", "projectused@...");
577 		(void) fprintf(fp, " NO       NO   <size>\n");
578 		(void) fprintf(fp, "\t%-22s ", "userobjused@...");
579 		(void) fprintf(fp, " NO       NO   <size>\n");
580 		(void) fprintf(fp, "\t%-22s ", "groupobjused@...");
581 		(void) fprintf(fp, " NO       NO   <size>\n");
582 		(void) fprintf(fp, "\t%-22s ", "projectobjused@...");
583 		(void) fprintf(fp, " NO       NO   <size>\n");
584 		(void) fprintf(fp, "\t%-22s ", "userquota@...");
585 		(void) fprintf(fp, "YES       NO   <size> | none\n");
586 		(void) fprintf(fp, "\t%-22s ", "groupquota@...");
587 		(void) fprintf(fp, "YES       NO   <size> | none\n");
588 		(void) fprintf(fp, "\t%-22s ", "projectquota@...");
589 		(void) fprintf(fp, "YES       NO   <size> | none\n");
590 		(void) fprintf(fp, "\t%-22s ", "userobjquota@...");
591 		(void) fprintf(fp, "YES       NO   <size> | none\n");
592 		(void) fprintf(fp, "\t%-22s ", "groupobjquota@...");
593 		(void) fprintf(fp, "YES       NO   <size> | none\n");
594 		(void) fprintf(fp, "\t%-22s ", "projectobjquota@...");
595 		(void) fprintf(fp, "YES       NO   <size> | none\n");
596 		(void) fprintf(fp, "\t%-22s ", "written@<snap>");
597 		(void) fprintf(fp, " NO       NO   <size>\n");
598 		(void) fprintf(fp, "\t%-22s ", "written#<bookmark>");
599 		(void) fprintf(fp, " NO       NO   <size>\n");
600 
601 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
602 		    "with standard units such as K, M, G, etc.\n"));
603 		(void) fprintf(fp, "%s", gettext("\nUser-defined properties "
604 		    "can be specified by using a name containing a colon "
605 		    "(:).\n"));
606 		(void) fprintf(fp, gettext("\nThe {user|group|project}"
607 		    "[obj]{used|quota}@ properties must be appended with\n"
608 		    "a user|group|project specifier of one of these forms:\n"
609 		    "    POSIX name      (eg: \"matt\")\n"
610 		    "    POSIX id        (eg: \"126829\")\n"
611 		    "    SMB name@domain (eg: \"matt@sun\")\n"
612 		    "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
613 	} else {
614 		(void) fprintf(fp,
615 		    gettext("\nFor the property list, run: %s\n"),
616 		    "zfs set|get");
617 		(void) fprintf(fp,
618 		    gettext("\nFor the delegated permission list, run: %s\n"),
619 		    "zfs allow|unallow");
620 		(void) fprintf(fp,
621 		    gettext("\nFor further help on a command or topic, "
622 		    "run: %s\n"), "zfs help [<topic>]");
623 	}
624 
625 	/*
626 	 * See comments at end of main().
627 	 */
628 	if (getenv("ZFS_ABORT") != NULL) {
629 		(void) printf("dumping core by request\n");
630 		abort();
631 	}
632 
633 	exit(requested ? 0 : 2);
634 }
635 
636 /*
637  * Take a property=value argument string and add it to the given nvlist.
638  * Modifies the argument inplace.
639  */
640 static boolean_t
parseprop(nvlist_t * props,char * propname)641 parseprop(nvlist_t *props, char *propname)
642 {
643 	char *propval;
644 
645 	if ((propval = strchr(propname, '=')) == NULL) {
646 		(void) fprintf(stderr, gettext("missing "
647 		    "'=' for property=value argument\n"));
648 		return (B_FALSE);
649 	}
650 	*propval = '\0';
651 	propval++;
652 	if (nvlist_exists(props, propname)) {
653 		(void) fprintf(stderr, gettext("property '%s' "
654 		    "specified multiple times\n"), propname);
655 		return (B_FALSE);
656 	}
657 	if (nvlist_add_string(props, propname, propval) != 0)
658 		nomem();
659 	return (B_TRUE);
660 }
661 
662 /*
663  * Take a property name argument and add it to the given nvlist.
664  * Modifies the argument inplace.
665  */
666 static boolean_t
parsepropname(nvlist_t * props,char * propname)667 parsepropname(nvlist_t *props, char *propname)
668 {
669 	if (strchr(propname, '=') != NULL) {
670 		(void) fprintf(stderr, gettext("invalid character "
671 		    "'=' in property argument\n"));
672 		return (B_FALSE);
673 	}
674 	if (nvlist_exists(props, propname)) {
675 		(void) fprintf(stderr, gettext("property '%s' "
676 		    "specified multiple times\n"), propname);
677 		return (B_FALSE);
678 	}
679 	if (nvlist_add_boolean(props, propname) != 0)
680 		nomem();
681 	return (B_TRUE);
682 }
683 
684 static int
parse_depth(char * opt,int * flags)685 parse_depth(char *opt, int *flags)
686 {
687 	char *tmp;
688 	int depth;
689 
690 	depth = (int)strtol(opt, &tmp, 0);
691 	if (*tmp) {
692 		(void) fprintf(stderr,
693 		    gettext("%s is not an integer\n"), optarg);
694 		usage(B_FALSE);
695 	}
696 	if (depth < 0) {
697 		(void) fprintf(stderr,
698 		    gettext("Depth can not be negative.\n"));
699 		usage(B_FALSE);
700 	}
701 	*flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
702 	return (depth);
703 }
704 
705 #define	PROGRESS_DELAY 2		/* seconds */
706 
707 static const char *pt_reverse =
708 	"\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";
709 static time_t pt_begin;
710 static char *pt_header = NULL;
711 static boolean_t pt_shown;
712 
713 static void
start_progress_timer(void)714 start_progress_timer(void)
715 {
716 	pt_begin = time(NULL) + PROGRESS_DELAY;
717 	pt_shown = B_FALSE;
718 }
719 
720 static void
set_progress_header(const char * header)721 set_progress_header(const char *header)
722 {
723 	assert(pt_header == NULL);
724 	pt_header = safe_strdup(header);
725 	if (pt_shown) {
726 		(void) printf("%s: ", header);
727 		(void) fflush(stdout);
728 	}
729 }
730 
731 static void
update_progress(const char * update)732 update_progress(const char *update)
733 {
734 	if (!pt_shown && time(NULL) > pt_begin) {
735 		int len = strlen(update);
736 
737 		(void) printf("%s: %s%*.*s", pt_header, update, len, len,
738 		    pt_reverse);
739 		(void) fflush(stdout);
740 		pt_shown = B_TRUE;
741 	} else if (pt_shown) {
742 		int len = strlen(update);
743 
744 		(void) printf("%s%*.*s", update, len, len, pt_reverse);
745 		(void) fflush(stdout);
746 	}
747 }
748 
749 static void
finish_progress(const char * done)750 finish_progress(const char *done)
751 {
752 	if (pt_shown) {
753 		(void) puts(done);
754 		(void) fflush(stdout);
755 	}
756 	free(pt_header);
757 	pt_header = NULL;
758 }
759 
760 static int
zfs_mount_and_share(libzfs_handle_t * hdl,const char * dataset,zfs_type_t type)761 zfs_mount_and_share(libzfs_handle_t *hdl, const char *dataset, zfs_type_t type)
762 {
763 	zfs_handle_t *zhp = NULL;
764 	int ret = 0;
765 
766 	zhp = zfs_open(hdl, dataset, type);
767 	if (zhp == NULL)
768 		return (1);
769 
770 	/*
771 	 * Volumes may neither be mounted or shared.  Potentially in the
772 	 * future filesystems detected on these volumes could be mounted.
773 	 */
774 	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
775 		zfs_close(zhp);
776 		return (0);
777 	}
778 
779 	/*
780 	 * Mount and/or share the new filesystem as appropriate.  We provide a
781 	 * verbose error message to let the user know that their filesystem was
782 	 * in fact created, even if we failed to mount or share it.
783 	 *
784 	 * If the user doesn't want the dataset automatically mounted, then
785 	 * skip the mount/share step
786 	 */
787 	if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type, B_FALSE) &&
788 	    zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON) {
789 		if (zfs_mount_delegation_check()) {
790 			(void) fprintf(stderr, gettext("filesystem "
791 			    "successfully created, but it may only be "
792 			    "mounted by root\n"));
793 			ret = 1;
794 		} else if (zfs_mount(zhp, NULL, 0) != 0) {
795 			(void) fprintf(stderr, gettext("filesystem "
796 			    "successfully created, but not mounted\n"));
797 			ret = 1;
798 		} else if (zfs_share(zhp, NULL) != 0) {
799 			(void) fprintf(stderr, gettext("filesystem "
800 			    "successfully created, but not shared\n"));
801 			ret = 1;
802 		}
803 		zfs_commit_shares(NULL);
804 	}
805 
806 	zfs_close(zhp);
807 
808 	return (ret);
809 }
810 
811 /*
812  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
813  *
814  * Given an existing dataset, create a writable copy whose initial contents
815  * are the same as the source.  The newly created dataset maintains a
816  * dependency on the original; the original cannot be destroyed so long as
817  * the clone exists.
818  *
819  * The '-p' flag creates all the non-existing ancestors of the target first.
820  */
821 static int
zfs_do_clone(int argc,char ** argv)822 zfs_do_clone(int argc, char **argv)
823 {
824 	zfs_handle_t *zhp = NULL;
825 	boolean_t parents = B_FALSE;
826 	nvlist_t *props;
827 	int ret = 0;
828 	int c;
829 
830 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
831 		nomem();
832 
833 	/* check options */
834 	while ((c = getopt(argc, argv, "o:p")) != -1) {
835 		switch (c) {
836 		case 'o':
837 			if (!parseprop(props, optarg)) {
838 				nvlist_free(props);
839 				return (1);
840 			}
841 			break;
842 		case 'p':
843 			parents = B_TRUE;
844 			break;
845 		case '?':
846 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
847 			    optopt);
848 			goto usage;
849 		}
850 	}
851 
852 	argc -= optind;
853 	argv += optind;
854 
855 	/* check number of arguments */
856 	if (argc < 1) {
857 		(void) fprintf(stderr, gettext("missing source dataset "
858 		    "argument\n"));
859 		goto usage;
860 	}
861 	if (argc < 2) {
862 		(void) fprintf(stderr, gettext("missing target dataset "
863 		    "argument\n"));
864 		goto usage;
865 	}
866 	if (argc > 2) {
867 		(void) fprintf(stderr, gettext("too many arguments\n"));
868 		goto usage;
869 	}
870 
871 	/* open the source dataset */
872 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL) {
873 		nvlist_free(props);
874 		return (1);
875 	}
876 
877 	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
878 	    ZFS_TYPE_VOLUME)) {
879 		/*
880 		 * Now create the ancestors of the target dataset.  If the
881 		 * target already exists and '-p' option was used we should not
882 		 * complain.
883 		 */
884 		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
885 		    ZFS_TYPE_VOLUME)) {
886 			zfs_close(zhp);
887 			nvlist_free(props);
888 			return (0);
889 		}
890 		if (zfs_create_ancestors(g_zfs, argv[1]) != 0) {
891 			zfs_close(zhp);
892 			nvlist_free(props);
893 			return (1);
894 		}
895 	}
896 
897 	/* pass to libzfs */
898 	ret = zfs_clone(zhp, argv[1], props);
899 
900 	/* create the mountpoint if necessary */
901 	if (ret == 0) {
902 		if (log_history) {
903 			(void) zpool_log_history(g_zfs, history_str);
904 			log_history = B_FALSE;
905 		}
906 
907 		ret = zfs_mount_and_share(g_zfs, argv[1], ZFS_TYPE_DATASET);
908 	}
909 
910 	zfs_close(zhp);
911 	nvlist_free(props);
912 
913 	return (!!ret);
914 
915 usage:
916 	ASSERT3P(zhp, ==, NULL);
917 	nvlist_free(props);
918 	usage(B_FALSE);
919 	return (-1);
920 }
921 
922 /*
923  * Return a default volblocksize for the pool which always uses more than
924  * half of the data sectors.  This primarily applies to dRAID which always
925  * writes full stripe widths.
926  */
927 static uint64_t
default_volblocksize(zpool_handle_t * zhp,nvlist_t * props)928 default_volblocksize(zpool_handle_t *zhp, nvlist_t *props)
929 {
930 	uint64_t volblocksize, asize = SPA_MINBLOCKSIZE;
931 	nvlist_t *tree, **vdevs;
932 	uint_t nvdevs;
933 
934 	nvlist_t *config = zpool_get_config(zhp, NULL);
935 
936 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) != 0 ||
937 	    nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
938 	    &vdevs, &nvdevs) != 0) {
939 		return (ZVOL_DEFAULT_BLOCKSIZE);
940 	}
941 
942 	for (int i = 0; i < nvdevs; i++) {
943 		nvlist_t *nv = vdevs[i];
944 		uint64_t ashift, ndata, nparity;
945 
946 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &ashift) != 0)
947 			continue;
948 
949 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DRAID_NDATA,
950 		    &ndata) == 0) {
951 			/* dRAID minimum allocation width */
952 			asize = MAX(asize, ndata * (1ULL << ashift));
953 		} else if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
954 		    &nparity) == 0) {
955 			/* raidz minimum allocation width */
956 			if (nparity == 1)
957 				asize = MAX(asize, 2 * (1ULL << ashift));
958 			else
959 				asize = MAX(asize, 4 * (1ULL << ashift));
960 		} else {
961 			/* mirror or (non-redundant) leaf vdev */
962 			asize = MAX(asize, 1ULL << ashift);
963 		}
964 	}
965 
966 	/*
967 	 * Calculate the target volblocksize such that more than half
968 	 * of the asize is used. The following table is for 4k sectors.
969 	 *
970 	 * n   asize   blksz  used  |   n   asize   blksz  used
971 	 * -------------------------+---------------------------------
972 	 * 1   4,096   8,192  100%  |   9  36,864  32,768   88%
973 	 * 2   8,192   8,192  100%  |  10  40,960  32,768   80%
974 	 * 3  12,288   8,192   66%  |  11  45,056  32,768   72%
975 	 * 4  16,384  16,384  100%  |  12  49,152  32,768   66%
976 	 * 5  20,480  16,384   80%  |  13  53,248  32,768   61%
977 	 * 6  24,576  16,384   66%  |  14  57,344  32,768   57%
978 	 * 7  28,672  16,384   57%  |  15  61,440  32,768   53%
979 	 * 8  32,768  32,768  100%  |  16  65,536  65,636  100%
980 	 *
981 	 * This is primarily a concern for dRAID which always allocates
982 	 * a full stripe width.  For dRAID the default stripe width is
983 	 * n=8 in which case the volblocksize is set to 32k. Ignoring
984 	 * compression there are no unused sectors.  This same reasoning
985 	 * applies to raidz[2,3] so target 4 sectors to minimize waste.
986 	 */
987 	uint64_t tgt_volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
988 	while (tgt_volblocksize * 2 <= asize)
989 		tgt_volblocksize *= 2;
990 
991 	const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
992 	if (nvlist_lookup_uint64(props, prop, &volblocksize) == 0) {
993 
994 		/* Issue a warning when a non-optimal size is requested. */
995 		if (volblocksize < ZVOL_DEFAULT_BLOCKSIZE) {
996 			(void) fprintf(stderr, gettext("Warning: "
997 			    "volblocksize (%llu) is less than the default "
998 			    "minimum block size (%llu).\nTo reduce wasted "
999 			    "space a volblocksize of %llu is recommended.\n"),
1000 			    (u_longlong_t)volblocksize,
1001 			    (u_longlong_t)ZVOL_DEFAULT_BLOCKSIZE,
1002 			    (u_longlong_t)tgt_volblocksize);
1003 		} else if (volblocksize < tgt_volblocksize) {
1004 			(void) fprintf(stderr, gettext("Warning: "
1005 			    "volblocksize (%llu) is much less than the "
1006 			    "minimum allocation\nunit (%llu), which wastes "
1007 			    "at least %llu%% of space. To reduce wasted "
1008 			    "space,\nuse a larger volblocksize (%llu is "
1009 			    "recommended), fewer dRAID data disks\n"
1010 			    "per group, or smaller sector size (ashift).\n"),
1011 			    (u_longlong_t)volblocksize, (u_longlong_t)asize,
1012 			    (u_longlong_t)((100 * (asize - volblocksize)) /
1013 			    asize), (u_longlong_t)tgt_volblocksize);
1014 		}
1015 	} else {
1016 		volblocksize = tgt_volblocksize;
1017 		fnvlist_add_uint64(props, prop, volblocksize);
1018 	}
1019 
1020 	return (volblocksize);
1021 }
1022 
1023 /*
1024  * zfs create [-Pnpv] [-o prop=value] ... fs
1025  * zfs create [-Pnpsv] [-b blocksize] [-o prop=value] ... -V vol size
1026  *
1027  * Create a new dataset.  This command can be used to create filesystems
1028  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
1029  * For volumes, the user must specify a size to be used.
1030  *
1031  * The '-s' flag applies only to volumes, and indicates that we should not try
1032  * to set the reservation for this volume.  By default we set a reservation
1033  * equal to the size for any volume.  For pools with SPA_VERSION >=
1034  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
1035  *
1036  * The '-p' flag creates all the non-existing ancestors of the target first.
1037  *
1038  * The '-n' flag is no-op (dry run) mode.  This will perform a user-space sanity
1039  * check of arguments and properties, but does not check for permissions,
1040  * available space, etc.
1041  *
1042  * The '-u' flag prevents the newly created file system from being mounted.
1043  *
1044  * The '-v' flag is for verbose output.
1045  *
1046  * The '-P' flag is used for parseable output.  It implies '-v'.
1047  */
1048 static int
zfs_do_create(int argc,char ** argv)1049 zfs_do_create(int argc, char **argv)
1050 {
1051 	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
1052 	zpool_handle_t *zpool_handle = NULL;
1053 	nvlist_t *real_props = NULL;
1054 	uint64_t volsize = 0;
1055 	int c;
1056 	boolean_t noreserve = B_FALSE;
1057 	boolean_t bflag = B_FALSE;
1058 	boolean_t parents = B_FALSE;
1059 	boolean_t dryrun = B_FALSE;
1060 	boolean_t nomount = B_FALSE;
1061 	boolean_t verbose = B_FALSE;
1062 	boolean_t parseable = B_FALSE;
1063 	int ret = 1;
1064 	nvlist_t *props;
1065 	uint64_t intval;
1066 	const char *strval;
1067 
1068 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
1069 		nomem();
1070 
1071 	/* check options */
1072 	while ((c = getopt(argc, argv, ":PV:b:nso:puv")) != -1) {
1073 		switch (c) {
1074 		case 'V':
1075 			type = ZFS_TYPE_VOLUME;
1076 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1077 				(void) fprintf(stderr, gettext("bad volume "
1078 				    "size '%s': %s\n"), optarg,
1079 				    libzfs_error_description(g_zfs));
1080 				goto error;
1081 			}
1082 
1083 			if (nvlist_add_uint64(props,
1084 			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
1085 				nomem();
1086 			volsize = intval;
1087 			break;
1088 		case 'P':
1089 			verbose = B_TRUE;
1090 			parseable = B_TRUE;
1091 			break;
1092 		case 'p':
1093 			parents = B_TRUE;
1094 			break;
1095 		case 'b':
1096 			bflag = B_TRUE;
1097 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1098 				(void) fprintf(stderr, gettext("bad volume "
1099 				    "block size '%s': %s\n"), optarg,
1100 				    libzfs_error_description(g_zfs));
1101 				goto error;
1102 			}
1103 
1104 			if (nvlist_add_uint64(props,
1105 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1106 			    intval) != 0)
1107 				nomem();
1108 			break;
1109 		case 'n':
1110 			dryrun = B_TRUE;
1111 			break;
1112 		case 'o':
1113 			if (!parseprop(props, optarg))
1114 				goto error;
1115 			break;
1116 		case 's':
1117 			noreserve = B_TRUE;
1118 			break;
1119 		case 'u':
1120 			nomount = B_TRUE;
1121 			break;
1122 		case 'v':
1123 			verbose = B_TRUE;
1124 			break;
1125 		case ':':
1126 			(void) fprintf(stderr, gettext("missing size "
1127 			    "argument\n"));
1128 			goto badusage;
1129 		case '?':
1130 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1131 			    optopt);
1132 			goto badusage;
1133 		}
1134 	}
1135 
1136 	if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
1137 		(void) fprintf(stderr, gettext("'-s' and '-b' can only be "
1138 		    "used when creating a volume\n"));
1139 		goto badusage;
1140 	}
1141 	if (nomount && type != ZFS_TYPE_FILESYSTEM) {
1142 		(void) fprintf(stderr, gettext("'-u' can only be "
1143 		    "used when creating a filesystem\n"));
1144 		goto badusage;
1145 	}
1146 
1147 	argc -= optind;
1148 	argv += optind;
1149 
1150 	/* check number of arguments */
1151 	if (argc == 0) {
1152 		(void) fprintf(stderr, gettext("missing %s argument\n"),
1153 		    zfs_type_to_name(type));
1154 		goto badusage;
1155 	}
1156 	if (argc > 1) {
1157 		(void) fprintf(stderr, gettext("too many arguments\n"));
1158 		goto badusage;
1159 	}
1160 
1161 	if (dryrun || type == ZFS_TYPE_VOLUME) {
1162 		char msg[ZFS_MAX_DATASET_NAME_LEN * 2];
1163 		char *p;
1164 
1165 		if ((p = strchr(argv[0], '/')) != NULL)
1166 			*p = '\0';
1167 		zpool_handle = zpool_open(g_zfs, argv[0]);
1168 		if (p != NULL)
1169 			*p = '/';
1170 		if (zpool_handle == NULL)
1171 			goto error;
1172 
1173 		(void) snprintf(msg, sizeof (msg),
1174 		    dryrun ? gettext("cannot verify '%s'") :
1175 		    gettext("cannot create '%s'"), argv[0]);
1176 		if (props && (real_props = zfs_valid_proplist(g_zfs, type,
1177 		    props, 0, NULL, zpool_handle, B_TRUE, msg)) == NULL) {
1178 			zpool_close(zpool_handle);
1179 			goto error;
1180 		}
1181 	}
1182 
1183 	if (type == ZFS_TYPE_VOLUME) {
1184 		const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
1185 		uint64_t volblocksize = default_volblocksize(zpool_handle,
1186 		    real_props);
1187 
1188 		if (volblocksize != ZVOL_DEFAULT_BLOCKSIZE &&
1189 		    nvlist_lookup_string(props, prop, &strval) != 0) {
1190 			char *tmp;
1191 			if (asprintf(&tmp, "%llu",
1192 			    (u_longlong_t)volblocksize) == -1)
1193 				nomem();
1194 			nvlist_add_string(props, prop, tmp);
1195 			free(tmp);
1196 		}
1197 
1198 		/*
1199 		 * If volsize is not a multiple of volblocksize, round it
1200 		 * up to the nearest multiple of the volblocksize.
1201 		 */
1202 		if (volsize % volblocksize) {
1203 			volsize = P2ROUNDUP_TYPED(volsize, volblocksize,
1204 			    uint64_t);
1205 
1206 			if (nvlist_add_uint64(props,
1207 			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), volsize) != 0) {
1208 				nvlist_free(props);
1209 				nomem();
1210 			}
1211 		}
1212 	}
1213 
1214 	if (type == ZFS_TYPE_VOLUME && !noreserve) {
1215 		uint64_t spa_version;
1216 		zfs_prop_t resv_prop;
1217 
1218 		spa_version = zpool_get_prop_int(zpool_handle,
1219 		    ZPOOL_PROP_VERSION, NULL);
1220 		if (spa_version >= SPA_VERSION_REFRESERVATION)
1221 			resv_prop = ZFS_PROP_REFRESERVATION;
1222 		else
1223 			resv_prop = ZFS_PROP_RESERVATION;
1224 
1225 		volsize = zvol_volsize_to_reservation(zpool_handle, volsize,
1226 		    real_props);
1227 
1228 		if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
1229 		    &strval) != 0) {
1230 			if (nvlist_add_uint64(props,
1231 			    zfs_prop_to_name(resv_prop), volsize) != 0) {
1232 				nvlist_free(props);
1233 				nomem();
1234 			}
1235 		}
1236 	}
1237 	if (zpool_handle != NULL) {
1238 		zpool_close(zpool_handle);
1239 		nvlist_free(real_props);
1240 	}
1241 
1242 	if (parents && zfs_name_valid(argv[0], type)) {
1243 		/*
1244 		 * Now create the ancestors of target dataset.  If the target
1245 		 * already exists and '-p' option was used we should not
1246 		 * complain.
1247 		 */
1248 		if (zfs_dataset_exists(g_zfs, argv[0], type)) {
1249 			ret = 0;
1250 			goto error;
1251 		}
1252 		if (verbose) {
1253 			(void) printf(parseable ? "create_ancestors\t%s\n" :
1254 			    dryrun ?  "would create ancestors of %s\n" :
1255 			    "create ancestors of %s\n", argv[0]);
1256 		}
1257 		if (!dryrun) {
1258 			if (zfs_create_ancestors(g_zfs, argv[0]) != 0) {
1259 				goto error;
1260 			}
1261 		}
1262 	}
1263 
1264 	if (verbose) {
1265 		nvpair_t *nvp = NULL;
1266 		(void) printf(parseable ? "create\t%s\n" :
1267 		    dryrun ? "would create %s\n" : "create %s\n", argv[0]);
1268 		while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
1269 			uint64_t uval;
1270 			const char *sval;
1271 
1272 			switch (nvpair_type(nvp)) {
1273 			case DATA_TYPE_UINT64:
1274 				VERIFY0(nvpair_value_uint64(nvp, &uval));
1275 				(void) printf(parseable ?
1276 				    "property\t%s\t%llu\n" : "\t%s=%llu\n",
1277 				    nvpair_name(nvp), (u_longlong_t)uval);
1278 				break;
1279 			case DATA_TYPE_STRING:
1280 				VERIFY0(nvpair_value_string(nvp, &sval));
1281 				(void) printf(parseable ?
1282 				    "property\t%s\t%s\n" : "\t%s=%s\n",
1283 				    nvpair_name(nvp), sval);
1284 				break;
1285 			default:
1286 				(void) fprintf(stderr, "property '%s' "
1287 				    "has illegal type %d\n",
1288 				    nvpair_name(nvp), nvpair_type(nvp));
1289 				abort();
1290 			}
1291 		}
1292 	}
1293 	if (dryrun) {
1294 		ret = 0;
1295 		goto error;
1296 	}
1297 
1298 	/* pass to libzfs */
1299 	if (zfs_create(g_zfs, argv[0], type, props) != 0)
1300 		goto error;
1301 
1302 	if (log_history) {
1303 		(void) zpool_log_history(g_zfs, history_str);
1304 		log_history = B_FALSE;
1305 	}
1306 
1307 	if (nomount) {
1308 		ret = 0;
1309 		goto error;
1310 	}
1311 
1312 	ret = zfs_mount_and_share(g_zfs, argv[0], ZFS_TYPE_DATASET);
1313 error:
1314 	nvlist_free(props);
1315 	return (ret);
1316 badusage:
1317 	nvlist_free(props);
1318 	usage(B_FALSE);
1319 	return (2);
1320 }
1321 
1322 /*
1323  * zfs destroy [-rRf] <fs, vol>
1324  * zfs destroy [-rRd] <snap>
1325  *
1326  *	-r	Recursively destroy all children
1327  *	-R	Recursively destroy all dependents, including clones
1328  *	-f	Force unmounting of any dependents
1329  *	-d	If we can't destroy now, mark for deferred destruction
1330  *
1331  * Destroys the given dataset.  By default, it will unmount any filesystems,
1332  * and refuse to destroy a dataset that has any dependents.  A dependent can
1333  * either be a child, or a clone of a child.
1334  */
1335 typedef struct destroy_cbdata {
1336 	boolean_t	cb_first;
1337 	boolean_t	cb_force;
1338 	boolean_t	cb_recurse;
1339 	boolean_t	cb_error;
1340 	boolean_t	cb_doclones;
1341 	zfs_handle_t	*cb_target;
1342 	boolean_t	cb_defer_destroy;
1343 	boolean_t	cb_verbose;
1344 	boolean_t	cb_parsable;
1345 	boolean_t	cb_dryrun;
1346 	nvlist_t	*cb_nvl;
1347 	nvlist_t	*cb_batchedsnaps;
1348 
1349 	/* first snap in contiguous run */
1350 	char		*cb_firstsnap;
1351 	/* previous snap in contiguous run */
1352 	char		*cb_prevsnap;
1353 	int64_t		cb_snapused;
1354 	char		*cb_snapspec;
1355 	char		*cb_bookmark;
1356 	uint64_t	cb_snap_count;
1357 } destroy_cbdata_t;
1358 
1359 /*
1360  * Check for any dependents based on the '-r' or '-R' flags.
1361  */
1362 static int
destroy_check_dependent(zfs_handle_t * zhp,void * data)1363 destroy_check_dependent(zfs_handle_t *zhp, void *data)
1364 {
1365 	destroy_cbdata_t *cbp = data;
1366 	const char *tname = zfs_get_name(cbp->cb_target);
1367 	const char *name = zfs_get_name(zhp);
1368 
1369 	if (strncmp(tname, name, strlen(tname)) == 0 &&
1370 	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
1371 		/*
1372 		 * This is a direct descendant, not a clone somewhere else in
1373 		 * the hierarchy.
1374 		 */
1375 		if (cbp->cb_recurse)
1376 			goto out;
1377 
1378 		if (cbp->cb_first) {
1379 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1380 			    "%s has children\n"),
1381 			    zfs_get_name(cbp->cb_target),
1382 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1383 			(void) fprintf(stderr, gettext("use '-r' to destroy "
1384 			    "the following datasets:\n"));
1385 			cbp->cb_first = B_FALSE;
1386 			cbp->cb_error = B_TRUE;
1387 		}
1388 
1389 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1390 	} else {
1391 		/*
1392 		 * This is a clone.  We only want to report this if the '-r'
1393 		 * wasn't specified, or the target is a snapshot.
1394 		 */
1395 		if (!cbp->cb_recurse &&
1396 		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1397 			goto out;
1398 
1399 		if (cbp->cb_first) {
1400 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1401 			    "%s has dependent clones\n"),
1402 			    zfs_get_name(cbp->cb_target),
1403 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1404 			(void) fprintf(stderr, gettext("use '-R' to destroy "
1405 			    "the following datasets:\n"));
1406 			cbp->cb_first = B_FALSE;
1407 			cbp->cb_error = B_TRUE;
1408 			cbp->cb_dryrun = B_TRUE;
1409 		}
1410 
1411 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1412 	}
1413 
1414 out:
1415 	zfs_close(zhp);
1416 	return (0);
1417 }
1418 
1419 static int
destroy_batched(destroy_cbdata_t * cb)1420 destroy_batched(destroy_cbdata_t *cb)
1421 {
1422 	int error = zfs_destroy_snaps_nvl(g_zfs,
1423 	    cb->cb_batchedsnaps, B_FALSE);
1424 	fnvlist_free(cb->cb_batchedsnaps);
1425 	cb->cb_batchedsnaps = fnvlist_alloc();
1426 	return (error);
1427 }
1428 
1429 static int
destroy_callback(zfs_handle_t * zhp,void * data)1430 destroy_callback(zfs_handle_t *zhp, void *data)
1431 {
1432 	destroy_cbdata_t *cb = data;
1433 	const char *name = zfs_get_name(zhp);
1434 	int error;
1435 
1436 	if (cb->cb_verbose) {
1437 		if (cb->cb_parsable) {
1438 			(void) printf("destroy\t%s\n", name);
1439 		} else if (cb->cb_dryrun) {
1440 			(void) printf(gettext("would destroy %s\n"),
1441 			    name);
1442 		} else {
1443 			(void) printf(gettext("will destroy %s\n"),
1444 			    name);
1445 		}
1446 	}
1447 
1448 	/*
1449 	 * Ignore pools (which we've already flagged as an error before getting
1450 	 * here).
1451 	 */
1452 	if (strchr(zfs_get_name(zhp), '/') == NULL &&
1453 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1454 		zfs_close(zhp);
1455 		return (0);
1456 	}
1457 	if (cb->cb_dryrun) {
1458 		zfs_close(zhp);
1459 		return (0);
1460 	}
1461 
1462 	/*
1463 	 * We batch up all contiguous snapshots (even of different
1464 	 * filesystems) and destroy them with one ioctl.  We can't
1465 	 * simply do all snap deletions and then all fs deletions,
1466 	 * because we must delete a clone before its origin.
1467 	 */
1468 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1469 		cb->cb_snap_count++;
1470 		fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1471 		if (cb->cb_snap_count % 10 == 0 && cb->cb_defer_destroy) {
1472 			error = destroy_batched(cb);
1473 			if (error != 0) {
1474 				zfs_close(zhp);
1475 				return (-1);
1476 			}
1477 		}
1478 	} else {
1479 		error = destroy_batched(cb);
1480 		if (error != 0 ||
1481 		    zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1482 		    zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1483 			zfs_close(zhp);
1484 			/*
1485 			 * When performing a recursive destroy we ignore errors
1486 			 * so that the recursive destroy could continue
1487 			 * destroying past problem datasets
1488 			 */
1489 			if (cb->cb_recurse) {
1490 				cb->cb_error = B_TRUE;
1491 				return (0);
1492 			}
1493 			return (-1);
1494 		}
1495 	}
1496 
1497 	zfs_close(zhp);
1498 	return (0);
1499 }
1500 
1501 static int
destroy_print_cb(zfs_handle_t * zhp,void * arg)1502 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1503 {
1504 	destroy_cbdata_t *cb = arg;
1505 	const char *name = zfs_get_name(zhp);
1506 	int err = 0;
1507 
1508 	if (nvlist_exists(cb->cb_nvl, name)) {
1509 		if (cb->cb_firstsnap == NULL)
1510 			cb->cb_firstsnap = strdup(name);
1511 		if (cb->cb_prevsnap != NULL)
1512 			free(cb->cb_prevsnap);
1513 		/* this snap continues the current range */
1514 		cb->cb_prevsnap = strdup(name);
1515 		if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1516 			nomem();
1517 		if (cb->cb_verbose) {
1518 			if (cb->cb_parsable) {
1519 				(void) printf("destroy\t%s\n", name);
1520 			} else if (cb->cb_dryrun) {
1521 				(void) printf(gettext("would destroy %s\n"),
1522 				    name);
1523 			} else {
1524 				(void) printf(gettext("will destroy %s\n"),
1525 				    name);
1526 			}
1527 		}
1528 	} else if (cb->cb_firstsnap != NULL) {
1529 		/* end of this range */
1530 		uint64_t used = 0;
1531 		err = lzc_snaprange_space(cb->cb_firstsnap,
1532 		    cb->cb_prevsnap, &used);
1533 		cb->cb_snapused += used;
1534 		free(cb->cb_firstsnap);
1535 		cb->cb_firstsnap = NULL;
1536 		free(cb->cb_prevsnap);
1537 		cb->cb_prevsnap = NULL;
1538 	}
1539 	zfs_close(zhp);
1540 	return (err);
1541 }
1542 
1543 static int
destroy_print_snapshots(zfs_handle_t * fs_zhp,destroy_cbdata_t * cb)1544 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1545 {
1546 	int err;
1547 	assert(cb->cb_firstsnap == NULL);
1548 	assert(cb->cb_prevsnap == NULL);
1549 	err = zfs_iter_snapshots_sorted_v2(fs_zhp, 0, destroy_print_cb, cb, 0,
1550 	    0);
1551 	if (cb->cb_firstsnap != NULL) {
1552 		uint64_t used = 0;
1553 		if (err == 0) {
1554 			err = lzc_snaprange_space(cb->cb_firstsnap,
1555 			    cb->cb_prevsnap, &used);
1556 		}
1557 		cb->cb_snapused += used;
1558 		free(cb->cb_firstsnap);
1559 		cb->cb_firstsnap = NULL;
1560 		free(cb->cb_prevsnap);
1561 		cb->cb_prevsnap = NULL;
1562 	}
1563 	return (err);
1564 }
1565 
1566 static int
snapshot_to_nvl_cb(zfs_handle_t * zhp,void * arg)1567 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1568 {
1569 	destroy_cbdata_t *cb = arg;
1570 	int err = 0;
1571 
1572 	/* Check for clones. */
1573 	if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1574 		cb->cb_target = zhp;
1575 		cb->cb_first = B_TRUE;
1576 		err = zfs_iter_dependents_v2(zhp, 0, B_TRUE,
1577 		    destroy_check_dependent, cb);
1578 	}
1579 
1580 	if (err == 0) {
1581 		if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1582 			nomem();
1583 	}
1584 	zfs_close(zhp);
1585 	return (err);
1586 }
1587 
1588 static int
gather_snapshots(zfs_handle_t * zhp,void * arg)1589 gather_snapshots(zfs_handle_t *zhp, void *arg)
1590 {
1591 	destroy_cbdata_t *cb = arg;
1592 	int err = 0;
1593 
1594 	err = zfs_iter_snapspec_v2(zhp, 0, cb->cb_snapspec,
1595 	    snapshot_to_nvl_cb, cb);
1596 	if (err == ENOENT)
1597 		err = 0;
1598 	if (err != 0)
1599 		goto out;
1600 
1601 	if (cb->cb_verbose) {
1602 		err = destroy_print_snapshots(zhp, cb);
1603 		if (err != 0)
1604 			goto out;
1605 	}
1606 
1607 	if (cb->cb_recurse)
1608 		err = zfs_iter_filesystems_v2(zhp, 0, gather_snapshots, cb);
1609 
1610 out:
1611 	zfs_close(zhp);
1612 	return (err);
1613 }
1614 
1615 static int
destroy_clones(destroy_cbdata_t * cb)1616 destroy_clones(destroy_cbdata_t *cb)
1617 {
1618 	nvpair_t *pair;
1619 	for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1620 	    pair != NULL;
1621 	    pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1622 		zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1623 		    ZFS_TYPE_SNAPSHOT);
1624 		if (zhp != NULL) {
1625 			boolean_t defer = cb->cb_defer_destroy;
1626 			int err;
1627 
1628 			/*
1629 			 * We can't defer destroy non-snapshots, so set it to
1630 			 * false while destroying the clones.
1631 			 */
1632 			cb->cb_defer_destroy = B_FALSE;
1633 			err = zfs_iter_dependents_v2(zhp, 0, B_FALSE,
1634 			    destroy_callback, cb);
1635 			cb->cb_defer_destroy = defer;
1636 			zfs_close(zhp);
1637 			if (err != 0)
1638 				return (err);
1639 		}
1640 	}
1641 	return (0);
1642 }
1643 
1644 static int
zfs_do_destroy(int argc,char ** argv)1645 zfs_do_destroy(int argc, char **argv)
1646 {
1647 	destroy_cbdata_t cb = { 0 };
1648 	int rv = 0;
1649 	int err = 0;
1650 	int c;
1651 	zfs_handle_t *zhp = NULL;
1652 	char *at, *pound;
1653 	zfs_type_t type = ZFS_TYPE_DATASET;
1654 
1655 	/* check options */
1656 	while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1657 		switch (c) {
1658 		case 'v':
1659 			cb.cb_verbose = B_TRUE;
1660 			break;
1661 		case 'p':
1662 			cb.cb_verbose = B_TRUE;
1663 			cb.cb_parsable = B_TRUE;
1664 			break;
1665 		case 'n':
1666 			cb.cb_dryrun = B_TRUE;
1667 			break;
1668 		case 'd':
1669 			cb.cb_defer_destroy = B_TRUE;
1670 			type = ZFS_TYPE_SNAPSHOT;
1671 			break;
1672 		case 'f':
1673 			cb.cb_force = B_TRUE;
1674 			break;
1675 		case 'r':
1676 			cb.cb_recurse = B_TRUE;
1677 			break;
1678 		case 'R':
1679 			cb.cb_recurse = B_TRUE;
1680 			cb.cb_doclones = B_TRUE;
1681 			break;
1682 		case '?':
1683 		default:
1684 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1685 			    optopt);
1686 			usage(B_FALSE);
1687 		}
1688 	}
1689 
1690 	argc -= optind;
1691 	argv += optind;
1692 
1693 	/* check number of arguments */
1694 	if (argc == 0) {
1695 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1696 		usage(B_FALSE);
1697 	}
1698 	if (argc > 1) {
1699 		(void) fprintf(stderr, gettext("too many arguments\n"));
1700 		usage(B_FALSE);
1701 	}
1702 
1703 	at = strchr(argv[0], '@');
1704 	pound = strchr(argv[0], '#');
1705 	if (at != NULL) {
1706 
1707 		/* Build the list of snaps to destroy in cb_nvl. */
1708 		cb.cb_nvl = fnvlist_alloc();
1709 
1710 		*at = '\0';
1711 		zhp = zfs_open(g_zfs, argv[0],
1712 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1713 		if (zhp == NULL) {
1714 			nvlist_free(cb.cb_nvl);
1715 			return (1);
1716 		}
1717 
1718 		cb.cb_snapspec = at + 1;
1719 		if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1720 		    cb.cb_error) {
1721 			rv = 1;
1722 			goto out;
1723 		}
1724 
1725 		if (nvlist_empty(cb.cb_nvl)) {
1726 			(void) fprintf(stderr, gettext("could not find any "
1727 			    "snapshots to destroy; check snapshot names.\n"));
1728 			rv = 1;
1729 			goto out;
1730 		}
1731 
1732 		if (cb.cb_verbose) {
1733 			char buf[16];
1734 			zfs_nicebytes(cb.cb_snapused, buf, sizeof (buf));
1735 			if (cb.cb_parsable) {
1736 				(void) printf("reclaim\t%llu\n",
1737 				    (u_longlong_t)cb.cb_snapused);
1738 			} else if (cb.cb_dryrun) {
1739 				(void) printf(gettext("would reclaim %s\n"),
1740 				    buf);
1741 			} else {
1742 				(void) printf(gettext("will reclaim %s\n"),
1743 				    buf);
1744 			}
1745 		}
1746 
1747 		if (!cb.cb_dryrun) {
1748 			if (cb.cb_doclones) {
1749 				cb.cb_batchedsnaps = fnvlist_alloc();
1750 				err = destroy_clones(&cb);
1751 				if (err == 0) {
1752 					err = zfs_destroy_snaps_nvl(g_zfs,
1753 					    cb.cb_batchedsnaps, B_FALSE);
1754 				}
1755 				if (err != 0) {
1756 					rv = 1;
1757 					goto out;
1758 				}
1759 			}
1760 			if (err == 0) {
1761 				err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1762 				    cb.cb_defer_destroy);
1763 			}
1764 		}
1765 
1766 		if (err != 0)
1767 			rv = 1;
1768 	} else if (pound != NULL) {
1769 		int err;
1770 		nvlist_t *nvl;
1771 
1772 		if (cb.cb_dryrun) {
1773 			(void) fprintf(stderr,
1774 			    "dryrun is not supported with bookmark\n");
1775 			return (-1);
1776 		}
1777 
1778 		if (cb.cb_defer_destroy) {
1779 			(void) fprintf(stderr,
1780 			    "defer destroy is not supported with bookmark\n");
1781 			return (-1);
1782 		}
1783 
1784 		if (cb.cb_recurse) {
1785 			(void) fprintf(stderr,
1786 			    "recursive is not supported with bookmark\n");
1787 			return (-1);
1788 		}
1789 
1790 		/*
1791 		 * Unfortunately, zfs_bookmark() doesn't honor the
1792 		 * casesensitivity setting.  However, we can't simply
1793 		 * remove this check, because lzc_destroy_bookmarks()
1794 		 * ignores non-existent bookmarks, so this is necessary
1795 		 * to get a proper error message.
1796 		 */
1797 		if (!zfs_bookmark_exists(argv[0])) {
1798 			(void) fprintf(stderr, gettext("bookmark '%s' "
1799 			    "does not exist.\n"), argv[0]);
1800 			return (1);
1801 		}
1802 
1803 		nvl = fnvlist_alloc();
1804 		fnvlist_add_boolean(nvl, argv[0]);
1805 
1806 		err = lzc_destroy_bookmarks(nvl, NULL);
1807 		if (err != 0) {
1808 			(void) zfs_standard_error(g_zfs, err,
1809 			    "cannot destroy bookmark");
1810 		}
1811 
1812 		nvlist_free(nvl);
1813 
1814 		return (err);
1815 	} else {
1816 		/* Open the given dataset */
1817 		if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1818 			return (1);
1819 
1820 		cb.cb_target = zhp;
1821 
1822 		/*
1823 		 * Perform an explicit check for pools before going any further.
1824 		 */
1825 		if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1826 		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1827 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1828 			    "operation does not apply to pools\n"),
1829 			    zfs_get_name(zhp));
1830 			(void) fprintf(stderr, gettext("use 'zfs destroy -r "
1831 			    "%s' to destroy all datasets in the pool\n"),
1832 			    zfs_get_name(zhp));
1833 			(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1834 			    "to destroy the pool itself\n"), zfs_get_name(zhp));
1835 			rv = 1;
1836 			goto out;
1837 		}
1838 
1839 		/*
1840 		 * Check for any dependents and/or clones.
1841 		 */
1842 		cb.cb_first = B_TRUE;
1843 		if (!cb.cb_doclones && zfs_iter_dependents_v2(zhp, 0, B_TRUE,
1844 		    destroy_check_dependent, &cb) != 0) {
1845 			rv = 1;
1846 			goto out;
1847 		}
1848 
1849 		if (cb.cb_error) {
1850 			rv = 1;
1851 			goto out;
1852 		}
1853 		cb.cb_batchedsnaps = fnvlist_alloc();
1854 		if (zfs_iter_dependents_v2(zhp, 0, B_FALSE, destroy_callback,
1855 		    &cb) != 0) {
1856 			rv = 1;
1857 			goto out;
1858 		}
1859 
1860 		/*
1861 		 * Do the real thing.  The callback will close the
1862 		 * handle regardless of whether it succeeds or not.
1863 		 */
1864 		err = destroy_callback(zhp, &cb);
1865 		zhp = NULL;
1866 		if (err == 0) {
1867 			err = zfs_destroy_snaps_nvl(g_zfs,
1868 			    cb.cb_batchedsnaps, cb.cb_defer_destroy);
1869 		}
1870 		if (err != 0 || cb.cb_error == B_TRUE)
1871 			rv = 1;
1872 	}
1873 
1874 out:
1875 	fnvlist_free(cb.cb_batchedsnaps);
1876 	fnvlist_free(cb.cb_nvl);
1877 	if (zhp != NULL)
1878 		zfs_close(zhp);
1879 	return (rv);
1880 }
1881 
1882 static boolean_t
is_recvd_column(zprop_get_cbdata_t * cbp)1883 is_recvd_column(zprop_get_cbdata_t *cbp)
1884 {
1885 	int i;
1886 	zfs_get_column_t col;
1887 
1888 	for (i = 0; i < ZFS_GET_NCOLS &&
1889 	    (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1890 		if (col == GET_COL_RECVD)
1891 			return (B_TRUE);
1892 	return (B_FALSE);
1893 }
1894 
1895 /*
1896  * Generates an nvlist with output version for every command based on params.
1897  * Purpose of this is to add a version of JSON output, considering the schema
1898  * format might be updated for each command in future.
1899  *
1900  * Schema:
1901  *
1902  * "output_version": {
1903  *    "command": string,
1904  *    "vers_major": integer,
1905  *    "vers_minor": integer,
1906  *  }
1907  */
1908 static nvlist_t *
zfs_json_schema(int maj_v,int min_v)1909 zfs_json_schema(int maj_v, int min_v)
1910 {
1911 	nvlist_t *sch = NULL;
1912 	nvlist_t *ov = NULL;
1913 	char cmd[MAX_CMD_LEN];
1914 	snprintf(cmd, MAX_CMD_LEN, "zfs %s", current_command->name);
1915 
1916 	sch = fnvlist_alloc();
1917 	ov = fnvlist_alloc();
1918 	fnvlist_add_string(ov, "command", cmd);
1919 	fnvlist_add_uint32(ov, "vers_major", maj_v);
1920 	fnvlist_add_uint32(ov, "vers_minor", min_v);
1921 	fnvlist_add_nvlist(sch, "output_version", ov);
1922 	fnvlist_free(ov);
1923 	return (sch);
1924 }
1925 
1926 static void
fill_dataset_info(nvlist_t * list,zfs_handle_t * zhp,boolean_t as_int)1927 fill_dataset_info(nvlist_t *list, zfs_handle_t *zhp, boolean_t as_int)
1928 {
1929 	char createtxg[ZFS_MAXPROPLEN];
1930 	zfs_type_t type = zfs_get_type(zhp);
1931 	nvlist_add_string(list, "name", zfs_get_name(zhp));
1932 
1933 	switch (type) {
1934 	case ZFS_TYPE_FILESYSTEM:
1935 		fnvlist_add_string(list, "type", "FILESYSTEM");
1936 		break;
1937 	case ZFS_TYPE_VOLUME:
1938 		fnvlist_add_string(list, "type", "VOLUME");
1939 		break;
1940 	case ZFS_TYPE_SNAPSHOT:
1941 		fnvlist_add_string(list, "type", "SNAPSHOT");
1942 		break;
1943 	case ZFS_TYPE_POOL:
1944 		fnvlist_add_string(list, "type", "POOL");
1945 		break;
1946 	case ZFS_TYPE_BOOKMARK:
1947 		fnvlist_add_string(list, "type", "BOOKMARK");
1948 		break;
1949 	default:
1950 		fnvlist_add_string(list, "type", "UNKNOWN");
1951 		break;
1952 	}
1953 
1954 	if (type != ZFS_TYPE_POOL)
1955 		fnvlist_add_string(list, "pool", zfs_get_pool_name(zhp));
1956 
1957 	if (as_int) {
1958 		fnvlist_add_uint64(list, "createtxg", zfs_prop_get_int(zhp,
1959 		    ZFS_PROP_CREATETXG));
1960 	} else {
1961 		if (zfs_prop_get(zhp, ZFS_PROP_CREATETXG, createtxg,
1962 		    sizeof (createtxg), NULL, NULL, 0, B_TRUE) == 0)
1963 			fnvlist_add_string(list, "createtxg", createtxg);
1964 	}
1965 
1966 	if (type == ZFS_TYPE_SNAPSHOT) {
1967 		char *ds, *snap;
1968 		ds = snap = strdup(zfs_get_name(zhp));
1969 		ds = strsep(&snap, "@");
1970 		fnvlist_add_string(list, "dataset", ds);
1971 		fnvlist_add_string(list, "snapshot_name", snap);
1972 		free(ds);
1973 	}
1974 }
1975 
1976 /*
1977  * zfs get [-rHp] [-j [--json-int]] [-o all | field[,field]...]
1978  *		[-s source[,source]...]
1979  *	< all | property[,property]... > < fs | snap | vol > ...
1980  *
1981  *	-r	recurse over any child datasets
1982  *	-H	scripted mode.  Headers are stripped, and fields are separated
1983  *		by tabs instead of spaces.
1984  *	-o	Set of fields to display.  One of "name,property,value,
1985  *		received,source". Default is "name,property,value,source".
1986  *		"all" is an alias for all five.
1987  *	-s	Set of sources to allow.  One of
1988  *		"local,default,inherited,received,temporary,none".  Default is
1989  *		all six.
1990  *	-p	Display values in parsable (literal) format.
1991  *	-j	Display output in JSON format.
1992  *	--json-int	Display numbers as integers instead of strings.
1993  *
1994  *  Prints properties for the given datasets.  The user can control which
1995  *  columns to display as well as which property types to allow.
1996  */
1997 
1998 /*
1999  * Invoked to display the properties for a single dataset.
2000  */
2001 static int
get_callback(zfs_handle_t * zhp,void * data)2002 get_callback(zfs_handle_t *zhp, void *data)
2003 {
2004 	char buf[ZFS_MAXPROPLEN];
2005 	char rbuf[ZFS_MAXPROPLEN];
2006 	zprop_source_t sourcetype;
2007 	char source[ZFS_MAX_DATASET_NAME_LEN];
2008 	zprop_get_cbdata_t *cbp = data;
2009 	nvlist_t *user_props = zfs_get_user_props(zhp);
2010 	zprop_list_t *pl = cbp->cb_proplist;
2011 	nvlist_t *propval;
2012 	nvlist_t *item, *d, *props;
2013 	item = d = props = NULL;
2014 	const char *strval;
2015 	const char *sourceval;
2016 	boolean_t received = is_recvd_column(cbp);
2017 	int err = 0;
2018 
2019 	if (cbp->cb_json) {
2020 		d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "datasets");
2021 		if (d == NULL) {
2022 			fprintf(stderr, "datasets obj not found.\n");
2023 			exit(1);
2024 		}
2025 		props = fnvlist_alloc();
2026 	}
2027 
2028 	for (; pl != NULL; pl = pl->pl_next) {
2029 		char *recvdval = NULL;
2030 		/*
2031 		 * Skip the special fake placeholder.  This will also skip over
2032 		 * the name property when 'all' is specified.
2033 		 */
2034 		if (pl->pl_prop == ZFS_PROP_NAME &&
2035 		    pl == cbp->cb_proplist)
2036 			continue;
2037 
2038 		if (pl->pl_prop != ZPROP_USERPROP) {
2039 			if (zfs_prop_get(zhp, pl->pl_prop, buf,
2040 			    sizeof (buf), &sourcetype, source,
2041 			    sizeof (source),
2042 			    cbp->cb_literal) != 0) {
2043 				if (pl->pl_all)
2044 					continue;
2045 				if (!zfs_prop_valid_for_type(pl->pl_prop,
2046 				    ZFS_TYPE_DATASET, B_FALSE)) {
2047 					(void) fprintf(stderr,
2048 					    gettext("No such property '%s'\n"),
2049 					    zfs_prop_to_name(pl->pl_prop));
2050 					continue;
2051 				}
2052 				sourcetype = ZPROP_SRC_NONE;
2053 				(void) strlcpy(buf, "-", sizeof (buf));
2054 			}
2055 
2056 			if (received && (zfs_prop_get_recvd(zhp,
2057 			    zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
2058 			    cbp->cb_literal) == 0))
2059 				recvdval = rbuf;
2060 
2061 			err = zprop_collect_property(zfs_get_name(zhp), cbp,
2062 			    zfs_prop_to_name(pl->pl_prop),
2063 			    buf, sourcetype, source, recvdval, props);
2064 		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
2065 			sourcetype = ZPROP_SRC_LOCAL;
2066 
2067 			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2068 			    buf, sizeof (buf), cbp->cb_literal) != 0) {
2069 				sourcetype = ZPROP_SRC_NONE;
2070 				(void) strlcpy(buf, "-", sizeof (buf));
2071 			}
2072 
2073 			err = zprop_collect_property(zfs_get_name(zhp), cbp,
2074 			    pl->pl_user_prop, buf, sourcetype, source, NULL,
2075 			    props);
2076 		} else if (zfs_prop_written(pl->pl_user_prop)) {
2077 			sourcetype = ZPROP_SRC_LOCAL;
2078 
2079 			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2080 			    buf, sizeof (buf), cbp->cb_literal) != 0) {
2081 				sourcetype = ZPROP_SRC_NONE;
2082 				(void) strlcpy(buf, "-", sizeof (buf));
2083 			}
2084 
2085 			err = zprop_collect_property(zfs_get_name(zhp), cbp,
2086 			    pl->pl_user_prop, buf, sourcetype, source, NULL,
2087 			    props);
2088 		} else {
2089 			if (nvlist_lookup_nvlist(user_props,
2090 			    pl->pl_user_prop, &propval) != 0) {
2091 				if (pl->pl_all)
2092 					continue;
2093 				sourcetype = ZPROP_SRC_NONE;
2094 				strval = "-";
2095 			} else {
2096 				strval = fnvlist_lookup_string(propval,
2097 				    ZPROP_VALUE);
2098 				sourceval = fnvlist_lookup_string(propval,
2099 				    ZPROP_SOURCE);
2100 
2101 				if (strcmp(sourceval,
2102 				    zfs_get_name(zhp)) == 0) {
2103 					sourcetype = ZPROP_SRC_LOCAL;
2104 				} else if (strcmp(sourceval,
2105 				    ZPROP_SOURCE_VAL_RECVD) == 0) {
2106 					sourcetype = ZPROP_SRC_RECEIVED;
2107 				} else {
2108 					sourcetype = ZPROP_SRC_INHERITED;
2109 					(void) strlcpy(source,
2110 					    sourceval, sizeof (source));
2111 				}
2112 			}
2113 
2114 			if (received && (zfs_prop_get_recvd(zhp,
2115 			    pl->pl_user_prop, rbuf, sizeof (rbuf),
2116 			    cbp->cb_literal) == 0))
2117 				recvdval = rbuf;
2118 
2119 			err = zprop_collect_property(zfs_get_name(zhp), cbp,
2120 			    pl->pl_user_prop, strval, sourcetype,
2121 			    source, recvdval, props);
2122 		}
2123 		if (err != 0)
2124 			return (err);
2125 	}
2126 
2127 	if (cbp->cb_json) {
2128 		if (!nvlist_empty(props)) {
2129 			item = fnvlist_alloc();
2130 			fill_dataset_info(item, zhp, cbp->cb_json_as_int);
2131 			fnvlist_add_nvlist(item, "properties", props);
2132 			fnvlist_add_nvlist(d, zfs_get_name(zhp), item);
2133 			fnvlist_free(props);
2134 			fnvlist_free(item);
2135 		} else {
2136 			fnvlist_free(props);
2137 		}
2138 	}
2139 
2140 	return (0);
2141 }
2142 
2143 static int
zfs_do_get(int argc,char ** argv)2144 zfs_do_get(int argc, char **argv)
2145 {
2146 	zprop_get_cbdata_t cb = { 0 };
2147 	int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2148 	int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
2149 	char *fields;
2150 	int ret = 0;
2151 	int limit = 0;
2152 	zprop_list_t fake_name = { 0 };
2153 	nvlist_t *data;
2154 
2155 	/*
2156 	 * Set up default columns and sources.
2157 	 */
2158 	cb.cb_sources = ZPROP_SRC_ALL;
2159 	cb.cb_columns[0] = GET_COL_NAME;
2160 	cb.cb_columns[1] = GET_COL_PROPERTY;
2161 	cb.cb_columns[2] = GET_COL_VALUE;
2162 	cb.cb_columns[3] = GET_COL_SOURCE;
2163 	cb.cb_type = ZFS_TYPE_DATASET;
2164 
2165 	struct option long_options[] = {
2166 		{"json", no_argument, NULL, 'j'},
2167 		{"json-int", no_argument, NULL, ZFS_OPTION_JSON_NUMS_AS_INT},
2168 		{0, 0, 0, 0}
2169 	};
2170 
2171 	/* check options */
2172 	while ((c = getopt_long(argc, argv, ":d:o:s:jrt:Hp", long_options,
2173 	    NULL)) != -1) {
2174 		switch (c) {
2175 		case 'p':
2176 			cb.cb_literal = B_TRUE;
2177 			break;
2178 		case 'd':
2179 			limit = parse_depth(optarg, &flags);
2180 			break;
2181 		case 'r':
2182 			flags |= ZFS_ITER_RECURSE;
2183 			break;
2184 		case 'H':
2185 			cb.cb_scripted = B_TRUE;
2186 			break;
2187 		case 'j':
2188 			cb.cb_json = B_TRUE;
2189 			cb.cb_jsobj = zfs_json_schema(0, 1);
2190 			data = fnvlist_alloc();
2191 			fnvlist_add_nvlist(cb.cb_jsobj, "datasets", data);
2192 			fnvlist_free(data);
2193 			break;
2194 		case ZFS_OPTION_JSON_NUMS_AS_INT:
2195 			cb.cb_json_as_int = B_TRUE;
2196 			cb.cb_literal = B_TRUE;
2197 			break;
2198 		case ':':
2199 			(void) fprintf(stderr, gettext("missing argument for "
2200 			    "'%c' option\n"), optopt);
2201 			usage(B_FALSE);
2202 			break;
2203 		case 'o':
2204 			/*
2205 			 * Process the set of columns to display.  We zero out
2206 			 * the structure to give us a blank slate.
2207 			 */
2208 			memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
2209 
2210 			i = 0;
2211 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
2212 				static const char *const col_subopts[] =
2213 				{ "name", "property", "value",
2214 				    "received", "source", "all" };
2215 				static const zfs_get_column_t col_subopt_col[] =
2216 				{ GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
2217 				    GET_COL_RECVD, GET_COL_SOURCE };
2218 				static const int col_subopt_flags[] =
2219 				{ 0, 0, 0, ZFS_ITER_RECVD_PROPS, 0 };
2220 
2221 				if (i == ZFS_GET_NCOLS) {
2222 					(void) fprintf(stderr, gettext("too "
2223 					    "many fields given to -o "
2224 					    "option\n"));
2225 					usage(B_FALSE);
2226 				}
2227 
2228 				for (c = 0; c < ARRAY_SIZE(col_subopts); ++c)
2229 					if (strcmp(tok, col_subopts[c]) == 0)
2230 						goto found;
2231 
2232 				(void) fprintf(stderr,
2233 				    gettext("invalid column name '%s'\n"), tok);
2234 				usage(B_FALSE);
2235 
2236 found:
2237 				if (c >= 5) {
2238 					if (i > 0) {
2239 						(void) fprintf(stderr,
2240 						    gettext("\"all\" conflicts "
2241 						    "with specific fields "
2242 						    "given to -o option\n"));
2243 						usage(B_FALSE);
2244 					}
2245 
2246 					memcpy(cb.cb_columns, col_subopt_col,
2247 					    sizeof (col_subopt_col));
2248 					flags |= ZFS_ITER_RECVD_PROPS;
2249 					i = ZFS_GET_NCOLS;
2250 				} else {
2251 					cb.cb_columns[i++] = col_subopt_col[c];
2252 					flags |= col_subopt_flags[c];
2253 				}
2254 			}
2255 			break;
2256 
2257 		case 's':
2258 			cb.cb_sources = 0;
2259 
2260 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
2261 				static const char *const source_opt[] = {
2262 					"local", "default",
2263 					"inherited", "received",
2264 					"temporary", "none" };
2265 				static const int source_flg[] = {
2266 					ZPROP_SRC_LOCAL, ZPROP_SRC_DEFAULT,
2267 					ZPROP_SRC_INHERITED, ZPROP_SRC_RECEIVED,
2268 					ZPROP_SRC_TEMPORARY, ZPROP_SRC_NONE };
2269 
2270 				for (i = 0; i < ARRAY_SIZE(source_opt); ++i)
2271 					if (strcmp(tok, source_opt[i]) == 0) {
2272 						cb.cb_sources |= source_flg[i];
2273 						goto found2;
2274 					}
2275 
2276 				(void) fprintf(stderr,
2277 				    gettext("invalid source '%s'\n"), tok);
2278 				usage(B_FALSE);
2279 found2:;
2280 			}
2281 			break;
2282 
2283 		case 't':
2284 			types = 0;
2285 			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2286 
2287 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
2288 				static const char *const type_opts[] = {
2289 					"filesystem",
2290 					"fs",
2291 					"volume",
2292 					"vol",
2293 					"snapshot",
2294 					"snap",
2295 					"bookmark",
2296 					"all"
2297 				};
2298 				static const int type_types[] = {
2299 					ZFS_TYPE_FILESYSTEM,
2300 					ZFS_TYPE_FILESYSTEM,
2301 					ZFS_TYPE_VOLUME,
2302 					ZFS_TYPE_VOLUME,
2303 					ZFS_TYPE_SNAPSHOT,
2304 					ZFS_TYPE_SNAPSHOT,
2305 					ZFS_TYPE_BOOKMARK,
2306 					ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK
2307 				};
2308 
2309 				for (i = 0; i < ARRAY_SIZE(type_opts); ++i)
2310 					if (strcmp(tok, type_opts[i]) == 0) {
2311 						types |= type_types[i];
2312 						goto found3;
2313 					}
2314 
2315 				(void) fprintf(stderr,
2316 				    gettext("invalid type '%s'\n"), tok);
2317 				usage(B_FALSE);
2318 found3:;
2319 			}
2320 			break;
2321 		case '?':
2322 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2323 			    optopt);
2324 			usage(B_FALSE);
2325 		}
2326 	}
2327 
2328 	argc -= optind;
2329 	argv += optind;
2330 
2331 	if (argc < 1) {
2332 		(void) fprintf(stderr, gettext("missing property "
2333 		    "argument\n"));
2334 		usage(B_FALSE);
2335 	}
2336 
2337 	if (!cb.cb_json && cb.cb_json_as_int) {
2338 		(void) fprintf(stderr, gettext("'--json-int' only works with"
2339 		    " '-j' option\n"));
2340 		usage(B_FALSE);
2341 	}
2342 
2343 	fields = argv[0];
2344 
2345 	/*
2346 	 * Handle users who want to get all snapshots or bookmarks
2347 	 * of a dataset (ex. 'zfs get -t snapshot refer <dataset>').
2348 	 */
2349 	if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
2350 	    argc > 1 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
2351 		flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
2352 		limit = 1;
2353 	}
2354 
2355 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2356 	    != 0)
2357 		usage(B_FALSE);
2358 
2359 	argc--;
2360 	argv++;
2361 
2362 	/*
2363 	 * As part of zfs_expand_proplist(), we keep track of the maximum column
2364 	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
2365 	 * need to know the maximum name length.  However, the user likely did
2366 	 * not specify 'name' as one of the properties to fetch, so we need to
2367 	 * make sure we always include at least this property for
2368 	 * print_get_headers() to work properly.
2369 	 */
2370 	if (cb.cb_proplist != NULL) {
2371 		fake_name.pl_prop = ZFS_PROP_NAME;
2372 		fake_name.pl_width = strlen(gettext("NAME"));
2373 		fake_name.pl_next = cb.cb_proplist;
2374 		cb.cb_proplist = &fake_name;
2375 	}
2376 
2377 	cb.cb_first = B_TRUE;
2378 
2379 	/* run for each object */
2380 	ret = zfs_for_each(argc, argv, flags, types, NULL,
2381 	    &cb.cb_proplist, limit, get_callback, &cb);
2382 
2383 	if (ret == 0 && cb.cb_json)
2384 		zcmd_print_json(cb.cb_jsobj);
2385 	else if (ret != 0 && cb.cb_json)
2386 		nvlist_free(cb.cb_jsobj);
2387 
2388 	if (cb.cb_proplist == &fake_name)
2389 		zprop_free_list(fake_name.pl_next);
2390 	else
2391 		zprop_free_list(cb.cb_proplist);
2392 
2393 	return (ret);
2394 }
2395 
2396 /*
2397  * inherit [-rS] <property> <fs|vol> ...
2398  *
2399  *	-r	Recurse over all children
2400  *	-S	Revert to received value, if any
2401  *
2402  * For each dataset specified on the command line, inherit the given property
2403  * from its parent.  Inheriting a property at the pool level will cause it to
2404  * use the default value.  The '-r' flag will recurse over all children, and is
2405  * useful for setting a property on a hierarchy-wide basis, regardless of any
2406  * local modifications for each dataset.
2407  */
2408 
2409 typedef struct inherit_cbdata {
2410 	const char *cb_propname;
2411 	boolean_t cb_received;
2412 } inherit_cbdata_t;
2413 
2414 static int
inherit_recurse_cb(zfs_handle_t * zhp,void * data)2415 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
2416 {
2417 	inherit_cbdata_t *cb = data;
2418 	zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
2419 
2420 	/*
2421 	 * If we're doing it recursively, then ignore properties that
2422 	 * are not valid for this type of dataset.
2423 	 */
2424 	if (prop != ZPROP_INVAL &&
2425 	    !zfs_prop_valid_for_type(prop, zfs_get_type(zhp), B_FALSE))
2426 		return (0);
2427 
2428 	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2429 }
2430 
2431 static int
inherit_cb(zfs_handle_t * zhp,void * data)2432 inherit_cb(zfs_handle_t *zhp, void *data)
2433 {
2434 	inherit_cbdata_t *cb = data;
2435 
2436 	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2437 }
2438 
2439 static int
zfs_do_inherit(int argc,char ** argv)2440 zfs_do_inherit(int argc, char **argv)
2441 {
2442 	int c;
2443 	zfs_prop_t prop;
2444 	inherit_cbdata_t cb = { 0 };
2445 	char *propname;
2446 	int ret = 0;
2447 	int flags = 0;
2448 	boolean_t received = B_FALSE;
2449 
2450 	/* check options */
2451 	while ((c = getopt(argc, argv, "rS")) != -1) {
2452 		switch (c) {
2453 		case 'r':
2454 			flags |= ZFS_ITER_RECURSE;
2455 			break;
2456 		case 'S':
2457 			received = B_TRUE;
2458 			break;
2459 		case '?':
2460 		default:
2461 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2462 			    optopt);
2463 			usage(B_FALSE);
2464 		}
2465 	}
2466 
2467 	argc -= optind;
2468 	argv += optind;
2469 
2470 	/* check number of arguments */
2471 	if (argc < 1) {
2472 		(void) fprintf(stderr, gettext("missing property argument\n"));
2473 		usage(B_FALSE);
2474 	}
2475 	if (argc < 2) {
2476 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
2477 		usage(B_FALSE);
2478 	}
2479 
2480 	propname = argv[0];
2481 	argc--;
2482 	argv++;
2483 
2484 	if ((prop = zfs_name_to_prop(propname)) != ZPROP_USERPROP) {
2485 		if (zfs_prop_readonly(prop)) {
2486 			(void) fprintf(stderr, gettext(
2487 			    "%s property is read-only\n"),
2488 			    propname);
2489 			return (1);
2490 		}
2491 		if (!zfs_prop_inheritable(prop) && !received) {
2492 			(void) fprintf(stderr, gettext("'%s' property cannot "
2493 			    "be inherited\n"), propname);
2494 			if (prop == ZFS_PROP_QUOTA ||
2495 			    prop == ZFS_PROP_RESERVATION ||
2496 			    prop == ZFS_PROP_REFQUOTA ||
2497 			    prop == ZFS_PROP_REFRESERVATION) {
2498 				(void) fprintf(stderr, gettext("use 'zfs set "
2499 				    "%s=none' to clear\n"), propname);
2500 				(void) fprintf(stderr, gettext("use 'zfs "
2501 				    "inherit -S %s' to revert to received "
2502 				    "value\n"), propname);
2503 			}
2504 			return (1);
2505 		}
2506 		if (received && (prop == ZFS_PROP_VOLSIZE ||
2507 		    prop == ZFS_PROP_VERSION)) {
2508 			(void) fprintf(stderr, gettext("'%s' property cannot "
2509 			    "be reverted to a received value\n"), propname);
2510 			return (1);
2511 		}
2512 	} else if (!zfs_prop_user(propname)) {
2513 		(void) fprintf(stderr, gettext("invalid property '%s'\n"),
2514 		    propname);
2515 		usage(B_FALSE);
2516 	}
2517 
2518 	cb.cb_propname = propname;
2519 	cb.cb_received = received;
2520 
2521 	if (flags & ZFS_ITER_RECURSE) {
2522 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2523 		    NULL, NULL, 0, inherit_recurse_cb, &cb);
2524 	} else {
2525 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2526 		    NULL, NULL, 0, inherit_cb, &cb);
2527 	}
2528 
2529 	return (ret);
2530 }
2531 
2532 typedef struct upgrade_cbdata {
2533 	uint64_t cb_numupgraded;
2534 	uint64_t cb_numsamegraded;
2535 	uint64_t cb_numfailed;
2536 	uint64_t cb_version;
2537 	boolean_t cb_newer;
2538 	boolean_t cb_foundone;
2539 	char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
2540 } upgrade_cbdata_t;
2541 
2542 static int
same_pool(zfs_handle_t * zhp,const char * name)2543 same_pool(zfs_handle_t *zhp, const char *name)
2544 {
2545 	int len1 = strcspn(name, "/@");
2546 	const char *zhname = zfs_get_name(zhp);
2547 	int len2 = strcspn(zhname, "/@");
2548 
2549 	if (len1 != len2)
2550 		return (B_FALSE);
2551 	return (strncmp(name, zhname, len1) == 0);
2552 }
2553 
2554 static int
upgrade_list_callback(zfs_handle_t * zhp,void * data)2555 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2556 {
2557 	upgrade_cbdata_t *cb = data;
2558 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2559 
2560 	/* list if it's old/new */
2561 	if ((!cb->cb_newer && version < ZPL_VERSION) ||
2562 	    (cb->cb_newer && version > ZPL_VERSION)) {
2563 		char *str;
2564 		if (cb->cb_newer) {
2565 			str = gettext("The following filesystems are "
2566 			    "formatted using a newer software version and\n"
2567 			    "cannot be accessed on the current system.\n\n");
2568 		} else {
2569 			str = gettext("The following filesystems are "
2570 			    "out of date, and can be upgraded.  After being\n"
2571 			    "upgraded, these filesystems (and any 'zfs send' "
2572 			    "streams generated from\n"
2573 			    "subsequent snapshots) will no longer be "
2574 			    "accessible by older software versions.\n\n");
2575 		}
2576 
2577 		if (!cb->cb_foundone) {
2578 			(void) puts(str);
2579 			(void) printf(gettext("VER  FILESYSTEM\n"));
2580 			(void) printf(gettext("---  ------------\n"));
2581 			cb->cb_foundone = B_TRUE;
2582 		}
2583 
2584 		(void) printf("%2u   %s\n", version, zfs_get_name(zhp));
2585 	}
2586 
2587 	return (0);
2588 }
2589 
2590 static int
upgrade_set_callback(zfs_handle_t * zhp,void * data)2591 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2592 {
2593 	upgrade_cbdata_t *cb = data;
2594 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2595 	int needed_spa_version;
2596 	int spa_version;
2597 
2598 	if (zfs_spa_version(zhp, &spa_version) < 0)
2599 		return (-1);
2600 
2601 	needed_spa_version = zfs_spa_version_map(cb->cb_version);
2602 
2603 	if (needed_spa_version < 0)
2604 		return (-1);
2605 
2606 	if (spa_version < needed_spa_version) {
2607 		/* can't upgrade */
2608 		(void) printf(gettext("%s: can not be "
2609 		    "upgraded; the pool version needs to first "
2610 		    "be upgraded\nto version %d\n\n"),
2611 		    zfs_get_name(zhp), needed_spa_version);
2612 		cb->cb_numfailed++;
2613 		return (0);
2614 	}
2615 
2616 	/* upgrade */
2617 	if (version < cb->cb_version) {
2618 		char verstr[24];
2619 		(void) snprintf(verstr, sizeof (verstr),
2620 		    "%llu", (u_longlong_t)cb->cb_version);
2621 		if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2622 			/*
2623 			 * If they did "zfs upgrade -a", then we could
2624 			 * be doing ioctls to different pools.  We need
2625 			 * to log this history once to each pool, and bypass
2626 			 * the normal history logging that happens in main().
2627 			 */
2628 			(void) zpool_log_history(g_zfs, history_str);
2629 			log_history = B_FALSE;
2630 		}
2631 		if (zfs_prop_set(zhp, "version", verstr) == 0)
2632 			cb->cb_numupgraded++;
2633 		else
2634 			cb->cb_numfailed++;
2635 		(void) strlcpy(cb->cb_lastfs, zfs_get_name(zhp),
2636 		    sizeof (cb->cb_lastfs));
2637 	} else if (version > cb->cb_version) {
2638 		/* can't downgrade */
2639 		(void) printf(gettext("%s: can not be downgraded; "
2640 		    "it is already at version %u\n"),
2641 		    zfs_get_name(zhp), version);
2642 		cb->cb_numfailed++;
2643 	} else {
2644 		cb->cb_numsamegraded++;
2645 	}
2646 	return (0);
2647 }
2648 
2649 /*
2650  * zfs upgrade
2651  * zfs upgrade -v
2652  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2653  */
2654 static int
zfs_do_upgrade(int argc,char ** argv)2655 zfs_do_upgrade(int argc, char **argv)
2656 {
2657 	boolean_t all = B_FALSE;
2658 	boolean_t showversions = B_FALSE;
2659 	int ret = 0;
2660 	upgrade_cbdata_t cb = { 0 };
2661 	int c;
2662 	int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2663 
2664 	/* check options */
2665 	while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2666 		switch (c) {
2667 		case 'r':
2668 			flags |= ZFS_ITER_RECURSE;
2669 			break;
2670 		case 'v':
2671 			showversions = B_TRUE;
2672 			break;
2673 		case 'V':
2674 			if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2675 			    optarg, &cb.cb_version) != 0) {
2676 				(void) fprintf(stderr,
2677 				    gettext("invalid version %s\n"), optarg);
2678 				usage(B_FALSE);
2679 			}
2680 			break;
2681 		case 'a':
2682 			all = B_TRUE;
2683 			break;
2684 		case '?':
2685 		default:
2686 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2687 			    optopt);
2688 			usage(B_FALSE);
2689 		}
2690 	}
2691 
2692 	argc -= optind;
2693 	argv += optind;
2694 
2695 	if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2696 		usage(B_FALSE);
2697 	if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2698 	    cb.cb_version || argc))
2699 		usage(B_FALSE);
2700 	if ((all || argc) && (showversions))
2701 		usage(B_FALSE);
2702 	if (all && argc)
2703 		usage(B_FALSE);
2704 
2705 	if (showversions) {
2706 		/* Show info on available versions. */
2707 		(void) printf(gettext("The following filesystem versions are "
2708 		    "supported:\n\n"));
2709 		(void) printf(gettext("VER  DESCRIPTION\n"));
2710 		(void) printf("---  -----------------------------------------"
2711 		    "---------------\n");
2712 		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
2713 		(void) printf(gettext(" 2   Enhanced directory entries\n"));
2714 		(void) printf(gettext(" 3   Case insensitive and filesystem "
2715 		    "user identifier (FUID)\n"));
2716 		(void) printf(gettext(" 4   userquota, groupquota "
2717 		    "properties\n"));
2718 		(void) printf(gettext(" 5   System attributes\n"));
2719 		(void) printf(gettext("\nFor more information on a particular "
2720 		    "version, including supported releases,\n"));
2721 		(void) printf("see the ZFS Administration Guide.\n\n");
2722 		ret = 0;
2723 	} else if (argc || all) {
2724 		/* Upgrade filesystems */
2725 		if (cb.cb_version == 0)
2726 			cb.cb_version = ZPL_VERSION;
2727 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2728 		    NULL, NULL, 0, upgrade_set_callback, &cb);
2729 		(void) printf(gettext("%llu filesystems upgraded\n"),
2730 		    (u_longlong_t)cb.cb_numupgraded);
2731 		if (cb.cb_numsamegraded) {
2732 			(void) printf(gettext("%llu filesystems already at "
2733 			    "this version\n"),
2734 			    (u_longlong_t)cb.cb_numsamegraded);
2735 		}
2736 		if (cb.cb_numfailed != 0)
2737 			ret = 1;
2738 	} else {
2739 		/* List old-version filesystems */
2740 		boolean_t found;
2741 		(void) printf(gettext("This system is currently running "
2742 		    "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2743 
2744 		flags |= ZFS_ITER_RECURSE;
2745 		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2746 		    NULL, NULL, 0, upgrade_list_callback, &cb);
2747 
2748 		found = cb.cb_foundone;
2749 		cb.cb_foundone = B_FALSE;
2750 		cb.cb_newer = B_TRUE;
2751 
2752 		ret |= zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2753 		    NULL, NULL, 0, upgrade_list_callback, &cb);
2754 
2755 		if (!cb.cb_foundone && !found) {
2756 			(void) printf(gettext("All filesystems are "
2757 			    "formatted with the current version.\n"));
2758 		}
2759 	}
2760 
2761 	return (ret);
2762 }
2763 
2764 /*
2765  * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2766  *               [-S field [-S field]...] [-t type[,...]]
2767  *               filesystem | snapshot | path
2768  * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2769  *                [-S field [-S field]...] [-t type[,...]]
2770  *                filesystem | snapshot | path
2771  * zfs projectspace [-Hp] [-o field[,...]] [-s field [-s field]...]
2772  *                [-S field [-S field]...] filesystem | snapshot | path
2773  *
2774  *	-H      Scripted mode; elide headers and separate columns by tabs.
2775  *	-i	Translate SID to POSIX ID.
2776  *	-n	Print numeric ID instead of user/group name.
2777  *	-o      Control which fields to display.
2778  *	-p	Use exact (parsable) numeric output.
2779  *	-s      Specify sort columns, descending order.
2780  *	-S      Specify sort columns, ascending order.
2781  *	-t      Control which object types to display.
2782  *
2783  *	Displays space consumed by, and quotas on, each user in the specified
2784  *	filesystem or snapshot.
2785  */
2786 
2787 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2788 enum us_field_types {
2789 	USFIELD_TYPE,
2790 	USFIELD_NAME,
2791 	USFIELD_USED,
2792 	USFIELD_QUOTA,
2793 	USFIELD_OBJUSED,
2794 	USFIELD_OBJQUOTA
2795 };
2796 static const char *const us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA",
2797 				    "OBJUSED", "OBJQUOTA" };
2798 static const char *const us_field_names[] = { "type", "name", "used", "quota",
2799 				    "objused", "objquota" };
2800 #define	USFIELD_LAST	(sizeof (us_field_names) / sizeof (char *))
2801 
2802 #define	USTYPE_PSX_GRP	(1 << 0)
2803 #define	USTYPE_PSX_USR	(1 << 1)
2804 #define	USTYPE_SMB_GRP	(1 << 2)
2805 #define	USTYPE_SMB_USR	(1 << 3)
2806 #define	USTYPE_PROJ	(1 << 4)
2807 #define	USTYPE_ALL	\
2808 	(USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR | \
2809 	    USTYPE_PROJ)
2810 
2811 static int us_type_bits[] = {
2812 	USTYPE_PSX_GRP,
2813 	USTYPE_PSX_USR,
2814 	USTYPE_SMB_GRP,
2815 	USTYPE_SMB_USR,
2816 	USTYPE_ALL
2817 };
2818 static const char *const us_type_names[] = { "posixgroup", "posixuser",
2819 	"smbgroup", "smbuser", "all" };
2820 
2821 typedef struct us_node {
2822 	nvlist_t	*usn_nvl;
2823 	uu_avl_node_t	usn_avlnode;
2824 	uu_list_node_t	usn_listnode;
2825 } us_node_t;
2826 
2827 typedef struct us_cbdata {
2828 	nvlist_t	**cb_nvlp;
2829 	uu_avl_pool_t	*cb_avl_pool;
2830 	uu_avl_t	*cb_avl;
2831 	boolean_t	cb_numname;
2832 	boolean_t	cb_nicenum;
2833 	boolean_t	cb_sid2posix;
2834 	zfs_userquota_prop_t cb_prop;
2835 	zfs_sort_column_t *cb_sortcol;
2836 	size_t		cb_width[USFIELD_LAST];
2837 } us_cbdata_t;
2838 
2839 static boolean_t us_populated = B_FALSE;
2840 
2841 typedef struct {
2842 	zfs_sort_column_t *si_sortcol;
2843 	boolean_t	si_numname;
2844 } us_sort_info_t;
2845 
2846 static int
us_field_index(const char * field)2847 us_field_index(const char *field)
2848 {
2849 	for (int i = 0; i < USFIELD_LAST; i++) {
2850 		if (strcmp(field, us_field_names[i]) == 0)
2851 			return (i);
2852 	}
2853 
2854 	return (-1);
2855 }
2856 
2857 static int
us_compare(const void * larg,const void * rarg,void * unused)2858 us_compare(const void *larg, const void *rarg, void *unused)
2859 {
2860 	const us_node_t *l = larg;
2861 	const us_node_t *r = rarg;
2862 	us_sort_info_t *si = (us_sort_info_t *)unused;
2863 	zfs_sort_column_t *sortcol = si->si_sortcol;
2864 	boolean_t numname = si->si_numname;
2865 	nvlist_t *lnvl = l->usn_nvl;
2866 	nvlist_t *rnvl = r->usn_nvl;
2867 	int rc = 0;
2868 	boolean_t lvb, rvb;
2869 
2870 	for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2871 		const char *lvstr = "";
2872 		const char *rvstr = "";
2873 		uint32_t lv32 = 0;
2874 		uint32_t rv32 = 0;
2875 		uint64_t lv64 = 0;
2876 		uint64_t rv64 = 0;
2877 		zfs_prop_t prop = sortcol->sc_prop;
2878 		const char *propname = NULL;
2879 		boolean_t reverse = sortcol->sc_reverse;
2880 
2881 		switch (prop) {
2882 		case ZFS_PROP_TYPE:
2883 			propname = "type";
2884 			(void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2885 			(void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2886 			if (rv32 != lv32)
2887 				rc = (rv32 < lv32) ? 1 : -1;
2888 			break;
2889 		case ZFS_PROP_NAME:
2890 			propname = "name";
2891 			if (numname) {
2892 compare_nums:
2893 				(void) nvlist_lookup_uint64(lnvl, propname,
2894 				    &lv64);
2895 				(void) nvlist_lookup_uint64(rnvl, propname,
2896 				    &rv64);
2897 				if (rv64 != lv64)
2898 					rc = (rv64 < lv64) ? 1 : -1;
2899 			} else {
2900 				if ((nvlist_lookup_string(lnvl, propname,
2901 				    &lvstr) == ENOENT) ||
2902 				    (nvlist_lookup_string(rnvl, propname,
2903 				    &rvstr) == ENOENT)) {
2904 					goto compare_nums;
2905 				}
2906 				rc = strcmp(lvstr, rvstr);
2907 			}
2908 			break;
2909 		case ZFS_PROP_USED:
2910 		case ZFS_PROP_QUOTA:
2911 			if (!us_populated)
2912 				break;
2913 			if (prop == ZFS_PROP_USED)
2914 				propname = "used";
2915 			else
2916 				propname = "quota";
2917 			(void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2918 			(void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2919 			if (rv64 != lv64)
2920 				rc = (rv64 < lv64) ? 1 : -1;
2921 			break;
2922 
2923 		default:
2924 			break;
2925 		}
2926 
2927 		if (rc != 0) {
2928 			if (rc < 0)
2929 				return (reverse ? 1 : -1);
2930 			else
2931 				return (reverse ? -1 : 1);
2932 		}
2933 	}
2934 
2935 	/*
2936 	 * If entries still seem to be the same, check if they are of the same
2937 	 * type (smbentity is added only if we are doing SID to POSIX ID
2938 	 * translation where we can have duplicate type/name combinations).
2939 	 */
2940 	if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2941 	    nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2942 	    lvb != rvb)
2943 		return (lvb < rvb ? -1 : 1);
2944 
2945 	return (0);
2946 }
2947 
2948 static boolean_t
zfs_prop_is_user(unsigned p)2949 zfs_prop_is_user(unsigned p)
2950 {
2951 	return (p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA ||
2952 	    p == ZFS_PROP_USEROBJUSED || p == ZFS_PROP_USEROBJQUOTA);
2953 }
2954 
2955 static boolean_t
zfs_prop_is_group(unsigned p)2956 zfs_prop_is_group(unsigned p)
2957 {
2958 	return (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA ||
2959 	    p == ZFS_PROP_GROUPOBJUSED || p == ZFS_PROP_GROUPOBJQUOTA);
2960 }
2961 
2962 static boolean_t
zfs_prop_is_project(unsigned p)2963 zfs_prop_is_project(unsigned p)
2964 {
2965 	return (p == ZFS_PROP_PROJECTUSED || p == ZFS_PROP_PROJECTQUOTA ||
2966 	    p == ZFS_PROP_PROJECTOBJUSED || p == ZFS_PROP_PROJECTOBJQUOTA);
2967 }
2968 
2969 static inline const char *
us_type2str(unsigned field_type)2970 us_type2str(unsigned field_type)
2971 {
2972 	switch (field_type) {
2973 	case USTYPE_PSX_USR:
2974 		return ("POSIX User");
2975 	case USTYPE_PSX_GRP:
2976 		return ("POSIX Group");
2977 	case USTYPE_SMB_USR:
2978 		return ("SMB User");
2979 	case USTYPE_SMB_GRP:
2980 		return ("SMB Group");
2981 	case USTYPE_PROJ:
2982 		return ("Project");
2983 	default:
2984 		return ("Undefined");
2985 	}
2986 }
2987 
2988 static int
userspace_cb(void * arg,const char * domain,uid_t rid,uint64_t space)2989 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2990 {
2991 	us_cbdata_t *cb = (us_cbdata_t *)arg;
2992 	zfs_userquota_prop_t prop = cb->cb_prop;
2993 	char *name = NULL;
2994 	const char *propname;
2995 	char sizebuf[32];
2996 	us_node_t *node;
2997 	uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2998 	uu_avl_t *avl = cb->cb_avl;
2999 	uu_avl_index_t idx;
3000 	nvlist_t *props;
3001 	us_node_t *n;
3002 	zfs_sort_column_t *sortcol = cb->cb_sortcol;
3003 	unsigned type = 0;
3004 	const char *typestr;
3005 	size_t namelen;
3006 	size_t typelen;
3007 	size_t sizelen;
3008 	int typeidx, nameidx, sizeidx;
3009 	us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
3010 	boolean_t smbentity = B_FALSE;
3011 
3012 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3013 		nomem();
3014 	node = safe_malloc(sizeof (us_node_t));
3015 	uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
3016 	node->usn_nvl = props;
3017 
3018 	if (domain != NULL && domain[0] != '\0') {
3019 #ifdef HAVE_IDMAP
3020 		/* SMB */
3021 		char sid[MAXNAMELEN + 32];
3022 		uid_t id;
3023 		uint64_t classes;
3024 		int err;
3025 		directory_error_t e;
3026 
3027 		smbentity = B_TRUE;
3028 
3029 		(void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
3030 
3031 		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
3032 			type = USTYPE_SMB_GRP;
3033 			err = sid_to_id(sid, B_FALSE, &id);
3034 		} else {
3035 			type = USTYPE_SMB_USR;
3036 			err = sid_to_id(sid, B_TRUE, &id);
3037 		}
3038 
3039 		if (err == 0) {
3040 			rid = id;
3041 			if (!cb->cb_sid2posix) {
3042 				e = directory_name_from_sid(NULL, sid, &name,
3043 				    &classes);
3044 				if (e != NULL)
3045 					directory_error_free(e);
3046 				if (name == NULL)
3047 					name = sid;
3048 			}
3049 		}
3050 #else
3051 		nvlist_free(props);
3052 		free(node);
3053 
3054 		return (-1);
3055 #endif /* HAVE_IDMAP */
3056 	}
3057 
3058 	if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
3059 		/* POSIX or -i */
3060 		if (zfs_prop_is_group(prop)) {
3061 			type = USTYPE_PSX_GRP;
3062 			if (!cb->cb_numname) {
3063 				struct group *g;
3064 
3065 				if ((g = getgrgid(rid)) != NULL)
3066 					name = g->gr_name;
3067 			}
3068 		} else if (zfs_prop_is_user(prop)) {
3069 			type = USTYPE_PSX_USR;
3070 			if (!cb->cb_numname) {
3071 				struct passwd *p;
3072 
3073 				if ((p = getpwuid(rid)) != NULL)
3074 					name = p->pw_name;
3075 			}
3076 		} else {
3077 			type = USTYPE_PROJ;
3078 		}
3079 	}
3080 
3081 	/*
3082 	 * Make sure that the type/name combination is unique when doing
3083 	 * SID to POSIX ID translation (hence changing the type from SMB to
3084 	 * POSIX).
3085 	 */
3086 	if (cb->cb_sid2posix &&
3087 	    nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
3088 		nomem();
3089 
3090 	/* Calculate/update width of TYPE field */
3091 	typestr = us_type2str(type);
3092 	typelen = strlen(gettext(typestr));
3093 	typeidx = us_field_index("type");
3094 	if (typelen > cb->cb_width[typeidx])
3095 		cb->cb_width[typeidx] = typelen;
3096 	if (nvlist_add_uint32(props, "type", type) != 0)
3097 		nomem();
3098 
3099 	/* Calculate/update width of NAME field */
3100 	if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
3101 		if (nvlist_add_uint64(props, "name", rid) != 0)
3102 			nomem();
3103 		namelen = snprintf(NULL, 0, "%u", rid);
3104 	} else {
3105 		if (nvlist_add_string(props, "name", name) != 0)
3106 			nomem();
3107 		namelen = strlen(name);
3108 	}
3109 	nameidx = us_field_index("name");
3110 	if (nameidx >= 0 && namelen > cb->cb_width[nameidx])
3111 		cb->cb_width[nameidx] = namelen;
3112 
3113 	/*
3114 	 * Check if this type/name combination is in the list and update it;
3115 	 * otherwise add new node to the list.
3116 	 */
3117 	if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
3118 		uu_avl_insert(avl, node, idx);
3119 	} else {
3120 		nvlist_free(props);
3121 		free(node);
3122 		node = n;
3123 		props = node->usn_nvl;
3124 	}
3125 
3126 	/* Calculate/update width of USED/QUOTA fields */
3127 	if (cb->cb_nicenum) {
3128 		if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
3129 		    prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
3130 		    prop == ZFS_PROP_PROJECTUSED ||
3131 		    prop == ZFS_PROP_PROJECTQUOTA) {
3132 			zfs_nicebytes(space, sizebuf, sizeof (sizebuf));
3133 		} else {
3134 			zfs_nicenum(space, sizebuf, sizeof (sizebuf));
3135 		}
3136 	} else {
3137 		(void) snprintf(sizebuf, sizeof (sizebuf), "%llu",
3138 		    (u_longlong_t)space);
3139 	}
3140 	sizelen = strlen(sizebuf);
3141 	if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
3142 	    prop == ZFS_PROP_PROJECTUSED) {
3143 		propname = "used";
3144 		if (!nvlist_exists(props, "quota"))
3145 			(void) nvlist_add_uint64(props, "quota", 0);
3146 	} else if (prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
3147 	    prop == ZFS_PROP_PROJECTQUOTA) {
3148 		propname = "quota";
3149 		if (!nvlist_exists(props, "used"))
3150 			(void) nvlist_add_uint64(props, "used", 0);
3151 	} else if (prop == ZFS_PROP_USEROBJUSED ||
3152 	    prop == ZFS_PROP_GROUPOBJUSED || prop == ZFS_PROP_PROJECTOBJUSED) {
3153 		propname = "objused";
3154 		if (!nvlist_exists(props, "objquota"))
3155 			(void) nvlist_add_uint64(props, "objquota", 0);
3156 	} else if (prop == ZFS_PROP_USEROBJQUOTA ||
3157 	    prop == ZFS_PROP_GROUPOBJQUOTA ||
3158 	    prop == ZFS_PROP_PROJECTOBJQUOTA) {
3159 		propname = "objquota";
3160 		if (!nvlist_exists(props, "objused"))
3161 			(void) nvlist_add_uint64(props, "objused", 0);
3162 	} else {
3163 		return (-1);
3164 	}
3165 	sizeidx = us_field_index(propname);
3166 	if (sizeidx >= 0 && sizelen > cb->cb_width[sizeidx])
3167 		cb->cb_width[sizeidx] = sizelen;
3168 
3169 	if (nvlist_add_uint64(props, propname, space) != 0)
3170 		nomem();
3171 
3172 	return (0);
3173 }
3174 
3175 static void
print_us_node(boolean_t scripted,boolean_t parsable,int * fields,int types,size_t * width,us_node_t * node)3176 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
3177     size_t *width, us_node_t *node)
3178 {
3179 	nvlist_t *nvl = node->usn_nvl;
3180 	char valstr[MAXNAMELEN];
3181 	boolean_t first = B_TRUE;
3182 	int cfield = 0;
3183 	int field;
3184 	uint32_t ustype;
3185 
3186 	/* Check type */
3187 	(void) nvlist_lookup_uint32(nvl, "type", &ustype);
3188 	if (!(ustype & types))
3189 		return;
3190 
3191 	while ((field = fields[cfield]) != USFIELD_LAST) {
3192 		nvpair_t *nvp = NULL;
3193 		data_type_t type;
3194 		uint32_t val32 = -1;
3195 		uint64_t val64 = -1;
3196 		const char *strval = "-";
3197 
3198 		while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL)
3199 			if (strcmp(nvpair_name(nvp),
3200 			    us_field_names[field]) == 0)
3201 				break;
3202 
3203 		type = nvp == NULL ? DATA_TYPE_UNKNOWN : nvpair_type(nvp);
3204 		switch (type) {
3205 		case DATA_TYPE_UINT32:
3206 			val32 = fnvpair_value_uint32(nvp);
3207 			break;
3208 		case DATA_TYPE_UINT64:
3209 			val64 = fnvpair_value_uint64(nvp);
3210 			break;
3211 		case DATA_TYPE_STRING:
3212 			strval = fnvpair_value_string(nvp);
3213 			break;
3214 		case DATA_TYPE_UNKNOWN:
3215 			break;
3216 		default:
3217 			(void) fprintf(stderr, "invalid data type\n");
3218 		}
3219 
3220 		switch (field) {
3221 		case USFIELD_TYPE:
3222 			if (type == DATA_TYPE_UINT32)
3223 				strval = us_type2str(val32);
3224 			break;
3225 		case USFIELD_NAME:
3226 			if (type == DATA_TYPE_UINT64) {
3227 				(void) sprintf(valstr, "%llu",
3228 				    (u_longlong_t)val64);
3229 				strval = valstr;
3230 			}
3231 			break;
3232 		case USFIELD_USED:
3233 		case USFIELD_QUOTA:
3234 			if (type == DATA_TYPE_UINT64) {
3235 				if (parsable) {
3236 					(void) sprintf(valstr, "%llu",
3237 					    (u_longlong_t)val64);
3238 					strval = valstr;
3239 				} else if (field == USFIELD_QUOTA &&
3240 				    val64 == 0) {
3241 					strval = "none";
3242 				} else {
3243 					zfs_nicebytes(val64, valstr,
3244 					    sizeof (valstr));
3245 					strval = valstr;
3246 				}
3247 			}
3248 			break;
3249 		case USFIELD_OBJUSED:
3250 		case USFIELD_OBJQUOTA:
3251 			if (type == DATA_TYPE_UINT64) {
3252 				if (parsable) {
3253 					(void) sprintf(valstr, "%llu",
3254 					    (u_longlong_t)val64);
3255 					strval = valstr;
3256 				} else if (field == USFIELD_OBJQUOTA &&
3257 				    val64 == 0) {
3258 					strval = "none";
3259 				} else {
3260 					zfs_nicenum(val64, valstr,
3261 					    sizeof (valstr));
3262 					strval = valstr;
3263 				}
3264 			}
3265 			break;
3266 		}
3267 
3268 		if (!first) {
3269 			if (scripted)
3270 				(void) putchar('\t');
3271 			else
3272 				(void) fputs("  ", stdout);
3273 		}
3274 		if (scripted)
3275 			(void) fputs(strval, stdout);
3276 		else if (field == USFIELD_TYPE || field == USFIELD_NAME)
3277 			(void) printf("%-*s", (int)width[field], strval);
3278 		else
3279 			(void) printf("%*s", (int)width[field], strval);
3280 
3281 		first = B_FALSE;
3282 		cfield++;
3283 	}
3284 
3285 	(void) putchar('\n');
3286 }
3287 
3288 static void
print_us(boolean_t scripted,boolean_t parsable,int * fields,int types,size_t * width,boolean_t rmnode,uu_avl_t * avl)3289 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
3290     size_t *width, boolean_t rmnode, uu_avl_t *avl)
3291 {
3292 	us_node_t *node;
3293 	const char *col;
3294 	int cfield = 0;
3295 	int field;
3296 
3297 	if (!scripted) {
3298 		boolean_t first = B_TRUE;
3299 
3300 		while ((field = fields[cfield]) != USFIELD_LAST) {
3301 			col = gettext(us_field_hdr[field]);
3302 			if (field == USFIELD_TYPE || field == USFIELD_NAME) {
3303 				(void) printf(first ? "%-*s" : "  %-*s",
3304 				    (int)width[field], col);
3305 			} else {
3306 				(void) printf(first ? "%*s" : "  %*s",
3307 				    (int)width[field], col);
3308 			}
3309 			first = B_FALSE;
3310 			cfield++;
3311 		}
3312 		(void) printf("\n");
3313 	}
3314 
3315 	for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
3316 		print_us_node(scripted, parsable, fields, types, width, node);
3317 		if (rmnode)
3318 			nvlist_free(node->usn_nvl);
3319 	}
3320 }
3321 
3322 static int
zfs_do_userspace(int argc,char ** argv)3323 zfs_do_userspace(int argc, char **argv)
3324 {
3325 	zfs_handle_t *zhp;
3326 	zfs_userquota_prop_t p;
3327 	uu_avl_pool_t *avl_pool;
3328 	uu_avl_t *avl_tree;
3329 	uu_avl_walk_t *walk;
3330 	char *delim;
3331 	char deffields[] = "type,name,used,quota,objused,objquota";
3332 	char *ofield = NULL;
3333 	char *tfield = NULL;
3334 	int cfield = 0;
3335 	int fields[256];
3336 	int i;
3337 	boolean_t scripted = B_FALSE;
3338 	boolean_t prtnum = B_FALSE;
3339 	boolean_t parsable = B_FALSE;
3340 	boolean_t sid2posix = B_FALSE;
3341 	int ret = 0;
3342 	int c;
3343 	zfs_sort_column_t *sortcol = NULL;
3344 	int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
3345 	us_cbdata_t cb;
3346 	us_node_t *node;
3347 	us_node_t *rmnode;
3348 	uu_list_pool_t *listpool;
3349 	uu_list_t *list;
3350 	uu_avl_index_t idx = 0;
3351 	uu_list_index_t idx2 = 0;
3352 
3353 	if (argc < 2)
3354 		usage(B_FALSE);
3355 
3356 	if (strcmp(argv[0], "groupspace") == 0) {
3357 		/* Toggle default group types */
3358 		types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
3359 	} else if (strcmp(argv[0], "projectspace") == 0) {
3360 		types = USTYPE_PROJ;
3361 		prtnum = B_TRUE;
3362 	}
3363 
3364 	while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
3365 		switch (c) {
3366 		case 'n':
3367 			if (types == USTYPE_PROJ) {
3368 				(void) fprintf(stderr,
3369 				    gettext("invalid option 'n'\n"));
3370 				usage(B_FALSE);
3371 			}
3372 			prtnum = B_TRUE;
3373 			break;
3374 		case 'H':
3375 			scripted = B_TRUE;
3376 			break;
3377 		case 'p':
3378 			parsable = B_TRUE;
3379 			break;
3380 		case 'o':
3381 			ofield = optarg;
3382 			break;
3383 		case 's':
3384 		case 'S':
3385 			if (zfs_add_sort_column(&sortcol, optarg,
3386 			    c == 's' ? B_FALSE : B_TRUE) != 0) {
3387 				(void) fprintf(stderr,
3388 				    gettext("invalid field '%s'\n"), optarg);
3389 				usage(B_FALSE);
3390 			}
3391 			break;
3392 		case 't':
3393 			if (types == USTYPE_PROJ) {
3394 				(void) fprintf(stderr,
3395 				    gettext("invalid option 't'\n"));
3396 				usage(B_FALSE);
3397 			}
3398 			tfield = optarg;
3399 			break;
3400 		case 'i':
3401 			if (types == USTYPE_PROJ) {
3402 				(void) fprintf(stderr,
3403 				    gettext("invalid option 'i'\n"));
3404 				usage(B_FALSE);
3405 			}
3406 			sid2posix = B_TRUE;
3407 			break;
3408 		case ':':
3409 			(void) fprintf(stderr, gettext("missing argument for "
3410 			    "'%c' option\n"), optopt);
3411 			usage(B_FALSE);
3412 			break;
3413 		case '?':
3414 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3415 			    optopt);
3416 			usage(B_FALSE);
3417 		}
3418 	}
3419 
3420 	argc -= optind;
3421 	argv += optind;
3422 
3423 	if (argc < 1) {
3424 		(void) fprintf(stderr, gettext("missing dataset name\n"));
3425 		usage(B_FALSE);
3426 	}
3427 	if (argc > 1) {
3428 		(void) fprintf(stderr, gettext("too many arguments\n"));
3429 		usage(B_FALSE);
3430 	}
3431 
3432 	/* Use default output fields if not specified using -o */
3433 	if (ofield == NULL)
3434 		ofield = deffields;
3435 	do {
3436 		if ((delim = strchr(ofield, ',')) != NULL)
3437 			*delim = '\0';
3438 		if ((fields[cfield++] = us_field_index(ofield)) == -1) {
3439 			(void) fprintf(stderr, gettext("invalid type '%s' "
3440 			    "for -o option\n"), ofield);
3441 			return (-1);
3442 		}
3443 		if (delim != NULL)
3444 			ofield = delim + 1;
3445 	} while (delim != NULL);
3446 	fields[cfield] = USFIELD_LAST;
3447 
3448 	/* Override output types (-t option) */
3449 	if (tfield != NULL) {
3450 		types = 0;
3451 
3452 		do {
3453 			boolean_t found = B_FALSE;
3454 
3455 			if ((delim = strchr(tfield, ',')) != NULL)
3456 				*delim = '\0';
3457 			for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
3458 			    i++) {
3459 				if (strcmp(tfield, us_type_names[i]) == 0) {
3460 					found = B_TRUE;
3461 					types |= us_type_bits[i];
3462 					break;
3463 				}
3464 			}
3465 			if (!found) {
3466 				(void) fprintf(stderr, gettext("invalid type "
3467 				    "'%s' for -t option\n"), tfield);
3468 				return (-1);
3469 			}
3470 			if (delim != NULL)
3471 				tfield = delim + 1;
3472 		} while (delim != NULL);
3473 	}
3474 
3475 	if ((zhp = zfs_path_to_zhandle(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM |
3476 	    ZFS_TYPE_SNAPSHOT)) == NULL)
3477 		return (1);
3478 	if (zfs_get_underlying_type(zhp) != ZFS_TYPE_FILESYSTEM) {
3479 		(void) fprintf(stderr, gettext("operation is only applicable "
3480 		    "to filesystems and their snapshots\n"));
3481 		zfs_close(zhp);
3482 		return (1);
3483 	}
3484 
3485 	if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
3486 	    offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
3487 		nomem();
3488 	if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
3489 		nomem();
3490 
3491 	/* Always add default sorting columns */
3492 	(void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
3493 	(void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
3494 
3495 	cb.cb_sortcol = sortcol;
3496 	cb.cb_numname = prtnum;
3497 	cb.cb_nicenum = !parsable;
3498 	cb.cb_avl_pool = avl_pool;
3499 	cb.cb_avl = avl_tree;
3500 	cb.cb_sid2posix = sid2posix;
3501 
3502 	for (i = 0; i < USFIELD_LAST; i++)
3503 		cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
3504 
3505 	for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
3506 		if ((zfs_prop_is_user(p) &&
3507 		    !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
3508 		    (zfs_prop_is_group(p) &&
3509 		    !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))) ||
3510 		    (zfs_prop_is_project(p) && types != USTYPE_PROJ))
3511 			continue;
3512 
3513 		cb.cb_prop = p;
3514 		if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0) {
3515 			zfs_close(zhp);
3516 			return (ret);
3517 		}
3518 	}
3519 	zfs_close(zhp);
3520 
3521 	/* Sort the list */
3522 	if ((node = uu_avl_first(avl_tree)) == NULL)
3523 		return (0);
3524 
3525 	us_populated = B_TRUE;
3526 
3527 	listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
3528 	    offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
3529 	list = uu_list_create(listpool, NULL, UU_DEFAULT);
3530 	uu_list_node_init(node, &node->usn_listnode, listpool);
3531 
3532 	while (node != NULL) {
3533 		rmnode = node;
3534 		node = uu_avl_next(avl_tree, node);
3535 		uu_avl_remove(avl_tree, rmnode);
3536 		if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
3537 			uu_list_insert(list, rmnode, idx2);
3538 	}
3539 
3540 	for (node = uu_list_first(list); node != NULL;
3541 	    node = uu_list_next(list, node)) {
3542 		us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
3543 
3544 		if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
3545 			uu_avl_insert(avl_tree, node, idx);
3546 	}
3547 
3548 	uu_list_destroy(list);
3549 	uu_list_pool_destroy(listpool);
3550 
3551 	/* Print and free node nvlist memory */
3552 	print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
3553 	    cb.cb_avl);
3554 
3555 	zfs_free_sort_columns(sortcol);
3556 
3557 	/* Clean up the AVL tree */
3558 	if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
3559 		nomem();
3560 
3561 	while ((node = uu_avl_walk_next(walk)) != NULL) {
3562 		uu_avl_remove(cb.cb_avl, node);
3563 		free(node);
3564 	}
3565 
3566 	uu_avl_walk_end(walk);
3567 	uu_avl_destroy(avl_tree);
3568 	uu_avl_pool_destroy(avl_pool);
3569 
3570 	return (ret);
3571 }
3572 
3573 /*
3574  * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property]
3575  *      [-t type[,...]] [filesystem|volume|snapshot] ...
3576  *
3577  *	-H	Scripted mode; elide headers and separate columns by tabs
3578  *	-p	Display values in parsable (literal) format.
3579  *	-r	Recurse over all children
3580  *	-d	Limit recursion by depth.
3581  *	-o	Control which fields to display.
3582  *	-s	Specify sort columns, descending order.
3583  *	-S	Specify sort columns, ascending order.
3584  *	-t	Control which object types to display.
3585  *
3586  * When given no arguments, list all filesystems in the system.
3587  * Otherwise, list the specified datasets, optionally recursing down them if
3588  * '-r' is specified.
3589  */
3590 typedef struct list_cbdata {
3591 	boolean_t	cb_first;
3592 	boolean_t	cb_literal;
3593 	boolean_t	cb_scripted;
3594 	zprop_list_t	*cb_proplist;
3595 	boolean_t	cb_json;
3596 	nvlist_t	*cb_jsobj;
3597 	boolean_t	cb_json_as_int;
3598 } list_cbdata_t;
3599 
3600 /*
3601  * Given a list of columns to display, output appropriate headers for each one.
3602  */
3603 static void
print_header(list_cbdata_t * cb)3604 print_header(list_cbdata_t *cb)
3605 {
3606 	zprop_list_t *pl = cb->cb_proplist;
3607 	char headerbuf[ZFS_MAXPROPLEN];
3608 	const char *header;
3609 	int i;
3610 	boolean_t first = B_TRUE;
3611 	boolean_t right_justify;
3612 
3613 	color_start(ANSI_BOLD);
3614 
3615 	for (; pl != NULL; pl = pl->pl_next) {
3616 		if (!first) {
3617 			(void) printf("  ");
3618 		} else {
3619 			first = B_FALSE;
3620 		}
3621 
3622 		right_justify = B_FALSE;
3623 		if (pl->pl_prop != ZPROP_USERPROP) {
3624 			header = zfs_prop_column_name(pl->pl_prop);
3625 			right_justify = zfs_prop_align_right(pl->pl_prop);
3626 		} else {
3627 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
3628 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
3629 			headerbuf[i] = '\0';
3630 			header = headerbuf;
3631 		}
3632 
3633 		if (pl->pl_next == NULL && !right_justify)
3634 			(void) printf("%s", header);
3635 		else if (right_justify)
3636 			(void) printf("%*s", (int)pl->pl_width, header);
3637 		else
3638 			(void) printf("%-*s", (int)pl->pl_width, header);
3639 	}
3640 
3641 	color_end();
3642 
3643 	(void) printf("\n");
3644 }
3645 
3646 /*
3647  * Decides on the color that the avail value should be printed in.
3648  * > 80% used = yellow
3649  * > 90% used = red
3650  */
3651 static const char *
zfs_list_avail_color(zfs_handle_t * zhp)3652 zfs_list_avail_color(zfs_handle_t *zhp)
3653 {
3654 	uint64_t used = zfs_prop_get_int(zhp, ZFS_PROP_USED);
3655 	uint64_t avail = zfs_prop_get_int(zhp, ZFS_PROP_AVAILABLE);
3656 	int percentage = (int)((double)avail / MAX(avail + used, 1) * 100);
3657 
3658 	if (percentage > 20)
3659 		return (NULL);
3660 	else if (percentage > 10)
3661 		return (ANSI_YELLOW);
3662 	else
3663 		return (ANSI_RED);
3664 }
3665 
3666 /*
3667  * Given a dataset and a list of fields, print out all the properties according
3668  * to the described layout, or return an nvlist containing all the fields, later
3669  * to be printed out as JSON object.
3670  */
3671 static void
collect_dataset(zfs_handle_t * zhp,list_cbdata_t * cb)3672 collect_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
3673 {
3674 	zprop_list_t *pl = cb->cb_proplist;
3675 	boolean_t first = B_TRUE;
3676 	char property[ZFS_MAXPROPLEN];
3677 	nvlist_t *userprops = zfs_get_user_props(zhp);
3678 	nvlist_t *propval;
3679 	const char *propstr;
3680 	boolean_t right_justify;
3681 	nvlist_t *item, *d, *props;
3682 	item = d = props = NULL;
3683 	zprop_source_t sourcetype = ZPROP_SRC_NONE;
3684 	char source[ZFS_MAX_DATASET_NAME_LEN];
3685 	if (cb->cb_json) {
3686 		d = fnvlist_lookup_nvlist(cb->cb_jsobj, "datasets");
3687 		if (d == NULL) {
3688 			fprintf(stderr, "datasets obj not found.\n");
3689 			exit(1);
3690 		}
3691 		item = fnvlist_alloc();
3692 		props = fnvlist_alloc();
3693 		fill_dataset_info(item, zhp, cb->cb_json_as_int);
3694 	}
3695 
3696 	for (; pl != NULL; pl = pl->pl_next) {
3697 		if (!cb->cb_json && !first) {
3698 			if (cb->cb_scripted)
3699 				(void) putchar('\t');
3700 			else
3701 				(void) fputs("  ", stdout);
3702 		} else {
3703 			first = B_FALSE;
3704 		}
3705 
3706 		if (pl->pl_prop == ZFS_PROP_NAME) {
3707 			(void) strlcpy(property, zfs_get_name(zhp),
3708 			    sizeof (property));
3709 			propstr = property;
3710 			right_justify = zfs_prop_align_right(pl->pl_prop);
3711 		} else if (pl->pl_prop != ZPROP_USERPROP) {
3712 			if (zfs_prop_get(zhp, pl->pl_prop, property,
3713 			    sizeof (property), &sourcetype, source,
3714 			    sizeof (source), cb->cb_literal) != 0)
3715 				propstr = "-";
3716 			else
3717 				propstr = property;
3718 			right_justify = zfs_prop_align_right(pl->pl_prop);
3719 		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
3720 			sourcetype = ZPROP_SRC_LOCAL;
3721 			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3722 			    property, sizeof (property), cb->cb_literal) != 0) {
3723 				sourcetype = ZPROP_SRC_NONE;
3724 				propstr = "-";
3725 			} else {
3726 				propstr = property;
3727 			}
3728 			right_justify = B_TRUE;
3729 		} else if (zfs_prop_written(pl->pl_user_prop)) {
3730 			sourcetype = ZPROP_SRC_LOCAL;
3731 			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3732 			    property, sizeof (property), cb->cb_literal) != 0) {
3733 				sourcetype = ZPROP_SRC_NONE;
3734 				propstr = "-";
3735 			} else {
3736 				propstr = property;
3737 			}
3738 			right_justify = B_TRUE;
3739 		} else {
3740 			if (nvlist_lookup_nvlist(userprops,
3741 			    pl->pl_user_prop, &propval) != 0) {
3742 				propstr = "-";
3743 			} else {
3744 				propstr = fnvlist_lookup_string(propval,
3745 				    ZPROP_VALUE);
3746 				strlcpy(source,
3747 				    fnvlist_lookup_string(propval,
3748 				    ZPROP_SOURCE), ZFS_MAX_DATASET_NAME_LEN);
3749 				if (strcmp(source,
3750 				    zfs_get_name(zhp)) == 0) {
3751 					sourcetype = ZPROP_SRC_LOCAL;
3752 				} else if (strcmp(source,
3753 				    ZPROP_SOURCE_VAL_RECVD) == 0) {
3754 					sourcetype = ZPROP_SRC_RECEIVED;
3755 				} else {
3756 					sourcetype = ZPROP_SRC_INHERITED;
3757 				}
3758 			}
3759 			right_justify = B_FALSE;
3760 		}
3761 
3762 		if (cb->cb_json) {
3763 			if (pl->pl_prop == ZFS_PROP_NAME)
3764 				continue;
3765 			const char *prop_name;
3766 			if (pl->pl_prop != ZPROP_USERPROP)
3767 				prop_name = zfs_prop_to_name(pl->pl_prop);
3768 			else
3769 				prop_name = pl->pl_user_prop;
3770 			if (zprop_nvlist_one_property(
3771 			    prop_name, propstr,
3772 			    sourcetype, source, NULL, props,
3773 			    cb->cb_json_as_int) != 0)
3774 				nomem();
3775 		} else {
3776 			/*
3777 			 * zfs_list_avail_color() needs
3778 			 * ZFS_PROP_AVAILABLE + USED, so we need another
3779 			 * for() search for the USED part when no colors
3780 			 * wanted, we can skip the whole thing
3781 			 */
3782 			if (use_color() && pl->pl_prop == ZFS_PROP_AVAILABLE) {
3783 				zprop_list_t *pl2 = cb->cb_proplist;
3784 				for (; pl2 != NULL; pl2 = pl2->pl_next) {
3785 					if (pl2->pl_prop == ZFS_PROP_USED) {
3786 						color_start(
3787 						    zfs_list_avail_color(zhp));
3788 						/*
3789 						 * found it, no need for more
3790 						 * loops
3791 						 */
3792 						break;
3793 					}
3794 				}
3795 			}
3796 
3797 			/*
3798 			 * If this is being called in scripted mode, or if
3799 			 * this is the last column and it is left-justified,
3800 			 * don't include a width format specifier.
3801 			 */
3802 			if (cb->cb_scripted || (pl->pl_next == NULL &&
3803 			    !right_justify))
3804 				(void) fputs(propstr, stdout);
3805 			else if (right_justify) {
3806 				(void) printf("%*s", (int)pl->pl_width,
3807 				    propstr);
3808 			} else {
3809 				(void) printf("%-*s", (int)pl->pl_width,
3810 				    propstr);
3811 			}
3812 
3813 			if (pl->pl_prop == ZFS_PROP_AVAILABLE)
3814 				color_end();
3815 		}
3816 	}
3817 	if (cb->cb_json) {
3818 		fnvlist_add_nvlist(item, "properties", props);
3819 		fnvlist_add_nvlist(d, zfs_get_name(zhp), item);
3820 		fnvlist_free(props);
3821 		fnvlist_free(item);
3822 	} else
3823 		(void) putchar('\n');
3824 }
3825 
3826 /*
3827  * Generic callback function to list a dataset or snapshot.
3828  */
3829 static int
list_callback(zfs_handle_t * zhp,void * data)3830 list_callback(zfs_handle_t *zhp, void *data)
3831 {
3832 	list_cbdata_t *cbp = data;
3833 
3834 	if (cbp->cb_first) {
3835 		if (!cbp->cb_scripted && !cbp->cb_json)
3836 			print_header(cbp);
3837 		cbp->cb_first = B_FALSE;
3838 	}
3839 
3840 	collect_dataset(zhp, cbp);
3841 
3842 	return (0);
3843 }
3844 
3845 static int
zfs_do_list(int argc,char ** argv)3846 zfs_do_list(int argc, char **argv)
3847 {
3848 	int c;
3849 	char default_fields[] =
3850 	    "name,used,available,referenced,mountpoint";
3851 	int types = ZFS_TYPE_DATASET;
3852 	boolean_t types_specified = B_FALSE;
3853 	char *fields = default_fields;
3854 	list_cbdata_t cb = { 0 };
3855 	int limit = 0;
3856 	int ret = 0;
3857 	zfs_sort_column_t *sortcol = NULL;
3858 	int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3859 	nvlist_t *data = NULL;
3860 
3861 	struct option long_options[] = {
3862 		{"json", no_argument, NULL, 'j'},
3863 		{"json-int", no_argument, NULL, ZFS_OPTION_JSON_NUMS_AS_INT},
3864 		{0, 0, 0, 0}
3865 	};
3866 
3867 	/* check options */
3868 	while ((c = getopt_long(argc, argv, "jHS:d:o:prs:t:", long_options,
3869 	    NULL)) != -1) {
3870 		switch (c) {
3871 		case 'o':
3872 			fields = optarg;
3873 			break;
3874 		case 'p':
3875 			cb.cb_literal = B_TRUE;
3876 			flags |= ZFS_ITER_LITERAL_PROPS;
3877 			break;
3878 		case 'd':
3879 			limit = parse_depth(optarg, &flags);
3880 			break;
3881 		case 'r':
3882 			flags |= ZFS_ITER_RECURSE;
3883 			break;
3884 		case 'j':
3885 			cb.cb_json = B_TRUE;
3886 			cb.cb_jsobj = zfs_json_schema(0, 1);
3887 			data = fnvlist_alloc();
3888 			fnvlist_add_nvlist(cb.cb_jsobj, "datasets", data);
3889 			fnvlist_free(data);
3890 			break;
3891 		case ZFS_OPTION_JSON_NUMS_AS_INT:
3892 			cb.cb_json_as_int = B_TRUE;
3893 			cb.cb_literal = B_TRUE;
3894 			break;
3895 		case 'H':
3896 			cb.cb_scripted = B_TRUE;
3897 			break;
3898 		case 's':
3899 			if (zfs_add_sort_column(&sortcol, optarg,
3900 			    B_FALSE) != 0) {
3901 				(void) fprintf(stderr,
3902 				    gettext("invalid property '%s'\n"), optarg);
3903 				usage(B_FALSE);
3904 			}
3905 			break;
3906 		case 'S':
3907 			if (zfs_add_sort_column(&sortcol, optarg,
3908 			    B_TRUE) != 0) {
3909 				(void) fprintf(stderr,
3910 				    gettext("invalid property '%s'\n"), optarg);
3911 				usage(B_FALSE);
3912 			}
3913 			break;
3914 		case 't':
3915 			types = 0;
3916 			types_specified = B_TRUE;
3917 			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3918 
3919 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
3920 				static const char *const type_subopts[] = {
3921 					"filesystem",
3922 					"fs",
3923 					"volume",
3924 					"vol",
3925 					"snapshot",
3926 					"snap",
3927 					"bookmark",
3928 					"all"
3929 				};
3930 				static const int type_types[] = {
3931 					ZFS_TYPE_FILESYSTEM,
3932 					ZFS_TYPE_FILESYSTEM,
3933 					ZFS_TYPE_VOLUME,
3934 					ZFS_TYPE_VOLUME,
3935 					ZFS_TYPE_SNAPSHOT,
3936 					ZFS_TYPE_SNAPSHOT,
3937 					ZFS_TYPE_BOOKMARK,
3938 					ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK
3939 				};
3940 
3941 				for (c = 0; c < ARRAY_SIZE(type_subopts); ++c)
3942 					if (strcmp(tok, type_subopts[c]) == 0) {
3943 						types |= type_types[c];
3944 						goto found3;
3945 					}
3946 
3947 				(void) fprintf(stderr,
3948 				    gettext("invalid type '%s'\n"), tok);
3949 				usage(B_FALSE);
3950 found3:;
3951 			}
3952 			break;
3953 		case ':':
3954 			(void) fprintf(stderr, gettext("missing argument for "
3955 			    "'%c' option\n"), optopt);
3956 			usage(B_FALSE);
3957 			break;
3958 		case '?':
3959 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3960 			    optopt);
3961 			usage(B_FALSE);
3962 		}
3963 	}
3964 
3965 	argc -= optind;
3966 	argv += optind;
3967 
3968 	if (!cb.cb_json && cb.cb_json_as_int) {
3969 		(void) fprintf(stderr, gettext("'--json-int' only works with"
3970 		    " '-j' option\n"));
3971 		usage(B_FALSE);
3972 	}
3973 
3974 	/*
3975 	 * If "-o space" and no types were specified, don't display snapshots.
3976 	 */
3977 	if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3978 		types &= ~ZFS_TYPE_SNAPSHOT;
3979 
3980 	/*
3981 	 * Handle users who want to list all snapshots or bookmarks
3982 	 * of the current dataset (ex. 'zfs list -t snapshot <dataset>').
3983 	 */
3984 	if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
3985 	    argc > 0 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
3986 		flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
3987 		limit = 1;
3988 	}
3989 
3990 	/*
3991 	 * If the user specifies '-o all', the zprop_get_list() doesn't
3992 	 * normally include the name of the dataset.  For 'zfs list', we always
3993 	 * want this property to be first.
3994 	 */
3995 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3996 	    != 0)
3997 		usage(B_FALSE);
3998 
3999 	cb.cb_first = B_TRUE;
4000 
4001 	/*
4002 	 * If we are only going to list and sort by properties that are "fast"
4003 	 * then we can use "simple" mode and avoid populating the properties
4004 	 * nvlist.
4005 	 */
4006 	if (zfs_list_only_by_fast(cb.cb_proplist) &&
4007 	    zfs_sort_only_by_fast(sortcol))
4008 		flags |= ZFS_ITER_SIMPLE;
4009 
4010 	ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
4011 	    limit, list_callback, &cb);
4012 
4013 	if (ret == 0 && cb.cb_json)
4014 		zcmd_print_json(cb.cb_jsobj);
4015 	else if (ret != 0 && cb.cb_json)
4016 		nvlist_free(cb.cb_jsobj);
4017 
4018 	zprop_free_list(cb.cb_proplist);
4019 	zfs_free_sort_columns(sortcol);
4020 
4021 	if (ret == 0 && cb.cb_first && !cb.cb_scripted)
4022 		(void) fprintf(stderr, gettext("no datasets available\n"));
4023 
4024 	return (ret);
4025 }
4026 
4027 /*
4028  * zfs rename [-fu] <fs | snap | vol> <fs | snap | vol>
4029  * zfs rename [-f] -p <fs | vol> <fs | vol>
4030  * zfs rename [-u] -r <snap> <snap>
4031  *
4032  * Renames the given dataset to another of the same type.
4033  *
4034  * The '-p' flag creates all the non-existing ancestors of the target first.
4035  * The '-u' flag prevents file systems from being remounted during rename.
4036  */
4037 static int
zfs_do_rename(int argc,char ** argv)4038 zfs_do_rename(int argc, char **argv)
4039 {
4040 	zfs_handle_t *zhp;
4041 	renameflags_t flags = { 0 };
4042 	int c;
4043 	int ret = 0;
4044 	int types;
4045 	boolean_t parents = B_FALSE;
4046 
4047 	/* check options */
4048 	while ((c = getopt(argc, argv, "pruf")) != -1) {
4049 		switch (c) {
4050 		case 'p':
4051 			parents = B_TRUE;
4052 			break;
4053 		case 'r':
4054 			flags.recursive = B_TRUE;
4055 			break;
4056 		case 'u':
4057 			flags.nounmount = B_TRUE;
4058 			break;
4059 		case 'f':
4060 			flags.forceunmount = B_TRUE;
4061 			break;
4062 		case '?':
4063 		default:
4064 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4065 			    optopt);
4066 			usage(B_FALSE);
4067 		}
4068 	}
4069 
4070 	argc -= optind;
4071 	argv += optind;
4072 
4073 	/* check number of arguments */
4074 	if (argc < 1) {
4075 		(void) fprintf(stderr, gettext("missing source dataset "
4076 		    "argument\n"));
4077 		usage(B_FALSE);
4078 	}
4079 	if (argc < 2) {
4080 		(void) fprintf(stderr, gettext("missing target dataset "
4081 		    "argument\n"));
4082 		usage(B_FALSE);
4083 	}
4084 	if (argc > 2) {
4085 		(void) fprintf(stderr, gettext("too many arguments\n"));
4086 		usage(B_FALSE);
4087 	}
4088 
4089 	if (flags.recursive && parents) {
4090 		(void) fprintf(stderr, gettext("-p and -r options are mutually "
4091 		    "exclusive\n"));
4092 		usage(B_FALSE);
4093 	}
4094 
4095 	if (flags.nounmount && parents) {
4096 		(void) fprintf(stderr, gettext("-u and -p options are mutually "
4097 		    "exclusive\n"));
4098 		usage(B_FALSE);
4099 	}
4100 
4101 	if (flags.recursive && strchr(argv[0], '@') == 0) {
4102 		(void) fprintf(stderr, gettext("source dataset for recursive "
4103 		    "rename must be a snapshot\n"));
4104 		usage(B_FALSE);
4105 	}
4106 
4107 	if (flags.nounmount)
4108 		types = ZFS_TYPE_FILESYSTEM;
4109 	else if (parents)
4110 		types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
4111 	else
4112 		types = ZFS_TYPE_DATASET;
4113 
4114 	if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
4115 		return (1);
4116 
4117 	/* If we were asked and the name looks good, try to create ancestors. */
4118 	if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
4119 	    zfs_create_ancestors(g_zfs, argv[1]) != 0) {
4120 		zfs_close(zhp);
4121 		return (1);
4122 	}
4123 
4124 	ret = (zfs_rename(zhp, argv[1], flags) != 0);
4125 
4126 	zfs_close(zhp);
4127 	return (ret);
4128 }
4129 
4130 /*
4131  * zfs promote <fs>
4132  *
4133  * Promotes the given clone fs to be the parent
4134  */
4135 static int
zfs_do_promote(int argc,char ** argv)4136 zfs_do_promote(int argc, char **argv)
4137 {
4138 	zfs_handle_t *zhp;
4139 	int ret = 0;
4140 
4141 	/* check options */
4142 	if (argc > 1 && argv[1][0] == '-') {
4143 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4144 		    argv[1][1]);
4145 		usage(B_FALSE);
4146 	}
4147 
4148 	/* check number of arguments */
4149 	if (argc < 2) {
4150 		(void) fprintf(stderr, gettext("missing clone filesystem"
4151 		    " argument\n"));
4152 		usage(B_FALSE);
4153 	}
4154 	if (argc > 2) {
4155 		(void) fprintf(stderr, gettext("too many arguments\n"));
4156 		usage(B_FALSE);
4157 	}
4158 
4159 	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4160 	if (zhp == NULL)
4161 		return (1);
4162 
4163 	ret = (zfs_promote(zhp) != 0);
4164 
4165 
4166 	zfs_close(zhp);
4167 	return (ret);
4168 }
4169 
4170 static int
zfs_do_redact(int argc,char ** argv)4171 zfs_do_redact(int argc, char **argv)
4172 {
4173 	char *snap = NULL;
4174 	char *bookname = NULL;
4175 	char **rsnaps = NULL;
4176 	int numrsnaps = 0;
4177 	argv++;
4178 	argc--;
4179 	if (argc < 3) {
4180 		(void) fprintf(stderr, gettext("too few arguments\n"));
4181 		usage(B_FALSE);
4182 	}
4183 
4184 	snap = argv[0];
4185 	bookname = argv[1];
4186 	rsnaps = argv + 2;
4187 	numrsnaps = argc - 2;
4188 
4189 	nvlist_t *rsnapnv = fnvlist_alloc();
4190 
4191 	for (int i = 0; i < numrsnaps; i++) {
4192 		fnvlist_add_boolean(rsnapnv, rsnaps[i]);
4193 	}
4194 
4195 	int err = lzc_redact(snap, bookname, rsnapnv);
4196 	fnvlist_free(rsnapnv);
4197 
4198 	switch (err) {
4199 	case 0:
4200 		break;
4201 	case ENOENT: {
4202 		zfs_handle_t *zhp = zfs_open(g_zfs, snap, ZFS_TYPE_SNAPSHOT);
4203 		if (zhp == NULL) {
4204 			(void) fprintf(stderr, gettext("provided snapshot %s "
4205 			    "does not exist\n"), snap);
4206 		} else {
4207 			zfs_close(zhp);
4208 		}
4209 		for (int i = 0; i < numrsnaps; i++) {
4210 			zhp = zfs_open(g_zfs, rsnaps[i], ZFS_TYPE_SNAPSHOT);
4211 			if (zhp == NULL) {
4212 				(void) fprintf(stderr, gettext("provided "
4213 				    "snapshot %s does not exist\n"), rsnaps[i]);
4214 			} else {
4215 				zfs_close(zhp);
4216 			}
4217 		}
4218 		break;
4219 	}
4220 	case EEXIST:
4221 		(void) fprintf(stderr, gettext("specified redaction bookmark "
4222 		    "(%s) provided already exists\n"), bookname);
4223 		break;
4224 	case ENAMETOOLONG:
4225 		(void) fprintf(stderr, gettext("provided bookmark name cannot "
4226 		    "be used, final name would be too long\n"));
4227 		break;
4228 	case E2BIG:
4229 		(void) fprintf(stderr, gettext("too many redaction snapshots "
4230 		    "specified\n"));
4231 		break;
4232 	case EINVAL:
4233 		if (strchr(bookname, '#') != NULL)
4234 			(void) fprintf(stderr, gettext(
4235 			    "redaction bookmark name must not contain '#'\n"));
4236 		else
4237 			(void) fprintf(stderr, gettext(
4238 			    "redaction snapshot must be descendent of "
4239 			    "snapshot being redacted\n"));
4240 		break;
4241 	case EALREADY:
4242 		(void) fprintf(stderr, gettext("attempted to redact redacted "
4243 		    "dataset or with respect to redacted dataset\n"));
4244 		break;
4245 	case ENOTSUP:
4246 		(void) fprintf(stderr, gettext("redaction bookmarks feature "
4247 		    "not enabled\n"));
4248 		break;
4249 	case EXDEV:
4250 		(void) fprintf(stderr, gettext("potentially invalid redaction "
4251 		    "snapshot; full dataset names required\n"));
4252 		break;
4253 	case ESRCH:
4254 		(void) fprintf(stderr, gettext("attempted to resume redaction "
4255 		    " with a mismatched redaction list\n"));
4256 		break;
4257 	default:
4258 		(void) fprintf(stderr, gettext("internal error: %s\n"),
4259 		    strerror(errno));
4260 	}
4261 
4262 	return (err);
4263 }
4264 
4265 /*
4266  * zfs rollback [-rRf] <snapshot>
4267  *
4268  *	-r	Delete any intervening snapshots before doing rollback
4269  *	-R	Delete any snapshots and their clones
4270  *	-f	ignored for backwards compatibility
4271  *
4272  * Given a filesystem, rollback to a specific snapshot, discarding any changes
4273  * since then and making it the active dataset.  If more recent snapshots exist,
4274  * the command will complain unless the '-r' flag is given.
4275  */
4276 typedef struct rollback_cbdata {
4277 	uint64_t	cb_create;
4278 	uint8_t		cb_younger_ds_printed;
4279 	boolean_t	cb_first;
4280 	int		cb_doclones;
4281 	char		*cb_target;
4282 	int		cb_error;
4283 	boolean_t	cb_recurse;
4284 } rollback_cbdata_t;
4285 
4286 static int
rollback_check_dependent(zfs_handle_t * zhp,void * data)4287 rollback_check_dependent(zfs_handle_t *zhp, void *data)
4288 {
4289 	rollback_cbdata_t *cbp = data;
4290 
4291 	if (cbp->cb_first && cbp->cb_recurse) {
4292 		(void) fprintf(stderr, gettext("cannot rollback to "
4293 		    "'%s': clones of previous snapshots exist\n"),
4294 		    cbp->cb_target);
4295 		(void) fprintf(stderr, gettext("use '-R' to "
4296 		    "force deletion of the following clones and "
4297 		    "dependents:\n"));
4298 		cbp->cb_first = 0;
4299 		cbp->cb_error = 1;
4300 	}
4301 
4302 	(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
4303 
4304 	zfs_close(zhp);
4305 	return (0);
4306 }
4307 
4308 
4309 /*
4310  * Report some snapshots/bookmarks more recent than the one specified.
4311  * Used when '-r' is not specified. We reuse this same callback for the
4312  * snapshot dependents - if 'cb_dependent' is set, then this is a
4313  * dependent and we should report it without checking the transaction group.
4314  */
4315 static int
rollback_check(zfs_handle_t * zhp,void * data)4316 rollback_check(zfs_handle_t *zhp, void *data)
4317 {
4318 	rollback_cbdata_t *cbp = data;
4319 	/*
4320 	 * Max number of younger snapshots and/or bookmarks to display before
4321 	 * we stop the iteration.
4322 	 */
4323 	const uint8_t max_younger = 32;
4324 
4325 	if (cbp->cb_doclones) {
4326 		zfs_close(zhp);
4327 		return (0);
4328 	}
4329 
4330 	if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
4331 		if (cbp->cb_first && !cbp->cb_recurse) {
4332 			(void) fprintf(stderr, gettext("cannot "
4333 			    "rollback to '%s': more recent snapshots "
4334 			    "or bookmarks exist\n"),
4335 			    cbp->cb_target);
4336 			(void) fprintf(stderr, gettext("use '-r' to "
4337 			    "force deletion of the following "
4338 			    "snapshots and bookmarks:\n"));
4339 			cbp->cb_first = 0;
4340 			cbp->cb_error = 1;
4341 		}
4342 
4343 		if (cbp->cb_recurse) {
4344 			if (zfs_iter_dependents_v2(zhp, 0, B_TRUE,
4345 			    rollback_check_dependent, cbp) != 0) {
4346 				zfs_close(zhp);
4347 				return (-1);
4348 			}
4349 		} else {
4350 			(void) fprintf(stderr, "%s\n",
4351 			    zfs_get_name(zhp));
4352 			cbp->cb_younger_ds_printed++;
4353 		}
4354 	}
4355 	zfs_close(zhp);
4356 
4357 	if (cbp->cb_younger_ds_printed == max_younger) {
4358 		/*
4359 		 * This non-recursive rollback is going to fail due to the
4360 		 * presence of snapshots and/or bookmarks that are younger than
4361 		 * the rollback target.
4362 		 * We printed some of the offending objects, now we stop
4363 		 * zfs_iter_snapshot/bookmark iteration so we can fail fast and
4364 		 * avoid iterating over the rest of the younger objects
4365 		 */
4366 		(void) fprintf(stderr, gettext("Output limited to %d "
4367 		    "snapshots/bookmarks\n"), max_younger);
4368 		return (-1);
4369 	}
4370 	return (0);
4371 }
4372 
4373 static int
zfs_do_rollback(int argc,char ** argv)4374 zfs_do_rollback(int argc, char **argv)
4375 {
4376 	int ret = 0;
4377 	int c;
4378 	boolean_t force = B_FALSE;
4379 	rollback_cbdata_t cb = { 0 };
4380 	zfs_handle_t *zhp, *snap;
4381 	char parentname[ZFS_MAX_DATASET_NAME_LEN];
4382 	char *delim;
4383 	uint64_t min_txg = 0;
4384 
4385 	/* check options */
4386 	while ((c = getopt(argc, argv, "rRf")) != -1) {
4387 		switch (c) {
4388 		case 'r':
4389 			cb.cb_recurse = 1;
4390 			break;
4391 		case 'R':
4392 			cb.cb_recurse = 1;
4393 			cb.cb_doclones = 1;
4394 			break;
4395 		case 'f':
4396 			force = B_TRUE;
4397 			break;
4398 		case '?':
4399 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4400 			    optopt);
4401 			usage(B_FALSE);
4402 		}
4403 	}
4404 
4405 	argc -= optind;
4406 	argv += optind;
4407 
4408 	/* check number of arguments */
4409 	if (argc < 1) {
4410 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
4411 		usage(B_FALSE);
4412 	}
4413 	if (argc > 1) {
4414 		(void) fprintf(stderr, gettext("too many arguments\n"));
4415 		usage(B_FALSE);
4416 	}
4417 
4418 	/* open the snapshot */
4419 	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
4420 		return (1);
4421 
4422 	/* open the parent dataset */
4423 	(void) strlcpy(parentname, argv[0], sizeof (parentname));
4424 	verify((delim = strrchr(parentname, '@')) != NULL);
4425 	*delim = '\0';
4426 	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
4427 		zfs_close(snap);
4428 		return (1);
4429 	}
4430 
4431 	/*
4432 	 * Check for more recent snapshots and/or clones based on the presence
4433 	 * of '-r' and '-R'.
4434 	 */
4435 	cb.cb_target = argv[0];
4436 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4437 	cb.cb_first = B_TRUE;
4438 	cb.cb_error = 0;
4439 
4440 	if (cb.cb_create > 0)
4441 		min_txg = cb.cb_create;
4442 
4443 	if ((ret = zfs_iter_snapshots_v2(zhp, 0, rollback_check, &cb,
4444 	    min_txg, 0)) != 0)
4445 		goto out;
4446 	if ((ret = zfs_iter_bookmarks_v2(zhp, 0, rollback_check, &cb)) != 0)
4447 		goto out;
4448 
4449 	if ((ret = cb.cb_error) != 0)
4450 		goto out;
4451 
4452 	/*
4453 	 * Rollback parent to the given snapshot.
4454 	 */
4455 	ret = zfs_rollback(zhp, snap, force);
4456 
4457 out:
4458 	zfs_close(snap);
4459 	zfs_close(zhp);
4460 
4461 	if (ret == 0)
4462 		return (0);
4463 	else
4464 		return (1);
4465 }
4466 
4467 /*
4468  * zfs set property=value ... { fs | snap | vol } ...
4469  *
4470  * Sets the given properties for all datasets specified on the command line.
4471  */
4472 
4473 static int
set_callback(zfs_handle_t * zhp,void * data)4474 set_callback(zfs_handle_t *zhp, void *data)
4475 {
4476 	zprop_set_cbdata_t *cb = data;
4477 	int ret = zfs_prop_set_list_flags(zhp, cb->cb_proplist, cb->cb_flags);
4478 
4479 	if (ret != 0 || libzfs_errno(g_zfs) != EZFS_SUCCESS) {
4480 		switch (libzfs_errno(g_zfs)) {
4481 		case EZFS_MOUNTFAILED:
4482 			(void) fprintf(stderr, gettext("property may be set "
4483 			    "but unable to remount filesystem\n"));
4484 			break;
4485 		case EZFS_SHARENFSFAILED:
4486 			(void) fprintf(stderr, gettext("property may be set "
4487 			    "but unable to reshare filesystem\n"));
4488 			break;
4489 		}
4490 	}
4491 	return (ret);
4492 }
4493 
4494 static int
zfs_do_set(int argc,char ** argv)4495 zfs_do_set(int argc, char **argv)
4496 {
4497 	zprop_set_cbdata_t cb = { 0 };
4498 	int ds_start = -1; /* argv idx of first dataset arg */
4499 	int ret = 0;
4500 	int i, c;
4501 
4502 	/* check options */
4503 	while ((c = getopt(argc, argv, "u")) != -1) {
4504 		switch (c) {
4505 		case 'u':
4506 			cb.cb_flags |= ZFS_SET_NOMOUNT;
4507 			break;
4508 		case '?':
4509 		default:
4510 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4511 			    optopt);
4512 			usage(B_FALSE);
4513 		}
4514 	}
4515 
4516 	argc -= optind;
4517 	argv += optind;
4518 
4519 	/* check number of arguments */
4520 	if (argc < 1) {
4521 		(void) fprintf(stderr, gettext("missing arguments\n"));
4522 		usage(B_FALSE);
4523 	}
4524 	if (argc < 2) {
4525 		if (strchr(argv[0], '=') == NULL) {
4526 			(void) fprintf(stderr, gettext("missing property=value "
4527 			    "argument(s)\n"));
4528 		} else {
4529 			(void) fprintf(stderr, gettext("missing dataset "
4530 			    "name(s)\n"));
4531 		}
4532 		usage(B_FALSE);
4533 	}
4534 
4535 	/* validate argument order:  prop=val args followed by dataset args */
4536 	for (i = 0; i < argc; i++) {
4537 		if (strchr(argv[i], '=') != NULL) {
4538 			if (ds_start > 0) {
4539 				/* out-of-order prop=val argument */
4540 				(void) fprintf(stderr, gettext("invalid "
4541 				    "argument order\n"));
4542 				usage(B_FALSE);
4543 			}
4544 		} else if (ds_start < 0) {
4545 			ds_start = i;
4546 		}
4547 	}
4548 	if (ds_start < 0) {
4549 		(void) fprintf(stderr, gettext("missing dataset name(s)\n"));
4550 		usage(B_FALSE);
4551 	}
4552 
4553 	/* Populate a list of property settings */
4554 	if (nvlist_alloc(&cb.cb_proplist, NV_UNIQUE_NAME, 0) != 0)
4555 		nomem();
4556 	for (i = 0; i < ds_start; i++) {
4557 		if (!parseprop(cb.cb_proplist, argv[i])) {
4558 			ret = -1;
4559 			goto error;
4560 		}
4561 	}
4562 
4563 	ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
4564 	    ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
4565 
4566 error:
4567 	nvlist_free(cb.cb_proplist);
4568 	return (ret);
4569 }
4570 
4571 typedef struct snap_cbdata {
4572 	nvlist_t *sd_nvl;
4573 	boolean_t sd_recursive;
4574 	const char *sd_snapname;
4575 } snap_cbdata_t;
4576 
4577 static int
zfs_snapshot_cb(zfs_handle_t * zhp,void * arg)4578 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4579 {
4580 	snap_cbdata_t *sd = arg;
4581 	char *name;
4582 	int rv = 0;
4583 	int error;
4584 
4585 	if (sd->sd_recursive &&
4586 	    zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
4587 		zfs_close(zhp);
4588 		return (0);
4589 	}
4590 
4591 	error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4592 	if (error == -1)
4593 		nomem();
4594 	fnvlist_add_boolean(sd->sd_nvl, name);
4595 	free(name);
4596 
4597 	if (sd->sd_recursive)
4598 		rv = zfs_iter_filesystems_v2(zhp, 0, zfs_snapshot_cb, sd);
4599 	zfs_close(zhp);
4600 	return (rv);
4601 }
4602 
4603 /*
4604  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
4605  *
4606  * Creates a snapshot with the given name.  While functionally equivalent to
4607  * 'zfs create', it is a separate command to differentiate intent.
4608  */
4609 static int
zfs_do_snapshot(int argc,char ** argv)4610 zfs_do_snapshot(int argc, char **argv)
4611 {
4612 	int ret = 0;
4613 	int c;
4614 	nvlist_t *props;
4615 	snap_cbdata_t sd = { 0 };
4616 	boolean_t multiple_snaps = B_FALSE;
4617 
4618 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4619 		nomem();
4620 	if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
4621 		nomem();
4622 
4623 	/* check options */
4624 	while ((c = getopt(argc, argv, "ro:")) != -1) {
4625 		switch (c) {
4626 		case 'o':
4627 			if (!parseprop(props, optarg)) {
4628 				nvlist_free(sd.sd_nvl);
4629 				nvlist_free(props);
4630 				return (1);
4631 			}
4632 			break;
4633 		case 'r':
4634 			sd.sd_recursive = B_TRUE;
4635 			multiple_snaps = B_TRUE;
4636 			break;
4637 		case '?':
4638 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4639 			    optopt);
4640 			goto usage;
4641 		}
4642 	}
4643 
4644 	argc -= optind;
4645 	argv += optind;
4646 
4647 	/* check number of arguments */
4648 	if (argc < 1) {
4649 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
4650 		goto usage;
4651 	}
4652 
4653 	if (argc > 1)
4654 		multiple_snaps = B_TRUE;
4655 	for (; argc > 0; argc--, argv++) {
4656 		char *atp;
4657 		zfs_handle_t *zhp;
4658 
4659 		atp = strchr(argv[0], '@');
4660 		if (atp == NULL)
4661 			goto usage;
4662 		*atp = '\0';
4663 		sd.sd_snapname = atp + 1;
4664 		zhp = zfs_open(g_zfs, argv[0],
4665 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4666 		if (zhp == NULL)
4667 			goto usage;
4668 		if (zfs_snapshot_cb(zhp, &sd) != 0)
4669 			goto usage;
4670 	}
4671 
4672 	ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
4673 	nvlist_free(sd.sd_nvl);
4674 	nvlist_free(props);
4675 	if (ret != 0 && multiple_snaps)
4676 		(void) fprintf(stderr, gettext("no snapshots were created\n"));
4677 	return (ret != 0);
4678 
4679 usage:
4680 	nvlist_free(sd.sd_nvl);
4681 	nvlist_free(props);
4682 	usage(B_FALSE);
4683 	return (-1);
4684 }
4685 
4686 /*
4687  * Array of prefixes to exclude –
4688  * a linear search, even if executed for each dataset,
4689  * is plenty good enough.
4690  */
4691 typedef struct zfs_send_exclude_arg {
4692 	size_t count;
4693 	const char **list;
4694 } zfs_send_exclude_arg_t;
4695 
4696 static boolean_t
zfs_do_send_exclude(zfs_handle_t * zhp,void * context)4697 zfs_do_send_exclude(zfs_handle_t *zhp, void *context)
4698 {
4699 	zfs_send_exclude_arg_t *excludes = context;
4700 	const char *name = zfs_get_name(zhp);
4701 
4702 	for (size_t i = 0; i < excludes->count; ++i) {
4703 		size_t len = strlen(excludes->list[i]);
4704 		if (strncmp(name, excludes->list[i], len) == 0 &&
4705 		    memchr("/@", name[len], sizeof ("/@")))
4706 			return (B_FALSE);
4707 	}
4708 
4709 	return (B_TRUE);
4710 }
4711 
4712 /*
4713  * Send a backup stream to stdout.
4714  */
4715 static int
zfs_do_send(int argc,char ** argv)4716 zfs_do_send(int argc, char **argv)
4717 {
4718 	char *fromname = NULL;
4719 	char *toname = NULL;
4720 	char *resume_token = NULL;
4721 	char *cp;
4722 	zfs_handle_t *zhp;
4723 	sendflags_t flags = { 0 };
4724 	int c, err;
4725 	nvlist_t *dbgnv = NULL;
4726 	char *redactbook = NULL;
4727 	zfs_send_exclude_arg_t excludes = { 0 };
4728 
4729 	struct option long_options[] = {
4730 		{"replicate",	no_argument,		NULL, 'R'},
4731 		{"skip-missing",	no_argument,	NULL, 's'},
4732 		{"redact",	required_argument,	NULL, 'd'},
4733 		{"props",	no_argument,		NULL, 'p'},
4734 		{"parsable",	no_argument,		NULL, 'P'},
4735 		{"dedup",	no_argument,		NULL, 'D'},
4736 		{"proctitle",	no_argument,		NULL, 'V'},
4737 		{"verbose",	no_argument,		NULL, 'v'},
4738 		{"dryrun",	no_argument,		NULL, 'n'},
4739 		{"large-block",	no_argument,		NULL, 'L'},
4740 		{"embed",	no_argument,		NULL, 'e'},
4741 		{"resume",	required_argument,	NULL, 't'},
4742 		{"compressed",	no_argument,		NULL, 'c'},
4743 		{"raw",		no_argument,		NULL, 'w'},
4744 		{"backup",	no_argument,		NULL, 'b'},
4745 		{"holds",	no_argument,		NULL, 'h'},
4746 		{"saved",	no_argument,		NULL, 'S'},
4747 		{"exclude",	required_argument,	NULL, 'X'},
4748 		{0, 0, 0, 0}
4749 	};
4750 
4751 	/* check options */
4752 	while ((c = getopt_long(argc, argv, ":i:I:RsDpVvnPLeht:cwbd:SX:",
4753 	    long_options, NULL)) != -1) {
4754 		switch (c) {
4755 		case 'X':
4756 			for (char *ds; (ds = strsep(&optarg, ",")) != NULL; ) {
4757 				if (!zfs_name_valid(ds, ZFS_TYPE_DATASET) ||
4758 				    strchr(ds, '/') == NULL) {
4759 					(void) fprintf(stderr, gettext("-X %s: "
4760 					    "not a valid non-root dataset name"
4761 					    ".\n"), ds);
4762 					usage(B_FALSE);
4763 				}
4764 				excludes.list = safe_realloc(excludes.list,
4765 				    sizeof (char *) * (excludes.count + 1));
4766 				excludes.list[excludes.count++] = ds;
4767 			}
4768 			break;
4769 		case 'i':
4770 			if (fromname)
4771 				usage(B_FALSE);
4772 			fromname = optarg;
4773 			break;
4774 		case 'I':
4775 			if (fromname)
4776 				usage(B_FALSE);
4777 			fromname = optarg;
4778 			flags.doall = B_TRUE;
4779 			break;
4780 		case 'R':
4781 			flags.replicate = B_TRUE;
4782 			break;
4783 		case 's':
4784 			flags.skipmissing = B_TRUE;
4785 			break;
4786 		case 'd':
4787 			redactbook = optarg;
4788 			break;
4789 		case 'p':
4790 			flags.props = B_TRUE;
4791 			break;
4792 		case 'b':
4793 			flags.backup = B_TRUE;
4794 			break;
4795 		case 'h':
4796 			flags.holds = B_TRUE;
4797 			break;
4798 		case 'P':
4799 			flags.parsable = B_TRUE;
4800 			break;
4801 		case 'V':
4802 			flags.progressastitle = B_TRUE;
4803 			break;
4804 		case 'v':
4805 			flags.verbosity++;
4806 			flags.progress = B_TRUE;
4807 			break;
4808 		case 'D':
4809 			(void) fprintf(stderr,
4810 			    gettext("WARNING: deduplicated send is no "
4811 			    "longer supported.  A regular,\n"
4812 			    "non-deduplicated stream will be generated.\n\n"));
4813 			break;
4814 		case 'n':
4815 			flags.dryrun = B_TRUE;
4816 			break;
4817 		case 'L':
4818 			flags.largeblock = B_TRUE;
4819 			break;
4820 		case 'e':
4821 			flags.embed_data = B_TRUE;
4822 			break;
4823 		case 't':
4824 			resume_token = optarg;
4825 			break;
4826 		case 'c':
4827 			flags.compress = B_TRUE;
4828 			break;
4829 		case 'w':
4830 			flags.raw = B_TRUE;
4831 			flags.compress = B_TRUE;
4832 			flags.embed_data = B_TRUE;
4833 			flags.largeblock = B_TRUE;
4834 			break;
4835 		case 'S':
4836 			flags.saved = B_TRUE;
4837 			break;
4838 		case ':':
4839 			/*
4840 			 * If a parameter was not passed, optopt contains the
4841 			 * value that would normally lead us into the
4842 			 * appropriate case statement.  If it's > 256, then this
4843 			 * must be a longopt and we should look at argv to get
4844 			 * the string.  Otherwise it's just the character, so we
4845 			 * should use it directly.
4846 			 */
4847 			if (optopt <= UINT8_MAX) {
4848 				(void) fprintf(stderr,
4849 				    gettext("missing argument for '%c' "
4850 				    "option\n"), optopt);
4851 			} else {
4852 				(void) fprintf(stderr,
4853 				    gettext("missing argument for '%s' "
4854 				    "option\n"), argv[optind - 1]);
4855 			}
4856 			free(excludes.list);
4857 			usage(B_FALSE);
4858 			break;
4859 		case '?':
4860 		default:
4861 			/*
4862 			 * If an invalid flag was passed, optopt contains the
4863 			 * character if it was a short flag, or 0 if it was a
4864 			 * longopt.
4865 			 */
4866 			if (optopt != 0) {
4867 				(void) fprintf(stderr,
4868 				    gettext("invalid option '%c'\n"), optopt);
4869 			} else {
4870 				(void) fprintf(stderr,
4871 				    gettext("invalid option '%s'\n"),
4872 				    argv[optind - 1]);
4873 
4874 			}
4875 			free(excludes.list);
4876 			usage(B_FALSE);
4877 		}
4878 	}
4879 
4880 	if ((flags.parsable || flags.progressastitle) && flags.verbosity == 0)
4881 		flags.verbosity = 1;
4882 
4883 	if (excludes.count > 0 && !flags.replicate) {
4884 		free(excludes.list);
4885 		(void) fprintf(stderr, gettext("Cannot specify "
4886 		    "dataset exclusion (-X) on a non-recursive "
4887 		    "send.\n"));
4888 		return (1);
4889 	}
4890 
4891 	argc -= optind;
4892 	argv += optind;
4893 
4894 	if (resume_token != NULL) {
4895 		if (fromname != NULL || flags.replicate || flags.props ||
4896 		    flags.backup || flags.holds ||
4897 		    flags.saved || redactbook != NULL) {
4898 			free(excludes.list);
4899 			(void) fprintf(stderr,
4900 			    gettext("invalid flags combined with -t\n"));
4901 			usage(B_FALSE);
4902 		}
4903 		if (argc > 0) {
4904 			free(excludes.list);
4905 			(void) fprintf(stderr, gettext("too many arguments\n"));
4906 			usage(B_FALSE);
4907 		}
4908 	} else {
4909 		if (argc < 1) {
4910 			free(excludes.list);
4911 			(void) fprintf(stderr,
4912 			    gettext("missing snapshot argument\n"));
4913 			usage(B_FALSE);
4914 		}
4915 		if (argc > 1) {
4916 			free(excludes.list);
4917 			(void) fprintf(stderr, gettext("too many arguments\n"));
4918 			usage(B_FALSE);
4919 		}
4920 	}
4921 
4922 	if (flags.saved) {
4923 		if (fromname != NULL || flags.replicate || flags.props ||
4924 		    flags.doall || flags.backup ||
4925 		    flags.holds || flags.largeblock || flags.embed_data ||
4926 		    flags.compress || flags.raw || redactbook != NULL) {
4927 			free(excludes.list);
4928 
4929 			(void) fprintf(stderr, gettext("incompatible flags "
4930 			    "combined with saved send flag\n"));
4931 			usage(B_FALSE);
4932 		}
4933 		if (strchr(argv[0], '@') != NULL) {
4934 			free(excludes.list);
4935 
4936 			(void) fprintf(stderr, gettext("saved send must "
4937 			    "specify the dataset with partially-received "
4938 			    "state\n"));
4939 			usage(B_FALSE);
4940 		}
4941 	}
4942 
4943 	if (flags.raw && redactbook != NULL) {
4944 		free(excludes.list);
4945 		(void) fprintf(stderr,
4946 		    gettext("Error: raw sends may not be redacted.\n"));
4947 		return (1);
4948 	}
4949 
4950 	if (!flags.dryrun && isatty(STDOUT_FILENO)) {
4951 		free(excludes.list);
4952 		(void) fprintf(stderr,
4953 		    gettext("Error: Stream can not be written to a terminal.\n"
4954 		    "You must redirect standard output.\n"));
4955 		return (1);
4956 	}
4957 
4958 	if (flags.saved) {
4959 		zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4960 		if (zhp == NULL) {
4961 			free(excludes.list);
4962 			return (1);
4963 		}
4964 
4965 		err = zfs_send_saved(zhp, &flags, STDOUT_FILENO,
4966 		    resume_token);
4967 		free(excludes.list);
4968 		zfs_close(zhp);
4969 		return (err != 0);
4970 	} else if (resume_token != NULL) {
4971 		free(excludes.list);
4972 		return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
4973 		    resume_token));
4974 	}
4975 
4976 	if (flags.skipmissing && !flags.replicate) {
4977 		free(excludes.list);
4978 		(void) fprintf(stderr,
4979 		    gettext("skip-missing flag can only be used in "
4980 		    "conjunction with replicate\n"));
4981 		usage(B_FALSE);
4982 	}
4983 
4984 	/*
4985 	 * For everything except -R and -I, use the new, cleaner code path.
4986 	 */
4987 	if (!(flags.replicate || flags.doall)) {
4988 		char frombuf[ZFS_MAX_DATASET_NAME_LEN];
4989 
4990 		if (fromname != NULL && (strchr(fromname, '#') == NULL &&
4991 		    strchr(fromname, '@') == NULL)) {
4992 			/*
4993 			 * Neither bookmark or snapshot was specified.  Print a
4994 			 * warning, and assume snapshot.
4995 			 */
4996 			(void) fprintf(stderr, "Warning: incremental source "
4997 			    "didn't specify type, assuming snapshot. Use '@' "
4998 			    "or '#' prefix to avoid ambiguity.\n");
4999 			(void) snprintf(frombuf, sizeof (frombuf), "@%s",
5000 			    fromname);
5001 			fromname = frombuf;
5002 		}
5003 		if (fromname != NULL &&
5004 		    (fromname[0] == '#' || fromname[0] == '@')) {
5005 			/*
5006 			 * Incremental source name begins with # or @.
5007 			 * Default to same fs as target.
5008 			 */
5009 			char tmpbuf[ZFS_MAX_DATASET_NAME_LEN];
5010 			(void) strlcpy(tmpbuf, fromname, sizeof (tmpbuf));
5011 			(void) strlcpy(frombuf, argv[0], sizeof (frombuf));
5012 			cp = strchr(frombuf, '@');
5013 			if (cp != NULL)
5014 				*cp = '\0';
5015 			(void) strlcat(frombuf, tmpbuf, sizeof (frombuf));
5016 			fromname = frombuf;
5017 		}
5018 
5019 		zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
5020 		if (zhp == NULL) {
5021 			free(excludes.list);
5022 			return (1);
5023 		}
5024 		err = zfs_send_one(zhp, fromname, STDOUT_FILENO, &flags,
5025 		    redactbook);
5026 
5027 		free(excludes.list);
5028 		zfs_close(zhp);
5029 		return (err != 0);
5030 	}
5031 
5032 	if (fromname != NULL && strchr(fromname, '#')) {
5033 		(void) fprintf(stderr,
5034 		    gettext("Error: multiple snapshots cannot be "
5035 		    "sent from a bookmark.\n"));
5036 		free(excludes.list);
5037 		return (1);
5038 	}
5039 
5040 	if (redactbook != NULL) {
5041 		(void) fprintf(stderr, gettext("Error: multiple snapshots "
5042 		    "cannot be sent redacted.\n"));
5043 		free(excludes.list);
5044 		return (1);
5045 	}
5046 
5047 	if ((cp = strchr(argv[0], '@')) == NULL) {
5048 		(void) fprintf(stderr, gettext("Error: "
5049 		    "Unsupported flag with filesystem or bookmark.\n"));
5050 		free(excludes.list);
5051 		return (1);
5052 	}
5053 	*cp = '\0';
5054 	toname = cp + 1;
5055 	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5056 	if (zhp == NULL) {
5057 		free(excludes.list);
5058 		return (1);
5059 	}
5060 
5061 	/*
5062 	 * If they specified the full path to the snapshot, chop off
5063 	 * everything except the short name of the snapshot, but special
5064 	 * case if they specify the origin.
5065 	 */
5066 	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
5067 		char origin[ZFS_MAX_DATASET_NAME_LEN];
5068 		zprop_source_t src;
5069 
5070 		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
5071 		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
5072 
5073 		if (strcmp(origin, fromname) == 0) {
5074 			fromname = NULL;
5075 			flags.fromorigin = B_TRUE;
5076 		} else {
5077 			*cp = '\0';
5078 			if (cp != fromname && strcmp(argv[0], fromname)) {
5079 				zfs_close(zhp);
5080 				free(excludes.list);
5081 				(void) fprintf(stderr,
5082 				    gettext("incremental source must be "
5083 				    "in same filesystem\n"));
5084 				usage(B_FALSE);
5085 			}
5086 			fromname = cp + 1;
5087 			if (strchr(fromname, '@') || strchr(fromname, '/')) {
5088 				zfs_close(zhp);
5089 				free(excludes.list);
5090 				(void) fprintf(stderr,
5091 				    gettext("invalid incremental source\n"));
5092 				usage(B_FALSE);
5093 			}
5094 		}
5095 	}
5096 
5097 	if (flags.replicate && fromname == NULL)
5098 		flags.doall = B_TRUE;
5099 
5100 	err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO,
5101 	    excludes.count > 0 ? zfs_do_send_exclude : NULL,
5102 	    &excludes, flags.verbosity >= 3 ? &dbgnv : NULL);
5103 
5104 	if (flags.verbosity >= 3 && dbgnv != NULL) {
5105 		/*
5106 		 * dump_nvlist prints to stdout, but that's been
5107 		 * redirected to a file.  Make it print to stderr
5108 		 * instead.
5109 		 */
5110 		(void) dup2(STDERR_FILENO, STDOUT_FILENO);
5111 		dump_nvlist(dbgnv, 0);
5112 		nvlist_free(dbgnv);
5113 	}
5114 
5115 	zfs_close(zhp);
5116 	free(excludes.list);
5117 	return (err != 0);
5118 }
5119 
5120 /*
5121  * Restore a backup stream from stdin.
5122  */
5123 static int
zfs_do_receive(int argc,char ** argv)5124 zfs_do_receive(int argc, char **argv)
5125 {
5126 	int c, err = 0;
5127 	recvflags_t flags = { 0 };
5128 	boolean_t abort_resumable = B_FALSE;
5129 	nvlist_t *props;
5130 
5131 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
5132 		nomem();
5133 
5134 	/* check options */
5135 	while ((c = getopt(argc, argv, ":o:x:dehMnuvFsAc")) != -1) {
5136 		switch (c) {
5137 		case 'o':
5138 			if (!parseprop(props, optarg)) {
5139 				nvlist_free(props);
5140 				usage(B_FALSE);
5141 			}
5142 			break;
5143 		case 'x':
5144 			if (!parsepropname(props, optarg)) {
5145 				nvlist_free(props);
5146 				usage(B_FALSE);
5147 			}
5148 			break;
5149 		case 'd':
5150 			if (flags.istail) {
5151 				(void) fprintf(stderr, gettext("invalid option "
5152 				    "combination: -d and -e are mutually "
5153 				    "exclusive\n"));
5154 				usage(B_FALSE);
5155 			}
5156 			flags.isprefix = B_TRUE;
5157 			break;
5158 		case 'e':
5159 			if (flags.isprefix) {
5160 				(void) fprintf(stderr, gettext("invalid option "
5161 				    "combination: -d and -e are mutually "
5162 				    "exclusive\n"));
5163 				usage(B_FALSE);
5164 			}
5165 			flags.istail = B_TRUE;
5166 			break;
5167 		case 'h':
5168 			flags.skipholds = B_TRUE;
5169 			break;
5170 		case 'M':
5171 			flags.forceunmount = B_TRUE;
5172 			break;
5173 		case 'n':
5174 			flags.dryrun = B_TRUE;
5175 			break;
5176 		case 'u':
5177 			flags.nomount = B_TRUE;
5178 			break;
5179 		case 'v':
5180 			flags.verbose = B_TRUE;
5181 			break;
5182 		case 's':
5183 			flags.resumable = B_TRUE;
5184 			break;
5185 		case 'F':
5186 			flags.force = B_TRUE;
5187 			break;
5188 		case 'A':
5189 			abort_resumable = B_TRUE;
5190 			break;
5191 		case 'c':
5192 			flags.heal = B_TRUE;
5193 			break;
5194 		case ':':
5195 			(void) fprintf(stderr, gettext("missing argument for "
5196 			    "'%c' option\n"), optopt);
5197 			usage(B_FALSE);
5198 			break;
5199 		case '?':
5200 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5201 			    optopt);
5202 			usage(B_FALSE);
5203 		}
5204 	}
5205 
5206 	argc -= optind;
5207 	argv += optind;
5208 
5209 	/* zfs recv -e (use "tail" name) implies -d (remove dataset "head") */
5210 	if (flags.istail)
5211 		flags.isprefix = B_TRUE;
5212 
5213 	/* check number of arguments */
5214 	if (argc < 1) {
5215 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
5216 		usage(B_FALSE);
5217 	}
5218 	if (argc > 1) {
5219 		(void) fprintf(stderr, gettext("too many arguments\n"));
5220 		usage(B_FALSE);
5221 	}
5222 
5223 	if (abort_resumable) {
5224 		if (flags.isprefix || flags.istail || flags.dryrun ||
5225 		    flags.resumable || flags.nomount) {
5226 			(void) fprintf(stderr, gettext("invalid option\n"));
5227 			usage(B_FALSE);
5228 		}
5229 
5230 		char namebuf[ZFS_MAX_DATASET_NAME_LEN];
5231 		(void) snprintf(namebuf, sizeof (namebuf),
5232 		    "%s/%%recv", argv[0]);
5233 
5234 		if (zfs_dataset_exists(g_zfs, namebuf,
5235 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
5236 			zfs_handle_t *zhp = zfs_open(g_zfs,
5237 			    namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5238 			if (zhp == NULL) {
5239 				nvlist_free(props);
5240 				return (1);
5241 			}
5242 			err = zfs_destroy(zhp, B_FALSE);
5243 			zfs_close(zhp);
5244 		} else {
5245 			zfs_handle_t *zhp = zfs_open(g_zfs,
5246 			    argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5247 			if (zhp == NULL)
5248 				usage(B_FALSE);
5249 			if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
5250 			    zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5251 			    NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
5252 				(void) fprintf(stderr,
5253 				    gettext("'%s' does not have any "
5254 				    "resumable receive state to abort\n"),
5255 				    argv[0]);
5256 				nvlist_free(props);
5257 				zfs_close(zhp);
5258 				return (1);
5259 			}
5260 			err = zfs_destroy(zhp, B_FALSE);
5261 			zfs_close(zhp);
5262 		}
5263 		nvlist_free(props);
5264 		return (err != 0);
5265 	}
5266 
5267 	if (isatty(STDIN_FILENO)) {
5268 		(void) fprintf(stderr,
5269 		    gettext("Error: Backup stream can not be read "
5270 		    "from a terminal.\n"
5271 		    "You must redirect standard input.\n"));
5272 		nvlist_free(props);
5273 		return (1);
5274 	}
5275 	err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
5276 	nvlist_free(props);
5277 
5278 	return (err != 0);
5279 }
5280 
5281 /*
5282  * allow/unallow stuff
5283  */
5284 /* copied from zfs/sys/dsl_deleg.h */
5285 #define	ZFS_DELEG_PERM_CREATE		"create"
5286 #define	ZFS_DELEG_PERM_DESTROY		"destroy"
5287 #define	ZFS_DELEG_PERM_SNAPSHOT		"snapshot"
5288 #define	ZFS_DELEG_PERM_ROLLBACK		"rollback"
5289 #define	ZFS_DELEG_PERM_CLONE		"clone"
5290 #define	ZFS_DELEG_PERM_PROMOTE		"promote"
5291 #define	ZFS_DELEG_PERM_RENAME		"rename"
5292 #define	ZFS_DELEG_PERM_MOUNT		"mount"
5293 #define	ZFS_DELEG_PERM_SHARE		"share"
5294 #define	ZFS_DELEG_PERM_SEND		"send"
5295 #define	ZFS_DELEG_PERM_RECEIVE		"receive"
5296 #define	ZFS_DELEG_PERM_RECEIVE_APPEND	"receive:append"
5297 #define	ZFS_DELEG_PERM_ALLOW		"allow"
5298 #define	ZFS_DELEG_PERM_USERPROP		"userprop"
5299 #define	ZFS_DELEG_PERM_VSCAN		"vscan" /* ??? */
5300 #define	ZFS_DELEG_PERM_USERQUOTA	"userquota"
5301 #define	ZFS_DELEG_PERM_GROUPQUOTA	"groupquota"
5302 #define	ZFS_DELEG_PERM_USERUSED		"userused"
5303 #define	ZFS_DELEG_PERM_GROUPUSED	"groupused"
5304 #define	ZFS_DELEG_PERM_USEROBJQUOTA	"userobjquota"
5305 #define	ZFS_DELEG_PERM_GROUPOBJQUOTA	"groupobjquota"
5306 #define	ZFS_DELEG_PERM_USEROBJUSED	"userobjused"
5307 #define	ZFS_DELEG_PERM_GROUPOBJUSED	"groupobjused"
5308 
5309 #define	ZFS_DELEG_PERM_HOLD		"hold"
5310 #define	ZFS_DELEG_PERM_RELEASE		"release"
5311 #define	ZFS_DELEG_PERM_DIFF		"diff"
5312 #define	ZFS_DELEG_PERM_BOOKMARK		"bookmark"
5313 #define	ZFS_DELEG_PERM_LOAD_KEY		"load-key"
5314 #define	ZFS_DELEG_PERM_CHANGE_KEY	"change-key"
5315 
5316 #define	ZFS_DELEG_PERM_PROJECTUSED	"projectused"
5317 #define	ZFS_DELEG_PERM_PROJECTQUOTA	"projectquota"
5318 #define	ZFS_DELEG_PERM_PROJECTOBJUSED	"projectobjused"
5319 #define	ZFS_DELEG_PERM_PROJECTOBJQUOTA	"projectobjquota"
5320 
5321 #define	ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
5322 
5323 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
5324 	{ ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
5325 	{ ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
5326 	{ ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
5327 	{ ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
5328 	{ ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
5329 	{ ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
5330 	{ ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
5331 	{ ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
5332 	{ ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
5333 	{ ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
5334 	{ ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
5335 	{ ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
5336 	{ ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
5337 	{ ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
5338 	{ ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
5339 	{ ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
5340 	{ ZFS_DELEG_PERM_LOAD_KEY, ZFS_DELEG_NOTE_LOAD_KEY },
5341 	{ ZFS_DELEG_PERM_CHANGE_KEY, ZFS_DELEG_NOTE_CHANGE_KEY },
5342 
5343 	{ ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
5344 	{ ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
5345 	{ ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
5346 	{ ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
5347 	{ ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
5348 	{ ZFS_DELEG_PERM_USEROBJQUOTA, ZFS_DELEG_NOTE_USEROBJQUOTA },
5349 	{ ZFS_DELEG_PERM_USEROBJUSED, ZFS_DELEG_NOTE_USEROBJUSED },
5350 	{ ZFS_DELEG_PERM_GROUPOBJQUOTA, ZFS_DELEG_NOTE_GROUPOBJQUOTA },
5351 	{ ZFS_DELEG_PERM_GROUPOBJUSED, ZFS_DELEG_NOTE_GROUPOBJUSED },
5352 	{ ZFS_DELEG_PERM_PROJECTUSED, ZFS_DELEG_NOTE_PROJECTUSED },
5353 	{ ZFS_DELEG_PERM_PROJECTQUOTA, ZFS_DELEG_NOTE_PROJECTQUOTA },
5354 	{ ZFS_DELEG_PERM_PROJECTOBJUSED, ZFS_DELEG_NOTE_PROJECTOBJUSED },
5355 	{ ZFS_DELEG_PERM_PROJECTOBJQUOTA, ZFS_DELEG_NOTE_PROJECTOBJQUOTA },
5356 	{ NULL, ZFS_DELEG_NOTE_NONE }
5357 };
5358 
5359 /* permission structure */
5360 typedef struct deleg_perm {
5361 	zfs_deleg_who_type_t	dp_who_type;
5362 	const char		*dp_name;
5363 	boolean_t		dp_local;
5364 	boolean_t		dp_descend;
5365 } deleg_perm_t;
5366 
5367 /* */
5368 typedef struct deleg_perm_node {
5369 	deleg_perm_t		dpn_perm;
5370 
5371 	uu_avl_node_t		dpn_avl_node;
5372 } deleg_perm_node_t;
5373 
5374 typedef struct fs_perm fs_perm_t;
5375 
5376 /* permissions set */
5377 typedef struct who_perm {
5378 	zfs_deleg_who_type_t	who_type;
5379 	const char		*who_name;		/* id */
5380 	char			who_ug_name[256];	/* user/group name */
5381 	fs_perm_t		*who_fsperm;		/* uplink */
5382 
5383 	uu_avl_t		*who_deleg_perm_avl;	/* permissions */
5384 } who_perm_t;
5385 
5386 /* */
5387 typedef struct who_perm_node {
5388 	who_perm_t	who_perm;
5389 	uu_avl_node_t	who_avl_node;
5390 } who_perm_node_t;
5391 
5392 typedef struct fs_perm_set fs_perm_set_t;
5393 /* fs permissions */
5394 struct fs_perm {
5395 	const char		*fsp_name;
5396 
5397 	uu_avl_t		*fsp_sc_avl;	/* sets,create */
5398 	uu_avl_t		*fsp_uge_avl;	/* user,group,everyone */
5399 
5400 	fs_perm_set_t		*fsp_set;	/* uplink */
5401 };
5402 
5403 /* */
5404 typedef struct fs_perm_node {
5405 	fs_perm_t	fspn_fsperm;
5406 	uu_avl_t	*fspn_avl;
5407 
5408 	uu_list_node_t	fspn_list_node;
5409 } fs_perm_node_t;
5410 
5411 /* top level structure */
5412 struct fs_perm_set {
5413 	uu_list_pool_t	*fsps_list_pool;
5414 	uu_list_t	*fsps_list; /* list of fs_perms */
5415 
5416 	uu_avl_pool_t	*fsps_named_set_avl_pool;
5417 	uu_avl_pool_t	*fsps_who_perm_avl_pool;
5418 	uu_avl_pool_t	*fsps_deleg_perm_avl_pool;
5419 };
5420 
5421 static inline const char *
deleg_perm_type(zfs_deleg_note_t note)5422 deleg_perm_type(zfs_deleg_note_t note)
5423 {
5424 	/* subcommands */
5425 	switch (note) {
5426 		/* SUBCOMMANDS */
5427 		/* OTHER */
5428 	case ZFS_DELEG_NOTE_GROUPQUOTA:
5429 	case ZFS_DELEG_NOTE_GROUPUSED:
5430 	case ZFS_DELEG_NOTE_USERPROP:
5431 	case ZFS_DELEG_NOTE_USERQUOTA:
5432 	case ZFS_DELEG_NOTE_USERUSED:
5433 	case ZFS_DELEG_NOTE_USEROBJQUOTA:
5434 	case ZFS_DELEG_NOTE_USEROBJUSED:
5435 	case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5436 	case ZFS_DELEG_NOTE_GROUPOBJUSED:
5437 	case ZFS_DELEG_NOTE_PROJECTUSED:
5438 	case ZFS_DELEG_NOTE_PROJECTQUOTA:
5439 	case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5440 	case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5441 		/* other */
5442 		return (gettext("other"));
5443 	default:
5444 		return (gettext("subcommand"));
5445 	}
5446 }
5447 
5448 static int
who_type2weight(zfs_deleg_who_type_t who_type)5449 who_type2weight(zfs_deleg_who_type_t who_type)
5450 {
5451 	int res;
5452 	switch (who_type) {
5453 		case ZFS_DELEG_NAMED_SET_SETS:
5454 		case ZFS_DELEG_NAMED_SET:
5455 			res = 0;
5456 			break;
5457 		case ZFS_DELEG_CREATE_SETS:
5458 		case ZFS_DELEG_CREATE:
5459 			res = 1;
5460 			break;
5461 		case ZFS_DELEG_USER_SETS:
5462 		case ZFS_DELEG_USER:
5463 			res = 2;
5464 			break;
5465 		case ZFS_DELEG_GROUP_SETS:
5466 		case ZFS_DELEG_GROUP:
5467 			res = 3;
5468 			break;
5469 		case ZFS_DELEG_EVERYONE_SETS:
5470 		case ZFS_DELEG_EVERYONE:
5471 			res = 4;
5472 			break;
5473 		default:
5474 			res = -1;
5475 	}
5476 
5477 	return (res);
5478 }
5479 
5480 static int
who_perm_compare(const void * larg,const void * rarg,void * unused)5481 who_perm_compare(const void *larg, const void *rarg, void *unused)
5482 {
5483 	(void) unused;
5484 	const who_perm_node_t *l = larg;
5485 	const who_perm_node_t *r = rarg;
5486 	zfs_deleg_who_type_t ltype = l->who_perm.who_type;
5487 	zfs_deleg_who_type_t rtype = r->who_perm.who_type;
5488 	int lweight = who_type2weight(ltype);
5489 	int rweight = who_type2weight(rtype);
5490 	int res = lweight - rweight;
5491 	if (res == 0)
5492 		res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
5493 		    ZFS_MAX_DELEG_NAME-1);
5494 
5495 	if (res == 0)
5496 		return (0);
5497 	if (res > 0)
5498 		return (1);
5499 	else
5500 		return (-1);
5501 }
5502 
5503 static int
deleg_perm_compare(const void * larg,const void * rarg,void * unused)5504 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
5505 {
5506 	(void) unused;
5507 	const deleg_perm_node_t *l = larg;
5508 	const deleg_perm_node_t *r = rarg;
5509 	int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
5510 	    ZFS_MAX_DELEG_NAME-1);
5511 
5512 	if (res == 0)
5513 		return (0);
5514 
5515 	if (res > 0)
5516 		return (1);
5517 	else
5518 		return (-1);
5519 }
5520 
5521 static inline void
fs_perm_set_init(fs_perm_set_t * fspset)5522 fs_perm_set_init(fs_perm_set_t *fspset)
5523 {
5524 	memset(fspset, 0, sizeof (fs_perm_set_t));
5525 
5526 	if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
5527 	    sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
5528 	    NULL, UU_DEFAULT)) == NULL)
5529 		nomem();
5530 	if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
5531 	    UU_DEFAULT)) == NULL)
5532 		nomem();
5533 
5534 	if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
5535 	    "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
5536 	    who_perm_node_t, who_avl_node), who_perm_compare,
5537 	    UU_DEFAULT)) == NULL)
5538 		nomem();
5539 
5540 	if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
5541 	    "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
5542 	    who_perm_node_t, who_avl_node), who_perm_compare,
5543 	    UU_DEFAULT)) == NULL)
5544 		nomem();
5545 
5546 	if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
5547 	    "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
5548 	    deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
5549 	    == NULL)
5550 		nomem();
5551 }
5552 
5553 static inline void fs_perm_fini(fs_perm_t *);
5554 static inline void who_perm_fini(who_perm_t *);
5555 
5556 static inline void
fs_perm_set_fini(fs_perm_set_t * fspset)5557 fs_perm_set_fini(fs_perm_set_t *fspset)
5558 {
5559 	fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
5560 
5561 	while (node != NULL) {
5562 		fs_perm_node_t *next_node =
5563 		    uu_list_next(fspset->fsps_list, node);
5564 		fs_perm_t *fsperm = &node->fspn_fsperm;
5565 		fs_perm_fini(fsperm);
5566 		uu_list_remove(fspset->fsps_list, node);
5567 		free(node);
5568 		node = next_node;
5569 	}
5570 
5571 	uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
5572 	uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
5573 	uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
5574 }
5575 
5576 static inline void
deleg_perm_init(deleg_perm_t * deleg_perm,zfs_deleg_who_type_t type,const char * name)5577 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
5578     const char *name)
5579 {
5580 	deleg_perm->dp_who_type = type;
5581 	deleg_perm->dp_name = name;
5582 }
5583 
5584 static inline void
who_perm_init(who_perm_t * who_perm,fs_perm_t * fsperm,zfs_deleg_who_type_t type,const char * name)5585 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
5586     zfs_deleg_who_type_t type, const char *name)
5587 {
5588 	uu_avl_pool_t	*pool;
5589 	pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
5590 
5591 	memset(who_perm, 0, sizeof (who_perm_t));
5592 
5593 	if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
5594 	    UU_DEFAULT)) == NULL)
5595 		nomem();
5596 
5597 	who_perm->who_type = type;
5598 	who_perm->who_name = name;
5599 	who_perm->who_fsperm = fsperm;
5600 }
5601 
5602 static inline void
who_perm_fini(who_perm_t * who_perm)5603 who_perm_fini(who_perm_t *who_perm)
5604 {
5605 	deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
5606 
5607 	while (node != NULL) {
5608 		deleg_perm_node_t *next_node =
5609 		    uu_avl_next(who_perm->who_deleg_perm_avl, node);
5610 
5611 		uu_avl_remove(who_perm->who_deleg_perm_avl, node);
5612 		free(node);
5613 		node = next_node;
5614 	}
5615 
5616 	uu_avl_destroy(who_perm->who_deleg_perm_avl);
5617 }
5618 
5619 static inline void
fs_perm_init(fs_perm_t * fsperm,fs_perm_set_t * fspset,const char * fsname)5620 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
5621 {
5622 	uu_avl_pool_t	*nset_pool = fspset->fsps_named_set_avl_pool;
5623 	uu_avl_pool_t	*who_pool = fspset->fsps_who_perm_avl_pool;
5624 
5625 	memset(fsperm, 0, sizeof (fs_perm_t));
5626 
5627 	if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
5628 	    == NULL)
5629 		nomem();
5630 
5631 	if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
5632 	    == NULL)
5633 		nomem();
5634 
5635 	fsperm->fsp_set = fspset;
5636 	fsperm->fsp_name = fsname;
5637 }
5638 
5639 static inline void
fs_perm_fini(fs_perm_t * fsperm)5640 fs_perm_fini(fs_perm_t *fsperm)
5641 {
5642 	who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
5643 	while (node != NULL) {
5644 		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
5645 		    node);
5646 		who_perm_t *who_perm = &node->who_perm;
5647 		who_perm_fini(who_perm);
5648 		uu_avl_remove(fsperm->fsp_sc_avl, node);
5649 		free(node);
5650 		node = next_node;
5651 	}
5652 
5653 	node = uu_avl_first(fsperm->fsp_uge_avl);
5654 	while (node != NULL) {
5655 		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
5656 		    node);
5657 		who_perm_t *who_perm = &node->who_perm;
5658 		who_perm_fini(who_perm);
5659 		uu_avl_remove(fsperm->fsp_uge_avl, node);
5660 		free(node);
5661 		node = next_node;
5662 	}
5663 
5664 	uu_avl_destroy(fsperm->fsp_sc_avl);
5665 	uu_avl_destroy(fsperm->fsp_uge_avl);
5666 }
5667 
5668 static void
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)5669 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
5670     zfs_deleg_who_type_t who_type, const char *name, char locality)
5671 {
5672 	uu_avl_index_t idx = 0;
5673 
5674 	deleg_perm_node_t *found_node = NULL;
5675 	deleg_perm_t	*deleg_perm = &node->dpn_perm;
5676 
5677 	deleg_perm_init(deleg_perm, who_type, name);
5678 
5679 	if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5680 	    == NULL)
5681 		uu_avl_insert(avl, node, idx);
5682 	else {
5683 		node = found_node;
5684 		deleg_perm = &node->dpn_perm;
5685 	}
5686 
5687 
5688 	switch (locality) {
5689 	case ZFS_DELEG_LOCAL:
5690 		deleg_perm->dp_local = B_TRUE;
5691 		break;
5692 	case ZFS_DELEG_DESCENDENT:
5693 		deleg_perm->dp_descend = B_TRUE;
5694 		break;
5695 	case ZFS_DELEG_NA:
5696 		break;
5697 	default:
5698 		assert(B_FALSE); /* invalid locality */
5699 	}
5700 }
5701 
5702 static inline int
parse_who_perm(who_perm_t * who_perm,nvlist_t * nvl,char locality)5703 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
5704 {
5705 	nvpair_t *nvp = NULL;
5706 	fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
5707 	uu_avl_t *avl = who_perm->who_deleg_perm_avl;
5708 	zfs_deleg_who_type_t who_type = who_perm->who_type;
5709 
5710 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5711 		const char *name = nvpair_name(nvp);
5712 		data_type_t type = nvpair_type(nvp);
5713 		uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
5714 		deleg_perm_node_t *node =
5715 		    safe_malloc(sizeof (deleg_perm_node_t));
5716 
5717 		VERIFY(type == DATA_TYPE_BOOLEAN);
5718 
5719 		uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
5720 		set_deleg_perm_node(avl, node, who_type, name, locality);
5721 	}
5722 
5723 	return (0);
5724 }
5725 
5726 static inline int
parse_fs_perm(fs_perm_t * fsperm,nvlist_t * nvl)5727 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
5728 {
5729 	nvpair_t *nvp = NULL;
5730 	fs_perm_set_t *fspset = fsperm->fsp_set;
5731 
5732 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5733 		nvlist_t *nvl2 = NULL;
5734 		const char *name = nvpair_name(nvp);
5735 		uu_avl_t *avl = NULL;
5736 		uu_avl_pool_t *avl_pool = NULL;
5737 		zfs_deleg_who_type_t perm_type = name[0];
5738 		char perm_locality = name[1];
5739 		const char *perm_name = name + 3;
5740 		who_perm_t *who_perm = NULL;
5741 
5742 		assert('$' == name[2]);
5743 
5744 		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5745 			return (-1);
5746 
5747 		switch (perm_type) {
5748 		case ZFS_DELEG_CREATE:
5749 		case ZFS_DELEG_CREATE_SETS:
5750 		case ZFS_DELEG_NAMED_SET:
5751 		case ZFS_DELEG_NAMED_SET_SETS:
5752 			avl_pool = fspset->fsps_named_set_avl_pool;
5753 			avl = fsperm->fsp_sc_avl;
5754 			break;
5755 		case ZFS_DELEG_USER:
5756 		case ZFS_DELEG_USER_SETS:
5757 		case ZFS_DELEG_GROUP:
5758 		case ZFS_DELEG_GROUP_SETS:
5759 		case ZFS_DELEG_EVERYONE:
5760 		case ZFS_DELEG_EVERYONE_SETS:
5761 			avl_pool = fspset->fsps_who_perm_avl_pool;
5762 			avl = fsperm->fsp_uge_avl;
5763 			break;
5764 
5765 		default:
5766 			assert(!"unhandled zfs_deleg_who_type_t");
5767 		}
5768 
5769 		who_perm_node_t *found_node = NULL;
5770 		who_perm_node_t *node = safe_malloc(
5771 		    sizeof (who_perm_node_t));
5772 		who_perm = &node->who_perm;
5773 		uu_avl_index_t idx = 0;
5774 
5775 		uu_avl_node_init(node, &node->who_avl_node, avl_pool);
5776 		who_perm_init(who_perm, fsperm, perm_type, perm_name);
5777 
5778 		if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5779 		    == NULL) {
5780 			if (avl == fsperm->fsp_uge_avl) {
5781 				uid_t rid = 0;
5782 				struct passwd *p = NULL;
5783 				struct group *g = NULL;
5784 				const char *nice_name = NULL;
5785 
5786 				switch (perm_type) {
5787 				case ZFS_DELEG_USER_SETS:
5788 				case ZFS_DELEG_USER:
5789 					rid = atoi(perm_name);
5790 					p = getpwuid(rid);
5791 					if (p)
5792 						nice_name = p->pw_name;
5793 					break;
5794 				case ZFS_DELEG_GROUP_SETS:
5795 				case ZFS_DELEG_GROUP:
5796 					rid = atoi(perm_name);
5797 					g = getgrgid(rid);
5798 					if (g)
5799 						nice_name = g->gr_name;
5800 					break;
5801 
5802 				default:
5803 					break;
5804 				}
5805 
5806 				if (nice_name != NULL) {
5807 					(void) strlcpy(
5808 					    node->who_perm.who_ug_name,
5809 					    nice_name, 256);
5810 				} else {
5811 					/* User or group unknown */
5812 					(void) snprintf(
5813 					    node->who_perm.who_ug_name,
5814 					    sizeof (node->who_perm.who_ug_name),
5815 					    "(unknown: %d)", rid);
5816 				}
5817 			}
5818 
5819 			uu_avl_insert(avl, node, idx);
5820 		} else {
5821 			node = found_node;
5822 			who_perm = &node->who_perm;
5823 		}
5824 
5825 		assert(who_perm != NULL);
5826 		(void) parse_who_perm(who_perm, nvl2, perm_locality);
5827 	}
5828 
5829 	return (0);
5830 }
5831 
5832 static inline int
parse_fs_perm_set(fs_perm_set_t * fspset,nvlist_t * nvl)5833 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
5834 {
5835 	nvpair_t *nvp = NULL;
5836 	uu_avl_index_t idx = 0;
5837 
5838 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5839 		nvlist_t *nvl2 = NULL;
5840 		const char *fsname = nvpair_name(nvp);
5841 		data_type_t type = nvpair_type(nvp);
5842 		fs_perm_t *fsperm = NULL;
5843 		fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
5844 
5845 		fsperm = &node->fspn_fsperm;
5846 
5847 		VERIFY(DATA_TYPE_NVLIST == type);
5848 
5849 		uu_list_node_init(node, &node->fspn_list_node,
5850 		    fspset->fsps_list_pool);
5851 
5852 		idx = uu_list_numnodes(fspset->fsps_list);
5853 		fs_perm_init(fsperm, fspset, fsname);
5854 
5855 		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5856 			return (-1);
5857 
5858 		(void) parse_fs_perm(fsperm, nvl2);
5859 
5860 		uu_list_insert(fspset->fsps_list, node, idx);
5861 	}
5862 
5863 	return (0);
5864 }
5865 
5866 static inline const char *
deleg_perm_comment(zfs_deleg_note_t note)5867 deleg_perm_comment(zfs_deleg_note_t note)
5868 {
5869 	const char *str = "";
5870 
5871 	/* subcommands */
5872 	switch (note) {
5873 		/* SUBCOMMANDS */
5874 	case ZFS_DELEG_NOTE_ALLOW:
5875 		str = gettext("Must also have the permission that is being"
5876 		    "\n\t\t\t\tallowed");
5877 		break;
5878 	case ZFS_DELEG_NOTE_CLONE:
5879 		str = gettext("Must also have the 'create' ability and 'mount'"
5880 		    "\n\t\t\t\tability in the origin file system");
5881 		break;
5882 	case ZFS_DELEG_NOTE_CREATE:
5883 		str = gettext("Must also have the 'mount' ability");
5884 		break;
5885 	case ZFS_DELEG_NOTE_DESTROY:
5886 		str = gettext("Must also have the 'mount' ability");
5887 		break;
5888 	case ZFS_DELEG_NOTE_DIFF:
5889 		str = gettext("Allows lookup of paths within a dataset;"
5890 		    "\n\t\t\t\tgiven an object number. Ordinary users need this"
5891 		    "\n\t\t\t\tin order to use zfs diff");
5892 		break;
5893 	case ZFS_DELEG_NOTE_HOLD:
5894 		str = gettext("Allows adding a user hold to a snapshot");
5895 		break;
5896 	case ZFS_DELEG_NOTE_MOUNT:
5897 		str = gettext("Allows mount/umount of ZFS datasets");
5898 		break;
5899 	case ZFS_DELEG_NOTE_PROMOTE:
5900 		str = gettext("Must also have the 'mount'\n\t\t\t\tand"
5901 		    " 'promote' ability in the origin file system");
5902 		break;
5903 	case ZFS_DELEG_NOTE_RECEIVE:
5904 		str = gettext("Must also have the 'mount' and 'create'"
5905 		    " ability");
5906 		break;
5907 	case ZFS_DELEG_NOTE_RELEASE:
5908 		str = gettext("Allows releasing a user hold which\n\t\t\t\t"
5909 		    "might destroy the snapshot");
5910 		break;
5911 	case ZFS_DELEG_NOTE_RENAME:
5912 		str = gettext("Must also have the 'mount' and 'create'"
5913 		    "\n\t\t\t\tability in the new parent");
5914 		break;
5915 	case ZFS_DELEG_NOTE_ROLLBACK:
5916 		str = gettext("");
5917 		break;
5918 	case ZFS_DELEG_NOTE_SEND:
5919 		str = gettext("");
5920 		break;
5921 	case ZFS_DELEG_NOTE_SHARE:
5922 		str = gettext("Allows sharing file systems over NFS or SMB"
5923 		    "\n\t\t\t\tprotocols");
5924 		break;
5925 	case ZFS_DELEG_NOTE_SNAPSHOT:
5926 		str = gettext("");
5927 		break;
5928 	case ZFS_DELEG_NOTE_LOAD_KEY:
5929 		str = gettext("Allows loading or unloading an encryption key");
5930 		break;
5931 	case ZFS_DELEG_NOTE_CHANGE_KEY:
5932 		str = gettext("Allows changing or adding an encryption key");
5933 		break;
5934 /*
5935  *	case ZFS_DELEG_NOTE_VSCAN:
5936  *		str = gettext("");
5937  *		break;
5938  */
5939 		/* OTHER */
5940 	case ZFS_DELEG_NOTE_GROUPQUOTA:
5941 		str = gettext("Allows accessing any groupquota@... property");
5942 		break;
5943 	case ZFS_DELEG_NOTE_GROUPUSED:
5944 		str = gettext("Allows reading any groupused@... property");
5945 		break;
5946 	case ZFS_DELEG_NOTE_USERPROP:
5947 		str = gettext("Allows changing any user property");
5948 		break;
5949 	case ZFS_DELEG_NOTE_USERQUOTA:
5950 		str = gettext("Allows accessing any userquota@... property");
5951 		break;
5952 	case ZFS_DELEG_NOTE_USERUSED:
5953 		str = gettext("Allows reading any userused@... property");
5954 		break;
5955 	case ZFS_DELEG_NOTE_USEROBJQUOTA:
5956 		str = gettext("Allows accessing any userobjquota@... property");
5957 		break;
5958 	case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5959 		str = gettext("Allows accessing any \n\t\t\t\t"
5960 		    "groupobjquota@... property");
5961 		break;
5962 	case ZFS_DELEG_NOTE_GROUPOBJUSED:
5963 		str = gettext("Allows reading any groupobjused@... property");
5964 		break;
5965 	case ZFS_DELEG_NOTE_USEROBJUSED:
5966 		str = gettext("Allows reading any userobjused@... property");
5967 		break;
5968 	case ZFS_DELEG_NOTE_PROJECTQUOTA:
5969 		str = gettext("Allows accessing any projectquota@... property");
5970 		break;
5971 	case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5972 		str = gettext("Allows accessing any \n\t\t\t\t"
5973 		    "projectobjquota@... property");
5974 		break;
5975 	case ZFS_DELEG_NOTE_PROJECTUSED:
5976 		str = gettext("Allows reading any projectused@... property");
5977 		break;
5978 	case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5979 		str = gettext("Allows accessing any \n\t\t\t\t"
5980 		    "projectobjused@... property");
5981 		break;
5982 		/* other */
5983 	default:
5984 		str = "";
5985 	}
5986 
5987 	return (str);
5988 }
5989 
5990 struct allow_opts {
5991 	boolean_t local;
5992 	boolean_t descend;
5993 	boolean_t user;
5994 	boolean_t group;
5995 	boolean_t everyone;
5996 	boolean_t create;
5997 	boolean_t set;
5998 	boolean_t recursive; /* unallow only */
5999 	boolean_t prt_usage;
6000 
6001 	boolean_t prt_perms;
6002 	char *who;
6003 	char *perms;
6004 	const char *dataset;
6005 };
6006 
6007 static inline int
prop_cmp(const void * a,const void * b)6008 prop_cmp(const void *a, const void *b)
6009 {
6010 	const char *str1 = *(const char **)a;
6011 	const char *str2 = *(const char **)b;
6012 	return (strcmp(str1, str2));
6013 }
6014 
6015 static void
allow_usage(boolean_t un,boolean_t requested,const char * msg)6016 allow_usage(boolean_t un, boolean_t requested, const char *msg)
6017 {
6018 	const char *opt_desc[] = {
6019 		"-h", gettext("show this help message and exit"),
6020 		"-l", gettext("set permission locally"),
6021 		"-d", gettext("set permission for descents"),
6022 		"-u", gettext("set permission for user"),
6023 		"-g", gettext("set permission for group"),
6024 		"-e", gettext("set permission for everyone"),
6025 		"-c", gettext("set create time permission"),
6026 		"-s", gettext("define permission set"),
6027 		/* unallow only */
6028 		"-r", gettext("remove permissions recursively"),
6029 	};
6030 	size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
6031 	size_t allow_size = unallow_size - 2;
6032 	const char *props[ZFS_NUM_PROPS];
6033 	int i;
6034 	size_t count = 0;
6035 	FILE *fp = requested ? stdout : stderr;
6036 	zprop_desc_t *pdtbl = zfs_prop_get_table();
6037 	const char *fmt = gettext("%-16s %-14s\t%s\n");
6038 
6039 	(void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
6040 	    HELP_ALLOW));
6041 	(void) fprintf(fp, gettext("Options:\n"));
6042 	for (i = 0; i < (un ? unallow_size : allow_size); i += 2) {
6043 		const char *opt = opt_desc[i];
6044 		const char *optdsc = opt_desc[i + 1];
6045 		(void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
6046 	}
6047 
6048 	(void) fprintf(fp, gettext("\nThe following permissions are "
6049 	    "supported:\n\n"));
6050 	(void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
6051 	    gettext("NOTES"));
6052 	for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
6053 		const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
6054 		zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
6055 		const char *perm_type = deleg_perm_type(perm_note);
6056 		const char *perm_comment = deleg_perm_comment(perm_note);
6057 		(void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
6058 	}
6059 
6060 	for (i = 0; i < ZFS_NUM_PROPS; i++) {
6061 		zprop_desc_t *pd = &pdtbl[i];
6062 		if (pd->pd_visible != B_TRUE)
6063 			continue;
6064 
6065 		if (pd->pd_attr == PROP_READONLY)
6066 			continue;
6067 
6068 		props[count++] = pd->pd_name;
6069 	}
6070 	props[count] = NULL;
6071 
6072 	qsort(props, count, sizeof (char *), prop_cmp);
6073 
6074 	for (i = 0; i < count; i++)
6075 		(void) fprintf(fp, fmt, props[i], gettext("property"), "");
6076 
6077 	if (msg != NULL)
6078 		(void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
6079 
6080 	exit(requested ? 0 : 2);
6081 }
6082 
6083 static inline const char *
munge_args(int argc,char ** argv,boolean_t un,size_t expected_argc,char ** permsp)6084 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
6085     char **permsp)
6086 {
6087 	if (un && argc == expected_argc - 1)
6088 		*permsp = NULL;
6089 	else if (argc == expected_argc)
6090 		*permsp = argv[argc - 2];
6091 	else
6092 		allow_usage(un, B_FALSE,
6093 		    gettext("wrong number of parameters\n"));
6094 
6095 	return (argv[argc - 1]);
6096 }
6097 
6098 static void
parse_allow_args(int argc,char ** argv,boolean_t un,struct allow_opts * opts)6099 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
6100 {
6101 	int uge_sum = opts->user + opts->group + opts->everyone;
6102 	int csuge_sum = opts->create + opts->set + uge_sum;
6103 	int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
6104 	int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
6105 
6106 	if (uge_sum > 1)
6107 		allow_usage(un, B_FALSE,
6108 		    gettext("-u, -g, and -e are mutually exclusive\n"));
6109 
6110 	if (opts->prt_usage) {
6111 		if (argc == 0 && all_sum == 0)
6112 			allow_usage(un, B_TRUE, NULL);
6113 		else
6114 			usage(B_FALSE);
6115 	}
6116 
6117 	if (opts->set) {
6118 		if (csuge_sum > 1)
6119 			allow_usage(un, B_FALSE,
6120 			    gettext("invalid options combined with -s\n"));
6121 
6122 		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6123 		if (argv[0][0] != '@')
6124 			allow_usage(un, B_FALSE,
6125 			    gettext("invalid set name: missing '@' prefix\n"));
6126 		opts->who = argv[0];
6127 	} else if (opts->create) {
6128 		if (ldcsuge_sum > 1)
6129 			allow_usage(un, B_FALSE,
6130 			    gettext("invalid options combined with -c\n"));
6131 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6132 	} else if (opts->everyone) {
6133 		if (csuge_sum > 1)
6134 			allow_usage(un, B_FALSE,
6135 			    gettext("invalid options combined with -e\n"));
6136 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6137 	} else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
6138 	    == 0) {
6139 		opts->everyone = B_TRUE;
6140 		argc--;
6141 		argv++;
6142 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6143 	} else if (argc == 1 && !un) {
6144 		opts->prt_perms = B_TRUE;
6145 		opts->dataset = argv[argc-1];
6146 	} else {
6147 		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6148 		opts->who = argv[0];
6149 	}
6150 
6151 	if (!opts->local && !opts->descend) {
6152 		opts->local = B_TRUE;
6153 		opts->descend = B_TRUE;
6154 	}
6155 }
6156 
6157 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)6158 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
6159     const char *who, char *perms, nvlist_t *top_nvl)
6160 {
6161 	int i;
6162 	char ld[2] = { '\0', '\0' };
6163 	char who_buf[MAXNAMELEN + 32];
6164 	char base_type = '\0';
6165 	char set_type = '\0';
6166 	nvlist_t *base_nvl = NULL;
6167 	nvlist_t *set_nvl = NULL;
6168 	nvlist_t *nvl;
6169 
6170 	if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
6171 		nomem();
6172 	if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
6173 		nomem();
6174 
6175 	switch (type) {
6176 	case ZFS_DELEG_NAMED_SET_SETS:
6177 	case ZFS_DELEG_NAMED_SET:
6178 		set_type = ZFS_DELEG_NAMED_SET_SETS;
6179 		base_type = ZFS_DELEG_NAMED_SET;
6180 		ld[0] = ZFS_DELEG_NA;
6181 		break;
6182 	case ZFS_DELEG_CREATE_SETS:
6183 	case ZFS_DELEG_CREATE:
6184 		set_type = ZFS_DELEG_CREATE_SETS;
6185 		base_type = ZFS_DELEG_CREATE;
6186 		ld[0] = ZFS_DELEG_NA;
6187 		break;
6188 	case ZFS_DELEG_USER_SETS:
6189 	case ZFS_DELEG_USER:
6190 		set_type = ZFS_DELEG_USER_SETS;
6191 		base_type = ZFS_DELEG_USER;
6192 		if (local)
6193 			ld[0] = ZFS_DELEG_LOCAL;
6194 		if (descend)
6195 			ld[1] = ZFS_DELEG_DESCENDENT;
6196 		break;
6197 	case ZFS_DELEG_GROUP_SETS:
6198 	case ZFS_DELEG_GROUP:
6199 		set_type = ZFS_DELEG_GROUP_SETS;
6200 		base_type = ZFS_DELEG_GROUP;
6201 		if (local)
6202 			ld[0] = ZFS_DELEG_LOCAL;
6203 		if (descend)
6204 			ld[1] = ZFS_DELEG_DESCENDENT;
6205 		break;
6206 	case ZFS_DELEG_EVERYONE_SETS:
6207 	case ZFS_DELEG_EVERYONE:
6208 		set_type = ZFS_DELEG_EVERYONE_SETS;
6209 		base_type = ZFS_DELEG_EVERYONE;
6210 		if (local)
6211 			ld[0] = ZFS_DELEG_LOCAL;
6212 		if (descend)
6213 			ld[1] = ZFS_DELEG_DESCENDENT;
6214 		break;
6215 
6216 	default:
6217 		assert(set_type != '\0' && base_type != '\0');
6218 	}
6219 
6220 	if (perms != NULL) {
6221 		char *curr = perms;
6222 		char *end = curr + strlen(perms);
6223 
6224 		while (curr < end) {
6225 			char *delim = strchr(curr, ',');
6226 			if (delim == NULL)
6227 				delim = end;
6228 			else
6229 				*delim = '\0';
6230 
6231 			if (curr[0] == '@')
6232 				nvl = set_nvl;
6233 			else
6234 				nvl = base_nvl;
6235 
6236 			(void) nvlist_add_boolean(nvl, curr);
6237 			if (delim != end)
6238 				*delim = ',';
6239 			curr = delim + 1;
6240 		}
6241 
6242 		for (i = 0; i < 2; i++) {
6243 			char locality = ld[i];
6244 			if (locality == 0)
6245 				continue;
6246 
6247 			if (!nvlist_empty(base_nvl)) {
6248 				if (who != NULL)
6249 					(void) snprintf(who_buf,
6250 					    sizeof (who_buf), "%c%c$%s",
6251 					    base_type, locality, who);
6252 				else
6253 					(void) snprintf(who_buf,
6254 					    sizeof (who_buf), "%c%c$",
6255 					    base_type, locality);
6256 
6257 				(void) nvlist_add_nvlist(top_nvl, who_buf,
6258 				    base_nvl);
6259 			}
6260 
6261 
6262 			if (!nvlist_empty(set_nvl)) {
6263 				if (who != NULL)
6264 					(void) snprintf(who_buf,
6265 					    sizeof (who_buf), "%c%c$%s",
6266 					    set_type, locality, who);
6267 				else
6268 					(void) snprintf(who_buf,
6269 					    sizeof (who_buf), "%c%c$",
6270 					    set_type, locality);
6271 
6272 				(void) nvlist_add_nvlist(top_nvl, who_buf,
6273 				    set_nvl);
6274 			}
6275 		}
6276 	} else {
6277 		for (i = 0; i < 2; i++) {
6278 			char locality = ld[i];
6279 			if (locality == 0)
6280 				continue;
6281 
6282 			if (who != NULL)
6283 				(void) snprintf(who_buf, sizeof (who_buf),
6284 				    "%c%c$%s", base_type, locality, who);
6285 			else
6286 				(void) snprintf(who_buf, sizeof (who_buf),
6287 				    "%c%c$", base_type, locality);
6288 			(void) nvlist_add_boolean(top_nvl, who_buf);
6289 
6290 			if (who != NULL)
6291 				(void) snprintf(who_buf, sizeof (who_buf),
6292 				    "%c%c$%s", set_type, locality, who);
6293 			else
6294 				(void) snprintf(who_buf, sizeof (who_buf),
6295 				    "%c%c$", set_type, locality);
6296 			(void) nvlist_add_boolean(top_nvl, who_buf);
6297 		}
6298 	}
6299 }
6300 
6301 static int
construct_fsacl_list(boolean_t un,struct allow_opts * opts,nvlist_t ** nvlp)6302 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
6303 {
6304 	if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
6305 		nomem();
6306 
6307 	if (opts->set) {
6308 		store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
6309 		    opts->descend, opts->who, opts->perms, *nvlp);
6310 	} else if (opts->create) {
6311 		store_allow_perm(ZFS_DELEG_CREATE, opts->local,
6312 		    opts->descend, NULL, opts->perms, *nvlp);
6313 	} else if (opts->everyone) {
6314 		store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
6315 		    opts->descend, NULL, opts->perms, *nvlp);
6316 	} else {
6317 		char *curr = opts->who;
6318 		char *end = curr + strlen(curr);
6319 
6320 		while (curr < end) {
6321 			const char *who;
6322 			zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
6323 			char *endch;
6324 			char *delim = strchr(curr, ',');
6325 			char errbuf[256];
6326 			char id[64];
6327 			struct passwd *p = NULL;
6328 			struct group *g = NULL;
6329 
6330 			uid_t rid;
6331 			if (delim == NULL)
6332 				delim = end;
6333 			else
6334 				*delim = '\0';
6335 
6336 			rid = (uid_t)strtol(curr, &endch, 0);
6337 			if (opts->user) {
6338 				who_type = ZFS_DELEG_USER;
6339 				if (*endch != '\0')
6340 					p = getpwnam(curr);
6341 				else
6342 					p = getpwuid(rid);
6343 
6344 				if (p != NULL)
6345 					rid = p->pw_uid;
6346 				else if (*endch != '\0') {
6347 					(void) snprintf(errbuf, sizeof (errbuf),
6348 					    gettext("invalid user %s\n"), curr);
6349 					allow_usage(un, B_TRUE, errbuf);
6350 				}
6351 			} else if (opts->group) {
6352 				who_type = ZFS_DELEG_GROUP;
6353 				if (*endch != '\0')
6354 					g = getgrnam(curr);
6355 				else
6356 					g = getgrgid(rid);
6357 
6358 				if (g != NULL)
6359 					rid = g->gr_gid;
6360 				else if (*endch != '\0') {
6361 					(void) snprintf(errbuf, sizeof (errbuf),
6362 					    gettext("invalid group %s\n"),
6363 					    curr);
6364 					allow_usage(un, B_TRUE, errbuf);
6365 				}
6366 			} else {
6367 				if (*endch != '\0') {
6368 					p = getpwnam(curr);
6369 				} else {
6370 					p = getpwuid(rid);
6371 				}
6372 
6373 				if (p == NULL) {
6374 					if (*endch != '\0') {
6375 						g = getgrnam(curr);
6376 					} else {
6377 						g = getgrgid(rid);
6378 					}
6379 				}
6380 
6381 				if (p != NULL) {
6382 					who_type = ZFS_DELEG_USER;
6383 					rid = p->pw_uid;
6384 				} else if (g != NULL) {
6385 					who_type = ZFS_DELEG_GROUP;
6386 					rid = g->gr_gid;
6387 				} else {
6388 					(void) snprintf(errbuf, sizeof (errbuf),
6389 					    gettext("invalid user/group %s\n"),
6390 					    curr);
6391 					allow_usage(un, B_TRUE, errbuf);
6392 				}
6393 			}
6394 
6395 			(void) sprintf(id, "%u", rid);
6396 			who = id;
6397 
6398 			store_allow_perm(who_type, opts->local,
6399 			    opts->descend, who, opts->perms, *nvlp);
6400 			curr = delim + 1;
6401 		}
6402 	}
6403 
6404 	return (0);
6405 }
6406 
6407 static void
print_set_creat_perms(uu_avl_t * who_avl)6408 print_set_creat_perms(uu_avl_t *who_avl)
6409 {
6410 	const char *sc_title[] = {
6411 		gettext("Permission sets:\n"),
6412 		gettext("Create time permissions:\n"),
6413 		NULL
6414 	};
6415 	who_perm_node_t *who_node = NULL;
6416 	int prev_weight = -1;
6417 
6418 	for (who_node = uu_avl_first(who_avl); who_node != NULL;
6419 	    who_node = uu_avl_next(who_avl, who_node)) {
6420 		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6421 		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6422 		const char *who_name = who_node->who_perm.who_name;
6423 		int weight = who_type2weight(who_type);
6424 		boolean_t first = B_TRUE;
6425 		deleg_perm_node_t *deleg_node;
6426 
6427 		if (prev_weight != weight) {
6428 			(void) printf("%s", sc_title[weight]);
6429 			prev_weight = weight;
6430 		}
6431 
6432 		if (who_name == NULL || strnlen(who_name, 1) == 0)
6433 			(void) printf("\t");
6434 		else
6435 			(void) printf("\t%s ", who_name);
6436 
6437 		for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
6438 		    deleg_node = uu_avl_next(avl, deleg_node)) {
6439 			if (first) {
6440 				(void) printf("%s",
6441 				    deleg_node->dpn_perm.dp_name);
6442 				first = B_FALSE;
6443 			} else
6444 				(void) printf(",%s",
6445 				    deleg_node->dpn_perm.dp_name);
6446 		}
6447 
6448 		(void) printf("\n");
6449 	}
6450 }
6451 
6452 static void
print_uge_deleg_perms(uu_avl_t * who_avl,boolean_t local,boolean_t descend,const char * title)6453 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
6454     const char *title)
6455 {
6456 	who_perm_node_t *who_node = NULL;
6457 	boolean_t prt_title = B_TRUE;
6458 	uu_avl_walk_t *walk;
6459 
6460 	if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
6461 		nomem();
6462 
6463 	while ((who_node = uu_avl_walk_next(walk)) != NULL) {
6464 		const char *who_name = who_node->who_perm.who_name;
6465 		const char *nice_who_name = who_node->who_perm.who_ug_name;
6466 		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6467 		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6468 		char delim = ' ';
6469 		deleg_perm_node_t *deleg_node;
6470 		boolean_t prt_who = B_TRUE;
6471 
6472 		for (deleg_node = uu_avl_first(avl);
6473 		    deleg_node != NULL;
6474 		    deleg_node = uu_avl_next(avl, deleg_node)) {
6475 			if (local != deleg_node->dpn_perm.dp_local ||
6476 			    descend != deleg_node->dpn_perm.dp_descend)
6477 				continue;
6478 
6479 			if (prt_who) {
6480 				const char *who = NULL;
6481 				if (prt_title) {
6482 					prt_title = B_FALSE;
6483 					(void) printf("%s", title);
6484 				}
6485 
6486 				switch (who_type) {
6487 				case ZFS_DELEG_USER_SETS:
6488 				case ZFS_DELEG_USER:
6489 					who = gettext("user");
6490 					if (nice_who_name)
6491 						who_name  = nice_who_name;
6492 					break;
6493 				case ZFS_DELEG_GROUP_SETS:
6494 				case ZFS_DELEG_GROUP:
6495 					who = gettext("group");
6496 					if (nice_who_name)
6497 						who_name  = nice_who_name;
6498 					break;
6499 				case ZFS_DELEG_EVERYONE_SETS:
6500 				case ZFS_DELEG_EVERYONE:
6501 					who = gettext("everyone");
6502 					who_name = NULL;
6503 					break;
6504 
6505 				default:
6506 					assert(who != NULL);
6507 				}
6508 
6509 				prt_who = B_FALSE;
6510 				if (who_name == NULL)
6511 					(void) printf("\t%s", who);
6512 				else
6513 					(void) printf("\t%s %s", who, who_name);
6514 			}
6515 
6516 			(void) printf("%c%s", delim,
6517 			    deleg_node->dpn_perm.dp_name);
6518 			delim = ',';
6519 		}
6520 
6521 		if (!prt_who)
6522 			(void) printf("\n");
6523 	}
6524 
6525 	uu_avl_walk_end(walk);
6526 }
6527 
6528 static void
print_fs_perms(fs_perm_set_t * fspset)6529 print_fs_perms(fs_perm_set_t *fspset)
6530 {
6531 	fs_perm_node_t *node = NULL;
6532 	char buf[MAXNAMELEN + 32];
6533 	const char *dsname = buf;
6534 
6535 	for (node = uu_list_first(fspset->fsps_list); node != NULL;
6536 	    node = uu_list_next(fspset->fsps_list, node)) {
6537 		uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
6538 		uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
6539 		int left = 0;
6540 
6541 		(void) snprintf(buf, sizeof (buf),
6542 		    gettext("---- Permissions on %s "),
6543 		    node->fspn_fsperm.fsp_name);
6544 		(void) printf("%s", dsname);
6545 		left = 70 - strlen(buf);
6546 		while (left-- > 0)
6547 			(void) printf("-");
6548 		(void) printf("\n");
6549 
6550 		print_set_creat_perms(sc_avl);
6551 		print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
6552 		    gettext("Local permissions:\n"));
6553 		print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
6554 		    gettext("Descendent permissions:\n"));
6555 		print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
6556 		    gettext("Local+Descendent permissions:\n"));
6557 	}
6558 }
6559 
6560 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
6561 
6562 struct deleg_perms {
6563 	boolean_t un;
6564 	nvlist_t *nvl;
6565 };
6566 
6567 static int
set_deleg_perms(zfs_handle_t * zhp,void * data)6568 set_deleg_perms(zfs_handle_t *zhp, void *data)
6569 {
6570 	struct deleg_perms *perms = (struct deleg_perms *)data;
6571 	zfs_type_t zfs_type = zfs_get_type(zhp);
6572 
6573 	if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
6574 		return (0);
6575 
6576 	return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
6577 }
6578 
6579 static int
zfs_do_allow_unallow_impl(int argc,char ** argv,boolean_t un)6580 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
6581 {
6582 	zfs_handle_t *zhp;
6583 	nvlist_t *perm_nvl = NULL;
6584 	nvlist_t *update_perm_nvl = NULL;
6585 	int error = 1;
6586 	int c;
6587 	struct allow_opts opts = { 0 };
6588 
6589 	const char *optstr = un ? "ldugecsrh" : "ldugecsh";
6590 
6591 	/* check opts */
6592 	while ((c = getopt(argc, argv, optstr)) != -1) {
6593 		switch (c) {
6594 		case 'l':
6595 			opts.local = B_TRUE;
6596 			break;
6597 		case 'd':
6598 			opts.descend = B_TRUE;
6599 			break;
6600 		case 'u':
6601 			opts.user = B_TRUE;
6602 			break;
6603 		case 'g':
6604 			opts.group = B_TRUE;
6605 			break;
6606 		case 'e':
6607 			opts.everyone = B_TRUE;
6608 			break;
6609 		case 's':
6610 			opts.set = B_TRUE;
6611 			break;
6612 		case 'c':
6613 			opts.create = B_TRUE;
6614 			break;
6615 		case 'r':
6616 			opts.recursive = B_TRUE;
6617 			break;
6618 		case ':':
6619 			(void) fprintf(stderr, gettext("missing argument for "
6620 			    "'%c' option\n"), optopt);
6621 			usage(B_FALSE);
6622 			break;
6623 		case 'h':
6624 			opts.prt_usage = B_TRUE;
6625 			break;
6626 		case '?':
6627 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6628 			    optopt);
6629 			usage(B_FALSE);
6630 		}
6631 	}
6632 
6633 	argc -= optind;
6634 	argv += optind;
6635 
6636 	/* check arguments */
6637 	parse_allow_args(argc, argv, un, &opts);
6638 
6639 	/* try to open the dataset */
6640 	if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
6641 	    ZFS_TYPE_VOLUME)) == NULL) {
6642 		(void) fprintf(stderr, "Failed to open dataset: %s\n",
6643 		    opts.dataset);
6644 		return (-1);
6645 	}
6646 
6647 	if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
6648 		goto cleanup2;
6649 
6650 	fs_perm_set_init(&fs_perm_set);
6651 	if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
6652 		(void) fprintf(stderr, "Failed to parse fsacl permissions\n");
6653 		goto cleanup1;
6654 	}
6655 
6656 	if (opts.prt_perms)
6657 		print_fs_perms(&fs_perm_set);
6658 	else {
6659 		(void) construct_fsacl_list(un, &opts, &update_perm_nvl);
6660 		if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
6661 			goto cleanup0;
6662 
6663 		if (un && opts.recursive) {
6664 			struct deleg_perms data = { un, update_perm_nvl };
6665 			if (zfs_iter_filesystems_v2(zhp, 0, set_deleg_perms,
6666 			    &data) != 0)
6667 				goto cleanup0;
6668 		}
6669 	}
6670 
6671 	error = 0;
6672 
6673 cleanup0:
6674 	nvlist_free(perm_nvl);
6675 	nvlist_free(update_perm_nvl);
6676 cleanup1:
6677 	fs_perm_set_fini(&fs_perm_set);
6678 cleanup2:
6679 	zfs_close(zhp);
6680 
6681 	return (error);
6682 }
6683 
6684 static int
zfs_do_allow(int argc,char ** argv)6685 zfs_do_allow(int argc, char **argv)
6686 {
6687 	return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
6688 }
6689 
6690 static int
zfs_do_unallow(int argc,char ** argv)6691 zfs_do_unallow(int argc, char **argv)
6692 {
6693 	return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
6694 }
6695 
6696 static int
zfs_do_hold_rele_impl(int argc,char ** argv,boolean_t holding)6697 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
6698 {
6699 	int errors = 0;
6700 	int i;
6701 	const char *tag;
6702 	boolean_t recursive = B_FALSE;
6703 	const char *opts = holding ? "rt" : "r";
6704 	int c;
6705 
6706 	/* check options */
6707 	while ((c = getopt(argc, argv, opts)) != -1) {
6708 		switch (c) {
6709 		case 'r':
6710 			recursive = B_TRUE;
6711 			break;
6712 		case '?':
6713 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6714 			    optopt);
6715 			usage(B_FALSE);
6716 		}
6717 	}
6718 
6719 	argc -= optind;
6720 	argv += optind;
6721 
6722 	/* check number of arguments */
6723 	if (argc < 2)
6724 		usage(B_FALSE);
6725 
6726 	tag = argv[0];
6727 	--argc;
6728 	++argv;
6729 
6730 	if (holding && tag[0] == '.') {
6731 		/* tags starting with '.' are reserved for libzfs */
6732 		(void) fprintf(stderr, gettext("tag may not start with '.'\n"));
6733 		usage(B_FALSE);
6734 	}
6735 
6736 	for (i = 0; i < argc; ++i) {
6737 		zfs_handle_t *zhp;
6738 		char parent[ZFS_MAX_DATASET_NAME_LEN];
6739 		const char *delim;
6740 		char *path = argv[i];
6741 
6742 		delim = strchr(path, '@');
6743 		if (delim == NULL) {
6744 			(void) fprintf(stderr,
6745 			    gettext("'%s' is not a snapshot\n"), path);
6746 			++errors;
6747 			continue;
6748 		}
6749 		(void) strlcpy(parent, path, MIN(sizeof (parent),
6750 		    delim - path + 1));
6751 
6752 		zhp = zfs_open(g_zfs, parent,
6753 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
6754 		if (zhp == NULL) {
6755 			++errors;
6756 			continue;
6757 		}
6758 		if (holding) {
6759 			if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
6760 				++errors;
6761 		} else {
6762 			if (zfs_release(zhp, delim+1, tag, recursive) != 0)
6763 				++errors;
6764 		}
6765 		zfs_close(zhp);
6766 	}
6767 
6768 	return (errors != 0);
6769 }
6770 
6771 /*
6772  * zfs hold [-r] [-t] <tag> <snap> ...
6773  *
6774  *	-r	Recursively hold
6775  *
6776  * Apply a user-hold with the given tag to the list of snapshots.
6777  */
6778 static int
zfs_do_hold(int argc,char ** argv)6779 zfs_do_hold(int argc, char **argv)
6780 {
6781 	return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
6782 }
6783 
6784 /*
6785  * zfs release [-r] <tag> <snap> ...
6786  *
6787  *	-r	Recursively release
6788  *
6789  * Release a user-hold with the given tag from the list of snapshots.
6790  */
6791 static int
zfs_do_release(int argc,char ** argv)6792 zfs_do_release(int argc, char **argv)
6793 {
6794 	return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
6795 }
6796 
6797 typedef struct holds_cbdata {
6798 	boolean_t	cb_recursive;
6799 	const char	*cb_snapname;
6800 	nvlist_t	**cb_nvlp;
6801 	size_t		cb_max_namelen;
6802 	size_t		cb_max_taglen;
6803 } holds_cbdata_t;
6804 
6805 #define	STRFTIME_FMT_STR "%a %b %e %H:%M %Y"
6806 #define	DATETIME_BUF_LEN (32)
6807 /*
6808  *
6809  */
6810 static void
print_holds(boolean_t scripted,int nwidth,int tagwidth,nvlist_t * nvl,boolean_t parsable)6811 print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl,
6812     boolean_t parsable)
6813 {
6814 	int i;
6815 	nvpair_t *nvp = NULL;
6816 	const char *const hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
6817 	const char *col;
6818 
6819 	if (!scripted) {
6820 		for (i = 0; i < 3; i++) {
6821 			col = gettext(hdr_cols[i]);
6822 			if (i < 2)
6823 				(void) printf("%-*s  ", i ? tagwidth : nwidth,
6824 				    col);
6825 			else
6826 				(void) printf("%s\n", col);
6827 		}
6828 	}
6829 
6830 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6831 		const char *zname = nvpair_name(nvp);
6832 		nvlist_t *nvl2;
6833 		nvpair_t *nvp2 = NULL;
6834 		(void) nvpair_value_nvlist(nvp, &nvl2);
6835 		while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
6836 			char tsbuf[DATETIME_BUF_LEN];
6837 			const char *tagname = nvpair_name(nvp2);
6838 			uint64_t val = 0;
6839 			time_t time;
6840 			struct tm t;
6841 
6842 			(void) nvpair_value_uint64(nvp2, &val);
6843 			time = (time_t)val;
6844 			(void) localtime_r(&time, &t);
6845 			(void) strftime(tsbuf, DATETIME_BUF_LEN,
6846 			    gettext(STRFTIME_FMT_STR), &t);
6847 
6848 			if (scripted) {
6849 				if (parsable) {
6850 					(void) printf("%s\t%s\t%ld\n", zname,
6851 					    tagname, (unsigned long)time);
6852 				} else {
6853 					(void) printf("%s\t%s\t%s\n", zname,
6854 					    tagname, tsbuf);
6855 				}
6856 			} else {
6857 				if (parsable) {
6858 					(void) printf("%-*s  %-*s  %ld\n",
6859 					    nwidth, zname, tagwidth,
6860 					    tagname, (unsigned long)time);
6861 				} else {
6862 					(void) printf("%-*s  %-*s  %s\n",
6863 					    nwidth, zname, tagwidth,
6864 					    tagname, tsbuf);
6865 				}
6866 			}
6867 		}
6868 	}
6869 }
6870 
6871 /*
6872  * Generic callback function to list a dataset or snapshot.
6873  */
6874 static int
holds_callback(zfs_handle_t * zhp,void * data)6875 holds_callback(zfs_handle_t *zhp, void *data)
6876 {
6877 	holds_cbdata_t *cbp = data;
6878 	nvlist_t *top_nvl = *cbp->cb_nvlp;
6879 	nvlist_t *nvl = NULL;
6880 	nvpair_t *nvp = NULL;
6881 	const char *zname = zfs_get_name(zhp);
6882 	size_t znamelen = strlen(zname);
6883 
6884 	if (cbp->cb_recursive) {
6885 		const char *snapname;
6886 		char *delim  = strchr(zname, '@');
6887 		if (delim == NULL)
6888 			return (0);
6889 
6890 		snapname = delim + 1;
6891 		if (strcmp(cbp->cb_snapname, snapname))
6892 			return (0);
6893 	}
6894 
6895 	if (zfs_get_holds(zhp, &nvl) != 0)
6896 		return (-1);
6897 
6898 	if (znamelen > cbp->cb_max_namelen)
6899 		cbp->cb_max_namelen  = znamelen;
6900 
6901 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6902 		const char *tag = nvpair_name(nvp);
6903 		size_t taglen = strlen(tag);
6904 		if (taglen > cbp->cb_max_taglen)
6905 			cbp->cb_max_taglen  = taglen;
6906 	}
6907 
6908 	return (nvlist_add_nvlist(top_nvl, zname, nvl));
6909 }
6910 
6911 /*
6912  * zfs holds [-rHp] <snap> ...
6913  *
6914  *	-r	Lists holds that are set on the named snapshots recursively.
6915  *	-H	Scripted mode; elide headers and separate columns by tabs.
6916  *	-p	Display values in parsable (literal) format.
6917  */
6918 static int
zfs_do_holds(int argc,char ** argv)6919 zfs_do_holds(int argc, char **argv)
6920 {
6921 	int c;
6922 	boolean_t errors = B_FALSE;
6923 	boolean_t scripted = B_FALSE;
6924 	boolean_t recursive = B_FALSE;
6925 	boolean_t parsable = B_FALSE;
6926 
6927 	int types = ZFS_TYPE_SNAPSHOT;
6928 	holds_cbdata_t cb = { 0 };
6929 
6930 	int limit = 0;
6931 	int ret = 0;
6932 	int flags = 0;
6933 
6934 	/* check options */
6935 	while ((c = getopt(argc, argv, "rHp")) != -1) {
6936 		switch (c) {
6937 		case 'r':
6938 			recursive = B_TRUE;
6939 			break;
6940 		case 'H':
6941 			scripted = B_TRUE;
6942 			break;
6943 		case 'p':
6944 			parsable = B_TRUE;
6945 			break;
6946 		case '?':
6947 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6948 			    optopt);
6949 			usage(B_FALSE);
6950 		}
6951 	}
6952 
6953 	if (recursive) {
6954 		types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
6955 		flags |= ZFS_ITER_RECURSE;
6956 	}
6957 
6958 	argc -= optind;
6959 	argv += optind;
6960 
6961 	/* check number of arguments */
6962 	if (argc < 1)
6963 		usage(B_FALSE);
6964 
6965 	nvlist_t *nvl = fnvlist_alloc();
6966 
6967 	for (int i = 0; i < argc; ++i) {
6968 		char *snapshot = argv[i];
6969 		const char *delim;
6970 		const char *snapname;
6971 
6972 		delim = strchr(snapshot, '@');
6973 		if (delim == NULL) {
6974 			(void) fprintf(stderr,
6975 			    gettext("'%s' is not a snapshot\n"), snapshot);
6976 			errors = B_TRUE;
6977 			continue;
6978 		}
6979 		snapname = delim + 1;
6980 		if (recursive)
6981 			snapshot[delim - snapshot] = '\0';
6982 
6983 		cb.cb_recursive = recursive;
6984 		cb.cb_snapname = snapname;
6985 		cb.cb_nvlp = &nvl;
6986 
6987 		/*
6988 		 *  1. collect holds data, set format options
6989 		 */
6990 		ret = zfs_for_each(1, argv + i, flags, types, NULL, NULL, limit,
6991 		    holds_callback, &cb);
6992 		if (ret != 0)
6993 			errors = B_TRUE;
6994 	}
6995 
6996 	/*
6997 	 *  2. print holds data
6998 	 */
6999 	print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl,
7000 	    parsable);
7001 
7002 	if (nvlist_empty(nvl))
7003 		(void) fprintf(stderr, gettext("no datasets available\n"));
7004 
7005 	nvlist_free(nvl);
7006 
7007 	return (errors);
7008 }
7009 
7010 #define	CHECK_SPINNER 30
7011 #define	SPINNER_TIME 3		/* seconds */
7012 #define	MOUNT_TIME 1		/* seconds */
7013 
7014 typedef struct get_all_state {
7015 	char		**ga_datasets;
7016 	int		ga_count;
7017 	boolean_t	ga_verbose;
7018 	get_all_cb_t	*ga_cbp;
7019 } get_all_state_t;
7020 
7021 static int
get_one_dataset(zfs_handle_t * zhp,void * data)7022 get_one_dataset(zfs_handle_t *zhp, void *data)
7023 {
7024 	static const char *const spin[] = { "-", "\\", "|", "/" };
7025 	static int spinval = 0;
7026 	static int spincheck = 0;
7027 	static time_t last_spin_time = (time_t)0;
7028 	get_all_state_t *state = data;
7029 	zfs_type_t type = zfs_get_type(zhp);
7030 
7031 	if (state->ga_verbose) {
7032 		if (--spincheck < 0) {
7033 			time_t now = time(NULL);
7034 			if (last_spin_time + SPINNER_TIME < now) {
7035 				update_progress(spin[spinval++ % 4]);
7036 				last_spin_time = now;
7037 			}
7038 			spincheck = CHECK_SPINNER;
7039 		}
7040 	}
7041 
7042 	/*
7043 	 * Iterate over any nested datasets.
7044 	 */
7045 	if (zfs_iter_filesystems_v2(zhp, 0, get_one_dataset, data) != 0) {
7046 		zfs_close(zhp);
7047 		return (1);
7048 	}
7049 
7050 	/*
7051 	 * Skip any datasets whose type does not match.
7052 	 */
7053 	if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
7054 		zfs_close(zhp);
7055 		return (0);
7056 	}
7057 	libzfs_add_handle(state->ga_cbp, zhp);
7058 	assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
7059 
7060 	return (0);
7061 }
7062 
7063 static int
get_recursive_datasets(zfs_handle_t * zhp,void * data)7064 get_recursive_datasets(zfs_handle_t *zhp, void *data)
7065 {
7066 	get_all_state_t *state = data;
7067 	int len = strlen(zfs_get_name(zhp));
7068 	for (int i = 0; i < state->ga_count; ++i) {
7069 		if (strcmp(state->ga_datasets[i], zfs_get_name(zhp)) == 0)
7070 			return (get_one_dataset(zhp, data));
7071 		else if ((strncmp(state->ga_datasets[i], zfs_get_name(zhp),
7072 		    len) == 0) && state->ga_datasets[i][len] == '/') {
7073 			(void) zfs_iter_filesystems_v2(zhp, 0,
7074 			    get_recursive_datasets, data);
7075 		}
7076 	}
7077 	zfs_close(zhp);
7078 	return (0);
7079 }
7080 
7081 static void
get_all_datasets(get_all_state_t * state)7082 get_all_datasets(get_all_state_t *state)
7083 {
7084 	if (state->ga_verbose)
7085 		set_progress_header(gettext("Reading ZFS config"));
7086 	if (state->ga_datasets == NULL)
7087 		(void) zfs_iter_root(g_zfs, get_one_dataset, state);
7088 	else
7089 		(void) zfs_iter_root(g_zfs, get_recursive_datasets, state);
7090 
7091 	if (state->ga_verbose)
7092 		finish_progress(gettext("done."));
7093 }
7094 
7095 /*
7096  * Generic callback for sharing or mounting filesystems.  Because the code is so
7097  * similar, we have a common function with an extra parameter to determine which
7098  * mode we are using.
7099  */
7100 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
7101 
7102 typedef struct share_mount_state {
7103 	share_mount_op_t	sm_op;
7104 	boolean_t	sm_verbose;
7105 	int	sm_flags;
7106 	char	*sm_options;
7107 	enum sa_protocol	sm_proto; /* only valid for OP_SHARE */
7108 	pthread_mutex_t	sm_lock; /* protects the remaining fields */
7109 	uint_t	sm_total; /* number of filesystems to process */
7110 	uint_t	sm_done; /* number of filesystems processed */
7111 	int	sm_status; /* -1 if any of the share/mount operations failed */
7112 } share_mount_state_t;
7113 
7114 /*
7115  * Share or mount a dataset.
7116  */
7117 static int
share_mount_one(zfs_handle_t * zhp,int op,int flags,enum sa_protocol protocol,boolean_t explicit,const char * options)7118 share_mount_one(zfs_handle_t *zhp, int op, int flags, enum sa_protocol protocol,
7119     boolean_t explicit, const char *options)
7120 {
7121 	char mountpoint[ZFS_MAXPROPLEN];
7122 	char shareopts[ZFS_MAXPROPLEN];
7123 	char smbshareopts[ZFS_MAXPROPLEN];
7124 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
7125 	struct mnttab mnt;
7126 	uint64_t zoned, canmount;
7127 	boolean_t shared_nfs, shared_smb;
7128 
7129 	assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
7130 
7131 	/*
7132 	 * Check to make sure we can mount/share this dataset.  If we
7133 	 * are in the global zone and the filesystem is exported to a
7134 	 * local zone, or if we are in a local zone and the
7135 	 * filesystem is not exported, then it is an error.
7136 	 */
7137 	zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
7138 
7139 	if (zoned && getzoneid() == GLOBAL_ZONEID) {
7140 		if (!explicit)
7141 			return (0);
7142 
7143 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7144 		    "dataset is exported to a local zone\n"), cmdname,
7145 		    zfs_get_name(zhp));
7146 		return (1);
7147 
7148 	} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
7149 		if (!explicit)
7150 			return (0);
7151 
7152 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7153 		    "permission denied\n"), cmdname,
7154 		    zfs_get_name(zhp));
7155 		return (1);
7156 	}
7157 
7158 	/*
7159 	 * Ignore any filesystems which don't apply to us. This
7160 	 * includes those with a legacy mountpoint, or those with
7161 	 * legacy share options.
7162 	 */
7163 	verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
7164 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
7165 	verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
7166 	    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
7167 	verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
7168 	    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
7169 
7170 	if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
7171 	    strcmp(smbshareopts, "off") == 0) {
7172 		if (!explicit)
7173 			return (0);
7174 
7175 		(void) fprintf(stderr, gettext("cannot share '%s': "
7176 		    "legacy share\n"), zfs_get_name(zhp));
7177 		(void) fprintf(stderr, gettext("use exports(5) or "
7178 		    "smb.conf(5) to share this filesystem, or set "
7179 		    "the sharenfs or sharesmb property\n"));
7180 		return (1);
7181 	}
7182 
7183 	/*
7184 	 * We cannot share or mount legacy filesystems. If the
7185 	 * shareopts is non-legacy but the mountpoint is legacy, we
7186 	 * treat it as a legacy share.
7187 	 */
7188 	if (strcmp(mountpoint, "legacy") == 0) {
7189 		if (!explicit)
7190 			return (0);
7191 
7192 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7193 		    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
7194 		(void) fprintf(stderr, gettext("use %s(8) to "
7195 		    "%s this filesystem\n"), cmdname, cmdname);
7196 		return (1);
7197 	}
7198 
7199 	if (strcmp(mountpoint, "none") == 0) {
7200 		if (!explicit)
7201 			return (0);
7202 
7203 		(void) fprintf(stderr, gettext("cannot %s '%s': no "
7204 		    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
7205 		return (1);
7206 	}
7207 
7208 	/*
7209 	 * canmount	explicit	outcome
7210 	 * on		no		pass through
7211 	 * on		yes		pass through
7212 	 * off		no		return 0
7213 	 * off		yes		display error, return 1
7214 	 * noauto	no		return 0
7215 	 * noauto	yes		pass through
7216 	 */
7217 	canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
7218 	if (canmount == ZFS_CANMOUNT_OFF) {
7219 		if (!explicit)
7220 			return (0);
7221 
7222 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7223 		    "'canmount' property is set to 'off'\n"), cmdname,
7224 		    zfs_get_name(zhp));
7225 		return (1);
7226 	} else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
7227 		/*
7228 		 * When performing a 'zfs mount -a', we skip any mounts for
7229 		 * datasets that have 'noauto' set. Sharing a dataset with
7230 		 * 'noauto' set is only allowed if it's mounted.
7231 		 */
7232 		if (op == OP_MOUNT)
7233 			return (0);
7234 		if (op == OP_SHARE && !zfs_is_mounted(zhp, NULL)) {
7235 			/* also purge it from existing exports */
7236 			zfs_unshare(zhp, mountpoint, NULL);
7237 			return (0);
7238 		}
7239 	}
7240 
7241 	/*
7242 	 * If this filesystem is encrypted and does not have
7243 	 * a loaded key, we can not mount it.
7244 	 */
7245 	if ((flags & MS_CRYPT) == 0 &&
7246 	    zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
7247 	    zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
7248 	    ZFS_KEYSTATUS_UNAVAILABLE) {
7249 		if (!explicit)
7250 			return (0);
7251 
7252 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7253 		    "encryption key not loaded\n"), cmdname, zfs_get_name(zhp));
7254 		return (1);
7255 	}
7256 
7257 	/*
7258 	 * If this filesystem is inconsistent and has a receive resume
7259 	 * token, we can not mount it.
7260 	 */
7261 	if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
7262 	    zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
7263 	    NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
7264 		if (!explicit)
7265 			return (0);
7266 
7267 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7268 		    "Contains partially-completed state from "
7269 		    "\"zfs receive -s\", which can be resumed with "
7270 		    "\"zfs send -t\"\n"),
7271 		    cmdname, zfs_get_name(zhp));
7272 		return (1);
7273 	}
7274 
7275 	if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE)) {
7276 		if (!explicit)
7277 			return (0);
7278 
7279 		(void) fprintf(stderr, gettext("cannot %s '%s': "
7280 		    "Dataset is not complete, was created by receiving "
7281 		    "a redacted zfs send stream.\n"), cmdname,
7282 		    zfs_get_name(zhp));
7283 		return (1);
7284 	}
7285 
7286 	/*
7287 	 * At this point, we have verified that the mountpoint and/or
7288 	 * shareopts are appropriate for auto management. If the
7289 	 * filesystem is already mounted or shared, return (failing
7290 	 * for explicit requests); otherwise mount or share the
7291 	 * filesystem.
7292 	 */
7293 	switch (op) {
7294 	case OP_SHARE: {
7295 		enum sa_protocol prot[] = {SA_PROTOCOL_NFS, SA_NO_PROTOCOL};
7296 		shared_nfs = zfs_is_shared(zhp, NULL, prot);
7297 		*prot = SA_PROTOCOL_SMB;
7298 		shared_smb = zfs_is_shared(zhp, NULL, prot);
7299 
7300 		if ((shared_nfs && shared_smb) ||
7301 		    (shared_nfs && strcmp(shareopts, "on") == 0 &&
7302 		    strcmp(smbshareopts, "off") == 0) ||
7303 		    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
7304 		    strcmp(shareopts, "off") == 0)) {
7305 			if (!explicit)
7306 				return (0);
7307 
7308 			(void) fprintf(stderr, gettext("cannot share "
7309 			    "'%s': filesystem already shared\n"),
7310 			    zfs_get_name(zhp));
7311 			return (1);
7312 		}
7313 
7314 		if (!zfs_is_mounted(zhp, NULL) &&
7315 		    zfs_mount(zhp, NULL, flags) != 0)
7316 			return (1);
7317 
7318 		*prot = protocol;
7319 		if (zfs_share(zhp, protocol == SA_NO_PROTOCOL ? NULL : prot))
7320 			return (1);
7321 
7322 	}
7323 		break;
7324 
7325 	case OP_MOUNT:
7326 		mnt.mnt_mntopts = (char *)(options ?: "");
7327 
7328 		if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
7329 		    zfs_is_mounted(zhp, NULL)) {
7330 			if (!explicit)
7331 				return (0);
7332 
7333 			(void) fprintf(stderr, gettext("cannot mount "
7334 			    "'%s': filesystem already mounted\n"),
7335 			    zfs_get_name(zhp));
7336 			return (1);
7337 		}
7338 
7339 		if (zfs_mount(zhp, options, flags) != 0)
7340 			return (1);
7341 		break;
7342 	}
7343 
7344 	return (0);
7345 }
7346 
7347 /*
7348  * Reports progress in the form "(current/total)".  Not thread-safe.
7349  */
7350 static void
report_mount_progress(int current,int total)7351 report_mount_progress(int current, int total)
7352 {
7353 	static time_t last_progress_time = 0;
7354 	time_t now = time(NULL);
7355 	char info[32];
7356 
7357 	/* display header if we're here for the first time */
7358 	if (current == 1) {
7359 		set_progress_header(gettext("Mounting ZFS filesystems"));
7360 	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
7361 		/* too soon to report again */
7362 		return;
7363 	}
7364 
7365 	last_progress_time = now;
7366 
7367 	(void) sprintf(info, "(%d/%d)", current, total);
7368 
7369 	if (current == total)
7370 		finish_progress(info);
7371 	else
7372 		update_progress(info);
7373 }
7374 
7375 /*
7376  * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
7377  * updates the progress meter.
7378  */
7379 static int
share_mount_one_cb(zfs_handle_t * zhp,void * arg)7380 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
7381 {
7382 	share_mount_state_t *sms = arg;
7383 	int ret;
7384 
7385 	ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
7386 	    B_FALSE, sms->sm_options);
7387 
7388 	pthread_mutex_lock(&sms->sm_lock);
7389 	if (ret != 0)
7390 		sms->sm_status = ret;
7391 	sms->sm_done++;
7392 	if (sms->sm_verbose)
7393 		report_mount_progress(sms->sm_done, sms->sm_total);
7394 	pthread_mutex_unlock(&sms->sm_lock);
7395 	return (ret);
7396 }
7397 
7398 static void
append_options(char * mntopts,char * newopts)7399 append_options(char *mntopts, char *newopts)
7400 {
7401 	int len = strlen(mntopts);
7402 
7403 	/* original length plus new string to append plus 1 for the comma */
7404 	if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
7405 		(void) fprintf(stderr, gettext("the opts argument for "
7406 		    "'%s' option is too long (more than %d chars)\n"),
7407 		    "-o", MNT_LINE_MAX);
7408 		usage(B_FALSE);
7409 	}
7410 
7411 	if (*mntopts)
7412 		mntopts[len++] = ',';
7413 
7414 	(void) strcpy(&mntopts[len], newopts);
7415 }
7416 
7417 static enum sa_protocol
sa_protocol_decode(const char * protocol)7418 sa_protocol_decode(const char *protocol)
7419 {
7420 	for (enum sa_protocol i = 0; i < ARRAY_SIZE(sa_protocol_names); ++i)
7421 		if (strcmp(protocol, sa_protocol_names[i]) == 0)
7422 			return (i);
7423 
7424 	(void) fputs(gettext("share type must be one of: "), stderr);
7425 	for (enum sa_protocol i = 0;
7426 	    i < ARRAY_SIZE(sa_protocol_names); ++i)
7427 		(void) fprintf(stderr, "%s%s",
7428 		    i != 0 ? ", " : "", sa_protocol_names[i]);
7429 	(void) fputc('\n', stderr);
7430 	usage(B_FALSE);
7431 }
7432 
7433 static int
share_mount(int op,int argc,char ** argv)7434 share_mount(int op, int argc, char **argv)
7435 {
7436 	int do_all = 0;
7437 	int recursive = 0;
7438 	boolean_t verbose = B_FALSE;
7439 	boolean_t json = B_FALSE;
7440 	int c, ret = 0;
7441 	char *options = NULL;
7442 	int flags = 0;
7443 	nvlist_t *jsobj, *data, *item;
7444 	const uint_t mount_nthr = 512;
7445 	uint_t nthr;
7446 	jsobj = data = item = NULL;
7447 
7448 	struct option long_options[] = {
7449 		{"json", no_argument, NULL, 'j'},
7450 		{0, 0, 0, 0}
7451 	};
7452 
7453 	/* check options */
7454 	while ((c = getopt_long(argc, argv,
7455 	    op == OP_MOUNT ? ":ajRlvo:Of" : "al",
7456 	    op == OP_MOUNT ? long_options : NULL, NULL)) != -1) {
7457 		switch (c) {
7458 		case 'a':
7459 			do_all = 1;
7460 			break;
7461 		case 'R':
7462 			recursive = 1;
7463 			break;
7464 		case 'v':
7465 			verbose = B_TRUE;
7466 			break;
7467 		case 'l':
7468 			flags |= MS_CRYPT;
7469 			break;
7470 		case 'j':
7471 			json = B_TRUE;
7472 			jsobj = zfs_json_schema(0, 1);
7473 			data = fnvlist_alloc();
7474 			break;
7475 		case 'o':
7476 			if (*optarg == '\0') {
7477 				(void) fprintf(stderr, gettext("empty mount "
7478 				    "options (-o) specified\n"));
7479 				usage(B_FALSE);
7480 			}
7481 
7482 			if (options == NULL)
7483 				options = safe_malloc(MNT_LINE_MAX + 1);
7484 
7485 			/* option validation is done later */
7486 			append_options(options, optarg);
7487 			break;
7488 		case 'O':
7489 			flags |= MS_OVERLAY;
7490 			break;
7491 		case 'f':
7492 			flags |= MS_FORCE;
7493 			break;
7494 		case ':':
7495 			(void) fprintf(stderr, gettext("missing argument for "
7496 			    "'%c' option\n"), optopt);
7497 			usage(B_FALSE);
7498 			break;
7499 		case '?':
7500 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7501 			    optopt);
7502 			usage(B_FALSE);
7503 		}
7504 	}
7505 
7506 	argc -= optind;
7507 	argv += optind;
7508 
7509 	if (json && argc != 0) {
7510 		(void) fprintf(stderr, gettext("too many arguments\n"));
7511 		usage(B_FALSE);
7512 	}
7513 
7514 	/* check number of arguments */
7515 	if (do_all || recursive) {
7516 		enum sa_protocol protocol = SA_NO_PROTOCOL;
7517 
7518 		if (op == OP_SHARE && argc > 0) {
7519 			protocol = sa_protocol_decode(argv[0]);
7520 			argc--;
7521 			argv++;
7522 		}
7523 
7524 		if (argc != 0 && do_all) {
7525 			(void) fprintf(stderr, gettext("too many arguments\n"));
7526 			usage(B_FALSE);
7527 		}
7528 
7529 		if (argc == 0 && recursive) {
7530 			(void) fprintf(stderr,
7531 			    gettext("no dataset provided\n"));
7532 			usage(B_FALSE);
7533 		}
7534 
7535 		start_progress_timer();
7536 		get_all_cb_t cb = { 0 };
7537 		get_all_state_t state = { 0 };
7538 		if (argc == 0) {
7539 			state.ga_datasets = NULL;
7540 			state.ga_count = -1;
7541 		} else {
7542 			zfs_handle_t *zhp;
7543 			for (int i = 0; i < argc; i++) {
7544 				zhp = zfs_open(g_zfs, argv[i],
7545 				    ZFS_TYPE_FILESYSTEM);
7546 				if (zhp == NULL)
7547 					usage(B_FALSE);
7548 				zfs_close(zhp);
7549 			}
7550 			state.ga_datasets = argv;
7551 			state.ga_count = argc;
7552 		}
7553 		state.ga_verbose = verbose;
7554 		state.ga_cbp = &cb;
7555 		get_all_datasets(&state);
7556 
7557 		if (cb.cb_used == 0) {
7558 			free(options);
7559 			return (0);
7560 		}
7561 
7562 		share_mount_state_t share_mount_state = { 0 };
7563 		share_mount_state.sm_op = op;
7564 		share_mount_state.sm_verbose = verbose;
7565 		share_mount_state.sm_flags = flags;
7566 		share_mount_state.sm_options = options;
7567 		share_mount_state.sm_proto = protocol;
7568 		share_mount_state.sm_total = cb.cb_used;
7569 		pthread_mutex_init(&share_mount_state.sm_lock, NULL);
7570 
7571 		/* For a 'zfs share -a' operation start with a clean slate. */
7572 		if (op == OP_SHARE)
7573 			zfs_truncate_shares(NULL);
7574 
7575 		/*
7576 		 * libshare isn't mt-safe, so only do the operation in parallel
7577 		 * if we're mounting. Additionally, the key-loading option must
7578 		 * be serialized so that we can prompt the user for their keys
7579 		 * in a consistent manner.
7580 		 */
7581 		nthr = op == OP_MOUNT && !(flags & MS_CRYPT) ? mount_nthr : 1;
7582 		zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
7583 		    share_mount_one_cb, &share_mount_state, nthr);
7584 		zfs_commit_shares(NULL);
7585 
7586 		ret = share_mount_state.sm_status;
7587 
7588 		for (int i = 0; i < cb.cb_used; i++)
7589 			zfs_close(cb.cb_handles[i]);
7590 		free(cb.cb_handles);
7591 	} else if (argc == 0) {
7592 		FILE *mnttab;
7593 		struct mnttab entry;
7594 
7595 		if ((op == OP_SHARE) || (options != NULL)) {
7596 			(void) fprintf(stderr, gettext("missing filesystem "
7597 			    "argument (specify -a for all)\n"));
7598 			usage(B_FALSE);
7599 		}
7600 
7601 		/*
7602 		 * When mount is given no arguments, go through
7603 		 * /proc/self/mounts and display any active ZFS mounts.
7604 		 * We hide any snapshots, since they are controlled
7605 		 * automatically.
7606 		 */
7607 
7608 		if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7609 			free(options);
7610 			return (ENOENT);
7611 		}
7612 
7613 		while (getmntent(mnttab, &entry) == 0) {
7614 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
7615 			    strchr(entry.mnt_special, '@') != NULL)
7616 				continue;
7617 			if (json) {
7618 				item = fnvlist_alloc();
7619 				fnvlist_add_string(item, "filesystem",
7620 				    entry.mnt_special);
7621 				fnvlist_add_string(item, "mountpoint",
7622 				    entry.mnt_mountp);
7623 				fnvlist_add_nvlist(data, entry.mnt_special,
7624 				    item);
7625 				fnvlist_free(item);
7626 			} else {
7627 				(void) printf("%-30s  %s\n", entry.mnt_special,
7628 				    entry.mnt_mountp);
7629 			}
7630 		}
7631 
7632 		(void) fclose(mnttab);
7633 		if (json) {
7634 			fnvlist_add_nvlist(jsobj, "datasets", data);
7635 			if (nvlist_empty(data))
7636 				fnvlist_free(jsobj);
7637 			else
7638 				zcmd_print_json(jsobj);
7639 			fnvlist_free(data);
7640 		}
7641 	} else {
7642 		zfs_handle_t *zhp;
7643 
7644 		if (argc > 1) {
7645 			(void) fprintf(stderr,
7646 			    gettext("too many arguments\n"));
7647 			usage(B_FALSE);
7648 		}
7649 
7650 		if ((zhp = zfs_open(g_zfs, argv[0],
7651 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
7652 			ret = 1;
7653 		} else {
7654 			ret = share_mount_one(zhp, op, flags, SA_NO_PROTOCOL,
7655 			    B_TRUE, options);
7656 			zfs_commit_shares(NULL);
7657 			zfs_close(zhp);
7658 		}
7659 	}
7660 
7661 	free(options);
7662 	return (ret);
7663 }
7664 
7665 /*
7666  * zfs mount -a
7667  * zfs mount filesystem
7668  *
7669  * Mount all filesystems, or mount the given filesystem.
7670  */
7671 static int
zfs_do_mount(int argc,char ** argv)7672 zfs_do_mount(int argc, char **argv)
7673 {
7674 	return (share_mount(OP_MOUNT, argc, argv));
7675 }
7676 
7677 /*
7678  * zfs share -a [nfs | smb]
7679  * zfs share filesystem
7680  *
7681  * Share all filesystems, or share the given filesystem.
7682  */
7683 static int
zfs_do_share(int argc,char ** argv)7684 zfs_do_share(int argc, char **argv)
7685 {
7686 	return (share_mount(OP_SHARE, argc, argv));
7687 }
7688 
7689 typedef struct unshare_unmount_node {
7690 	zfs_handle_t	*un_zhp;
7691 	char		*un_mountp;
7692 	uu_avl_node_t	un_avlnode;
7693 } unshare_unmount_node_t;
7694 
7695 static int
unshare_unmount_compare(const void * larg,const void * rarg,void * unused)7696 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
7697 {
7698 	(void) unused;
7699 	const unshare_unmount_node_t *l = larg;
7700 	const unshare_unmount_node_t *r = rarg;
7701 
7702 	return (strcmp(l->un_mountp, r->un_mountp));
7703 }
7704 
7705 /*
7706  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
7707  * absolute path, find the entry /proc/self/mounts, verify that it's a
7708  * ZFS filesystem, and unmount it appropriately.
7709  */
7710 static int
unshare_unmount_path(int op,char * path,int flags,boolean_t is_manual)7711 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
7712 {
7713 	zfs_handle_t *zhp;
7714 	int ret = 0;
7715 	struct stat64 statbuf;
7716 	struct extmnttab entry;
7717 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
7718 	ino_t path_inode;
7719 
7720 	/*
7721 	 * Search for the given (major,minor) pair in the mount table.
7722 	 */
7723 
7724 	if (getextmntent(path, &entry, &statbuf) != 0) {
7725 		if (op == OP_SHARE) {
7726 			(void) fprintf(stderr, gettext("cannot %s '%s': not "
7727 			    "currently mounted\n"), cmdname, path);
7728 			return (1);
7729 		}
7730 		(void) fprintf(stderr, gettext("warning: %s not in"
7731 		    "/proc/self/mounts\n"), path);
7732 		if ((ret = umount2(path, flags)) != 0)
7733 			(void) fprintf(stderr, gettext("%s: %s\n"), path,
7734 			    strerror(errno));
7735 		return (ret != 0);
7736 	}
7737 	path_inode = statbuf.st_ino;
7738 
7739 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
7740 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
7741 		    "filesystem\n"), cmdname, path);
7742 		return (1);
7743 	}
7744 
7745 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7746 	    ZFS_TYPE_FILESYSTEM)) == NULL)
7747 		return (1);
7748 
7749 	ret = 1;
7750 	if (stat64(entry.mnt_mountp, &statbuf) != 0) {
7751 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
7752 		    cmdname, path, strerror(errno));
7753 		goto out;
7754 	} else if (statbuf.st_ino != path_inode) {
7755 		(void) fprintf(stderr, gettext("cannot "
7756 		    "%s '%s': not a mountpoint\n"), cmdname, path);
7757 		goto out;
7758 	}
7759 
7760 	if (op == OP_SHARE) {
7761 		char nfs_mnt_prop[ZFS_MAXPROPLEN];
7762 		char smbshare_prop[ZFS_MAXPROPLEN];
7763 
7764 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
7765 		    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
7766 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
7767 		    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
7768 
7769 		if (strcmp(nfs_mnt_prop, "off") == 0 &&
7770 		    strcmp(smbshare_prop, "off") == 0) {
7771 			(void) fprintf(stderr, gettext("cannot unshare "
7772 			    "'%s': legacy share\n"), path);
7773 			(void) fprintf(stderr, gettext("use exportfs(8) "
7774 			    "or smbcontrol(1) to unshare this filesystem\n"));
7775 		} else if (!zfs_is_shared(zhp, NULL, NULL)) {
7776 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
7777 			    "not currently shared\n"), path);
7778 		} else {
7779 			ret = zfs_unshare(zhp, path, NULL);
7780 			zfs_commit_shares(NULL);
7781 		}
7782 	} else {
7783 		char mtpt_prop[ZFS_MAXPROPLEN];
7784 
7785 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
7786 		    sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
7787 
7788 		if (is_manual) {
7789 			ret = zfs_unmount(zhp, NULL, flags);
7790 		} else if (strcmp(mtpt_prop, "legacy") == 0) {
7791 			(void) fprintf(stderr, gettext("cannot unmount "
7792 			    "'%s': legacy mountpoint\n"),
7793 			    zfs_get_name(zhp));
7794 			(void) fprintf(stderr, gettext("use umount(8) "
7795 			    "to unmount this filesystem\n"));
7796 		} else {
7797 			ret = zfs_unmountall(zhp, flags);
7798 		}
7799 	}
7800 
7801 out:
7802 	zfs_close(zhp);
7803 
7804 	return (ret != 0);
7805 }
7806 
7807 /*
7808  * Generic callback for unsharing or unmounting a filesystem.
7809  */
7810 static int
unshare_unmount(int op,int argc,char ** argv)7811 unshare_unmount(int op, int argc, char **argv)
7812 {
7813 	int do_all = 0;
7814 	int flags = 0;
7815 	int ret = 0;
7816 	int c;
7817 	zfs_handle_t *zhp;
7818 	char nfs_mnt_prop[ZFS_MAXPROPLEN];
7819 	char sharesmb[ZFS_MAXPROPLEN];
7820 
7821 	/* check options */
7822 	while ((c = getopt(argc, argv, op == OP_SHARE ? ":a" : "afu")) != -1) {
7823 		switch (c) {
7824 		case 'a':
7825 			do_all = 1;
7826 			break;
7827 		case 'f':
7828 			flags |= MS_FORCE;
7829 			break;
7830 		case 'u':
7831 			flags |= MS_CRYPT;
7832 			break;
7833 		case ':':
7834 			(void) fprintf(stderr, gettext("missing argument for "
7835 			    "'%c' option\n"), optopt);
7836 			usage(B_FALSE);
7837 			break;
7838 		case '?':
7839 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
7840 			    optopt);
7841 			usage(B_FALSE);
7842 		}
7843 	}
7844 
7845 	argc -= optind;
7846 	argv += optind;
7847 
7848 	if (do_all) {
7849 		/*
7850 		 * We could make use of zfs_for_each() to walk all datasets in
7851 		 * the system, but this would be very inefficient, especially
7852 		 * since we would have to linearly search /proc/self/mounts for
7853 		 * each one. Instead, do one pass through /proc/self/mounts
7854 		 * looking for zfs entries and call zfs_unmount() for each one.
7855 		 *
7856 		 * Things get a little tricky if the administrator has created
7857 		 * mountpoints beneath other ZFS filesystems.  In this case, we
7858 		 * have to unmount the deepest filesystems first.  To accomplish
7859 		 * this, we place all the mountpoints in an AVL tree sorted by
7860 		 * the special type (dataset name), and walk the result in
7861 		 * reverse to make sure to get any snapshots first.
7862 		 */
7863 		FILE *mnttab;
7864 		struct mnttab entry;
7865 		uu_avl_pool_t *pool;
7866 		uu_avl_t *tree = NULL;
7867 		unshare_unmount_node_t *node;
7868 		uu_avl_index_t idx;
7869 		uu_avl_walk_t *walk;
7870 		enum sa_protocol *protocol = NULL,
7871 		    single_protocol[] = {SA_NO_PROTOCOL, SA_NO_PROTOCOL};
7872 
7873 		if (op == OP_SHARE && argc > 0) {
7874 			*single_protocol = sa_protocol_decode(argv[0]);
7875 			protocol = single_protocol;
7876 			argc--;
7877 			argv++;
7878 		}
7879 
7880 		if (argc != 0) {
7881 			(void) fprintf(stderr, gettext("too many arguments\n"));
7882 			usage(B_FALSE);
7883 		}
7884 
7885 		if (((pool = uu_avl_pool_create("unmount_pool",
7886 		    sizeof (unshare_unmount_node_t),
7887 		    offsetof(unshare_unmount_node_t, un_avlnode),
7888 		    unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
7889 		    ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
7890 			nomem();
7891 
7892 		if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7893 			uu_avl_destroy(tree);
7894 			uu_avl_pool_destroy(pool);
7895 			return (ENOENT);
7896 		}
7897 
7898 		while (getmntent(mnttab, &entry) == 0) {
7899 
7900 			/* ignore non-ZFS entries */
7901 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
7902 				continue;
7903 
7904 			/* ignore snapshots */
7905 			if (strchr(entry.mnt_special, '@') != NULL)
7906 				continue;
7907 
7908 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7909 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
7910 				ret = 1;
7911 				continue;
7912 			}
7913 
7914 			/*
7915 			 * Ignore datasets that are excluded/restricted by
7916 			 * parent pool name.
7917 			 */
7918 			if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
7919 				zfs_close(zhp);
7920 				continue;
7921 			}
7922 
7923 			switch (op) {
7924 			case OP_SHARE:
7925 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7926 				    nfs_mnt_prop,
7927 				    sizeof (nfs_mnt_prop),
7928 				    NULL, NULL, 0, B_FALSE) == 0);
7929 				if (strcmp(nfs_mnt_prop, "off") != 0)
7930 					break;
7931 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7932 				    nfs_mnt_prop,
7933 				    sizeof (nfs_mnt_prop),
7934 				    NULL, NULL, 0, B_FALSE) == 0);
7935 				if (strcmp(nfs_mnt_prop, "off") == 0)
7936 					continue;
7937 				break;
7938 			case OP_MOUNT:
7939 				/* Ignore legacy mounts */
7940 				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
7941 				    nfs_mnt_prop,
7942 				    sizeof (nfs_mnt_prop),
7943 				    NULL, NULL, 0, B_FALSE) == 0);
7944 				if (strcmp(nfs_mnt_prop, "legacy") == 0)
7945 					continue;
7946 				/* Ignore canmount=noauto mounts */
7947 				if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
7948 				    ZFS_CANMOUNT_NOAUTO)
7949 					continue;
7950 				break;
7951 			default:
7952 				break;
7953 			}
7954 
7955 			node = safe_malloc(sizeof (unshare_unmount_node_t));
7956 			node->un_zhp = zhp;
7957 			node->un_mountp = safe_strdup(entry.mnt_mountp);
7958 
7959 			uu_avl_node_init(node, &node->un_avlnode, pool);
7960 
7961 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
7962 				uu_avl_insert(tree, node, idx);
7963 			} else {
7964 				zfs_close(node->un_zhp);
7965 				free(node->un_mountp);
7966 				free(node);
7967 			}
7968 		}
7969 		(void) fclose(mnttab);
7970 
7971 		/*
7972 		 * Walk the AVL tree in reverse, unmounting each filesystem and
7973 		 * removing it from the AVL tree in the process.
7974 		 */
7975 		if ((walk = uu_avl_walk_start(tree,
7976 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
7977 			nomem();
7978 
7979 		while ((node = uu_avl_walk_next(walk)) != NULL) {
7980 			const char *mntarg = NULL;
7981 
7982 			uu_avl_remove(tree, node);
7983 			switch (op) {
7984 			case OP_SHARE:
7985 				if (zfs_unshare(node->un_zhp,
7986 				    node->un_mountp, protocol) != 0)
7987 					ret = 1;
7988 				break;
7989 
7990 			case OP_MOUNT:
7991 				if (zfs_unmount(node->un_zhp,
7992 				    mntarg, flags) != 0)
7993 					ret = 1;
7994 				break;
7995 			}
7996 
7997 			zfs_close(node->un_zhp);
7998 			free(node->un_mountp);
7999 			free(node);
8000 		}
8001 
8002 		if (op == OP_SHARE)
8003 			zfs_commit_shares(protocol);
8004 
8005 		uu_avl_walk_end(walk);
8006 		uu_avl_destroy(tree);
8007 		uu_avl_pool_destroy(pool);
8008 
8009 	} else {
8010 		if (argc != 1) {
8011 			if (argc == 0)
8012 				(void) fprintf(stderr,
8013 				    gettext("missing filesystem argument\n"));
8014 			else
8015 				(void) fprintf(stderr,
8016 				    gettext("too many arguments\n"));
8017 			usage(B_FALSE);
8018 		}
8019 
8020 		/*
8021 		 * We have an argument, but it may be a full path or a ZFS
8022 		 * filesystem.  Pass full paths off to unmount_path() (shared by
8023 		 * manual_unmount), otherwise open the filesystem and pass to
8024 		 * zfs_unmount().
8025 		 */
8026 		if (argv[0][0] == '/')
8027 			return (unshare_unmount_path(op, argv[0],
8028 			    flags, B_FALSE));
8029 
8030 		if ((zhp = zfs_open(g_zfs, argv[0],
8031 		    ZFS_TYPE_FILESYSTEM)) == NULL)
8032 			return (1);
8033 
8034 		verify(zfs_prop_get(zhp, op == OP_SHARE ?
8035 		    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
8036 		    nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
8037 		    NULL, 0, B_FALSE) == 0);
8038 
8039 		switch (op) {
8040 		case OP_SHARE:
8041 			verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
8042 			    nfs_mnt_prop,
8043 			    sizeof (nfs_mnt_prop),
8044 			    NULL, NULL, 0, B_FALSE) == 0);
8045 			verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
8046 			    sharesmb, sizeof (sharesmb), NULL, NULL,
8047 			    0, B_FALSE) == 0);
8048 
8049 			if (strcmp(nfs_mnt_prop, "off") == 0 &&
8050 			    strcmp(sharesmb, "off") == 0) {
8051 				(void) fprintf(stderr, gettext("cannot "
8052 				    "unshare '%s': legacy share\n"),
8053 				    zfs_get_name(zhp));
8054 				(void) fprintf(stderr, gettext("use "
8055 				    "exports(5) or smb.conf(5) to unshare "
8056 				    "this filesystem\n"));
8057 				ret = 1;
8058 			} else if (!zfs_is_shared(zhp, NULL, NULL)) {
8059 				(void) fprintf(stderr, gettext("cannot "
8060 				    "unshare '%s': not currently "
8061 				    "shared\n"), zfs_get_name(zhp));
8062 				ret = 1;
8063 			} else if (zfs_unshareall(zhp, NULL) != 0) {
8064 				ret = 1;
8065 			}
8066 			break;
8067 
8068 		case OP_MOUNT:
8069 			if (strcmp(nfs_mnt_prop, "legacy") == 0) {
8070 				(void) fprintf(stderr, gettext("cannot "
8071 				    "unmount '%s': legacy "
8072 				    "mountpoint\n"), zfs_get_name(zhp));
8073 				(void) fprintf(stderr, gettext("use "
8074 				    "umount(8) to unmount this "
8075 				    "filesystem\n"));
8076 				ret = 1;
8077 			} else if (!zfs_is_mounted(zhp, NULL)) {
8078 				(void) fprintf(stderr, gettext("cannot "
8079 				    "unmount '%s': not currently "
8080 				    "mounted\n"),
8081 				    zfs_get_name(zhp));
8082 				ret = 1;
8083 			} else if (zfs_unmountall(zhp, flags) != 0) {
8084 				ret = 1;
8085 			}
8086 			break;
8087 		}
8088 
8089 		zfs_close(zhp);
8090 	}
8091 
8092 	return (ret);
8093 }
8094 
8095 /*
8096  * zfs unmount [-fu] -a
8097  * zfs unmount [-fu] filesystem
8098  *
8099  * Unmount all filesystems, or a specific ZFS filesystem.
8100  */
8101 static int
zfs_do_unmount(int argc,char ** argv)8102 zfs_do_unmount(int argc, char **argv)
8103 {
8104 	return (unshare_unmount(OP_MOUNT, argc, argv));
8105 }
8106 
8107 /*
8108  * zfs unshare -a
8109  * zfs unshare filesystem
8110  *
8111  * Unshare all filesystems, or a specific ZFS filesystem.
8112  */
8113 static int
zfs_do_unshare(int argc,char ** argv)8114 zfs_do_unshare(int argc, char **argv)
8115 {
8116 	return (unshare_unmount(OP_SHARE, argc, argv));
8117 }
8118 
8119 static int
find_command_idx(const char * command,int * idx)8120 find_command_idx(const char *command, int *idx)
8121 {
8122 	int i;
8123 
8124 	for (i = 0; i < NCOMMAND; i++) {
8125 		if (command_table[i].name == NULL)
8126 			continue;
8127 
8128 		if (strcmp(command, command_table[i].name) == 0) {
8129 			*idx = i;
8130 			return (0);
8131 		}
8132 	}
8133 	return (1);
8134 }
8135 
8136 static int
zfs_do_diff(int argc,char ** argv)8137 zfs_do_diff(int argc, char **argv)
8138 {
8139 	zfs_handle_t *zhp;
8140 	int flags = 0;
8141 	char *tosnap = NULL;
8142 	char *fromsnap = NULL;
8143 	char *atp, *copy;
8144 	int err = 0;
8145 	int c;
8146 	struct sigaction sa;
8147 
8148 	while ((c = getopt(argc, argv, "FHth")) != -1) {
8149 		switch (c) {
8150 		case 'F':
8151 			flags |= ZFS_DIFF_CLASSIFY;
8152 			break;
8153 		case 'H':
8154 			flags |= ZFS_DIFF_PARSEABLE;
8155 			break;
8156 		case 't':
8157 			flags |= ZFS_DIFF_TIMESTAMP;
8158 			break;
8159 		case 'h':
8160 			flags |= ZFS_DIFF_NO_MANGLE;
8161 			break;
8162 		default:
8163 			(void) fprintf(stderr,
8164 			    gettext("invalid option '%c'\n"), optopt);
8165 			usage(B_FALSE);
8166 		}
8167 	}
8168 
8169 	argc -= optind;
8170 	argv += optind;
8171 
8172 	if (argc < 1) {
8173 		(void) fprintf(stderr,
8174 		    gettext("must provide at least one snapshot name\n"));
8175 		usage(B_FALSE);
8176 	}
8177 
8178 	if (argc > 2) {
8179 		(void) fprintf(stderr, gettext("too many arguments\n"));
8180 		usage(B_FALSE);
8181 	}
8182 
8183 	fromsnap = argv[0];
8184 	tosnap = (argc == 2) ? argv[1] : NULL;
8185 
8186 	copy = NULL;
8187 	if (*fromsnap != '@')
8188 		copy = strdup(fromsnap);
8189 	else if (tosnap)
8190 		copy = strdup(tosnap);
8191 	if (copy == NULL)
8192 		usage(B_FALSE);
8193 
8194 	if ((atp = strchr(copy, '@')) != NULL)
8195 		*atp = '\0';
8196 
8197 	if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL) {
8198 		free(copy);
8199 		return (1);
8200 	}
8201 	free(copy);
8202 
8203 	/*
8204 	 * Ignore SIGPIPE so that the library can give us
8205 	 * information on any failure
8206 	 */
8207 	if (sigemptyset(&sa.sa_mask) == -1) {
8208 		err = errno;
8209 		goto out;
8210 	}
8211 	sa.sa_flags = 0;
8212 	sa.sa_handler = SIG_IGN;
8213 	if (sigaction(SIGPIPE, &sa, NULL) == -1) {
8214 		err = errno;
8215 		goto out;
8216 	}
8217 
8218 	err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
8219 out:
8220 	zfs_close(zhp);
8221 
8222 	return (err != 0);
8223 }
8224 
8225 /*
8226  * zfs bookmark <fs@source>|<fs#source> <fs#bookmark>
8227  *
8228  * Creates a bookmark with the given name from the source snapshot
8229  * or creates a copy of an existing source bookmark.
8230  */
8231 static int
zfs_do_bookmark(int argc,char ** argv)8232 zfs_do_bookmark(int argc, char **argv)
8233 {
8234 	char *source, *bookname;
8235 	char expbuf[ZFS_MAX_DATASET_NAME_LEN];
8236 	int source_type;
8237 	nvlist_t *nvl;
8238 	int ret = 0;
8239 	int c;
8240 
8241 	/* check options */
8242 	while ((c = getopt(argc, argv, "")) != -1) {
8243 		switch (c) {
8244 		case '?':
8245 			(void) fprintf(stderr,
8246 			    gettext("invalid option '%c'\n"), optopt);
8247 			goto usage;
8248 		}
8249 	}
8250 
8251 	argc -= optind;
8252 	argv += optind;
8253 
8254 	/* check number of arguments */
8255 	if (argc < 1) {
8256 		(void) fprintf(stderr, gettext("missing source argument\n"));
8257 		goto usage;
8258 	}
8259 	if (argc < 2) {
8260 		(void) fprintf(stderr, gettext("missing bookmark argument\n"));
8261 		goto usage;
8262 	}
8263 
8264 	source = argv[0];
8265 	bookname = argv[1];
8266 
8267 	if (strchr(source, '@') == NULL && strchr(source, '#') == NULL) {
8268 		(void) fprintf(stderr,
8269 		    gettext("invalid source name '%s': "
8270 		    "must contain a '@' or '#'\n"), source);
8271 		goto usage;
8272 	}
8273 	if (strchr(bookname, '#') == NULL) {
8274 		(void) fprintf(stderr,
8275 		    gettext("invalid bookmark name '%s': "
8276 		    "must contain a '#'\n"), bookname);
8277 		goto usage;
8278 	}
8279 
8280 	/*
8281 	 * expand source or bookname to full path:
8282 	 * one of them may be specified as short name
8283 	 */
8284 	{
8285 		char **expand;
8286 		char *source_short, *bookname_short;
8287 		source_short = strpbrk(source, "@#");
8288 		bookname_short = strpbrk(bookname, "#");
8289 		if (source_short == source &&
8290 		    bookname_short == bookname) {
8291 			(void) fprintf(stderr, gettext(
8292 			    "either source or bookmark must be specified as "
8293 			    "full dataset paths"));
8294 			goto usage;
8295 		} else if (source_short != source &&
8296 		    bookname_short != bookname) {
8297 			expand = NULL;
8298 		} else if (source_short != source) {
8299 			strlcpy(expbuf, source, sizeof (expbuf));
8300 			expand = &bookname;
8301 		} else if (bookname_short != bookname) {
8302 			strlcpy(expbuf, bookname, sizeof (expbuf));
8303 			expand = &source;
8304 		} else {
8305 			abort();
8306 		}
8307 		if (expand != NULL) {
8308 			*strpbrk(expbuf, "@#") = '\0'; /* dataset name in buf */
8309 			(void) strlcat(expbuf, *expand, sizeof (expbuf));
8310 			*expand = expbuf;
8311 		}
8312 	}
8313 
8314 	/* determine source type */
8315 	switch (*strpbrk(source, "@#")) {
8316 		case '@': source_type = ZFS_TYPE_SNAPSHOT; break;
8317 		case '#': source_type = ZFS_TYPE_BOOKMARK; break;
8318 		default: abort();
8319 	}
8320 
8321 	/* test the source exists */
8322 	zfs_handle_t *zhp;
8323 	zhp = zfs_open(g_zfs, source, source_type);
8324 	if (zhp == NULL)
8325 		goto usage;
8326 	zfs_close(zhp);
8327 
8328 	nvl = fnvlist_alloc();
8329 	fnvlist_add_string(nvl, bookname, source);
8330 	ret = lzc_bookmark(nvl, NULL);
8331 	fnvlist_free(nvl);
8332 
8333 	if (ret != 0) {
8334 		const char *err_msg = NULL;
8335 		char errbuf[1024];
8336 
8337 		(void) snprintf(errbuf, sizeof (errbuf),
8338 		    dgettext(TEXT_DOMAIN,
8339 		    "cannot create bookmark '%s'"), bookname);
8340 
8341 		switch (ret) {
8342 		case EXDEV:
8343 			err_msg = "bookmark is in a different pool";
8344 			break;
8345 		case ZFS_ERR_BOOKMARK_SOURCE_NOT_ANCESTOR:
8346 			err_msg = "source is not an ancestor of the "
8347 			    "new bookmark's dataset";
8348 			break;
8349 		case EEXIST:
8350 			err_msg = "bookmark exists";
8351 			break;
8352 		case EINVAL:
8353 			err_msg = "invalid argument";
8354 			break;
8355 		case ENOTSUP:
8356 			err_msg = "bookmark feature not enabled";
8357 			break;
8358 		case ENOSPC:
8359 			err_msg = "out of space";
8360 			break;
8361 		case ENOENT:
8362 			err_msg = "dataset does not exist";
8363 			break;
8364 		default:
8365 			(void) zfs_standard_error(g_zfs, ret, errbuf);
8366 			break;
8367 		}
8368 		if (err_msg != NULL) {
8369 			(void) fprintf(stderr, "%s: %s\n", errbuf,
8370 			    dgettext(TEXT_DOMAIN, err_msg));
8371 		}
8372 	}
8373 
8374 	return (ret != 0);
8375 
8376 usage:
8377 	usage(B_FALSE);
8378 	return (-1);
8379 }
8380 
8381 static int
zfs_do_channel_program(int argc,char ** argv)8382 zfs_do_channel_program(int argc, char **argv)
8383 {
8384 	int ret, fd, c;
8385 	size_t progsize, progread;
8386 	nvlist_t *outnvl = NULL;
8387 	uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
8388 	uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
8389 	boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
8390 	zpool_handle_t *zhp;
8391 
8392 	struct option long_options[] = {
8393 		{"json", no_argument, NULL, 'j'},
8394 		{0, 0, 0, 0}
8395 	};
8396 
8397 	/* check options */
8398 	while ((c = getopt_long(argc, argv, "nt:m:j", long_options,
8399 	    NULL)) != -1) {
8400 		switch (c) {
8401 		case 't':
8402 		case 'm': {
8403 			uint64_t arg;
8404 			char *endp;
8405 
8406 			errno = 0;
8407 			arg = strtoull(optarg, &endp, 0);
8408 			if (errno != 0 || *endp != '\0') {
8409 				(void) fprintf(stderr, gettext(
8410 				    "invalid argument "
8411 				    "'%s': expected integer\n"), optarg);
8412 				goto usage;
8413 			}
8414 
8415 			if (c == 't') {
8416 				instrlimit = arg;
8417 			} else {
8418 				ASSERT3U(c, ==, 'm');
8419 				memlimit = arg;
8420 			}
8421 			break;
8422 		}
8423 		case 'n': {
8424 			sync_flag = B_FALSE;
8425 			break;
8426 		}
8427 		case 'j': {
8428 			json_output = B_TRUE;
8429 			break;
8430 		}
8431 		case '?':
8432 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8433 			    optopt);
8434 			goto usage;
8435 		}
8436 	}
8437 
8438 	argc -= optind;
8439 	argv += optind;
8440 
8441 	if (argc < 2) {
8442 		(void) fprintf(stderr,
8443 		    gettext("invalid number of arguments\n"));
8444 		goto usage;
8445 	}
8446 
8447 	const char *poolname = argv[0];
8448 	const char *filename = argv[1];
8449 	if (strcmp(filename, "-") == 0) {
8450 		fd = 0;
8451 		filename = "standard input";
8452 	} else if ((fd = open(filename, O_RDONLY)) < 0) {
8453 		(void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
8454 		    filename, strerror(errno));
8455 		return (1);
8456 	}
8457 
8458 	if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8459 		(void) fprintf(stderr, gettext("cannot open pool '%s'\n"),
8460 		    poolname);
8461 		if (fd != 0)
8462 			(void) close(fd);
8463 		return (1);
8464 	}
8465 	zpool_close(zhp);
8466 
8467 	/*
8468 	 * Read in the channel program, expanding the program buffer as
8469 	 * necessary.
8470 	 */
8471 	progread = 0;
8472 	progsize = 1024;
8473 	char *progbuf = safe_malloc(progsize);
8474 	do {
8475 		ret = read(fd, progbuf + progread, progsize - progread);
8476 		progread += ret;
8477 		if (progread == progsize && ret > 0) {
8478 			progsize *= 2;
8479 			progbuf = safe_realloc(progbuf, progsize);
8480 		}
8481 	} while (ret > 0);
8482 
8483 	if (fd != 0)
8484 		(void) close(fd);
8485 	if (ret < 0) {
8486 		free(progbuf);
8487 		(void) fprintf(stderr,
8488 		    gettext("cannot read '%s': %s\n"),
8489 		    filename, strerror(errno));
8490 		return (1);
8491 	}
8492 	progbuf[progread] = '\0';
8493 
8494 	/*
8495 	 * Any remaining arguments are passed as arguments to the lua script as
8496 	 * a string array:
8497 	 * {
8498 	 *	"argv" -> [ "arg 1", ... "arg n" ],
8499 	 * }
8500 	 */
8501 	nvlist_t *argnvl = fnvlist_alloc();
8502 	fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV,
8503 	    (const char **)argv + 2, argc - 2);
8504 
8505 	if (sync_flag) {
8506 		ret = lzc_channel_program(poolname, progbuf,
8507 		    instrlimit, memlimit, argnvl, &outnvl);
8508 	} else {
8509 		ret = lzc_channel_program_nosync(poolname, progbuf,
8510 		    instrlimit, memlimit, argnvl, &outnvl);
8511 	}
8512 
8513 	if (ret != 0) {
8514 		/*
8515 		 * On error, report the error message handed back by lua if one
8516 		 * exists.  Otherwise, generate an appropriate error message,
8517 		 * falling back on strerror() for an unexpected return code.
8518 		 */
8519 		const char *errstring = NULL;
8520 		const char *msg = gettext("Channel program execution failed");
8521 		uint64_t instructions = 0;
8522 		if (outnvl != NULL && nvlist_exists(outnvl, ZCP_RET_ERROR)) {
8523 			const char *es = NULL;
8524 			(void) nvlist_lookup_string(outnvl,
8525 			    ZCP_RET_ERROR, &es);
8526 			if (es == NULL)
8527 				errstring = strerror(ret);
8528 			else
8529 				errstring = es;
8530 			if (ret == ETIME) {
8531 				(void) nvlist_lookup_uint64(outnvl,
8532 				    ZCP_ARG_INSTRLIMIT, &instructions);
8533 			}
8534 		} else {
8535 			switch (ret) {
8536 			case EINVAL:
8537 				errstring =
8538 				    "Invalid instruction or memory limit.";
8539 				break;
8540 			case ENOMEM:
8541 				errstring = "Return value too large.";
8542 				break;
8543 			case ENOSPC:
8544 				errstring = "Memory limit exhausted.";
8545 				break;
8546 			case ETIME:
8547 				errstring = "Timed out.";
8548 				break;
8549 			case EPERM:
8550 				errstring = "Permission denied. Channel "
8551 				    "programs must be run as root.";
8552 				break;
8553 			default:
8554 				(void) zfs_standard_error(g_zfs, ret, msg);
8555 			}
8556 		}
8557 		if (errstring != NULL)
8558 			(void) fprintf(stderr, "%s:\n%s\n", msg, errstring);
8559 
8560 		if (ret == ETIME && instructions != 0)
8561 			(void) fprintf(stderr,
8562 			    gettext("%llu Lua instructions\n"),
8563 			    (u_longlong_t)instructions);
8564 	} else {
8565 		if (json_output) {
8566 			(void) nvlist_print_json(stdout, outnvl);
8567 		} else if (nvlist_empty(outnvl)) {
8568 			(void) fprintf(stdout, gettext("Channel program fully "
8569 			    "executed and did not produce output.\n"));
8570 		} else {
8571 			(void) fprintf(stdout, gettext("Channel program fully "
8572 			    "executed and produced output:\n"));
8573 			dump_nvlist(outnvl, 4);
8574 		}
8575 	}
8576 
8577 	free(progbuf);
8578 	fnvlist_free(outnvl);
8579 	fnvlist_free(argnvl);
8580 	return (ret != 0);
8581 
8582 usage:
8583 	usage(B_FALSE);
8584 	return (-1);
8585 }
8586 
8587 
8588 typedef struct loadkey_cbdata {
8589 	boolean_t cb_loadkey;
8590 	boolean_t cb_recursive;
8591 	boolean_t cb_noop;
8592 	char *cb_keylocation;
8593 	uint64_t cb_numfailed;
8594 	uint64_t cb_numattempted;
8595 } loadkey_cbdata_t;
8596 
8597 static int
load_key_callback(zfs_handle_t * zhp,void * data)8598 load_key_callback(zfs_handle_t *zhp, void *data)
8599 {
8600 	int ret;
8601 	boolean_t is_encroot;
8602 	loadkey_cbdata_t *cb = data;
8603 	uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8604 
8605 	/*
8606 	 * If we are working recursively, we want to skip loading / unloading
8607 	 * keys for non-encryption roots and datasets whose keys are already
8608 	 * in the desired end-state.
8609 	 */
8610 	if (cb->cb_recursive) {
8611 		ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
8612 		if (ret != 0)
8613 			return (ret);
8614 		if (!is_encroot)
8615 			return (0);
8616 
8617 		if ((cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_AVAILABLE) ||
8618 		    (!cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_UNAVAILABLE))
8619 			return (0);
8620 	}
8621 
8622 	cb->cb_numattempted++;
8623 
8624 	if (cb->cb_loadkey)
8625 		ret = zfs_crypto_load_key(zhp, cb->cb_noop, cb->cb_keylocation);
8626 	else
8627 		ret = zfs_crypto_unload_key(zhp);
8628 
8629 	if (ret != 0) {
8630 		cb->cb_numfailed++;
8631 		return (ret);
8632 	}
8633 
8634 	return (0);
8635 }
8636 
8637 static int
load_unload_keys(int argc,char ** argv,boolean_t loadkey)8638 load_unload_keys(int argc, char **argv, boolean_t loadkey)
8639 {
8640 	int c, ret = 0, flags = 0;
8641 	boolean_t do_all = B_FALSE;
8642 	loadkey_cbdata_t cb = { 0 };
8643 
8644 	cb.cb_loadkey = loadkey;
8645 
8646 	while ((c = getopt(argc, argv, "anrL:")) != -1) {
8647 		/* noop and alternate keylocations only apply to zfs load-key */
8648 		if (loadkey) {
8649 			switch (c) {
8650 			case 'n':
8651 				cb.cb_noop = B_TRUE;
8652 				continue;
8653 			case 'L':
8654 				cb.cb_keylocation = optarg;
8655 				continue;
8656 			default:
8657 				break;
8658 			}
8659 		}
8660 
8661 		switch (c) {
8662 		case 'a':
8663 			do_all = B_TRUE;
8664 			cb.cb_recursive = B_TRUE;
8665 			break;
8666 		case 'r':
8667 			flags |= ZFS_ITER_RECURSE;
8668 			cb.cb_recursive = B_TRUE;
8669 			break;
8670 		default:
8671 			(void) fprintf(stderr,
8672 			    gettext("invalid option '%c'\n"), optopt);
8673 			usage(B_FALSE);
8674 		}
8675 	}
8676 
8677 	argc -= optind;
8678 	argv += optind;
8679 
8680 	if (!do_all && argc == 0) {
8681 		(void) fprintf(stderr,
8682 		    gettext("Missing dataset argument or -a option\n"));
8683 		usage(B_FALSE);
8684 	}
8685 
8686 	if (do_all && argc != 0) {
8687 		(void) fprintf(stderr,
8688 		    gettext("Cannot specify dataset with -a option\n"));
8689 		usage(B_FALSE);
8690 	}
8691 
8692 	if (cb.cb_recursive && cb.cb_keylocation != NULL &&
8693 	    strcmp(cb.cb_keylocation, "prompt") != 0) {
8694 		(void) fprintf(stderr, gettext("alternate keylocation may only "
8695 		    "be 'prompt' with -r or -a\n"));
8696 		usage(B_FALSE);
8697 	}
8698 
8699 	ret = zfs_for_each(argc, argv, flags,
8700 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL, 0,
8701 	    load_key_callback, &cb);
8702 
8703 	if (cb.cb_noop || (cb.cb_recursive && cb.cb_numattempted != 0)) {
8704 		(void) printf(gettext("%llu / %llu key(s) successfully %s\n"),
8705 		    (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
8706 		    (u_longlong_t)cb.cb_numattempted,
8707 		    loadkey ? (cb.cb_noop ? "verified" : "loaded") :
8708 		    "unloaded");
8709 	}
8710 
8711 	if (cb.cb_numfailed != 0)
8712 		ret = -1;
8713 
8714 	return (ret);
8715 }
8716 
8717 static int
zfs_do_load_key(int argc,char ** argv)8718 zfs_do_load_key(int argc, char **argv)
8719 {
8720 	return (load_unload_keys(argc, argv, B_TRUE));
8721 }
8722 
8723 
8724 static int
zfs_do_unload_key(int argc,char ** argv)8725 zfs_do_unload_key(int argc, char **argv)
8726 {
8727 	return (load_unload_keys(argc, argv, B_FALSE));
8728 }
8729 
8730 static int
zfs_do_change_key(int argc,char ** argv)8731 zfs_do_change_key(int argc, char **argv)
8732 {
8733 	int c, ret;
8734 	uint64_t keystatus;
8735 	boolean_t loadkey = B_FALSE, inheritkey = B_FALSE;
8736 	zfs_handle_t *zhp = NULL;
8737 	nvlist_t *props = fnvlist_alloc();
8738 
8739 	while ((c = getopt(argc, argv, "lio:")) != -1) {
8740 		switch (c) {
8741 		case 'l':
8742 			loadkey = B_TRUE;
8743 			break;
8744 		case 'i':
8745 			inheritkey = B_TRUE;
8746 			break;
8747 		case 'o':
8748 			if (!parseprop(props, optarg)) {
8749 				nvlist_free(props);
8750 				return (1);
8751 			}
8752 			break;
8753 		default:
8754 			(void) fprintf(stderr,
8755 			    gettext("invalid option '%c'\n"), optopt);
8756 			usage(B_FALSE);
8757 		}
8758 	}
8759 
8760 	if (inheritkey && !nvlist_empty(props)) {
8761 		(void) fprintf(stderr,
8762 		    gettext("Properties not allowed for inheriting\n"));
8763 		usage(B_FALSE);
8764 	}
8765 
8766 	argc -= optind;
8767 	argv += optind;
8768 
8769 	if (argc < 1) {
8770 		(void) fprintf(stderr, gettext("Missing dataset argument\n"));
8771 		usage(B_FALSE);
8772 	}
8773 
8774 	if (argc > 1) {
8775 		(void) fprintf(stderr, gettext("Too many arguments\n"));
8776 		usage(B_FALSE);
8777 	}
8778 
8779 	zhp = zfs_open(g_zfs, argv[argc - 1],
8780 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
8781 	if (zhp == NULL)
8782 		usage(B_FALSE);
8783 
8784 	if (loadkey) {
8785 		keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8786 		if (keystatus != ZFS_KEYSTATUS_AVAILABLE) {
8787 			ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
8788 			if (ret != 0) {
8789 				nvlist_free(props);
8790 				zfs_close(zhp);
8791 				return (-1);
8792 			}
8793 		}
8794 
8795 		/* refresh the properties so the new keystatus is visible */
8796 		zfs_refresh_properties(zhp);
8797 	}
8798 
8799 	ret = zfs_crypto_rewrap(zhp, props, inheritkey);
8800 	if (ret != 0) {
8801 		nvlist_free(props);
8802 		zfs_close(zhp);
8803 		return (-1);
8804 	}
8805 
8806 	nvlist_free(props);
8807 	zfs_close(zhp);
8808 	return (0);
8809 }
8810 
8811 /*
8812  * 1) zfs project [-d|-r] <file|directory ...>
8813  *    List project ID and inherit flag of file(s) or directories.
8814  *    -d: List the directory itself, not its children.
8815  *    -r: List subdirectories recursively.
8816  *
8817  * 2) zfs project -C [-k] [-r] <file|directory ...>
8818  *    Clear project inherit flag and/or ID on the file(s) or directories.
8819  *    -k: Keep the project ID unchanged. If not specified, the project ID
8820  *	  will be reset as zero.
8821  *    -r: Clear on subdirectories recursively.
8822  *
8823  * 3) zfs project -c [-0] [-d|-r] [-p id] <file|directory ...>
8824  *    Check project ID and inherit flag on the file(s) or directories,
8825  *    report the outliers.
8826  *    -0: Print file name followed by a NUL instead of newline.
8827  *    -d: Check the directory itself, not its children.
8828  *    -p: Specify the referenced ID for comparing with the target file(s)
8829  *	  or directories' project IDs. If not specified, the target (top)
8830  *	  directory's project ID will be used as the referenced one.
8831  *    -r: Check subdirectories recursively.
8832  *
8833  * 4) zfs project [-p id] [-r] [-s] <file|directory ...>
8834  *    Set project ID and/or inherit flag on the file(s) or directories.
8835  *    -p: Set the project ID as the given id.
8836  *    -r: Set on subdirectories recursively. If not specify "-p" option,
8837  *	  it will use top-level directory's project ID as the given id,
8838  *	  then set both project ID and inherit flag on all descendants
8839  *	  of the top-level directory.
8840  *    -s: Set project inherit flag.
8841  */
8842 static int
zfs_do_project(int argc,char ** argv)8843 zfs_do_project(int argc, char **argv)
8844 {
8845 	zfs_project_control_t zpc = {
8846 		.zpc_expected_projid = ZFS_INVALID_PROJID,
8847 		.zpc_op = ZFS_PROJECT_OP_DEFAULT,
8848 		.zpc_dironly = B_FALSE,
8849 		.zpc_keep_projid = B_FALSE,
8850 		.zpc_newline = B_TRUE,
8851 		.zpc_recursive = B_FALSE,
8852 		.zpc_set_flag = B_FALSE,
8853 	};
8854 	int ret = 0, c;
8855 
8856 	if (argc < 2)
8857 		usage(B_FALSE);
8858 
8859 	while ((c = getopt(argc, argv, "0Ccdkp:rs")) != -1) {
8860 		switch (c) {
8861 		case '0':
8862 			zpc.zpc_newline = B_FALSE;
8863 			break;
8864 		case 'C':
8865 			if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8866 				(void) fprintf(stderr, gettext("cannot "
8867 				    "specify '-C' '-c' '-s' together\n"));
8868 				usage(B_FALSE);
8869 			}
8870 
8871 			zpc.zpc_op = ZFS_PROJECT_OP_CLEAR;
8872 			break;
8873 		case 'c':
8874 			if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8875 				(void) fprintf(stderr, gettext("cannot "
8876 				    "specify '-C' '-c' '-s' together\n"));
8877 				usage(B_FALSE);
8878 			}
8879 
8880 			zpc.zpc_op = ZFS_PROJECT_OP_CHECK;
8881 			break;
8882 		case 'd':
8883 			zpc.zpc_dironly = B_TRUE;
8884 			/* overwrite "-r" option */
8885 			zpc.zpc_recursive = B_FALSE;
8886 			break;
8887 		case 'k':
8888 			zpc.zpc_keep_projid = B_TRUE;
8889 			break;
8890 		case 'p': {
8891 			char *endptr;
8892 
8893 			errno = 0;
8894 			zpc.zpc_expected_projid = strtoull(optarg, &endptr, 0);
8895 			if (errno != 0 || *endptr != '\0') {
8896 				(void) fprintf(stderr,
8897 				    gettext("project ID must be less than "
8898 				    "%u\n"), UINT32_MAX);
8899 				usage(B_FALSE);
8900 			}
8901 			if (zpc.zpc_expected_projid >= UINT32_MAX) {
8902 				(void) fprintf(stderr,
8903 				    gettext("invalid project ID\n"));
8904 				usage(B_FALSE);
8905 			}
8906 			break;
8907 		}
8908 		case 'r':
8909 			zpc.zpc_recursive = B_TRUE;
8910 			/* overwrite "-d" option */
8911 			zpc.zpc_dironly = B_FALSE;
8912 			break;
8913 		case 's':
8914 			if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8915 				(void) fprintf(stderr, gettext("cannot "
8916 				    "specify '-C' '-c' '-s' together\n"));
8917 				usage(B_FALSE);
8918 			}
8919 
8920 			zpc.zpc_set_flag = B_TRUE;
8921 			zpc.zpc_op = ZFS_PROJECT_OP_SET;
8922 			break;
8923 		default:
8924 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
8925 			    optopt);
8926 			usage(B_FALSE);
8927 		}
8928 	}
8929 
8930 	if (zpc.zpc_op == ZFS_PROJECT_OP_DEFAULT) {
8931 		if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID)
8932 			zpc.zpc_op = ZFS_PROJECT_OP_SET;
8933 		else
8934 			zpc.zpc_op = ZFS_PROJECT_OP_LIST;
8935 	}
8936 
8937 	switch (zpc.zpc_op) {
8938 	case ZFS_PROJECT_OP_LIST:
8939 		if (zpc.zpc_keep_projid) {
8940 			(void) fprintf(stderr,
8941 			    gettext("'-k' is only valid together with '-C'\n"));
8942 			usage(B_FALSE);
8943 		}
8944 		if (!zpc.zpc_newline) {
8945 			(void) fprintf(stderr,
8946 			    gettext("'-0' is only valid together with '-c'\n"));
8947 			usage(B_FALSE);
8948 		}
8949 		break;
8950 	case ZFS_PROJECT_OP_CHECK:
8951 		if (zpc.zpc_keep_projid) {
8952 			(void) fprintf(stderr,
8953 			    gettext("'-k' is only valid together with '-C'\n"));
8954 			usage(B_FALSE);
8955 		}
8956 		break;
8957 	case ZFS_PROJECT_OP_CLEAR:
8958 		if (zpc.zpc_dironly) {
8959 			(void) fprintf(stderr,
8960 			    gettext("'-d' is useless together with '-C'\n"));
8961 			usage(B_FALSE);
8962 		}
8963 		if (!zpc.zpc_newline) {
8964 			(void) fprintf(stderr,
8965 			    gettext("'-0' is only valid together with '-c'\n"));
8966 			usage(B_FALSE);
8967 		}
8968 		if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID) {
8969 			(void) fprintf(stderr,
8970 			    gettext("'-p' is useless together with '-C'\n"));
8971 			usage(B_FALSE);
8972 		}
8973 		break;
8974 	case ZFS_PROJECT_OP_SET:
8975 		if (zpc.zpc_dironly) {
8976 			(void) fprintf(stderr,
8977 			    gettext("'-d' is useless for set project ID and/or "
8978 			    "inherit flag\n"));
8979 			usage(B_FALSE);
8980 		}
8981 		if (zpc.zpc_keep_projid) {
8982 			(void) fprintf(stderr,
8983 			    gettext("'-k' is only valid together with '-C'\n"));
8984 			usage(B_FALSE);
8985 		}
8986 		if (!zpc.zpc_newline) {
8987 			(void) fprintf(stderr,
8988 			    gettext("'-0' is only valid together with '-c'\n"));
8989 			usage(B_FALSE);
8990 		}
8991 		break;
8992 	default:
8993 		ASSERT(0);
8994 		break;
8995 	}
8996 
8997 	argv += optind;
8998 	argc -= optind;
8999 	if (argc == 0) {
9000 		(void) fprintf(stderr,
9001 		    gettext("missing file or directory target(s)\n"));
9002 		usage(B_FALSE);
9003 	}
9004 
9005 	for (int i = 0; i < argc; i++) {
9006 		int err;
9007 
9008 		err = zfs_project_handle(argv[i], &zpc);
9009 		if (err && !ret)
9010 			ret = err;
9011 	}
9012 
9013 	return (ret);
9014 }
9015 
9016 static int
zfs_do_wait(int argc,char ** argv)9017 zfs_do_wait(int argc, char **argv)
9018 {
9019 	boolean_t enabled[ZFS_WAIT_NUM_ACTIVITIES];
9020 	int error = 0, i;
9021 	int c;
9022 
9023 	/* By default, wait for all types of activity. */
9024 	for (i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++)
9025 		enabled[i] = B_TRUE;
9026 
9027 	while ((c = getopt(argc, argv, "t:")) != -1) {
9028 		switch (c) {
9029 		case 't':
9030 			/* Reset activities array */
9031 			memset(&enabled, 0, sizeof (enabled));
9032 
9033 			for (char *tok; (tok = strsep(&optarg, ",")); ) {
9034 				static const char *const col_subopts[
9035 				    ZFS_WAIT_NUM_ACTIVITIES] = { "deleteq" };
9036 
9037 				for (i = 0; i < ARRAY_SIZE(col_subopts); ++i)
9038 					if (strcmp(tok, col_subopts[i]) == 0) {
9039 						enabled[i] = B_TRUE;
9040 						goto found;
9041 					}
9042 
9043 				(void) fprintf(stderr,
9044 				    gettext("invalid activity '%s'\n"), tok);
9045 				usage(B_FALSE);
9046 found:;
9047 			}
9048 			break;
9049 		case '?':
9050 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
9051 			    optopt);
9052 			usage(B_FALSE);
9053 		}
9054 	}
9055 
9056 	argv += optind;
9057 	argc -= optind;
9058 	if (argc < 1) {
9059 		(void) fprintf(stderr, gettext("missing 'filesystem' "
9060 		    "argument\n"));
9061 		usage(B_FALSE);
9062 	}
9063 	if (argc > 1) {
9064 		(void) fprintf(stderr, gettext("too many arguments\n"));
9065 		usage(B_FALSE);
9066 	}
9067 
9068 	zfs_handle_t *zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM);
9069 	if (zhp == NULL)
9070 		return (1);
9071 
9072 	for (;;) {
9073 		boolean_t missing = B_FALSE;
9074 		boolean_t any_waited = B_FALSE;
9075 
9076 		for (int i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++) {
9077 			boolean_t waited;
9078 
9079 			if (!enabled[i])
9080 				continue;
9081 
9082 			error = zfs_wait_status(zhp, i, &missing, &waited);
9083 			if (error != 0 || missing)
9084 				break;
9085 
9086 			any_waited = (any_waited || waited);
9087 		}
9088 
9089 		if (error != 0 || missing || !any_waited)
9090 			break;
9091 	}
9092 
9093 	zfs_close(zhp);
9094 
9095 	return (error);
9096 }
9097 
9098 /*
9099  * Display version message
9100  */
9101 static int
zfs_do_version(int argc,char ** argv)9102 zfs_do_version(int argc, char **argv)
9103 {
9104 	int c;
9105 	nvlist_t *jsobj = NULL, *zfs_ver = NULL;
9106 	boolean_t json = B_FALSE;
9107 
9108 	struct option long_options[] = {
9109 		{"json", no_argument, NULL, 'j'},
9110 		{0, 0, 0, 0}
9111 	};
9112 
9113 	while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
9114 		switch (c) {
9115 		case 'j':
9116 			json = B_TRUE;
9117 			jsobj = zfs_json_schema(0, 1);
9118 			break;
9119 		case '?':
9120 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
9121 			    optopt);
9122 			usage(B_FALSE);
9123 		}
9124 	}
9125 
9126 	argc -= optind;
9127 	if (argc != 0) {
9128 		(void) fprintf(stderr, "too many arguments\n");
9129 		usage(B_FALSE);
9130 	}
9131 
9132 	if (json) {
9133 		zfs_ver = zfs_version_nvlist();
9134 		if (zfs_ver) {
9135 			fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
9136 			zcmd_print_json(jsobj);
9137 			fnvlist_free(zfs_ver);
9138 			return (0);
9139 		} else
9140 			return (-1);
9141 	} else
9142 		return (zfs_version_print() != 0);
9143 }
9144 
9145 /* Display documentation */
9146 static int
zfs_do_help(int argc,char ** argv)9147 zfs_do_help(int argc, char **argv)
9148 {
9149 	char page[MAXNAMELEN];
9150 	if (argc < 3 || strcmp(argv[2], "zfs") == 0)
9151 		strcpy(page, "zfs");
9152 	else if (strcmp(argv[2], "concepts") == 0 ||
9153 	    strcmp(argv[2], "props") == 0)
9154 		snprintf(page, sizeof (page), "zfs%s", argv[2]);
9155 	else
9156 		snprintf(page, sizeof (page), "zfs-%s", argv[2]);
9157 
9158 	execlp("man", "man", page, NULL);
9159 
9160 	fprintf(stderr, "couldn't run man program: %s", strerror(errno));
9161 	return (-1);
9162 }
9163 
9164 int
main(int argc,char ** argv)9165 main(int argc, char **argv)
9166 {
9167 	int ret = 0;
9168 	int i = 0;
9169 	const char *cmdname;
9170 	char **newargv;
9171 
9172 	(void) setlocale(LC_ALL, "");
9173 	(void) setlocale(LC_NUMERIC, "C");
9174 	(void) textdomain(TEXT_DOMAIN);
9175 
9176 	opterr = 0;
9177 
9178 	/*
9179 	 * Make sure the user has specified some command.
9180 	 */
9181 	if (argc < 2) {
9182 		(void) fprintf(stderr, gettext("missing command\n"));
9183 		usage(B_FALSE);
9184 	}
9185 
9186 	cmdname = argv[1];
9187 
9188 	/*
9189 	 * The 'umount' command is an alias for 'unmount'
9190 	 */
9191 	if (strcmp(cmdname, "umount") == 0)
9192 		cmdname = "unmount";
9193 
9194 	/*
9195 	 * The 'recv' command is an alias for 'receive'
9196 	 */
9197 	if (strcmp(cmdname, "recv") == 0)
9198 		cmdname = "receive";
9199 
9200 	/*
9201 	 * The 'snap' command is an alias for 'snapshot'
9202 	 */
9203 	if (strcmp(cmdname, "snap") == 0)
9204 		cmdname = "snapshot";
9205 
9206 	/*
9207 	 * Special case '-?'
9208 	 */
9209 	if ((strcmp(cmdname, "-?") == 0) ||
9210 	    (strcmp(cmdname, "--help") == 0))
9211 		usage(B_TRUE);
9212 
9213 	/*
9214 	 * Special case '-V|--version'
9215 	 */
9216 	if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
9217 		return (zfs_version_print() != 0);
9218 
9219 	/*
9220 	 * Special case 'help'
9221 	 */
9222 	if (strcmp(cmdname, "help") == 0)
9223 		return (zfs_do_help(argc, argv));
9224 
9225 	if ((g_zfs = libzfs_init()) == NULL) {
9226 		(void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
9227 		return (1);
9228 	}
9229 
9230 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
9231 
9232 	libzfs_print_on_error(g_zfs, B_TRUE);
9233 
9234 	zfs_setproctitle_init(argc, argv, environ);
9235 
9236 	/*
9237 	 * Many commands modify input strings for string parsing reasons.
9238 	 * We create a copy to protect the original argv.
9239 	 */
9240 	newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
9241 	for (i = 0; i < argc; i++)
9242 		newargv[i] = strdup(argv[i]);
9243 	newargv[argc] = NULL;
9244 
9245 	/*
9246 	 * Run the appropriate command.
9247 	 */
9248 	libzfs_mnttab_cache(g_zfs, B_TRUE);
9249 	if (find_command_idx(cmdname, &i) == 0) {
9250 		current_command = &command_table[i];
9251 		ret = command_table[i].func(argc - 1, newargv + 1);
9252 	} else if (strchr(cmdname, '=') != NULL) {
9253 		verify(find_command_idx("set", &i) == 0);
9254 		current_command = &command_table[i];
9255 		ret = command_table[i].func(argc, newargv);
9256 	} else {
9257 		(void) fprintf(stderr, gettext("unrecognized "
9258 		    "command '%s'\n"), cmdname);
9259 		usage(B_FALSE);
9260 		ret = 1;
9261 	}
9262 
9263 	for (i = 0; i < argc; i++)
9264 		free(newargv[i]);
9265 	free(newargv);
9266 
9267 	if (ret == 0 && log_history)
9268 		(void) zpool_log_history(g_zfs, history_str);
9269 
9270 	libzfs_fini(g_zfs);
9271 
9272 	/*
9273 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
9274 	 * for the purposes of running ::findleaks.
9275 	 */
9276 	if (getenv("ZFS_ABORT") != NULL) {
9277 		(void) printf("dumping core by request\n");
9278 		abort();
9279 	}
9280 
9281 	return (ret);
9282 }
9283 
9284 /*
9285  * zfs zone nsfile filesystem
9286  *
9287  * Add or delete the given dataset to/from the namespace.
9288  */
9289 #ifdef __linux__
9290 static int
zfs_do_zone_impl(int argc,char ** argv,boolean_t attach)9291 zfs_do_zone_impl(int argc, char **argv, boolean_t attach)
9292 {
9293 	zfs_handle_t *zhp;
9294 	int ret;
9295 
9296 	if (argc < 3) {
9297 		(void) fprintf(stderr, gettext("missing argument(s)\n"));
9298 		usage(B_FALSE);
9299 	}
9300 	if (argc > 3) {
9301 		(void) fprintf(stderr, gettext("too many arguments\n"));
9302 		usage(B_FALSE);
9303 	}
9304 
9305 	zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9306 	if (zhp == NULL)
9307 		return (1);
9308 
9309 	ret = (zfs_userns(zhp, argv[1], attach) != 0);
9310 
9311 	zfs_close(zhp);
9312 	return (ret);
9313 }
9314 
9315 static int
zfs_do_zone(int argc,char ** argv)9316 zfs_do_zone(int argc, char **argv)
9317 {
9318 	return (zfs_do_zone_impl(argc, argv, B_TRUE));
9319 }
9320 
9321 static int
zfs_do_unzone(int argc,char ** argv)9322 zfs_do_unzone(int argc, char **argv)
9323 {
9324 	return (zfs_do_zone_impl(argc, argv, B_FALSE));
9325 }
9326 #endif
9327 
9328 #ifdef __FreeBSD__
9329 #include <sys/jail.h>
9330 #include <jail.h>
9331 /*
9332  * Attach/detach the given dataset to/from the given jail
9333  */
9334 static int
zfs_do_jail_impl(int argc,char ** argv,boolean_t attach)9335 zfs_do_jail_impl(int argc, char **argv, boolean_t attach)
9336 {
9337 	zfs_handle_t *zhp;
9338 	int jailid, ret;
9339 
9340 	/* check number of arguments */
9341 	if (argc < 3) {
9342 		(void) fprintf(stderr, gettext("missing argument(s)\n"));
9343 		usage(B_FALSE);
9344 	}
9345 	if (argc > 3) {
9346 		(void) fprintf(stderr, gettext("too many arguments\n"));
9347 		usage(B_FALSE);
9348 	}
9349 
9350 	jailid = jail_getid(argv[1]);
9351 	if (jailid < 0) {
9352 		(void) fprintf(stderr, gettext("invalid jail id or name\n"));
9353 		usage(B_FALSE);
9354 	}
9355 
9356 	zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9357 	if (zhp == NULL)
9358 		return (1);
9359 
9360 	ret = (zfs_jail(zhp, jailid, attach) != 0);
9361 
9362 	zfs_close(zhp);
9363 	return (ret);
9364 }
9365 
9366 /*
9367  * zfs jail jailid filesystem
9368  *
9369  * Attach the given dataset to the given jail
9370  */
9371 static int
zfs_do_jail(int argc,char ** argv)9372 zfs_do_jail(int argc, char **argv)
9373 {
9374 	return (zfs_do_jail_impl(argc, argv, B_TRUE));
9375 }
9376 
9377 /*
9378  * zfs unjail jailid filesystem
9379  *
9380  * Detach the given dataset from the given jail
9381  */
9382 static int
zfs_do_unjail(int argc,char ** argv)9383 zfs_do_unjail(int argc, char **argv)
9384 {
9385 	return (zfs_do_jail_impl(argc, argv, B_FALSE));
9386 }
9387 #endif
9388