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