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