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