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