]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
MFC r344601 (by sef): Set process title during zfs send.
[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:RbDpVvnPLet: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                         flags.progress = B_TRUE;
3842                         flags.progressastitle = B_TRUE;
3843                         break;
3844                 case 'v':
3845                         if (flags.verbose)
3846                                 extraverbose = B_TRUE;
3847                         flags.verbose = B_TRUE;
3848                         flags.progress = B_TRUE;
3849                         break;
3850                 case 'D':
3851                         flags.dedup = B_TRUE;
3852                         break;
3853                 case 'n':
3854                         flags.dryrun = B_TRUE;
3855                         break;
3856                 case 'L':
3857                         flags.largeblock = B_TRUE;
3858                         break;
3859                 case 'e':
3860                         flags.embed_data = B_TRUE;
3861                         break;
3862                 case 't':
3863                         resume_token = optarg;
3864                         break;
3865                 case 'c':
3866                         flags.compress = B_TRUE;
3867                         break;
3868                 case ':':
3869                         (void) fprintf(stderr, gettext("missing argument for "
3870                             "'%c' option\n"), optopt);
3871                         usage(B_FALSE);
3872                         break;
3873                 case '?':
3874                         /*FALLTHROUGH*/
3875                 default:
3876                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3877                             optopt);
3878                         usage(B_FALSE);
3879                 }
3880         }
3881
3882         argc -= optind;
3883         argv += optind;
3884
3885         if (resume_token != NULL) {
3886                 if (fromname != NULL || flags.replicate || flags.props ||
3887                     flags.dedup) {
3888                         (void) fprintf(stderr,
3889                             gettext("invalid flags combined with -t\n"));
3890                         usage(B_FALSE);
3891                 }
3892                 if (argc != 0) {
3893                         (void) fprintf(stderr, gettext("no additional "
3894                             "arguments are permitted with -t\n"));
3895                         usage(B_FALSE);
3896                 }
3897         } else {
3898                 if (argc < 1) {
3899                         (void) fprintf(stderr,
3900                             gettext("missing snapshot argument\n"));
3901                         usage(B_FALSE);
3902                 }
3903                 if (argc > 1) {
3904                         (void) fprintf(stderr, gettext("too many arguments\n"));
3905                         usage(B_FALSE);
3906                 }
3907         }
3908
3909         if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3910                 (void) fprintf(stderr,
3911                     gettext("Error: Stream can not be written to a terminal.\n"
3912                     "You must redirect standard output.\n"));
3913                 return (1);
3914         }
3915
3916         if (resume_token != NULL) {
3917                 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3918                     resume_token));
3919         }
3920
3921         /*
3922          * Special case sending a filesystem, or from a bookmark.
3923          */
3924         if (strchr(argv[0], '@') == NULL ||
3925             (fromname && strchr(fromname, '#') != NULL)) {
3926                 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
3927                 enum lzc_send_flags lzc_flags = 0;
3928
3929                 if (flags.replicate || flags.doall || flags.props ||
3930                     flags.dedup || flags.dryrun || flags.verbose ||
3931                     flags.progress) {
3932                         (void) fprintf(stderr,
3933                             gettext("Error: "
3934                             "Unsupported flag with filesystem or bookmark.\n"));
3935                         return (1);
3936                 }
3937
3938                 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3939                 if (zhp == NULL)
3940                         return (1);
3941
3942                 if (flags.largeblock)
3943                         lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3944                 if (flags.embed_data)
3945                         lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3946                 if (flags.compress)
3947                         lzc_flags |= LZC_SEND_FLAG_COMPRESS;
3948
3949                 if (fromname != NULL &&
3950                     (fromname[0] == '#' || fromname[0] == '@')) {
3951                         /*
3952                          * Incremental source name begins with # or @.
3953                          * Default to same fs as target.
3954                          */
3955                         (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3956                         cp = strchr(frombuf, '@');
3957                         if (cp != NULL)
3958                                 *cp = '\0';
3959                         (void) strlcat(frombuf, fromname, sizeof (frombuf));
3960                         fromname = frombuf;
3961                 }
3962                 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3963                 zfs_close(zhp);
3964                 return (err != 0);
3965         }
3966
3967         cp = strchr(argv[0], '@');
3968         *cp = '\0';
3969         toname = cp + 1;
3970         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3971         if (zhp == NULL)
3972                 return (1);
3973
3974         /*
3975          * If they specified the full path to the snapshot, chop off
3976          * everything except the short name of the snapshot, but special
3977          * case if they specify the origin.
3978          */
3979         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3980                 char origin[ZFS_MAX_DATASET_NAME_LEN];
3981                 zprop_source_t src;
3982
3983                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3984                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3985
3986                 if (strcmp(origin, fromname) == 0) {
3987                         fromname = NULL;
3988                         flags.fromorigin = B_TRUE;
3989                 } else {
3990                         *cp = '\0';
3991                         if (cp != fromname && strcmp(argv[0], fromname)) {
3992                                 (void) fprintf(stderr,
3993                                     gettext("incremental source must be "
3994                                     "in same filesystem\n"));
3995                                 usage(B_FALSE);
3996                         }
3997                         fromname = cp + 1;
3998                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
3999                                 (void) fprintf(stderr,
4000                                     gettext("invalid incremental source\n"));
4001                                 usage(B_FALSE);
4002                         }
4003                 }
4004         }
4005
4006         if (flags.replicate && fromname == NULL)
4007                 flags.doall = B_TRUE;
4008
4009         err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
4010             extraverbose ? &dbgnv : NULL);
4011
4012         if (extraverbose && dbgnv != NULL) {
4013                 /*
4014                  * dump_nvlist prints to stdout, but that's been
4015                  * redirected to a file.  Make it print to stderr
4016                  * instead.
4017                  */
4018                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
4019                 dump_nvlist(dbgnv, 0);
4020                 nvlist_free(dbgnv);
4021         }
4022         zfs_close(zhp);
4023
4024         return (err != 0);
4025 }
4026
4027 /*
4028  * Restore a backup stream from stdin.
4029  */
4030 static int
4031 zfs_do_receive(int argc, char **argv)
4032 {
4033         int c, err = 0;
4034         recvflags_t flags = { 0 };
4035         boolean_t abort_resumable = B_FALSE;
4036
4037         nvlist_t *props;
4038         nvpair_t *nvp = NULL;
4039
4040         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4041                 nomem();
4042
4043         /* check options */
4044         while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
4045                 switch (c) {
4046                 case 'o':
4047                         if (parseprop(props, optarg) != 0)
4048                                 return (1);
4049                         break;
4050                 case 'd':
4051                         flags.isprefix = B_TRUE;
4052                         break;
4053                 case 'e':
4054                         flags.isprefix = B_TRUE;
4055                         flags.istail = B_TRUE;
4056                         break;
4057                 case 'n':
4058                         flags.dryrun = B_TRUE;
4059                         break;
4060                 case 'u':
4061                         flags.nomount = B_TRUE;
4062                         break;
4063                 case 'v':
4064                         flags.verbose = B_TRUE;
4065                         break;
4066                 case 's':
4067                         flags.resumable = B_TRUE;
4068                         break;
4069                 case 'F':
4070                         flags.force = B_TRUE;
4071                         break;
4072                 case 'A':
4073                         abort_resumable = B_TRUE;
4074                         break;
4075                 case ':':
4076                         (void) fprintf(stderr, gettext("missing argument for "
4077                             "'%c' option\n"), optopt);
4078                         usage(B_FALSE);
4079                         break;
4080                 case '?':
4081                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4082                             optopt);
4083                         usage(B_FALSE);
4084                 }
4085         }
4086
4087         argc -= optind;
4088         argv += optind;
4089
4090         /* check number of arguments */
4091         if (argc < 1) {
4092                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4093                 usage(B_FALSE);
4094         }
4095         if (argc > 1) {
4096                 (void) fprintf(stderr, gettext("too many arguments\n"));
4097                 usage(B_FALSE);
4098         }
4099
4100         while ((nvp = nvlist_next_nvpair(props, nvp))) {
4101                 if (strcmp(nvpair_name(nvp), "origin") != 0) {
4102                         (void) fprintf(stderr, gettext("invalid option"));
4103                         usage(B_FALSE);
4104                 }
4105         }
4106
4107         if (abort_resumable) {
4108                 if (flags.isprefix || flags.istail || flags.dryrun ||
4109                     flags.resumable || flags.nomount) {
4110                         (void) fprintf(stderr, gettext("invalid option"));
4111                         usage(B_FALSE);
4112                 }
4113
4114                 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4115                 (void) snprintf(namebuf, sizeof (namebuf),
4116                     "%s/%%recv", argv[0]);
4117
4118                 if (zfs_dataset_exists(g_zfs, namebuf,
4119                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4120                         zfs_handle_t *zhp = zfs_open(g_zfs,
4121                             namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4122                         if (zhp == NULL)
4123                                 return (1);
4124                         err = zfs_destroy(zhp, B_FALSE);
4125                 } else {
4126                         zfs_handle_t *zhp = zfs_open(g_zfs,
4127                             argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4128                         if (zhp == NULL)
4129                                 usage(B_FALSE);
4130                         if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4131                             zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4132                             NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4133                                 (void) fprintf(stderr,
4134                                     gettext("'%s' does not have any "
4135                                     "resumable receive state to abort\n"),
4136                                     argv[0]);
4137                                 return (1);
4138                         }
4139                         err = zfs_destroy(zhp, B_FALSE);
4140                 }
4141
4142                 return (err != 0);
4143         }
4144
4145         if (isatty(STDIN_FILENO)) {
4146                 (void) fprintf(stderr,
4147                     gettext("Error: Backup stream can not be read "
4148                     "from a terminal.\n"
4149                     "You must redirect standard input.\n"));
4150                 return (1);
4151         }
4152         err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4153
4154         return (err != 0);
4155 }
4156
4157 /*
4158  * allow/unallow stuff
4159  */
4160 /* copied from zfs/sys/dsl_deleg.h */
4161 #define ZFS_DELEG_PERM_CREATE           "create"
4162 #define ZFS_DELEG_PERM_DESTROY          "destroy"
4163 #define ZFS_DELEG_PERM_SNAPSHOT         "snapshot"
4164 #define ZFS_DELEG_PERM_ROLLBACK         "rollback"
4165 #define ZFS_DELEG_PERM_CLONE            "clone"
4166 #define ZFS_DELEG_PERM_PROMOTE          "promote"
4167 #define ZFS_DELEG_PERM_RENAME           "rename"
4168 #define ZFS_DELEG_PERM_MOUNT            "mount"
4169 #define ZFS_DELEG_PERM_SHARE            "share"
4170 #define ZFS_DELEG_PERM_SEND             "send"
4171 #define ZFS_DELEG_PERM_RECEIVE          "receive"
4172 #define ZFS_DELEG_PERM_ALLOW            "allow"
4173 #define ZFS_DELEG_PERM_USERPROP         "userprop"
4174 #define ZFS_DELEG_PERM_VSCAN            "vscan" /* ??? */
4175 #define ZFS_DELEG_PERM_USERQUOTA        "userquota"
4176 #define ZFS_DELEG_PERM_GROUPQUOTA       "groupquota"
4177 #define ZFS_DELEG_PERM_USERUSED         "userused"
4178 #define ZFS_DELEG_PERM_GROUPUSED        "groupused"
4179 #define ZFS_DELEG_PERM_HOLD             "hold"
4180 #define ZFS_DELEG_PERM_RELEASE          "release"
4181 #define ZFS_DELEG_PERM_DIFF             "diff"
4182 #define ZFS_DELEG_PERM_BOOKMARK         "bookmark"
4183 #define ZFS_DELEG_PERM_REMAP            "remap"
4184
4185 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4186
4187 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4188         { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4189         { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4190         { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4191         { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4192         { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4193         { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4194         { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4195         { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4196         { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4197         { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4198         { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4199         { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4200         { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4201         { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4202         { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4203         { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4204         { ZFS_DELEG_PERM_REMAP, ZFS_DELEG_NOTE_REMAP },
4205
4206         { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4207         { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4208         { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4209         { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4210         { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4211         { NULL, ZFS_DELEG_NOTE_NONE }
4212 };
4213
4214 /* permission structure */
4215 typedef struct deleg_perm {
4216         zfs_deleg_who_type_t    dp_who_type;
4217         const char              *dp_name;
4218         boolean_t               dp_local;
4219         boolean_t               dp_descend;
4220 } deleg_perm_t;
4221
4222 /* */
4223 typedef struct deleg_perm_node {
4224         deleg_perm_t            dpn_perm;
4225
4226         uu_avl_node_t           dpn_avl_node;
4227 } deleg_perm_node_t;
4228
4229 typedef struct fs_perm fs_perm_t;
4230
4231 /* permissions set */
4232 typedef struct who_perm {
4233         zfs_deleg_who_type_t    who_type;
4234         const char              *who_name;              /* id */
4235         char                    who_ug_name[256];       /* user/group name */
4236         fs_perm_t               *who_fsperm;            /* uplink */
4237
4238         uu_avl_t                *who_deleg_perm_avl;    /* permissions */
4239 } who_perm_t;
4240
4241 /* */
4242 typedef struct who_perm_node {
4243         who_perm_t      who_perm;
4244         uu_avl_node_t   who_avl_node;
4245 } who_perm_node_t;
4246
4247 typedef struct fs_perm_set fs_perm_set_t;
4248 /* fs permissions */
4249 struct fs_perm {
4250         const char              *fsp_name;
4251
4252         uu_avl_t                *fsp_sc_avl;    /* sets,create */
4253         uu_avl_t                *fsp_uge_avl;   /* user,group,everyone */
4254
4255         fs_perm_set_t           *fsp_set;       /* uplink */
4256 };
4257
4258 /* */
4259 typedef struct fs_perm_node {
4260         fs_perm_t       fspn_fsperm;
4261         uu_avl_t        *fspn_avl;
4262
4263         uu_list_node_t  fspn_list_node;
4264 } fs_perm_node_t;
4265
4266 /* top level structure */
4267 struct fs_perm_set {
4268         uu_list_pool_t  *fsps_list_pool;
4269         uu_list_t       *fsps_list; /* list of fs_perms */
4270
4271         uu_avl_pool_t   *fsps_named_set_avl_pool;
4272         uu_avl_pool_t   *fsps_who_perm_avl_pool;
4273         uu_avl_pool_t   *fsps_deleg_perm_avl_pool;
4274 };
4275
4276 static inline const char *
4277 deleg_perm_type(zfs_deleg_note_t note)
4278 {
4279         /* subcommands */
4280         switch (note) {
4281                 /* SUBCOMMANDS */
4282                 /* OTHER */
4283         case ZFS_DELEG_NOTE_GROUPQUOTA:
4284         case ZFS_DELEG_NOTE_GROUPUSED:
4285         case ZFS_DELEG_NOTE_USERPROP:
4286         case ZFS_DELEG_NOTE_USERQUOTA:
4287         case ZFS_DELEG_NOTE_USERUSED:
4288                 /* other */
4289                 return (gettext("other"));
4290         default:
4291                 return (gettext("subcommand"));
4292         }
4293 }
4294
4295 static int
4296 who_type2weight(zfs_deleg_who_type_t who_type)
4297 {
4298         int res;
4299         switch (who_type) {
4300                 case ZFS_DELEG_NAMED_SET_SETS:
4301                 case ZFS_DELEG_NAMED_SET:
4302                         res = 0;
4303                         break;
4304                 case ZFS_DELEG_CREATE_SETS:
4305                 case ZFS_DELEG_CREATE:
4306                         res = 1;
4307                         break;
4308                 case ZFS_DELEG_USER_SETS:
4309                 case ZFS_DELEG_USER:
4310                         res = 2;
4311                         break;
4312                 case ZFS_DELEG_GROUP_SETS:
4313                 case ZFS_DELEG_GROUP:
4314                         res = 3;
4315                         break;
4316                 case ZFS_DELEG_EVERYONE_SETS:
4317                 case ZFS_DELEG_EVERYONE:
4318                         res = 4;
4319                         break;
4320                 default:
4321                         res = -1;
4322         }
4323
4324         return (res);
4325 }
4326
4327 /* ARGSUSED */
4328 static int
4329 who_perm_compare(const void *larg, const void *rarg, void *unused)
4330 {
4331         const who_perm_node_t *l = larg;
4332         const who_perm_node_t *r = rarg;
4333         zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4334         zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4335         int lweight = who_type2weight(ltype);
4336         int rweight = who_type2weight(rtype);
4337         int res = lweight - rweight;
4338         if (res == 0)
4339                 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4340                     ZFS_MAX_DELEG_NAME-1);
4341
4342         if (res == 0)
4343                 return (0);
4344         if (res > 0)
4345                 return (1);
4346         else
4347                 return (-1);
4348 }
4349
4350 /* ARGSUSED */
4351 static int
4352 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4353 {
4354         const deleg_perm_node_t *l = larg;
4355         const deleg_perm_node_t *r = rarg;
4356         int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4357             ZFS_MAX_DELEG_NAME-1);
4358
4359         if (res == 0)
4360                 return (0);
4361
4362         if (res > 0)
4363                 return (1);
4364         else
4365                 return (-1);
4366 }
4367
4368 static inline void
4369 fs_perm_set_init(fs_perm_set_t *fspset)
4370 {
4371         bzero(fspset, sizeof (fs_perm_set_t));
4372
4373         if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4374             sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4375             NULL, UU_DEFAULT)) == NULL)
4376                 nomem();
4377         if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4378             UU_DEFAULT)) == NULL)
4379                 nomem();
4380
4381         if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4382             "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4383             who_perm_node_t, who_avl_node), who_perm_compare,
4384             UU_DEFAULT)) == NULL)
4385                 nomem();
4386
4387         if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4388             "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4389             who_perm_node_t, who_avl_node), who_perm_compare,
4390             UU_DEFAULT)) == NULL)
4391                 nomem();
4392
4393         if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4394             "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4395             deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4396             == NULL)
4397                 nomem();
4398 }
4399
4400 static inline void fs_perm_fini(fs_perm_t *);
4401 static inline void who_perm_fini(who_perm_t *);
4402
4403 static inline void
4404 fs_perm_set_fini(fs_perm_set_t *fspset)
4405 {
4406         fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4407
4408         while (node != NULL) {
4409                 fs_perm_node_t *next_node =
4410                     uu_list_next(fspset->fsps_list, node);
4411                 fs_perm_t *fsperm = &node->fspn_fsperm;
4412                 fs_perm_fini(fsperm);
4413                 uu_list_remove(fspset->fsps_list, node);
4414                 free(node);
4415                 node = next_node;
4416         }
4417
4418         uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4419         uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4420         uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4421 }
4422
4423 static inline void
4424 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4425     const char *name)
4426 {
4427         deleg_perm->dp_who_type = type;
4428         deleg_perm->dp_name = name;
4429 }
4430
4431 static inline void
4432 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4433     zfs_deleg_who_type_t type, const char *name)
4434 {
4435         uu_avl_pool_t   *pool;
4436         pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4437
4438         bzero(who_perm, sizeof (who_perm_t));
4439
4440         if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4441             UU_DEFAULT)) == NULL)
4442                 nomem();
4443
4444         who_perm->who_type = type;
4445         who_perm->who_name = name;
4446         who_perm->who_fsperm = fsperm;
4447 }
4448
4449 static inline void
4450 who_perm_fini(who_perm_t *who_perm)
4451 {
4452         deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4453
4454         while (node != NULL) {
4455                 deleg_perm_node_t *next_node =
4456                     uu_avl_next(who_perm->who_deleg_perm_avl, node);
4457
4458                 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4459                 free(node);
4460                 node = next_node;
4461         }
4462
4463         uu_avl_destroy(who_perm->who_deleg_perm_avl);
4464 }
4465
4466 static inline void
4467 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4468 {
4469         uu_avl_pool_t   *nset_pool = fspset->fsps_named_set_avl_pool;
4470         uu_avl_pool_t   *who_pool = fspset->fsps_who_perm_avl_pool;
4471
4472         bzero(fsperm, sizeof (fs_perm_t));
4473
4474         if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4475             == NULL)
4476                 nomem();
4477
4478         if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4479             == NULL)
4480                 nomem();
4481
4482         fsperm->fsp_set = fspset;
4483         fsperm->fsp_name = fsname;
4484 }
4485
4486 static inline void
4487 fs_perm_fini(fs_perm_t *fsperm)
4488 {
4489         who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4490         while (node != NULL) {
4491                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4492                     node);
4493                 who_perm_t *who_perm = &node->who_perm;
4494                 who_perm_fini(who_perm);
4495                 uu_avl_remove(fsperm->fsp_sc_avl, node);
4496                 free(node);
4497                 node = next_node;
4498         }
4499
4500         node = uu_avl_first(fsperm->fsp_uge_avl);
4501         while (node != NULL) {
4502                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4503                     node);
4504                 who_perm_t *who_perm = &node->who_perm;
4505                 who_perm_fini(who_perm);
4506                 uu_avl_remove(fsperm->fsp_uge_avl, node);
4507                 free(node);
4508                 node = next_node;
4509         }
4510
4511         uu_avl_destroy(fsperm->fsp_sc_avl);
4512         uu_avl_destroy(fsperm->fsp_uge_avl);
4513 }
4514
4515 static void
4516 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4517     zfs_deleg_who_type_t who_type, const char *name, char locality)
4518 {
4519         uu_avl_index_t idx = 0;
4520
4521         deleg_perm_node_t *found_node = NULL;
4522         deleg_perm_t    *deleg_perm = &node->dpn_perm;
4523
4524         deleg_perm_init(deleg_perm, who_type, name);
4525
4526         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4527             == NULL)
4528                 uu_avl_insert(avl, node, idx);
4529         else {
4530                 node = found_node;
4531                 deleg_perm = &node->dpn_perm;
4532         }
4533
4534
4535         switch (locality) {
4536         case ZFS_DELEG_LOCAL:
4537                 deleg_perm->dp_local = B_TRUE;
4538                 break;
4539         case ZFS_DELEG_DESCENDENT:
4540                 deleg_perm->dp_descend = B_TRUE;
4541                 break;
4542         case ZFS_DELEG_NA:
4543                 break;
4544         default:
4545                 assert(B_FALSE); /* invalid locality */
4546         }
4547 }
4548
4549 static inline int
4550 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4551 {
4552         nvpair_t *nvp = NULL;
4553         fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4554         uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4555         zfs_deleg_who_type_t who_type = who_perm->who_type;
4556
4557         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4558                 const char *name = nvpair_name(nvp);
4559                 data_type_t type = nvpair_type(nvp);
4560                 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4561                 deleg_perm_node_t *node =
4562                     safe_malloc(sizeof (deleg_perm_node_t));
4563
4564                 assert(type == DATA_TYPE_BOOLEAN);
4565
4566                 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4567                 set_deleg_perm_node(avl, node, who_type, name, locality);
4568         }
4569
4570         return (0);
4571 }
4572
4573 static inline int
4574 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4575 {
4576         nvpair_t *nvp = NULL;
4577         fs_perm_set_t *fspset = fsperm->fsp_set;
4578
4579         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4580                 nvlist_t *nvl2 = NULL;
4581                 const char *name = nvpair_name(nvp);
4582                 uu_avl_t *avl = NULL;
4583                 uu_avl_pool_t *avl_pool = NULL;
4584                 zfs_deleg_who_type_t perm_type = name[0];
4585                 char perm_locality = name[1];
4586                 const char *perm_name = name + 3;
4587                 boolean_t is_set = B_TRUE;
4588                 who_perm_t *who_perm = NULL;
4589
4590                 assert('$' == name[2]);
4591
4592                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4593                         return (-1);
4594
4595                 switch (perm_type) {
4596                 case ZFS_DELEG_CREATE:
4597                 case ZFS_DELEG_CREATE_SETS:
4598                 case ZFS_DELEG_NAMED_SET:
4599                 case ZFS_DELEG_NAMED_SET_SETS:
4600                         avl_pool = fspset->fsps_named_set_avl_pool;
4601                         avl = fsperm->fsp_sc_avl;
4602                         break;
4603                 case ZFS_DELEG_USER:
4604                 case ZFS_DELEG_USER_SETS:
4605                 case ZFS_DELEG_GROUP:
4606                 case ZFS_DELEG_GROUP_SETS:
4607                 case ZFS_DELEG_EVERYONE:
4608                 case ZFS_DELEG_EVERYONE_SETS:
4609                         avl_pool = fspset->fsps_who_perm_avl_pool;
4610                         avl = fsperm->fsp_uge_avl;
4611                         break;
4612
4613                 default:
4614                         assert(!"unhandled zfs_deleg_who_type_t");
4615                 }
4616
4617                 if (is_set) {
4618                         who_perm_node_t *found_node = NULL;
4619                         who_perm_node_t *node = safe_malloc(
4620                             sizeof (who_perm_node_t));
4621                         who_perm = &node->who_perm;
4622                         uu_avl_index_t idx = 0;
4623
4624                         uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4625                         who_perm_init(who_perm, fsperm, perm_type, perm_name);
4626
4627                         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4628                             == NULL) {
4629                                 if (avl == fsperm->fsp_uge_avl) {
4630                                         uid_t rid = 0;
4631                                         struct passwd *p = NULL;
4632                                         struct group *g = NULL;
4633                                         const char *nice_name = NULL;
4634
4635                                         switch (perm_type) {
4636                                         case ZFS_DELEG_USER_SETS:
4637                                         case ZFS_DELEG_USER:
4638                                                 rid = atoi(perm_name);
4639                                                 p = getpwuid(rid);
4640                                                 if (p)
4641                                                         nice_name = p->pw_name;
4642                                                 break;
4643                                         case ZFS_DELEG_GROUP_SETS:
4644                                         case ZFS_DELEG_GROUP:
4645                                                 rid = atoi(perm_name);
4646                                                 g = getgrgid(rid);
4647                                                 if (g)
4648                                                         nice_name = g->gr_name;
4649                                                 break;
4650
4651                                         default:
4652                                                 break;
4653                                         }
4654
4655                                         if (nice_name != NULL)
4656                                                 (void) strlcpy(
4657                                                     node->who_perm.who_ug_name,
4658                                                     nice_name, 256);
4659                                 }
4660
4661                                 uu_avl_insert(avl, node, idx);
4662                         } else {
4663                                 node = found_node;
4664                                 who_perm = &node->who_perm;
4665                         }
4666                 }
4667
4668                 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4669         }
4670
4671         return (0);
4672 }
4673
4674 static inline int
4675 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4676 {
4677         nvpair_t *nvp = NULL;
4678         uu_avl_index_t idx = 0;
4679
4680         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4681                 nvlist_t *nvl2 = NULL;
4682                 const char *fsname = nvpair_name(nvp);
4683                 data_type_t type = nvpair_type(nvp);
4684                 fs_perm_t *fsperm = NULL;
4685                 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4686                 if (node == NULL)
4687                         nomem();
4688
4689                 fsperm = &node->fspn_fsperm;
4690
4691                 assert(DATA_TYPE_NVLIST == type);
4692
4693                 uu_list_node_init(node, &node->fspn_list_node,
4694                     fspset->fsps_list_pool);
4695
4696                 idx = uu_list_numnodes(fspset->fsps_list);
4697                 fs_perm_init(fsperm, fspset, fsname);
4698
4699                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4700                         return (-1);
4701
4702                 (void) parse_fs_perm(fsperm, nvl2);
4703
4704                 uu_list_insert(fspset->fsps_list, node, idx);
4705         }
4706
4707         return (0);
4708 }
4709
4710 static inline const char *
4711 deleg_perm_comment(zfs_deleg_note_t note)
4712 {
4713         const char *str = "";
4714
4715         /* subcommands */
4716         switch (note) {
4717                 /* SUBCOMMANDS */
4718         case ZFS_DELEG_NOTE_ALLOW:
4719                 str = gettext("Must also have the permission that is being"
4720                     "\n\t\t\t\tallowed");
4721                 break;
4722         case ZFS_DELEG_NOTE_CLONE:
4723                 str = gettext("Must also have the 'create' ability and 'mount'"
4724                     "\n\t\t\t\tability in the origin file system");
4725                 break;
4726         case ZFS_DELEG_NOTE_CREATE:
4727                 str = gettext("Must also have the 'mount' ability");
4728                 break;
4729         case ZFS_DELEG_NOTE_DESTROY:
4730                 str = gettext("Must also have the 'mount' ability");
4731                 break;
4732         case ZFS_DELEG_NOTE_DIFF:
4733                 str = gettext("Allows lookup of paths within a dataset;"
4734                     "\n\t\t\t\tgiven an object number. Ordinary users need this"
4735                     "\n\t\t\t\tin order to use zfs diff");
4736                 break;
4737         case ZFS_DELEG_NOTE_HOLD:
4738                 str = gettext("Allows adding a user hold to a snapshot");
4739                 break;
4740         case ZFS_DELEG_NOTE_MOUNT:
4741                 str = gettext("Allows mount/umount of ZFS datasets");
4742                 break;
4743         case ZFS_DELEG_NOTE_PROMOTE:
4744                 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4745                     " 'promote' ability in the origin file system");
4746                 break;
4747         case ZFS_DELEG_NOTE_RECEIVE:
4748                 str = gettext("Must also have the 'mount' and 'create'"
4749                     " ability");
4750                 break;
4751         case ZFS_DELEG_NOTE_RELEASE:
4752                 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4753                     "might destroy the snapshot");
4754                 break;
4755         case ZFS_DELEG_NOTE_RENAME:
4756                 str = gettext("Must also have the 'mount' and 'create'"
4757                     "\n\t\t\t\tability in the new parent");
4758                 break;
4759         case ZFS_DELEG_NOTE_ROLLBACK:
4760                 str = gettext("");
4761                 break;
4762         case ZFS_DELEG_NOTE_SEND:
4763                 str = gettext("");
4764                 break;
4765         case ZFS_DELEG_NOTE_SHARE:
4766                 str = gettext("Allows sharing file systems over NFS or SMB"
4767                     "\n\t\t\t\tprotocols");
4768                 break;
4769         case ZFS_DELEG_NOTE_SNAPSHOT:
4770                 str = gettext("");
4771                 break;
4772 /*
4773  *      case ZFS_DELEG_NOTE_VSCAN:
4774  *              str = gettext("");
4775  *              break;
4776  */
4777                 /* OTHER */
4778         case ZFS_DELEG_NOTE_GROUPQUOTA:
4779                 str = gettext("Allows accessing any groupquota@... property");
4780                 break;
4781         case ZFS_DELEG_NOTE_GROUPUSED:
4782                 str = gettext("Allows reading any groupused@... property");
4783                 break;
4784         case ZFS_DELEG_NOTE_USERPROP:
4785                 str = gettext("Allows changing any user property");
4786                 break;
4787         case ZFS_DELEG_NOTE_USERQUOTA:
4788                 str = gettext("Allows accessing any userquota@... property");
4789                 break;
4790         case ZFS_DELEG_NOTE_USERUSED:
4791                 str = gettext("Allows reading any userused@... property");
4792                 break;
4793                 /* other */
4794         default:
4795                 str = "";
4796         }
4797
4798         return (str);
4799 }
4800
4801 struct allow_opts {
4802         boolean_t local;
4803         boolean_t descend;
4804         boolean_t user;
4805         boolean_t group;
4806         boolean_t everyone;
4807         boolean_t create;
4808         boolean_t set;
4809         boolean_t recursive; /* unallow only */
4810         boolean_t prt_usage;
4811
4812         boolean_t prt_perms;
4813         char *who;
4814         char *perms;
4815         const char *dataset;
4816 };
4817
4818 static inline int
4819 prop_cmp(const void *a, const void *b)
4820 {
4821         const char *str1 = *(const char **)a;
4822         const char *str2 = *(const char **)b;
4823         return (strcmp(str1, str2));
4824 }
4825
4826 static void
4827 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4828 {
4829         const char *opt_desc[] = {
4830                 "-h", gettext("show this help message and exit"),
4831                 "-l", gettext("set permission locally"),
4832                 "-d", gettext("set permission for descents"),
4833                 "-u", gettext("set permission for user"),
4834                 "-g", gettext("set permission for group"),
4835                 "-e", gettext("set permission for everyone"),
4836                 "-c", gettext("set create time permission"),
4837                 "-s", gettext("define permission set"),
4838                 /* unallow only */
4839                 "-r", gettext("remove permissions recursively"),
4840         };
4841         size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4842         size_t allow_size = unallow_size - 2;
4843         const char *props[ZFS_NUM_PROPS];
4844         int i;
4845         size_t count = 0;
4846         FILE *fp = requested ? stdout : stderr;
4847         zprop_desc_t *pdtbl = zfs_prop_get_table();
4848         const char *fmt = gettext("%-16s %-14s\t%s\n");
4849
4850         (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4851             HELP_ALLOW));
4852         (void) fprintf(fp, gettext("Options:\n"));
4853         for (i = 0; i < (un ? unallow_size : allow_size); i++) {
4854                 const char *opt = opt_desc[i++];
4855                 const char *optdsc = opt_desc[i];
4856                 (void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4857         }
4858
4859         (void) fprintf(fp, gettext("\nThe following permissions are "
4860             "supported:\n\n"));
4861         (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4862             gettext("NOTES"));
4863         for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4864                 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4865                 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4866                 const char *perm_type = deleg_perm_type(perm_note);
4867                 const char *perm_comment = deleg_perm_comment(perm_note);
4868                 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4869         }
4870
4871         for (i = 0; i < ZFS_NUM_PROPS; i++) {
4872                 zprop_desc_t *pd = &pdtbl[i];
4873                 if (pd->pd_visible != B_TRUE)
4874                         continue;
4875
4876                 if (pd->pd_attr == PROP_READONLY)
4877                         continue;
4878
4879                 props[count++] = pd->pd_name;
4880         }
4881         props[count] = NULL;
4882
4883         qsort(props, count, sizeof (char *), prop_cmp);
4884
4885         for (i = 0; i < count; i++)
4886                 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4887
4888         if (msg != NULL)
4889                 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4890
4891         exit(requested ? 0 : 2);
4892 }
4893
4894 static inline const char *
4895 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4896     char **permsp)
4897 {
4898         if (un && argc == expected_argc - 1)
4899                 *permsp = NULL;
4900         else if (argc == expected_argc)
4901                 *permsp = argv[argc - 2];
4902         else
4903                 allow_usage(un, B_FALSE,
4904                     gettext("wrong number of parameters\n"));
4905
4906         return (argv[argc - 1]);
4907 }
4908
4909 static void
4910 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4911 {
4912         int uge_sum = opts->user + opts->group + opts->everyone;
4913         int csuge_sum = opts->create + opts->set + uge_sum;
4914         int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4915         int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4916
4917         if (uge_sum > 1)
4918                 allow_usage(un, B_FALSE,
4919                     gettext("-u, -g, and -e are mutually exclusive\n"));
4920
4921         if (opts->prt_usage) {
4922                 if (argc == 0 && all_sum == 0)
4923                         allow_usage(un, B_TRUE, NULL);
4924                 else
4925                         usage(B_FALSE);
4926         }
4927
4928         if (opts->set) {
4929                 if (csuge_sum > 1)
4930                         allow_usage(un, B_FALSE,
4931                             gettext("invalid options combined with -s\n"));
4932
4933                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4934                 if (argv[0][0] != '@')
4935                         allow_usage(un, B_FALSE,
4936                             gettext("invalid set name: missing '@' prefix\n"));
4937                 opts->who = argv[0];
4938         } else if (opts->create) {
4939                 if (ldcsuge_sum > 1)
4940                         allow_usage(un, B_FALSE,
4941                             gettext("invalid options combined with -c\n"));
4942                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4943         } else if (opts->everyone) {
4944                 if (csuge_sum > 1)
4945                         allow_usage(un, B_FALSE,
4946                             gettext("invalid options combined with -e\n"));
4947                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4948         } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4949             == 0) {
4950                 opts->everyone = B_TRUE;
4951                 argc--;
4952                 argv++;
4953                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4954         } else if (argc == 1 && !un) {
4955                 opts->prt_perms = B_TRUE;
4956                 opts->dataset = argv[argc-1];
4957         } else {
4958                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4959                 opts->who = argv[0];
4960         }
4961
4962         if (!opts->local && !opts->descend) {
4963                 opts->local = B_TRUE;
4964                 opts->descend = B_TRUE;
4965         }
4966 }
4967
4968 static void
4969 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4970     const char *who, char *perms, nvlist_t *top_nvl)
4971 {
4972         int i;
4973         char ld[2] = { '\0', '\0' };
4974         char who_buf[MAXNAMELEN + 32];
4975         char base_type = '\0';
4976         char set_type = '\0';
4977         nvlist_t *base_nvl = NULL;
4978         nvlist_t *set_nvl = NULL;
4979         nvlist_t *nvl;
4980
4981         if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4982                 nomem();
4983         if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4984                 nomem();
4985
4986         switch (type) {
4987         case ZFS_DELEG_NAMED_SET_SETS:
4988         case ZFS_DELEG_NAMED_SET:
4989                 set_type = ZFS_DELEG_NAMED_SET_SETS;
4990                 base_type = ZFS_DELEG_NAMED_SET;
4991                 ld[0] = ZFS_DELEG_NA;
4992                 break;
4993         case ZFS_DELEG_CREATE_SETS:
4994         case ZFS_DELEG_CREATE:
4995                 set_type = ZFS_DELEG_CREATE_SETS;
4996                 base_type = ZFS_DELEG_CREATE;
4997                 ld[0] = ZFS_DELEG_NA;
4998                 break;
4999         case ZFS_DELEG_USER_SETS:
5000         case ZFS_DELEG_USER:
5001                 set_type = ZFS_DELEG_USER_SETS;
5002                 base_type = ZFS_DELEG_USER;
5003                 if (local)
5004                         ld[0] = ZFS_DELEG_LOCAL;
5005                 if (descend)
5006                         ld[1] = ZFS_DELEG_DESCENDENT;
5007                 break;
5008         case ZFS_DELEG_GROUP_SETS:
5009         case ZFS_DELEG_GROUP:
5010                 set_type = ZFS_DELEG_GROUP_SETS;
5011                 base_type = ZFS_DELEG_GROUP;
5012                 if (local)
5013                         ld[0] = ZFS_DELEG_LOCAL;
5014                 if (descend)
5015                         ld[1] = ZFS_DELEG_DESCENDENT;
5016                 break;
5017         case ZFS_DELEG_EVERYONE_SETS:
5018         case ZFS_DELEG_EVERYONE:
5019                 set_type = ZFS_DELEG_EVERYONE_SETS;
5020                 base_type = ZFS_DELEG_EVERYONE;
5021                 if (local)
5022                         ld[0] = ZFS_DELEG_LOCAL;
5023                 if (descend)
5024                         ld[1] = ZFS_DELEG_DESCENDENT;
5025                 break;
5026
5027         default:
5028                 assert(set_type != '\0' && base_type != '\0');
5029         }
5030
5031         if (perms != NULL) {
5032                 char *curr = perms;
5033                 char *end = curr + strlen(perms);
5034
5035                 while (curr < end) {
5036                         char *delim = strchr(curr, ',');
5037                         if (delim == NULL)
5038                                 delim = end;
5039                         else
5040                                 *delim = '\0';
5041
5042                         if (curr[0] == '@')
5043                                 nvl = set_nvl;
5044                         else
5045                                 nvl = base_nvl;
5046
5047                         (void) nvlist_add_boolean(nvl, curr);
5048                         if (delim != end)
5049                                 *delim = ',';
5050                         curr = delim + 1;
5051                 }
5052
5053                 for (i = 0; i < 2; i++) {
5054                         char locality = ld[i];
5055                         if (locality == 0)
5056                                 continue;
5057
5058                         if (!nvlist_empty(base_nvl)) {
5059                                 if (who != NULL)
5060                                         (void) snprintf(who_buf,
5061                                             sizeof (who_buf), "%c%c$%s",
5062                                             base_type, locality, who);
5063                                 else
5064                                         (void) snprintf(who_buf,
5065                                             sizeof (who_buf), "%c%c$",
5066                                             base_type, locality);
5067
5068                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
5069                                     base_nvl);
5070                         }
5071
5072
5073                         if (!nvlist_empty(set_nvl)) {
5074                                 if (who != NULL)
5075                                         (void) snprintf(who_buf,
5076                                             sizeof (who_buf), "%c%c$%s",
5077                                             set_type, locality, who);
5078                                 else
5079                                         (void) snprintf(who_buf,
5080                                             sizeof (who_buf), "%c%c$",
5081                                             set_type, locality);
5082
5083                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
5084                                     set_nvl);
5085                         }
5086                 }
5087         } else {
5088                 for (i = 0; i < 2; i++) {
5089                         char locality = ld[i];
5090                         if (locality == 0)
5091                                 continue;
5092
5093                         if (who != NULL)
5094                                 (void) snprintf(who_buf, sizeof (who_buf),
5095                                     "%c%c$%s", base_type, locality, who);
5096                         else
5097                                 (void) snprintf(who_buf, sizeof (who_buf),
5098                                     "%c%c$", base_type, locality);
5099                         (void) nvlist_add_boolean(top_nvl, who_buf);
5100
5101                         if (who != NULL)
5102                                 (void) snprintf(who_buf, sizeof (who_buf),
5103                                     "%c%c$%s", set_type, locality, who);
5104                         else
5105                                 (void) snprintf(who_buf, sizeof (who_buf),
5106                                     "%c%c$", set_type, locality);
5107                         (void) nvlist_add_boolean(top_nvl, who_buf);
5108                 }
5109         }
5110 }
5111
5112 static int
5113 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5114 {
5115         if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5116                 nomem();
5117
5118         if (opts->set) {
5119                 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5120                     opts->descend, opts->who, opts->perms, *nvlp);
5121         } else if (opts->create) {
5122                 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5123                     opts->descend, NULL, opts->perms, *nvlp);
5124         } else if (opts->everyone) {
5125                 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5126                     opts->descend, NULL, opts->perms, *nvlp);
5127         } else {
5128                 char *curr = opts->who;
5129                 char *end = curr + strlen(curr);
5130
5131                 while (curr < end) {
5132                         const char *who;
5133                         zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5134                         char *endch;
5135                         char *delim = strchr(curr, ',');
5136                         char errbuf[256];
5137                         char id[64];
5138                         struct passwd *p = NULL;
5139                         struct group *g = NULL;
5140
5141                         uid_t rid;
5142                         if (delim == NULL)
5143                                 delim = end;
5144                         else
5145                                 *delim = '\0';
5146
5147                         rid = (uid_t)strtol(curr, &endch, 0);
5148                         if (opts->user) {
5149                                 who_type = ZFS_DELEG_USER;
5150                                 if (*endch != '\0')
5151                                         p = getpwnam(curr);
5152                                 else
5153                                         p = getpwuid(rid);
5154
5155                                 if (p != NULL)
5156                                         rid = p->pw_uid;
5157                                 else {
5158                                         (void) snprintf(errbuf, 256, gettext(
5159                                             "invalid user %s"), curr);
5160                                         allow_usage(un, B_TRUE, errbuf);
5161                                 }
5162                         } else if (opts->group) {
5163                                 who_type = ZFS_DELEG_GROUP;
5164                                 if (*endch != '\0')
5165                                         g = getgrnam(curr);
5166                                 else
5167                                         g = getgrgid(rid);
5168
5169                                 if (g != NULL)
5170                                         rid = g->gr_gid;
5171                                 else {
5172                                         (void) snprintf(errbuf, 256, gettext(
5173                                             "invalid group %s"),  curr);
5174                                         allow_usage(un, B_TRUE, errbuf);
5175                                 }
5176                         } else {
5177                                 if (*endch != '\0') {
5178                                         p = getpwnam(curr);
5179                                 } else {
5180                                         p = getpwuid(rid);
5181                                 }
5182
5183                                 if (p == NULL) {
5184                                         if (*endch != '\0') {
5185                                                 g = getgrnam(curr);
5186                                         } else {
5187                                                 g = getgrgid(rid);
5188                                         }
5189                                 }
5190
5191                                 if (p != NULL) {
5192                                         who_type = ZFS_DELEG_USER;
5193                                         rid = p->pw_uid;
5194                                 } else if (g != NULL) {
5195                                         who_type = ZFS_DELEG_GROUP;
5196                                         rid = g->gr_gid;
5197                                 } else {
5198                                         (void) snprintf(errbuf, 256, gettext(
5199                                             "invalid user/group %s"), curr);
5200                                         allow_usage(un, B_TRUE, errbuf);
5201                                 }
5202                         }
5203
5204                         (void) sprintf(id, "%u", rid);
5205                         who = id;
5206
5207                         store_allow_perm(who_type, opts->local,
5208                             opts->descend, who, opts->perms, *nvlp);
5209                         curr = delim + 1;
5210                 }
5211         }
5212
5213         return (0);
5214 }
5215
5216 static void
5217 print_set_creat_perms(uu_avl_t *who_avl)
5218 {
5219         const char *sc_title[] = {
5220                 gettext("Permission sets:\n"),
5221                 gettext("Create time permissions:\n"),
5222                 NULL
5223         };
5224         const char **title_ptr = sc_title;
5225         who_perm_node_t *who_node = NULL;
5226         int prev_weight = -1;
5227
5228         for (who_node = uu_avl_first(who_avl); who_node != NULL;
5229             who_node = uu_avl_next(who_avl, who_node)) {
5230                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5231                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5232                 const char *who_name = who_node->who_perm.who_name;
5233                 int weight = who_type2weight(who_type);
5234                 boolean_t first = B_TRUE;
5235                 deleg_perm_node_t *deleg_node;
5236
5237                 if (prev_weight != weight) {
5238                         (void) printf(*title_ptr++);
5239                         prev_weight = weight;
5240                 }
5241
5242                 if (who_name == NULL || strnlen(who_name, 1) == 0)
5243                         (void) printf("\t");
5244                 else
5245                         (void) printf("\t%s ", who_name);
5246
5247                 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5248                     deleg_node = uu_avl_next(avl, deleg_node)) {
5249                         if (first) {
5250                                 (void) printf("%s",
5251                                     deleg_node->dpn_perm.dp_name);
5252                                 first = B_FALSE;
5253                         } else
5254                                 (void) printf(",%s",
5255                                     deleg_node->dpn_perm.dp_name);
5256                 }
5257
5258                 (void) printf("\n");
5259         }
5260 }
5261
5262 static void
5263 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5264     const char *title)
5265 {
5266         who_perm_node_t *who_node = NULL;
5267         boolean_t prt_title = B_TRUE;
5268         uu_avl_walk_t *walk;
5269
5270         if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5271                 nomem();
5272
5273         while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5274                 const char *who_name = who_node->who_perm.who_name;
5275                 const char *nice_who_name = who_node->who_perm.who_ug_name;
5276                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5277                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5278                 char delim = ' ';
5279                 deleg_perm_node_t *deleg_node;
5280                 boolean_t prt_who = B_TRUE;
5281
5282                 for (deleg_node = uu_avl_first(avl);
5283                     deleg_node != NULL;
5284                     deleg_node = uu_avl_next(avl, deleg_node)) {
5285                         if (local != deleg_node->dpn_perm.dp_local ||
5286                             descend != deleg_node->dpn_perm.dp_descend)
5287                                 continue;
5288
5289                         if (prt_who) {
5290                                 const char *who = NULL;
5291                                 if (prt_title) {
5292                                         prt_title = B_FALSE;
5293                                         (void) printf(title);
5294                                 }
5295
5296                                 switch (who_type) {
5297                                 case ZFS_DELEG_USER_SETS:
5298                                 case ZFS_DELEG_USER:
5299                                         who = gettext("user");
5300                                         if (nice_who_name)
5301                                                 who_name  = nice_who_name;
5302                                         break;
5303                                 case ZFS_DELEG_GROUP_SETS:
5304                                 case ZFS_DELEG_GROUP:
5305                                         who = gettext("group");
5306                                         if (nice_who_name)
5307                                                 who_name  = nice_who_name;
5308                                         break;
5309                                 case ZFS_DELEG_EVERYONE_SETS:
5310                                 case ZFS_DELEG_EVERYONE:
5311                                         who = gettext("everyone");
5312                                         who_name = NULL;
5313                                         break;
5314
5315                                 default:
5316                                         assert(who != NULL);
5317                                 }
5318
5319                                 prt_who = B_FALSE;
5320                                 if (who_name == NULL)
5321                                         (void) printf("\t%s", who);
5322                                 else
5323                                         (void) printf("\t%s %s", who, who_name);
5324                         }
5325
5326                         (void) printf("%c%s", delim,
5327                             deleg_node->dpn_perm.dp_name);
5328                         delim = ',';
5329                 }
5330
5331                 if (!prt_who)
5332                         (void) printf("\n");
5333         }
5334
5335         uu_avl_walk_end(walk);
5336 }
5337
5338 static void
5339 print_fs_perms(fs_perm_set_t *fspset)
5340 {
5341         fs_perm_node_t *node = NULL;
5342         char buf[MAXNAMELEN + 32];
5343         const char *dsname = buf;
5344
5345         for (node = uu_list_first(fspset->fsps_list); node != NULL;
5346             node = uu_list_next(fspset->fsps_list, node)) {
5347                 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5348                 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5349                 int left = 0;
5350
5351                 (void) snprintf(buf, sizeof (buf),
5352                     gettext("---- Permissions on %s "),
5353                     node->fspn_fsperm.fsp_name);
5354                 (void) printf(dsname);
5355                 left = 70 - strlen(buf);
5356                 while (left-- > 0)
5357                         (void) printf("-");
5358                 (void) printf("\n");
5359
5360                 print_set_creat_perms(sc_avl);
5361                 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5362                     gettext("Local permissions:\n"));
5363                 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5364                     gettext("Descendent permissions:\n"));
5365                 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5366                     gettext("Local+Descendent permissions:\n"));
5367         }
5368 }
5369
5370 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5371
5372 struct deleg_perms {
5373         boolean_t un;
5374         nvlist_t *nvl;
5375 };
5376
5377 static int
5378 set_deleg_perms(zfs_handle_t *zhp, void *data)
5379 {
5380         struct deleg_perms *perms = (struct deleg_perms *)data;
5381         zfs_type_t zfs_type = zfs_get_type(zhp);
5382
5383         if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5384                 return (0);
5385
5386         return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5387 }
5388
5389 static int
5390 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5391 {
5392         zfs_handle_t *zhp;
5393         nvlist_t *perm_nvl = NULL;
5394         nvlist_t *update_perm_nvl = NULL;
5395         int error = 1;
5396         int c;
5397         struct allow_opts opts = { 0 };
5398
5399         const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5400
5401         /* check opts */
5402         while ((c = getopt(argc, argv, optstr)) != -1) {
5403                 switch (c) {
5404                 case 'l':
5405                         opts.local = B_TRUE;
5406                         break;
5407                 case 'd':
5408                         opts.descend = B_TRUE;
5409                         break;
5410                 case 'u':
5411                         opts.user = B_TRUE;
5412                         break;
5413                 case 'g':
5414                         opts.group = B_TRUE;
5415                         break;
5416                 case 'e':
5417                         opts.everyone = B_TRUE;
5418                         break;
5419                 case 's':
5420                         opts.set = B_TRUE;
5421                         break;
5422                 case 'c':
5423                         opts.create = B_TRUE;
5424                         break;
5425                 case 'r':
5426                         opts.recursive = B_TRUE;
5427                         break;
5428                 case ':':
5429                         (void) fprintf(stderr, gettext("missing argument for "
5430                             "'%c' option\n"), optopt);
5431                         usage(B_FALSE);
5432                         break;
5433                 case 'h':
5434                         opts.prt_usage = B_TRUE;
5435                         break;
5436                 case '?':
5437                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5438                             optopt);
5439                         usage(B_FALSE);
5440                 }
5441         }
5442
5443         argc -= optind;
5444         argv += optind;
5445
5446         /* check arguments */
5447         parse_allow_args(argc, argv, un, &opts);
5448
5449         /* try to open the dataset */
5450         if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5451             ZFS_TYPE_VOLUME)) == NULL) {
5452                 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5453                     opts.dataset);
5454                 return (-1);
5455         }
5456
5457         if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5458                 goto cleanup2;
5459
5460         fs_perm_set_init(&fs_perm_set);
5461         if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5462                 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5463                 goto cleanup1;
5464         }
5465
5466         if (opts.prt_perms)
5467                 print_fs_perms(&fs_perm_set);
5468         else {
5469                 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5470                 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5471                         goto cleanup0;
5472
5473                 if (un && opts.recursive) {
5474                         struct deleg_perms data = { un, update_perm_nvl };
5475                         if (zfs_iter_filesystems(zhp, set_deleg_perms,
5476                             &data) != 0)
5477                                 goto cleanup0;
5478                 }
5479         }
5480
5481         error = 0;
5482
5483 cleanup0:
5484         nvlist_free(perm_nvl);
5485         nvlist_free(update_perm_nvl);
5486 cleanup1:
5487         fs_perm_set_fini(&fs_perm_set);
5488 cleanup2:
5489         zfs_close(zhp);
5490
5491         return (error);
5492 }
5493
5494 static int
5495 zfs_do_allow(int argc, char **argv)
5496 {
5497         return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5498 }
5499
5500 static int
5501 zfs_do_unallow(int argc, char **argv)
5502 {
5503         return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5504 }
5505
5506 static int
5507 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5508 {
5509         int errors = 0;
5510         int i;
5511         const char *tag;
5512         boolean_t recursive = B_FALSE;
5513         const char *opts = holding ? "rt" : "r";
5514         int c;
5515
5516         /* check options */
5517         while ((c = getopt(argc, argv, opts)) != -1) {
5518                 switch (c) {
5519                 case 'r':
5520                         recursive = B_TRUE;
5521                         break;
5522                 case '?':
5523                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5524                             optopt);
5525                         usage(B_FALSE);
5526                 }
5527         }
5528
5529         argc -= optind;
5530         argv += optind;
5531
5532         /* check number of arguments */
5533         if (argc < 2)
5534                 usage(B_FALSE);
5535
5536         tag = argv[0];
5537         --argc;
5538         ++argv;
5539
5540         if (holding && tag[0] == '.') {
5541                 /* tags starting with '.' are reserved for libzfs */
5542                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5543                 usage(B_FALSE);
5544         }
5545
5546         for (i = 0; i < argc; ++i) {
5547                 zfs_handle_t *zhp;
5548                 char parent[ZFS_MAX_DATASET_NAME_LEN];
5549                 const char *delim;
5550                 char *path = argv[i];
5551
5552                 delim = strchr(path, '@');
5553                 if (delim == NULL) {
5554                         (void) fprintf(stderr,
5555                             gettext("'%s' is not a snapshot\n"), path);
5556                         ++errors;
5557                         continue;
5558                 }
5559                 (void) strncpy(parent, path, delim - path);
5560                 parent[delim - path] = '\0';
5561
5562                 zhp = zfs_open(g_zfs, parent,
5563                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5564                 if (zhp == NULL) {
5565                         ++errors;
5566                         continue;
5567                 }
5568                 if (holding) {
5569                         if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5570                                 ++errors;
5571                 } else {
5572                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5573                                 ++errors;
5574                 }
5575                 zfs_close(zhp);
5576         }
5577
5578         return (errors != 0);
5579 }
5580
5581 /*
5582  * zfs hold [-r] [-t] <tag> <snap> ...
5583  *
5584  *      -r      Recursively hold
5585  *
5586  * Apply a user-hold with the given tag to the list of snapshots.
5587  */
5588 static int
5589 zfs_do_hold(int argc, char **argv)
5590 {
5591         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5592 }
5593
5594 /*
5595  * zfs release [-r] <tag> <snap> ...
5596  *
5597  *      -r      Recursively release
5598  *
5599  * Release a user-hold with the given tag from the list of snapshots.
5600  */
5601 static int
5602 zfs_do_release(int argc, char **argv)
5603 {
5604         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5605 }
5606
5607 typedef struct holds_cbdata {
5608         boolean_t       cb_recursive;
5609         const char      *cb_snapname;
5610         nvlist_t        **cb_nvlp;
5611         size_t          cb_max_namelen;
5612         size_t          cb_max_taglen;
5613 } holds_cbdata_t;
5614
5615 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5616 #define DATETIME_BUF_LEN (32)
5617 /*
5618  *
5619  */
5620 static void
5621 print_holds(boolean_t scripted, boolean_t literal, size_t nwidth,
5622     size_t tagwidth, nvlist_t *nvl)
5623 {
5624         int i;
5625         nvpair_t *nvp = NULL;
5626         char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5627         const char *col;
5628
5629         if (!scripted) {
5630                 for (i = 0; i < 3; i++) {
5631                         col = gettext(hdr_cols[i]);
5632                         if (i < 2)
5633                                 (void) printf("%-*s  ", i ? tagwidth : nwidth,
5634                                     col);
5635                         else
5636                                 (void) printf("%s\n", col);
5637                 }
5638         }
5639
5640         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5641                 char *zname = nvpair_name(nvp);
5642                 nvlist_t *nvl2;
5643                 nvpair_t *nvp2 = NULL;
5644                 (void) nvpair_value_nvlist(nvp, &nvl2);
5645                 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5646                         char tsbuf[DATETIME_BUF_LEN];
5647                         char *tagname = nvpair_name(nvp2);
5648                         uint64_t val = 0;
5649                         time_t time;
5650                         struct tm t;
5651
5652                         (void) nvpair_value_uint64(nvp2, &val);
5653                         if (literal)
5654                                 snprintf(tsbuf, DATETIME_BUF_LEN, "%llu", val);
5655                         else {
5656                                 time = (time_t)val;
5657                                 (void) localtime_r(&time, &t);
5658                                 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5659                                     gettext(STRFTIME_FMT_STR), &t);
5660                         }
5661
5662                         if (scripted) {
5663                                 (void) printf("%s\t%s\t%s\n", zname,
5664                                     tagname, tsbuf);
5665                         } else {
5666                                 (void) printf("%-*s  %-*s  %s\n", nwidth,
5667                                     zname, tagwidth, tagname, tsbuf);
5668                         }
5669                 }
5670         }
5671 }
5672
5673 /*
5674  * Generic callback function to list a dataset or snapshot.
5675  */
5676 static int
5677 holds_callback(zfs_handle_t *zhp, void *data)
5678 {
5679         holds_cbdata_t *cbp = data;
5680         nvlist_t *top_nvl = *cbp->cb_nvlp;
5681         nvlist_t *nvl = NULL;
5682         nvpair_t *nvp = NULL;
5683         const char *zname = zfs_get_name(zhp);
5684         size_t znamelen = strlen(zname);
5685
5686         if (cbp->cb_recursive && cbp->cb_snapname != NULL) {
5687                 const char *snapname;
5688                 char *delim  = strchr(zname, '@');
5689                 if (delim == NULL)
5690                         return (0);
5691
5692                 snapname = delim + 1;
5693                 if (strcmp(cbp->cb_snapname, snapname))
5694                         return (0);
5695         }
5696
5697         if (zfs_get_holds(zhp, &nvl) != 0)
5698                 return (-1);
5699
5700         if (znamelen > cbp->cb_max_namelen)
5701                 cbp->cb_max_namelen  = znamelen;
5702
5703         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5704                 const char *tag = nvpair_name(nvp);
5705                 size_t taglen = strlen(tag);
5706                 if (taglen > cbp->cb_max_taglen)
5707                         cbp->cb_max_taglen  = taglen;
5708         }
5709
5710         return (nvlist_add_nvlist(top_nvl, zname, nvl));
5711 }
5712
5713 /*
5714  * zfs holds [-Hp] [-r | -d max] <dataset|snap> ...
5715  *
5716  *      -H      Suppress header output
5717  *      -p      Output literal values
5718  *      -r      Recursively search for holds
5719  *      -d max  Limit depth of recursive search
5720  */
5721 static int
5722 zfs_do_holds(int argc, char **argv)
5723 {
5724         int errors = 0;
5725         int c;
5726         int i;
5727         boolean_t scripted = B_FALSE;
5728         boolean_t literal = B_FALSE;
5729         boolean_t recursive = B_FALSE;
5730         const char *opts = "d:rHp";
5731         nvlist_t *nvl;
5732
5733         int types = ZFS_TYPE_SNAPSHOT;
5734         holds_cbdata_t cb = { 0 };
5735
5736         int limit = 0;
5737         int ret = 0;
5738         int flags = 0;
5739
5740         /* check options */
5741         while ((c = getopt(argc, argv, opts)) != -1) {
5742                 switch (c) {
5743                 case 'd':
5744                         limit = parse_depth(optarg, &flags);
5745                         recursive = B_TRUE;
5746                         break;
5747                 case 'r':
5748                         recursive = B_TRUE;
5749                         break;
5750                 case 'H':
5751                         scripted = B_TRUE;
5752                         break;
5753                 case 'p':
5754                         literal = B_TRUE;
5755                         break;
5756                 case '?':
5757                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5758                             optopt);
5759                         usage(B_FALSE);
5760                 }
5761         }
5762
5763         if (recursive) {
5764                 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5765                 flags |= ZFS_ITER_RECURSE;
5766         }
5767
5768         argc -= optind;
5769         argv += optind;
5770
5771         /* check number of arguments */
5772         if (argc < 1)
5773                 usage(B_FALSE);
5774
5775         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5776                 nomem();
5777
5778         for (i = 0; i < argc; ++i) {
5779                 char *snapshot = argv[i];
5780                 const char *delim;
5781                 const char *snapname = NULL;
5782
5783                 delim = strchr(snapshot, '@');
5784                 if (delim != NULL) {
5785                         snapname = delim + 1;
5786                         if (recursive)
5787                                 snapshot[delim - snapshot] = '\0';
5788                 }
5789
5790                 cb.cb_recursive = recursive;
5791                 cb.cb_snapname = snapname;
5792                 cb.cb_nvlp = &nvl;
5793
5794                 /*
5795                  *  1. collect holds data, set format options
5796                  */
5797                 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5798                     holds_callback, &cb);
5799                 if (ret != 0)
5800                         ++errors;
5801         }
5802
5803         /*
5804          *  2. print holds data
5805          */
5806         print_holds(scripted, literal, cb.cb_max_namelen, cb.cb_max_taglen,
5807             nvl);
5808
5809         if (nvlist_empty(nvl))
5810                 (void) printf(gettext("no datasets available\n"));
5811
5812         nvlist_free(nvl);
5813
5814         return (0 != errors);
5815 }
5816
5817 #define CHECK_SPINNER 30
5818 #define SPINNER_TIME 3          /* seconds */
5819 #define MOUNT_TIME 5            /* seconds */
5820
5821 static int
5822 get_one_dataset(zfs_handle_t *zhp, void *data)
5823 {
5824         static char *spin[] = { "-", "\\", "|", "/" };
5825         static int spinval = 0;
5826         static int spincheck = 0;
5827         static time_t last_spin_time = (time_t)0;
5828         get_all_cb_t *cbp = data;
5829         zfs_type_t type = zfs_get_type(zhp);
5830
5831         if (cbp->cb_verbose) {
5832                 if (--spincheck < 0) {
5833                         time_t now = time(NULL);
5834                         if (last_spin_time + SPINNER_TIME < now) {
5835                                 update_progress(spin[spinval++ % 4]);
5836                                 last_spin_time = now;
5837                         }
5838                         spincheck = CHECK_SPINNER;
5839                 }
5840         }
5841
5842         /*
5843          * Interate over any nested datasets.
5844          */
5845         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5846                 zfs_close(zhp);
5847                 return (1);
5848         }
5849
5850         /*
5851          * Skip any datasets whose type does not match.
5852          */
5853         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5854                 zfs_close(zhp);
5855                 return (0);
5856         }
5857         libzfs_add_handle(cbp, zhp);
5858         assert(cbp->cb_used <= cbp->cb_alloc);
5859
5860         return (0);
5861 }
5862
5863 static void
5864 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5865 {
5866         get_all_cb_t cb = { 0 };
5867         cb.cb_verbose = verbose;
5868         cb.cb_getone = get_one_dataset;
5869
5870         if (verbose)
5871                 set_progress_header(gettext("Reading ZFS config"));
5872         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5873
5874         *dslist = cb.cb_handles;
5875         *count = cb.cb_used;
5876
5877         if (verbose)
5878                 finish_progress(gettext("done."));
5879 }
5880
5881 /*
5882  * Generic callback for sharing or mounting filesystems.  Because the code is so
5883  * similar, we have a common function with an extra parameter to determine which
5884  * mode we are using.
5885  */
5886 #define OP_SHARE        0x1
5887 #define OP_MOUNT        0x2
5888
5889 /*
5890  * Share or mount a dataset.
5891  */
5892 static int
5893 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5894     boolean_t explicit, const char *options)
5895 {
5896         char mountpoint[ZFS_MAXPROPLEN];
5897         char shareopts[ZFS_MAXPROPLEN];
5898         char smbshareopts[ZFS_MAXPROPLEN];
5899         const char *cmdname = op == OP_SHARE ? "share" : "mount";
5900         struct mnttab mnt;
5901         uint64_t zoned, canmount;
5902         boolean_t shared_nfs, shared_smb;
5903
5904         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5905
5906         /*
5907          * Check to make sure we can mount/share this dataset.  If we
5908          * are in the global zone and the filesystem is exported to a
5909          * local zone, or if we are in a local zone and the
5910          * filesystem is not exported, then it is an error.
5911          */
5912         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5913
5914         if (zoned && getzoneid() == GLOBAL_ZONEID) {
5915                 if (!explicit)
5916                         return (0);
5917
5918                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5919                     "dataset is exported to a local zone\n"), cmdname,
5920                     zfs_get_name(zhp));
5921                 return (1);
5922
5923         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5924                 if (!explicit)
5925                         return (0);
5926
5927                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5928                     "permission denied\n"), cmdname,
5929                     zfs_get_name(zhp));
5930                 return (1);
5931         }
5932
5933         /*
5934          * Ignore any filesystems which don't apply to us. This
5935          * includes those with a legacy mountpoint, or those with
5936          * legacy share options.
5937          */
5938         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5939             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5940         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5941             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5942         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5943             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5944
5945         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5946             strcmp(smbshareopts, "off") == 0) {
5947                 if (!explicit)
5948                         return (0);
5949
5950                 (void) fprintf(stderr, gettext("cannot share '%s': "
5951                     "legacy share\n"), zfs_get_name(zhp));
5952                 (void) fprintf(stderr, gettext("to "
5953                     "share this filesystem set "
5954                     "sharenfs property on\n"));
5955                 return (1);
5956         }
5957
5958         /*
5959          * We cannot share or mount legacy filesystems. If the
5960          * shareopts is non-legacy but the mountpoint is legacy, we
5961          * treat it as a legacy share.
5962          */
5963         if (strcmp(mountpoint, "legacy") == 0) {
5964                 if (!explicit)
5965                         return (0);
5966
5967                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5968                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5969                 (void) fprintf(stderr, gettext("use %s(8) to "
5970                     "%s this filesystem\n"), cmdname, cmdname);
5971                 return (1);
5972         }
5973
5974         if (strcmp(mountpoint, "none") == 0) {
5975                 if (!explicit)
5976                         return (0);
5977
5978                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5979                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5980                 return (1);
5981         }
5982
5983         /*
5984          * canmount     explicit        outcome
5985          * on           no              pass through
5986          * on           yes             pass through
5987          * off          no              return 0
5988          * off          yes             display error, return 1
5989          * noauto       no              return 0
5990          * noauto       yes             pass through
5991          */
5992         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5993         if (canmount == ZFS_CANMOUNT_OFF) {
5994                 if (!explicit)
5995                         return (0);
5996
5997                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5998                     "'canmount' property is set to 'off'\n"), cmdname,
5999                     zfs_get_name(zhp));
6000                 return (1);
6001         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
6002                 return (0);
6003         }
6004
6005         /*
6006          * If this filesystem is inconsistent and has a receive resume
6007          * token, we can not mount it.
6008          */
6009         if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
6010             zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
6011             NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
6012                 if (!explicit)
6013                         return (0);
6014
6015                 (void) fprintf(stderr, gettext("cannot %s '%s': "
6016                     "Contains partially-completed state from "
6017                     "\"zfs receive -r\", which can be resumed with "
6018                     "\"zfs send -t\"\n"),
6019                     cmdname, zfs_get_name(zhp));
6020                 return (1);
6021         }
6022
6023         /*
6024          * At this point, we have verified that the mountpoint and/or
6025          * shareopts are appropriate for auto management. If the
6026          * filesystem is already mounted or shared, return (failing
6027          * for explicit requests); otherwise mount or share the
6028          * filesystem.
6029          */
6030         switch (op) {
6031         case OP_SHARE:
6032
6033                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
6034                 shared_smb = zfs_is_shared_smb(zhp, NULL);
6035
6036                 if ((shared_nfs && shared_smb) ||
6037                     (shared_nfs && strcmp(shareopts, "on") == 0 &&
6038                     strcmp(smbshareopts, "off") == 0) ||
6039                     (shared_smb && strcmp(smbshareopts, "on") == 0 &&
6040                     strcmp(shareopts, "off") == 0)) {
6041                         if (!explicit)
6042                                 return (0);
6043
6044                         (void) fprintf(stderr, gettext("cannot share "
6045                             "'%s': filesystem already shared\n"),
6046                             zfs_get_name(zhp));
6047                         return (1);
6048                 }
6049
6050                 if (!zfs_is_mounted(zhp, NULL) &&
6051                     zfs_mount(zhp, NULL, 0) != 0)
6052                         return (1);
6053
6054                 if (protocol == NULL) {
6055                         if (zfs_shareall(zhp) != 0)
6056                                 return (1);
6057                 } else if (strcmp(protocol, "nfs") == 0) {
6058                         if (zfs_share_nfs(zhp))
6059                                 return (1);
6060                 } else if (strcmp(protocol, "smb") == 0) {
6061                         if (zfs_share_smb(zhp))
6062                                 return (1);
6063                 } else {
6064                         (void) fprintf(stderr, gettext("cannot share "
6065                             "'%s': invalid share type '%s' "
6066                             "specified\n"),
6067                             zfs_get_name(zhp), protocol);
6068                         return (1);
6069                 }
6070
6071                 break;
6072
6073         case OP_MOUNT:
6074                 if (options == NULL)
6075                         mnt.mnt_mntopts = "";
6076                 else
6077                         mnt.mnt_mntopts = (char *)options;
6078
6079                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6080                     zfs_is_mounted(zhp, NULL)) {
6081                         if (!explicit)
6082                                 return (0);
6083
6084                         (void) fprintf(stderr, gettext("cannot mount "
6085                             "'%s': filesystem already mounted\n"),
6086                             zfs_get_name(zhp));
6087                         return (1);
6088                 }
6089
6090                 if (zfs_mount(zhp, options, flags) != 0)
6091                         return (1);
6092                 break;
6093         }
6094
6095         return (0);
6096 }
6097
6098 /*
6099  * Reports progress in the form "(current/total)".  Not thread-safe.
6100  */
6101 static void
6102 report_mount_progress(int current, int total)
6103 {
6104         static time_t last_progress_time = 0;
6105         time_t now = time(NULL);
6106         char info[32];
6107
6108         /* report 1..n instead of 0..n-1 */
6109         ++current;
6110
6111         /* display header if we're here for the first time */
6112         if (current == 1) {
6113                 set_progress_header(gettext("Mounting ZFS filesystems"));
6114         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6115                 /* too soon to report again */
6116                 return;
6117         }
6118
6119         last_progress_time = now;
6120
6121         (void) sprintf(info, "(%d/%d)", current, total);
6122
6123         if (current == total)
6124                 finish_progress(info);
6125         else
6126                 update_progress(info);
6127 }
6128
6129 static void
6130 append_options(char *mntopts, char *newopts)
6131 {
6132         int len = strlen(mntopts);
6133
6134         /* original length plus new string to append plus 1 for the comma */
6135         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6136                 (void) fprintf(stderr, gettext("the opts argument for "
6137                     "'%c' option is too long (more than %d chars)\n"),
6138                     "-o", MNT_LINE_MAX);
6139                 usage(B_FALSE);
6140         }
6141
6142         if (*mntopts)
6143                 mntopts[len++] = ',';
6144
6145         (void) strcpy(&mntopts[len], newopts);
6146 }
6147
6148 static int
6149 share_mount(int op, int argc, char **argv)
6150 {
6151         int do_all = 0;
6152         boolean_t verbose = B_FALSE;
6153         int c, ret = 0;
6154         char *options = NULL;
6155         int flags = 0;
6156
6157         /* check options */
6158         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
6159             != -1) {
6160                 switch (c) {
6161                 case 'a':
6162                         do_all = 1;
6163                         break;
6164                 case 'v':
6165                         verbose = B_TRUE;
6166                         break;
6167                 case 'o':
6168                         if (*optarg == '\0') {
6169                                 (void) fprintf(stderr, gettext("empty mount "
6170                                     "options (-o) specified\n"));
6171                                 usage(B_FALSE);
6172                         }
6173
6174                         if (options == NULL)
6175                                 options = safe_malloc(MNT_LINE_MAX + 1);
6176
6177                         /* option validation is done later */
6178                         append_options(options, optarg);
6179                         break;
6180
6181                 case 'O':
6182                         warnx("no overlay mounts support on FreeBSD, ignoring");
6183                         break;
6184                 case ':':
6185                         (void) fprintf(stderr, gettext("missing argument for "
6186                             "'%c' option\n"), optopt);
6187                         usage(B_FALSE);
6188                         break;
6189                 case '?':
6190                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6191                             optopt);
6192                         usage(B_FALSE);
6193                 }
6194         }
6195
6196         argc -= optind;
6197         argv += optind;
6198
6199         /* check number of arguments */
6200         if (do_all) {
6201                 zfs_handle_t **dslist = NULL;
6202                 size_t i, count = 0;
6203                 char *protocol = NULL;
6204
6205                 if (op == OP_SHARE && argc > 0) {
6206                         if (strcmp(argv[0], "nfs") != 0 &&
6207                             strcmp(argv[0], "smb") != 0) {
6208                                 (void) fprintf(stderr, gettext("share type "
6209                                     "must be 'nfs' or 'smb'\n"));
6210                                 usage(B_FALSE);
6211                         }
6212                         protocol = argv[0];
6213                         argc--;
6214                         argv++;
6215                 }
6216
6217                 if (argc != 0) {
6218                         (void) fprintf(stderr, gettext("too many arguments\n"));
6219                         usage(B_FALSE);
6220                 }
6221
6222                 start_progress_timer();
6223                 get_all_datasets(&dslist, &count, verbose);
6224
6225                 if (count == 0)
6226                         return (0);
6227
6228                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
6229 #ifdef illumos
6230                 sa_init_selective_arg_t sharearg;
6231                 sharearg.zhandle_arr = dslist;
6232                 sharearg.zhandle_len = count;
6233                 if ((ret = zfs_init_libshare_arg(zfs_get_handle(dslist[0]),
6234                     SA_INIT_SHARE_API_SELECTIVE, &sharearg)) != SA_OK) {
6235                         (void) fprintf(stderr,
6236                             gettext("Could not initialize libshare, %d"), ret);
6237                         return (ret);
6238                 }
6239 #endif
6240
6241                 for (i = 0; i < count; i++) {
6242                         if (verbose)
6243                                 report_mount_progress(i, count);
6244
6245                         if (share_mount_one(dslist[i], op, flags, protocol,
6246                             B_FALSE, options) != 0)
6247                                 ret = 1;
6248                         zfs_close(dslist[i]);
6249                 }
6250
6251                 free(dslist);
6252         } else if (argc == 0) {
6253                 struct mnttab entry;
6254
6255                 if ((op == OP_SHARE) || (options != NULL)) {
6256                         (void) fprintf(stderr, gettext("missing filesystem "
6257                             "argument (specify -a for all)\n"));
6258                         usage(B_FALSE);
6259                 }
6260
6261                 /*
6262                  * When mount is given no arguments, go through /etc/mnttab and
6263                  * display any active ZFS mounts.  We hide any snapshots, since
6264                  * they are controlled automatically.
6265                  */
6266                 rewind(mnttab_file);
6267                 while (getmntent(mnttab_file, &entry) == 0) {
6268                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6269                             strchr(entry.mnt_special, '@') != NULL)
6270                                 continue;
6271
6272                         (void) printf("%-30s  %s\n", entry.mnt_special,
6273                             entry.mnt_mountp);
6274                 }
6275
6276         } else {
6277                 zfs_handle_t *zhp;
6278
6279                 if (argc > 1) {
6280                         (void) fprintf(stderr,
6281                             gettext("too many arguments\n"));
6282                         usage(B_FALSE);
6283                 }
6284
6285                 if ((zhp = zfs_open(g_zfs, argv[0],
6286                     ZFS_TYPE_FILESYSTEM)) == NULL) {
6287                         ret = 1;
6288                 } else {
6289                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6290                             options);
6291                         zfs_close(zhp);
6292                 }
6293         }
6294
6295         return (ret);
6296 }
6297
6298 /*
6299  * zfs mount -a [nfs]
6300  * zfs mount filesystem
6301  *
6302  * Mount all filesystems, or mount the given filesystem.
6303  */
6304 static int
6305 zfs_do_mount(int argc, char **argv)
6306 {
6307         return (share_mount(OP_MOUNT, argc, argv));
6308 }
6309
6310 /*
6311  * zfs share -a [nfs | smb]
6312  * zfs share filesystem
6313  *
6314  * Share all filesystems, or share the given filesystem.
6315  */
6316 static int
6317 zfs_do_share(int argc, char **argv)
6318 {
6319         return (share_mount(OP_SHARE, argc, argv));
6320 }
6321
6322 typedef struct unshare_unmount_node {
6323         zfs_handle_t    *un_zhp;
6324         char            *un_mountp;
6325         uu_avl_node_t   un_avlnode;
6326 } unshare_unmount_node_t;
6327
6328 /* ARGSUSED */
6329 static int
6330 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6331 {
6332         const unshare_unmount_node_t *l = larg;
6333         const unshare_unmount_node_t *r = rarg;
6334
6335         return (strcmp(l->un_mountp, r->un_mountp));
6336 }
6337
6338 /*
6339  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
6340  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6341  * and unmount it appropriately.
6342  */
6343 static int
6344 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6345 {
6346         zfs_handle_t *zhp;
6347         int ret = 0;
6348         struct stat64 statbuf;
6349         struct extmnttab entry;
6350         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6351         ino_t path_inode;
6352
6353         /*
6354          * Search for the path in /etc/mnttab.  Rather than looking for the
6355          * specific path, which can be fooled by non-standard paths (i.e. ".."
6356          * or "//"), we stat() the path and search for the corresponding
6357          * (major,minor) device pair.
6358          */
6359         if (stat64(path, &statbuf) != 0) {
6360                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6361                     cmdname, path, strerror(errno));
6362                 return (1);
6363         }
6364         path_inode = statbuf.st_ino;
6365
6366         /*
6367          * Search for the given (major,minor) pair in the mount table.
6368          */
6369 #ifdef illumos
6370         rewind(mnttab_file);
6371         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6372                 if (entry.mnt_major == major(statbuf.st_dev) &&
6373                     entry.mnt_minor == minor(statbuf.st_dev))
6374                         break;
6375         }
6376 #else
6377         {
6378                 struct statfs sfs;
6379
6380                 if (statfs(path, &sfs) != 0) {
6381                         (void) fprintf(stderr, "%s: %s\n", path,
6382                             strerror(errno));
6383                         ret = -1;
6384                 }
6385                 statfs2mnttab(&sfs, &entry);
6386         }
6387 #endif
6388         if (ret != 0) {
6389                 if (op == OP_SHARE) {
6390                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
6391                             "currently mounted\n"), cmdname, path);
6392                         return (1);
6393                 }
6394                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6395                     path);
6396                 if ((ret = umount2(path, flags)) != 0)
6397                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
6398                             strerror(errno));
6399                 return (ret != 0);
6400         }
6401
6402         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6403                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6404                     "filesystem\n"), cmdname, path);
6405                 return (1);
6406         }
6407
6408         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6409             ZFS_TYPE_FILESYSTEM)) == NULL)
6410                 return (1);
6411
6412         ret = 1;
6413         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6414                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6415                     cmdname, path, strerror(errno));
6416                 goto out;
6417         } else if (statbuf.st_ino != path_inode) {
6418                 (void) fprintf(stderr, gettext("cannot "
6419                     "%s '%s': not a mountpoint\n"), cmdname, path);
6420                 goto out;
6421         }
6422
6423         if (op == OP_SHARE) {
6424                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6425                 char smbshare_prop[ZFS_MAXPROPLEN];
6426
6427                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6428                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6429                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6430                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6431
6432                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6433                     strcmp(smbshare_prop, "off") == 0) {
6434                         (void) fprintf(stderr, gettext("cannot unshare "
6435                             "'%s': legacy share\n"), path);
6436 #ifdef illumos
6437                         (void) fprintf(stderr, gettext("use "
6438                             "unshare(1M) to unshare this filesystem\n"));
6439 #endif
6440                 } else if (!zfs_is_shared(zhp)) {
6441                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
6442                             "not currently shared\n"), path);
6443                 } else {
6444                         ret = zfs_unshareall_bypath(zhp, path);
6445                 }
6446         } else {
6447                 char mtpt_prop[ZFS_MAXPROPLEN];
6448
6449                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6450                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6451
6452                 if (is_manual) {
6453                         ret = zfs_unmount(zhp, NULL, flags);
6454                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6455                         (void) fprintf(stderr, gettext("cannot unmount "
6456                             "'%s': legacy mountpoint\n"),
6457                             zfs_get_name(zhp));
6458                         (void) fprintf(stderr, gettext("use umount(8) "
6459                             "to unmount this filesystem\n"));
6460                 } else {
6461                         ret = zfs_unmountall(zhp, flags);
6462                 }
6463         }
6464
6465 out:
6466         zfs_close(zhp);
6467
6468         return (ret != 0);
6469 }
6470
6471 /*
6472  * Generic callback for unsharing or unmounting a filesystem.
6473  */
6474 static int
6475 unshare_unmount(int op, int argc, char **argv)
6476 {
6477         int do_all = 0;
6478         int flags = 0;
6479         int ret = 0;
6480         int c;
6481         zfs_handle_t *zhp;
6482         char nfs_mnt_prop[ZFS_MAXPROPLEN];
6483         char sharesmb[ZFS_MAXPROPLEN];
6484
6485         /* check options */
6486         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6487                 switch (c) {
6488                 case 'a':
6489                         do_all = 1;
6490                         break;
6491                 case 'f':
6492                         flags = MS_FORCE;
6493                         break;
6494                 case '?':
6495                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6496                             optopt);
6497                         usage(B_FALSE);
6498                 }
6499         }
6500
6501         argc -= optind;
6502         argv += optind;
6503
6504         if (do_all) {
6505                 /*
6506                  * We could make use of zfs_for_each() to walk all datasets in
6507                  * the system, but this would be very inefficient, especially
6508                  * since we would have to linearly search /etc/mnttab for each
6509                  * one.  Instead, do one pass through /etc/mnttab looking for
6510                  * zfs entries and call zfs_unmount() for each one.
6511                  *
6512                  * Things get a little tricky if the administrator has created
6513                  * mountpoints beneath other ZFS filesystems.  In this case, we
6514                  * have to unmount the deepest filesystems first.  To accomplish
6515                  * this, we place all the mountpoints in an AVL tree sorted by
6516                  * the special type (dataset name), and walk the result in
6517                  * reverse to make sure to get any snapshots first.
6518                  */
6519                 struct mnttab entry;
6520                 uu_avl_pool_t *pool;
6521                 uu_avl_t *tree = NULL;
6522                 unshare_unmount_node_t *node;
6523                 uu_avl_index_t idx;
6524                 uu_avl_walk_t *walk;
6525
6526                 if (argc != 0) {
6527                         (void) fprintf(stderr, gettext("too many arguments\n"));
6528                         usage(B_FALSE);
6529                 }
6530
6531                 if (((pool = uu_avl_pool_create("unmount_pool",
6532                     sizeof (unshare_unmount_node_t),
6533                     offsetof(unshare_unmount_node_t, un_avlnode),
6534                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6535                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6536                         nomem();
6537
6538                 rewind(mnttab_file);
6539                 while (getmntent(mnttab_file, &entry) == 0) {
6540
6541                         /* ignore non-ZFS entries */
6542                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6543                                 continue;
6544
6545                         /* ignore snapshots */
6546                         if (strchr(entry.mnt_special, '@') != NULL)
6547                                 continue;
6548
6549                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6550                             ZFS_TYPE_FILESYSTEM)) == NULL) {
6551                                 ret = 1;
6552                                 continue;
6553                         }
6554
6555                         /*
6556                          * Ignore datasets that are excluded/restricted by
6557                          * parent pool name.
6558                          */
6559                         if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
6560                                 zfs_close(zhp);
6561                                 continue;
6562                         }
6563
6564                         switch (op) {
6565                         case OP_SHARE:
6566                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6567                                     nfs_mnt_prop,
6568                                     sizeof (nfs_mnt_prop),
6569                                     NULL, NULL, 0, B_FALSE) == 0);
6570                                 if (strcmp(nfs_mnt_prop, "off") != 0)
6571                                         break;
6572                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6573                                     nfs_mnt_prop,
6574                                     sizeof (nfs_mnt_prop),
6575                                     NULL, NULL, 0, B_FALSE) == 0);
6576                                 if (strcmp(nfs_mnt_prop, "off") == 0)
6577                                         continue;
6578                                 break;
6579                         case OP_MOUNT:
6580                                 /* Ignore legacy mounts */
6581                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6582                                     nfs_mnt_prop,
6583                                     sizeof (nfs_mnt_prop),
6584                                     NULL, NULL, 0, B_FALSE) == 0);
6585                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6586                                         continue;
6587                                 /* Ignore canmount=noauto mounts */
6588                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6589                                     ZFS_CANMOUNT_NOAUTO)
6590                                         continue;
6591                         default:
6592                                 break;
6593                         }
6594
6595                         node = safe_malloc(sizeof (unshare_unmount_node_t));
6596                         node->un_zhp = zhp;
6597                         node->un_mountp = safe_strdup(entry.mnt_mountp);
6598
6599                         uu_avl_node_init(node, &node->un_avlnode, pool);
6600
6601                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6602                                 uu_avl_insert(tree, node, idx);
6603                         } else {
6604                                 zfs_close(node->un_zhp);
6605                                 free(node->un_mountp);
6606                                 free(node);
6607                         }
6608                 }
6609
6610                 /*
6611                  * Walk the AVL tree in reverse, unmounting each filesystem and
6612                  * removing it from the AVL tree in the process.
6613                  */
6614                 if ((walk = uu_avl_walk_start(tree,
6615                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6616                         nomem();
6617
6618                 while ((node = uu_avl_walk_next(walk)) != NULL) {
6619                         uu_avl_remove(tree, node);
6620
6621                         switch (op) {
6622                         case OP_SHARE:
6623                                 if (zfs_unshareall_bypath(node->un_zhp,
6624                                     node->un_mountp) != 0)
6625                                         ret = 1;
6626                                 break;
6627
6628                         case OP_MOUNT:
6629                                 if (zfs_unmount(node->un_zhp,
6630                                     node->un_mountp, flags) != 0)
6631                                         ret = 1;
6632                                 break;
6633                         }
6634
6635                         zfs_close(node->un_zhp);
6636                         free(node->un_mountp);
6637                         free(node);
6638                 }
6639
6640                 uu_avl_walk_end(walk);
6641                 uu_avl_destroy(tree);
6642                 uu_avl_pool_destroy(pool);
6643
6644         } else {
6645                 if (argc != 1) {
6646                         if (argc == 0)
6647                                 (void) fprintf(stderr,
6648                                     gettext("missing filesystem argument\n"));
6649                         else
6650                                 (void) fprintf(stderr,
6651                                     gettext("too many arguments\n"));
6652                         usage(B_FALSE);
6653                 }
6654
6655                 /*
6656                  * We have an argument, but it may be a full path or a ZFS
6657                  * filesystem.  Pass full paths off to unmount_path() (shared by
6658                  * manual_unmount), otherwise open the filesystem and pass to
6659                  * zfs_unmount().
6660                  */
6661                 if (argv[0][0] == '/')
6662                         return (unshare_unmount_path(op, argv[0],
6663                             flags, B_FALSE));
6664
6665                 if ((zhp = zfs_open(g_zfs, argv[0],
6666                     ZFS_TYPE_FILESYSTEM)) == NULL)
6667                         return (1);
6668
6669                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6670                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6671                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6672                     NULL, 0, B_FALSE) == 0);
6673
6674                 switch (op) {
6675                 case OP_SHARE:
6676                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6677                             nfs_mnt_prop,
6678                             sizeof (nfs_mnt_prop),
6679                             NULL, NULL, 0, B_FALSE) == 0);
6680                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6681                             sharesmb, sizeof (sharesmb), NULL, NULL,
6682                             0, B_FALSE) == 0);
6683
6684                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
6685                             strcmp(sharesmb, "off") == 0) {
6686                                 (void) fprintf(stderr, gettext("cannot "
6687                                     "unshare '%s': legacy share\n"),
6688                                     zfs_get_name(zhp));
6689 #ifdef illumos
6690                                 (void) fprintf(stderr, gettext("use "
6691                                     "unshare(1M) to unshare this "
6692                                     "filesystem\n"));
6693 #endif
6694                                 ret = 1;
6695                         } else if (!zfs_is_shared(zhp)) {
6696                                 (void) fprintf(stderr, gettext("cannot "
6697                                     "unshare '%s': not currently "
6698                                     "shared\n"), zfs_get_name(zhp));
6699                                 ret = 1;
6700                         } else if (zfs_unshareall(zhp) != 0) {
6701                                 ret = 1;
6702                         }
6703                         break;
6704
6705                 case OP_MOUNT:
6706                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6707                                 (void) fprintf(stderr, gettext("cannot "
6708                                     "unmount '%s': legacy "
6709                                     "mountpoint\n"), zfs_get_name(zhp));
6710                                 (void) fprintf(stderr, gettext("use "
6711                                     "umount(8) to unmount this "
6712                                     "filesystem\n"));
6713                                 ret = 1;
6714                         } else if (!zfs_is_mounted(zhp, NULL)) {
6715                                 (void) fprintf(stderr, gettext("cannot "
6716                                     "unmount '%s': not currently "
6717                                     "mounted\n"),
6718                                     zfs_get_name(zhp));
6719                                 ret = 1;
6720                         } else if (zfs_unmountall(zhp, flags) != 0) {
6721                                 ret = 1;
6722                         }
6723                         break;
6724                 }
6725
6726                 zfs_close(zhp);
6727         }
6728
6729         return (ret);
6730 }
6731
6732 /*
6733  * zfs unmount -a
6734  * zfs unmount filesystem
6735  *
6736  * Unmount all filesystems, or a specific ZFS filesystem.
6737  */
6738 static int
6739 zfs_do_unmount(int argc, char **argv)
6740 {
6741         return (unshare_unmount(OP_MOUNT, argc, argv));
6742 }
6743
6744 /*
6745  * zfs unshare -a
6746  * zfs unshare filesystem
6747  *
6748  * Unshare all filesystems, or a specific ZFS filesystem.
6749  */
6750 static int
6751 zfs_do_unshare(int argc, char **argv)
6752 {
6753         return (unshare_unmount(OP_SHARE, argc, argv));
6754 }
6755
6756 /*
6757  * Attach/detach the given dataset to/from the given jail
6758  */
6759 /* ARGSUSED */
6760 static int
6761 do_jail(int argc, char **argv, int attach)
6762 {
6763         zfs_handle_t *zhp;
6764         int jailid, ret;
6765
6766         /* check number of arguments */
6767         if (argc < 3) {
6768                 (void) fprintf(stderr, gettext("missing argument(s)\n"));
6769                 usage(B_FALSE);
6770         }
6771         if (argc > 3) {
6772                 (void) fprintf(stderr, gettext("too many arguments\n"));
6773                 usage(B_FALSE);
6774         }
6775
6776         jailid = jail_getid(argv[1]);
6777         if (jailid < 0) {
6778                 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
6779                 usage(B_FALSE);
6780         }
6781
6782         zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
6783         if (zhp == NULL)
6784                 return (1);
6785
6786         ret = (zfs_jail(zhp, jailid, attach) != 0);
6787
6788         zfs_close(zhp);
6789         return (ret);
6790 }
6791
6792 /*
6793  * zfs jail jailid filesystem
6794  *
6795  * Attach the given dataset to the given jail
6796  */
6797 /* ARGSUSED */
6798 static int
6799 zfs_do_jail(int argc, char **argv)
6800 {
6801
6802         return (do_jail(argc, argv, 1));
6803 }
6804
6805 /*
6806  * zfs unjail jailid filesystem
6807  *
6808  * Detach the given dataset from the given jail
6809  */
6810 /* ARGSUSED */
6811 static int
6812 zfs_do_unjail(int argc, char **argv)
6813 {
6814
6815         return (do_jail(argc, argv, 0));
6816 }
6817
6818 /*
6819  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6820  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6821  */
6822 static int
6823 manual_mount(int argc, char **argv)
6824 {
6825         zfs_handle_t *zhp;
6826         char mountpoint[ZFS_MAXPROPLEN];
6827         char mntopts[MNT_LINE_MAX] = { '\0' };
6828         int ret = 0;
6829         int c;
6830         int flags = 0;
6831         char *dataset, *path;
6832
6833         /* check options */
6834         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6835                 switch (c) {
6836                 case 'o':
6837                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6838                         break;
6839                 case 'O':
6840                         flags |= MS_OVERLAY;
6841                         break;
6842                 case 'm':
6843                         flags |= MS_NOMNTTAB;
6844                         break;
6845                 case ':':
6846                         (void) fprintf(stderr, gettext("missing argument for "
6847                             "'%c' option\n"), optopt);
6848                         usage(B_FALSE);
6849                         break;
6850                 case '?':
6851                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6852                             optopt);
6853                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6854                             "<path>\n"));
6855                         return (2);
6856                 }
6857         }
6858
6859         argc -= optind;
6860         argv += optind;
6861
6862         /* check that we only have two arguments */
6863         if (argc != 2) {
6864                 if (argc == 0)
6865                         (void) fprintf(stderr, gettext("missing dataset "
6866                             "argument\n"));
6867                 else if (argc == 1)
6868                         (void) fprintf(stderr,
6869                             gettext("missing mountpoint argument\n"));
6870                 else
6871                         (void) fprintf(stderr, gettext("too many arguments\n"));
6872                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6873                 return (2);
6874         }
6875
6876         dataset = argv[0];
6877         path = argv[1];
6878
6879         /* try to open the dataset */
6880         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6881                 return (1);
6882
6883         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6884             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6885
6886         /* check for legacy mountpoint and complain appropriately */
6887         ret = 0;
6888         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6889                 if (zmount(dataset, path, flags, MNTTYPE_ZFS,
6890                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6891                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
6892                             strerror(errno));
6893                         ret = 1;
6894                 }
6895         } else {
6896                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6897                     "mounted using 'mount -t zfs'\n"), dataset);
6898                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6899                     "instead.\n"), path);
6900                 (void) fprintf(stderr, gettext("If you must use 'mount -t zfs' "
6901                     "or /etc/fstab, use 'zfs set mountpoint=legacy'.\n"));
6902                 (void) fprintf(stderr, gettext("See zfs(8) for more "
6903                     "information.\n"));
6904                 ret = 1;
6905         }
6906
6907         return (ret);
6908 }
6909
6910 /*
6911  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6912  * unmounts of non-legacy filesystems, as this is the dominant administrative
6913  * interface.
6914  */
6915 static int
6916 manual_unmount(int argc, char **argv)
6917 {
6918         int flags = 0;
6919         int c;
6920
6921         /* check options */
6922         while ((c = getopt(argc, argv, "f")) != -1) {
6923                 switch (c) {
6924                 case 'f':
6925                         flags = MS_FORCE;
6926                         break;
6927                 case '?':
6928                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6929                             optopt);
6930                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
6931                             "<path>\n"));
6932                         return (2);
6933                 }
6934         }
6935
6936         argc -= optind;
6937         argv += optind;
6938
6939         /* check arguments */
6940         if (argc != 1) {
6941                 if (argc == 0)
6942                         (void) fprintf(stderr, gettext("missing path "
6943                             "argument\n"));
6944                 else
6945                         (void) fprintf(stderr, gettext("too many arguments\n"));
6946                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6947                 return (2);
6948         }
6949
6950         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6951 }
6952
6953 static int
6954 find_command_idx(char *command, int *idx)
6955 {
6956         int i;
6957
6958         for (i = 0; i < NCOMMAND; i++) {
6959                 if (command_table[i].name == NULL)
6960                         continue;
6961
6962                 if (strcmp(command, command_table[i].name) == 0) {
6963                         *idx = i;
6964                         return (0);
6965                 }
6966         }
6967         return (1);
6968 }
6969
6970 static int
6971 zfs_do_diff(int argc, char **argv)
6972 {
6973         zfs_handle_t *zhp;
6974         int flags = 0;
6975         char *tosnap = NULL;
6976         char *fromsnap = NULL;
6977         char *atp, *copy;
6978         int err = 0;
6979         int c;
6980
6981         while ((c = getopt(argc, argv, "FHt")) != -1) {
6982                 switch (c) {
6983                 case 'F':
6984                         flags |= ZFS_DIFF_CLASSIFY;
6985                         break;
6986                 case 'H':
6987                         flags |= ZFS_DIFF_PARSEABLE;
6988                         break;
6989                 case 't':
6990                         flags |= ZFS_DIFF_TIMESTAMP;
6991                         break;
6992                 default:
6993                         (void) fprintf(stderr,
6994                             gettext("invalid option '%c'\n"), optopt);
6995                         usage(B_FALSE);
6996                 }
6997         }
6998
6999         argc -= optind;
7000         argv += optind;
7001
7002         if (argc < 1) {
7003                 (void) fprintf(stderr,
7004                     gettext("must provide at least one snapshot name\n"));
7005                 usage(B_FALSE);
7006         }
7007
7008         if (argc > 2) {
7009                 (void) fprintf(stderr, gettext("too many arguments\n"));
7010                 usage(B_FALSE);
7011         }
7012
7013         fromsnap = argv[0];
7014         tosnap = (argc == 2) ? argv[1] : NULL;
7015
7016         copy = NULL;
7017         if (*fromsnap != '@')
7018                 copy = strdup(fromsnap);
7019         else if (tosnap)
7020                 copy = strdup(tosnap);
7021         if (copy == NULL)
7022                 usage(B_FALSE);
7023
7024         if ((atp = strchr(copy, '@')) != NULL)
7025                 *atp = '\0';
7026
7027         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
7028                 return (1);
7029
7030         free(copy);
7031
7032         /*
7033          * Ignore SIGPIPE so that the library can give us
7034          * information on any failure
7035          */
7036         (void) sigignore(SIGPIPE);
7037
7038         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
7039
7040         zfs_close(zhp);
7041
7042         return (err != 0);
7043 }
7044
7045 /*
7046  * zfs remap <filesystem | volume>
7047  *
7048  * Remap the indirect blocks in the given fileystem or volume.
7049  */
7050 static int
7051 zfs_do_remap(int argc, char **argv)
7052 {
7053         const char *fsname;
7054         int err = 0;
7055         int c;
7056
7057         /* check options */
7058         while ((c = getopt(argc, argv, "")) != -1) {
7059                 switch (c) {
7060                 case '?':
7061                         (void) fprintf(stderr,
7062                             gettext("invalid option '%c'\n"), optopt);
7063                         usage(B_FALSE);
7064                 }
7065         }
7066
7067         if (argc != 2) {
7068                 (void) fprintf(stderr, gettext("wrong number of arguments\n"));
7069                 usage(B_FALSE);
7070         }
7071
7072         fsname = argv[1];
7073         err = zfs_remap_indirects(g_zfs, fsname);
7074
7075         return (err);
7076 }
7077
7078 /*
7079  * zfs bookmark <fs@snap> <fs#bmark>
7080  *
7081  * Creates a bookmark with the given name from the given snapshot.
7082  */
7083 static int
7084 zfs_do_bookmark(int argc, char **argv)
7085 {
7086         char snapname[ZFS_MAX_DATASET_NAME_LEN];
7087         zfs_handle_t *zhp;
7088         nvlist_t *nvl;
7089         int ret = 0;
7090         int c;
7091
7092         /* check options */
7093         while ((c = getopt(argc, argv, "")) != -1) {
7094                 switch (c) {
7095                 case '?':
7096                         (void) fprintf(stderr,
7097                             gettext("invalid option '%c'\n"), optopt);
7098                         goto usage;
7099                 }
7100         }
7101
7102         argc -= optind;
7103         argv += optind;
7104
7105         /* check number of arguments */
7106         if (argc < 1) {
7107                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
7108                 goto usage;
7109         }
7110         if (argc < 2) {
7111                 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
7112                 goto usage;
7113         }
7114
7115         if (strchr(argv[1], '#') == NULL) {
7116                 (void) fprintf(stderr,
7117                     gettext("invalid bookmark name '%s' -- "
7118                     "must contain a '#'\n"), argv[1]);
7119                 goto usage;
7120         }
7121
7122         if (argv[0][0] == '@') {
7123                 /*
7124                  * Snapshot name begins with @.
7125                  * Default to same fs as bookmark.
7126                  */
7127                 (void) strncpy(snapname, argv[1], sizeof (snapname));
7128                 *strchr(snapname, '#') = '\0';
7129                 (void) strlcat(snapname, argv[0], sizeof (snapname));
7130         } else {
7131                 (void) strncpy(snapname, argv[0], sizeof (snapname));
7132         }
7133         zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
7134         if (zhp == NULL)
7135                 goto usage;
7136         zfs_close(zhp);
7137
7138
7139         nvl = fnvlist_alloc();
7140         fnvlist_add_string(nvl, argv[1], snapname);
7141         ret = lzc_bookmark(nvl, NULL);
7142         fnvlist_free(nvl);
7143
7144         if (ret != 0) {
7145                 const char *err_msg;
7146                 char errbuf[1024];
7147
7148                 (void) snprintf(errbuf, sizeof (errbuf),
7149                     dgettext(TEXT_DOMAIN,
7150                     "cannot create bookmark '%s'"), argv[1]);
7151
7152                 switch (ret) {
7153                 case EXDEV:
7154                         err_msg = "bookmark is in a different pool";
7155                         break;
7156                 case EEXIST:
7157                         err_msg = "bookmark exists";
7158                         break;
7159                 case EINVAL:
7160                         err_msg = "invalid argument";
7161                         break;
7162                 case ENOTSUP:
7163                         err_msg = "bookmark feature not enabled";
7164                         break;
7165                 case ENOSPC:
7166                         err_msg = "out of space";
7167                         break;
7168                 default:
7169                         err_msg = "unknown error";
7170                         break;
7171                 }
7172                 (void) fprintf(stderr, "%s: %s\n", errbuf,
7173                     dgettext(TEXT_DOMAIN, err_msg));
7174         }
7175
7176         return (ret != 0);
7177
7178 usage:
7179         usage(B_FALSE);
7180         return (-1);
7181 }
7182
7183 static int
7184 zfs_do_channel_program(int argc, char **argv)
7185 {
7186         int ret, fd;
7187         char c;
7188         char *progbuf, *filename, *poolname;
7189         size_t progsize, progread;
7190         nvlist_t *outnvl;
7191         uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7192         uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
7193         boolean_t sync_flag = B_TRUE;
7194         zpool_handle_t *zhp;
7195
7196         /* check options */
7197         while (-1 !=
7198             (c = getopt(argc, argv, "nt:(instr-limit)m:(memory-limit)"))) {
7199                 switch (c) {
7200                 case 't':
7201                 case 'm': {
7202                         uint64_t arg;
7203                         char *endp;
7204
7205                         errno = 0;
7206                         arg = strtoull(optarg, &endp, 0);
7207                         if (errno != 0 || *endp != '\0') {
7208                                 (void) fprintf(stderr, gettext(
7209                                     "invalid argument "
7210                                     "'%s': expected integer\n"), optarg);
7211                                 goto usage;
7212                         }
7213
7214                         if (c == 't') {
7215                                 if (arg > ZCP_MAX_INSTRLIMIT || arg == 0) {
7216                                         (void) fprintf(stderr, gettext(
7217                                             "Invalid instruction limit: "
7218                                             "%s\n"), optarg);
7219                                         return (1);
7220                                 } else {
7221                                         instrlimit = arg;
7222                                 }
7223                         } else {
7224                                 ASSERT3U(c, ==, 'm');
7225                                 if (arg > ZCP_MAX_MEMLIMIT || arg == 0) {
7226                                         (void) fprintf(stderr, gettext(
7227                                             "Invalid memory limit: "
7228                                             "%s\n"), optarg);
7229                                         return (1);
7230                                 } else {
7231                                         memlimit = arg;
7232                                 }
7233                         }
7234                         break;
7235                 }
7236                 case 'n': {
7237                         sync_flag = B_FALSE;
7238                         break;
7239                 }
7240                 case '?':
7241                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7242                             optopt);
7243                         goto usage;
7244                 }
7245         }
7246
7247         argc -= optind;
7248         argv += optind;
7249
7250         if (argc < 2) {
7251                 (void) fprintf(stderr,
7252                     gettext("invalid number of arguments\n"));
7253                 goto usage;
7254         }
7255
7256         poolname = argv[0];
7257         filename = argv[1];
7258         if (strcmp(filename, "-") == 0) {
7259                 fd = 0;
7260                 filename = "standard input";
7261         } else if ((fd = open(filename, O_RDONLY)) < 0) {
7262                 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7263                     filename, strerror(errno));
7264                 return (1);
7265         }
7266
7267         if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7268                 (void) fprintf(stderr, gettext("cannot open pool '%s'"),
7269                     poolname);
7270                 return (1);
7271         }
7272         zpool_close(zhp);
7273
7274         /*
7275          * Read in the channel program, expanding the program buffer as
7276          * necessary.
7277          */
7278         progread = 0;
7279         progsize = 1024;
7280         progbuf = safe_malloc(progsize);
7281         do {
7282                 ret = read(fd, progbuf + progread, progsize - progread);
7283                 progread += ret;
7284                 if (progread == progsize && ret > 0) {
7285                         progsize *= 2;
7286                         progbuf = safe_realloc(progbuf, progsize);
7287                 }
7288         } while (ret > 0);
7289
7290         if (fd != 0)
7291                 (void) close(fd);
7292         if (ret < 0) {
7293                 free(progbuf);
7294                 (void) fprintf(stderr,
7295                     gettext("cannot read '%s': %s\n"),
7296                     filename, strerror(errno));
7297                 return (1);
7298         }
7299         progbuf[progread] = '\0';
7300
7301         /*
7302          * Any remaining arguments are passed as arguments to the lua script as
7303          * a string array:
7304          * {
7305          *      "argv" -> [ "arg 1", ... "arg n" ],
7306          * }
7307          */
7308         nvlist_t *argnvl = fnvlist_alloc();
7309         fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7310
7311         if (sync_flag) {
7312                 ret = lzc_channel_program(poolname, progbuf,
7313                     instrlimit, memlimit, argnvl, &outnvl);
7314         } else {
7315                 ret = lzc_channel_program_nosync(poolname, progbuf,
7316                     instrlimit, memlimit, argnvl, &outnvl);
7317         }
7318
7319         if (ret != 0) {
7320                 /*
7321                  * On error, report the error message handed back by lua if one
7322                  * exists.  Otherwise, generate an appropriate error message,
7323                  * falling back on strerror() for an unexpected return code.
7324                  */
7325                 char *errstring = NULL;
7326                 if (nvlist_exists(outnvl, ZCP_RET_ERROR)) {
7327                         (void) nvlist_lookup_string(outnvl,
7328                             ZCP_RET_ERROR, &errstring);
7329                         if (errstring == NULL)
7330                                 errstring = strerror(ret);
7331                 } else {
7332                         switch (ret) {
7333                         case EINVAL:
7334                                 errstring =
7335                                     "Invalid instruction or memory limit.";
7336                                 break;
7337                         case ENOMEM:
7338                                 errstring = "Return value too large.";
7339                                 break;
7340                         case ENOSPC:
7341                                 errstring = "Memory limit exhausted.";
7342                                 break;
7343 #ifdef illumos
7344                         case ETIME:
7345 #else
7346                         case ETIMEDOUT:
7347 #endif
7348                                 errstring = "Timed out.";
7349                                 break;
7350                         case EPERM:
7351                                 errstring = "Permission denied. Channel "
7352                                     "programs must be run as root.";
7353                                 break;
7354                         default:
7355                                 errstring = strerror(ret);
7356                         }
7357                 }
7358                 (void) fprintf(stderr,
7359                     gettext("Channel program execution failed:\n%s\n"),
7360                     errstring);
7361         } else {
7362                 (void) printf("Channel program fully executed ");
7363                 if (nvlist_empty(outnvl)) {
7364                         (void) printf("with no return value.\n");
7365                 } else {
7366                         (void) printf("with return value:\n");
7367                         dump_nvlist(outnvl, 4);
7368                 }
7369         }
7370
7371         free(progbuf);
7372         fnvlist_free(outnvl);
7373         fnvlist_free(argnvl);
7374         return (ret != 0);
7375
7376 usage:
7377         usage(B_FALSE);
7378         return (-1);
7379 }
7380
7381 int
7382 main(int argc, char **argv)
7383 {
7384         int ret = 0;
7385         int i;
7386         char *progname;
7387         char *cmdname;
7388
7389         (void) setlocale(LC_ALL, "");
7390         (void) textdomain(TEXT_DOMAIN);
7391
7392         opterr = 0;
7393
7394         if ((g_zfs = libzfs_init()) == NULL) {
7395                 (void) fprintf(stderr, gettext("internal error: failed to "
7396                     "initialize ZFS library\n"));
7397                 return (1);
7398         }
7399
7400         zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7401
7402         libzfs_print_on_error(g_zfs, B_TRUE);
7403
7404         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
7405                 (void) fprintf(stderr, gettext("internal error: unable to "
7406                     "open %s\n"), MNTTAB);
7407                 return (1);
7408         }
7409
7410         /*
7411          * This command also doubles as the /etc/fs mount and unmount program.
7412          * Determine if we should take this behavior based on argv[0].
7413          */
7414         progname = basename(argv[0]);
7415         if (strcmp(progname, "mount") == 0) {
7416                 ret = manual_mount(argc, argv);
7417         } else if (strcmp(progname, "umount") == 0) {
7418                 ret = manual_unmount(argc, argv);
7419         } else {
7420                 /*
7421                  * Make sure the user has specified some command.
7422                  */
7423                 if (argc < 2) {
7424                         (void) fprintf(stderr, gettext("missing command\n"));
7425                         usage(B_FALSE);
7426                 }
7427
7428                 cmdname = argv[1];
7429
7430                 /*
7431                  * The 'umount' command is an alias for 'unmount'
7432                  */
7433                 if (strcmp(cmdname, "umount") == 0)
7434                         cmdname = "unmount";
7435
7436                 /*
7437                  * The 'recv' command is an alias for 'receive'
7438                  */
7439                 if (strcmp(cmdname, "recv") == 0)
7440                         cmdname = "receive";
7441
7442                 /*
7443                  * The 'snap' command is an alias for 'snapshot'
7444                  */
7445                 if (strcmp(cmdname, "snap") == 0)
7446                         cmdname = "snapshot";
7447
7448                 /*
7449                  * Special case '-?'
7450                  */
7451                 if (strcmp(cmdname, "-?") == 0)
7452                         usage(B_TRUE);
7453
7454                 /*
7455                  * Run the appropriate command.
7456                  */
7457                 libzfs_mnttab_cache(g_zfs, B_TRUE);
7458                 if (find_command_idx(cmdname, &i) == 0) {
7459                         current_command = &command_table[i];
7460                         ret = command_table[i].func(argc - 1, argv + 1);
7461                 } else if (strchr(cmdname, '=') != NULL) {
7462                         verify(find_command_idx("set", &i) == 0);
7463                         current_command = &command_table[i];
7464                         ret = command_table[i].func(argc, argv);
7465                 } else {
7466                         (void) fprintf(stderr, gettext("unrecognized "
7467                             "command '%s'\n"), cmdname);
7468                         usage(B_FALSE);
7469                 }
7470                 libzfs_mnttab_cache(g_zfs, B_FALSE);
7471         }
7472
7473         (void) fclose(mnttab_file);
7474
7475         if (ret == 0 && log_history)
7476                 (void) zpool_log_history(g_zfs, history_str);
7477
7478         libzfs_fini(g_zfs);
7479
7480         /*
7481          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7482          * for the purposes of running ::findleaks.
7483          */
7484         if (getenv("ZFS_ABORT") != NULL) {
7485                 (void) printf("dumping core by request\n");
7486                 abort();
7487         }
7488
7489         return (ret);
7490 }