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