Fix mount helper
[zfs.git] / cmd / zfs / zfs_main.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25
26 #include <assert.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <libgen.h>
30 #include <libintl.h>
31 #include <libuutil.h>
32 #include <libnvpair.h>
33 #include <locale.h>
34 #include <stddef.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <strings.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <zone.h>
41 #include <grp.h>
42 #include <pwd.h>
43 #include <signal.h>
44 #include <sys/mkdev.h>
45 #include <sys/mntent.h>
46 #include <sys/mnttab.h>
47 #include <sys/mount.h>
48 #include <sys/stat.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/types.h>
51 #include <time.h>
52
53 #include <libzfs.h>
54 #include <libuutil.h>
55
56 #include "zfs_iter.h"
57 #include "zfs_util.h"
58 #include "zfs_comutil.h"
59
60 libzfs_handle_t *g_zfs;
61
62 static FILE *mnttab_file;
63 static char history_str[HIS_MAX_RECORD_LEN];
64 const char *pypath = "/usr/lib/zfs/pyzfs.py";
65
66 static int zfs_do_clone(int argc, char **argv);
67 static int zfs_do_create(int argc, char **argv);
68 static int zfs_do_destroy(int argc, char **argv);
69 static int zfs_do_get(int argc, char **argv);
70 static int zfs_do_inherit(int argc, char **argv);
71 static int zfs_do_list(int argc, char **argv);
72 static int zfs_do_mount(int argc, char **argv);
73 static int zfs_do_rename(int argc, char **argv);
74 static int zfs_do_rollback(int argc, char **argv);
75 static int zfs_do_set(int argc, char **argv);
76 static int zfs_do_upgrade(int argc, char **argv);
77 static int zfs_do_snapshot(int argc, char **argv);
78 static int zfs_do_unmount(int argc, char **argv);
79 static int zfs_do_share(int argc, char **argv);
80 static int zfs_do_unshare(int argc, char **argv);
81 static int zfs_do_send(int argc, char **argv);
82 static int zfs_do_receive(int argc, char **argv);
83 static int zfs_do_promote(int argc, char **argv);
84 static int zfs_do_userspace(int argc, char **argv);
85 static int zfs_do_python(int argc, char **argv);
86 static int zfs_do_hold(int argc, char **argv);
87 static int zfs_do_release(int argc, char **argv);
88 static int zfs_do_diff(int argc, char **argv);
89
90 /*
91  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
92  */
93
94 #ifdef DEBUG
95 const char *
96 _umem_debug_init(void)
97 {
98         return ("default,verbose"); /* $UMEM_DEBUG setting */
99 }
100
101 const char *
102 _umem_logging_init(void)
103 {
104         return ("fail,contents"); /* $UMEM_LOGGING setting */
105 }
106 #endif
107
108 typedef enum {
109         HELP_CLONE,
110         HELP_CREATE,
111         HELP_DESTROY,
112         HELP_GET,
113         HELP_INHERIT,
114         HELP_UPGRADE,
115         HELP_LIST,
116         HELP_MOUNT,
117         HELP_PROMOTE,
118         HELP_RECEIVE,
119         HELP_RENAME,
120         HELP_ROLLBACK,
121         HELP_SEND,
122         HELP_SET,
123         HELP_SHARE,
124         HELP_SNAPSHOT,
125         HELP_UNMOUNT,
126         HELP_UNSHARE,
127         HELP_ALLOW,
128         HELP_UNALLOW,
129         HELP_USERSPACE,
130         HELP_GROUPSPACE,
131         HELP_HOLD,
132         HELP_HOLDS,
133         HELP_RELEASE,
134         HELP_DIFF
135 } zfs_help_t;
136
137 typedef struct zfs_command {
138         const char      *name;
139         int             (*func)(int argc, char **argv);
140         zfs_help_t      usage;
141 } zfs_command_t;
142
143 /*
144  * Master command table.  Each ZFS command has a name, associated function, and
145  * usage message.  The usage messages need to be internationalized, so we have
146  * to have a function to return the usage message based on a command index.
147  *
148  * These commands are organized according to how they are displayed in the usage
149  * message.  An empty command (one with a NULL name) indicates an empty line in
150  * the generic usage message.
151  */
152 static zfs_command_t command_table[] = {
153         { "create",     zfs_do_create,          HELP_CREATE             },
154         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
155         { NULL },
156         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
157         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
158         { "clone",      zfs_do_clone,           HELP_CLONE              },
159         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
160         { "rename",     zfs_do_rename,          HELP_RENAME             },
161         { NULL },
162         { "list",       zfs_do_list,            HELP_LIST               },
163         { NULL },
164         { "set",        zfs_do_set,             HELP_SET                },
165         { "get",        zfs_do_get,             HELP_GET                },
166         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
167         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
168         { "userspace",  zfs_do_userspace,       HELP_USERSPACE          },
169         { "groupspace", zfs_do_userspace,       HELP_GROUPSPACE         },
170         { NULL },
171         { "mount",      zfs_do_mount,           HELP_MOUNT              },
172         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
173         { "share",      zfs_do_share,           HELP_SHARE              },
174         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
175         { NULL },
176         { "send",       zfs_do_send,            HELP_SEND               },
177         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
178         { NULL },
179         { "allow",      zfs_do_python,          HELP_ALLOW              },
180         { NULL },
181         { "unallow",    zfs_do_python,          HELP_UNALLOW            },
182         { NULL },
183         { "hold",       zfs_do_hold,            HELP_HOLD               },
184         { "holds",      zfs_do_python,          HELP_HOLDS              },
185         { "release",    zfs_do_release,         HELP_RELEASE            },
186         { "diff",       zfs_do_diff,            HELP_DIFF               },
187 };
188
189 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
190
191 zfs_command_t *current_command;
192
193 static const char *
194 get_usage(zfs_help_t idx)
195 {
196         switch (idx) {
197         case HELP_CLONE:
198                 return (gettext("\tclone [-p] [-o property=value] ... "
199                     "<snapshot> <filesystem|volume>\n"));
200         case HELP_CREATE:
201                 return (gettext("\tcreate [-p] [-o property=value] ... "
202                     "<filesystem>\n"
203                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
204                     "-V <size> <volume>\n"));
205         case HELP_DESTROY:
206                 return (gettext("\tdestroy [-rRf] <filesystem|volume>\n"
207                     "\tdestroy [-rRd] <snapshot>\n"));
208         case HELP_GET:
209                 return (gettext("\tget [-rHp] [-d max] "
210                     "[-o \"all\" | field[,...]] [-s source[,...]]\n"
211                     "\t    <\"all\" | property[,...]> "
212                     "[filesystem|volume|snapshot] ...\n"));
213         case HELP_INHERIT:
214                 return (gettext("\tinherit [-rS] <property> "
215                     "<filesystem|volume|snapshot> ...\n"));
216         case HELP_UPGRADE:
217                 return (gettext("\tupgrade [-v]\n"
218                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
219         case HELP_LIST:
220                 return (gettext("\tlist [-rH][-d max] "
221                     "[-o property[,...]] [-t type[,...]] [-s property] ...\n"
222                     "\t    [-S property] ... "
223                     "[filesystem|volume|snapshot] ...\n"));
224         case HELP_MOUNT:
225                 return (gettext("\tmount\n"
226                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
227         case HELP_PROMOTE:
228                 return (gettext("\tpromote <clone-filesystem>\n"));
229         case HELP_RECEIVE:
230                 return (gettext("\treceive [-vnFu] <filesystem|volume|"
231                 "snapshot>\n"
232                 "\treceive [-vnFu] [-d | -e] <filesystem>\n"));
233         case HELP_RENAME:
234                 return (gettext("\trename <filesystem|volume|snapshot> "
235                     "<filesystem|volume|snapshot>\n"
236                     "\trename -p <filesystem|volume> <filesystem|volume>\n"
237                     "\trename -r <snapshot> <snapshot>"));
238         case HELP_ROLLBACK:
239                 return (gettext("\trollback [-rRf] <snapshot>\n"));
240         case HELP_SEND:
241                 return (gettext("\tsend [-RDp] [-[iI] snapshot] <snapshot>\n"));
242         case HELP_SET:
243                 return (gettext("\tset <property=value> "
244                     "<filesystem|volume|snapshot> ...\n"));
245         case HELP_SHARE:
246                 return (gettext("\tshare <-a | filesystem>\n"));
247         case HELP_SNAPSHOT:
248                 return (gettext("\tsnapshot [-r] [-o property=value] ... "
249                     "<filesystem@snapname|volume@snapname>\n"));
250         case HELP_UNMOUNT:
251                 return (gettext("\tunmount [-f] "
252                     "<-a | filesystem|mountpoint>\n"));
253         case HELP_UNSHARE:
254                 return (gettext("\tunshare "
255                     "<-a | filesystem|mountpoint>\n"));
256         case HELP_ALLOW:
257                 return (gettext("\tallow <filesystem|volume>\n"
258                     "\tallow [-ldug] "
259                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
260                     "\t    <filesystem|volume>\n"
261                     "\tallow [-ld] -e <perm|@setname>[,...] "
262                     "<filesystem|volume>\n"
263                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
264                     "\tallow -s @setname <perm|@setname>[,...] "
265                     "<filesystem|volume>\n"));
266         case HELP_UNALLOW:
267                 return (gettext("\tunallow [-rldug] "
268                     "<\"everyone\"|user|group>[,...]\n"
269                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
270                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
271                     "<filesystem|volume>\n"
272                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
273                     "<filesystem|volume>\n"
274                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
275                     "<filesystem|volume>\n"));
276         case HELP_USERSPACE:
277                 return (gettext("\tuserspace [-hniHp] [-o field[,...]] "
278                     "[-sS field] ... [-t type[,...]]\n"
279                     "\t    <filesystem|snapshot>\n"));
280         case HELP_GROUPSPACE:
281                 return (gettext("\tgroupspace [-hniHpU] [-o field[,...]] "
282                     "[-sS field] ... [-t type[,...]]\n"
283                     "\t    <filesystem|snapshot>\n"));
284         case HELP_HOLD:
285                 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
286         case HELP_HOLDS:
287                 return (gettext("\tholds [-r] <snapshot> ...\n"));
288         case HELP_RELEASE:
289                 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
290         case HELP_DIFF:
291                 return (gettext("\tdiff [-FHt] <snapshot> "
292                     "[snapshot|filesystem]\n"));
293         }
294
295         abort();
296         /* NOTREACHED */
297 }
298
299 void
300 nomem(void)
301 {
302         (void) fprintf(stderr, gettext("internal error: out of memory\n"));
303         exit(1);
304 }
305
306 /*
307  * Utility function to guarantee malloc() success.
308  */
309
310 void *
311 safe_malloc(size_t size)
312 {
313         void *data;
314
315         if ((data = calloc(1, size)) == NULL)
316                 nomem();
317
318         return (data);
319 }
320
321 static char *
322 safe_strdup(char *str)
323 {
324         char *dupstr = strdup(str);
325
326         if (dupstr == NULL)
327                 nomem();
328
329         return (dupstr);
330 }
331
332 /*
333  * Callback routine that will print out information for each of
334  * the properties.
335  */
336 static int
337 usage_prop_cb(int prop, void *cb)
338 {
339         FILE *fp = cb;
340
341         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
342
343         if (zfs_prop_readonly(prop))
344                 (void) fprintf(fp, " NO    ");
345         else
346                 (void) fprintf(fp, "YES    ");
347
348         if (zfs_prop_inheritable(prop))
349                 (void) fprintf(fp, "  YES   ");
350         else
351                 (void) fprintf(fp, "   NO   ");
352
353         if (zfs_prop_values(prop) == NULL)
354                 (void) fprintf(fp, "-\n");
355         else
356                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
357
358         return (ZPROP_CONT);
359 }
360
361 /*
362  * Display usage message.  If we're inside a command, display only the usage for
363  * that command.  Otherwise, iterate over the entire command table and display
364  * a complete usage message.
365  */
366 static void
367 usage(boolean_t requested)
368 {
369         int i;
370         boolean_t show_properties = B_FALSE;
371         FILE *fp = requested ? stdout : stderr;
372
373         if (current_command == NULL) {
374
375                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
376                 (void) fprintf(fp,
377                     gettext("where 'command' is one of the following:\n\n"));
378
379                 for (i = 0; i < NCOMMAND; i++) {
380                         if (command_table[i].name == NULL)
381                                 (void) fprintf(fp, "\n");
382                         else
383                                 (void) fprintf(fp, "%s",
384                                     get_usage(command_table[i].usage));
385                 }
386
387                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
388                     "pool/[dataset/]*dataset[@name]\n"));
389         } else {
390                 (void) fprintf(fp, gettext("usage:\n"));
391                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
392         }
393
394         if (current_command != NULL &&
395             (strcmp(current_command->name, "set") == 0 ||
396             strcmp(current_command->name, "get") == 0 ||
397             strcmp(current_command->name, "inherit") == 0 ||
398             strcmp(current_command->name, "list") == 0))
399                 show_properties = B_TRUE;
400
401         if (show_properties) {
402                 (void) fprintf(fp,
403                     gettext("\nThe following properties are supported:\n"));
404
405                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
406                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
407
408                 /* Iterate over all properties */
409                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
410                     ZFS_TYPE_DATASET);
411
412                 (void) fprintf(fp, "\t%-15s ", "userused@...");
413                 (void) fprintf(fp, " NO       NO   <size>\n");
414                 (void) fprintf(fp, "\t%-15s ", "groupused@...");
415                 (void) fprintf(fp, " NO       NO   <size>\n");
416                 (void) fprintf(fp, "\t%-15s ", "userquota@...");
417                 (void) fprintf(fp, "YES       NO   <size> | none\n");
418                 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
419                 (void) fprintf(fp, "YES       NO   <size> | none\n");
420
421                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
422                     "with standard units such as K, M, G, etc.\n"));
423                 (void) fprintf(fp, gettext("\nUser-defined properties can "
424                     "be specified by using a name containing a colon (:).\n"));
425                 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
426                     "properties must be appended with\n"
427                     "a user or group specifier of one of these forms:\n"
428                     "    POSIX name      (eg: \"matt\")\n"
429                     "    POSIX id        (eg: \"126829\")\n"
430                     "    SMB name@domain (eg: \"matt@sun\")\n"
431                     "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
432         } else {
433                 (void) fprintf(fp,
434                     gettext("\nFor the property list, run: %s\n"),
435                     "zfs set|get");
436                 (void) fprintf(fp,
437                     gettext("\nFor the delegated permission list, run: %s\n"),
438                     "zfs allow|unallow");
439         }
440
441         /*
442          * See comments at end of main().
443          */
444         if (getenv("ZFS_ABORT") != NULL) {
445                 (void) printf("dumping core by request\n");
446                 abort();
447         }
448
449         exit(requested ? 0 : 2);
450 }
451
452 static int
453 parseprop(nvlist_t *props)
454 {
455         char *propname = optarg;
456         char *propval, *strval;
457
458         if ((propval = strchr(propname, '=')) == NULL) {
459                 (void) fprintf(stderr, gettext("missing "
460                     "'=' for -o option\n"));
461                 return (-1);
462         }
463         *propval = '\0';
464         propval++;
465         if (nvlist_lookup_string(props, propname, &strval) == 0) {
466                 (void) fprintf(stderr, gettext("property '%s' "
467                     "specified multiple times\n"), propname);
468                 return (-1);
469         }
470         if (nvlist_add_string(props, propname, propval) != 0)
471                 nomem();
472         return (0);
473 }
474
475 static int
476 parse_depth(char *opt, int *flags)
477 {
478         char *tmp;
479         int depth;
480
481         depth = (int)strtol(opt, &tmp, 0);
482         if (*tmp) {
483                 (void) fprintf(stderr,
484                     gettext("%s is not an integer\n"), optarg);
485                 usage(B_FALSE);
486         }
487         if (depth < 0) {
488                 (void) fprintf(stderr,
489                     gettext("Depth can not be negative.\n"));
490                 usage(B_FALSE);
491         }
492         *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
493         return (depth);
494 }
495
496 #define PROGRESS_DELAY 2                /* seconds */
497
498 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";
499 static time_t pt_begin;
500 static char *pt_header = NULL;
501 static boolean_t pt_shown;
502
503 static void
504 start_progress_timer(void)
505 {
506         pt_begin = time(NULL) + PROGRESS_DELAY;
507         pt_shown = B_FALSE;
508 }
509
510 static void
511 set_progress_header(char *header)
512 {
513         assert(pt_header == NULL);
514         pt_header = safe_strdup(header);
515         if (pt_shown) {
516                 (void) printf("%s: ", header);
517                 (void) fflush(stdout);
518         }
519 }
520
521 static void
522 update_progress(char *update)
523 {
524         if (!pt_shown && time(NULL) > pt_begin) {
525                 int len = strlen(update);
526
527                 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
528                     pt_reverse);
529                 (void) fflush(stdout);
530                 pt_shown = B_TRUE;
531         } else if (pt_shown) {
532                 int len = strlen(update);
533
534                 (void) printf("%s%*.*s", update, len, len, pt_reverse);
535                 (void) fflush(stdout);
536         }
537 }
538
539 static void
540 finish_progress(char *done)
541 {
542         if (pt_shown) {
543                 (void) printf("%s\n", done);
544                 (void) fflush(stdout);
545         }
546         free(pt_header);
547         pt_header = NULL;
548 }
549
550 /*
551  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
552  *
553  * Given an existing dataset, create a writable copy whose initial contents
554  * are the same as the source.  The newly created dataset maintains a
555  * dependency on the original; the original cannot be destroyed so long as
556  * the clone exists.
557  *
558  * The '-p' flag creates all the non-existing ancestors of the target first.
559  */
560 static int
561 zfs_do_clone(int argc, char **argv)
562 {
563         zfs_handle_t *zhp = NULL;
564         boolean_t parents = B_FALSE;
565         nvlist_t *props;
566         int ret;
567         int c;
568
569         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
570                 nomem();
571
572         /* check options */
573         while ((c = getopt(argc, argv, "o:p")) != -1) {
574                 switch (c) {
575                 case 'o':
576                         if (parseprop(props))
577                                 return (1);
578                         break;
579                 case 'p':
580                         parents = B_TRUE;
581                         break;
582                 case '?':
583                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
584                             optopt);
585                         goto usage;
586                 }
587         }
588
589         argc -= optind;
590         argv += optind;
591
592         /* check number of arguments */
593         if (argc < 1) {
594                 (void) fprintf(stderr, gettext("missing source dataset "
595                     "argument\n"));
596                 goto usage;
597         }
598         if (argc < 2) {
599                 (void) fprintf(stderr, gettext("missing target dataset "
600                     "argument\n"));
601                 goto usage;
602         }
603         if (argc > 2) {
604                 (void) fprintf(stderr, gettext("too many arguments\n"));
605                 goto usage;
606         }
607
608         /* open the source dataset */
609         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
610                 return (1);
611
612         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
613             ZFS_TYPE_VOLUME)) {
614                 /*
615                  * Now create the ancestors of the target dataset.  If the
616                  * target already exists and '-p' option was used we should not
617                  * complain.
618                  */
619                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
620                     ZFS_TYPE_VOLUME))
621                         return (0);
622                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
623                         return (1);
624         }
625
626         /* pass to libzfs */
627         ret = zfs_clone(zhp, argv[1], props);
628
629         /* create the mountpoint if necessary */
630         if (ret == 0) {
631                 zfs_handle_t *clone;
632
633                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
634                 if (clone != NULL) {
635                         if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
636                                 if ((ret = zfs_mount(clone, NULL, 0)) == 0)
637                                         ret = zfs_share(clone);
638                         zfs_close(clone);
639                 }
640         }
641
642         zfs_close(zhp);
643         nvlist_free(props);
644
645         return (!!ret);
646
647 usage:
648         if (zhp)
649                 zfs_close(zhp);
650         nvlist_free(props);
651         usage(B_FALSE);
652         return (-1);
653 }
654
655 /*
656  * zfs create [-p] [-o prop=value] ... fs
657  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
658  *
659  * Create a new dataset.  This command can be used to create filesystems
660  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
661  * For volumes, the user must specify a size to be used.
662  *
663  * The '-s' flag applies only to volumes, and indicates that we should not try
664  * to set the reservation for this volume.  By default we set a reservation
665  * equal to the size for any volume.  For pools with SPA_VERSION >=
666  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
667  *
668  * The '-p' flag creates all the non-existing ancestors of the target first.
669  */
670 static int
671 zfs_do_create(int argc, char **argv)
672 {
673         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
674         zfs_handle_t *zhp = NULL;
675         uint64_t volsize = 0;
676         int c;
677         boolean_t noreserve = B_FALSE;
678         boolean_t bflag = B_FALSE;
679         boolean_t parents = B_FALSE;
680         int ret = 1;
681         nvlist_t *props;
682         uint64_t intval;
683         int canmount = ZFS_CANMOUNT_OFF;
684
685         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
686                 nomem();
687
688         /* check options */
689         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
690                 switch (c) {
691                 case 'V':
692                         type = ZFS_TYPE_VOLUME;
693                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
694                                 (void) fprintf(stderr, gettext("bad volume "
695                                     "size '%s': %s\n"), optarg,
696                                     libzfs_error_description(g_zfs));
697                                 goto error;
698                         }
699
700                         if (nvlist_add_uint64(props,
701                             zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
702                                 nomem();
703                         volsize = intval;
704                         break;
705                 case 'p':
706                         parents = B_TRUE;
707                         break;
708                 case 'b':
709                         bflag = B_TRUE;
710                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
711                                 (void) fprintf(stderr, gettext("bad volume "
712                                     "block size '%s': %s\n"), optarg,
713                                     libzfs_error_description(g_zfs));
714                                 goto error;
715                         }
716
717                         if (nvlist_add_uint64(props,
718                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
719                             intval) != 0)
720                                 nomem();
721                         break;
722                 case 'o':
723                         if (parseprop(props))
724                                 goto error;
725                         break;
726                 case 's':
727                         noreserve = B_TRUE;
728                         break;
729                 case ':':
730                         (void) fprintf(stderr, gettext("missing size "
731                             "argument\n"));
732                         goto badusage;
733                         break;
734                 case '?':
735                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
736                             optopt);
737                         goto badusage;
738                 }
739         }
740
741         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
742                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
743                     "used when creating a volume\n"));
744                 goto badusage;
745         }
746
747         argc -= optind;
748         argv += optind;
749
750         /* check number of arguments */
751         if (argc == 0) {
752                 (void) fprintf(stderr, gettext("missing %s argument\n"),
753                     zfs_type_to_name(type));
754                 goto badusage;
755         }
756         if (argc > 1) {
757                 (void) fprintf(stderr, gettext("too many arguments\n"));
758                 goto badusage;
759         }
760
761         if (type == ZFS_TYPE_VOLUME && !noreserve) {
762                 zpool_handle_t *zpool_handle;
763                 uint64_t spa_version;
764                 char *p;
765                 zfs_prop_t resv_prop;
766                 char *strval;
767
768                 if ((p = strchr(argv[0], '/')))
769                         *p = '\0';
770                 zpool_handle = zpool_open(g_zfs, argv[0]);
771                 if (p != NULL)
772                         *p = '/';
773                 if (zpool_handle == NULL)
774                         goto error;
775                 spa_version = zpool_get_prop_int(zpool_handle,
776                     ZPOOL_PROP_VERSION, NULL);
777                 zpool_close(zpool_handle);
778                 if (spa_version >= SPA_VERSION_REFRESERVATION)
779                         resv_prop = ZFS_PROP_REFRESERVATION;
780                 else
781                         resv_prop = ZFS_PROP_RESERVATION;
782                 volsize = zvol_volsize_to_reservation(volsize, props);
783
784                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
785                     &strval) != 0) {
786                         if (nvlist_add_uint64(props,
787                             zfs_prop_to_name(resv_prop), volsize) != 0) {
788                                 nvlist_free(props);
789                                 nomem();
790                         }
791                 }
792         }
793
794         if (parents && zfs_name_valid(argv[0], type)) {
795                 /*
796                  * Now create the ancestors of target dataset.  If the target
797                  * already exists and '-p' option was used we should not
798                  * complain.
799                  */
800                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
801                         ret = 0;
802                         goto error;
803                 }
804                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
805                         goto error;
806         }
807
808         /* pass to libzfs */
809         if (zfs_create(g_zfs, argv[0], type, props) != 0)
810                 goto error;
811
812         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
813                 goto error;
814
815         ret = 0;
816         /*
817          * if the user doesn't want the dataset automatically mounted,
818          * then skip the mount/share step
819          */
820         if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
821                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
822
823         /*
824          * Mount and/or share the new filesystem as appropriate.  We provide a
825          * verbose error message to let the user know that their filesystem was
826          * in fact created, even if we failed to mount or share it.
827          */
828         if (canmount == ZFS_CANMOUNT_ON) {
829                 if (zfs_mount(zhp, NULL, 0) != 0) {
830                         (void) fprintf(stderr, gettext("filesystem "
831                             "successfully created, but not mounted\n"));
832                         ret = 1;
833                 } else if (zfs_share(zhp) != 0) {
834                         (void) fprintf(stderr, gettext("filesystem "
835                             "successfully created, but not shared\n"));
836                         ret = 1;
837                 }
838         }
839
840 error:
841         if (zhp)
842                 zfs_close(zhp);
843         nvlist_free(props);
844         return (ret);
845 badusage:
846         nvlist_free(props);
847         usage(B_FALSE);
848         return (2);
849 }
850
851 /*
852  * zfs destroy [-rRf] <fs, vol>
853  * zfs destroy [-rRd] <snap>
854  *
855  *      -r      Recursively destroy all children
856  *      -R      Recursively destroy all dependents, including clones
857  *      -f      Force unmounting of any dependents
858  *      -d      If we can't destroy now, mark for deferred destruction
859  *
860  * Destroys the given dataset.  By default, it will unmount any filesystems,
861  * and refuse to destroy a dataset that has any dependents.  A dependent can
862  * either be a child, or a clone of a child.
863  */
864 typedef struct destroy_cbdata {
865         boolean_t       cb_first;
866         int             cb_force;
867         int             cb_recurse;
868         int             cb_error;
869         int             cb_needforce;
870         int             cb_doclones;
871         boolean_t       cb_closezhp;
872         zfs_handle_t    *cb_target;
873         char            *cb_snapname;
874         boolean_t       cb_defer_destroy;
875 } destroy_cbdata_t;
876
877 /*
878  * Check for any dependents based on the '-r' or '-R' flags.
879  */
880 static int
881 destroy_check_dependent(zfs_handle_t *zhp, void *data)
882 {
883         destroy_cbdata_t *cbp = data;
884         const char *tname = zfs_get_name(cbp->cb_target);
885         const char *name = zfs_get_name(zhp);
886
887         if (strncmp(tname, name, strlen(tname)) == 0 &&
888             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
889                 /*
890                  * This is a direct descendant, not a clone somewhere else in
891                  * the hierarchy.
892                  */
893                 if (cbp->cb_recurse)
894                         goto out;
895
896                 if (cbp->cb_first) {
897                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
898                             "%s has children\n"),
899                             zfs_get_name(cbp->cb_target),
900                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
901                         (void) fprintf(stderr, gettext("use '-r' to destroy "
902                             "the following datasets:\n"));
903                         cbp->cb_first = B_FALSE;
904                         cbp->cb_error = 1;
905                 }
906
907                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
908         } else {
909                 /*
910                  * This is a clone.  We only want to report this if the '-r'
911                  * wasn't specified, or the target is a snapshot.
912                  */
913                 if (!cbp->cb_recurse &&
914                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
915                         goto out;
916
917                 if (cbp->cb_first) {
918                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
919                             "%s has dependent clones\n"),
920                             zfs_get_name(cbp->cb_target),
921                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
922                         (void) fprintf(stderr, gettext("use '-R' to destroy "
923                             "the following datasets:\n"));
924                         cbp->cb_first = B_FALSE;
925                         cbp->cb_error = 1;
926                 }
927
928                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
929         }
930
931 out:
932         zfs_close(zhp);
933         return (0);
934 }
935
936 static int
937 destroy_callback(zfs_handle_t *zhp, void *data)
938 {
939         destroy_cbdata_t *cbp = data;
940
941         /*
942          * Ignore pools (which we've already flagged as an error before getting
943          * here).
944          */
945         if (strchr(zfs_get_name(zhp), '/') == NULL &&
946             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
947                 zfs_close(zhp);
948                 return (0);
949         }
950
951         /*
952          * Bail out on the first error.
953          */
954         if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
955             zfs_destroy(zhp, cbp->cb_defer_destroy) != 0) {
956                 zfs_close(zhp);
957                 return (-1);
958         }
959
960         zfs_close(zhp);
961         return (0);
962 }
963
964 static int
965 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
966 {
967         destroy_cbdata_t *cbp = arg;
968         char thissnap[MAXPATHLEN];
969         zfs_handle_t *szhp;
970         boolean_t closezhp = cbp->cb_closezhp;
971         int rv;
972
973         (void) snprintf(thissnap, sizeof (thissnap),
974             "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
975
976         libzfs_print_on_error(g_zfs, B_FALSE);
977         szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
978         libzfs_print_on_error(g_zfs, B_TRUE);
979         if (szhp) {
980                 /*
981                  * Destroy any clones of this snapshot
982                  */
983                 if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
984                     cbp) != 0) {
985                         zfs_close(szhp);
986                         if (closezhp)
987                                 zfs_close(zhp);
988                         return (-1);
989                 }
990                 zfs_close(szhp);
991         }
992
993         cbp->cb_closezhp = B_TRUE;
994         rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
995         if (closezhp)
996                 zfs_close(zhp);
997         return (rv);
998 }
999
1000 static int
1001 zfs_do_destroy(int argc, char **argv)
1002 {
1003         destroy_cbdata_t cb = { 0 };
1004         int c;
1005         zfs_handle_t *zhp;
1006         char *cp;
1007         zfs_type_t type = ZFS_TYPE_DATASET;
1008
1009         /* check options */
1010         while ((c = getopt(argc, argv, "dfrR")) != -1) {
1011                 switch (c) {
1012                 case 'd':
1013                         cb.cb_defer_destroy = B_TRUE;
1014                         type = ZFS_TYPE_SNAPSHOT;
1015                         break;
1016                 case 'f':
1017                         cb.cb_force = 1;
1018                         break;
1019                 case 'r':
1020                         cb.cb_recurse = 1;
1021                         break;
1022                 case 'R':
1023                         cb.cb_recurse = 1;
1024                         cb.cb_doclones = 1;
1025                         break;
1026                 case '?':
1027                 default:
1028                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1029                             optopt);
1030                         usage(B_FALSE);
1031                 }
1032         }
1033
1034         argc -= optind;
1035         argv += optind;
1036
1037         /* check number of arguments */
1038         if (argc == 0) {
1039                 (void) fprintf(stderr, gettext("missing path argument\n"));
1040                 usage(B_FALSE);
1041         }
1042         if (argc > 1) {
1043                 (void) fprintf(stderr, gettext("too many arguments\n"));
1044                 usage(B_FALSE);
1045         }
1046
1047         /*
1048          * If we are doing recursive destroy of a snapshot, then the
1049          * named snapshot may not exist.  Go straight to libzfs.
1050          */
1051         if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
1052                 int ret;
1053
1054                 *cp = '\0';
1055                 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
1056                         return (1);
1057                 *cp = '@';
1058                 cp++;
1059
1060                 if (cb.cb_doclones) {
1061                         boolean_t defer = cb.cb_defer_destroy;
1062
1063                         /*
1064                          * Temporarily ignore the defer_destroy setting since
1065                          * it's not supported for clones.
1066                          */
1067                         cb.cb_defer_destroy = B_FALSE;
1068                         cb.cb_snapname = cp;
1069                         if (destroy_snap_clones(zhp, &cb) != 0) {
1070                                 zfs_close(zhp);
1071                                 return (1);
1072                         }
1073                         cb.cb_defer_destroy = defer;
1074                 }
1075
1076                 ret = zfs_destroy_snaps(zhp, cp, cb.cb_defer_destroy);
1077                 zfs_close(zhp);
1078                 if (ret) {
1079                         (void) fprintf(stderr,
1080                             gettext("no snapshots destroyed\n"));
1081                 }
1082                 return (ret != 0);
1083         }
1084
1085         /* Open the given dataset */
1086         if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1087                 return (1);
1088
1089         cb.cb_target = zhp;
1090
1091         /*
1092          * Perform an explicit check for pools before going any further.
1093          */
1094         if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1095             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1096                 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1097                     "operation does not apply to pools\n"),
1098                     zfs_get_name(zhp));
1099                 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1100                     "%s' to destroy all datasets in the pool\n"),
1101                     zfs_get_name(zhp));
1102                 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1103                     "to destroy the pool itself\n"), zfs_get_name(zhp));
1104                 zfs_close(zhp);
1105                 return (1);
1106         }
1107
1108         /*
1109          * Check for any dependents and/or clones.
1110          */
1111         cb.cb_first = B_TRUE;
1112         if (!cb.cb_doclones && !cb.cb_defer_destroy &&
1113             zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1114             &cb) != 0) {
1115                 zfs_close(zhp);
1116                 return (1);
1117         }
1118
1119         if (cb.cb_error || (!cb.cb_defer_destroy &&
1120             (zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0))) {
1121                 zfs_close(zhp);
1122                 return (1);
1123         }
1124
1125         /*
1126          * Do the real thing.  The callback will close the handle regardless of
1127          * whether it succeeds or not.
1128          */
1129
1130         if (destroy_callback(zhp, &cb) != 0)
1131                 return (1);
1132
1133         return (0);
1134 }
1135
1136 static boolean_t
1137 is_recvd_column(zprop_get_cbdata_t *cbp)
1138 {
1139         int i;
1140         zfs_get_column_t col;
1141
1142         for (i = 0; i < ZFS_GET_NCOLS &&
1143             (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1144                 if (col == GET_COL_RECVD)
1145                         return (B_TRUE);
1146         return (B_FALSE);
1147 }
1148
1149 /*
1150  * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1151  *      < all | property[,property]... > < fs | snap | vol > ...
1152  *
1153  *      -r      recurse over any child datasets
1154  *      -H      scripted mode.  Headers are stripped, and fields are separated
1155  *              by tabs instead of spaces.
1156  *      -o      Set of fields to display.  One of "name,property,value,
1157  *              received,source". Default is "name,property,value,source".
1158  *              "all" is an alias for all five.
1159  *      -s      Set of sources to allow.  One of
1160  *              "local,default,inherited,received,temporary,none".  Default is
1161  *              all six.
1162  *      -p      Display values in parsable (literal) format.
1163  *
1164  *  Prints properties for the given datasets.  The user can control which
1165  *  columns to display as well as which property types to allow.
1166  */
1167
1168 /*
1169  * Invoked to display the properties for a single dataset.
1170  */
1171 static int
1172 get_callback(zfs_handle_t *zhp, void *data)
1173 {
1174         char buf[ZFS_MAXPROPLEN];
1175         char rbuf[ZFS_MAXPROPLEN];
1176         zprop_source_t sourcetype;
1177         char source[ZFS_MAXNAMELEN];
1178         zprop_get_cbdata_t *cbp = data;
1179         nvlist_t *user_props = zfs_get_user_props(zhp);
1180         zprop_list_t *pl = cbp->cb_proplist;
1181         nvlist_t *propval;
1182         char *strval;
1183         char *sourceval;
1184         boolean_t received = is_recvd_column(cbp);
1185
1186         for (; pl != NULL; pl = pl->pl_next) {
1187                 char *recvdval = NULL;
1188                 /*
1189                  * Skip the special fake placeholder.  This will also skip over
1190                  * the name property when 'all' is specified.
1191                  */
1192                 if (pl->pl_prop == ZFS_PROP_NAME &&
1193                     pl == cbp->cb_proplist)
1194                         continue;
1195
1196                 if (pl->pl_prop != ZPROP_INVAL) {
1197                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1198                             sizeof (buf), &sourcetype, source,
1199                             sizeof (source),
1200                             cbp->cb_literal) != 0) {
1201                                 if (pl->pl_all)
1202                                         continue;
1203                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1204                                     ZFS_TYPE_DATASET)) {
1205                                         (void) fprintf(stderr,
1206                                             gettext("No such property '%s'\n"),
1207                                             zfs_prop_to_name(pl->pl_prop));
1208                                         continue;
1209                                 }
1210                                 sourcetype = ZPROP_SRC_NONE;
1211                                 (void) strlcpy(buf, "-", sizeof (buf));
1212                         }
1213
1214                         if (received && (zfs_prop_get_recvd(zhp,
1215                             zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1216                             cbp->cb_literal) == 0))
1217                                 recvdval = rbuf;
1218
1219                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1220                             zfs_prop_to_name(pl->pl_prop),
1221                             buf, sourcetype, source, recvdval);
1222                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1223                         sourcetype = ZPROP_SRC_LOCAL;
1224
1225                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1226                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1227                                 sourcetype = ZPROP_SRC_NONE;
1228                                 (void) strlcpy(buf, "-", sizeof (buf));
1229                         }
1230
1231                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1232                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1233                 } else {
1234                         if (nvlist_lookup_nvlist(user_props,
1235                             pl->pl_user_prop, &propval) != 0) {
1236                                 if (pl->pl_all)
1237                                         continue;
1238                                 sourcetype = ZPROP_SRC_NONE;
1239                                 strval = "-";
1240                         } else {
1241                                 verify(nvlist_lookup_string(propval,
1242                                     ZPROP_VALUE, &strval) == 0);
1243                                 verify(nvlist_lookup_string(propval,
1244                                     ZPROP_SOURCE, &sourceval) == 0);
1245
1246                                 if (strcmp(sourceval,
1247                                     zfs_get_name(zhp)) == 0) {
1248                                         sourcetype = ZPROP_SRC_LOCAL;
1249                                 } else if (strcmp(sourceval,
1250                                     ZPROP_SOURCE_VAL_RECVD) == 0) {
1251                                         sourcetype = ZPROP_SRC_RECEIVED;
1252                                 } else {
1253                                         sourcetype = ZPROP_SRC_INHERITED;
1254                                         (void) strlcpy(source,
1255                                             sourceval, sizeof (source));
1256                                 }
1257                         }
1258
1259                         if (received && (zfs_prop_get_recvd(zhp,
1260                             pl->pl_user_prop, rbuf, sizeof (rbuf),
1261                             cbp->cb_literal) == 0))
1262                                 recvdval = rbuf;
1263
1264                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1265                             pl->pl_user_prop, strval, sourcetype,
1266                             source, recvdval);
1267                 }
1268         }
1269
1270         return (0);
1271 }
1272
1273 static int
1274 zfs_do_get(int argc, char **argv)
1275 {
1276         zprop_get_cbdata_t cb = { 0 };
1277         int i, c, flags = 0;
1278         char *value, *fields;
1279         int ret;
1280         int limit = 0;
1281         zprop_list_t fake_name = { 0 };
1282
1283         /*
1284          * Set up default columns and sources.
1285          */
1286         cb.cb_sources = ZPROP_SRC_ALL;
1287         cb.cb_columns[0] = GET_COL_NAME;
1288         cb.cb_columns[1] = GET_COL_PROPERTY;
1289         cb.cb_columns[2] = GET_COL_VALUE;
1290         cb.cb_columns[3] = GET_COL_SOURCE;
1291         cb.cb_type = ZFS_TYPE_DATASET;
1292
1293         /* check options */
1294         while ((c = getopt(argc, argv, ":d:o:s:rHp")) != -1) {
1295                 switch (c) {
1296                 case 'p':
1297                         cb.cb_literal = B_TRUE;
1298                         break;
1299                 case 'd':
1300                         limit = parse_depth(optarg, &flags);
1301                         break;
1302                 case 'r':
1303                         flags |= ZFS_ITER_RECURSE;
1304                         break;
1305                 case 'H':
1306                         cb.cb_scripted = B_TRUE;
1307                         break;
1308                 case ':':
1309                         (void) fprintf(stderr, gettext("missing argument for "
1310                             "'%c' option\n"), optopt);
1311                         usage(B_FALSE);
1312                         break;
1313                 case 'o':
1314                         /*
1315                          * Process the set of columns to display.  We zero out
1316                          * the structure to give us a blank slate.
1317                          */
1318                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1319                         i = 0;
1320                         while (*optarg != '\0') {
1321                                 static char *col_subopts[] =
1322                                     { "name", "property", "value", "received",
1323                                     "source", "all", NULL };
1324
1325                                 if (i == ZFS_GET_NCOLS) {
1326                                         (void) fprintf(stderr, gettext("too "
1327                                             "many fields given to -o "
1328                                             "option\n"));
1329                                         usage(B_FALSE);
1330                                 }
1331
1332                                 switch (getsubopt(&optarg, col_subopts,
1333                                     &value)) {
1334                                 case 0:
1335                                         cb.cb_columns[i++] = GET_COL_NAME;
1336                                         break;
1337                                 case 1:
1338                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1339                                         break;
1340                                 case 2:
1341                                         cb.cb_columns[i++] = GET_COL_VALUE;
1342                                         break;
1343                                 case 3:
1344                                         cb.cb_columns[i++] = GET_COL_RECVD;
1345                                         flags |= ZFS_ITER_RECVD_PROPS;
1346                                         break;
1347                                 case 4:
1348                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1349                                         break;
1350                                 case 5:
1351                                         if (i > 0) {
1352                                                 (void) fprintf(stderr,
1353                                                     gettext("\"all\" conflicts "
1354                                                     "with specific fields "
1355                                                     "given to -o option\n"));
1356                                                 usage(B_FALSE);
1357                                         }
1358                                         cb.cb_columns[0] = GET_COL_NAME;
1359                                         cb.cb_columns[1] = GET_COL_PROPERTY;
1360                                         cb.cb_columns[2] = GET_COL_VALUE;
1361                                         cb.cb_columns[3] = GET_COL_RECVD;
1362                                         cb.cb_columns[4] = GET_COL_SOURCE;
1363                                         flags |= ZFS_ITER_RECVD_PROPS;
1364                                         i = ZFS_GET_NCOLS;
1365                                         break;
1366                                 default:
1367                                         (void) fprintf(stderr,
1368                                             gettext("invalid column name "
1369                                             "'%s'\n"), value);
1370                                         usage(B_FALSE);
1371                                 }
1372                         }
1373                         break;
1374
1375                 case 's':
1376                         cb.cb_sources = 0;
1377                         while (*optarg != '\0') {
1378                                 static char *source_subopts[] = {
1379                                         "local", "default", "inherited",
1380                                         "received", "temporary", "none",
1381                                         NULL };
1382
1383                                 switch (getsubopt(&optarg, source_subopts,
1384                                     &value)) {
1385                                 case 0:
1386                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1387                                         break;
1388                                 case 1:
1389                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1390                                         break;
1391                                 case 2:
1392                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1393                                         break;
1394                                 case 3:
1395                                         cb.cb_sources |= ZPROP_SRC_RECEIVED;
1396                                         break;
1397                                 case 4:
1398                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1399                                         break;
1400                                 case 5:
1401                                         cb.cb_sources |= ZPROP_SRC_NONE;
1402                                         break;
1403                                 default:
1404                                         (void) fprintf(stderr,
1405                                             gettext("invalid source "
1406                                             "'%s'\n"), value);
1407                                         usage(B_FALSE);
1408                                 }
1409                         }
1410                         break;
1411
1412                 case '?':
1413                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1414                             optopt);
1415                         usage(B_FALSE);
1416                 }
1417         }
1418
1419         argc -= optind;
1420         argv += optind;
1421
1422         if (argc < 1) {
1423                 (void) fprintf(stderr, gettext("missing property "
1424                     "argument\n"));
1425                 usage(B_FALSE);
1426         }
1427
1428         fields = argv[0];
1429
1430         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1431             != 0)
1432                 usage(B_FALSE);
1433
1434         argc--;
1435         argv++;
1436
1437         /*
1438          * As part of zfs_expand_proplist(), we keep track of the maximum column
1439          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1440          * need to know the maximum name length.  However, the user likely did
1441          * not specify 'name' as one of the properties to fetch, so we need to
1442          * make sure we always include at least this property for
1443          * print_get_headers() to work properly.
1444          */
1445         if (cb.cb_proplist != NULL) {
1446                 fake_name.pl_prop = ZFS_PROP_NAME;
1447                 fake_name.pl_width = strlen(gettext("NAME"));
1448                 fake_name.pl_next = cb.cb_proplist;
1449                 cb.cb_proplist = &fake_name;
1450         }
1451
1452         cb.cb_first = B_TRUE;
1453
1454         /* run for each object */
1455         ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET, NULL,
1456             &cb.cb_proplist, limit, get_callback, &cb);
1457
1458         if (cb.cb_proplist == &fake_name)
1459                 zprop_free_list(fake_name.pl_next);
1460         else
1461                 zprop_free_list(cb.cb_proplist);
1462
1463         return (ret);
1464 }
1465
1466 /*
1467  * inherit [-rS] <property> <fs|vol> ...
1468  *
1469  *      -r      Recurse over all children
1470  *      -S      Revert to received value, if any
1471  *
1472  * For each dataset specified on the command line, inherit the given property
1473  * from its parent.  Inheriting a property at the pool level will cause it to
1474  * use the default value.  The '-r' flag will recurse over all children, and is
1475  * useful for setting a property on a hierarchy-wide basis, regardless of any
1476  * local modifications for each dataset.
1477  */
1478
1479 typedef struct inherit_cbdata {
1480         const char *cb_propname;
1481         boolean_t cb_received;
1482 } inherit_cbdata_t;
1483
1484 static int
1485 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1486 {
1487         inherit_cbdata_t *cb = data;
1488         zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1489
1490         /*
1491          * If we're doing it recursively, then ignore properties that
1492          * are not valid for this type of dataset.
1493          */
1494         if (prop != ZPROP_INVAL &&
1495             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1496                 return (0);
1497
1498         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1499 }
1500
1501 static int
1502 inherit_cb(zfs_handle_t *zhp, void *data)
1503 {
1504         inherit_cbdata_t *cb = data;
1505
1506         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1507 }
1508
1509 static int
1510 zfs_do_inherit(int argc, char **argv)
1511 {
1512         int c;
1513         zfs_prop_t prop;
1514         inherit_cbdata_t cb = { 0 };
1515         char *propname;
1516         int ret;
1517         int flags = 0;
1518         boolean_t received = B_FALSE;
1519
1520         /* check options */
1521         while ((c = getopt(argc, argv, "rS")) != -1) {
1522                 switch (c) {
1523                 case 'r':
1524                         flags |= ZFS_ITER_RECURSE;
1525                         break;
1526                 case 'S':
1527                         received = B_TRUE;
1528                         break;
1529                 case '?':
1530                 default:
1531                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1532                             optopt);
1533                         usage(B_FALSE);
1534                 }
1535         }
1536
1537         argc -= optind;
1538         argv += optind;
1539
1540         /* check number of arguments */
1541         if (argc < 1) {
1542                 (void) fprintf(stderr, gettext("missing property argument\n"));
1543                 usage(B_FALSE);
1544         }
1545         if (argc < 2) {
1546                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1547                 usage(B_FALSE);
1548         }
1549
1550         propname = argv[0];
1551         argc--;
1552         argv++;
1553
1554         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1555                 if (zfs_prop_readonly(prop)) {
1556                         (void) fprintf(stderr, gettext(
1557                             "%s property is read-only\n"),
1558                             propname);
1559                         return (1);
1560                 }
1561                 if (!zfs_prop_inheritable(prop) && !received) {
1562                         (void) fprintf(stderr, gettext("'%s' property cannot "
1563                             "be inherited\n"), propname);
1564                         if (prop == ZFS_PROP_QUOTA ||
1565                             prop == ZFS_PROP_RESERVATION ||
1566                             prop == ZFS_PROP_REFQUOTA ||
1567                             prop == ZFS_PROP_REFRESERVATION)
1568                                 (void) fprintf(stderr, gettext("use 'zfs set "
1569                                     "%s=none' to clear\n"), propname);
1570                         return (1);
1571                 }
1572                 if (received && (prop == ZFS_PROP_VOLSIZE ||
1573                     prop == ZFS_PROP_VERSION)) {
1574                         (void) fprintf(stderr, gettext("'%s' property cannot "
1575                             "be reverted to a received value\n"), propname);
1576                         return (1);
1577                 }
1578         } else if (!zfs_prop_user(propname)) {
1579                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1580                     propname);
1581                 usage(B_FALSE);
1582         }
1583
1584         cb.cb_propname = propname;
1585         cb.cb_received = received;
1586
1587         if (flags & ZFS_ITER_RECURSE) {
1588                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1589                     NULL, NULL, 0, inherit_recurse_cb, &cb);
1590         } else {
1591                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1592                     NULL, NULL, 0, inherit_cb, &cb);
1593         }
1594
1595         return (ret);
1596 }
1597
1598 typedef struct upgrade_cbdata {
1599         uint64_t cb_numupgraded;
1600         uint64_t cb_numsamegraded;
1601         uint64_t cb_numfailed;
1602         uint64_t cb_version;
1603         boolean_t cb_newer;
1604         boolean_t cb_foundone;
1605         char cb_lastfs[ZFS_MAXNAMELEN];
1606 } upgrade_cbdata_t;
1607
1608 static int
1609 same_pool(zfs_handle_t *zhp, const char *name)
1610 {
1611         int len1 = strcspn(name, "/@");
1612         const char *zhname = zfs_get_name(zhp);
1613         int len2 = strcspn(zhname, "/@");
1614
1615         if (len1 != len2)
1616                 return (B_FALSE);
1617         return (strncmp(name, zhname, len1) == 0);
1618 }
1619
1620 static int
1621 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1622 {
1623         upgrade_cbdata_t *cb = data;
1624         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1625
1626         /* list if it's old/new */
1627         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1628             (cb->cb_newer && version > ZPL_VERSION)) {
1629                 char *str;
1630                 if (cb->cb_newer) {
1631                         str = gettext("The following filesystems are "
1632                             "formatted using a newer software version and\n"
1633                             "cannot be accessed on the current system.\n\n");
1634                 } else {
1635                         str = gettext("The following filesystems are "
1636                             "out of date, and can be upgraded.  After being\n"
1637                             "upgraded, these filesystems (and any 'zfs send' "
1638                             "streams generated from\n"
1639                             "subsequent snapshots) will no longer be "
1640                             "accessible by older software versions.\n\n");
1641                 }
1642
1643                 if (!cb->cb_foundone) {
1644                         (void) puts(str);
1645                         (void) printf(gettext("VER  FILESYSTEM\n"));
1646                         (void) printf(gettext("---  ------------\n"));
1647                         cb->cb_foundone = B_TRUE;
1648                 }
1649
1650                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1651         }
1652
1653         return (0);
1654 }
1655
1656 static int
1657 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1658 {
1659         upgrade_cbdata_t *cb = data;
1660         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1661         int needed_spa_version;
1662         int spa_version;
1663
1664         if (zfs_spa_version(zhp, &spa_version) < 0)
1665                 return (-1);
1666
1667         needed_spa_version = zfs_spa_version_map(cb->cb_version);
1668
1669         if (needed_spa_version < 0)
1670                 return (-1);
1671
1672         if (spa_version < needed_spa_version) {
1673                 /* can't upgrade */
1674                 (void) printf(gettext("%s: can not be "
1675                     "upgraded; the pool version needs to first "
1676                     "be upgraded\nto version %d\n\n"),
1677                     zfs_get_name(zhp), needed_spa_version);
1678                 cb->cb_numfailed++;
1679                 return (0);
1680         }
1681
1682         /* upgrade */
1683         if (version < cb->cb_version) {
1684                 char verstr[16];
1685                 (void) snprintf(verstr, sizeof (verstr),
1686                     "%llu", (u_longlong_t)cb->cb_version);
1687                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1688                         /*
1689                          * If they did "zfs upgrade -a", then we could
1690                          * be doing ioctls to different pools.  We need
1691                          * to log this history once to each pool.
1692                          */
1693                         verify(zpool_stage_history(g_zfs, history_str) == 0);
1694                 }
1695                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1696                         cb->cb_numupgraded++;
1697                 else
1698                         cb->cb_numfailed++;
1699                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1700         } else if (version > cb->cb_version) {
1701                 /* can't downgrade */
1702                 (void) printf(gettext("%s: can not be downgraded; "
1703                     "it is already at version %u\n"),
1704                     zfs_get_name(zhp), version);
1705                 cb->cb_numfailed++;
1706         } else {
1707                 cb->cb_numsamegraded++;
1708         }
1709         return (0);
1710 }
1711
1712 /*
1713  * zfs upgrade
1714  * zfs upgrade -v
1715  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1716  */
1717 static int
1718 zfs_do_upgrade(int argc, char **argv)
1719 {
1720         boolean_t all = B_FALSE;
1721         boolean_t showversions = B_FALSE;
1722         int ret;
1723         upgrade_cbdata_t cb = { 0 };
1724         signed char c;
1725         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1726
1727         /* check options */
1728         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1729                 switch (c) {
1730                 case 'r':
1731                         flags |= ZFS_ITER_RECURSE;
1732                         break;
1733                 case 'v':
1734                         showversions = B_TRUE;
1735                         break;
1736                 case 'V':
1737                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1738                             optarg, &cb.cb_version) != 0) {
1739                                 (void) fprintf(stderr,
1740                                     gettext("invalid version %s\n"), optarg);
1741                                 usage(B_FALSE);
1742                         }
1743                         break;
1744                 case 'a':
1745                         all = B_TRUE;
1746                         break;
1747                 case '?':
1748                 default:
1749                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1750                             optopt);
1751                         usage(B_FALSE);
1752                 }
1753         }
1754
1755         argc -= optind;
1756         argv += optind;
1757
1758         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1759                 usage(B_FALSE);
1760         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1761             cb.cb_version || argc))
1762                 usage(B_FALSE);
1763         if ((all || argc) && (showversions))
1764                 usage(B_FALSE);
1765         if (all && argc)
1766                 usage(B_FALSE);
1767
1768         if (showversions) {
1769                 /* Show info on available versions. */
1770                 (void) printf(gettext("The following filesystem versions are "
1771                     "supported:\n\n"));
1772                 (void) printf(gettext("VER  DESCRIPTION\n"));
1773                 (void) printf("---  -----------------------------------------"
1774                     "---------------\n");
1775                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1776                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
1777                 (void) printf(gettext(" 3   Case insensitive and File system "
1778                     "unique identifier (FUID)\n"));
1779                 (void) printf(gettext(" 4   userquota, groupquota "
1780                     "properties\n"));
1781                 (void) printf(gettext(" 5   System attributes\n"));
1782                 (void) printf(gettext("\nFor more information on a particular "
1783                     "version, including supported releases,\n"));
1784                 (void) printf("see the ZFS Administration Guide.\n\n");
1785                 ret = 0;
1786         } else if (argc || all) {
1787                 /* Upgrade filesystems */
1788                 if (cb.cb_version == 0)
1789                         cb.cb_version = ZPL_VERSION;
1790                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
1791                     NULL, NULL, 0, upgrade_set_callback, &cb);
1792                 (void) printf(gettext("%llu filesystems upgraded\n"),
1793                     (u_longlong_t)cb.cb_numupgraded);
1794                 if (cb.cb_numsamegraded) {
1795                         (void) printf(gettext("%llu filesystems already at "
1796                             "this version\n"),
1797                             (u_longlong_t)cb.cb_numsamegraded);
1798                 }
1799                 if (cb.cb_numfailed != 0)
1800                         ret = 1;
1801         } else {
1802                 /* List old-version filesytems */
1803                 boolean_t found;
1804                 (void) printf(gettext("This system is currently running "
1805                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
1806
1807                 flags |= ZFS_ITER_RECURSE;
1808                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1809                     NULL, NULL, 0, upgrade_list_callback, &cb);
1810
1811                 found = cb.cb_foundone;
1812                 cb.cb_foundone = B_FALSE;
1813                 cb.cb_newer = B_TRUE;
1814
1815                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1816                     NULL, NULL, 0, upgrade_list_callback, &cb);
1817
1818                 if (!cb.cb_foundone && !found) {
1819                         (void) printf(gettext("All filesystems are "
1820                             "formatted with the current version.\n"));
1821                 }
1822         }
1823
1824         return (ret);
1825 }
1826
1827 /*
1828  * zfs userspace
1829  */
1830 static int
1831 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
1832 {
1833         zfs_userquota_prop_t *typep = arg;
1834         zfs_userquota_prop_t p = *typep;
1835         char *name = NULL;
1836         char *ug, *propname;
1837         char namebuf[32];
1838         char sizebuf[32];
1839
1840         if (domain == NULL || domain[0] == '\0') {
1841                 if (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) {
1842                         struct group *g = getgrgid(rid);
1843                         if (g)
1844                                 name = g->gr_name;
1845                 } else {
1846                         struct passwd *p = getpwuid(rid);
1847                         if (p)
1848                                 name = p->pw_name;
1849                 }
1850         }
1851
1852         if (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA)
1853                 ug = "group";
1854         else
1855                 ug = "user";
1856
1857         if (p == ZFS_PROP_USERUSED || p == ZFS_PROP_GROUPUSED)
1858                 propname = "used";
1859         else
1860                 propname = "quota";
1861
1862         if (name == NULL) {
1863                 (void) snprintf(namebuf, sizeof (namebuf),
1864                     "%llu", (longlong_t)rid);
1865                 name = namebuf;
1866         }
1867         zfs_nicenum(space, sizebuf, sizeof (sizebuf));
1868
1869         (void) printf("%s %s %s%c%s %s\n", propname, ug, domain,
1870             domain[0] ? '-' : ' ', name, sizebuf);
1871
1872         return (0);
1873 }
1874
1875 static int
1876 zfs_do_userspace(int argc, char **argv)
1877 {
1878         zfs_handle_t *zhp;
1879         zfs_userquota_prop_t p;
1880         int error;
1881
1882         /*
1883          * Try the python version.  If the execv fails, we'll continue
1884          * and do a simplistic implementation.
1885          */
1886         (void) execv(pypath, argv-1);
1887
1888         (void) printf("internal error: %s not found\n"
1889             "falling back on built-in implementation, "
1890             "some features will not work\n", pypath);
1891
1892         if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
1893                 return (1);
1894
1895         (void) printf("PROP TYPE NAME VALUE\n");
1896
1897         for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
1898                 error = zfs_userspace(zhp, p, userspace_cb, &p);
1899                 if (error)
1900                         break;
1901         }
1902         return (error);
1903 }
1904
1905 /*
1906  * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
1907  *      [-s property [-s property]...] [-S property [-S property]...]
1908  *      <dataset> ...
1909  *
1910  *      -r      Recurse over all children
1911  *      -d      Limit recursion by depth.
1912  *      -H      Scripted mode; elide headers and separate columns by tabs
1913  *      -o      Control which fields to display.
1914  *      -t      Control which object types to display.
1915  *      -s      Specify sort columns, descending order.
1916  *      -S      Specify sort columns, ascending order.
1917  *
1918  * When given no arguments, lists all filesystems in the system.
1919  * Otherwise, list the specified datasets, optionally recursing down them if
1920  * '-r' is specified.
1921  */
1922 typedef struct list_cbdata {
1923         boolean_t       cb_first;
1924         boolean_t       cb_scripted;
1925         zprop_list_t    *cb_proplist;
1926 } list_cbdata_t;
1927
1928 /*
1929  * Given a list of columns to display, output appropriate headers for each one.
1930  */
1931 static void
1932 print_header(zprop_list_t *pl)
1933 {
1934         char headerbuf[ZFS_MAXPROPLEN];
1935         const char *header;
1936         int i;
1937         boolean_t first = B_TRUE;
1938         boolean_t right_justify;
1939
1940         for (; pl != NULL; pl = pl->pl_next) {
1941                 if (!first) {
1942                         (void) printf("  ");
1943                 } else {
1944                         first = B_FALSE;
1945                 }
1946
1947                 right_justify = B_FALSE;
1948                 if (pl->pl_prop != ZPROP_INVAL) {
1949                         header = zfs_prop_column_name(pl->pl_prop);
1950                         right_justify = zfs_prop_align_right(pl->pl_prop);
1951                 } else {
1952                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1953                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
1954                         headerbuf[i] = '\0';
1955                         header = headerbuf;
1956                 }
1957
1958                 if (pl->pl_next == NULL && !right_justify)
1959                         (void) printf("%s", header);
1960                 else if (right_justify)
1961                         (void) printf("%*s", (int)pl->pl_width, header);
1962                 else
1963                         (void) printf("%-*s", (int)pl->pl_width, header);
1964         }
1965
1966         (void) printf("\n");
1967 }
1968
1969 /*
1970  * Given a dataset and a list of fields, print out all the properties according
1971  * to the described layout.
1972  */
1973 static void
1974 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1975 {
1976         boolean_t first = B_TRUE;
1977         char property[ZFS_MAXPROPLEN];
1978         nvlist_t *userprops = zfs_get_user_props(zhp);
1979         nvlist_t *propval;
1980         char *propstr;
1981         boolean_t right_justify;
1982         int width;
1983
1984         for (; pl != NULL; pl = pl->pl_next) {
1985                 if (!first) {
1986                         if (scripted)
1987                                 (void) printf("\t");
1988                         else
1989                                 (void) printf("  ");
1990                 } else {
1991                         first = B_FALSE;
1992                 }
1993
1994                 if (pl->pl_prop != ZPROP_INVAL) {
1995                         if (zfs_prop_get(zhp, pl->pl_prop, property,
1996                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1997                                 propstr = "-";
1998                         else
1999                                 propstr = property;
2000
2001                         right_justify = zfs_prop_align_right(pl->pl_prop);
2002                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2003                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2004                             property, sizeof (property), B_FALSE) != 0)
2005                                 propstr = "-";
2006                         else
2007                                 propstr = property;
2008                         right_justify = B_TRUE;
2009                 } else {
2010                         if (nvlist_lookup_nvlist(userprops,
2011                             pl->pl_user_prop, &propval) != 0)
2012                                 propstr = "-";
2013                         else
2014                                 verify(nvlist_lookup_string(propval,
2015                                     ZPROP_VALUE, &propstr) == 0);
2016                         right_justify = B_FALSE;
2017                 }
2018
2019                 width = pl->pl_width;
2020
2021                 /*
2022                  * If this is being called in scripted mode, or if this is the
2023                  * last column and it is left-justified, don't include a width
2024                  * format specifier.
2025                  */
2026                 if (scripted || (pl->pl_next == NULL && !right_justify))
2027                         (void) printf("%s", propstr);
2028                 else if (right_justify)
2029                         (void) printf("%*s", width, propstr);
2030                 else
2031                         (void) printf("%-*s", width, propstr);
2032         }
2033
2034         (void) printf("\n");
2035 }
2036
2037 /*
2038  * Generic callback function to list a dataset or snapshot.
2039  */
2040 static int
2041 list_callback(zfs_handle_t *zhp, void *data)
2042 {
2043         list_cbdata_t *cbp = data;
2044
2045         if (cbp->cb_first) {
2046                 if (!cbp->cb_scripted)
2047                         print_header(cbp->cb_proplist);
2048                 cbp->cb_first = B_FALSE;
2049         }
2050
2051         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2052
2053         return (0);
2054 }
2055
2056 static int
2057 zfs_do_list(int argc, char **argv)
2058 {
2059         int c;
2060         boolean_t scripted = B_FALSE;
2061         static char default_fields[] =
2062             "name,used,available,referenced,mountpoint";
2063         int types = ZFS_TYPE_DATASET;
2064         boolean_t types_specified = B_FALSE;
2065         char *fields = NULL;
2066         list_cbdata_t cb = { 0 };
2067         char *value;
2068         int limit = 0;
2069         int ret;
2070         zfs_sort_column_t *sortcol = NULL;
2071         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2072
2073         /* check options */
2074         while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2075                 switch (c) {
2076                 case 'o':
2077                         fields = optarg;
2078                         break;
2079                 case 'd':
2080                         limit = parse_depth(optarg, &flags);
2081                         break;
2082                 case 'r':
2083                         flags |= ZFS_ITER_RECURSE;
2084                         break;
2085                 case 'H':
2086                         scripted = B_TRUE;
2087                         break;
2088                 case 's':
2089                         if (zfs_add_sort_column(&sortcol, optarg,
2090                             B_FALSE) != 0) {
2091                                 (void) fprintf(stderr,
2092                                     gettext("invalid property '%s'\n"), optarg);
2093                                 usage(B_FALSE);
2094                         }
2095                         break;
2096                 case 'S':
2097                         if (zfs_add_sort_column(&sortcol, optarg,
2098                             B_TRUE) != 0) {
2099                                 (void) fprintf(stderr,
2100                                     gettext("invalid property '%s'\n"), optarg);
2101                                 usage(B_FALSE);
2102                         }
2103                         break;
2104                 case 't':
2105                         types = 0;
2106                         types_specified = B_TRUE;
2107                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2108                         while (*optarg != '\0') {
2109                                 static char *type_subopts[] = { "filesystem",
2110                                     "volume", "snapshot", "all", NULL };
2111
2112                                 switch (getsubopt(&optarg, type_subopts,
2113                                     &value)) {
2114                                 case 0:
2115                                         types |= ZFS_TYPE_FILESYSTEM;
2116                                         break;
2117                                 case 1:
2118                                         types |= ZFS_TYPE_VOLUME;
2119                                         break;
2120                                 case 2:
2121                                         types |= ZFS_TYPE_SNAPSHOT;
2122                                         break;
2123                                 case 3:
2124                                         types = ZFS_TYPE_DATASET;
2125                                         break;
2126
2127                                 default:
2128                                         (void) fprintf(stderr,
2129                                             gettext("invalid type '%s'\n"),
2130                                             value);
2131                                         usage(B_FALSE);
2132                                 }
2133                         }
2134                         break;
2135                 case ':':
2136                         (void) fprintf(stderr, gettext("missing argument for "
2137                             "'%c' option\n"), optopt);
2138                         usage(B_FALSE);
2139                         break;
2140                 case '?':
2141                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2142                             optopt);
2143                         usage(B_FALSE);
2144                 }
2145         }
2146
2147         argc -= optind;
2148         argv += optind;
2149
2150         if (fields == NULL)
2151                 fields = default_fields;
2152
2153         /*
2154          * If "-o space" and no types were specified, don't display snapshots.
2155          */
2156         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
2157                 types &= ~ZFS_TYPE_SNAPSHOT;
2158
2159         /*
2160          * If the user specifies '-o all', the zprop_get_list() doesn't
2161          * normally include the name of the dataset.  For 'zfs list', we always
2162          * want this property to be first.
2163          */
2164         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2165             != 0)
2166                 usage(B_FALSE);
2167
2168         cb.cb_scripted = scripted;
2169         cb.cb_first = B_TRUE;
2170
2171         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
2172             limit, list_callback, &cb);
2173
2174         zprop_free_list(cb.cb_proplist);
2175         zfs_free_sort_columns(sortcol);
2176
2177         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
2178                 (void) printf(gettext("no datasets available\n"));
2179
2180         return (ret);
2181 }
2182
2183 /*
2184  * zfs rename <fs | snap | vol> <fs | snap | vol>
2185  * zfs rename -p <fs | vol> <fs | vol>
2186  * zfs rename -r <snap> <snap>
2187  *
2188  * Renames the given dataset to another of the same type.
2189  *
2190  * The '-p' flag creates all the non-existing ancestors of the target first.
2191  */
2192 /* ARGSUSED */
2193 static int
2194 zfs_do_rename(int argc, char **argv)
2195 {
2196         zfs_handle_t *zhp;
2197         int c;
2198         int ret;
2199         boolean_t recurse = B_FALSE;
2200         boolean_t parents = B_FALSE;
2201
2202         /* check options */
2203         while ((c = getopt(argc, argv, "pr")) != -1) {
2204                 switch (c) {
2205                 case 'p':
2206                         parents = B_TRUE;
2207                         break;
2208                 case 'r':
2209                         recurse = B_TRUE;
2210                         break;
2211                 case '?':
2212                 default:
2213                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2214                             optopt);
2215                         usage(B_FALSE);
2216                 }
2217         }
2218
2219         argc -= optind;
2220         argv += optind;
2221
2222         /* check number of arguments */
2223         if (argc < 1) {
2224                 (void) fprintf(stderr, gettext("missing source dataset "
2225                     "argument\n"));
2226                 usage(B_FALSE);
2227         }
2228         if (argc < 2) {
2229                 (void) fprintf(stderr, gettext("missing target dataset "
2230                     "argument\n"));
2231                 usage(B_FALSE);
2232         }
2233         if (argc > 2) {
2234                 (void) fprintf(stderr, gettext("too many arguments\n"));
2235                 usage(B_FALSE);
2236         }
2237
2238         if (recurse && parents) {
2239                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
2240                     "exclusive\n"));
2241                 usage(B_FALSE);
2242         }
2243
2244         if (recurse && strchr(argv[0], '@') == 0) {
2245                 (void) fprintf(stderr, gettext("source dataset for recursive "
2246                     "rename must be a snapshot\n"));
2247                 usage(B_FALSE);
2248         }
2249
2250         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
2251             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
2252                 return (1);
2253
2254         /* If we were asked and the name looks good, try to create ancestors. */
2255         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
2256             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
2257                 zfs_close(zhp);
2258                 return (1);
2259         }
2260
2261         ret = (zfs_rename(zhp, argv[1], recurse) != 0);
2262
2263         zfs_close(zhp);
2264         return (ret);
2265 }
2266
2267 /*
2268  * zfs promote <fs>
2269  *
2270  * Promotes the given clone fs to be the parent
2271  */
2272 /* ARGSUSED */
2273 static int
2274 zfs_do_promote(int argc, char **argv)
2275 {
2276         zfs_handle_t *zhp;
2277         int ret;
2278
2279         /* check options */
2280         if (argc > 1 && argv[1][0] == '-') {
2281                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2282                     argv[1][1]);
2283                 usage(B_FALSE);
2284         }
2285
2286         /* check number of arguments */
2287         if (argc < 2) {
2288                 (void) fprintf(stderr, gettext("missing clone filesystem"
2289                     " argument\n"));
2290                 usage(B_FALSE);
2291         }
2292         if (argc > 2) {
2293                 (void) fprintf(stderr, gettext("too many arguments\n"));
2294                 usage(B_FALSE);
2295         }
2296
2297         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2298         if (zhp == NULL)
2299                 return (1);
2300
2301         ret = (zfs_promote(zhp) != 0);
2302
2303
2304         zfs_close(zhp);
2305         return (ret);
2306 }
2307
2308 /*
2309  * zfs rollback [-rRf] <snapshot>
2310  *
2311  *      -r      Delete any intervening snapshots before doing rollback
2312  *      -R      Delete any snapshots and their clones
2313  *      -f      ignored for backwards compatability
2314  *
2315  * Given a filesystem, rollback to a specific snapshot, discarding any changes
2316  * since then and making it the active dataset.  If more recent snapshots exist,
2317  * the command will complain unless the '-r' flag is given.
2318  */
2319 typedef struct rollback_cbdata {
2320         uint64_t        cb_create;
2321         boolean_t       cb_first;
2322         int             cb_doclones;
2323         char            *cb_target;
2324         int             cb_error;
2325         boolean_t       cb_recurse;
2326         boolean_t       cb_dependent;
2327 } rollback_cbdata_t;
2328
2329 /*
2330  * Report any snapshots more recent than the one specified.  Used when '-r' is
2331  * not specified.  We reuse this same callback for the snapshot dependents - if
2332  * 'cb_dependent' is set, then this is a dependent and we should report it
2333  * without checking the transaction group.
2334  */
2335 static int
2336 rollback_check(zfs_handle_t *zhp, void *data)
2337 {
2338         rollback_cbdata_t *cbp = data;
2339
2340         if (cbp->cb_doclones) {
2341                 zfs_close(zhp);
2342                 return (0);
2343         }
2344
2345         if (!cbp->cb_dependent) {
2346                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
2347                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2348                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
2349                     cbp->cb_create) {
2350
2351                         if (cbp->cb_first && !cbp->cb_recurse) {
2352                                 (void) fprintf(stderr, gettext("cannot "
2353                                     "rollback to '%s': more recent snapshots "
2354                                     "exist\n"),
2355                                     cbp->cb_target);
2356                                 (void) fprintf(stderr, gettext("use '-r' to "
2357                                     "force deletion of the following "
2358                                     "snapshots:\n"));
2359                                 cbp->cb_first = 0;
2360                                 cbp->cb_error = 1;
2361                         }
2362
2363                         if (cbp->cb_recurse) {
2364                                 cbp->cb_dependent = B_TRUE;
2365                                 if (zfs_iter_dependents(zhp, B_TRUE,
2366                                     rollback_check, cbp) != 0) {
2367                                         zfs_close(zhp);
2368                                         return (-1);
2369                                 }
2370                                 cbp->cb_dependent = B_FALSE;
2371                         } else {
2372                                 (void) fprintf(stderr, "%s\n",
2373                                     zfs_get_name(zhp));
2374                         }
2375                 }
2376         } else {
2377                 if (cbp->cb_first && cbp->cb_recurse) {
2378                         (void) fprintf(stderr, gettext("cannot rollback to "
2379                             "'%s': clones of previous snapshots exist\n"),
2380                             cbp->cb_target);
2381                         (void) fprintf(stderr, gettext("use '-R' to "
2382                             "force deletion of the following clones and "
2383                             "dependents:\n"));
2384                         cbp->cb_first = 0;
2385                         cbp->cb_error = 1;
2386                 }
2387
2388                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2389         }
2390
2391         zfs_close(zhp);
2392         return (0);
2393 }
2394
2395 static int
2396 zfs_do_rollback(int argc, char **argv)
2397 {
2398         int ret;
2399         int c;
2400         boolean_t force = B_FALSE;
2401         rollback_cbdata_t cb = { 0 };
2402         zfs_handle_t *zhp, *snap;
2403         char parentname[ZFS_MAXNAMELEN];
2404         char *delim;
2405
2406         /* check options */
2407         while ((c = getopt(argc, argv, "rRf")) != -1) {
2408                 switch (c) {
2409                 case 'r':
2410                         cb.cb_recurse = 1;
2411                         break;
2412                 case 'R':
2413                         cb.cb_recurse = 1;
2414                         cb.cb_doclones = 1;
2415                         break;
2416                 case 'f':
2417                         force = B_TRUE;
2418                         break;
2419                 case '?':
2420                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2421                             optopt);
2422                         usage(B_FALSE);
2423                 }
2424         }
2425
2426         argc -= optind;
2427         argv += optind;
2428
2429         /* check number of arguments */
2430         if (argc < 1) {
2431                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2432                 usage(B_FALSE);
2433         }
2434         if (argc > 1) {
2435                 (void) fprintf(stderr, gettext("too many arguments\n"));
2436                 usage(B_FALSE);
2437         }
2438
2439         /* open the snapshot */
2440         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2441                 return (1);
2442
2443         /* open the parent dataset */
2444         (void) strlcpy(parentname, argv[0], sizeof (parentname));
2445         verify((delim = strrchr(parentname, '@')) != NULL);
2446         *delim = '\0';
2447         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2448                 zfs_close(snap);
2449                 return (1);
2450         }
2451
2452         /*
2453          * Check for more recent snapshots and/or clones based on the presence
2454          * of '-r' and '-R'.
2455          */
2456         cb.cb_target = argv[0];
2457         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2458         cb.cb_first = B_TRUE;
2459         cb.cb_error = 0;
2460         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2461                 goto out;
2462
2463         if ((ret = cb.cb_error) != 0)
2464                 goto out;
2465
2466         /*
2467          * Rollback parent to the given snapshot.
2468          */
2469         ret = zfs_rollback(zhp, snap, force);
2470
2471 out:
2472         zfs_close(snap);
2473         zfs_close(zhp);
2474
2475         if (ret == 0)
2476                 return (0);
2477         else
2478                 return (1);
2479 }
2480
2481 /*
2482  * zfs set property=value { fs | snap | vol } ...
2483  *
2484  * Sets the given property for all datasets specified on the command line.
2485  */
2486 typedef struct set_cbdata {
2487         char            *cb_propname;
2488         char            *cb_value;
2489 } set_cbdata_t;
2490
2491 static int
2492 set_callback(zfs_handle_t *zhp, void *data)
2493 {
2494         set_cbdata_t *cbp = data;
2495
2496         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2497                 switch (libzfs_errno(g_zfs)) {
2498                 case EZFS_MOUNTFAILED:
2499                         (void) fprintf(stderr, gettext("property may be set "
2500                             "but unable to remount filesystem\n"));
2501                         break;
2502                 case EZFS_SHARENFSFAILED:
2503                         (void) fprintf(stderr, gettext("property may be set "
2504                             "but unable to reshare filesystem\n"));
2505                         break;
2506                 }
2507                 return (1);
2508         }
2509         return (0);
2510 }
2511
2512 static int
2513 zfs_do_set(int argc, char **argv)
2514 {
2515         set_cbdata_t cb;
2516         int ret;
2517
2518         /* check for options */
2519         if (argc > 1 && argv[1][0] == '-') {
2520                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2521                     argv[1][1]);
2522                 usage(B_FALSE);
2523         }
2524
2525         /* check number of arguments */
2526         if (argc < 2) {
2527                 (void) fprintf(stderr, gettext("missing property=value "
2528                     "argument\n"));
2529                 usage(B_FALSE);
2530         }
2531         if (argc < 3) {
2532                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2533                 usage(B_FALSE);
2534         }
2535
2536         /* validate property=value argument */
2537         cb.cb_propname = argv[1];
2538         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
2539             (cb.cb_value[1] == '\0')) {
2540                 (void) fprintf(stderr, gettext("missing value in "
2541                     "property=value argument\n"));
2542                 usage(B_FALSE);
2543         }
2544
2545         *cb.cb_value = '\0';
2546         cb.cb_value++;
2547
2548         if (*cb.cb_propname == '\0') {
2549                 (void) fprintf(stderr,
2550                     gettext("missing property in property=value argument\n"));
2551                 usage(B_FALSE);
2552         }
2553
2554         ret = zfs_for_each(argc - 2, argv + 2, 0,
2555             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
2556
2557         return (ret);
2558 }
2559
2560 /*
2561  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
2562  *
2563  * Creates a snapshot with the given name.  While functionally equivalent to
2564  * 'zfs create', it is a separate command to differentiate intent.
2565  */
2566 static int
2567 zfs_do_snapshot(int argc, char **argv)
2568 {
2569         boolean_t recursive = B_FALSE;
2570         int ret;
2571         signed char c;
2572         nvlist_t *props;
2573
2574         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2575                 nomem();
2576
2577         /* check options */
2578         while ((c = getopt(argc, argv, "ro:")) != -1) {
2579                 switch (c) {
2580                 case 'o':
2581                         if (parseprop(props))
2582                                 return (1);
2583                         break;
2584                 case 'r':
2585                         recursive = B_TRUE;
2586                         break;
2587                 case '?':
2588                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2589                             optopt);
2590                         goto usage;
2591                 }
2592         }
2593
2594         argc -= optind;
2595         argv += optind;
2596
2597         /* check number of arguments */
2598         if (argc < 1) {
2599                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2600                 goto usage;
2601         }
2602         if (argc > 1) {
2603                 (void) fprintf(stderr, gettext("too many arguments\n"));
2604                 goto usage;
2605         }
2606
2607         ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
2608         nvlist_free(props);
2609         if (ret && recursive)
2610                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
2611         return (ret != 0);
2612
2613 usage:
2614         nvlist_free(props);
2615         usage(B_FALSE);
2616         return (-1);
2617 }
2618
2619 /*
2620  * zfs send [-vDp] -R [-i|-I <@snap>] <fs@snap>
2621  * zfs send [-vDp] [-i|-I <@snap>] <fs@snap>
2622  *
2623  * Send a backup stream to stdout.
2624  */
2625 static int
2626 zfs_do_send(int argc, char **argv)
2627 {
2628         char *fromname = NULL;
2629         char *toname = NULL;
2630         char *cp;
2631         zfs_handle_t *zhp;
2632         sendflags_t flags = { 0 };
2633         int c, err;
2634         nvlist_t *dbgnv;
2635         boolean_t extraverbose = B_FALSE;
2636
2637         /* check options */
2638         while ((c = getopt(argc, argv, ":i:I:RDpv")) != -1) {
2639                 switch (c) {
2640                 case 'i':
2641                         if (fromname)
2642                                 usage(B_FALSE);
2643                         fromname = optarg;
2644                         break;
2645                 case 'I':
2646                         if (fromname)
2647                                 usage(B_FALSE);
2648                         fromname = optarg;
2649                         flags.doall = B_TRUE;
2650                         break;
2651                 case 'R':
2652                         flags.replicate = B_TRUE;
2653                         break;
2654                 case 'p':
2655                         flags.props = B_TRUE;
2656                         break;
2657                 case 'v':
2658                         if (flags.verbose)
2659                                 extraverbose = B_TRUE;
2660                         flags.verbose = B_TRUE;
2661                         break;
2662                 case 'D':
2663                         flags.dedup = B_TRUE;
2664                         break;
2665                 case ':':
2666                         (void) fprintf(stderr, gettext("missing argument for "
2667                             "'%c' option\n"), optopt);
2668                         usage(B_FALSE);
2669                         break;
2670                 case '?':
2671                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2672                             optopt);
2673                         usage(B_FALSE);
2674                 }
2675         }
2676
2677         argc -= optind;
2678         argv += optind;
2679
2680         /* check number of arguments */
2681         if (argc < 1) {
2682                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2683                 usage(B_FALSE);
2684         }
2685         if (argc > 1) {
2686                 (void) fprintf(stderr, gettext("too many arguments\n"));
2687                 usage(B_FALSE);
2688         }
2689
2690         if (isatty(STDOUT_FILENO)) {
2691                 (void) fprintf(stderr,
2692                     gettext("Error: Stream can not be written to a terminal.\n"
2693                     "You must redirect standard output.\n"));
2694                 return (1);
2695         }
2696
2697         cp = strchr(argv[0], '@');
2698         if (cp == NULL) {
2699                 (void) fprintf(stderr,
2700                     gettext("argument must be a snapshot\n"));
2701                 usage(B_FALSE);
2702         }
2703         *cp = '\0';
2704         toname = cp + 1;
2705         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2706         if (zhp == NULL)
2707                 return (1);
2708
2709         /*
2710          * If they specified the full path to the snapshot, chop off
2711          * everything except the short name of the snapshot, but special
2712          * case if they specify the origin.
2713          */
2714         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2715                 char origin[ZFS_MAXNAMELEN];
2716                 zprop_source_t src;
2717
2718                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2719                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2720
2721                 if (strcmp(origin, fromname) == 0) {
2722                         fromname = NULL;
2723                         flags.fromorigin = B_TRUE;
2724                 } else {
2725                         *cp = '\0';
2726                         if (cp != fromname && strcmp(argv[0], fromname)) {
2727                                 (void) fprintf(stderr,
2728                                     gettext("incremental source must be "
2729                                     "in same filesystem\n"));
2730                                 usage(B_FALSE);
2731                         }
2732                         fromname = cp + 1;
2733                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
2734                                 (void) fprintf(stderr,
2735                                     gettext("invalid incremental source\n"));
2736                                 usage(B_FALSE);
2737                         }
2738                 }
2739         }
2740
2741         if (flags.replicate && fromname == NULL)
2742                 flags.doall = B_TRUE;
2743
2744         err = zfs_send(zhp, fromname, toname, flags, STDOUT_FILENO, NULL, 0,
2745             extraverbose ? &dbgnv : NULL);
2746
2747         if (extraverbose) {
2748                 /*
2749                  * dump_nvlist prints to stdout, but that's been
2750                  * redirected to a file.  Make it print to stderr
2751                  * instead.
2752                  */
2753                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
2754                 dump_nvlist(dbgnv, 0);
2755                 nvlist_free(dbgnv);
2756         }
2757         zfs_close(zhp);
2758
2759         return (err != 0);
2760 }
2761
2762 /*
2763  * zfs receive [-vnFu] [-d | -e] <fs@snap>
2764  *
2765  * Restore a backup stream from stdin.
2766  */
2767 static int
2768 zfs_do_receive(int argc, char **argv)
2769 {
2770         int c, err;
2771         recvflags_t flags = { 0 };
2772
2773         /* check options */
2774         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
2775                 switch (c) {
2776                 case 'd':
2777                         flags.isprefix = B_TRUE;
2778                         break;
2779                 case 'e':
2780                         flags.isprefix = B_TRUE;
2781                         flags.istail = B_TRUE;
2782                         break;
2783                 case 'n':
2784                         flags.dryrun = B_TRUE;
2785                         break;
2786                 case 'u':
2787                         flags.nomount = B_TRUE;
2788                         break;
2789                 case 'v':
2790                         flags.verbose = B_TRUE;
2791                         break;
2792                 case 'F':
2793                         flags.force = B_TRUE;
2794                         break;
2795                 case ':':
2796                         (void) fprintf(stderr, gettext("missing argument for "
2797                             "'%c' option\n"), optopt);
2798                         usage(B_FALSE);
2799                         break;
2800                 case '?':
2801                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2802                             optopt);
2803                         usage(B_FALSE);
2804                 }
2805         }
2806
2807         argc -= optind;
2808         argv += optind;
2809
2810         /* check number of arguments */
2811         if (argc < 1) {
2812                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2813                 usage(B_FALSE);
2814         }
2815         if (argc > 1) {
2816                 (void) fprintf(stderr, gettext("too many arguments\n"));
2817                 usage(B_FALSE);
2818         }
2819
2820         if (isatty(STDIN_FILENO)) {
2821                 (void) fprintf(stderr,
2822                     gettext("Error: Backup stream can not be read "
2823                     "from a terminal.\n"
2824                     "You must redirect standard input.\n"));
2825                 return (1);
2826         }
2827
2828         err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2829
2830         return (err != 0);
2831 }
2832
2833 static int
2834 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
2835 {
2836         int errors = 0;
2837         int i;
2838         const char *tag;
2839         boolean_t recursive = B_FALSE;
2840         boolean_t temphold = B_FALSE;
2841         const char *opts = holding ? "rt" : "r";
2842         int c;
2843
2844         /* check options */
2845         while ((c = getopt(argc, argv, opts)) != -1) {
2846                 switch (c) {
2847                 case 'r':
2848                         recursive = B_TRUE;
2849                         break;
2850                 case 't':
2851                         temphold = B_TRUE;
2852                         break;
2853                 case '?':
2854                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2855                             optopt);
2856                         usage(B_FALSE);
2857                 }
2858         }
2859
2860         argc -= optind;
2861         argv += optind;
2862
2863         /* check number of arguments */
2864         if (argc < 2)
2865                 usage(B_FALSE);
2866
2867         tag = argv[0];
2868         --argc;
2869         ++argv;
2870
2871         if (holding && tag[0] == '.') {
2872                 /* tags starting with '.' are reserved for libzfs */
2873                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
2874                 usage(B_FALSE);
2875         }
2876
2877         for (i = 0; i < argc; ++i) {
2878                 zfs_handle_t *zhp;
2879                 char parent[ZFS_MAXNAMELEN];
2880                 const char *delim;
2881                 char *path = argv[i];
2882
2883                 delim = strchr(path, '@');
2884                 if (delim == NULL) {
2885                         (void) fprintf(stderr,
2886                             gettext("'%s' is not a snapshot\n"), path);
2887                         ++errors;
2888                         continue;
2889                 }
2890                 (void) strncpy(parent, path, delim - path);
2891                 parent[delim - path] = '\0';
2892
2893                 zhp = zfs_open(g_zfs, parent,
2894                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2895                 if (zhp == NULL) {
2896                         ++errors;
2897                         continue;
2898                 }
2899                 if (holding) {
2900                         if (zfs_hold(zhp, delim+1, tag, recursive,
2901                             temphold, B_FALSE, -1, 0, 0) != 0)
2902                                 ++errors;
2903                 } else {
2904                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
2905                                 ++errors;
2906                 }
2907                 zfs_close(zhp);
2908         }
2909
2910         return (errors != 0);
2911 }
2912
2913 /*
2914  * zfs hold [-r] [-t] <tag> <snap> ...
2915  *
2916  *      -r      Recursively hold
2917  *      -t      Temporary hold (hidden option)
2918  *
2919  * Apply a user-hold with the given tag to the list of snapshots.
2920  */
2921 static int
2922 zfs_do_hold(int argc, char **argv)
2923 {
2924         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
2925 }
2926
2927 /*
2928  * zfs release [-r] <tag> <snap> ...
2929  *
2930  *      -r      Recursively release
2931  *
2932  * Release a user-hold with the given tag from the list of snapshots.
2933  */
2934 static int
2935 zfs_do_release(int argc, char **argv)
2936 {
2937         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
2938 }
2939
2940 #define CHECK_SPINNER 30
2941 #define SPINNER_TIME 3          /* seconds */
2942 #define MOUNT_TIME 5            /* seconds */
2943
2944 static int
2945 get_one_dataset(zfs_handle_t *zhp, void *data)
2946 {
2947         static char *spin[] = { "-", "\\", "|", "/" };
2948         static int spinval = 0;
2949         static int spincheck = 0;
2950         static time_t last_spin_time = (time_t)0;
2951         get_all_cb_t *cbp = data;
2952         zfs_type_t type = zfs_get_type(zhp);
2953
2954         if (cbp->cb_verbose) {
2955                 if (--spincheck < 0) {
2956                         time_t now = time(NULL);
2957                         if (last_spin_time + SPINNER_TIME < now) {
2958                                 update_progress(spin[spinval++ % 4]);
2959                                 last_spin_time = now;
2960                         }
2961                         spincheck = CHECK_SPINNER;
2962                 }
2963         }
2964
2965         /*
2966          * Interate over any nested datasets.
2967          */
2968         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2969                 zfs_close(zhp);
2970                 return (1);
2971         }
2972
2973         /*
2974          * Skip any datasets whose type does not match.
2975          */
2976         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
2977                 zfs_close(zhp);
2978                 return (0);
2979         }
2980         libzfs_add_handle(cbp, zhp);
2981         assert(cbp->cb_used <= cbp->cb_alloc);
2982
2983         return (0);
2984 }
2985
2986 static void
2987 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
2988 {
2989         get_all_cb_t cb = { 0 };
2990         cb.cb_verbose = verbose;
2991         cb.cb_getone = get_one_dataset;
2992
2993         if (verbose)
2994                 set_progress_header(gettext("Reading ZFS config"));
2995         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2996
2997         *dslist = cb.cb_handles;
2998         *count = cb.cb_used;
2999
3000         if (verbose)
3001                 finish_progress(gettext("done."));
3002 }
3003
3004 /*
3005  * Generic callback for sharing or mounting filesystems.  Because the code is so
3006  * similar, we have a common function with an extra parameter to determine which
3007  * mode we are using.
3008  */
3009 #define OP_SHARE        0x1
3010 #define OP_MOUNT        0x2
3011
3012 /*
3013  * Share or mount a dataset.
3014  */
3015 static int
3016 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3017     boolean_t explicit, const char *options)
3018 {
3019         char mountpoint[ZFS_MAXPROPLEN];
3020         char shareopts[ZFS_MAXPROPLEN];
3021         char smbshareopts[ZFS_MAXPROPLEN];
3022         const char *cmdname = op == OP_SHARE ? "share" : "mount";
3023         struct mnttab mnt;
3024         uint64_t zoned, canmount;
3025         boolean_t shared_nfs, shared_smb;
3026
3027         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
3028
3029         /*
3030          * Check to make sure we can mount/share this dataset.  If we
3031          * are in the global zone and the filesystem is exported to a
3032          * local zone, or if we are in a local zone and the
3033          * filesystem is not exported, then it is an error.
3034          */
3035         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3036
3037         if (zoned && getzoneid() == GLOBAL_ZONEID) {
3038                 if (!explicit)
3039                         return (0);
3040
3041                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3042                     "dataset is exported to a local zone\n"), cmdname,
3043                     zfs_get_name(zhp));
3044                 return (1);
3045
3046         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3047                 if (!explicit)
3048                         return (0);
3049
3050                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3051                     "permission denied\n"), cmdname,
3052                     zfs_get_name(zhp));
3053                 return (1);
3054         }
3055
3056         /*
3057          * Ignore any filesystems which don't apply to us. This
3058          * includes those with a legacy mountpoint, or those with
3059          * legacy share options.
3060          */
3061         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3062             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3063         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3064             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3065         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3066             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3067
3068         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3069             strcmp(smbshareopts, "off") == 0) {
3070                 if (!explicit)
3071                         return (0);
3072
3073                 (void) fprintf(stderr, gettext("cannot share '%s': "
3074                     "legacy share\n"), zfs_get_name(zhp));
3075                 (void) fprintf(stderr, gettext("use share(1M) to "
3076                     "share this filesystem, or set "
3077                     "sharenfs property on\n"));
3078                 return (1);
3079         }
3080
3081         /*
3082          * We cannot share or mount legacy filesystems. If the
3083          * shareopts is non-legacy but the mountpoint is legacy, we
3084          * treat it as a legacy share.
3085          */
3086         if (strcmp(mountpoint, "legacy") == 0) {
3087                 if (!explicit)
3088                         return (0);
3089
3090                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3091                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3092                 (void) fprintf(stderr, gettext("use %s(1M) to "
3093                     "%s this filesystem\n"), cmdname, cmdname);
3094                 return (1);
3095         }
3096
3097         if (strcmp(mountpoint, "none") == 0) {
3098                 if (!explicit)
3099                         return (0);
3100
3101                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
3102                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3103                 return (1);
3104         }
3105
3106         /*
3107          * canmount     explicit        outcome
3108          * on           no              pass through
3109          * on           yes             pass through
3110          * off          no              return 0
3111          * off          yes             display error, return 1
3112          * noauto       no              return 0
3113          * noauto       yes             pass through
3114          */
3115         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3116         if (canmount == ZFS_CANMOUNT_OFF) {
3117                 if (!explicit)
3118                         return (0);
3119
3120                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3121                     "'canmount' property is set to 'off'\n"), cmdname,
3122                     zfs_get_name(zhp));
3123                 return (1);
3124         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3125                 return (0);
3126         }
3127
3128         /*
3129          * At this point, we have verified that the mountpoint and/or
3130          * shareopts are appropriate for auto management. If the
3131          * filesystem is already mounted or shared, return (failing
3132          * for explicit requests); otherwise mount or share the
3133          * filesystem.
3134          */
3135         switch (op) {
3136         case OP_SHARE:
3137
3138                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3139                 shared_smb = zfs_is_shared_smb(zhp, NULL);
3140
3141                 if ((shared_nfs && shared_smb) ||
3142                     ((shared_nfs && strcmp(shareopts, "on") == 0) &&
3143                     (strcmp(smbshareopts, "off") == 0)) ||
3144                     ((shared_smb && strcmp(smbshareopts, "on") == 0) &&
3145                     (strcmp(shareopts, "off") == 0))) {
3146                         if (!explicit)
3147                                 return (0);
3148
3149                         (void) fprintf(stderr, gettext("cannot share "
3150                             "'%s': filesystem already shared\n"),
3151                             zfs_get_name(zhp));
3152                         return (1);
3153                 }
3154
3155                 if (!zfs_is_mounted(zhp, NULL) &&
3156                     zfs_mount(zhp, NULL, 0) != 0)
3157                         return (1);
3158
3159                 if (protocol == NULL) {
3160                         if (zfs_shareall(zhp) != 0)
3161                                 return (1);
3162                 } else if (strcmp(protocol, "nfs") == 0) {
3163                         if (zfs_share_nfs(zhp))
3164                                 return (1);
3165                 } else if (strcmp(protocol, "smb") == 0) {
3166                         if (zfs_share_smb(zhp))
3167                                 return (1);
3168                 } else {
3169                         (void) fprintf(stderr, gettext("cannot share "
3170                             "'%s': invalid share type '%s' "
3171                             "specified\n"),
3172                             zfs_get_name(zhp), protocol);
3173                         return (1);
3174                 }
3175
3176                 break;
3177
3178         case OP_MOUNT:
3179                 if (options == NULL)
3180                         mnt.mnt_mntopts = "";
3181                 else
3182                         mnt.mnt_mntopts = (char *)options;
3183
3184                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3185                     zfs_is_mounted(zhp, NULL)) {
3186                         if (!explicit)
3187                                 return (0);
3188
3189                         (void) fprintf(stderr, gettext("cannot mount "
3190                             "'%s': filesystem already mounted\n"),
3191                             zfs_get_name(zhp));
3192                         return (1);
3193                 }
3194
3195                 if (zfs_mount(zhp, options, flags) != 0)
3196                         return (1);
3197                 break;
3198         }
3199
3200         return (0);
3201 }
3202
3203 /*
3204  * Reports progress in the form "(current/total)".  Not thread-safe.
3205  */
3206 static void
3207 report_mount_progress(int current, int total)
3208 {
3209         static time_t last_progress_time = 0;
3210         time_t now = time(NULL);
3211         char info[32];
3212
3213         /* report 1..n instead of 0..n-1 */
3214         ++current;
3215
3216         /* display header if we're here for the first time */
3217         if (current == 1) {
3218                 set_progress_header(gettext("Mounting ZFS filesystems"));
3219         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3220                 /* too soon to report again */
3221                 return;
3222         }
3223
3224         last_progress_time = now;
3225
3226         (void) sprintf(info, "(%d/%d)", current, total);
3227
3228         if (current == total)
3229                 finish_progress(info);
3230         else
3231                 update_progress(info);
3232 }
3233
3234 static void
3235 append_options(char *mntopts, char *newopts)
3236 {
3237         int len = strlen(mntopts);
3238
3239         /* original length plus new string to append plus 1 for the comma */
3240         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3241                 (void) fprintf(stderr, gettext("the opts argument for "
3242                     "'%s' option is too long (more than %d chars)\n"),
3243                     "-o", MNT_LINE_MAX);
3244                 usage(B_FALSE);
3245         }
3246
3247         if (*mntopts)
3248                 mntopts[len++] = ',';
3249
3250         (void) strcpy(&mntopts[len], newopts);
3251 }
3252
3253 static int
3254 share_mount(int op, int argc, char **argv)
3255 {
3256         int do_all = 0;
3257         boolean_t verbose = B_FALSE;
3258         int c, ret = 0;
3259         char *options = NULL;
3260         int flags = 0;
3261
3262         /* check options */
3263         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:" : "a"))
3264             != -1) {
3265                 switch (c) {
3266                 case 'a':
3267                         do_all = 1;
3268                         break;
3269                 case 'v':
3270                         verbose = B_TRUE;
3271                         break;
3272                 case 'o':
3273                         if (*optarg == '\0') {
3274                                 (void) fprintf(stderr, gettext("empty mount "
3275                                     "options (-o) specified\n"));
3276                                 usage(B_FALSE);
3277                         }
3278
3279                         if (options == NULL)
3280                                 options = safe_malloc(MNT_LINE_MAX + 1);
3281
3282                         /* option validation is done later */
3283                         append_options(options, optarg);
3284                         break;
3285
3286                 case ':':
3287                         (void) fprintf(stderr, gettext("missing argument for "
3288                             "'%c' option\n"), optopt);
3289                         usage(B_FALSE);
3290                         break;
3291                 case '?':
3292                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3293                             optopt);
3294                         usage(B_FALSE);
3295                 }
3296         }
3297
3298         argc -= optind;
3299         argv += optind;
3300
3301         /* check number of arguments */
3302         if (do_all) {
3303                 zfs_handle_t **dslist = NULL;
3304                 size_t i, count = 0;
3305                 char *protocol = NULL;
3306
3307                 if (op == OP_SHARE && argc > 0) {
3308                         if (strcmp(argv[0], "nfs") != 0 &&
3309                             strcmp(argv[0], "smb") != 0) {
3310                                 (void) fprintf(stderr, gettext("share type "
3311                                     "must be 'nfs' or 'smb'\n"));
3312                                 usage(B_FALSE);
3313                         }
3314                         protocol = argv[0];
3315                         argc--;
3316                         argv++;
3317                 }
3318
3319                 if (argc != 0) {
3320                         (void) fprintf(stderr, gettext("too many arguments\n"));
3321                         usage(B_FALSE);
3322                 }
3323
3324                 start_progress_timer();
3325                 get_all_datasets(&dslist, &count, verbose);
3326
3327                 if (count == 0)
3328                         return (0);
3329
3330                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
3331
3332                 for (i = 0; i < count; i++) {
3333                         if (verbose)
3334                                 report_mount_progress(i, count);
3335
3336                         if (share_mount_one(dslist[i], op, flags, protocol,
3337                             B_FALSE, options) != 0)
3338                                 ret = 1;
3339                         zfs_close(dslist[i]);
3340                 }
3341
3342                 free(dslist);
3343         } else if (argc == 0) {
3344                 struct mnttab entry;
3345
3346                 if ((op == OP_SHARE) || (options != NULL)) {
3347                         (void) fprintf(stderr, gettext("missing filesystem "
3348                             "argument (specify -a for all)\n"));
3349                         usage(B_FALSE);
3350                 }
3351
3352                 /*
3353                  * When mount is given no arguments, go through /etc/mtab and
3354                  * display any active ZFS mounts.  We hide any snapshots, since
3355                  * they are controlled automatically.
3356                  */
3357                 rewind(mnttab_file);
3358                 while (getmntent(mnttab_file, &entry) == 0) {
3359                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3360                             strchr(entry.mnt_special, '@') != NULL)
3361                                 continue;
3362
3363                         (void) printf("%-30s  %s\n", entry.mnt_special,
3364                             entry.mnt_mountp);
3365                 }
3366
3367         } else {
3368                 zfs_handle_t *zhp;
3369
3370                 if (argc > 1) {
3371                         (void) fprintf(stderr,
3372                             gettext("too many arguments\n"));
3373                         usage(B_FALSE);
3374                 }
3375
3376                 if ((zhp = zfs_open(g_zfs, argv[0],
3377                     ZFS_TYPE_FILESYSTEM)) == NULL) {
3378                         ret = 1;
3379                 } else {
3380                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3381                             options);
3382                         zfs_close(zhp);
3383                 }
3384         }
3385
3386         return (ret);
3387 }
3388
3389 /*
3390  * zfs mount -a [nfs]
3391  * zfs mount filesystem
3392  *
3393  * Mount all filesystems, or mount the given filesystem.
3394  */
3395 static int
3396 zfs_do_mount(int argc, char **argv)
3397 {
3398         return (share_mount(OP_MOUNT, argc, argv));
3399 }
3400
3401 /*
3402  * zfs share -a [nfs | smb]
3403  * zfs share filesystem
3404  *
3405  * Share all filesystems, or share the given filesystem.
3406  */
3407 static int
3408 zfs_do_share(int argc, char **argv)
3409 {
3410         return (share_mount(OP_SHARE, argc, argv));
3411 }
3412
3413 typedef struct unshare_unmount_node {
3414         zfs_handle_t    *un_zhp;
3415         char            *un_mountp;
3416         uu_avl_node_t   un_avlnode;
3417 } unshare_unmount_node_t;
3418
3419 /* ARGSUSED */
3420 static int
3421 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3422 {
3423         const unshare_unmount_node_t *l = larg;
3424         const unshare_unmount_node_t *r = rarg;
3425
3426         return (strcmp(l->un_mountp, r->un_mountp));
3427 }
3428
3429 /*
3430  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3431  * absolute path, find the entry /etc/mtab, verify that its a ZFS filesystem,
3432  * and unmount it appropriately.
3433  */
3434 static int
3435 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3436 {
3437         zfs_handle_t *zhp;
3438         int ret;
3439         struct stat64 statbuf;
3440         struct extmnttab entry;
3441         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3442         ino_t path_inode;
3443
3444         /*
3445          * Search for the path in /etc/mtab.  Rather than looking for the
3446          * specific path, which can be fooled by non-standard paths (i.e. ".."
3447          * or "//"), we stat() the path and search for the corresponding
3448          * (major,minor) device pair.
3449          */
3450         if (stat64(path, &statbuf) != 0) {
3451                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3452                     cmdname, path, strerror(errno));
3453                 return (1);
3454         }
3455         path_inode = statbuf.st_ino;
3456
3457         /*
3458          * Search for the given (major,minor) pair in the mount table.
3459          */
3460         rewind(mnttab_file);
3461         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3462                 if (entry.mnt_major == major(statbuf.st_dev) &&
3463                     entry.mnt_minor == minor(statbuf.st_dev))
3464                         break;
3465         }
3466         if (ret != 0) {
3467                 if (op == OP_SHARE) {
3468                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
3469                             "currently mounted\n"), cmdname, path);
3470                         return (1);
3471                 }
3472                 (void) fprintf(stderr, gettext("warning: %s not in mtab\n"),
3473                     path);
3474                 if ((ret = umount2(path, flags)) != 0)
3475                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
3476                             strerror(errno));
3477                 return (ret != 0);
3478         }
3479
3480         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3481                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3482                     "filesystem\n"), cmdname, path);
3483                 return (1);
3484         }
3485
3486         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3487             ZFS_TYPE_FILESYSTEM)) == NULL)
3488                 return (1);
3489
3490         ret = 1;
3491         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3492                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3493                     cmdname, path, strerror(errno));
3494                 goto out;
3495         } else if (statbuf.st_ino != path_inode) {
3496                 (void) fprintf(stderr, gettext("cannot "
3497                     "%s '%s': not a mountpoint\n"), cmdname, path);
3498                 goto out;
3499         }
3500
3501         if (op == OP_SHARE) {
3502                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
3503                 char smbshare_prop[ZFS_MAXPROPLEN];
3504
3505                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3506                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3507                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3508                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3509
3510                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
3511                     strcmp(smbshare_prop, "off") == 0) {
3512                         (void) fprintf(stderr, gettext("cannot unshare "
3513                             "'%s': legacy share\n"), path);
3514                         (void) fprintf(stderr, gettext("use exportfs(8) "
3515                             "or smbcontrol(1) to unshare this filesystem\n"));
3516                 } else if (!zfs_is_shared(zhp)) {
3517                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
3518                             "not currently shared\n"), path);
3519                 } else {
3520                         ret = zfs_unshareall_bypath(zhp, path);
3521                 }
3522         } else {
3523                 char mtpt_prop[ZFS_MAXPROPLEN];
3524
3525                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3526                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3527
3528                 if (is_manual) {
3529                         ret = zfs_unmount(zhp, NULL, flags);
3530                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
3531                         (void) fprintf(stderr, gettext("cannot unmount "
3532                             "'%s': legacy mountpoint\n"),
3533                             zfs_get_name(zhp));
3534                         (void) fprintf(stderr, gettext("use umount(8) "
3535                             "to unmount this filesystem\n"));
3536                 } else {
3537                         ret = zfs_unmountall(zhp, flags);
3538                 }
3539         }
3540
3541 out:
3542         zfs_close(zhp);
3543
3544         return (ret != 0);
3545 }
3546
3547 /*
3548  * Generic callback for unsharing or unmounting a filesystem.
3549  */
3550 static int
3551 unshare_unmount(int op, int argc, char **argv)
3552 {
3553         int do_all = 0;
3554         int flags = 0;
3555         int ret = 0;
3556         int c;
3557         zfs_handle_t *zhp;
3558         char nfs_mnt_prop[ZFS_MAXPROPLEN];
3559         char sharesmb[ZFS_MAXPROPLEN];
3560
3561         /* check options */
3562         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3563                 switch (c) {
3564                 case 'a':
3565                         do_all = 1;
3566                         break;
3567                 case 'f':
3568                         flags = MS_FORCE;
3569                         break;
3570                 case '?':
3571                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3572                             optopt);
3573                         usage(B_FALSE);
3574                 }
3575         }
3576
3577         argc -= optind;
3578         argv += optind;
3579
3580         if (do_all) {
3581                 /*
3582                  * We could make use of zfs_for_each() to walk all datasets in
3583                  * the system, but this would be very inefficient, especially
3584                  * since we would have to linearly search /etc/mtab for each
3585                  * one.  Instead, do one pass through /etc/mtab looking for
3586                  * zfs entries and call zfs_unmount() for each one.
3587                  *
3588                  * Things get a little tricky if the administrator has created
3589                  * mountpoints beneath other ZFS filesystems.  In this case, we
3590                  * have to unmount the deepest filesystems first.  To accomplish
3591                  * this, we place all the mountpoints in an AVL tree sorted by
3592                  * the special type (dataset name), and walk the result in
3593                  * reverse to make sure to get any snapshots first.
3594                  */
3595                 struct mnttab entry;
3596                 uu_avl_pool_t *pool;
3597                 uu_avl_t *tree = NULL;
3598                 unshare_unmount_node_t *node;
3599                 uu_avl_index_t idx;
3600                 uu_avl_walk_t *walk;
3601
3602                 if (argc != 0) {
3603                         (void) fprintf(stderr, gettext("too many arguments\n"));
3604                         usage(B_FALSE);
3605                 }
3606
3607                 if (((pool = uu_avl_pool_create("unmount_pool",
3608                     sizeof (unshare_unmount_node_t),
3609                     offsetof(unshare_unmount_node_t, un_avlnode),
3610                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
3611                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
3612                         nomem();
3613
3614                 rewind(mnttab_file);
3615                 while (getmntent(mnttab_file, &entry) == 0) {
3616
3617                         /* ignore non-ZFS entries */
3618                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3619                                 continue;
3620
3621                         /* ignore snapshots */
3622                         if (strchr(entry.mnt_special, '@') != NULL)
3623                                 continue;
3624
3625                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3626                             ZFS_TYPE_FILESYSTEM)) == NULL) {
3627                                 ret = 1;
3628                                 continue;
3629                         }
3630
3631                         switch (op) {
3632                         case OP_SHARE:
3633                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3634                                     nfs_mnt_prop,
3635                                     sizeof (nfs_mnt_prop),
3636                                     NULL, NULL, 0, B_FALSE) == 0);
3637                                 if (strcmp(nfs_mnt_prop, "off") != 0)
3638                                         break;
3639                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3640                                     nfs_mnt_prop,
3641                                     sizeof (nfs_mnt_prop),
3642                                     NULL, NULL, 0, B_FALSE) == 0);
3643                                 if (strcmp(nfs_mnt_prop, "off") == 0)
3644                                         continue;
3645                                 break;
3646                         case OP_MOUNT:
3647                                 /* Ignore legacy mounts */
3648                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3649                                     nfs_mnt_prop,
3650                                     sizeof (nfs_mnt_prop),
3651                                     NULL, NULL, 0, B_FALSE) == 0);
3652                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
3653                                         continue;
3654                                 /* Ignore canmount=noauto mounts */
3655                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3656                                     ZFS_CANMOUNT_NOAUTO)
3657                                         continue;
3658                         default:
3659                                 break;
3660                         }
3661
3662                         node = safe_malloc(sizeof (unshare_unmount_node_t));
3663                         node->un_zhp = zhp;
3664                         node->un_mountp = safe_strdup(entry.mnt_mountp);
3665
3666                         uu_avl_node_init(node, &node->un_avlnode, pool);
3667
3668                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3669                                 uu_avl_insert(tree, node, idx);
3670                         } else {
3671                                 zfs_close(node->un_zhp);
3672                                 free(node->un_mountp);
3673                                 free(node);
3674                         }
3675                 }
3676
3677                 /*
3678                  * Walk the AVL tree in reverse, unmounting each filesystem and
3679                  * removing it from the AVL tree in the process.
3680                  */
3681                 if ((walk = uu_avl_walk_start(tree,
3682                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
3683                         nomem();
3684
3685                 while ((node = uu_avl_walk_next(walk)) != NULL) {
3686                         uu_avl_remove(tree, node);
3687
3688                         switch (op) {
3689                         case OP_SHARE:
3690                                 if (zfs_unshareall_bypath(node->un_zhp,
3691                                     node->un_mountp) != 0)
3692                                         ret = 1;
3693                                 break;
3694
3695                         case OP_MOUNT:
3696                                 if (zfs_unmount(node->un_zhp,
3697                                     node->un_mountp, flags) != 0)
3698                                         ret = 1;
3699                                 break;
3700                         }
3701
3702                         zfs_close(node->un_zhp);
3703                         free(node->un_mountp);
3704                         free(node);
3705                 }
3706
3707                 uu_avl_walk_end(walk);
3708                 uu_avl_destroy(tree);
3709                 uu_avl_pool_destroy(pool);
3710
3711         } else {
3712                 if (argc != 1) {
3713                         if (argc == 0)
3714                                 (void) fprintf(stderr,
3715                                     gettext("missing filesystem argument\n"));
3716                         else
3717                                 (void) fprintf(stderr,
3718                                     gettext("too many arguments\n"));
3719                         usage(B_FALSE);
3720                 }
3721
3722                 /*
3723                  * We have an argument, but it may be a full path or a ZFS
3724                  * filesystem.  Pass full paths off to unmount_path() (shared by
3725                  * manual_unmount), otherwise open the filesystem and pass to
3726                  * zfs_unmount().
3727                  */
3728                 if (argv[0][0] == '/')
3729                         return (unshare_unmount_path(op, argv[0],
3730                             flags, B_FALSE));
3731
3732                 if ((zhp = zfs_open(g_zfs, argv[0],
3733                     ZFS_TYPE_FILESYSTEM)) == NULL)
3734                         return (1);
3735
3736                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
3737                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3738                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
3739                     NULL, 0, B_FALSE) == 0);
3740
3741                 switch (op) {
3742                 case OP_SHARE:
3743                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3744                             nfs_mnt_prop,
3745                             sizeof (nfs_mnt_prop),
3746                             NULL, NULL, 0, B_FALSE) == 0);
3747                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3748                             sharesmb, sizeof (sharesmb), NULL, NULL,
3749                             0, B_FALSE) == 0);
3750
3751                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
3752                             strcmp(sharesmb, "off") == 0) {
3753                                 (void) fprintf(stderr, gettext("cannot "
3754                                     "unshare '%s': legacy share\n"),
3755                                     zfs_get_name(zhp));
3756                                 (void) fprintf(stderr, gettext("use "
3757                                     "unshare(1M) to unshare this "
3758                                     "filesystem\n"));
3759                                 ret = 1;
3760                         } else if (!zfs_is_shared(zhp)) {
3761                                 (void) fprintf(stderr, gettext("cannot "
3762                                     "unshare '%s': not currently "
3763                                     "shared\n"), zfs_get_name(zhp));
3764                                 ret = 1;
3765                         } else if (zfs_unshareall(zhp) != 0) {
3766                                 ret = 1;
3767                         }
3768                         break;
3769
3770                 case OP_MOUNT:
3771                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
3772                                 (void) fprintf(stderr, gettext("cannot "
3773                                     "unmount '%s': legacy "
3774                                     "mountpoint\n"), zfs_get_name(zhp));
3775                                 (void) fprintf(stderr, gettext("use "
3776                                     "umount(1M) to unmount this "
3777                                     "filesystem\n"));
3778                                 ret = 1;
3779                         } else if (!zfs_is_mounted(zhp, NULL)) {
3780                                 (void) fprintf(stderr, gettext("cannot "
3781                                     "unmount '%s': not currently "
3782                                     "mounted\n"),
3783                                     zfs_get_name(zhp));
3784                                 ret = 1;
3785                         } else if (zfs_unmountall(zhp, flags) != 0) {
3786                                 ret = 1;
3787                         }
3788                         break;
3789                 }
3790
3791                 zfs_close(zhp);
3792         }
3793
3794         return (ret);
3795 }
3796
3797 /*
3798  * zfs unmount -a
3799  * zfs unmount filesystem
3800  *
3801  * Unmount all filesystems, or a specific ZFS filesystem.
3802  */
3803 static int
3804 zfs_do_unmount(int argc, char **argv)
3805 {
3806         return (unshare_unmount(OP_MOUNT, argc, argv));
3807 }
3808
3809 /*
3810  * zfs unshare -a
3811  * zfs unshare filesystem
3812  *
3813  * Unshare all filesystems, or a specific ZFS filesystem.
3814  */
3815 static int
3816 zfs_do_unshare(int argc, char **argv)
3817 {
3818         return (unshare_unmount(OP_SHARE, argc, argv));
3819 }
3820
3821 /* ARGSUSED */
3822 static int
3823 zfs_do_python(int argc, char **argv)
3824 {
3825         (void) execv(pypath, argv-1);
3826         (void) printf("internal error: %s not found\n", pypath);
3827         return (-1);
3828 }
3829
3830 static int
3831 find_command_idx(char *command, int *idx)
3832 {
3833         int i;
3834
3835         for (i = 0; i < NCOMMAND; i++) {
3836                 if (command_table[i].name == NULL)
3837                         continue;
3838
3839                 if (strcmp(command, command_table[i].name) == 0) {
3840                         *idx = i;
3841                         return (0);
3842                 }
3843         }
3844         return (1);
3845 }
3846
3847 static int
3848 zfs_do_diff(int argc, char **argv)
3849 {
3850         zfs_handle_t *zhp;
3851         int flags = 0;
3852         char *tosnap = NULL;
3853         char *fromsnap = NULL;
3854         char *atp, *copy;
3855         int err;
3856         int c;
3857
3858         while ((c = getopt(argc, argv, "FHt")) != -1) {
3859                 switch (c) {
3860                 case 'F':
3861                         flags |= ZFS_DIFF_CLASSIFY;
3862                         break;
3863                 case 'H':
3864                         flags |= ZFS_DIFF_PARSEABLE;
3865                         break;
3866                 case 't':
3867                         flags |= ZFS_DIFF_TIMESTAMP;
3868                         break;
3869                 default:
3870                         (void) fprintf(stderr,
3871                             gettext("invalid option '%c'\n"), optopt);
3872                         usage(B_FALSE);
3873                 }
3874         }
3875
3876         argc -= optind;
3877         argv += optind;
3878
3879         if (argc < 1) {
3880                 (void) fprintf(stderr,
3881                 gettext("must provide at least one snapshot name\n"));
3882                 usage(B_FALSE);
3883         }
3884
3885         if (argc > 2) {
3886                 (void) fprintf(stderr, gettext("too many arguments\n"));
3887                 usage(B_FALSE);
3888         }
3889
3890         fromsnap = argv[0];
3891         tosnap = (argc == 2) ? argv[1] : NULL;
3892
3893         copy = NULL;
3894         if (*fromsnap != '@')
3895                 copy = strdup(fromsnap);
3896         else if (tosnap)
3897                 copy = strdup(tosnap);
3898         if (copy == NULL)
3899                 usage(B_FALSE);
3900
3901         if ((atp = strchr(copy, '@')))
3902                 *atp = '\0';
3903
3904         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
3905                 return (1);
3906
3907         free(copy);
3908
3909         /*
3910          * Ignore SIGPIPE so that the library can give us
3911          * information on any failure
3912          */
3913         (void) sigignore(SIGPIPE);
3914
3915         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
3916
3917         zfs_close(zhp);
3918
3919         return (err != 0);
3920 }
3921
3922 int
3923 main(int argc, char **argv)
3924 {
3925         int ret;
3926         int i = 0;
3927         char *cmdname;
3928
3929         (void) setlocale(LC_ALL, "");
3930         (void) textdomain(TEXT_DOMAIN);
3931
3932         opterr = 0;
3933
3934         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
3935                 (void) fprintf(stderr, gettext("internal error: unable to "
3936                     "open %s\n"), MNTTAB);
3937                 return (1);
3938         }
3939
3940         /*
3941          * Make sure the user has specified some command.
3942          */
3943         if (argc < 2) {
3944                 (void) fprintf(stderr, gettext("missing command\n"));
3945                 usage(B_FALSE);
3946         }
3947
3948         cmdname = argv[1];
3949
3950         /*
3951          * The 'umount' command is an alias for 'unmount'
3952          */
3953         if (strcmp(cmdname, "umount") == 0)
3954                 cmdname = "unmount";
3955
3956         /*
3957          * The 'recv' command is an alias for 'receive'
3958          */
3959         if (strcmp(cmdname, "recv") == 0)
3960                 cmdname = "receive";
3961
3962         /*
3963          * Special case '-?'
3964          */
3965         if ((strcmp(cmdname, "-?") == 0) ||
3966             (strcmp(cmdname, "--help") == 0))
3967                 usage(B_TRUE);
3968
3969         if ((g_zfs = libzfs_init()) == NULL)
3970                 return (1);
3971
3972         zpool_set_history_str("zfs", argc, argv, history_str);
3973         verify(zpool_stage_history(g_zfs, history_str) == 0);
3974
3975         libzfs_print_on_error(g_zfs, B_TRUE);
3976
3977         /*
3978          * Run the appropriate command.
3979          */
3980         libzfs_mnttab_cache(g_zfs, B_TRUE);
3981         if (find_command_idx(cmdname, &i) == 0) {
3982                 current_command = &command_table[i];
3983                 ret = command_table[i].func(argc - 1, argv + 1);
3984         } else if (strchr(cmdname, '=') != NULL) {
3985                 verify(find_command_idx("set", &i) == 0);
3986                 current_command = &command_table[i];
3987                 ret = command_table[i].func(argc, argv);
3988         } else {
3989                 (void) fprintf(stderr, gettext("unrecognized "
3990                     "command '%s'\n"), cmdname);
3991                 usage(B_FALSE);
3992                 ret = 1;
3993         }
3994         libzfs_mnttab_cache(g_zfs, B_FALSE);
3995         libzfs_fini(g_zfs);
3996
3997         (void) fclose(mnttab_file);
3998
3999         /*
4000          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4001          * for the purposes of running ::findleaks.
4002          */
4003         if (getenv("ZFS_ABORT") != NULL) {
4004                 (void) printf("dumping core by request\n");
4005                 abort();
4006         }
4007
4008         return (ret);
4009 }