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