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