Update 'zfs send' documentation
[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 [-vRDp] [-[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         if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
1883                 return (1);
1884
1885         (void) printf("PROP TYPE NAME VALUE\n");
1886
1887         for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
1888                 error = zfs_userspace(zhp, p, userspace_cb, &p);
1889                 if (error)
1890                         break;
1891         }
1892         return (error);
1893 }
1894
1895 /*
1896  * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
1897  *      [-s property [-s property]...] [-S property [-S property]...]
1898  *      <dataset> ...
1899  *
1900  *      -r      Recurse over all children
1901  *      -d      Limit recursion by depth.
1902  *      -H      Scripted mode; elide headers and separate columns by tabs
1903  *      -o      Control which fields to display.
1904  *      -t      Control which object types to display.
1905  *      -s      Specify sort columns, descending order.
1906  *      -S      Specify sort columns, ascending order.
1907  *
1908  * When given no arguments, lists all filesystems in the system.
1909  * Otherwise, list the specified datasets, optionally recursing down them if
1910  * '-r' is specified.
1911  */
1912 typedef struct list_cbdata {
1913         boolean_t       cb_first;
1914         boolean_t       cb_scripted;
1915         zprop_list_t    *cb_proplist;
1916 } list_cbdata_t;
1917
1918 /*
1919  * Given a list of columns to display, output appropriate headers for each one.
1920  */
1921 static void
1922 print_header(zprop_list_t *pl)
1923 {
1924         char headerbuf[ZFS_MAXPROPLEN];
1925         const char *header;
1926         int i;
1927         boolean_t first = B_TRUE;
1928         boolean_t right_justify;
1929
1930         for (; pl != NULL; pl = pl->pl_next) {
1931                 if (!first) {
1932                         (void) printf("  ");
1933                 } else {
1934                         first = B_FALSE;
1935                 }
1936
1937                 right_justify = B_FALSE;
1938                 if (pl->pl_prop != ZPROP_INVAL) {
1939                         header = zfs_prop_column_name(pl->pl_prop);
1940                         right_justify = zfs_prop_align_right(pl->pl_prop);
1941                 } else {
1942                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1943                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
1944                         headerbuf[i] = '\0';
1945                         header = headerbuf;
1946                 }
1947
1948                 if (pl->pl_next == NULL && !right_justify)
1949                         (void) printf("%s", header);
1950                 else if (right_justify)
1951                         (void) printf("%*s", (int)pl->pl_width, header);
1952                 else
1953                         (void) printf("%-*s", (int)pl->pl_width, header);
1954         }
1955
1956         (void) printf("\n");
1957 }
1958
1959 /*
1960  * Given a dataset and a list of fields, print out all the properties according
1961  * to the described layout.
1962  */
1963 static void
1964 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1965 {
1966         boolean_t first = B_TRUE;
1967         char property[ZFS_MAXPROPLEN];
1968         nvlist_t *userprops = zfs_get_user_props(zhp);
1969         nvlist_t *propval;
1970         char *propstr;
1971         boolean_t right_justify;
1972         int width;
1973
1974         for (; pl != NULL; pl = pl->pl_next) {
1975                 if (!first) {
1976                         if (scripted)
1977                                 (void) printf("\t");
1978                         else
1979                                 (void) printf("  ");
1980                 } else {
1981                         first = B_FALSE;
1982                 }
1983
1984                 if (pl->pl_prop != ZPROP_INVAL) {
1985                         if (zfs_prop_get(zhp, pl->pl_prop, property,
1986                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1987                                 propstr = "-";
1988                         else
1989                                 propstr = property;
1990
1991                         right_justify = zfs_prop_align_right(pl->pl_prop);
1992                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1993                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1994                             property, sizeof (property), B_FALSE) != 0)
1995                                 propstr = "-";
1996                         else
1997                                 propstr = property;
1998                         right_justify = B_TRUE;
1999                 } else {
2000                         if (nvlist_lookup_nvlist(userprops,
2001                             pl->pl_user_prop, &propval) != 0)
2002                                 propstr = "-";
2003                         else
2004                                 verify(nvlist_lookup_string(propval,
2005                                     ZPROP_VALUE, &propstr) == 0);
2006                         right_justify = B_FALSE;
2007                 }
2008
2009                 width = pl->pl_width;
2010
2011                 /*
2012                  * If this is being called in scripted mode, or if this is the
2013                  * last column and it is left-justified, don't include a width
2014                  * format specifier.
2015                  */
2016                 if (scripted || (pl->pl_next == NULL && !right_justify))
2017                         (void) printf("%s", propstr);
2018                 else if (right_justify)
2019                         (void) printf("%*s", width, propstr);
2020                 else
2021                         (void) printf("%-*s", width, propstr);
2022         }
2023
2024         (void) printf("\n");
2025 }
2026
2027 /*
2028  * Generic callback function to list a dataset or snapshot.
2029  */
2030 static int
2031 list_callback(zfs_handle_t *zhp, void *data)
2032 {
2033         list_cbdata_t *cbp = data;
2034
2035         if (cbp->cb_first) {
2036                 if (!cbp->cb_scripted)
2037                         print_header(cbp->cb_proplist);
2038                 cbp->cb_first = B_FALSE;
2039         }
2040
2041         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2042
2043         return (0);
2044 }
2045
2046 static int
2047 zfs_do_list(int argc, char **argv)
2048 {
2049         int c;
2050         boolean_t scripted = B_FALSE;
2051         static char default_fields[] =
2052             "name,used,available,referenced,mountpoint";
2053         int types = ZFS_TYPE_DATASET;
2054         boolean_t types_specified = B_FALSE;
2055         char *fields = NULL;
2056         list_cbdata_t cb = { 0 };
2057         char *value;
2058         int limit = 0;
2059         int ret;
2060         zfs_sort_column_t *sortcol = NULL;
2061         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2062
2063         /* check options */
2064         while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2065                 switch (c) {
2066                 case 'o':
2067                         fields = optarg;
2068                         break;
2069                 case 'd':
2070                         limit = parse_depth(optarg, &flags);
2071                         break;
2072                 case 'r':
2073                         flags |= ZFS_ITER_RECURSE;
2074                         break;
2075                 case 'H':
2076                         scripted = B_TRUE;
2077                         break;
2078                 case 's':
2079                         if (zfs_add_sort_column(&sortcol, optarg,
2080                             B_FALSE) != 0) {
2081                                 (void) fprintf(stderr,
2082                                     gettext("invalid property '%s'\n"), optarg);
2083                                 usage(B_FALSE);
2084                         }
2085                         break;
2086                 case 'S':
2087                         if (zfs_add_sort_column(&sortcol, optarg,
2088                             B_TRUE) != 0) {
2089                                 (void) fprintf(stderr,
2090                                     gettext("invalid property '%s'\n"), optarg);
2091                                 usage(B_FALSE);
2092                         }
2093                         break;
2094                 case 't':
2095                         types = 0;
2096                         types_specified = B_TRUE;
2097                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2098                         while (*optarg != '\0') {
2099                                 static char *type_subopts[] = { "filesystem",
2100                                     "volume", "snapshot", "all", NULL };
2101
2102                                 switch (getsubopt(&optarg, type_subopts,
2103                                     &value)) {
2104                                 case 0:
2105                                         types |= ZFS_TYPE_FILESYSTEM;
2106                                         break;
2107                                 case 1:
2108                                         types |= ZFS_TYPE_VOLUME;
2109                                         break;
2110                                 case 2:
2111                                         types |= ZFS_TYPE_SNAPSHOT;
2112                                         break;
2113                                 case 3:
2114                                         types = ZFS_TYPE_DATASET;
2115                                         break;
2116
2117                                 default:
2118                                         (void) fprintf(stderr,
2119                                             gettext("invalid type '%s'\n"),
2120                                             value);
2121                                         usage(B_FALSE);
2122                                 }
2123                         }
2124                         break;
2125                 case ':':
2126                         (void) fprintf(stderr, gettext("missing argument for "
2127                             "'%c' option\n"), optopt);
2128                         usage(B_FALSE);
2129                         break;
2130                 case '?':
2131                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2132                             optopt);
2133                         usage(B_FALSE);
2134                 }
2135         }
2136
2137         argc -= optind;
2138         argv += optind;
2139
2140         if (fields == NULL)
2141                 fields = default_fields;
2142
2143         /*
2144          * If "-o space" and no types were specified, don't display snapshots.
2145          */
2146         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
2147                 types &= ~ZFS_TYPE_SNAPSHOT;
2148
2149         /*
2150          * If the user specifies '-o all', the zprop_get_list() doesn't
2151          * normally include the name of the dataset.  For 'zfs list', we always
2152          * want this property to be first.
2153          */
2154         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2155             != 0)
2156                 usage(B_FALSE);
2157
2158         cb.cb_scripted = scripted;
2159         cb.cb_first = B_TRUE;
2160
2161         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
2162             limit, list_callback, &cb);
2163
2164         zprop_free_list(cb.cb_proplist);
2165         zfs_free_sort_columns(sortcol);
2166
2167         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
2168                 (void) printf(gettext("no datasets available\n"));
2169
2170         return (ret);
2171 }
2172
2173 /*
2174  * zfs rename <fs | snap | vol> <fs | snap | vol>
2175  * zfs rename -p <fs | vol> <fs | vol>
2176  * zfs rename -r <snap> <snap>
2177  *
2178  * Renames the given dataset to another of the same type.
2179  *
2180  * The '-p' flag creates all the non-existing ancestors of the target first.
2181  */
2182 /* ARGSUSED */
2183 static int
2184 zfs_do_rename(int argc, char **argv)
2185 {
2186         zfs_handle_t *zhp;
2187         int c;
2188         int ret;
2189         boolean_t recurse = B_FALSE;
2190         boolean_t parents = B_FALSE;
2191
2192         /* check options */
2193         while ((c = getopt(argc, argv, "pr")) != -1) {
2194                 switch (c) {
2195                 case 'p':
2196                         parents = B_TRUE;
2197                         break;
2198                 case 'r':
2199                         recurse = B_TRUE;
2200                         break;
2201                 case '?':
2202                 default:
2203                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2204                             optopt);
2205                         usage(B_FALSE);
2206                 }
2207         }
2208
2209         argc -= optind;
2210         argv += optind;
2211
2212         /* check number of arguments */
2213         if (argc < 1) {
2214                 (void) fprintf(stderr, gettext("missing source dataset "
2215                     "argument\n"));
2216                 usage(B_FALSE);
2217         }
2218         if (argc < 2) {
2219                 (void) fprintf(stderr, gettext("missing target dataset "
2220                     "argument\n"));
2221                 usage(B_FALSE);
2222         }
2223         if (argc > 2) {
2224                 (void) fprintf(stderr, gettext("too many arguments\n"));
2225                 usage(B_FALSE);
2226         }
2227
2228         if (recurse && parents) {
2229                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
2230                     "exclusive\n"));
2231                 usage(B_FALSE);
2232         }
2233
2234         if (recurse && strchr(argv[0], '@') == 0) {
2235                 (void) fprintf(stderr, gettext("source dataset for recursive "
2236                     "rename must be a snapshot\n"));
2237                 usage(B_FALSE);
2238         }
2239
2240         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
2241             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
2242                 return (1);
2243
2244         /* If we were asked and the name looks good, try to create ancestors. */
2245         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
2246             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
2247                 zfs_close(zhp);
2248                 return (1);
2249         }
2250
2251         ret = (zfs_rename(zhp, argv[1], recurse) != 0);
2252
2253         zfs_close(zhp);
2254         return (ret);
2255 }
2256
2257 /*
2258  * zfs promote <fs>
2259  *
2260  * Promotes the given clone fs to be the parent
2261  */
2262 /* ARGSUSED */
2263 static int
2264 zfs_do_promote(int argc, char **argv)
2265 {
2266         zfs_handle_t *zhp;
2267         int ret;
2268
2269         /* check options */
2270         if (argc > 1 && argv[1][0] == '-') {
2271                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2272                     argv[1][1]);
2273                 usage(B_FALSE);
2274         }
2275
2276         /* check number of arguments */
2277         if (argc < 2) {
2278                 (void) fprintf(stderr, gettext("missing clone filesystem"
2279                     " argument\n"));
2280                 usage(B_FALSE);
2281         }
2282         if (argc > 2) {
2283                 (void) fprintf(stderr, gettext("too many arguments\n"));
2284                 usage(B_FALSE);
2285         }
2286
2287         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2288         if (zhp == NULL)
2289                 return (1);
2290
2291         ret = (zfs_promote(zhp) != 0);
2292
2293
2294         zfs_close(zhp);
2295         return (ret);
2296 }
2297
2298 /*
2299  * zfs rollback [-rRf] <snapshot>
2300  *
2301  *      -r      Delete any intervening snapshots before doing rollback
2302  *      -R      Delete any snapshots and their clones
2303  *      -f      ignored for backwards compatability
2304  *
2305  * Given a filesystem, rollback to a specific snapshot, discarding any changes
2306  * since then and making it the active dataset.  If more recent snapshots exist,
2307  * the command will complain unless the '-r' flag is given.
2308  */
2309 typedef struct rollback_cbdata {
2310         uint64_t        cb_create;
2311         boolean_t       cb_first;
2312         int             cb_doclones;
2313         char            *cb_target;
2314         int             cb_error;
2315         boolean_t       cb_recurse;
2316         boolean_t       cb_dependent;
2317 } rollback_cbdata_t;
2318
2319 /*
2320  * Report any snapshots more recent than the one specified.  Used when '-r' is
2321  * not specified.  We reuse this same callback for the snapshot dependents - if
2322  * 'cb_dependent' is set, then this is a dependent and we should report it
2323  * without checking the transaction group.
2324  */
2325 static int
2326 rollback_check(zfs_handle_t *zhp, void *data)
2327 {
2328         rollback_cbdata_t *cbp = data;
2329
2330         if (cbp->cb_doclones) {
2331                 zfs_close(zhp);
2332                 return (0);
2333         }
2334
2335         if (!cbp->cb_dependent) {
2336                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
2337                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2338                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
2339                     cbp->cb_create) {
2340
2341                         if (cbp->cb_first && !cbp->cb_recurse) {
2342                                 (void) fprintf(stderr, gettext("cannot "
2343                                     "rollback to '%s': more recent snapshots "
2344                                     "exist\n"),
2345                                     cbp->cb_target);
2346                                 (void) fprintf(stderr, gettext("use '-r' to "
2347                                     "force deletion of the following "
2348                                     "snapshots:\n"));
2349                                 cbp->cb_first = 0;
2350                                 cbp->cb_error = 1;
2351                         }
2352
2353                         if (cbp->cb_recurse) {
2354                                 cbp->cb_dependent = B_TRUE;
2355                                 if (zfs_iter_dependents(zhp, B_TRUE,
2356                                     rollback_check, cbp) != 0) {
2357                                         zfs_close(zhp);
2358                                         return (-1);
2359                                 }
2360                                 cbp->cb_dependent = B_FALSE;
2361                         } else {
2362                                 (void) fprintf(stderr, "%s\n",
2363                                     zfs_get_name(zhp));
2364                         }
2365                 }
2366         } else {
2367                 if (cbp->cb_first && cbp->cb_recurse) {
2368                         (void) fprintf(stderr, gettext("cannot rollback to "
2369                             "'%s': clones of previous snapshots exist\n"),
2370                             cbp->cb_target);
2371                         (void) fprintf(stderr, gettext("use '-R' to "
2372                             "force deletion of the following clones and "
2373                             "dependents:\n"));
2374                         cbp->cb_first = 0;
2375                         cbp->cb_error = 1;
2376                 }
2377
2378                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2379         }
2380
2381         zfs_close(zhp);
2382         return (0);
2383 }
2384
2385 static int
2386 zfs_do_rollback(int argc, char **argv)
2387 {
2388         int ret;
2389         int c;
2390         boolean_t force = B_FALSE;
2391         rollback_cbdata_t cb = { 0 };
2392         zfs_handle_t *zhp, *snap;
2393         char parentname[ZFS_MAXNAMELEN];
2394         char *delim;
2395
2396         /* check options */
2397         while ((c = getopt(argc, argv, "rRf")) != -1) {
2398                 switch (c) {
2399                 case 'r':
2400                         cb.cb_recurse = 1;
2401                         break;
2402                 case 'R':
2403                         cb.cb_recurse = 1;
2404                         cb.cb_doclones = 1;
2405                         break;
2406                 case 'f':
2407                         force = B_TRUE;
2408                         break;
2409                 case '?':
2410                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2411                             optopt);
2412                         usage(B_FALSE);
2413                 }
2414         }
2415
2416         argc -= optind;
2417         argv += optind;
2418
2419         /* check number of arguments */
2420         if (argc < 1) {
2421                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2422                 usage(B_FALSE);
2423         }
2424         if (argc > 1) {
2425                 (void) fprintf(stderr, gettext("too many arguments\n"));
2426                 usage(B_FALSE);
2427         }
2428
2429         /* open the snapshot */
2430         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2431                 return (1);
2432
2433         /* open the parent dataset */
2434         (void) strlcpy(parentname, argv[0], sizeof (parentname));
2435         verify((delim = strrchr(parentname, '@')) != NULL);
2436         *delim = '\0';
2437         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2438                 zfs_close(snap);
2439                 return (1);
2440         }
2441
2442         /*
2443          * Check for more recent snapshots and/or clones based on the presence
2444          * of '-r' and '-R'.
2445          */
2446         cb.cb_target = argv[0];
2447         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2448         cb.cb_first = B_TRUE;
2449         cb.cb_error = 0;
2450         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2451                 goto out;
2452
2453         if ((ret = cb.cb_error) != 0)
2454                 goto out;
2455
2456         /*
2457          * Rollback parent to the given snapshot.
2458          */
2459         ret = zfs_rollback(zhp, snap, force);
2460
2461 out:
2462         zfs_close(snap);
2463         zfs_close(zhp);
2464
2465         if (ret == 0)
2466                 return (0);
2467         else
2468                 return (1);
2469 }
2470
2471 /*
2472  * zfs set property=value { fs | snap | vol } ...
2473  *
2474  * Sets the given property for all datasets specified on the command line.
2475  */
2476 typedef struct set_cbdata {
2477         char            *cb_propname;
2478         char            *cb_value;
2479 } set_cbdata_t;
2480
2481 static int
2482 set_callback(zfs_handle_t *zhp, void *data)
2483 {
2484         set_cbdata_t *cbp = data;
2485
2486         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2487                 switch (libzfs_errno(g_zfs)) {
2488                 case EZFS_MOUNTFAILED:
2489                         (void) fprintf(stderr, gettext("property may be set "
2490                             "but unable to remount filesystem\n"));
2491                         break;
2492                 case EZFS_SHARENFSFAILED:
2493                         (void) fprintf(stderr, gettext("property may be set "
2494                             "but unable to reshare filesystem\n"));
2495                         break;
2496                 }
2497                 return (1);
2498         }
2499         return (0);
2500 }
2501
2502 static int
2503 zfs_do_set(int argc, char **argv)
2504 {
2505         set_cbdata_t cb;
2506         int ret;
2507
2508         /* check for options */
2509         if (argc > 1 && argv[1][0] == '-') {
2510                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2511                     argv[1][1]);
2512                 usage(B_FALSE);
2513         }
2514
2515         /* check number of arguments */
2516         if (argc < 2) {
2517                 (void) fprintf(stderr, gettext("missing property=value "
2518                     "argument\n"));
2519                 usage(B_FALSE);
2520         }
2521         if (argc < 3) {
2522                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2523                 usage(B_FALSE);
2524         }
2525
2526         /* validate property=value argument */
2527         cb.cb_propname = argv[1];
2528         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
2529             (cb.cb_value[1] == '\0')) {
2530                 (void) fprintf(stderr, gettext("missing value in "
2531                     "property=value argument\n"));
2532                 usage(B_FALSE);
2533         }
2534
2535         *cb.cb_value = '\0';
2536         cb.cb_value++;
2537
2538         if (*cb.cb_propname == '\0') {
2539                 (void) fprintf(stderr,
2540                     gettext("missing property in property=value argument\n"));
2541                 usage(B_FALSE);
2542         }
2543
2544         ret = zfs_for_each(argc - 2, argv + 2, 0,
2545             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
2546
2547         return (ret);
2548 }
2549
2550 /*
2551  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
2552  *
2553  * Creates a snapshot with the given name.  While functionally equivalent to
2554  * 'zfs create', it is a separate command to differentiate intent.
2555  */
2556 static int
2557 zfs_do_snapshot(int argc, char **argv)
2558 {
2559         boolean_t recursive = B_FALSE;
2560         int ret;
2561         signed char c;
2562         nvlist_t *props;
2563
2564         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2565                 nomem();
2566
2567         /* check options */
2568         while ((c = getopt(argc, argv, "ro:")) != -1) {
2569                 switch (c) {
2570                 case 'o':
2571                         if (parseprop(props))
2572                                 return (1);
2573                         break;
2574                 case 'r':
2575                         recursive = B_TRUE;
2576                         break;
2577                 case '?':
2578                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2579                             optopt);
2580                         goto usage;
2581                 }
2582         }
2583
2584         argc -= optind;
2585         argv += optind;
2586
2587         /* check number of arguments */
2588         if (argc < 1) {
2589                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2590                 goto usage;
2591         }
2592         if (argc > 1) {
2593                 (void) fprintf(stderr, gettext("too many arguments\n"));
2594                 goto usage;
2595         }
2596
2597         ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
2598         nvlist_free(props);
2599         if (ret && recursive)
2600                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
2601         return (ret != 0);
2602
2603 usage:
2604         nvlist_free(props);
2605         usage(B_FALSE);
2606         return (-1);
2607 }
2608
2609 /*
2610  * zfs send [-vDp] -R [-i|-I <@snap>] <fs@snap>
2611  * zfs send [-vDp] [-i|-I <@snap>] <fs@snap>
2612  *
2613  * Send a backup stream to stdout.
2614  */
2615 static int
2616 zfs_do_send(int argc, char **argv)
2617 {
2618         char *fromname = NULL;
2619         char *toname = NULL;
2620         char *cp;
2621         zfs_handle_t *zhp;
2622         sendflags_t flags = { 0 };
2623         int c, err;
2624         nvlist_t *dbgnv;
2625         boolean_t extraverbose = B_FALSE;
2626
2627         /* check options */
2628         while ((c = getopt(argc, argv, ":i:I:RDpv")) != -1) {
2629                 switch (c) {
2630                 case 'i':
2631                         if (fromname)
2632                                 usage(B_FALSE);
2633                         fromname = optarg;
2634                         break;
2635                 case 'I':
2636                         if (fromname)
2637                                 usage(B_FALSE);
2638                         fromname = optarg;
2639                         flags.doall = B_TRUE;
2640                         break;
2641                 case 'R':
2642                         flags.replicate = B_TRUE;
2643                         break;
2644                 case 'p':
2645                         flags.props = B_TRUE;
2646                         break;
2647                 case 'v':
2648                         if (flags.verbose)
2649                                 extraverbose = B_TRUE;
2650                         flags.verbose = B_TRUE;
2651                         break;
2652                 case 'D':
2653                         flags.dedup = B_TRUE;
2654                         break;
2655                 case ':':
2656                         (void) fprintf(stderr, gettext("missing argument for "
2657                             "'%c' option\n"), optopt);
2658                         usage(B_FALSE);
2659                         break;
2660                 case '?':
2661                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2662                             optopt);
2663                         usage(B_FALSE);
2664                 }
2665         }
2666
2667         argc -= optind;
2668         argv += optind;
2669
2670         /* check number of arguments */
2671         if (argc < 1) {
2672                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2673                 usage(B_FALSE);
2674         }
2675         if (argc > 1) {
2676                 (void) fprintf(stderr, gettext("too many arguments\n"));
2677                 usage(B_FALSE);
2678         }
2679
2680         if (isatty(STDOUT_FILENO)) {
2681                 (void) fprintf(stderr,
2682                     gettext("Error: Stream can not be written to a terminal.\n"
2683                     "You must redirect standard output.\n"));
2684                 return (1);
2685         }
2686
2687         cp = strchr(argv[0], '@');
2688         if (cp == NULL) {
2689                 (void) fprintf(stderr,
2690                     gettext("argument must be a snapshot\n"));
2691                 usage(B_FALSE);
2692         }
2693         *cp = '\0';
2694         toname = cp + 1;
2695         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2696         if (zhp == NULL)
2697                 return (1);
2698
2699         /*
2700          * If they specified the full path to the snapshot, chop off
2701          * everything except the short name of the snapshot, but special
2702          * case if they specify the origin.
2703          */
2704         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2705                 char origin[ZFS_MAXNAMELEN];
2706                 zprop_source_t src;
2707
2708                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2709                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2710
2711                 if (strcmp(origin, fromname) == 0) {
2712                         fromname = NULL;
2713                         flags.fromorigin = B_TRUE;
2714                 } else {
2715                         *cp = '\0';
2716                         if (cp != fromname && strcmp(argv[0], fromname)) {
2717                                 (void) fprintf(stderr,
2718                                     gettext("incremental source must be "
2719                                     "in same filesystem\n"));
2720                                 usage(B_FALSE);
2721                         }
2722                         fromname = cp + 1;
2723                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
2724                                 (void) fprintf(stderr,
2725                                     gettext("invalid incremental source\n"));
2726                                 usage(B_FALSE);
2727                         }
2728                 }
2729         }
2730
2731         if (flags.replicate && fromname == NULL)
2732                 flags.doall = B_TRUE;
2733
2734         err = zfs_send(zhp, fromname, toname, flags, STDOUT_FILENO, NULL, 0,
2735             extraverbose ? &dbgnv : NULL);
2736
2737         if (extraverbose) {
2738                 /*
2739                  * dump_nvlist prints to stdout, but that's been
2740                  * redirected to a file.  Make it print to stderr
2741                  * instead.
2742                  */
2743                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
2744                 dump_nvlist(dbgnv, 0);
2745                 nvlist_free(dbgnv);
2746         }
2747         zfs_close(zhp);
2748
2749         return (err != 0);
2750 }
2751
2752 /*
2753  * zfs receive [-vnFu] [-d | -e] <fs@snap>
2754  *
2755  * Restore a backup stream from stdin.
2756  */
2757 static int
2758 zfs_do_receive(int argc, char **argv)
2759 {
2760         int c, err;
2761         recvflags_t flags = { 0 };
2762
2763         /* check options */
2764         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
2765                 switch (c) {
2766                 case 'd':
2767                         flags.isprefix = B_TRUE;
2768                         break;
2769                 case 'e':
2770                         flags.isprefix = B_TRUE;
2771                         flags.istail = B_TRUE;
2772                         break;
2773                 case 'n':
2774                         flags.dryrun = B_TRUE;
2775                         break;
2776                 case 'u':
2777                         flags.nomount = B_TRUE;
2778                         break;
2779                 case 'v':
2780                         flags.verbose = B_TRUE;
2781                         break;
2782                 case 'F':
2783                         flags.force = B_TRUE;
2784                         break;
2785                 case ':':
2786                         (void) fprintf(stderr, gettext("missing argument for "
2787                             "'%c' option\n"), optopt);
2788                         usage(B_FALSE);
2789                         break;
2790                 case '?':
2791                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2792                             optopt);
2793                         usage(B_FALSE);
2794                 }
2795         }
2796
2797         argc -= optind;
2798         argv += optind;
2799
2800         /* check number of arguments */
2801         if (argc < 1) {
2802                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2803                 usage(B_FALSE);
2804         }
2805         if (argc > 1) {
2806                 (void) fprintf(stderr, gettext("too many arguments\n"));
2807                 usage(B_FALSE);
2808         }
2809
2810         if (isatty(STDIN_FILENO)) {
2811                 (void) fprintf(stderr,
2812                     gettext("Error: Backup stream can not be read "
2813                     "from a terminal.\n"
2814                     "You must redirect standard input.\n"));
2815                 return (1);
2816         }
2817
2818         err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2819
2820         return (err != 0);
2821 }
2822
2823 static int
2824 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
2825 {
2826         int errors = 0;
2827         int i;
2828         const char *tag;
2829         boolean_t recursive = B_FALSE;
2830         boolean_t temphold = B_FALSE;
2831         const char *opts = holding ? "rt" : "r";
2832         int c;
2833
2834         /* check options */
2835         while ((c = getopt(argc, argv, opts)) != -1) {
2836                 switch (c) {
2837                 case 'r':
2838                         recursive = B_TRUE;
2839                         break;
2840                 case 't':
2841                         temphold = B_TRUE;
2842                         break;
2843                 case '?':
2844                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2845                             optopt);
2846                         usage(B_FALSE);
2847                 }
2848         }
2849
2850         argc -= optind;
2851         argv += optind;
2852
2853         /* check number of arguments */
2854         if (argc < 2)
2855                 usage(B_FALSE);
2856
2857         tag = argv[0];
2858         --argc;
2859         ++argv;
2860
2861         if (holding && tag[0] == '.') {
2862                 /* tags starting with '.' are reserved for libzfs */
2863                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
2864                 usage(B_FALSE);
2865         }
2866
2867         for (i = 0; i < argc; ++i) {
2868                 zfs_handle_t *zhp;
2869                 char parent[ZFS_MAXNAMELEN];
2870                 const char *delim;
2871                 char *path = argv[i];
2872
2873                 delim = strchr(path, '@');
2874                 if (delim == NULL) {
2875                         (void) fprintf(stderr,
2876                             gettext("'%s' is not a snapshot\n"), path);
2877                         ++errors;
2878                         continue;
2879                 }
2880                 (void) strncpy(parent, path, delim - path);
2881                 parent[delim - path] = '\0';
2882
2883                 zhp = zfs_open(g_zfs, parent,
2884                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2885                 if (zhp == NULL) {
2886                         ++errors;
2887                         continue;
2888                 }
2889                 if (holding) {
2890                         if (zfs_hold(zhp, delim+1, tag, recursive,
2891                             temphold, B_FALSE, -1, 0, 0) != 0)
2892                                 ++errors;
2893                 } else {
2894                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
2895                                 ++errors;
2896                 }
2897                 zfs_close(zhp);
2898         }
2899
2900         return (errors != 0);
2901 }
2902
2903 /*
2904  * zfs hold [-r] [-t] <tag> <snap> ...
2905  *
2906  *      -r      Recursively hold
2907  *      -t      Temporary hold (hidden option)
2908  *
2909  * Apply a user-hold with the given tag to the list of snapshots.
2910  */
2911 static int
2912 zfs_do_hold(int argc, char **argv)
2913 {
2914         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
2915 }
2916
2917 /*
2918  * zfs release [-r] <tag> <snap> ...
2919  *
2920  *      -r      Recursively release
2921  *
2922  * Release a user-hold with the given tag from the list of snapshots.
2923  */
2924 static int
2925 zfs_do_release(int argc, char **argv)
2926 {
2927         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
2928 }
2929
2930 #define CHECK_SPINNER 30
2931 #define SPINNER_TIME 3          /* seconds */
2932 #define MOUNT_TIME 5            /* seconds */
2933
2934 static int
2935 get_one_dataset(zfs_handle_t *zhp, void *data)
2936 {
2937         static char *spin[] = { "-", "\\", "|", "/" };
2938         static int spinval = 0;
2939         static int spincheck = 0;
2940         static time_t last_spin_time = (time_t)0;
2941         get_all_cb_t *cbp = data;
2942         zfs_type_t type = zfs_get_type(zhp);
2943
2944         if (cbp->cb_verbose) {
2945                 if (--spincheck < 0) {
2946                         time_t now = time(NULL);
2947                         if (last_spin_time + SPINNER_TIME < now) {
2948                                 update_progress(spin[spinval++ % 4]);
2949                                 last_spin_time = now;
2950                         }
2951                         spincheck = CHECK_SPINNER;
2952                 }
2953         }
2954
2955         /*
2956          * Interate over any nested datasets.
2957          */
2958         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2959                 zfs_close(zhp);
2960                 return (1);
2961         }
2962
2963         /*
2964          * Skip any datasets whose type does not match.
2965          */
2966         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
2967                 zfs_close(zhp);
2968                 return (0);
2969         }
2970         libzfs_add_handle(cbp, zhp);
2971         assert(cbp->cb_used <= cbp->cb_alloc);
2972
2973         return (0);
2974 }
2975
2976 static void
2977 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
2978 {
2979         get_all_cb_t cb = { 0 };
2980         cb.cb_verbose = verbose;
2981         cb.cb_getone = get_one_dataset;
2982
2983         if (verbose)
2984                 set_progress_header(gettext("Reading ZFS config"));
2985         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2986
2987         *dslist = cb.cb_handles;
2988         *count = cb.cb_used;
2989
2990         if (verbose)
2991                 finish_progress(gettext("done."));
2992 }
2993
2994 /*
2995  * Generic callback for sharing or mounting filesystems.  Because the code is so
2996  * similar, we have a common function with an extra parameter to determine which
2997  * mode we are using.
2998  */
2999 #define OP_SHARE        0x1
3000 #define OP_MOUNT        0x2
3001
3002 /*
3003  * Share or mount a dataset.
3004  */
3005 static int
3006 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3007     boolean_t explicit, const char *options)
3008 {
3009         char mountpoint[ZFS_MAXPROPLEN];
3010         char shareopts[ZFS_MAXPROPLEN];
3011         char smbshareopts[ZFS_MAXPROPLEN];
3012         const char *cmdname = op == OP_SHARE ? "share" : "mount";
3013         struct mnttab mnt;
3014         uint64_t zoned, canmount;
3015         boolean_t shared_nfs, shared_smb;
3016
3017         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
3018
3019         /*
3020          * Check to make sure we can mount/share this dataset.  If we
3021          * are in the global zone and the filesystem is exported to a
3022          * local zone, or if we are in a local zone and the
3023          * filesystem is not exported, then it is an error.
3024          */
3025         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3026
3027         if (zoned && getzoneid() == GLOBAL_ZONEID) {
3028                 if (!explicit)
3029                         return (0);
3030
3031                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3032                     "dataset is exported to a local zone\n"), cmdname,
3033                     zfs_get_name(zhp));
3034                 return (1);
3035
3036         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3037                 if (!explicit)
3038                         return (0);
3039
3040                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3041                     "permission denied\n"), cmdname,
3042                     zfs_get_name(zhp));
3043                 return (1);
3044         }
3045
3046         /*
3047          * Ignore any filesystems which don't apply to us. This
3048          * includes those with a legacy mountpoint, or those with
3049          * legacy share options.
3050          */
3051         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3052             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3053         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3054             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3055         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3056             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3057
3058         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3059             strcmp(smbshareopts, "off") == 0) {
3060                 if (!explicit)
3061                         return (0);
3062
3063                 (void) fprintf(stderr, gettext("cannot share '%s': "
3064                     "legacy share\n"), zfs_get_name(zhp));
3065                 (void) fprintf(stderr, gettext("use share(1M) to "
3066                     "share this filesystem, or set "
3067                     "sharenfs property on\n"));
3068                 return (1);
3069         }
3070
3071         /*
3072          * We cannot share or mount legacy filesystems. If the
3073          * shareopts is non-legacy but the mountpoint is legacy, we
3074          * treat it as a legacy share.
3075          */
3076         if (strcmp(mountpoint, "legacy") == 0) {
3077                 if (!explicit)
3078                         return (0);
3079
3080                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3081                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3082                 (void) fprintf(stderr, gettext("use %s(1M) to "
3083                     "%s this filesystem\n"), cmdname, cmdname);
3084                 return (1);
3085         }
3086
3087         if (strcmp(mountpoint, "none") == 0) {
3088                 if (!explicit)
3089                         return (0);
3090
3091                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
3092                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3093                 return (1);
3094         }
3095
3096         /*
3097          * canmount     explicit        outcome
3098          * on           no              pass through
3099          * on           yes             pass through
3100          * off          no              return 0
3101          * off          yes             display error, return 1
3102          * noauto       no              return 0
3103          * noauto       yes             pass through
3104          */
3105         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3106         if (canmount == ZFS_CANMOUNT_OFF) {
3107                 if (!explicit)
3108                         return (0);
3109
3110                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3111                     "'canmount' property is set to 'off'\n"), cmdname,
3112                     zfs_get_name(zhp));
3113                 return (1);
3114         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3115                 return (0);
3116         }
3117
3118         /*
3119          * At this point, we have verified that the mountpoint and/or
3120          * shareopts are appropriate for auto management. If the
3121          * filesystem is already mounted or shared, return (failing
3122          * for explicit requests); otherwise mount or share the
3123          * filesystem.
3124          */
3125         switch (op) {
3126         case OP_SHARE:
3127
3128                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3129                 shared_smb = zfs_is_shared_smb(zhp, NULL);
3130
3131                 if ((shared_nfs && shared_smb) ||
3132                     ((shared_nfs && strcmp(shareopts, "on") == 0) &&
3133                     (strcmp(smbshareopts, "off") == 0)) ||
3134                     ((shared_smb && strcmp(smbshareopts, "on") == 0) &&
3135                     (strcmp(shareopts, "off") == 0))) {
3136                         if (!explicit)
3137                                 return (0);
3138
3139                         (void) fprintf(stderr, gettext("cannot share "
3140                             "'%s': filesystem already shared\n"),
3141                             zfs_get_name(zhp));
3142                         return (1);
3143                 }
3144
3145                 if (!zfs_is_mounted(zhp, NULL) &&
3146                     zfs_mount(zhp, NULL, 0) != 0)
3147                         return (1);
3148
3149                 if (protocol == NULL) {
3150                         if (zfs_shareall(zhp) != 0)
3151                                 return (1);
3152                 } else if (strcmp(protocol, "nfs") == 0) {
3153                         if (zfs_share_nfs(zhp))
3154                                 return (1);
3155                 } else if (strcmp(protocol, "smb") == 0) {
3156                         if (zfs_share_smb(zhp))
3157                                 return (1);
3158                 } else {
3159                         (void) fprintf(stderr, gettext("cannot share "
3160                             "'%s': invalid share type '%s' "
3161                             "specified\n"),
3162                             zfs_get_name(zhp), protocol);
3163                         return (1);
3164                 }
3165
3166                 break;
3167
3168         case OP_MOUNT:
3169                 if (options == NULL)
3170                         mnt.mnt_mntopts = "";
3171                 else
3172                         mnt.mnt_mntopts = (char *)options;
3173
3174                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3175                     zfs_is_mounted(zhp, NULL)) {
3176                         if (!explicit)
3177                                 return (0);
3178
3179                         (void) fprintf(stderr, gettext("cannot mount "
3180                             "'%s': filesystem already mounted\n"),
3181                             zfs_get_name(zhp));
3182                         return (1);
3183                 }
3184
3185                 if (zfs_mount(zhp, options, flags) != 0)
3186                         return (1);
3187                 break;
3188         }
3189
3190         return (0);
3191 }
3192
3193 /*
3194  * Reports progress in the form "(current/total)".  Not thread-safe.
3195  */
3196 static void
3197 report_mount_progress(int current, int total)
3198 {
3199         static time_t last_progress_time = 0;
3200         time_t now = time(NULL);
3201         char info[32];
3202
3203         /* report 1..n instead of 0..n-1 */
3204         ++current;
3205
3206         /* display header if we're here for the first time */
3207         if (current == 1) {
3208                 set_progress_header(gettext("Mounting ZFS filesystems"));
3209         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3210                 /* too soon to report again */
3211                 return;
3212         }
3213
3214         last_progress_time = now;
3215
3216         (void) sprintf(info, "(%d/%d)", current, total);
3217
3218         if (current == total)
3219                 finish_progress(info);
3220         else
3221                 update_progress(info);
3222 }
3223
3224 static void
3225 append_options(char *mntopts, char *newopts)
3226 {
3227         int len = strlen(mntopts);
3228
3229         /* original length plus new string to append plus 1 for the comma */
3230         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3231                 (void) fprintf(stderr, gettext("the opts argument for "
3232                     "'%s' option is too long (more than %d chars)\n"),
3233                     "-o", MNT_LINE_MAX);
3234                 usage(B_FALSE);
3235         }
3236
3237         if (*mntopts)
3238                 mntopts[len++] = ',';
3239
3240         (void) strcpy(&mntopts[len], newopts);
3241 }
3242
3243 static int
3244 share_mount(int op, int argc, char **argv)
3245 {
3246         int do_all = 0;
3247         boolean_t verbose = B_FALSE;
3248         int c, ret = 0;
3249         char *options = NULL;
3250         int flags = 0;
3251
3252         /* check options */
3253         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:" : "a"))
3254             != -1) {
3255                 switch (c) {
3256                 case 'a':
3257                         do_all = 1;
3258                         break;
3259                 case 'v':
3260                         verbose = B_TRUE;
3261                         break;
3262                 case 'o':
3263                         if (*optarg == '\0') {
3264                                 (void) fprintf(stderr, gettext("empty mount "
3265                                     "options (-o) specified\n"));
3266                                 usage(B_FALSE);
3267                         }
3268
3269                         if (options == NULL)
3270                                 options = safe_malloc(MNT_LINE_MAX + 1);
3271
3272                         /* option validation is done later */
3273                         append_options(options, optarg);
3274                         break;
3275
3276                 case ':':
3277                         (void) fprintf(stderr, gettext("missing argument for "
3278                             "'%c' option\n"), optopt);
3279                         usage(B_FALSE);
3280                         break;
3281                 case '?':
3282                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3283                             optopt);
3284                         usage(B_FALSE);
3285                 }
3286         }
3287
3288         argc -= optind;
3289         argv += optind;
3290
3291         /* check number of arguments */
3292         if (do_all) {
3293                 zfs_handle_t **dslist = NULL;
3294                 size_t i, count = 0;
3295                 char *protocol = NULL;
3296
3297                 if (op == OP_SHARE && argc > 0) {
3298                         if (strcmp(argv[0], "nfs") != 0 &&
3299                             strcmp(argv[0], "smb") != 0) {
3300                                 (void) fprintf(stderr, gettext("share type "
3301                                     "must be 'nfs' or 'smb'\n"));
3302                                 usage(B_FALSE);
3303                         }
3304                         protocol = argv[0];
3305                         argc--;
3306                         argv++;
3307                 }
3308
3309                 if (argc != 0) {
3310                         (void) fprintf(stderr, gettext("too many arguments\n"));
3311                         usage(B_FALSE);
3312                 }
3313
3314                 start_progress_timer();
3315                 get_all_datasets(&dslist, &count, verbose);
3316
3317                 if (count == 0)
3318                         return (0);
3319
3320                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
3321
3322                 for (i = 0; i < count; i++) {
3323                         if (verbose)
3324                                 report_mount_progress(i, count);
3325
3326                         if (share_mount_one(dslist[i], op, flags, protocol,
3327                             B_FALSE, options) != 0)
3328                                 ret = 1;
3329                         zfs_close(dslist[i]);
3330                 }
3331
3332                 free(dslist);
3333         } else if (argc == 0) {
3334                 struct mnttab entry;
3335
3336                 if ((op == OP_SHARE) || (options != NULL)) {
3337                         (void) fprintf(stderr, gettext("missing filesystem "
3338                             "argument (specify -a for all)\n"));
3339                         usage(B_FALSE);
3340                 }
3341
3342                 /*
3343                  * When mount is given no arguments, go through /etc/mtab and
3344                  * display any active ZFS mounts.  We hide any snapshots, since
3345                  * they are controlled automatically.
3346                  */
3347                 rewind(mnttab_file);
3348                 while (getmntent(mnttab_file, &entry) == 0) {
3349                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3350                             strchr(entry.mnt_special, '@') != NULL)
3351                                 continue;
3352
3353                         (void) printf("%-30s  %s\n", entry.mnt_special,
3354                             entry.mnt_mountp);
3355                 }
3356
3357         } else {
3358                 zfs_handle_t *zhp;
3359
3360                 if (argc > 1) {
3361                         (void) fprintf(stderr,
3362                             gettext("too many arguments\n"));
3363                         usage(B_FALSE);
3364                 }
3365
3366                 if ((zhp = zfs_open(g_zfs, argv[0],
3367                     ZFS_TYPE_FILESYSTEM)) == NULL) {
3368                         ret = 1;
3369                 } else {
3370                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3371                             options);
3372                         zfs_close(zhp);
3373                 }
3374         }
3375
3376         return (ret);
3377 }
3378
3379 /*
3380  * zfs mount -a [nfs]
3381  * zfs mount filesystem
3382  *
3383  * Mount all filesystems, or mount the given filesystem.
3384  */
3385 static int
3386 zfs_do_mount(int argc, char **argv)
3387 {
3388         return (share_mount(OP_MOUNT, argc, argv));
3389 }
3390
3391 /*
3392  * zfs share -a [nfs | smb]
3393  * zfs share filesystem
3394  *
3395  * Share all filesystems, or share the given filesystem.
3396  */
3397 static int
3398 zfs_do_share(int argc, char **argv)
3399 {
3400         return (share_mount(OP_SHARE, argc, argv));
3401 }
3402
3403 typedef struct unshare_unmount_node {
3404         zfs_handle_t    *un_zhp;
3405         char            *un_mountp;
3406         uu_avl_node_t   un_avlnode;
3407 } unshare_unmount_node_t;
3408
3409 /* ARGSUSED */
3410 static int
3411 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3412 {
3413         const unshare_unmount_node_t *l = larg;
3414         const unshare_unmount_node_t *r = rarg;
3415
3416         return (strcmp(l->un_mountp, r->un_mountp));
3417 }
3418
3419 /*
3420  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3421  * absolute path, find the entry /etc/mtab, verify that its a ZFS filesystem,
3422  * and unmount it appropriately.
3423  */
3424 static int
3425 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3426 {
3427         zfs_handle_t *zhp;
3428         int ret;
3429         struct stat64 statbuf;
3430         struct extmnttab entry;
3431         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3432         ino_t path_inode;
3433
3434         /*
3435          * Search for the path in /etc/mtab.  Rather than looking for the
3436          * specific path, which can be fooled by non-standard paths (i.e. ".."
3437          * or "//"), we stat() the path and search for the corresponding
3438          * (major,minor) device pair.
3439          */
3440         if (stat64(path, &statbuf) != 0) {
3441                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3442                     cmdname, path, strerror(errno));
3443                 return (1);
3444         }
3445         path_inode = statbuf.st_ino;
3446
3447         /*
3448          * Search for the given (major,minor) pair in the mount table.
3449          */
3450         rewind(mnttab_file);
3451         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3452                 if (entry.mnt_major == major(statbuf.st_dev) &&
3453                     entry.mnt_minor == minor(statbuf.st_dev))
3454                         break;
3455         }
3456         if (ret != 0) {
3457                 if (op == OP_SHARE) {
3458                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
3459                             "currently mounted\n"), cmdname, path);
3460                         return (1);
3461                 }
3462                 (void) fprintf(stderr, gettext("warning: %s not in mtab\n"),
3463                     path);
3464                 if ((ret = umount2(path, flags)) != 0)
3465                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
3466                             strerror(errno));
3467                 return (ret != 0);
3468         }
3469
3470         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3471                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3472                     "filesystem\n"), cmdname, path);
3473                 return (1);
3474         }
3475
3476         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3477             ZFS_TYPE_FILESYSTEM)) == NULL)
3478                 return (1);
3479
3480         ret = 1;
3481         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3482                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3483                     cmdname, path, strerror(errno));
3484                 goto out;
3485         } else if (statbuf.st_ino != path_inode) {
3486                 (void) fprintf(stderr, gettext("cannot "
3487                     "%s '%s': not a mountpoint\n"), cmdname, path);
3488                 goto out;
3489         }
3490
3491         if (op == OP_SHARE) {
3492                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
3493                 char smbshare_prop[ZFS_MAXPROPLEN];
3494
3495                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3496                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3497                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3498                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3499
3500                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
3501                     strcmp(smbshare_prop, "off") == 0) {
3502                         (void) fprintf(stderr, gettext("cannot unshare "
3503                             "'%s': legacy share\n"), path);
3504                         (void) fprintf(stderr, gettext("use exportfs(8) "
3505                             "or smbcontrol(1) to unshare this filesystem\n"));
3506                 } else if (!zfs_is_shared(zhp)) {
3507                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
3508                             "not currently shared\n"), path);
3509                 } else {
3510                         ret = zfs_unshareall_bypath(zhp, path);
3511                 }
3512         } else {
3513                 char mtpt_prop[ZFS_MAXPROPLEN];
3514
3515                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3516                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3517
3518                 if (is_manual) {
3519                         ret = zfs_unmount(zhp, NULL, flags);
3520                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
3521                         (void) fprintf(stderr, gettext("cannot unmount "
3522                             "'%s': legacy mountpoint\n"),
3523                             zfs_get_name(zhp));
3524                         (void) fprintf(stderr, gettext("use umount(8) "
3525                             "to unmount this filesystem\n"));
3526                 } else {
3527                         ret = zfs_unmountall(zhp, flags);
3528                 }
3529         }
3530
3531 out:
3532         zfs_close(zhp);
3533
3534         return (ret != 0);
3535 }
3536
3537 /*
3538  * Generic callback for unsharing or unmounting a filesystem.
3539  */
3540 static int
3541 unshare_unmount(int op, int argc, char **argv)
3542 {
3543         int do_all = 0;
3544         int flags = 0;
3545         int ret = 0;
3546         int c;
3547         zfs_handle_t *zhp;
3548         char nfs_mnt_prop[ZFS_MAXPROPLEN];
3549         char sharesmb[ZFS_MAXPROPLEN];
3550
3551         /* check options */
3552         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3553                 switch (c) {
3554                 case 'a':
3555                         do_all = 1;
3556                         break;
3557                 case 'f':
3558                         flags = MS_FORCE;
3559                         break;
3560                 case '?':
3561                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3562                             optopt);
3563                         usage(B_FALSE);
3564                 }
3565         }
3566
3567         argc -= optind;
3568         argv += optind;
3569
3570         if (do_all) {
3571                 /*
3572                  * We could make use of zfs_for_each() to walk all datasets in
3573                  * the system, but this would be very inefficient, especially
3574                  * since we would have to linearly search /etc/mtab for each
3575                  * one.  Instead, do one pass through /etc/mtab looking for
3576                  * zfs entries and call zfs_unmount() for each one.
3577                  *
3578                  * Things get a little tricky if the administrator has created
3579                  * mountpoints beneath other ZFS filesystems.  In this case, we
3580                  * have to unmount the deepest filesystems first.  To accomplish
3581                  * this, we place all the mountpoints in an AVL tree sorted by
3582                  * the special type (dataset name), and walk the result in
3583                  * reverse to make sure to get any snapshots first.
3584                  */
3585                 struct mnttab entry;
3586                 uu_avl_pool_t *pool;
3587                 uu_avl_t *tree = NULL;
3588                 unshare_unmount_node_t *node;
3589                 uu_avl_index_t idx;
3590                 uu_avl_walk_t *walk;
3591
3592                 if (argc != 0) {
3593                         (void) fprintf(stderr, gettext("too many arguments\n"));
3594                         usage(B_FALSE);
3595                 }
3596
3597                 if (((pool = uu_avl_pool_create("unmount_pool",
3598                     sizeof (unshare_unmount_node_t),
3599                     offsetof(unshare_unmount_node_t, un_avlnode),
3600                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
3601                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
3602                         nomem();
3603
3604                 rewind(mnttab_file);
3605                 while (getmntent(mnttab_file, &entry) == 0) {
3606
3607                         /* ignore non-ZFS entries */
3608                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3609                                 continue;
3610
3611                         /* ignore snapshots */
3612                         if (strchr(entry.mnt_special, '@') != NULL)
3613                                 continue;
3614
3615                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3616                             ZFS_TYPE_FILESYSTEM)) == NULL) {
3617                                 ret = 1;
3618                                 continue;
3619                         }
3620
3621                         switch (op) {
3622                         case OP_SHARE:
3623                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3624                                     nfs_mnt_prop,
3625                                     sizeof (nfs_mnt_prop),
3626                                     NULL, NULL, 0, B_FALSE) == 0);
3627                                 if (strcmp(nfs_mnt_prop, "off") != 0)
3628                                         break;
3629                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3630                                     nfs_mnt_prop,
3631                                     sizeof (nfs_mnt_prop),
3632                                     NULL, NULL, 0, B_FALSE) == 0);
3633                                 if (strcmp(nfs_mnt_prop, "off") == 0)
3634                                         continue;
3635                                 break;
3636                         case OP_MOUNT:
3637                                 /* Ignore legacy mounts */
3638                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3639                                     nfs_mnt_prop,
3640                                     sizeof (nfs_mnt_prop),
3641                                     NULL, NULL, 0, B_FALSE) == 0);
3642                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
3643                                         continue;
3644                                 /* Ignore canmount=noauto mounts */
3645                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3646                                     ZFS_CANMOUNT_NOAUTO)
3647                                         continue;
3648                         default:
3649                                 break;
3650                         }
3651
3652                         node = safe_malloc(sizeof (unshare_unmount_node_t));
3653                         node->un_zhp = zhp;
3654                         node->un_mountp = safe_strdup(entry.mnt_mountp);
3655
3656                         uu_avl_node_init(node, &node->un_avlnode, pool);
3657
3658                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3659                                 uu_avl_insert(tree, node, idx);
3660                         } else {
3661                                 zfs_close(node->un_zhp);
3662                                 free(node->un_mountp);
3663                                 free(node);
3664                         }
3665                 }
3666
3667                 /*
3668                  * Walk the AVL tree in reverse, unmounting each filesystem and
3669                  * removing it from the AVL tree in the process.
3670                  */
3671                 if ((walk = uu_avl_walk_start(tree,
3672                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
3673                         nomem();
3674
3675                 while ((node = uu_avl_walk_next(walk)) != NULL) {
3676                         uu_avl_remove(tree, node);
3677
3678                         switch (op) {
3679                         case OP_SHARE:
3680                                 if (zfs_unshareall_bypath(node->un_zhp,
3681                                     node->un_mountp) != 0)
3682                                         ret = 1;
3683                                 break;
3684
3685                         case OP_MOUNT:
3686                                 if (zfs_unmount(node->un_zhp,
3687                                     node->un_mountp, flags) != 0)
3688                                         ret = 1;
3689                                 break;
3690                         }
3691
3692                         zfs_close(node->un_zhp);
3693                         free(node->un_mountp);
3694                         free(node);
3695                 }
3696
3697                 uu_avl_walk_end(walk);
3698                 uu_avl_destroy(tree);
3699                 uu_avl_pool_destroy(pool);
3700
3701         } else {
3702                 if (argc != 1) {
3703                         if (argc == 0)
3704                                 (void) fprintf(stderr,
3705                                     gettext("missing filesystem argument\n"));
3706                         else
3707                                 (void) fprintf(stderr,
3708                                     gettext("too many arguments\n"));
3709                         usage(B_FALSE);
3710                 }
3711
3712                 /*
3713                  * We have an argument, but it may be a full path or a ZFS
3714                  * filesystem.  Pass full paths off to unmount_path() (shared by
3715                  * manual_unmount), otherwise open the filesystem and pass to
3716                  * zfs_unmount().
3717                  */
3718                 if (argv[0][0] == '/')
3719                         return (unshare_unmount_path(op, argv[0],
3720                             flags, B_FALSE));
3721
3722                 if ((zhp = zfs_open(g_zfs, argv[0],
3723                     ZFS_TYPE_FILESYSTEM)) == NULL)
3724                         return (1);
3725
3726                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
3727                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3728                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
3729                     NULL, 0, B_FALSE) == 0);
3730
3731                 switch (op) {
3732                 case OP_SHARE:
3733                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3734                             nfs_mnt_prop,
3735                             sizeof (nfs_mnt_prop),
3736                             NULL, NULL, 0, B_FALSE) == 0);
3737                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3738                             sharesmb, sizeof (sharesmb), NULL, NULL,
3739                             0, B_FALSE) == 0);
3740
3741                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
3742                             strcmp(sharesmb, "off") == 0) {
3743                                 (void) fprintf(stderr, gettext("cannot "
3744                                     "unshare '%s': legacy share\n"),
3745                                     zfs_get_name(zhp));
3746                                 (void) fprintf(stderr, gettext("use "
3747                                     "unshare(1M) to unshare this "
3748                                     "filesystem\n"));
3749                                 ret = 1;
3750                         } else if (!zfs_is_shared(zhp)) {
3751                                 (void) fprintf(stderr, gettext("cannot "
3752                                     "unshare '%s': not currently "
3753                                     "shared\n"), zfs_get_name(zhp));
3754                                 ret = 1;
3755                         } else if (zfs_unshareall(zhp) != 0) {
3756                                 ret = 1;
3757                         }
3758                         break;
3759
3760                 case OP_MOUNT:
3761                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
3762                                 (void) fprintf(stderr, gettext("cannot "
3763                                     "unmount '%s': legacy "
3764                                     "mountpoint\n"), zfs_get_name(zhp));
3765                                 (void) fprintf(stderr, gettext("use "
3766                                     "umount(1M) to unmount this "
3767                                     "filesystem\n"));
3768                                 ret = 1;
3769                         } else if (!zfs_is_mounted(zhp, NULL)) {
3770                                 (void) fprintf(stderr, gettext("cannot "
3771                                     "unmount '%s': not currently "
3772                                     "mounted\n"),
3773                                     zfs_get_name(zhp));
3774                                 ret = 1;
3775                         } else if (zfs_unmountall(zhp, flags) != 0) {
3776                                 ret = 1;
3777                         }
3778                         break;
3779                 }
3780
3781                 zfs_close(zhp);
3782         }
3783
3784         return (ret);
3785 }
3786
3787 /*
3788  * zfs unmount -a
3789  * zfs unmount filesystem
3790  *
3791  * Unmount all filesystems, or a specific ZFS filesystem.
3792  */
3793 static int
3794 zfs_do_unmount(int argc, char **argv)
3795 {
3796         return (unshare_unmount(OP_MOUNT, argc, argv));
3797 }
3798
3799 /*
3800  * zfs unshare -a
3801  * zfs unshare filesystem
3802  *
3803  * Unshare all filesystems, or a specific ZFS filesystem.
3804  */
3805 static int
3806 zfs_do_unshare(int argc, char **argv)
3807 {
3808         return (unshare_unmount(OP_SHARE, argc, argv));
3809 }
3810
3811 /* ARGSUSED */
3812 static int
3813 zfs_do_python(int argc, char **argv)
3814 {
3815         (void) execv(pypath, argv-1);
3816         (void) printf("internal error: %s not found\n", pypath);
3817         return (-1);
3818 }
3819
3820 static int
3821 find_command_idx(char *command, int *idx)
3822 {
3823         int i;
3824
3825         for (i = 0; i < NCOMMAND; i++) {
3826                 if (command_table[i].name == NULL)
3827                         continue;
3828
3829                 if (strcmp(command, command_table[i].name) == 0) {
3830                         *idx = i;
3831                         return (0);
3832                 }
3833         }
3834         return (1);
3835 }
3836
3837 static int
3838 zfs_do_diff(int argc, char **argv)
3839 {
3840         zfs_handle_t *zhp;
3841         int flags = 0;
3842         char *tosnap = NULL;
3843         char *fromsnap = NULL;
3844         char *atp, *copy;
3845         int err;
3846         int c;
3847
3848         while ((c = getopt(argc, argv, "FHt")) != -1) {
3849                 switch (c) {
3850                 case 'F':
3851                         flags |= ZFS_DIFF_CLASSIFY;
3852                         break;
3853                 case 'H':
3854                         flags |= ZFS_DIFF_PARSEABLE;
3855                         break;
3856                 case 't':
3857                         flags |= ZFS_DIFF_TIMESTAMP;
3858                         break;
3859                 default:
3860                         (void) fprintf(stderr,
3861                             gettext("invalid option '%c'\n"), optopt);
3862                         usage(B_FALSE);
3863                 }
3864         }
3865
3866         argc -= optind;
3867         argv += optind;
3868
3869         if (argc < 1) {
3870                 (void) fprintf(stderr,
3871                 gettext("must provide at least one snapshot name\n"));
3872                 usage(B_FALSE);
3873         }
3874
3875         if (argc > 2) {
3876                 (void) fprintf(stderr, gettext("too many arguments\n"));
3877                 usage(B_FALSE);
3878         }
3879
3880         fromsnap = argv[0];
3881         tosnap = (argc == 2) ? argv[1] : NULL;
3882
3883         copy = NULL;
3884         if (*fromsnap != '@')
3885                 copy = strdup(fromsnap);
3886         else if (tosnap)
3887                 copy = strdup(tosnap);
3888         if (copy == NULL)
3889                 usage(B_FALSE);
3890
3891         if ((atp = strchr(copy, '@')))
3892                 *atp = '\0';
3893
3894         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
3895                 return (1);
3896
3897         free(copy);
3898
3899         /*
3900          * Ignore SIGPIPE so that the library can give us
3901          * information on any failure
3902          */
3903         (void) sigignore(SIGPIPE);
3904
3905         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
3906
3907         zfs_close(zhp);
3908
3909         return (err != 0);
3910 }
3911
3912 int
3913 main(int argc, char **argv)
3914 {
3915         int ret;
3916         int i = 0;
3917         char *cmdname;
3918
3919         (void) setlocale(LC_ALL, "");
3920         (void) textdomain(TEXT_DOMAIN);
3921
3922         opterr = 0;
3923
3924         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
3925                 (void) fprintf(stderr, gettext("internal error: unable to "
3926                     "open %s\n"), MNTTAB);
3927                 return (1);
3928         }
3929
3930         /*
3931          * Make sure the user has specified some command.
3932          */
3933         if (argc < 2) {
3934                 (void) fprintf(stderr, gettext("missing command\n"));
3935                 usage(B_FALSE);
3936         }
3937
3938         cmdname = argv[1];
3939
3940         /*
3941          * The 'umount' command is an alias for 'unmount'
3942          */
3943         if (strcmp(cmdname, "umount") == 0)
3944                 cmdname = "unmount";
3945
3946         /*
3947          * The 'recv' command is an alias for 'receive'
3948          */
3949         if (strcmp(cmdname, "recv") == 0)
3950                 cmdname = "receive";
3951
3952         /*
3953          * Special case '-?'
3954          */
3955         if ((strcmp(cmdname, "-?") == 0) ||
3956             (strcmp(cmdname, "--help") == 0))
3957                 usage(B_TRUE);
3958
3959         if ((g_zfs = libzfs_init()) == NULL)
3960                 return (1);
3961
3962         zpool_set_history_str("zfs", argc, argv, history_str);
3963         verify(zpool_stage_history(g_zfs, history_str) == 0);
3964
3965         libzfs_print_on_error(g_zfs, B_TRUE);
3966
3967         /*
3968          * Run the appropriate command.
3969          */
3970         libzfs_mnttab_cache(g_zfs, B_TRUE);
3971         if (find_command_idx(cmdname, &i) == 0) {
3972                 current_command = &command_table[i];
3973                 ret = command_table[i].func(argc - 1, argv + 1);
3974         } else if (strchr(cmdname, '=') != NULL) {
3975                 verify(find_command_idx("set", &i) == 0);
3976                 current_command = &command_table[i];
3977                 ret = command_table[i].func(argc, argv);
3978         } else {
3979                 (void) fprintf(stderr, gettext("unrecognized "
3980                     "command '%s'\n"), cmdname);
3981                 usage(B_FALSE);
3982                 ret = 1;
3983         }
3984         libzfs_mnttab_cache(g_zfs, B_FALSE);
3985         libzfs_fini(g_zfs);
3986
3987         (void) fclose(mnttab_file);
3988
3989         /*
3990          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
3991          * for the purposes of running ::findleaks.
3992          */
3993         if (getenv("ZFS_ABORT") != NULL) {
3994                 (void) printf("dumping core by request\n");
3995                 abort();
3996         }
3997
3998         return (ret);
3999 }