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