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