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