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