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