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