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