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