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