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