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