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