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