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