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