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