]> git.proxmox.com Git - mirror_zfs.git/blame - cmd/zfs/zfs_main.c
FreeBSD: Fix module autoloading when built in base
[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) {
6630 return (0);
6631 }
6632
1bf9a552
TC
6633 /*
6634 * If this filesystem is encrypted and does not have
6635 * a loaded key, we can not mount it.
6636 */
6637 if ((flags & MS_CRYPT) == 0 &&
6638 zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
6639 zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
6640 ZFS_KEYSTATUS_UNAVAILABLE) {
6641 if (!explicit)
6642 return (0);
6643
6644 (void) fprintf(stderr, gettext("cannot %s '%s': "
6645 "encryption key not loaded\n"), cmdname, zfs_get_name(zhp));
6646 return (1);
6647 }
6648
47dfff3b
MA
6649 /*
6650 * If this filesystem is inconsistent and has a receive resume
6651 * token, we can not mount it.
6652 */
6653 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
6654 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
6655 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
6656 if (!explicit)
6657 return (0);
6658
6659 (void) fprintf(stderr, gettext("cannot %s '%s': "
6660 "Contains partially-completed state from "
c03f0470 6661 "\"zfs receive -s\", which can be resumed with "
47dfff3b
MA
6662 "\"zfs send -t\"\n"),
6663 cmdname, zfs_get_name(zhp));
6664 return (1);
6665 }
6666
30af21b0
PD
6667 if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE)) {
6668 if (!explicit)
6669 return (0);
6670
6671 (void) fprintf(stderr, gettext("cannot %s '%s': "
6672 "Dataset is not complete, was created by receiving "
6673 "a redacted zfs send stream.\n"), cmdname,
6674 zfs_get_name(zhp));
6675 return (1);
6676 }
6677
572e2857
BB
6678 /*
6679 * At this point, we have verified that the mountpoint and/or
6680 * shareopts are appropriate for auto management. If the
6681 * filesystem is already mounted or shared, return (failing
6682 * for explicit requests); otherwise mount or share the
6683 * filesystem.
6684 */
6685 switch (op) {
6686 case OP_SHARE:
6687
6688 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
6689 shared_smb = zfs_is_shared_smb(zhp, NULL);
6690
149e873a 6691 if ((shared_nfs && shared_smb) ||
648a09ad
BB
6692 (shared_nfs && strcmp(shareopts, "on") == 0 &&
6693 strcmp(smbshareopts, "off") == 0) ||
6694 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
6695 strcmp(shareopts, "off") == 0)) {
34dc7c2f
BB
6696 if (!explicit)
6697 return (0);
6698
572e2857
BB
6699 (void) fprintf(stderr, gettext("cannot share "
6700 "'%s': filesystem already shared\n"),
34dc7c2f
BB
6701 zfs_get_name(zhp));
6702 return (1);
34dc7c2f
BB
6703 }
6704
572e2857 6705 if (!zfs_is_mounted(zhp, NULL) &&
b5256303 6706 zfs_mount(zhp, NULL, flags) != 0)
572e2857 6707 return (1);
34dc7c2f 6708
572e2857
BB
6709 if (protocol == NULL) {
6710 if (zfs_shareall(zhp) != 0)
34dc7c2f 6711 return (1);
572e2857
BB
6712 } else if (strcmp(protocol, "nfs") == 0) {
6713 if (zfs_share_nfs(zhp))
34dc7c2f 6714 return (1);
572e2857
BB
6715 } else if (strcmp(protocol, "smb") == 0) {
6716 if (zfs_share_smb(zhp))
34dc7c2f 6717 return (1);
572e2857
BB
6718 } else {
6719 (void) fprintf(stderr, gettext("cannot share "
6720 "'%s': invalid share type '%s' "
6721 "specified\n"),
6722 zfs_get_name(zhp), protocol);
6723 return (1);
6724 }
34dc7c2f 6725
572e2857 6726 break;
34dc7c2f 6727
572e2857
BB
6728 case OP_MOUNT:
6729 if (options == NULL)
6730 mnt.mnt_mntopts = "";
6731 else
6732 mnt.mnt_mntopts = (char *)options;
34dc7c2f 6733
572e2857
BB
6734 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6735 zfs_is_mounted(zhp, NULL)) {
6736 if (!explicit)
6737 return (0);
34dc7c2f 6738
572e2857
BB
6739 (void) fprintf(stderr, gettext("cannot mount "
6740 "'%s': filesystem already mounted\n"),
6741 zfs_get_name(zhp));
6742 return (1);
34dc7c2f 6743 }
572e2857 6744
d1b84da8 6745 if (zfs_mount(zhp, options, flags) != 0)
572e2857
BB
6746 return (1);
6747 break;
6748 }
34dc7c2f 6749
34dc7c2f
BB
6750 return (0);
6751}
6752
6753/*
6754 * Reports progress in the form "(current/total)". Not thread-safe.
6755 */
6756static void
6757report_mount_progress(int current, int total)
6758{
428870ff 6759 static time_t last_progress_time = 0;
34dc7c2f 6760 time_t now = time(NULL);
428870ff 6761 char info[32];
34dc7c2f
BB
6762
6763 /* report 1..n instead of 0..n-1 */
6764 ++current;
6765
6766 /* display header if we're here for the first time */
6767 if (current == 1) {
428870ff 6768 set_progress_header(gettext("Mounting ZFS filesystems"));
34dc7c2f
BB
6769 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6770 /* too soon to report again */
6771 return;
6772 }
6773
6774 last_progress_time = now;
6775
428870ff 6776 (void) sprintf(info, "(%d/%d)", current, total);
34dc7c2f 6777
428870ff
BB
6778 if (current == total)
6779 finish_progress(info);
6780 else
6781 update_progress(info);
34dc7c2f
BB
6782}
6783
a10d50f9
SR
6784/*
6785 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
6786 * updates the progress meter.
6787 */
6788static int
6789share_mount_one_cb(zfs_handle_t *zhp, void *arg)
6790{
6791 share_mount_state_t *sms = arg;
6792 int ret;
6793
6794 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
6795 B_FALSE, sms->sm_options);
6796
6797 pthread_mutex_lock(&sms->sm_lock);
6798 if (ret != 0)
6799 sms->sm_status = ret;
6800 sms->sm_done++;
6801 if (sms->sm_verbose)
6802 report_mount_progress(sms->sm_done, sms->sm_total);
6803 pthread_mutex_unlock(&sms->sm_lock);
6804 return (ret);
6805}
6806
34dc7c2f
BB
6807static void
6808append_options(char *mntopts, char *newopts)
6809{
6810 int len = strlen(mntopts);
6811
6812 /* original length plus new string to append plus 1 for the comma */
6813 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6814 (void) fprintf(stderr, gettext("the opts argument for "
d6320ddb 6815 "'%s' option is too long (more than %d chars)\n"),
34dc7c2f
BB
6816 "-o", MNT_LINE_MAX);
6817 usage(B_FALSE);
6818 }
6819
6820 if (*mntopts)
6821 mntopts[len++] = ',';
6822
6823 (void) strcpy(&mntopts[len], newopts);
6824}
6825
6826static int
6827share_mount(int op, int argc, char **argv)
6828{
6829 int do_all = 0;
6830 boolean_t verbose = B_FALSE;
6831 int c, ret = 0;
6832 char *options = NULL;
572e2857 6833 int flags = 0;
34dc7c2f
BB
6834
6835 /* check options */
30af21b0 6836 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":alvo:Of" : "al"))
34dc7c2f
BB
6837 != -1) {
6838 switch (c) {
6839 case 'a':
6840 do_all = 1;
6841 break;
6842 case 'v':
6843 verbose = B_TRUE;
6844 break;
b5256303
TC
6845 case 'l':
6846 flags |= MS_CRYPT;
6847 break;
34dc7c2f
BB
6848 case 'o':
6849 if (*optarg == '\0') {
6850 (void) fprintf(stderr, gettext("empty mount "
6851 "options (-o) specified\n"));
6852 usage(B_FALSE);
6853 }
6854
6855 if (options == NULL)
6856 options = safe_malloc(MNT_LINE_MAX + 1);
6857
6858 /* option validation is done later */
6859 append_options(options, optarg);
6860 break;
e18be9a6
SC
6861 case 'O':
6862 flags |= MS_OVERLAY;
6863 break;
30af21b0
PD
6864 case 'f':
6865 flags |= MS_FORCE;
6866 break;
34dc7c2f
BB
6867 case ':':
6868 (void) fprintf(stderr, gettext("missing argument for "
6869 "'%c' option\n"), optopt);
6870 usage(B_FALSE);
6871 break;
6872 case '?':
6873 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6874 optopt);
6875 usage(B_FALSE);
6876 }
6877 }
6878
6879 argc -= optind;
6880 argv += optind;
6881
6882 /* check number of arguments */
6883 if (do_all) {
34dc7c2f
BB
6884 char *protocol = NULL;
6885
572e2857
BB
6886 if (op == OP_SHARE && argc > 0) {
6887 if (strcmp(argv[0], "nfs") != 0 &&
6888 strcmp(argv[0], "smb") != 0) {
34dc7c2f 6889 (void) fprintf(stderr, gettext("share type "
428870ff 6890 "must be 'nfs' or 'smb'\n"));
34dc7c2f
BB
6891 usage(B_FALSE);
6892 }
6893 protocol = argv[0];
6894 argc--;
6895 argv++;
34dc7c2f
BB
6896 }
6897
6898 if (argc != 0) {
6899 (void) fprintf(stderr, gettext("too many arguments\n"));
6900 usage(B_FALSE);
6901 }
6902
428870ff 6903 start_progress_timer();
a10d50f9
SR
6904 get_all_cb_t cb = { 0 };
6905 get_all_datasets(&cb, verbose);
34dc7c2f 6906
a10d50f9 6907 if (cb.cb_used == 0) {
e2c292bb 6908 if (options != NULL)
6909 free(options);
34dc7c2f 6910 return (0);
e2c292bb 6911 }
34dc7c2f 6912
a10d50f9
SR
6913 share_mount_state_t share_mount_state = { 0 };
6914 share_mount_state.sm_op = op;
6915 share_mount_state.sm_verbose = verbose;
6916 share_mount_state.sm_flags = flags;
6917 share_mount_state.sm_options = options;
6918 share_mount_state.sm_proto = protocol;
6919 share_mount_state.sm_total = cb.cb_used;
6920 pthread_mutex_init(&share_mount_state.sm_lock, NULL);
34dc7c2f 6921
a10d50f9
SR
6922 /*
6923 * libshare isn't mt-safe, so only do the operation in parallel
8e3c3ed1
TC
6924 * if we're mounting. Additionally, the key-loading option must
6925 * be serialized so that we can prompt the user for their keys
6926 * in a consistent manner.
a10d50f9
SR
6927 */
6928 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
8e3c3ed1
TC
6929 share_mount_one_cb, &share_mount_state,
6930 op == OP_MOUNT && !(flags & MS_CRYPT));
c15d36c6
GW
6931 zfs_commit_all_shares();
6932
a10d50f9 6933 ret = share_mount_state.sm_status;
34dc7c2f 6934
a10d50f9
SR
6935 for (int i = 0; i < cb.cb_used; i++)
6936 zfs_close(cb.cb_handles[i]);
6937 free(cb.cb_handles);
34dc7c2f
BB
6938 } else if (argc == 0) {
6939 struct mnttab entry;
6940
6941 if ((op == OP_SHARE) || (options != NULL)) {
6942 (void) fprintf(stderr, gettext("missing filesystem "
6943 "argument (specify -a for all)\n"));
6944 usage(B_FALSE);
6945 }
6946
6947 /*
79251738 6948 * When mount is given no arguments, go through
6949 * /proc/self/mounts and display any active ZFS mounts.
6950 * We hide any snapshots, since they are controlled
6951 * automatically.
34dc7c2f 6952 */
cbca6076
JL
6953
6954 /* Reopen MNTTAB to prevent reading stale data from open file */
e2c292bb 6955 if (freopen(MNTTAB, "r", mnttab_file) == NULL) {
6956 if (options != NULL)
6957 free(options);
cbca6076 6958 return (ENOENT);
e2c292bb 6959 }
cbca6076 6960
34dc7c2f
BB
6961 while (getmntent(mnttab_file, &entry) == 0) {
6962 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6963 strchr(entry.mnt_special, '@') != NULL)
6964 continue;
6965
6966 (void) printf("%-30s %s\n", entry.mnt_special,
6967 entry.mnt_mountp);
6968 }
6969
6970 } else {
6971 zfs_handle_t *zhp;
6972
34dc7c2f
BB
6973 if (argc > 1) {
6974 (void) fprintf(stderr,
6975 gettext("too many arguments\n"));
6976 usage(B_FALSE);
6977 }
6978
572e2857
BB
6979 if ((zhp = zfs_open(g_zfs, argv[0],
6980 ZFS_TYPE_FILESYSTEM)) == NULL) {
34dc7c2f
BB
6981 ret = 1;
6982 } else {
6983 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6984 options);
c15d36c6 6985 zfs_commit_all_shares();
34dc7c2f
BB
6986 zfs_close(zhp);
6987 }
6988 }
6989
e2c292bb 6990 if (options != NULL)
6991 free(options);
6992
34dc7c2f
BB
6993 return (ret);
6994}
6995
6996/*
428870ff 6997 * zfs mount -a [nfs]
34dc7c2f
BB
6998 * zfs mount filesystem
6999 *
7000 * Mount all filesystems, or mount the given filesystem.
7001 */
7002static int
7003zfs_do_mount(int argc, char **argv)
7004{
7005 return (share_mount(OP_MOUNT, argc, argv));
7006}
7007
7008/*
428870ff 7009 * zfs share -a [nfs | smb]
34dc7c2f
BB
7010 * zfs share filesystem
7011 *
7012 * Share all filesystems, or share the given filesystem.
7013 */
7014static int
7015zfs_do_share(int argc, char **argv)
7016{
7017 return (share_mount(OP_SHARE, argc, argv));
7018}
7019
7020typedef struct unshare_unmount_node {
7021 zfs_handle_t *un_zhp;
7022 char *un_mountp;
7023 uu_avl_node_t un_avlnode;
7024} unshare_unmount_node_t;
7025
7026/* ARGSUSED */
7027static int
7028unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
7029{
7030 const unshare_unmount_node_t *l = larg;
7031 const unshare_unmount_node_t *r = rarg;
7032
7033 return (strcmp(l->un_mountp, r->un_mountp));
7034}
7035
7036/*
7037 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
46df7e6c
JS
7038 * absolute path, find the entry /proc/self/mounts, verify that it's a
7039 * ZFS filesystem, and unmount it appropriately.
34dc7c2f
BB
7040 */
7041static int
7042unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
7043{
7044 zfs_handle_t *zhp;
ad60af8e 7045 int ret = 0;
34dc7c2f
BB
7046 struct stat64 statbuf;
7047 struct extmnttab entry;
7048 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
7049 ino_t path_inode;
7050
34dc7c2f
BB
7051 /*
7052 * Search for the given (major,minor) pair in the mount table.
7053 */
cbca6076
JL
7054
7055 /* Reopen MNTTAB to prevent reading stale data from open file */
7056 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
7057 return (ENOENT);
7058
d31277ab 7059 if (getextmntent(path, &entry, &statbuf) != 0) {
34dc7c2f
BB
7060 if (op == OP_SHARE) {
7061 (void) fprintf(stderr, gettext("cannot %s '%s': not "
7062 "currently mounted\n"), cmdname, path);
7063 return (1);
7064 }
79251738 7065 (void) fprintf(stderr, gettext("warning: %s not in"
7066 "/proc/self/mounts\n"), path);
34dc7c2f
BB
7067 if ((ret = umount2(path, flags)) != 0)
7068 (void) fprintf(stderr, gettext("%s: %s\n"), path,
7069 strerror(errno));
7070 return (ret != 0);
7071 }
d31277ab 7072 path_inode = statbuf.st_ino;
34dc7c2f
BB
7073
7074 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
7075 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
7076 "filesystem\n"), cmdname, path);
7077 return (1);
7078 }
7079
7080 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7081 ZFS_TYPE_FILESYSTEM)) == NULL)
7082 return (1);
7083
34dc7c2f 7084 ret = 1;
b128c09f
BB
7085 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
7086 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
7087 cmdname, path, strerror(errno));
7088 goto out;
7089 } else if (statbuf.st_ino != path_inode) {
7090 (void) fprintf(stderr, gettext("cannot "
7091 "%s '%s': not a mountpoint\n"), cmdname, path);
7092 goto out;
7093 }
7094
34dc7c2f
BB
7095 if (op == OP_SHARE) {
7096 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7097 char smbshare_prop[ZFS_MAXPROPLEN];
7098
7099 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
7100 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
7101 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
7102 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
7103
7104 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7105 strcmp(smbshare_prop, "off") == 0) {
7106 (void) fprintf(stderr, gettext("cannot unshare "
7107 "'%s': legacy share\n"), path);
9a616b5d
BB
7108 (void) fprintf(stderr, gettext("use exportfs(8) "
7109 "or smbcontrol(1) to unshare this filesystem\n"));
34dc7c2f
BB
7110 } else if (!zfs_is_shared(zhp)) {
7111 (void) fprintf(stderr, gettext("cannot unshare '%s': "
7112 "not currently shared\n"), path);
7113 } else {
7114 ret = zfs_unshareall_bypath(zhp, path);
c15d36c6 7115 zfs_commit_all_shares();
34dc7c2f
BB
7116 }
7117 } else {
7118 char mtpt_prop[ZFS_MAXPROPLEN];
7119
7120 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
7121 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
7122
b128c09f 7123 if (is_manual) {
34dc7c2f
BB
7124 ret = zfs_unmount(zhp, NULL, flags);
7125 } else if (strcmp(mtpt_prop, "legacy") == 0) {
7126 (void) fprintf(stderr, gettext("cannot unmount "
7127 "'%s': legacy mountpoint\n"),
7128 zfs_get_name(zhp));
9a616b5d 7129 (void) fprintf(stderr, gettext("use umount(8) "
34dc7c2f
BB
7130 "to unmount this filesystem\n"));
7131 } else {
7132 ret = zfs_unmountall(zhp, flags);
7133 }
7134 }
7135
b128c09f 7136out:
34dc7c2f
BB
7137 zfs_close(zhp);
7138
7139 return (ret != 0);
7140}
7141
7142/*
7143 * Generic callback for unsharing or unmounting a filesystem.
7144 */
7145static int
7146unshare_unmount(int op, int argc, char **argv)
7147{
7148 int do_all = 0;
7149 int flags = 0;
7150 int ret = 0;
572e2857 7151 int c;
34dc7c2f 7152 zfs_handle_t *zhp;
428870ff 7153 char nfs_mnt_prop[ZFS_MAXPROPLEN];
34dc7c2f
BB
7154 char sharesmb[ZFS_MAXPROPLEN];
7155
7156 /* check options */
765d1f06 7157 while ((c = getopt(argc, argv, op == OP_SHARE ? ":a" : "afu")) != -1) {
34dc7c2f
BB
7158 switch (c) {
7159 case 'a':
7160 do_all = 1;
7161 break;
7162 case 'f':
765d1f06
TC
7163 flags |= MS_FORCE;
7164 break;
7165 case 'u':
7166 flags |= MS_CRYPT;
34dc7c2f 7167 break;
2f71caf2 7168 case ':':
7169 (void) fprintf(stderr, gettext("missing argument for "
7170 "'%c' option\n"), optopt);
7171 usage(B_FALSE);
7172 break;
34dc7c2f
BB
7173 case '?':
7174 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7175 optopt);
7176 usage(B_FALSE);
7177 }
7178 }
7179
7180 argc -= optind;
7181 argv += optind;
7182
7183 if (do_all) {
7184 /*
7185 * We could make use of zfs_for_each() to walk all datasets in
7186 * the system, but this would be very inefficient, especially
79251738 7187 * since we would have to linearly search /proc/self/mounts for
7188 * each one. Instead, do one pass through /proc/self/mounts
7189 * looking for zfs entries and call zfs_unmount() for each one.
34dc7c2f
BB
7190 *
7191 * Things get a little tricky if the administrator has created
7192 * mountpoints beneath other ZFS filesystems. In this case, we
7193 * have to unmount the deepest filesystems first. To accomplish
7194 * this, we place all the mountpoints in an AVL tree sorted by
7195 * the special type (dataset name), and walk the result in
7196 * reverse to make sure to get any snapshots first.
7197 */
7198 struct mnttab entry;
7199 uu_avl_pool_t *pool;
149e873a 7200 uu_avl_t *tree = NULL;
34dc7c2f
BB
7201 unshare_unmount_node_t *node;
7202 uu_avl_index_t idx;
7203 uu_avl_walk_t *walk;
2f71caf2 7204 char *protocol = NULL;
7205
7206 if (op == OP_SHARE && argc > 0) {
7207 if (strcmp(argv[0], "nfs") != 0 &&
7208 strcmp(argv[0], "smb") != 0) {
7209 (void) fprintf(stderr, gettext("share type "
7210 "must be 'nfs' or 'smb'\n"));
7211 usage(B_FALSE);
7212 }
7213 protocol = argv[0];
7214 argc--;
7215 argv++;
7216 }
34dc7c2f
BB
7217
7218 if (argc != 0) {
7219 (void) fprintf(stderr, gettext("too many arguments\n"));
7220 usage(B_FALSE);
7221 }
7222
428870ff 7223 if (((pool = uu_avl_pool_create("unmount_pool",
34dc7c2f
BB
7224 sizeof (unshare_unmount_node_t),
7225 offsetof(unshare_unmount_node_t, un_avlnode),
428870ff
BB
7226 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
7227 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
7228 nomem();
34dc7c2f 7229
cbca6076
JL
7230 /* Reopen MNTTAB to prevent reading stale data from open file */
7231 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
7232 return (ENOENT);
7233
34dc7c2f
BB
7234 while (getmntent(mnttab_file, &entry) == 0) {
7235
7236 /* ignore non-ZFS entries */
7237 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
7238 continue;
7239
7240 /* ignore snapshots */
7241 if (strchr(entry.mnt_special, '@') != NULL)
7242 continue;
7243
7244 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7245 ZFS_TYPE_FILESYSTEM)) == NULL) {
7246 ret = 1;
7247 continue;
7248 }
7249
d21d5b82
GDN
7250 /*
7251 * Ignore datasets that are excluded/restricted by
7252 * parent pool name.
7253 */
7254 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
7255 zfs_close(zhp);
7256 continue;
7257 }
7258
34dc7c2f
BB
7259 switch (op) {
7260 case OP_SHARE:
7261 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
428870ff
BB
7262 nfs_mnt_prop,
7263 sizeof (nfs_mnt_prop),
34dc7c2f 7264 NULL, NULL, 0, B_FALSE) == 0);
428870ff 7265 if (strcmp(nfs_mnt_prop, "off") != 0)
34dc7c2f
BB
7266 break;
7267 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
428870ff
BB
7268 nfs_mnt_prop,
7269 sizeof (nfs_mnt_prop),
34dc7c2f 7270 NULL, NULL, 0, B_FALSE) == 0);
428870ff 7271 if (strcmp(nfs_mnt_prop, "off") == 0)
34dc7c2f
BB
7272 continue;
7273 break;
7274 case OP_MOUNT:
7275 /* Ignore legacy mounts */
7276 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
428870ff
BB
7277 nfs_mnt_prop,
7278 sizeof (nfs_mnt_prop),
34dc7c2f 7279 NULL, NULL, 0, B_FALSE) == 0);
428870ff 7280 if (strcmp(nfs_mnt_prop, "legacy") == 0)
34dc7c2f
BB
7281 continue;
7282 /* Ignore canmount=noauto mounts */
7283 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
7284 ZFS_CANMOUNT_NOAUTO)
7285 continue;
7286 default:
7287 break;
7288 }
7289
7290 node = safe_malloc(sizeof (unshare_unmount_node_t));
7291 node->un_zhp = zhp;
428870ff 7292 node->un_mountp = safe_strdup(entry.mnt_mountp);
34dc7c2f
BB
7293
7294 uu_avl_node_init(node, &node->un_avlnode, pool);
7295
7296 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
7297 uu_avl_insert(tree, node, idx);
7298 } else {
7299 zfs_close(node->un_zhp);
7300 free(node->un_mountp);
7301 free(node);
7302 }
7303 }
7304
7305 /*
7306 * Walk the AVL tree in reverse, unmounting each filesystem and
7307 * removing it from the AVL tree in the process.
7308 */
7309 if ((walk = uu_avl_walk_start(tree,
428870ff
BB
7310 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
7311 nomem();
34dc7c2f
BB
7312
7313 while ((node = uu_avl_walk_next(walk)) != NULL) {
4bc72196 7314 const char *mntarg = NULL;
34dc7c2f 7315
4bc72196 7316 uu_avl_remove(tree, node);
34dc7c2f
BB
7317 switch (op) {
7318 case OP_SHARE:
2f71caf2 7319 if (zfs_unshareall_bytype(node->un_zhp,
7320 node->un_mountp, protocol) != 0)
34dc7c2f
BB
7321 ret = 1;
7322 break;
7323
7324 case OP_MOUNT:
7325 if (zfs_unmount(node->un_zhp,
4bc72196 7326 mntarg, flags) != 0)
34dc7c2f
BB
7327 ret = 1;
7328 break;
7329 }
7330
7331 zfs_close(node->un_zhp);
7332 free(node->un_mountp);
7333 free(node);
7334 }
7335
c15d36c6
GW
7336 if (op == OP_SHARE)
7337 zfs_commit_shares(protocol);
7338
34dc7c2f
BB
7339 uu_avl_walk_end(walk);
7340 uu_avl_destroy(tree);
7341 uu_avl_pool_destroy(pool);
7342
34dc7c2f
BB
7343 } else {
7344 if (argc != 1) {
7345 if (argc == 0)
7346 (void) fprintf(stderr,
7347 gettext("missing filesystem argument\n"));
7348 else
7349 (void) fprintf(stderr,
7350 gettext("too many arguments\n"));
7351 usage(B_FALSE);
7352 }
7353
7354 /*
7355 * We have an argument, but it may be a full path or a ZFS
7356 * filesystem. Pass full paths off to unmount_path() (shared by
7357 * manual_unmount), otherwise open the filesystem and pass to
7358 * zfs_unmount().
7359 */
7360 if (argv[0][0] == '/')
7361 return (unshare_unmount_path(op, argv[0],
7362 flags, B_FALSE));
7363
572e2857
BB
7364 if ((zhp = zfs_open(g_zfs, argv[0],
7365 ZFS_TYPE_FILESYSTEM)) == NULL)
34dc7c2f
BB
7366 return (1);
7367
572e2857
BB
7368 verify(zfs_prop_get(zhp, op == OP_SHARE ?
7369 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
7370 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
7371 NULL, 0, B_FALSE) == 0);
34dc7c2f 7372
572e2857
BB
7373 switch (op) {
7374 case OP_SHARE:
7375 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7376 nfs_mnt_prop,
7377 sizeof (nfs_mnt_prop),
7378 NULL, NULL, 0, B_FALSE) == 0);
7379 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7380 sharesmb, sizeof (sharesmb), NULL, NULL,
7381 0, B_FALSE) == 0);
7382
7383 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7384 strcmp(sharesmb, "off") == 0) {
7385 (void) fprintf(stderr, gettext("cannot "
7386 "unshare '%s': legacy share\n"),
7387 zfs_get_name(zhp));
7388 (void) fprintf(stderr, gettext("use "
7389 "unshare(1M) to unshare this "
7390 "filesystem\n"));
7391 ret = 1;
7392 } else if (!zfs_is_shared(zhp)) {
7393 (void) fprintf(stderr, gettext("cannot "
7394 "unshare '%s': not currently "
7395 "shared\n"), zfs_get_name(zhp));
7396 ret = 1;
7397 } else if (zfs_unshareall(zhp) != 0) {
7398 ret = 1;
7399 }
7400 break;
34dc7c2f 7401
572e2857
BB
7402 case OP_MOUNT:
7403 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
7404 (void) fprintf(stderr, gettext("cannot "
7405 "unmount '%s': legacy "
7406 "mountpoint\n"), zfs_get_name(zhp));
7407 (void) fprintf(stderr, gettext("use "
7408 "umount(1M) to unmount this "
7409 "filesystem\n"));
7410 ret = 1;
7411 } else if (!zfs_is_mounted(zhp, NULL)) {
7412 (void) fprintf(stderr, gettext("cannot "
7413 "unmount '%s': not currently "
7414 "mounted\n"),
7415 zfs_get_name(zhp));
7416 ret = 1;
7417 } else if (zfs_unmountall(zhp, flags) != 0) {
7418 ret = 1;
34dc7c2f 7419 }
572e2857 7420 break;
34dc7c2f
BB
7421 }
7422
7423 zfs_close(zhp);
7424 }
7425
7426 return (ret);
7427}
7428
7429/*
765d1f06
TC
7430 * zfs unmount [-fu] -a
7431 * zfs unmount [-fu] filesystem
34dc7c2f
BB
7432 *
7433 * Unmount all filesystems, or a specific ZFS filesystem.
7434 */
7435static int
7436zfs_do_unmount(int argc, char **argv)
7437{
7438 return (unshare_unmount(OP_MOUNT, argc, argv));
7439}
7440
7441/*
7442 * zfs unshare -a
7443 * zfs unshare filesystem
7444 *
7445 * Unshare all filesystems, or a specific ZFS filesystem.
7446 */
7447static int
7448zfs_do_unshare(int argc, char **argv)
7449{
7450 return (unshare_unmount(OP_SHARE, argc, argv));
7451}
7452
34dc7c2f
BB
7453static int
7454find_command_idx(char *command, int *idx)
7455{
7456 int i;
7457
7458 for (i = 0; i < NCOMMAND; i++) {
7459 if (command_table[i].name == NULL)
7460 continue;
7461
7462 if (strcmp(command, command_table[i].name) == 0) {
7463 *idx = i;
7464 return (0);
7465 }
7466 }
7467 return (1);
7468}
7469
572e2857
BB
7470static int
7471zfs_do_diff(int argc, char **argv)
7472{
7473 zfs_handle_t *zhp;
7474 int flags = 0;
7475 char *tosnap = NULL;
7476 char *fromsnap = NULL;
7477 char *atp, *copy;
ad60af8e 7478 int err = 0;
572e2857 7479 int c;
2a15c00f 7480 struct sigaction sa;
572e2857
BB
7481
7482 while ((c = getopt(argc, argv, "FHt")) != -1) {
7483 switch (c) {
7484 case 'F':
7485 flags |= ZFS_DIFF_CLASSIFY;
7486 break;
7487 case 'H':
7488 flags |= ZFS_DIFF_PARSEABLE;
7489 break;
7490 case 't':
7491 flags |= ZFS_DIFF_TIMESTAMP;
7492 break;
7493 default:
7494 (void) fprintf(stderr,
7495 gettext("invalid option '%c'\n"), optopt);
7496 usage(B_FALSE);
7497 }
7498 }
7499
7500 argc -= optind;
7501 argv += optind;
7502
7503 if (argc < 1) {
7504 (void) fprintf(stderr,
a1d477c2 7505 gettext("must provide at least one snapshot name\n"));
572e2857
BB
7506 usage(B_FALSE);
7507 }
7508
7509 if (argc > 2) {
7510 (void) fprintf(stderr, gettext("too many arguments\n"));
7511 usage(B_FALSE);
7512 }
7513
7514 fromsnap = argv[0];
7515 tosnap = (argc == 2) ? argv[1] : NULL;
7516
7517 copy = NULL;
7518 if (*fromsnap != '@')
7519 copy = strdup(fromsnap);
7520 else if (tosnap)
7521 copy = strdup(tosnap);
7522 if (copy == NULL)
7523 usage(B_FALSE);
7524
648a09ad 7525 if ((atp = strchr(copy, '@')) != NULL)
572e2857
BB
7526 *atp = '\0';
7527
9ec0403d 7528 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL) {
7529 free(copy);
572e2857 7530 return (1);
9ec0403d 7531 }
572e2857
BB
7532 free(copy);
7533
7534 /*
7535 * Ignore SIGPIPE so that the library can give us
7536 * information on any failure
7537 */
2a15c00f
TK
7538 if (sigemptyset(&sa.sa_mask) == -1) {
7539 err = errno;
7540 goto out;
7541 }
7542 sa.sa_flags = 0;
7543 sa.sa_handler = SIG_IGN;
7544 if (sigaction(SIGPIPE, &sa, NULL) == -1) {
7545 err = errno;
7546 goto out;
7547 }
572e2857
BB
7548
7549 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
2a15c00f 7550out:
572e2857
BB
7551 zfs_close(zhp);
7552
7553 return (err != 0);
7554}
7555
da536844 7556/*
a73f361f 7557 * zfs bookmark <fs@source>|<fs#source> <fs#bookmark>
da536844 7558 *
a73f361f
CS
7559 * Creates a bookmark with the given name from the source snapshot
7560 * or creates a copy of an existing source bookmark.
da536844
MA
7561 */
7562static int
7563zfs_do_bookmark(int argc, char **argv)
7564{
a73f361f
CS
7565 char *source, *bookname;
7566 char expbuf[ZFS_MAX_DATASET_NAME_LEN];
7567 int source_type;
da536844
MA
7568 nvlist_t *nvl;
7569 int ret = 0;
7570 int c;
7571
7572 /* check options */
7573 while ((c = getopt(argc, argv, "")) != -1) {
7574 switch (c) {
7575 case '?':
7576 (void) fprintf(stderr,
7577 gettext("invalid option '%c'\n"), optopt);
7578 goto usage;
7579 }
7580 }
7581
7582 argc -= optind;
7583 argv += optind;
7584
7585 /* check number of arguments */
7586 if (argc < 1) {
a73f361f 7587 (void) fprintf(stderr, gettext("missing source argument\n"));
da536844
MA
7588 goto usage;
7589 }
7590 if (argc < 2) {
7591 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
7592 goto usage;
7593 }
7594
a73f361f
CS
7595 source = argv[0];
7596 bookname = argv[1];
7597
7598 if (strchr(source, '@') == NULL && strchr(source, '#') == NULL) {
4af6873a 7599 (void) fprintf(stderr,
a73f361f
CS
7600 gettext("invalid source name '%s': "
7601 "must contain a '@' or '#'\n"), source);
4af6873a 7602 goto usage;
7603 }
a73f361f 7604 if (strchr(bookname, '#') == NULL) {
da536844 7605 (void) fprintf(stderr,
587e228a 7606 gettext("invalid bookmark name '%s': "
a73f361f 7607 "must contain a '#'\n"), bookname);
da536844
MA
7608 goto usage;
7609 }
7610
a73f361f
CS
7611 /*
7612 * expand source or bookname to full path:
7613 * one of them may be specified as short name
7614 */
7615 {
7616 char **expand;
7617 char *source_short, *bookname_short;
7618 source_short = strpbrk(source, "@#");
7619 bookname_short = strpbrk(bookname, "#");
7620 if (source_short == source &&
7621 bookname_short == bookname) {
7622 (void) fprintf(stderr, gettext(
7623 "either source or bookmark must be specified as "
7624 "full dataset paths"));
7625 goto usage;
7626 } else if (source_short != source &&
7627 bookname_short != bookname) {
7628 expand = NULL;
7629 } else if (source_short != source) {
7630 strlcpy(expbuf, source, sizeof (expbuf));
7631 expand = &bookname;
7632 } else if (bookname_short != bookname) {
7633 strlcpy(expbuf, bookname, sizeof (expbuf));
7634 expand = &source;
7635 } else {
7636 abort();
7637 }
7638 if (expand != NULL) {
7639 *strpbrk(expbuf, "@#") = '\0'; /* dataset name in buf */
7640 (void) strlcat(expbuf, *expand, sizeof (expbuf));
7641 *expand = expbuf;
7642 }
da536844 7643 }
a73f361f
CS
7644
7645 /* determine source type */
7646 switch (*strpbrk(source, "@#")) {
7647 case '@': source_type = ZFS_TYPE_SNAPSHOT; break;
7648 case '#': source_type = ZFS_TYPE_BOOKMARK; break;
7649 default: abort();
587e228a 7650 }
7651
a73f361f
CS
7652 /* test the source exists */
7653 zfs_handle_t *zhp;
7654 zhp = zfs_open(g_zfs, source, source_type);
da536844
MA
7655 if (zhp == NULL)
7656 goto usage;
7657 zfs_close(zhp);
7658
da536844 7659 nvl = fnvlist_alloc();
a73f361f 7660 fnvlist_add_string(nvl, bookname, source);
da536844
MA
7661 ret = lzc_bookmark(nvl, NULL);
7662 fnvlist_free(nvl);
7663
7664 if (ret != 0) {
b83a0e2d 7665 const char *err_msg = NULL;
da536844
MA
7666 char errbuf[1024];
7667
7668 (void) snprintf(errbuf, sizeof (errbuf),
7669 dgettext(TEXT_DOMAIN,
587e228a 7670 "cannot create bookmark '%s'"), bookname);
da536844
MA
7671
7672 switch (ret) {
7673 case EXDEV:
7674 err_msg = "bookmark is in a different pool";
7675 break;
a73f361f
CS
7676 case ZFS_ERR_BOOKMARK_SOURCE_NOT_ANCESTOR:
7677 err_msg = "source is not an ancestor of the "
7678 "new bookmark's dataset";
7679 break;
da536844
MA
7680 case EEXIST:
7681 err_msg = "bookmark exists";
7682 break;
7683 case EINVAL:
7684 err_msg = "invalid argument";
7685 break;
7686 case ENOTSUP:
7687 err_msg = "bookmark feature not enabled";
7688 break;
3d45fdd6
MA
7689 case ENOSPC:
7690 err_msg = "out of space";
7691 break;
587e228a 7692 case ENOENT:
7693 err_msg = "dataset does not exist";
7694 break;
da536844 7695 default:
b83a0e2d 7696 (void) zfs_standard_error(g_zfs, ret, errbuf);
da536844
MA
7697 break;
7698 }
b83a0e2d
DB
7699 if (err_msg != NULL) {
7700 (void) fprintf(stderr, "%s: %s\n", errbuf,
7701 dgettext(TEXT_DOMAIN, err_msg));
7702 }
da536844
MA
7703 }
7704
3d45fdd6 7705 return (ret != 0);
da536844
MA
7706
7707usage:
7708 usage(B_FALSE);
7709 return (-1);
7710}
7711
d99a0153
CW
7712static int
7713zfs_do_channel_program(int argc, char **argv)
7714{
7715 int ret, fd, c;
7716 char *progbuf, *filename, *poolname;
7717 size_t progsize, progread;
b83a0e2d 7718 nvlist_t *outnvl = NULL;
d99a0153
CW
7719 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7720 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
272b5d73 7721 boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
d99a0153
CW
7722 zpool_handle_t *zhp;
7723
7724 /* check options */
272b5d73 7725 while ((c = getopt(argc, argv, "nt:m:j")) != -1) {
d99a0153
CW
7726 switch (c) {
7727 case 't':
7728 case 'm': {
7729 uint64_t arg;
7730 char *endp;
7731
7732 errno = 0;
7733 arg = strtoull(optarg, &endp, 0);
7734 if (errno != 0 || *endp != '\0') {
7735 (void) fprintf(stderr, gettext(
7736 "invalid argument "
7737 "'%s': expected integer\n"), optarg);
7738 goto usage;
7739 }
7740
7741 if (c == 't') {
917f475f 7742 instrlimit = arg;
d99a0153
CW
7743 } else {
7744 ASSERT3U(c, ==, 'm');
917f475f 7745 memlimit = arg;
d99a0153
CW
7746 }
7747 break;
7748 }
5b72a38d
SD
7749 case 'n': {
7750 sync_flag = B_FALSE;
7751 break;
7752 }
272b5d73
AP
7753 case 'j': {
7754 json_output = B_TRUE;
7755 break;
7756 }
d99a0153
CW
7757 case '?':
7758 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7759 optopt);
7760 goto usage;
7761 }
7762 }
7763
7764 argc -= optind;
7765 argv += optind;
7766
7767 if (argc < 2) {
7768 (void) fprintf(stderr,
7769 gettext("invalid number of arguments\n"));
7770 goto usage;
7771 }
7772
7773 poolname = argv[0];
7774 filename = argv[1];
7775 if (strcmp(filename, "-") == 0) {
7776 fd = 0;
7777 filename = "standard input";
7778 } else if ((fd = open(filename, O_RDONLY)) < 0) {
7779 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7780 filename, strerror(errno));
7781 return (1);
7782 }
7783
7784 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
62b2152e 7785 (void) fprintf(stderr, gettext("cannot open pool '%s'\n"),
d99a0153 7786 poolname);
cbce5813
DB
7787 if (fd != 0)
7788 (void) close(fd);
d99a0153
CW
7789 return (1);
7790 }
7791 zpool_close(zhp);
7792
7793 /*
7794 * Read in the channel program, expanding the program buffer as
7795 * necessary.
7796 */
7797 progread = 0;
7798 progsize = 1024;
7799 progbuf = safe_malloc(progsize);
7800 do {
7801 ret = read(fd, progbuf + progread, progsize - progread);
7802 progread += ret;
7803 if (progread == progsize && ret > 0) {
7804 progsize *= 2;
7805 progbuf = safe_realloc(progbuf, progsize);
7806 }
7807 } while (ret > 0);
7808
7809 if (fd != 0)
7810 (void) close(fd);
7811 if (ret < 0) {
7812 free(progbuf);
7813 (void) fprintf(stderr,
7814 gettext("cannot read '%s': %s\n"),
7815 filename, strerror(errno));
7816 return (1);
7817 }
7818 progbuf[progread] = '\0';
7819
7820 /*
7821 * Any remaining arguments are passed as arguments to the lua script as
7822 * a string array:
7823 * {
7824 * "argv" -> [ "arg 1", ... "arg n" ],
7825 * }
7826 */
7827 nvlist_t *argnvl = fnvlist_alloc();
7828 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7829
5b72a38d
SD
7830 if (sync_flag) {
7831 ret = lzc_channel_program(poolname, progbuf,
7832 instrlimit, memlimit, argnvl, &outnvl);
7833 } else {
7834 ret = lzc_channel_program_nosync(poolname, progbuf,
7835 instrlimit, memlimit, argnvl, &outnvl);
7836 }
d99a0153
CW
7837
7838 if (ret != 0) {
7839 /*
7840 * On error, report the error message handed back by lua if one
7841 * exists. Otherwise, generate an appropriate error message,
7842 * falling back on strerror() for an unexpected return code.
7843 */
7844 char *errstring = NULL;
b83a0e2d 7845 const char *msg = gettext("Channel program execution failed");
d99a0153 7846 uint64_t instructions = 0;
b83a0e2d 7847 if (outnvl != NULL && nvlist_exists(outnvl, ZCP_RET_ERROR)) {
d99a0153
CW
7848 (void) nvlist_lookup_string(outnvl,
7849 ZCP_RET_ERROR, &errstring);
7850 if (errstring == NULL)
7851 errstring = strerror(ret);
7852 if (ret == ETIME) {
7853 (void) nvlist_lookup_uint64(outnvl,
7854 ZCP_ARG_INSTRLIMIT, &instructions);
7855 }
7856 } else {
7857 switch (ret) {
7858 case EINVAL:
7859 errstring =
7860 "Invalid instruction or memory limit.";
7861 break;
7862 case ENOMEM:
7863 errstring = "Return value too large.";
7864 break;
7865 case ENOSPC:
7866 errstring = "Memory limit exhausted.";
7867 break;
7868 case ETIME:
7869 errstring = "Timed out.";
7870 break;
7871 case EPERM:
7872 errstring = "Permission denied. Channel "
7873 "programs must be run as root.";
7874 break;
7875 default:
b83a0e2d 7876 (void) zfs_standard_error(g_zfs, ret, msg);
d99a0153
CW
7877 }
7878 }
b83a0e2d
DB
7879 if (errstring != NULL)
7880 (void) fprintf(stderr, "%s:\n%s\n", msg, errstring);
7881
d99a0153 7882 if (ret == ETIME && instructions != 0)
272b5d73
AP
7883 (void) fprintf(stderr,
7884 gettext("%llu Lua instructions\n"),
d99a0153
CW
7885 (u_longlong_t)instructions);
7886 } else {
272b5d73
AP
7887 if (json_output) {
7888 (void) nvlist_print_json(stdout, outnvl);
7889 } else if (nvlist_empty(outnvl)) {
7890 (void) fprintf(stdout, gettext("Channel program fully "
7891 "executed and did not produce output.\n"));
d99a0153 7892 } else {
272b5d73
AP
7893 (void) fprintf(stdout, gettext("Channel program fully "
7894 "executed and produced output:\n"));
d99a0153
CW
7895 dump_nvlist(outnvl, 4);
7896 }
7897 }
7898
7899 free(progbuf);
7900 fnvlist_free(outnvl);
7901 fnvlist_free(argnvl);
7902 return (ret != 0);
7903
7904usage:
7905 usage(B_FALSE);
7906 return (-1);
7907}
7908
7909
b5256303
TC
7910typedef struct loadkey_cbdata {
7911 boolean_t cb_loadkey;
7912 boolean_t cb_recursive;
7913 boolean_t cb_noop;
7914 char *cb_keylocation;
7915 uint64_t cb_numfailed;
7916 uint64_t cb_numattempted;
7917} loadkey_cbdata_t;
7918
7919static int
7920load_key_callback(zfs_handle_t *zhp, void *data)
7921{
7922 int ret;
7923 boolean_t is_encroot;
7924 loadkey_cbdata_t *cb = data;
7925 uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
7926
7927 /*
7928 * If we are working recursively, we want to skip loading / unloading
7929 * keys for non-encryption roots and datasets whose keys are already
7930 * in the desired end-state.
7931 */
7932 if (cb->cb_recursive) {
7933 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
7934 if (ret != 0)
7935 return (ret);
7936 if (!is_encroot)
7937 return (0);
7938
7939 if ((cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_AVAILABLE) ||
7940 (!cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_UNAVAILABLE))
7941 return (0);
7942 }
7943
7944 cb->cb_numattempted++;
7945
7946 if (cb->cb_loadkey)
7947 ret = zfs_crypto_load_key(zhp, cb->cb_noop, cb->cb_keylocation);
7948 else
7949 ret = zfs_crypto_unload_key(zhp);
7950
7951 if (ret != 0) {
7952 cb->cb_numfailed++;
7953 return (ret);
7954 }
7955
7956 return (0);
7957}
7958
7959static int
7960load_unload_keys(int argc, char **argv, boolean_t loadkey)
7961{
7962 int c, ret = 0, flags = 0;
7963 boolean_t do_all = B_FALSE;
7964 loadkey_cbdata_t cb = { 0 };
7965
7966 cb.cb_loadkey = loadkey;
7967
7968 while ((c = getopt(argc, argv, "anrL:")) != -1) {
7969 /* noop and alternate keylocations only apply to zfs load-key */
7970 if (loadkey) {
7971 switch (c) {
7972 case 'n':
7973 cb.cb_noop = B_TRUE;
7974 continue;
7975 case 'L':
7976 cb.cb_keylocation = optarg;
7977 continue;
7978 default:
7979 break;
7980 }
7981 }
7982
7983 switch (c) {
7984 case 'a':
7985 do_all = B_TRUE;
7986 cb.cb_recursive = B_TRUE;
7987 break;
7988 case 'r':
7989 flags |= ZFS_ITER_RECURSE;
7990 cb.cb_recursive = B_TRUE;
7991 break;
7992 default:
7993 (void) fprintf(stderr,
7994 gettext("invalid option '%c'\n"), optopt);
7995 usage(B_FALSE);
7996 }
7997 }
7998
7999 argc -= optind;
8000 argv += optind;
8001
8002 if (!do_all && argc == 0) {
8003 (void) fprintf(stderr,
8004 gettext("Missing dataset argument or -a option\n"));
8005 usage(B_FALSE);
8006 }
8007
8008 if (do_all && argc != 0) {
8009 (void) fprintf(stderr,
8010 gettext("Cannot specify dataset with -a option\n"));
8011 usage(B_FALSE);
8012 }
8013
8014 if (cb.cb_recursive && cb.cb_keylocation != NULL &&
8015 strcmp(cb.cb_keylocation, "prompt") != 0) {
8016 (void) fprintf(stderr, gettext("alternate keylocation may only "
8017 "be 'prompt' with -r or -a\n"));
8018 usage(B_FALSE);
8019 }
8020
8021 ret = zfs_for_each(argc, argv, flags,
8022 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL, 0,
8023 load_key_callback, &cb);
8024
8025 if (cb.cb_noop || (cb.cb_recursive && cb.cb_numattempted != 0)) {
8026 (void) printf(gettext("%llu / %llu key(s) successfully %s\n"),
8027 (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
8028 (u_longlong_t)cb.cb_numattempted,
8029 loadkey ? (cb.cb_noop ? "verified" : "loaded") :
8030 "unloaded");
8031 }
8032
8033 if (cb.cb_numfailed != 0)
8034 ret = -1;
8035
8036 return (ret);
8037}
8038
8039static int
8040zfs_do_load_key(int argc, char **argv)
8041{
8042 return (load_unload_keys(argc, argv, B_TRUE));
8043}
8044
8045
8046static int
8047zfs_do_unload_key(int argc, char **argv)
8048{
8049 return (load_unload_keys(argc, argv, B_FALSE));
8050}
8051
8052static int
8053zfs_do_change_key(int argc, char **argv)
8054{
8055 int c, ret;
8056 uint64_t keystatus;
8057 boolean_t loadkey = B_FALSE, inheritkey = B_FALSE;
8058 zfs_handle_t *zhp = NULL;
8059 nvlist_t *props = fnvlist_alloc();
8060
8061 while ((c = getopt(argc, argv, "lio:")) != -1) {
8062 switch (c) {
8063 case 'l':
8064 loadkey = B_TRUE;
8065 break;
8066 case 'i':
8067 inheritkey = B_TRUE;
8068 break;
8069 case 'o':
8070 if (!parseprop(props, optarg)) {
8071 nvlist_free(props);
8072 return (1);
8073 }
8074 break;
8075 default:
8076 (void) fprintf(stderr,
8077 gettext("invalid option '%c'\n"), optopt);
8078 usage(B_FALSE);
8079 }
8080 }
8081
8082 if (inheritkey && !nvlist_empty(props)) {
8083 (void) fprintf(stderr,
8084 gettext("Properties not allowed for inheriting\n"));
8085 usage(B_FALSE);
8086 }
8087
8088 argc -= optind;
8089 argv += optind;
8090
8091 if (argc < 1) {
8092 (void) fprintf(stderr, gettext("Missing dataset argument\n"));
8093 usage(B_FALSE);
8094 }
8095
8096 if (argc > 1) {
8097 (void) fprintf(stderr, gettext("Too many arguments\n"));
8098 usage(B_FALSE);
8099 }
8100
8101 zhp = zfs_open(g_zfs, argv[argc - 1],
8102 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
8103 if (zhp == NULL)
8104 usage(B_FALSE);
8105
8106 if (loadkey) {
8107 keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8108 if (keystatus != ZFS_KEYSTATUS_AVAILABLE) {
8109 ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
4807c0ba
TC
8110 if (ret != 0) {
8111 nvlist_free(props);
8112 zfs_close(zhp);
8113 return (-1);
8114 }
b5256303
TC
8115 }
8116
4807c0ba 8117 /* refresh the properties so the new keystatus is visible */
b5256303
TC
8118 zfs_refresh_properties(zhp);
8119 }
8120
8121 ret = zfs_crypto_rewrap(zhp, props, inheritkey);
4807c0ba
TC
8122 if (ret != 0) {
8123 nvlist_free(props);
8124 zfs_close(zhp);
8125 return (-1);
8126 }
b5256303
TC
8127
8128 nvlist_free(props);
8129 zfs_close(zhp);
8130 return (0);
b5256303
TC
8131}
8132
9c5167d1
NF
8133/*
8134 * 1) zfs project [-d|-r] <file|directory ...>
8135 * List project ID and inherit flag of file(s) or directories.
8136 * -d: List the directory itself, not its children.
8137 * -r: List subdirectories recursively.
8138 *
8139 * 2) zfs project -C [-k] [-r] <file|directory ...>
8140 * Clear project inherit flag and/or ID on the file(s) or directories.
8141 * -k: Keep the project ID unchanged. If not specified, the project ID
8142 * will be reset as zero.
8143 * -r: Clear on subdirectories recursively.
8144 *
8145 * 3) zfs project -c [-0] [-d|-r] [-p id] <file|directory ...>
8146 * Check project ID and inherit flag on the file(s) or directories,
8147 * report the outliers.
8148 * -0: Print file name followed by a NUL instead of newline.
8149 * -d: Check the directory itself, not its children.
8150 * -p: Specify the referenced ID for comparing with the target file(s)
8151 * or directories' project IDs. If not specified, the target (top)
8152 * directory's project ID will be used as the referenced one.
8153 * -r: Check subdirectories recursively.
8154 *
8155 * 4) zfs project [-p id] [-r] [-s] <file|directory ...>
8156 * Set project ID and/or inherit flag on the file(s) or directories.
8157 * -p: Set the project ID as the given id.
ad0b23b1 8158 * -r: Set on subdirectories recursively. If not specify "-p" option,
9c5167d1
NF
8159 * it will use top-level directory's project ID as the given id,
8160 * then set both project ID and inherit flag on all descendants
8161 * of the top-level directory.
8162 * -s: Set project inherit flag.
8163 */
8164static int
8165zfs_do_project(int argc, char **argv)
8166{
8167 zfs_project_control_t zpc = {
8168 .zpc_expected_projid = ZFS_INVALID_PROJID,
8169 .zpc_op = ZFS_PROJECT_OP_DEFAULT,
8170 .zpc_dironly = B_FALSE,
8171 .zpc_keep_projid = B_FALSE,
8172 .zpc_newline = B_TRUE,
8173 .zpc_recursive = B_FALSE,
8174 .zpc_set_flag = B_FALSE,
8175 };
8176 int ret = 0, c;
8177
8178 if (argc < 2)
8179 usage(B_FALSE);
8180
8181 while ((c = getopt(argc, argv, "0Ccdkp:rs")) != -1) {
8182 switch (c) {
8183 case '0':
8184 zpc.zpc_newline = B_FALSE;
8185 break;
8186 case 'C':
8187 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8188 (void) fprintf(stderr, gettext("cannot "
8189 "specify '-C' '-c' '-s' together\n"));
8190 usage(B_FALSE);
8191 }
8192
8193 zpc.zpc_op = ZFS_PROJECT_OP_CLEAR;
8194 break;
8195 case 'c':
8196 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8197 (void) fprintf(stderr, gettext("cannot "
8198 "specify '-C' '-c' '-s' together\n"));
8199 usage(B_FALSE);
8200 }
8201
8202 zpc.zpc_op = ZFS_PROJECT_OP_CHECK;
8203 break;
8204 case 'd':
8205 zpc.zpc_dironly = B_TRUE;
8206 /* overwrite "-r" option */
8207 zpc.zpc_recursive = B_FALSE;
8208 break;
8209 case 'k':
8210 zpc.zpc_keep_projid = B_TRUE;
8211 break;
8212 case 'p': {
8213 char *endptr;
8214
8215 errno = 0;
8216 zpc.zpc_expected_projid = strtoull(optarg, &endptr, 0);
8217 if (errno != 0 || *endptr != '\0') {
8218 (void) fprintf(stderr,
8219 gettext("project ID must be less than "
8220 "%u\n"), UINT32_MAX);
8221 usage(B_FALSE);
8222 }
8223 if (zpc.zpc_expected_projid >= UINT32_MAX) {
8224 (void) fprintf(stderr,
8225 gettext("invalid project ID\n"));
8226 usage(B_FALSE);
8227 }
8228 break;
8229 }
8230 case 'r':
8231 zpc.zpc_recursive = B_TRUE;
8232 /* overwrite "-d" option */
8233 zpc.zpc_dironly = B_FALSE;
8234 break;
8235 case 's':
8236 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8237 (void) fprintf(stderr, gettext("cannot "
8238 "specify '-C' '-c' '-s' together\n"));
8239 usage(B_FALSE);
8240 }
8241
8242 zpc.zpc_set_flag = B_TRUE;
8243 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8244 break;
8245 default:
8246 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8247 optopt);
8248 usage(B_FALSE);
8249 }
8250 }
8251
8252 if (zpc.zpc_op == ZFS_PROJECT_OP_DEFAULT) {
8253 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID)
8254 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8255 else
8256 zpc.zpc_op = ZFS_PROJECT_OP_LIST;
8257 }
8258
8259 switch (zpc.zpc_op) {
8260 case ZFS_PROJECT_OP_LIST:
8261 if (zpc.zpc_keep_projid) {
8262 (void) fprintf(stderr,
8263 gettext("'-k' is only valid together with '-C'\n"));
8264 usage(B_FALSE);
8265 }
8266 if (!zpc.zpc_newline) {
8267 (void) fprintf(stderr,
8268 gettext("'-0' is only valid together with '-c'\n"));
8269 usage(B_FALSE);
8270 }
8271 break;
8272 case ZFS_PROJECT_OP_CHECK:
8273 if (zpc.zpc_keep_projid) {
8274 (void) fprintf(stderr,
8275 gettext("'-k' is only valid together with '-C'\n"));
8276 usage(B_FALSE);
8277 }
8278 break;
8279 case ZFS_PROJECT_OP_CLEAR:
8280 if (zpc.zpc_dironly) {
8281 (void) fprintf(stderr,
8282 gettext("'-d' is useless together with '-C'\n"));
8283 usage(B_FALSE);
8284 }
8285 if (!zpc.zpc_newline) {
8286 (void) fprintf(stderr,
8287 gettext("'-0' is only valid together with '-c'\n"));
8288 usage(B_FALSE);
8289 }
8290 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID) {
8291 (void) fprintf(stderr,
8292 gettext("'-p' is useless together with '-C'\n"));
8293 usage(B_FALSE);
8294 }
8295 break;
8296 case ZFS_PROJECT_OP_SET:
8297 if (zpc.zpc_dironly) {
8298 (void) fprintf(stderr,
8299 gettext("'-d' is useless for set project ID and/or "
8300 "inherit flag\n"));
8301 usage(B_FALSE);
8302 }
8303 if (zpc.zpc_keep_projid) {
8304 (void) fprintf(stderr,
8305 gettext("'-k' is only valid together with '-C'\n"));
8306 usage(B_FALSE);
8307 }
8308 if (!zpc.zpc_newline) {
8309 (void) fprintf(stderr,
8310 gettext("'-0' is only valid together with '-c'\n"));
8311 usage(B_FALSE);
8312 }
8313 break;
8314 default:
8315 ASSERT(0);
8316 break;
8317 }
8318
8319 argv += optind;
8320 argc -= optind;
8321 if (argc == 0) {
8322 (void) fprintf(stderr,
8323 gettext("missing file or directory target(s)\n"));
8324 usage(B_FALSE);
8325 }
8326
8327 for (int i = 0; i < argc; i++) {
8328 int err;
8329
8330 err = zfs_project_handle(argv[i], &zpc);
8331 if (err && !ret)
8332 ret = err;
8333 }
8334
8335 return (ret);
8336}
8337
5a42ef04
PD
8338static int
8339zfs_do_wait(int argc, char **argv)
8340{
8341 boolean_t enabled[ZFS_WAIT_NUM_ACTIVITIES];
8342 int error, i;
8343 char c;
8344
8345 /* By default, wait for all types of activity. */
8346 for (i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++)
8347 enabled[i] = B_TRUE;
8348
8349 while ((c = getopt(argc, argv, "t:")) != -1) {
8350 switch (c) {
8351 case 't':
8352 {
8353 static char *col_subopts[] = { "deleteq", NULL };
8354 char *value;
8355
8356 /* Reset activities array */
8357 bzero(&enabled, sizeof (enabled));
8358 while (*optarg != '\0') {
8359 int activity = getsubopt(&optarg, col_subopts,
8360 &value);
8361
8362 if (activity < 0) {
8363 (void) fprintf(stderr,
8364 gettext("invalid activity '%s'\n"),
8365 value);
8366 usage(B_FALSE);
8367 }
8368
8369 enabled[activity] = B_TRUE;
8370 }
8371 break;
8372 }
8373 case '?':
8374 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8375 optopt);
8376 usage(B_FALSE);
8377 }
8378 }
8379
8380 argv += optind;
8381 argc -= optind;
8382 if (argc < 1) {
8383 (void) fprintf(stderr, gettext("missing 'filesystem' "
8384 "argument\n"));
8385 usage(B_FALSE);
8386 }
8387 if (argc > 1) {
8388 (void) fprintf(stderr, gettext("too many arguments\n"));
8389 usage(B_FALSE);
8390 }
8391
8392 zfs_handle_t *zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM);
8393 if (zhp == NULL)
8394 return (1);
8395
8396 for (;;) {
8397 boolean_t missing = B_FALSE;
8398 boolean_t any_waited = B_FALSE;
8399
8400 for (int i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++) {
8401 boolean_t waited;
8402
8403 if (!enabled[i])
8404 continue;
8405
8406 error = zfs_wait_status(zhp, i, &missing, &waited);
8407 if (error != 0 || missing)
8408 break;
8409
8410 any_waited = (any_waited || waited);
8411 }
8412
8413 if (error != 0 || missing || !any_waited)
8414 break;
8415 }
8416
8417 zfs_close(zhp);
8418
8419 return (error);
8420}
8421
50478c6d
T
8422/*
8423 * Display version message
8424 */
8425static int
8426zfs_do_version(int argc, char **argv)
8427{
8428 if (zfs_version_print() == -1)
8429 return (1);
8430
8431 return (0);
8432}
8433
34dc7c2f
BB
8434int
8435main(int argc, char **argv)
8436{
ad60af8e 8437 int ret = 0;
d4ed6673 8438 int i = 0;
34dc7c2f 8439 char *cmdname;
edc05fdb 8440 char **newargv;
34dc7c2f
BB
8441
8442 (void) setlocale(LC_ALL, "");
8443 (void) textdomain(TEXT_DOMAIN);
8444
8445 opterr = 0;
8446
34dc7c2f 8447 /*
d53368f6 8448 * Make sure the user has specified some command.
34dc7c2f 8449 */
d53368f6
BB
8450 if (argc < 2) {
8451 (void) fprintf(stderr, gettext("missing command\n"));
8452 usage(B_FALSE);
8453 }
34dc7c2f 8454
d53368f6 8455 cmdname = argv[1];
34dc7c2f 8456
d53368f6
BB
8457 /*
8458 * The 'umount' command is an alias for 'unmount'
8459 */
8460 if (strcmp(cmdname, "umount") == 0)
8461 cmdname = "unmount";
34dc7c2f 8462
d53368f6
BB
8463 /*
8464 * The 'recv' command is an alias for 'receive'
8465 */
8466 if (strcmp(cmdname, "recv") == 0)
8467 cmdname = "receive";
34dc7c2f 8468
10b75496
S
8469 /*
8470 * The 'snap' command is an alias for 'snapshot'
8471 */
8472 if (strcmp(cmdname, "snap") == 0)
8473 cmdname = "snapshot";
8474
d53368f6
BB
8475 /*
8476 * Special case '-?'
8477 */
8478 if ((strcmp(cmdname, "-?") == 0) ||
8479 (strcmp(cmdname, "--help") == 0))
8480 usage(B_TRUE);
34dc7c2f 8481
50478c6d
T
8482 /*
8483 * Special case '-V|--version'
8484 */
8485 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
8486 return (zfs_do_version(argc, argv));
8487
65037d9b 8488 if ((g_zfs = libzfs_init()) == NULL) {
afc8f0a6 8489 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
d53368f6 8490 return (1);
65037d9b 8491 }
9b020fd9 8492
0bc7a7a7
TF
8493 mnttab_file = g_zfs->libzfs_mnttab;
8494
6f1ffb06 8495 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
9b020fd9 8496
d53368f6 8497 libzfs_print_on_error(g_zfs, B_TRUE);
9b020fd9 8498
edc05fdb
D
8499 /*
8500 * Many commands modify input strings for string parsing reasons.
8501 * We create a copy to protect the original argv.
8502 */
8503 newargv = malloc((argc + 1) * sizeof (newargv[0]));
8504 for (i = 0; i < argc; i++)
8505 newargv[i] = strdup(argv[i]);
8506 newargv[argc] = NULL;
8507
d53368f6
BB
8508 /*
8509 * Run the appropriate command.
8510 */
e0730668 8511 libzfs_mnttab_cache(g_zfs, B_TRUE);
d53368f6
BB
8512 if (find_command_idx(cmdname, &i) == 0) {
8513 current_command = &command_table[i];
edc05fdb 8514 ret = command_table[i].func(argc - 1, newargv + 1);
d53368f6
BB
8515 } else if (strchr(cmdname, '=') != NULL) {
8516 verify(find_command_idx("set", &i) == 0);
8517 current_command = &command_table[i];
edc05fdb 8518 ret = command_table[i].func(argc, newargv);
d53368f6
BB
8519 } else {
8520 (void) fprintf(stderr, gettext("unrecognized "
8521 "command '%s'\n"), cmdname);
8522 usage(B_FALSE);
8523 ret = 1;
34dc7c2f
BB
8524 }
8525
edc05fdb
D
8526 for (i = 0; i < argc; i++)
8527 free(newargv[i]);
8528 free(newargv);
8529
6f1ffb06
MA
8530 if (ret == 0 && log_history)
8531 (void) zpool_log_history(g_zfs, history_str);
8532
fb8e608d
TC
8533 libzfs_fini(g_zfs);
8534
34dc7c2f
BB
8535 /*
8536 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
8537 * for the purposes of running ::findleaks.
8538 */
8539 if (getenv("ZFS_ABORT") != NULL) {
8540 (void) printf("dumping core by request\n");
8541 abort();
8542 }
8543
8544 return (ret);
8545}
4bc72196
MM
8546
8547#ifdef __FreeBSD__
8548#include <sys/jail.h>
8549#include <jail.h>
8550/*
8551 * Attach/detach the given dataset to/from the given jail
8552 */
8553/* ARGSUSED */
8554static int
8555zfs_do_jail_impl(int argc, char **argv, boolean_t attach)
8556{
8557 zfs_handle_t *zhp;
8558 int jailid, ret;
8559
8560 /* check number of arguments */
8561 if (argc < 3) {
8562 (void) fprintf(stderr, gettext("missing argument(s)\n"));
8563 usage(B_FALSE);
8564 }
8565 if (argc > 3) {
8566 (void) fprintf(stderr, gettext("too many arguments\n"));
8567 usage(B_FALSE);
8568 }
8569
8570 jailid = jail_getid(argv[1]);
8571 if (jailid < 0) {
8572 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
8573 usage(B_FALSE);
8574 }
8575
8576 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
8577 if (zhp == NULL)
8578 return (1);
8579
8580 ret = (zfs_jail(zhp, jailid, attach) != 0);
8581
8582 zfs_close(zhp);
8583 return (ret);
8584}
8585
8586/*
8587 * zfs jail jailid filesystem
8588 *
8589 * Attach the given dataset to the given jail
8590 */
8591/* ARGSUSED */
8592static int
8593zfs_do_jail(int argc, char **argv)
8594{
8595 return (zfs_do_jail_impl(argc, argv, B_TRUE));
8596}
8597
8598/*
8599 * zfs unjail jailid filesystem
8600 *
8601 * Detach the given dataset from the given jail
8602 */
8603/* ARGSUSED */
8604static int
8605zfs_do_unjail(int argc, char **argv)
8606{
8607 return (zfs_do_jail_impl(argc, argv, B_FALSE));
8608}
8609#endif