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