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