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