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