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