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