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