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