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