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