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