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