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