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