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